diff --git a/.github/workflows/gbf_commit.yml b/.github/workflows/gbf_commit.yml index c3c6c166..de852c79 100644 --- a/.github/workflows/gbf_commit.yml +++ b/.github/workflows/gbf_commit.yml @@ -22,4 +22,3 @@ jobs: openrouter-api-key: ${{ secrets.OPEN_ROUTER_API_KEY }} openrouter-model: ${{ vars.OPEN_ROUTER_MODEL }} token: ${{ secrets.PAT }} - classic-token: ${{ secrets.CLASSIC_TOKEN }} diff --git a/.github/workflows/gbf_issue.yml b/.github/workflows/gbf_issue.yml index 2588d7c7..da6fbc7f 100644 --- a/.github/workflows/gbf_issue.yml +++ b/.github/workflows/gbf_issue.yml @@ -23,5 +23,3 @@ jobs: supabase-url: ${{ secrets.SUPABASE_URL }} supabase-key: ${{ secrets.SUPABASE_KEY }} token: ${{ secrets.PAT }} - classic-token: ${{ secrets.CLASSIC_TOKEN }} - diff --git a/.github/workflows/gbf_issue_comment.yml b/.github/workflows/gbf_issue_comment.yml index 0165b7d6..01abd4d3 100644 --- a/.github/workflows/gbf_issue_comment.yml +++ b/.github/workflows/gbf_issue_comment.yml @@ -23,5 +23,3 @@ jobs: supabase-url: ${{ secrets.SUPABASE_URL }} supabase-key: ${{ secrets.SUPABASE_KEY }} token: ${{ secrets.PAT }} - classic-token: ${{ secrets.CLASSIC_TOKEN }} - diff --git a/.github/workflows/gbf_pull_request.yml b/.github/workflows/gbf_pull_request.yml index 746194bd..aa993419 100644 --- a/.github/workflows/gbf_pull_request.yml +++ b/.github/workflows/gbf_pull_request.yml @@ -21,4 +21,3 @@ jobs: openrouter-model: ${{ vars.OPEN_ROUTER_MODEL }} project-ids: 2 token: ${{ secrets.PAT }} - classic-token: ${{ secrets.CLASSIC_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/gbf_pull_request_review_comment.yml b/.github/workflows/gbf_pull_request_review_comment.yml index 78eb48c6..9e0684ab 100644 --- a/.github/workflows/gbf_pull_request_review_comment.yml +++ b/.github/workflows/gbf_pull_request_review_comment.yml @@ -23,4 +23,4 @@ jobs: supabase-url: ${{ secrets.SUPABASE_URL }} supabase-key: ${{ secrets.SUPABASE_KEY }} token: ${{ secrets.PAT }} - classic-token: ${{ secrets.CLASSIC_TOKEN }} + \ No newline at end of file diff --git a/.github/workflows/gbf_update_ai_knowledge.yml b/.github/workflows/gbf_update_ai_knowledge.yml index 9464fdc8..edae97a0 100644 --- a/.github/workflows/gbf_update_ai_knowledge.yml +++ b/.github/workflows/gbf_update_ai_knowledge.yml @@ -13,16 +13,8 @@ jobs: - name: Checkout Repository uses: actions/checkout@v4 - - name: Set up DOCKER_HOST as output - id: docker-env - run: | - echo "docker_host=unix://${HOME}/.orbstack/run/docker.sock" >> $GITHUB_OUTPUT - - name: Update AI knowledge uses: ./ - env: - DOCKER_HOST: ${{ steps.docker-env.outputs.docker_host }} - RUNNER_TEMP: ${{ github.workspace }}/.runner_temp with: debug: ${{ vars.DEBUG }} ai-ignore-files: build/* @@ -33,4 +25,3 @@ jobs: supabase-url: ${{ secrets.SUPABASE_URL }} supabase-key: ${{ secrets.SUPABASE_KEY }} token: ${{ secrets.PAT }} - classic-token: ${{ secrets.CLASSIC_TOKEN }} diff --git a/.github/workflows/release_workflow.yml b/.github/workflows/release_workflow.yml index 0c59c0d8..db1d361b 100644 --- a/.github/workflows/release_workflow.yml +++ b/.github/workflows/release_workflow.yml @@ -84,38 +84,10 @@ jobs: default_author: user_info message: 'gh-action: updated compiled files' - compile-vector-server: - name: Compile vector server - runs-on: [self-hosted, macOS, X64] - needs: prepare-compiled-files - steps: - - name: Checkout Repository - uses: actions/checkout@v4 - - - name: Set up DOCKER_HOST as output - id: docker-env - run: | - echo "docker_host=unix://${HOME}/.orbstack/run/docker.sock" >> $GITHUB_OUTPUT - - - name: Git Board Flow - Compile Vector Server - uses: ./ - env: - DOCKER_HOST: ${{ steps.docker-env.outputs.docker_host }} - RUNNER_TEMP: ${{ github.workspace }}/.runner_temp - with: - debug: ${{ vars.DEBUG }} - single-action: 'compile_vector_server' - single-action-version: '${{ github.event.inputs.version }}' - single-action-title: '${{ github.event.inputs.title }}' - single-action-changelog: '${{ github.event.inputs.changelog }}' - single-action-issue: '${{ github.event.inputs.issue }}' - token: ${{ secrets.PAT }} - classic-token: ${{ secrets.CLASSIC_TOKEN }} - tag: name: Publish version runs-on: ubuntu-latest - needs: [ prepare-compiled-files, compile-vector-server ] + needs: [ prepare-compiled-files ] steps: - name: Checkout Repository uses: actions/checkout@v4 diff --git a/action.yml b/action.yml index 9a585664..cb4a78fa 100644 --- a/action.yml +++ b/action.yml @@ -387,9 +387,6 @@ inputs: token: description: "Fine-grained personal access token for branch and project operations" required: true - classic-token: - description: "Classic token for authentication with GitHub Container Registry" - default: "" supabase-key: description: "Supabase key for AI operations." default: "" @@ -432,21 +429,6 @@ inputs: ai-members-only: description: "Restrict AI features to only organization/project members." default: "true" - docker-container-name: - description: "Name of the Docker container to use." - default: "git-board-flow" - docker-domain: - description: "Domain of the Docker container to use." - default: "localhost" - docker-port: - description: "Port of the Docker container to use." - default: "8000" - docker-cache-os: - description: "OS of the Docker container to cache. Valid values: ubuntu-any-value, macos-any-value, windows-any-value" - default: "ubuntu-latest" - docker-cache-arch: - description: "Architecture of the Docker container to cache. Valid values: amd64, arm64, arm/v7, 386, s390x, ppc64le" - default: "amd64" runs: using: "node20" main: "build/github_action/index.js" diff --git a/build/.DS_Store b/build/.DS_Store new file mode 100644 index 00000000..e9cff235 Binary files /dev/null and b/build/.DS_Store differ diff --git a/build/cli/build/Release/cpufeatures.node b/build/cli/build/Release/cpufeatures.node index ddb5b2ba..7fc79247 100755 Binary files a/build/cli/build/Release/cpufeatures.node and b/build/cli/build/Release/cpufeatures.node differ diff --git a/build/cli/index.js b/build/cli/index.js index c15ec6c1..3c01f62e 100755 --- a/build/cli/index.js +++ b/build/cli/index.js @@ -2,7 +2,7 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 87351: +/***/ 7351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -32,7 +32,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(22037)); +const os = __importStar(__nccwpck_require__(2037)); const utils_1 = __nccwpck_require__(5278); /** * Commands @@ -105,7 +105,7 @@ function escapeProperty(s) { /***/ }), -/***/ 42186: +/***/ 2186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -144,12 +144,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(87351); +const command_1 = __nccwpck_require__(7351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const oidc_utils_1 = __nccwpck_require__(98041); +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const oidc_utils_1 = __nccwpck_require__(8041); /** * The code to exit an action */ @@ -434,12 +434,12 @@ exports.getIDToken = getIDToken; /** * Summary exports */ -var summary_1 = __nccwpck_require__(81327); +var summary_1 = __nccwpck_require__(1327); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ -var summary_2 = __nccwpck_require__(81327); +var summary_2 = __nccwpck_require__(1327); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports @@ -451,7 +451,7 @@ Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: funct /** * Platform utilities exports */ -exports.platform = __importStar(__nccwpck_require__(85243)); +exports.platform = __importStar(__nccwpck_require__(5243)); //# sourceMappingURL=core.js.map /***/ }), @@ -490,8 +490,8 @@ exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const crypto = __importStar(__nccwpck_require__(6113)); -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); +const fs = __importStar(__nccwpck_require__(7147)); +const os = __importStar(__nccwpck_require__(2037)); const utils_1 = __nccwpck_require__(5278); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; @@ -525,7 +525,7 @@ exports.prepareKeyValueMessage = prepareKeyValueMessage; /***/ }), -/***/ 98041: +/***/ 8041: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -541,9 +541,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(96255); -const auth_1 = __nccwpck_require__(35526); -const core_1 = __nccwpck_require__(42186); +const http_client_1 = __nccwpck_require__(6255); +const auth_1 = __nccwpck_require__(5526); +const core_1 = __nccwpck_require__(2186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { @@ -639,7 +639,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(71017)); +const path = __importStar(__nccwpck_require__(1017)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. @@ -678,7 +678,7 @@ exports.toPlatformPath = toPlatformPath; /***/ }), -/***/ 85243: +/***/ 5243: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -720,8 +720,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; -const os_1 = __importDefault(__nccwpck_require__(22037)); -const exec = __importStar(__nccwpck_require__(71514)); +const os_1 = __importDefault(__nccwpck_require__(2037)); +const exec = __importStar(__nccwpck_require__(1514)); const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { silent: true @@ -779,7 +779,7 @@ exports.getDetails = getDetails; /***/ }), -/***/ 81327: +/***/ 1327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -795,8 +795,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(22037); -const fs_1 = __nccwpck_require__(57147); +const os_1 = __nccwpck_require__(2037); +const fs_1 = __nccwpck_require__(7147); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; @@ -1116,7 +1116,7 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 71514: +/***/ 1514: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1151,8 +1151,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(71576); -const tr = __importStar(__nccwpck_require__(88159)); +const string_decoder_1 = __nccwpck_require__(1576); +const tr = __importStar(__nccwpck_require__(8159)); /** * Exec a command. * Output will be streamed to the live console. @@ -1226,7 +1226,7 @@ exports.getExecOutput = getExecOutput; /***/ }), -/***/ 88159: +/***/ 8159: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1261,13 +1261,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const events = __importStar(__nccwpck_require__(82361)); -const child = __importStar(__nccwpck_require__(32081)); -const path = __importStar(__nccwpck_require__(71017)); -const io = __importStar(__nccwpck_require__(47351)); -const ioUtil = __importStar(__nccwpck_require__(81962)); -const timers_1 = __nccwpck_require__(39512); +const os = __importStar(__nccwpck_require__(2037)); +const events = __importStar(__nccwpck_require__(2361)); +const child = __importStar(__nccwpck_require__(2081)); +const path = __importStar(__nccwpck_require__(1017)); +const io = __importStar(__nccwpck_require__(7436)); +const ioUtil = __importStar(__nccwpck_require__(1962)); +const timers_1 = __nccwpck_require__(9512); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* @@ -1851,15 +1851,15 @@ class ExecState extends events.EventEmitter { /***/ }), -/***/ 74087: +/***/ 4087: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Context = void 0; -const fs_1 = __nccwpck_require__(57147); -const os_1 = __nccwpck_require__(22037); +const fs_1 = __nccwpck_require__(7147); +const os_1 = __nccwpck_require__(2037); class Context { /** * Hydrate the context from the environment @@ -1914,7 +1914,7 @@ exports.Context = Context; /***/ }), -/***/ 95438: +/***/ 5438: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1944,8 +1944,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const utils_1 = __nccwpck_require__(73030); +const Context = __importStar(__nccwpck_require__(4087)); +const utils_1 = __nccwpck_require__(3030); exports.context = new Context.Context(); /** * Returns a hydrated octokit ready to use for GitHub Actions @@ -1962,7 +1962,7 @@ exports.getOctokit = getOctokit; /***/ }), -/***/ 47914: +/***/ 7914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2001,8 +2001,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(96255)); -const undici_1 = __nccwpck_require__(41773); +const httpClient = __importStar(__nccwpck_require__(6255)); +const undici_1 = __nccwpck_require__(1773); function getAuthString(token, options) { if (!token && !options.auth) { throw new Error('Parameter token or opts.auth is required'); @@ -2039,7 +2039,7 @@ exports.getApiBaseUrl = getApiBaseUrl; /***/ }), -/***/ 73030: +/***/ 3030: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2069,12 +2069,12 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const Utils = __importStar(__nccwpck_require__(47914)); +const Context = __importStar(__nccwpck_require__(4087)); +const Utils = __importStar(__nccwpck_require__(7914)); // octokit + plugins -const core_1 = __nccwpck_require__(76762); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); -const plugin_paginate_rest_1 = __nccwpck_require__(64193); +const core_1 = __nccwpck_require__(6762); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(3044); +const plugin_paginate_rest_1 = __nccwpck_require__(4193); exports.context = new Context.Context(); const baseUrl = Utils.getApiBaseUrl(); exports.defaults = { @@ -2105,7 +2105,7 @@ exports.getOctokitOptions = getOctokitOptions; /***/ }), -/***/ 35526: +/***/ 5526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -2193,7 +2193,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 96255: +/***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2233,11 +2233,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(13685)); -const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(19835)); -const tunnel = __importStar(__nccwpck_require__(74294)); -const undici_1 = __nccwpck_require__(41773); +const http = __importStar(__nccwpck_require__(3685)); +const https = __importStar(__nccwpck_require__(5687)); +const pm = __importStar(__nccwpck_require__(9835)); +const tunnel = __importStar(__nccwpck_require__(4294)); +const undici_1 = __nccwpck_require__(1773); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -2852,7 +2852,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 19835: +/***/ 9835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -2954,7 +2954,7 @@ class DecodedURL extends URL { /***/ }), -/***/ 81962: +/***/ 1962: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2990,8 +2990,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -const fs = __importStar(__nccwpck_require__(57147)); -const path = __importStar(__nccwpck_require__(71017)); +const fs = __importStar(__nccwpck_require__(7147)); +const path = __importStar(__nccwpck_require__(1017)); _a = fs.promises // export const {open} = 'fs' , exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; @@ -3144,7 +3144,7 @@ exports.getCmdPath = getCmdPath; /***/ }), -/***/ 47351: +/***/ 7436: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -3179,9 +3179,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; -const assert_1 = __nccwpck_require__(39491); -const path = __importStar(__nccwpck_require__(71017)); -const ioUtil = __importStar(__nccwpck_require__(81962)); +const assert_1 = __nccwpck_require__(9491); +const path = __importStar(__nccwpck_require__(1017)); +const ioUtil = __importStar(__nccwpck_require__(1962)); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js @@ -3450,140044 +3450,56157 @@ function copyFile(srcFile, destFile, force) { /***/ }), -/***/ 3358: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 334: +/***/ ((module) => { "use strict"; -/** - * @license - * Copyright 2020 Balena Ltd. - * - * 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. - * - * ------------------------------------------------------------------------ - * - * Copyright 2018 Zeit, Inc. - * Licensed under the MIT License. See file LICENSE.md for a full copy. - * - * ------------------------------------------------------------------------ - */ - -/** - * This module implements the [dockerignore - * spec](https://docs.docker.com/engine/reference/builder/#dockerignore-file), - * closely following Docker's (Moby) Golang implementation: - * https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go - * https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go - * https://github.com/moby/moby/blob/v19.03.8/pkg/archive/archive.go#L825 - * - * Something the spec is not clear about, but we discovered by reading source code - * and testing against the "docker build" command, is the handling of backslashes and - * forward slashes as path separators and escape characters in the .dockerignore file - * across platforms including Windows, Linux and macOS: - * - * * On Linux and macOS, only forward slashes can be used as path separators in the - * .dockerignore file, and the backslash works as an escape character. - * * On Windows, both forward slashes and backslashes are allowed as path separators - * in the .dockerignore file, and the backslash is not used as an escape character. - * - * This is consistent with how Windows works generally: both forward slashes and - * backslashes are accepted as path separators by the cmd.exe Command Prompt or - * PowerShell, and by library functions like the Golang filepath.Clean or the - * Node.js path.normalize. - * - * Similarly, path strings provided to the IgnoreBase.ignores() and IgnoreBase.filter() - * methods can use either forward slashes or backslashes as path separators on Windows, - * but only forward slashes are accepted as path separators on Linux and macOS. - */ - -const path = __nccwpck_require__(71017); - -const factory = options => new IgnoreBase(options); // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L538-L539 -// Fixes typescript module import - - -factory.default = factory; -module.exports = factory; - -function make_array(subject) { - return Array.isArray(subject) ? subject : [subject]; -} - -const REGEX_TRAILING_SLASH = /(?<=.)\/$/; -const REGEX_TRAILING_BACKSLASH = /(?<=.)\\$/; -const REGEX_TRAILING_PATH_SEP = path.sep === '\\' ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH; -const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('dockerignore') : 'dockerignore'; // An implementation of Go's filepath.Clean -// https://golang.org/pkg/path/filepath/#Clean -// https://github.com/golang/go/blob/master/src/path/filepath/path.go -// Note that, like Go, on Windows this function converts forward slashes -// to backslashes. - -function cleanPath(file) { - return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, ''); -} // Javascript port of Golang's filepath.ToSlash -// https://golang.org/pkg/path/filepath/#ToSlash -// https://github.com/golang/go/blob/master/src/path/filepath/path.go -// Convert any OS-specific path separator to '/'. Backslash is converted -// to forward slash on Windows, but not on Linux/macOS. -// Note that both forward slashes and backslashes are valid path separators on -// Windows. As a result, code such as `pattern.split(path.sep).join('/')` fails -// on Windows when forward slashes are used as path separators. - - -function toSlash(file) { - if (path.sep === '/') { - return file; +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); - return file.replace(/\\/g, '/'); -} // Javascript port of Golang's filepath.FromSlash -// https://github.com/golang/go/blob/master/src/path/filepath/path.go +// 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 + }; +} -function fromSlash(file) { - if (path.sep === '/') { - return file; +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; } - - return file.replace(/\//g, path.sep); + return `token ${token}`; } -class IgnoreBase { - constructor({ - // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372 - ignorecase = true - } = {}) { - this._rules = []; - this._ignorecase = ignorecase; - this[KEY_IGNORE] = true; +// 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); +} - this._initCache(); +// 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); - _initCache() { - this._cache = {}; - } // @param {Array.|string|Ignore} pattern - - - add(pattern) { - this._added = false; - - if (typeof pattern === 'string') { - pattern = pattern.split(/\r?\n/g); - } - - make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache(); - } +/***/ }), - return this; - } // legacy +/***/ 6762: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; - addPattern(pattern) { - return this.add(pattern); +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); - _addPattern(pattern) { - // https://github.com/kaelzhang/node-ignore/issues/32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules); - this._added = true; - return; - } - - if (this._checkPattern(pattern)) { - const rule = this._createRule(pattern.trim()); +// pkg/dist-src/index.js +var index_exports = {}; +__export(index_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(index_exports); +var import_universal_user_agent = __nccwpck_require__(5030); +var import_before_after_hook = __nccwpck_require__(3682); +var import_request = __nccwpck_require__(6234); +var import_graphql = __nccwpck_require__(8467); +var import_auth_token = __nccwpck_require__(334); - if (rule !== null) { - this._added = true; +// pkg/dist-src/version.js +var VERSION = "5.2.2"; - this._rules.push(rule); - } - } +// pkg/dist-src/index.js +var noop = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = noop; } - - _checkPattern(pattern) { - // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L34-L40 - return pattern && typeof pattern === 'string' && pattern.indexOf('#') !== 0 && pattern.trim() !== ""; + if (typeof logger.info !== "function") { + logger.info = noop; } - - filter(paths) { - return make_array(paths).filter(path => this._filter(path)); + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; } - - createFilter() { - return path => this._filter(path); + if (typeof logger.error !== "function") { + logger.error = consoleError; } - - ignores(path) { - return !this._filter(path); - } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53 - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55 - - - _createRule(pattern) { - const origin = pattern; - let negative = false; // > An optional prefix "!" which negates the pattern; - // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L43-L46 - - if (pattern[0] === '!') { - negative = true; - pattern = pattern.substring(1).trim(); - } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L47-L53 - - - if (pattern.length > 0) { - pattern = cleanPath(pattern); - pattern = toSlash(pattern); - - if (pattern.length > 1 && pattern[0] === '/') { - pattern = pattern.slice(1); + return logger; +} +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 + ) + ); } - } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L54-L55 - - - if (negative) { - pattern = '!' + pattern; - } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L30 - - - pattern = pattern.trim(); - - if (pattern === "") { - return null; - } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L34 - // convert forward slashes to backslashes on Windows - - - pattern = cleanPath(pattern); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L36-L42 - - if (pattern[0] === '!') { - if (pattern.length === 1) { - return 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)) + ); } - - negative = true; - pattern = pattern.substring(1); - } else { - negative = false; - } - - return { - origin, - pattern, - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54 - dirs: pattern.split(path.sep), - negative }; - } // @returns `Boolean` true if the `path` is NOT ignored - - - _filter(path) { - if (!path) { - return false; + 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 (path in this._cache) { - return this._cache[path]; + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; } - - return this._cache[path] = this._test(path); - } // @returns {Boolean} true if a file is NOT ignored - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62 - - - _test(file) { - file = fromSlash(file); // equivalent to golang filepath.Dir() https://golang.org/src/path/filepath/path.go - - const parentPath = cleanPath(path.dirname(file)); - const parentPathDirs = parentPath.split(path.sep); - let matched = false; - - this._rules.forEach(rule => { - let match = this._match(file, rule); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L80 - - - if (!match && parentPath !== ".") { - // Check to see if the pattern matches one of our parent dirs. - if (rule.dirs.includes('**')) { - // Ah shucks! We have to test every possible parent path that has - // a number of dirs _n_ where - // `rule.dirs.filter(doubleStar).length <= _n_ <= parentPathDirs.length` - // since the ** can imply any number of directories including 0 - for (let i = rule.dirs.filter(x => x !== '**').length; i <= parentPathDirs.length; i++) { - match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule); - } - } else if (rule.dirs.length <= parentPathDirs.length) { - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L83 - match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule); - } - } - - if (match) { - matched = !rule.negative; + 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 = createLogger(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); - return !matched; - } // @returns {Boolean} true if a file is matched by a rule +/***/ }), - _match(file, rule) { - return this._compile(rule).regexp.test(file); - } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139 +/***/ 9440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; - _compile(rule) { - if (rule.regexp) { - return rule; - } +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); - let regStr = '^'; // Go through the pattern and convert it to a regexp. +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); - let escapedSlash = path.sep === '\\' ? '\\\\' : path.sep; +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(5030); - for (let i = 0; i < rule.pattern.length; i++) { - const ch = rule.pattern[i]; +// pkg/dist-src/version.js +var VERSION = "9.0.6"; - if (ch === '*') { - if (rule.pattern[i + 1] === '*') { - // is some flavor of "**" - i++; // Treat **/ as ** so eat the "/" +// 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: "" + } +}; - if (rule.pattern[i + 1] === path.sep) { - i++; - } +// 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; + }, {}); +} - if (rule.pattern[i + 1] === undefined) { - // is "**EOF" - to align with .gitignore just accept all - regStr += ".*"; - } else { - // is "**" - // Note that this allows for any # of /'s (even 0) because - // the .* will eat everything, even /'s - regStr += `(.*${escapedSlash})?`; - } - } else { - // is "*" so map it to anything but "/" - regStr += `[^${escapedSlash}]*`; - } - } else if (ch === '?') { - // "?" is any char except "/" - regStr += `[^${escapedSlash}]`; - } else if (ch === '.' || ch === '$') { - // Escape some regexp special chars that have no meaning - // in golang's filepath.Match - regStr += `\\${ch}`; - } else if (ch === '\\') { - // escape next char. Note that a trailing \ in the pattern - // will be left alone (but need to escape it) - if (path.sep === '\\') { - // On windows map "\" to "\\", meaning an escaped backslash, - // and then just continue because filepath.Match on - // Windows doesn't allow escaping at all - regStr += escapedSlash; - continue; - } +// 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); +} - if (rule.pattern[i + 1] !== undefined) { - regStr += '\\' + rule.pattern[i + 1]; - i++; - } else { - regStr += '\\'; - } - } else { - regStr += ch; - } +// 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; +} - regStr += "$"; - rule.regexp = new RegExp(regStr, this._ignorecase ? 'i' : ''); - return rule; +// 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; } - -/***/ }), - -/***/ 8258: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.registerAdminService = registerAdminService; -exports.addAdminServicesToServer = addAdminServicesToServer; -const registeredAdminServices = []; -function registerAdminService(getServiceDefinition, getHandlers) { - registeredAdminServices.push({ getServiceDefinition, getHandlers }); -} -function addAdminServicesToServer(server) { - for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { - server.addService(getServiceDefinition(), getHandlers()); +// 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; } -//# sourceMappingURL=admin.js.map - -/***/ }), - -/***/ 34186: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// 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("&"); +} -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BackoffTimeout = void 0; -const constants_1 = __nccwpck_require__(90634); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'backoff'; -const INITIAL_BACKOFF_MS = 1000; -const BACKOFF_MULTIPLIER = 1.6; -const MAX_BACKOFF_MS = 120000; -const BACKOFF_JITTER = 0.2; -/** - * Get a number uniformly at random in the range [min, max) - * @param min - * @param max - */ -function uniformRandom(min, max) { - return Math.random() * (max - min) + min; +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? { }, 0); - clearTimeout(this.timerId); - } - static getNextId() { - return this.nextId++; +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]; } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '{' + this.id + '} ' + text); - } - runTimer(delay) { - var _a, _b; - this.trace('runTimer(delay=' + delay + ')'); - this.endTime = this.startTime; - this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); - clearTimeout(this.timerId); - this.timerId = setTimeout(() => { - this.trace('timer fired'); - this.running = false; - this.callback(); - }, delay); - if (!this.hasRef) { - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Call the callback after the current amount of delay time - */ - runOnce() { - this.trace('runOnce()'); - this.running = true; - this.startTime = new Date(); - this.runTimer(this.nextDelay); - const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); - const jitterMagnitude = nextBackoff * this.jitter; - this.nextDelay = - nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); - } - /** - * Stop the timer. The callback will not be called until `runOnce` is called - * again. - */ - stop() { - this.trace('stop()'); - clearTimeout(this.timerId); - this.running = false; - } - /** - * Reset the delay time to its initial value. If the timer is still running, - * retroactively apply that reset to the current timer. - */ - reset() { - this.trace('reset() running=' + this.running); - this.nextDelay = this.initialDelay; - if (this.running) { - const now = new Date(); - const newEndTime = this.startTime; - newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); - clearTimeout(this.timerId); - if (now < newEndTime) { - this.runTimer(newEndTime.getTime() - now.getTime()); - } - else { - this.running = false; - } - } - } - /** - * Check whether the timer is currently running. - */ - isRunning() { - return this.running; - } - /** - * Set that while the timer is running, it should keep the Node process - * running. - */ - ref() { - var _a, _b; - this.hasRef = true; - (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Set that while the timer is running, it should not keep the Node process - * running. - */ - unref() { - var _a, _b; - this.hasRef = false; - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Get the approximate timestamp of when the timer will fire. Only valid if - * this.isRunning() is true. - */ - getEndTime() { - return this.endTime; + } + 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(""); } -exports.BackoffTimeout = BackoffTimeout; -BackoffTimeout.nextId = 0; -//# sourceMappingURL=backoff-timeout.js.map - -/***/ }), - -/***/ 21426: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CallCredentials = void 0; -const metadata_1 = __nccwpck_require__(83665); -function isCurrentOauth2Client(client) { - return ('getRequestHeaders' in client && - typeof client.getRequestHeaders === 'function'); +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); } -/** - * A class that represents a generic method of adding authentication-related - * metadata on a per-request basis. - */ -class CallCredentials { - /** - * Creates a new CallCredentials object from a given function that generates - * Metadata objects. - * @param metadataGenerator A function that accepts a set of options, and - * generates a Metadata object based on these options, which is passed back - * to the caller via a supplied (err, metadata) callback. - */ - static createFromMetadataGenerator(metadataGenerator) { - return new SingleCallCredentials(metadataGenerator); - } - /** - * Create a gRPC credential from a Google credential object. - * @param googleCredentials The authentication client to use. - * @return The resulting CallCredentials object. - */ - static createFromGoogleCredential(googleCredentials) { - return CallCredentials.createFromMetadataGenerator((options, callback) => { - let getHeaders; - if (isCurrentOauth2Client(googleCredentials)) { - getHeaders = googleCredentials.getRequestHeaders(options.service_url); - } - else { - getHeaders = new Promise((resolve, reject) => { - googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { - if (err) { - reject(err); - return; - } - if (!headers) { - reject(new Error('Headers not set by metadata plugin')); - return; - } - resolve(headers); - }); - }); - } - getHeaders.then(headers => { - const metadata = new metadata_1.Metadata(); - for (const key of Object.keys(headers)) { - metadata.add(key, headers[key]); - } - callback(null, metadata); - }, err => { - callback(err); - }); - }); - } - static createEmpty() { - return new EmptyCallCredentials(); - } +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } } -exports.CallCredentials = CallCredentials; -class ComposedCallCredentials extends CallCredentials { - constructor(creds) { - super(); - this.creds = creds; - } - async generateMetadata(options) { - const base = new metadata_1.Metadata(); - const generated = await Promise.all(this.creds.map(cred => cred.generateMetadata(options))); - for (const gen of generated) { - base.merge(gen); - } - return base; - } - compose(other) { - return new ComposedCallCredentials(this.creds.concat([other])); - } - _equals(other) { - if (this === other) { - return true; +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)); + } + }); } - if (other instanceof ComposedCallCredentials) { - return this.creds.every((value, index) => value._equals(other.creds[index])); + } 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())); + } + }); } - else { - return false; + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); } + } } -} -class SingleCallCredentials extends CallCredentials { - constructor(metadataGenerator) { - super(); - this.metadataGenerator = metadataGenerator; - } - generateMetadata(options) { - return new Promise((resolve, reject) => { - this.metadataGenerator(options, (err, metadata) => { - if (metadata !== undefined) { - resolve(metadata); - } - else { - reject(err); - } - }); - }); - } - compose(other) { - return new ComposedCallCredentials([this, other]); + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof SingleCallCredentials) { - return this.metadataGenerator === other.metadataGenerator; + } + 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); } - else { - return false; + 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(/\/$/, ""); + } } -class EmptyCallCredentials extends CallCredentials { - generateMetadata(options) { - return Promise.resolve(new metadata_1.Metadata()); + +// 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(","); } - compose(other) { - return other; + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } } - _equals(other) { - return other instanceof EmptyCallCredentials; + } + 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 + ); } -//# sourceMappingURL=call-credentials.js.map -/***/ }), +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} -/***/ 78710: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// 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 + }); +} -"use strict"; +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InterceptingListenerImpl = void 0; -exports.statusOrFromValue = statusOrFromValue; -exports.statusOrFromError = statusOrFromError; -exports.isInterceptingListener = isInterceptingListener; -const metadata_1 = __nccwpck_require__(83665); -function statusOrFromValue(value) { - return { - ok: true, - value: value - }; -} -function statusOrFromError(error) { - var _a; - return { - ok: false, - error: Object.assign(Object.assign({}, error), { metadata: (_a = error.metadata) !== null && _a !== void 0 ? _a : new metadata_1.Metadata() }) - }; -} -function isInterceptingListener(listener) { - return (listener.onReceiveMetadata !== undefined && - listener.onReceiveMetadata.length === 1); -} -class InterceptingListenerImpl { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.processingMessage = false; - this.pendingStatus = null; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextListener.onReceiveStatus(this.pendingStatus); - } - } - onReceiveMetadata(metadata) { - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, metadata => { - this.processingMetadata = false; - this.nextListener.onReceiveMetadata(metadata); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - /* If this listener processes messages asynchronously, the last message may - * be reordered with respect to the status */ - this.processingMessage = true; - this.listener.onReceiveMessage(message, msg => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } - else { - this.nextListener.onReceiveMessage(msg); - this.processPendingStatus(); - } - }); - } - onReceiveStatus(status) { - this.listener.onReceiveStatus(status, processedStatus => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = processedStatus; - } - else { - this.nextListener.onReceiveStatus(processedStatus); - } - }); - } -} -exports.InterceptingListenerImpl = InterceptingListenerImpl; -//# sourceMappingURL=call-interface.js.map /***/ }), -/***/ 70380: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8467: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getNextCallNumber = getNextCallNumber; -let nextCallNumber = 0; -function getNextCallNumber() { - return nextCallNumber++; -} -//# sourceMappingURL=call-number.js.map +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 index_exports = {}; +__export(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest +}); +module.exports = __toCommonJS(index_exports); +var import_request3 = __nccwpck_require__(6234); +var import_universal_user_agent = __nccwpck_require__(5030); -/***/ 97453: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// pkg/dist-src/version.js +var VERSION = "7.1.1"; -"use strict"; +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(6234); -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = void 0; -exports.callErrorFromStatus = callErrorFromStatus; -const events_1 = __nccwpck_require__(82361); -const stream_1 = __nccwpck_require__(12781); -const constants_1 = __nccwpck_require__(90634); -/** - * Construct a ServiceError from a StatusObject. This function exists primarily - * as an attempt to make the error stack trace clearly communicate that the - * error is not necessarily a problem in gRPC itself. - * @param status - */ -function callErrorFromStatus(status, callerStack) { - const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; - const error = new Error(message); - const stack = `${error.stack}\nfor call at\n${callerStack}`; - return Object.assign(new Error(message), status, { stack }); +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(6234); + +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } -class ClientUnaryCallImpl extends events_1.EventEmitter { - constructor() { - super(); - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; +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); } -} -exports.ClientUnaryCallImpl = ClientUnaryCallImpl; -class ClientReadableStreamImpl extends stream_1.Readable { - constructor(deserialize) { - super({ objectMode: true }); - this.deserialize = deserialize; + } +}; + +// 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`) + ); } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + 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` + ) + ); } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + 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; } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + if (!result.variables) { + result.variables = {}; } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + 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; + }); } -exports.ClientReadableStreamImpl = ClientReadableStreamImpl; -class ClientWritableStreamImpl extends stream_1.Writable { - constructor(serialize) { - super({ objectMode: true }); - this.serialize = serialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _write(chunk, encoding, cb) { - var _a; - const context = { - callback: cb, - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } + +// 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 + }); } -exports.ClientWritableStreamImpl = ClientWritableStreamImpl; -class ClientDuplexStreamImpl extends stream_1.Duplex { - constructor(serialize, deserialize) { - super({ objectMode: true }); - this.serialize = serialize; - this.deserialize = deserialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); - } - _write(chunk, encoding, cb) { - var _a; - const context = { - callback: cb, - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } + +// 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" + }); } -exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl; -//# sourceMappingURL=call.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + /***/ }), -/***/ 25649: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4193: +/***/ ((module) => { "use strict"; -/* - * Copyright 2024 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FileWatcherCertificateProvider = void 0; -const fs = __nccwpck_require__(57147); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const util_1 = __nccwpck_require__(73837); -const TRACER_NAME = 'certificate_provider'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const readFilePromise = (0, util_1.promisify)(fs.readFile); -class FileWatcherCertificateProvider { - constructor(config) { - this.config = config; - this.refreshTimer = null; - this.fileResultPromise = null; - this.latestCaUpdate = undefined; - this.caListeners = new Set(); - this.latestIdentityUpdate = undefined; - this.identityListeners = new Set(); - this.lastUpdateTime = null; - if ((config.certificateFile === undefined) !== (config.privateKeyFile === undefined)) { - throw new Error('certificateFile and privateKeyFile must be set or unset together'); - } - if (config.certificateFile === undefined && config.caCertificateFile === undefined) { - throw new Error('At least one of certificateFile and caCertificateFile must be set'); - } - trace('File watcher constructed with config ' + JSON.stringify(config)); - } - updateCertificates() { - if (this.fileResultPromise) { - return; - } - this.fileResultPromise = Promise.allSettled([ - this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), - this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), - this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() - ]); - this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { - if (!this.refreshTimer) { - return; - } - trace('File watcher read certificates certificate ' + certificateResult.status + ', privateKey ' + privateKeyResult.status + ', CA certificate ' + caCertificateResult.status); - this.lastUpdateTime = new Date(); - this.fileResultPromise = null; - if (certificateResult.status === 'fulfilled' && privateKeyResult.status === 'fulfilled') { - this.latestIdentityUpdate = { - certificate: certificateResult.value, - privateKey: privateKeyResult.value - }; - } - else { - this.latestIdentityUpdate = null; - } - if (caCertificateResult.status === 'fulfilled') { - this.latestCaUpdate = { - caCertificate: caCertificateResult.value - }; - } - else { - this.latestCaUpdate = null; - } - for (const listener of this.identityListeners) { - listener(this.latestIdentityUpdate); - } - for (const listener of this.caListeners) { - listener(this.latestCaUpdate); - } - }); - trace('File watcher initiated certificate update'); - } - maybeStartWatchingFiles() { - if (!this.refreshTimer) { - /* Perform the first read immediately, but only if there was not already - * a recent read, to avoid reading from the filesystem significantly more - * frequently than configured if the provider quickly switches between - * used and unused. */ - const timeSinceLastUpdate = this.lastUpdateTime ? (new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity; - if (timeSinceLastUpdate > this.config.refreshIntervalMs) { - this.updateCertificates(); - } - if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { - // Clear out old updates if they are definitely stale - this.latestCaUpdate = undefined; - this.latestIdentityUpdate = undefined; - } - this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); - trace('File watcher started watching'); - } - } - maybeStopWatchingFiles() { - if (this.caListeners.size === 0 && this.identityListeners.size === 0) { - this.fileResultPromise = null; - if (this.refreshTimer) { - clearInterval(this.refreshTimer); - this.refreshTimer = null; - } - } - } - addCaCertificateListener(listener) { - this.caListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestCaUpdate !== undefined) { - process.nextTick(listener, this.latestCaUpdate); - } - } - removeCaCertificateListener(listener) { - this.caListeners.delete(listener); - this.maybeStopWatchingFiles(); - } - addIdentityCertificateListener(listener) { - this.identityListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestIdentityUpdate !== undefined) { - process.nextTick(listener, this.latestIdentityUpdate); - } - } - removeIdentityCertificateListener(listener) { - this.identityListeners.delete(listener); - this.maybeStopWatchingFiles(); - } -} -exports.FileWatcherCertificateProvider = FileWatcherCertificateProvider; -//# sourceMappingURL=certificate-provider.js.map - -/***/ }), +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); -/***/ 44030: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composePaginateRest: () => composePaginateRest, + isPaginatingEndpoint: () => isPaginatingEndpoint, + paginateRest: () => paginateRest, + paginatingEndpoints: () => paginatingEndpoints +}); +module.exports = __toCommonJS(dist_src_exports); -"use strict"; +// pkg/dist-src/version.js +var VERSION = "9.2.2"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChannelCredentials = void 0; -exports.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials; -const tls_1 = __nccwpck_require__(24404); -const call_credentials_1 = __nccwpck_require__(21426); -const tls_helpers_1 = __nccwpck_require__(86581); -const uri_parser_1 = __nccwpck_require__(65974); -const resolver_1 = __nccwpck_require__(31594); -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function verifyIsBufferOrNull(obj, friendlyName) { - if (obj && !(obj instanceof Buffer)) { - throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); - } -} -/** - * A class that contains credentials for communicating over a channel, as well - * as a set of per-call credentials, which are applied to every method call made - * over a channel initialized with an instance of this class. - */ -class ChannelCredentials { - /** - * Returns a copy of this object with the included set of per-call credentials - * expanded to include callCredentials. - * @param callCredentials A CallCredentials object to associate with this - * instance. - */ - compose(callCredentials) { - return new ComposedChannelCredentialsImpl(this, callCredentials); - } - /** - * Return a new ChannelCredentials instance with a given set of credentials. - * The resulting instance can be used to construct a Channel that communicates - * over TLS. - * @param rootCerts The root certificate data. - * @param privateKey The client certificate private key, if available. - * @param certChain The client certificate key chain, if available. - * @param verifyOptions Additional options to modify certificate verification - */ - static createSsl(rootCerts, privateKey, certChain, verifyOptions) { - var _a; - verifyIsBufferOrNull(rootCerts, 'Root certificate'); - verifyIsBufferOrNull(privateKey, 'Private key'); - verifyIsBufferOrNull(certChain, 'Certificate chain'); - if (privateKey && !certChain) { - throw new Error('Private key must be given with accompanying certificate chain'); - } - if (!privateKey && certChain) { - throw new Error('Certificate chain must be given with accompanying private key'); - } - const secureContext = (0, tls_1.createSecureContext)({ - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, - key: privateKey !== null && privateKey !== void 0 ? privateKey : undefined, - cert: certChain !== null && certChain !== void 0 ? certChain : undefined, - ciphers: tls_helpers_1.CIPHER_SUITES, - }); - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with credentials created using - * the provided secureContext. The resulting instances can be used to - * construct a Channel that communicates over TLS. gRPC will not override - * anything in the provided secureContext, so the environment variables - * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will - * not be applied. - * @param secureContext The return value of tls.createSecureContext() - * @param verifyOptions Additional options to modify certificate verification - */ - static createFromSecureContext(secureContext, verifyOptions) { - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with no credentials. - */ - static createInsecure() { - return new InsecureChannelCredentialsImpl(); - } -} -exports.ChannelCredentials = ChannelCredentials; -class InsecureChannelCredentialsImpl extends ChannelCredentials { - constructor() { - super(); - } - compose(callCredentials) { - throw new Error('Cannot compose insecure credentials'); - } - _isSecure() { - return false; - } - _equals(other) { - return other instanceof InsecureChannelCredentialsImpl; - } - _createSecureConnector(channelTarget, options, callCredentials) { - return { - connect(socket) { - return Promise.resolve({ - socket, - secure: false - }); - }, - waitForReady: () => { - return Promise.resolve(); - }, - getCallCredentials: () => { - return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); - }, - destroy() { } - }; - } -} -function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) { - var _a, _b; - const connectionOptions = { - secureContext: secureContext +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] }; - let realTarget = channelTarget; - if ('grpc.http_connect_target' in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); - if (parsedTarget) { - realTarget = parsedTarget; - } - } - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); - const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath; - connectionOptions.host = remoteHost; - if (verifyOptions.checkServerIdentity) { - connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; - } - if (verifyOptions.rejectUnauthorized !== undefined) { - connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; - } - connectionOptions.ALPNProtocols = ['h2']; - if (options['grpc.ssl_target_name_override']) { - const sslTargetNameOverride = options['grpc.ssl_target_name_override']; - const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity; - connectionOptions.checkServerIdentity = (host, cert) => { - return originalCheckServerIdentity(sslTargetNameOverride, cert); - }; - connectionOptions.servername = sslTargetNameOverride; - } - else { - connectionOptions.servername = remoteHost; - } - if (options['grpc-node.tls_enable_trace']) { - connectionOptions.enableTrace = true; - } - return connectionOptions; -} -class SecureConnectorImpl { - constructor(connectionOptions, callCredentials) { - this.connectionOptions = connectionOptions; - this.callCredentials = callCredentials; - } - connect(socket) { - const tlsConnectOptions = Object.assign({ socket: socket }, this.connectionOptions); - return new Promise((resolve, reject) => { - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.on('error', (error) => { - reject(error); - }); - }); - } - waitForReady() { - return Promise.resolve(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { } -} -class SecureChannelCredentialsImpl extends ChannelCredentials { - constructor(secureContext, verifyOptions) { - super(); - this.secureContext = secureContext; - this.verifyOptions = verifyOptions; - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof SecureChannelCredentialsImpl) { - return (this.secureContext === other.secureContext && - this.verifyOptions.checkServerIdentity === - other.verifyOptions.checkServerIdentity); - } - else { - return false; - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); - return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } + } + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) + return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + return response; } -class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { - constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) { - super(); - this.caCertificateProvider = caCertificateProvider; - this.identityCertificateProvider = identityCertificateProvider; - this.verifyOptions = verifyOptions; - this.refcount = 0; - /** - * `undefined` means that the certificates have not yet been loaded. `null` - * means that an attempt to load them has completed, and has failed. - */ - this.latestCaUpdate = undefined; - /** - * `undefined` means that the certificates have not yet been loaded. `null` - * means that an attempt to load them has completed, and has failed. - */ - this.latestIdentityUpdate = undefined; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - this.secureContextWatchers = []; - } - _isSecure() { - return true; - } - _equals(other) { - var _a, _b; - if (this === other) { - return true; - } - if (other instanceof CertificateProviderChannelCredentialsImpl) { - return this.caCertificateProvider === other.caCertificateProvider && - this.identityCertificateProvider === other.identityCertificateProvider && - ((_a = this.verifyOptions) === null || _a === void 0 ? void 0 : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === void 0 ? void 0 : _b.checkServerIdentity); - } - else { - return false; - } - } - ref() { - var _a; - if (this.refcount === 0) { - this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - this.refcount += 1; - } - unref() { - var _a; - this.refcount -= 1; - if (this.refcount === 0) { - this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - this.ref(); - return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } - maybeUpdateWatchers() { - if (this.hasReceivedUpdates()) { - for (const watcher of this.secureContextWatchers) { - watcher(this.getLatestSecureContext()); - } - this.secureContextWatchers = []; - } - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.maybeUpdateWatchers(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.maybeUpdateWatchers(); - } - hasReceivedUpdates() { - if (this.latestCaUpdate === undefined) { - return false; - } - if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { - return false; - } - return true; - } - getSecureContext() { - if (this.hasReceivedUpdates()) { - return Promise.resolve(this.getLatestSecureContext()); - } - else { - return new Promise(resolve => { - this.secureContextWatchers.push(resolve); - }); - } - } - getLatestSecureContext() { - var _a, _b; - if (!this.latestCaUpdate) { - return null; - } - if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { - return null; - } + +// pkg/dist-src/iterator.js +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) + return { done: true }; try { - return (0, tls_1.createSecureContext)({ - ca: this.latestCaUpdate.caCertificate, - key: (_a = this.latestIdentityUpdate) === null || _a === void 0 ? void 0 : _a.privateKey, - cert: (_b = this.latestIdentityUpdate) === null || _b === void 0 ? void 0 : _b.certificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to createSecureContext with error ' + e.message); - return null; - } - } -} -CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class { - constructor(parent, channelTarget, options, callCredentials) { - this.parent = parent; - this.channelTarget = channelTarget; - this.options = options; - this.callCredentials = callCredentials; - } - connect(socket) { - return new Promise((resolve, reject) => { - const secureContext = this.parent.getLatestSecureContext(); - if (!secureContext) { - reject(new Error('Failed to load credentials')); - return; - } - if (socket.closed) { - reject(new Error('Socket closed while loading credentials')); + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) + throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] } - const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); - const tlsConnectOptions = Object.assign({ socket: socket }, connnectionOptions); - const closeCallback = () => { - reject(new Error('Socket closed')); - }; - const errorCallback = (error) => { - reject(error); - }; - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - tlsSocket.removeListener('close', closeCallback); - tlsSocket.removeListener('error', errorCallback); - if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.once('close', closeCallback); - tlsSocket.once('error', errorCallback); - }); - } - async waitForReady() { - await this.parent.getSecureContext(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { - this.parent.unref(); - } -}; -function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) { - return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); -} -class ComposedChannelCredentialsImpl extends ChannelCredentials { - constructor(channelCredentials, callCredentials) { - super(); - this.channelCredentials = channelCredentials; - this.callCredentials = callCredentials; - if (!channelCredentials._isSecure()) { - throw new Error('Cannot compose insecure credentials'); - } - } - compose(callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials); - return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof ComposedChannelCredentialsImpl) { - return (this.channelCredentials._equals(other.channelCredentials) && - this.callCredentials._equals(other.callCredentials)); - } - else { - return false; + }; } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); - } + } + }) + }; } -//# sourceMappingURL=channel-credentials.js.map - -/***/ }), - -/***/ 99810: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.recognizedOptions = void 0; -exports.channelOptionsEqual = channelOptionsEqual; -/** - * This is for checking provided options at runtime. This is an object for - * easier membership checking. - */ -exports.recognizedOptions = { - 'grpc.ssl_target_name_override': true, - 'grpc.primary_user_agent': true, - 'grpc.secondary_user_agent': true, - 'grpc.default_authority': true, - 'grpc.keepalive_time_ms': true, - 'grpc.keepalive_timeout_ms': true, - 'grpc.keepalive_permit_without_calls': true, - 'grpc.service_config': true, - 'grpc.max_concurrent_streams': true, - 'grpc.initial_reconnect_backoff_ms': true, - 'grpc.max_reconnect_backoff_ms': true, - 'grpc.use_local_subchannel_pool': true, - 'grpc.max_send_message_length': true, - 'grpc.max_receive_message_length': true, - 'grpc.enable_http_proxy': true, - 'grpc.enable_channelz': true, - 'grpc.dns_min_time_between_resolutions_ms': true, - 'grpc.enable_retries': true, - 'grpc.per_rpc_retry_buffer_size': true, - 'grpc.retry_buffer_size': true, - 'grpc.max_connection_age_ms': true, - 'grpc.max_connection_age_grace_ms': true, - 'grpc-node.max_session_memory': true, - 'grpc.service_config_disable_resolution': true, - 'grpc.client_idle_timeout_ms': true, - 'grpc-node.tls_enable_trace': true, - 'grpc.lb.ring_hash.ring_size_cap': true, - 'grpc-node.retry_max_attempts_limit': true, - 'grpc-node.flow_control_window': true, - 'grpc.server_call_metric_recording': true -}; -function channelOptionsEqual(options1, options2) { - const keys1 = Object.keys(options1).sort(); - const keys2 = Object.keys(options2).sort(); - if (keys1.length !== keys2.length) { - return false; - } - for (let i = 0; i < keys1.length; i += 1) { - if (keys1[i] !== keys2[i]) { - return false; - } - if (options1[keys1[i]] !== options2[keys2[i]]) { - return false; - } - } - return true; +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); } -//# sourceMappingURL=channel-options.js.map - -/***/ }), - -/***/ 13860: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChannelImplementation = void 0; -const channel_credentials_1 = __nccwpck_require__(44030); -const internal_channel_1 = __nccwpck_require__(69672); -class ChannelImplementation { - constructor(target, credentials, options) { - if (typeof target !== 'string') { - throw new TypeError('Channel target must be a string'); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError('Channel credentials must be a ChannelCredentials object'); - } - if (options) { - if (typeof options !== 'object') { - throw new TypeError('Channel options must be an object'); - } - } - this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); - } - close() { - this.internalChannel.close(); - } - getTarget() { - return this.internalChannel.getTarget(); - } - getConnectivityState(tryToConnect) { - return this.internalChannel.getConnectivityState(tryToConnect); - } - watchConnectivityState(currentState, deadline, callback) { - this.internalChannel.watchConnectivityState(currentState, deadline, callback); +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.internalChannel.getChannelzRef(); + let earlyExit = false; + function done() { + earlyExit = true; } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== 'string') { - throw new TypeError('Channel#createCall: method must be a string'); - } - if (!(typeof deadline === 'number' || deadline instanceof Date)) { - throw new TypeError('Channel#createCall: deadline must be a number or Date'); - } - return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; } + return gather(octokit, results, iterator2, mapFn); + }); } -exports.ChannelImplementation = ChannelImplementation; -//# sourceMappingURL=channel.js.map - -/***/ }), -/***/ 79975: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.registerChannelzSocket = exports.registerChannelzServer = exports.registerChannelzSubchannel = exports.registerChannelzChannel = exports.ChannelzCallTrackerStub = exports.ChannelzCallTracker = exports.ChannelzChildrenTrackerStub = exports.ChannelzChildrenTracker = exports.ChannelzTrace = exports.ChannelzTraceStub = void 0; -exports.unregisterChannelzRef = unregisterChannelzRef; -exports.getChannelzHandlers = getChannelzHandlers; -exports.getChannelzServiceDefinition = getChannelzServiceDefinition; -exports.setup = setup; -const net_1 = __nccwpck_require__(41808); -const ordered_map_1 = __nccwpck_require__(12592); -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const subchannel_address_1 = __nccwpck_require__(99905); -const admin_1 = __nccwpck_require__(8258); -const make_client_1 = __nccwpck_require__(38541); -function channelRefToMessage(ref) { - return { - channel_id: ref.id, - name: ref.name, - }; -} -function subchannelRefToMessage(ref) { - return { - subchannel_id: ref.id, - name: ref.name, - }; -} -function serverRefToMessage(ref) { - return { - server_id: ref.id, - }; -} -function socketRefToMessage(ref) { - return { - socket_id: ref.id, - name: ref.name, - }; -} -/** - * The loose upper bound on the number of events that should be retained in a - * trace. This may be exceeded by up to a factor of 2. Arbitrarily chosen as a - * number that should be large enough to contain the recent relevant - * information, but small enough to not use excessive memory. - */ -const TARGET_RETAINED_TRACES = 32; -/** - * Default number of sockets/servers/channels/subchannels to return - */ -const DEFAULT_MAX_RESULTS = 100; -class ChannelzTraceStub { - constructor() { - this.events = []; - this.creationTimestamp = new Date(); - this.eventsLogged = 0; - } - addTrace() { } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: [], - }; - } -} -exports.ChannelzTraceStub = ChannelzTraceStub; -class ChannelzTrace { - constructor() { - this.events = []; - this.eventsLogged = 0; - this.creationTimestamp = new Date(); - } - addTrace(severity, description, child) { - const timestamp = new Date(); - this.events.push({ - description: description, - severity: severity, - timestamp: timestamp, - childChannel: (child === null || child === void 0 ? void 0 : child.kind) === 'channel' ? child : undefined, - childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === 'subchannel' ? child : undefined, - }); - // Whenever the trace array gets too large, discard the first half - if (this.events.length >= TARGET_RETAINED_TRACES * 2) { - this.events = this.events.slice(TARGET_RETAINED_TRACES); - } - this.eventsLogged += 1; - } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: this.events.map(event => { - return { - description: event.description, - severity: event.severity, - timestamp: dateToProtoTimestamp(event.timestamp), - channel_ref: event.childChannel - ? channelRefToMessage(event.childChannel) - : null, - subchannel_ref: event.childSubchannel - ? subchannelRefToMessage(event.childSubchannel) - : null, - }; - }), - }; - } -} -exports.ChannelzTrace = ChannelzTrace; -class ChannelzChildrenTracker { - constructor() { - this.channelChildren = new ordered_map_1.OrderedMap(); - this.subchannelChildren = new ordered_map_1.OrderedMap(); - this.socketChildren = new ordered_map_1.OrderedMap(); - this.trackerMap = { - ["channel" /* EntityTypes.channel */]: this.channelChildren, - ["subchannel" /* EntityTypes.subchannel */]: this.subchannelChildren, - ["socket" /* EntityTypes.socket */]: this.socketChildren, - }; - } - refChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.find(child.id); - if (trackedChild.equals(tracker.end())) { - tracker.setElement(child.id, { - ref: child, - count: 1, - }, trackedChild); - } - else { - trackedChild.pointer[1].count += 1; - } - } - unrefChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.getElementByKey(child.id); - if (trackedChild !== undefined) { - trackedChild.count -= 1; - if (trackedChild.count === 0) { - tracker.eraseElementByKey(child.id); - } - } - } - getChildLists() { - return { - channels: this.channelChildren, - subchannels: this.subchannelChildren, - sockets: this.socketChildren, - }; - } -} -exports.ChannelzChildrenTracker = ChannelzChildrenTracker; -class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { - refChild() { } - unrefChild() { } -} -exports.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; -class ChannelzCallTracker { - constructor() { - this.callsStarted = 0; - this.callsSucceeded = 0; - this.callsFailed = 0; - this.lastCallStartedTimestamp = null; - } - addCallStarted() { - this.callsStarted += 1; - this.lastCallStartedTimestamp = new Date(); - } - addCallSucceeded() { - this.callsSucceeded += 1; - } - addCallFailed() { - this.callsFailed += 1; - } -} -exports.ChannelzCallTracker = ChannelzCallTracker; -class ChannelzCallTrackerStub extends ChannelzCallTracker { - addCallStarted() { } - addCallSucceeded() { } - addCallFailed() { } -} -exports.ChannelzCallTrackerStub = ChannelzCallTrackerStub; -const entityMaps = { - ["channel" /* EntityTypes.channel */]: new ordered_map_1.OrderedMap(), - ["subchannel" /* EntityTypes.subchannel */]: new ordered_map_1.OrderedMap(), - ["server" /* EntityTypes.server */]: new ordered_map_1.OrderedMap(), - ["socket" /* EntityTypes.socket */]: new ordered_map_1.OrderedMap(), -}; -const generateRegisterFn = (kind) => { - let nextId = 1; - function getNextId() { - return nextId++; - } - const entityMap = entityMaps[kind]; - return (name, getInfo, channelzEnabled) => { - const id = getNextId(); - const ref = { id, name, kind }; - if (channelzEnabled) { - entityMap.setElement(id, { ref, getInfo }); - } - return ref; - }; -}; -exports.registerChannelzChannel = generateRegisterFn("channel" /* EntityTypes.channel */); -exports.registerChannelzSubchannel = generateRegisterFn("subchannel" /* EntityTypes.subchannel */); -exports.registerChannelzServer = generateRegisterFn("server" /* EntityTypes.server */); -exports.registerChannelzSocket = generateRegisterFn("socket" /* EntityTypes.socket */); -function unregisterChannelzRef(ref) { - entityMaps[ref.kind].eraseElementByKey(ref.id); -} -/** - * Parse a single section of an IPv6 address as two bytes - * @param addressSection A hexadecimal string of length up to 4 - * @returns The pair of bytes representing this address section - */ -function parseIPv6Section(addressSection) { - const numberValue = Number.parseInt(addressSection, 16); - return [(numberValue / 256) | 0, numberValue % 256]; -} -/** - * Parse a chunk of an IPv6 address string to some number of bytes - * @param addressChunk Some number of segments of up to 4 hexadecimal - * characters each, joined by colons. - * @returns The list of bytes representing this address chunk - */ -function parseIPv6Chunk(addressChunk) { - if (addressChunk === '') { - return []; - } - const bytePairs = addressChunk - .split(':') - .map(section => parseIPv6Section(section)); - const result = []; - return result.concat(...bytePairs); -} -function isIPv6MappedIPv4(ipAddress) { - return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith('::ffff:') && (0, net_1.isIPv4)(ipAddress.substring(7)); -} -/** - * Prerequisite: isIPv4(ipAddress) - * @param ipAddress - * @returns - */ -function ipv4AddressStringToBuffer(ipAddress) { - return Buffer.from(Uint8Array.from(ipAddress.split('.').map(segment => Number.parseInt(segment)))); -} -/** - * Converts an IPv4 or IPv6 address from string representation to binary - * representation - * @param ipAddress an IP address in standard IPv4 or IPv6 text format - * @returns - */ -function ipAddressStringToBuffer(ipAddress) { - if ((0, net_1.isIPv4)(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress); - } - else if (isIPv6MappedIPv4(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress.substring(7)); - } - else if ((0, net_1.isIPv6)(ipAddress)) { - let leftSection; - let rightSection; - const doubleColonIndex = ipAddress.indexOf('::'); - if (doubleColonIndex === -1) { - leftSection = ipAddress; - rightSection = ''; - } - else { - leftSection = ipAddress.substring(0, doubleColonIndex); - rightSection = ipAddress.substring(doubleColonIndex + 2); - } - const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); - const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); - const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); - return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); - } - else { - return null; - } -} -function connectivityStateToMessage(state) { - switch (state) { - case connectivity_state_1.ConnectivityState.CONNECTING: - return { - state: 'CONNECTING', - }; - case connectivity_state_1.ConnectivityState.IDLE: - return { - state: 'IDLE', - }; - case connectivity_state_1.ConnectivityState.READY: - return { - state: 'READY', - }; - case connectivity_state_1.ConnectivityState.SHUTDOWN: - return { - state: 'SHUTDOWN', - }; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - return { - state: 'TRANSIENT_FAILURE', - }; - default: - return { - state: 'UNKNOWN', - }; - } -} -function dateToProtoTimestamp(date) { - if (!date) { - return null; - } - const millisSinceEpoch = date.getTime(); - return { - seconds: (millisSinceEpoch / 1000) | 0, - nanos: (millisSinceEpoch % 1000) * 1000000, - }; -} -function getChannelMessage(channelEntry) { - const resolvedInfo = channelEntry.getInfo(); - const channelRef = []; - const subchannelRef = []; - resolvedInfo.children.channels.forEach(el => { - channelRef.push(channelRefToMessage(el[1].ref)); - }); - resolvedInfo.children.subchannels.forEach(el => { - subchannelRef.push(subchannelRefToMessage(el[1].ref)); - }); - return { - ref: channelRefToMessage(channelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - channel_ref: channelRef, - subchannel_ref: subchannelRef, - }; -} -function GetChannel(call, callback) { - const channelId = parseInt(call.request.channel_id, 10); - const channelEntry = entityMaps["channel" /* EntityTypes.channel */].getElementByKey(channelId); - if (channelEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No channel data found for id ' + channelId, - }); - return; - } - callback(null, { channel: getChannelMessage(channelEntry) }); -} -function GetTopChannels(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resultList = []; - const startId = parseInt(call.request.start_channel_id, 10); - const channelEntries = entityMaps["channel" /* EntityTypes.channel */]; - let i; - for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getChannelMessage(i.pointer[1])); - } - callback(null, { - channel: resultList, - end: i.equals(channelEntries.end()), - }); -} -function getServerMessage(serverEntry) { - const resolvedInfo = serverEntry.getInfo(); - const listenSocket = []; - resolvedInfo.listenerChildren.sockets.forEach(el => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - return { - ref: serverRefToMessage(serverEntry.ref), - data: { - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - listen_socket: listenSocket, - }; -} -function GetServer(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntries = entityMaps["server" /* EntityTypes.server */]; - const serverEntry = serverEntries.getElementByKey(serverId); - if (serverEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No server data found for id ' + serverId, - }); - return; - } - callback(null, { server: getServerMessage(serverEntry) }); -} -function GetServers(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const startId = parseInt(call.request.start_server_id, 10); - const serverEntries = entityMaps["server" /* EntityTypes.server */]; - const resultList = []; - let i; - for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getServerMessage(i.pointer[1])); - } - callback(null, { - server: resultList, - end: i.equals(serverEntries.end()), - }); -} -function GetSubchannel(call, callback) { - const subchannelId = parseInt(call.request.subchannel_id, 10); - const subchannelEntry = entityMaps["subchannel" /* EntityTypes.subchannel */].getElementByKey(subchannelId); - if (subchannelEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No subchannel data found for id ' + subchannelId, - }); - return; - } - const resolvedInfo = subchannelEntry.getInfo(); - const listenSocket = []; - resolvedInfo.children.sockets.forEach(el => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - const subchannelMessage = { - ref: subchannelRefToMessage(subchannelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - socket_ref: listenSocket, - }; - callback(null, { subchannel: subchannelMessage }); -} -function subchannelAddressToAddressMessage(subchannelAddress) { - var _a; - if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { - return { - address: 'tcpip_address', - tcpip_address: { - ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : undefined, - port: subchannelAddress.port, - }, - }; - } - else { - return { - address: 'uds_address', - uds_address: { - filename: subchannelAddress.path, - }, - }; - } -} -function GetSocket(call, callback) { - var _a, _b, _c, _d, _e; - const socketId = parseInt(call.request.socket_id, 10); - const socketEntry = entityMaps["socket" /* EntityTypes.socket */].getElementByKey(socketId); - if (socketEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No socket data found for id ' + socketId, - }); - return; - } - const resolvedInfo = socketEntry.getInfo(); - const securityMessage = resolvedInfo.security - ? { - model: 'tls', - tls: { - cipher_suite: resolvedInfo.security.cipherSuiteStandardName - ? 'standard_name' - : 'other_name', - standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : undefined, - other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : undefined, - local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : undefined, - remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : undefined, - }, - } - : null; - const socketMessage = { - ref: socketRefToMessage(socketEntry.ref), - local: resolvedInfo.localAddress - ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) - : null, - remote: resolvedInfo.remoteAddress - ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) - : null, - remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : undefined, - security: securityMessage, - data: { - keep_alives_sent: resolvedInfo.keepAlivesSent, - streams_started: resolvedInfo.streamsStarted, - streams_succeeded: resolvedInfo.streamsSucceeded, - streams_failed: resolvedInfo.streamsFailed, - last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), - last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), - messages_received: resolvedInfo.messagesReceived, - messages_sent: resolvedInfo.messagesSent, - last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), - last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), - local_flow_control_window: resolvedInfo.localFlowControlWindow - ? { value: resolvedInfo.localFlowControlWindow } - : null, - remote_flow_control_window: resolvedInfo.remoteFlowControlWindow - ? { value: resolvedInfo.remoteFlowControlWindow } - : null, - }, - }; - callback(null, { socket: socketMessage }); -} -function GetServerSockets(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntry = entityMaps["server" /* EntityTypes.server */].getElementByKey(serverId); - if (serverEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No server data found for id ' + serverId, - }); - return; - } - const startId = parseInt(call.request.start_socket_id, 10); - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resolvedInfo = serverEntry.getInfo(); - // If we wanted to include listener sockets in the result, this line would - // instead say - // const allSockets = resolvedInfo.listenerChildren.sockets.concat(resolvedInfo.sessionChildren.sockets).sort((ref1, ref2) => ref1.id - ref2.id); - const allSockets = resolvedInfo.sessionChildren.sockets; - const resultList = []; - let i; - for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(socketRefToMessage(i.pointer[1].ref)); - } - callback(null, { - socket_ref: resultList, - end: i.equals(allSockets.end()), - }); -} -function getChannelzHandlers() { - return { - GetChannel, - GetTopChannels, - GetServer, - GetServers, - GetSubchannel, - GetSocket, - GetServerSockets, - }; -} -let loadedChannelzDefinition = null; -function getChannelzServiceDefinition() { - if (loadedChannelzDefinition) { - return loadedChannelzDefinition; - } - /* The purpose of this complexity is to avoid loading @grpc/proto-loader at - * runtime for users who will not use/enable channelz. */ - const loaderLoadSync = (__nccwpck_require__(48934)/* .loadSync */ .J_); - const loadedProto = loaderLoadSync('channelz.proto', { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [__nccwpck_require__.ab + "proto"], - }); - const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); - loadedChannelzDefinition = - channelzGrpcObject.grpc.channelz.v1.Channelz.service; - return loadedChannelzDefinition; +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = [ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/secret-scanning/alerts", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/columns/{column_id}/cards", + "GET /projects/{project_id}/collaborators", + "GET /projects/{project_id}/columns", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /repositories/{repository_id}/environments/{environment_name}/secrets", + "GET /repositories/{repository_id}/environments/{environment_name}/variables", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +]; + +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } } -function setup() { - (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); + +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; } -//# sourceMappingURL=channelz.js.map +paginateRest.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + /***/ }), -/***/ 82127: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3044: +/***/ ((module) => { "use strict"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = void 0; -exports.getInterceptingCall = getInterceptingCall; -const metadata_1 = __nccwpck_require__(83665); -const call_interface_1 = __nccwpck_require__(78710); -const constants_1 = __nccwpck_require__(90634); -const error_1 = __nccwpck_require__(22336); -/** - * Error class associated with passing both interceptors and interceptor - * providers to a client constructor or as call options. - */ -class InterceptorConfigurationError extends Error { - constructor(message) { - super(message); - this.name = 'InterceptorConfigurationError'; - Error.captureStackTrace(this, InterceptorConfigurationError); - } -} -exports.InterceptorConfigurationError = InterceptorConfigurationError; -class ListenerBuilder { - constructor() { - this.metadata = undefined; - this.message = undefined; - this.status = undefined; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveStatus(onReceiveStatus) { - this.status = onReceiveStatus; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveStatus: this.status, - }; - } -} -exports.ListenerBuilder = ListenerBuilder; -class RequesterBuilder { - constructor() { - this.start = undefined; - this.message = undefined; - this.halfClose = undefined; - this.cancel = undefined; - } - withStart(start) { - this.start = start; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withHalfClose(halfClose) { - this.halfClose = halfClose; - return this; - } - withCancel(cancel) { - this.cancel = cancel; - return this; - } - build() { - return { - start: this.start, - sendMessage: this.message, - halfClose: this.halfClose, - cancel: this.cancel, - }; - } -} -exports.RequesterBuilder = RequesterBuilder; -/** - * A Listener with a default pass-through implementation of each method. Used - * for filling out Listeners with some methods omitted. - */ -const defaultListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveStatus: (status, next) => { - next(status); - }, +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 }); }; -/** - * A Requester with a default pass-through implementation of each method. Used - * for filling out Requesters with some methods omitted. - */ -const defaultRequester = { - start: (metadata, listener, next) => { - next(metadata, listener); - }, - sendMessage: (message, next) => { - next(message); - }, - halfClose: next => { - next(); - }, - cancel: next => { - next(); - }, +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; }; -class InterceptingCall { - constructor(nextCall, requester) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - /** - * Indicates that metadata has been passed to the requester's start - * method but it has not been passed to the corresponding next callback - */ - this.processingMetadata = false; - /** - * Message context for a pending message that is waiting for - */ - this.pendingMessageContext = null; - /** - * Indicates that a message has been passed to the requester's sendMessage - * method but it has not been passed to the corresponding next callback - */ - this.processingMessage = false; - /** - * Indicates that a status was received but could not be propagated because - * a message was still being processed. - */ - this.pendingHalfClose = false; - if (requester) { - this.requester = { - start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start, - sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage, - halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose, - cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel, - }; - } - else { - this.requester = defaultRequester; - } - } - cancelWithStatus(status, details) { - this.requester.cancel(() => { - this.nextCall.cancelWithStatus(status, details); - }); - } - getPeer() { - return this.nextCall.getPeer(); - } - processPendingMessage() { - if (this.pendingMessageContext) { - this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); - this.pendingMessageContext = null; - this.pendingMessage = null; - } - } - processPendingHalfClose() { - if (this.pendingHalfClose) { - this.nextCall.halfClose(); - } - } - start(metadata, interceptingListener) { - var _a, _b, _c, _d, _e, _f; - const fullInterceptingListener = { - onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : (metadata => { }), - onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : (message => { }), - onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status => { }), - }; - this.processingMetadata = true; - this.requester.start(metadata, fullInterceptingListener, (md, listener) => { - var _a, _b, _c; - this.processingMetadata = false; - let finalInterceptingListener; - if ((0, call_interface_1.isInterceptingListener)(listener)) { - finalInterceptingListener = listener; - } - else { - const fullListener = { - onReceiveMetadata: (_a = listener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultListener.onReceiveMetadata, - onReceiveMessage: (_b = listener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultListener.onReceiveMessage, - onReceiveStatus: (_c = listener.onReceiveStatus) !== null && _c !== void 0 ? _c : defaultListener.onReceiveStatus, - }; - finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); - } - this.nextCall.start(md, finalInterceptingListener); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context, message) { - this.processingMessage = true; - this.requester.sendMessage(message, finalMessage => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessageContext = context; - this.pendingMessage = message; - } - else { - this.nextCall.sendMessageWithContext(context, finalMessage); - this.processPendingHalfClose(); - } - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - startRead() { - this.nextCall.startRead(); - } - halfClose() { - this.requester.halfClose(() => { - if (this.processingMetadata || this.processingMessage) { - this.pendingHalfClose = true; - } - else { - this.nextCall.halfClose(); - } - }); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } -} -exports.InterceptingCall = InterceptingCall; -function getCall(channel, path, options) { - var _a, _b; - const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity; - const host = options.host; - const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null; - const propagateFlags = options.propagate_flags; - const credentials = options.credentials; - const call = channel.createCall(path, deadline, host, parent, propagateFlags); - if (credentials) { - call.setCredentials(credentials); - } - return call; -} -/** - * InterceptingCall implementation that directly owns the underlying Call - * object and handles serialization and deseraizliation. - */ -class BaseInterceptingCall { - constructor(call, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - methodDefinition) { - this.call = call; - this.methodDefinition = methodDefinition; - } - cancelWithStatus(status, details) { - this.call.cancelWithStatus(status, details); - } - getPeer() { - return this.call.getPeer(); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context, message) { - let serialized; - try { - serialized = this.methodDefinition.requestSerialize(message); - } - catch (e) { - this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); - return; - } - this.call.sendMessageWithContext(context, serialized); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - start(metadata, interceptingListener) { - let readError = null; - this.call.start(metadata, { - onReceiveMetadata: metadata => { - var _a; - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata); - }, - onReceiveMessage: message => { - var _a; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let deserialized; - try { - deserialized = this.methodDefinition.responseDeserialize(message); - } - catch (e) { - readError = { - code: constants_1.Status.INTERNAL, - details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, - metadata: new metadata_1.Metadata(), - }; - this.call.cancelWithStatus(readError.code, readError.details); - return; - } - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized); - }, - onReceiveStatus: status => { - var _a, _b; - if (readError) { - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError); - } - else { - (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status); - } - }, - }); - } - startRead() { - this.call.startRead(); - } - halfClose() { - this.call.halfClose(); - } - getAuthContext() { - return this.call.getAuthContext(); - } -} -/** - * BaseInterceptingCall with special-cased behavior for methods with unary - * responses. - */ -class BaseUnaryInterceptingCall extends BaseInterceptingCall { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - constructor(call, methodDefinition) { - super(call, methodDefinition); - } - start(metadata, listener) { - var _a, _b; - let receivedMessage = false; - const wrapperListener = { - onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : (metadata => { }), - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage: (message) => { - var _a; - receivedMessage = true; - (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, message); - }, - onReceiveStatus: (status) => { - var _a, _b; - if (!receivedMessage) { - (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, null); - } - (_b = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(listener, status); - }, - }; - super.start(metadata, wrapperListener); - this.call.startRead(); - } -} -/** - * BaseInterceptingCall with special-cased behavior for methods with streaming - * responses. - */ -class BaseStreamingInterceptingCall extends BaseInterceptingCall { -} -function getBottomInterceptingCall(channel, options, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -methodDefinition) { - const call = getCall(channel, methodDefinition.path, options); - if (methodDefinition.responseStream) { - return new BaseStreamingInterceptingCall(call, methodDefinition); - } - else { - return new BaseUnaryInterceptingCall(call, methodDefinition); - } -} -function getInterceptingCall(interceptorArgs, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -methodDefinition, options, channel) { - if (interceptorArgs.clientInterceptors.length > 0 && - interceptorArgs.clientInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as options ' + - 'to the client constructor. Only one of these is allowed.'); - } - if (interceptorArgs.callInterceptors.length > 0 && - interceptorArgs.callInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as call ' + - 'options. Only one of these is allowed.'); - } - let interceptors = []; - // Interceptors passed to the call override interceptors passed to the client constructor - if (interceptorArgs.callInterceptors.length > 0 || - interceptorArgs.callInterceptorProviders.length > 0) { - interceptors = [] - .concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map(provider => provider(methodDefinition))) - .filter(interceptor => interceptor); - // Filter out falsy values when providers return nothing - } - else { - interceptors = [] - .concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map(provider => provider(methodDefinition))) - .filter(interceptor => interceptor); - // Filter out falsy values when providers return nothing - } - const interceptorOptions = Object.assign({}, options, { - method_definition: methodDefinition, - }); - /* For each interceptor in the list, the nextCall function passed to it is - * based on the next interceptor in the list, using a nextCall function - * constructed with the following interceptor in the list, and so on. The - * initialValue, which is effectively at the end of the list, is a nextCall - * function that invokes getBottomInterceptingCall, the result of which - * handles (de)serialization and also gets the underlying call from the - * channel. */ - const getCall = interceptors.reduceRight((nextCall, nextInterceptor) => { - return currentOptions => nextInterceptor(currentOptions, nextCall); - }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); - return getCall(interceptorOptions); -} -//# sourceMappingURL=client-interceptors.js.map - -/***/ }), +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -/***/ 87172: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); -"use strict"; +// pkg/dist-src/version.js +var VERSION = "10.4.1"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Client = void 0; -const call_1 = __nccwpck_require__(97453); -const channel_1 = __nccwpck_require__(13860); -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const client_interceptors_1 = __nccwpck_require__(82127); -const CHANNEL_SYMBOL = Symbol(); -const INTERCEPTOR_SYMBOL = Symbol(); -const INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); -const CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); -function isFunction(arg) { - return typeof arg === 'function'; -} -function getErrorStackString(error) { - var _a; - return ((_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n').slice(1).join('\n')) || 'no stack trace available'; -} -/** - * A generic gRPC client. Primarily useful as a base class for all generated - * clients. - */ -class Client { - constructor(address, credentials, options = {}) { - var _a, _b; - options = Object.assign({}, options); - this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : []; - delete options.interceptors; - this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : []; - delete options.interceptor_providers; - if (this[INTERCEPTOR_SYMBOL].length > 0 && - this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { - throw new Error('Both interceptors and interceptor_providers were passed as options ' + - 'to the client constructor. Only one of these is allowed.'); - } - this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = - options.callInvocationTransformer; - delete options.callInvocationTransformer; - if (options.channelOverride) { - this[CHANNEL_SYMBOL] = options.channelOverride; - } - else if (options.channelFactoryOverride) { - const channelFactoryOverride = options.channelFactoryOverride; - delete options.channelFactoryOverride; - this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); - } - else { - this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); - } - } - close() { - this[CHANNEL_SYMBOL].close(); - } - getChannel() { - return this[CHANNEL_SYMBOL]; - } - waitForReady(deadline, callback) { - const checkState = (err) => { - if (err) { - callback(new Error('Failed to connect before the deadline')); - return; - } - let newState; - try { - newState = this[CHANNEL_SYMBOL].getConnectivityState(true); - } - catch (e) { - callback(new Error('The channel has been closed')); - return; - } - if (newState === connectivity_state_1.ConnectivityState.READY) { - callback(); - } - else { - try { - this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); - } - catch (e) { - callback(new Error('The channel has been closed')); - } - } - }; - setImmediate(checkState); - } - checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { - if (isFunction(arg1)) { - return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 }; - } - else if (isFunction(arg2)) { - if (arg1 instanceof metadata_1.Metadata) { - return { metadata: arg1, options: {}, callback: arg2 }; - } - else { - return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 }; - } - } - else { - if (!(arg1 instanceof metadata_1.Metadata && - arg2 instanceof Object && - isFunction(arg3))) { - throw new Error('Incorrect arguments passed'); - } - return { metadata: arg1, options: arg2, callback: arg3 }; - } - } - makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - argument: argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientUnaryCallImpl(), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: metadata => { - emitter.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); - } - responseMessage = message; - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: 'No message received', - metadata: status.metadata, - }, callerStack)); - } - else { - callProperties.callback(null, responseMessage); - } - } - else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - emitter.emit('status', status); - }, - }); - call.sendMessage(argument); - call.halfClose(); - return emitter; - } - makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientWritableStreamImpl(serialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: metadata => { - emitter.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); - } - responseMessage = message; - call.startRead(); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: 'No message received', - metadata: status.metadata, - }, callerStack)); - } - else { - callProperties.callback(null, responseMessage); - } - } - else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - emitter.emit('status', status); - }, - }); - return emitter; - } - checkMetadataAndOptions(arg1, arg2) { - let metadata; - let options; - if (arg1 instanceof metadata_1.Metadata) { - metadata = arg1; - if (arg2) { - options = arg2; - } - else { - options = {}; - } - } - else { - if (arg1) { - options = arg1; - } - else { - options = {}; - } - metadata = new metadata_1.Metadata(); - } - return { metadata, options }; - } - makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - argument: argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientReadableStreamImpl(deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - stream.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata) { - stream.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - stream.emit('status', status); - }, - }); - call.sendMessage(argument); - call.halfClose(); - return stream; - } - makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - stream.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata) { - stream.emit('metadata', metadata); - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - stream.emit('status', status); - }, - }); - return stream; - } -} -exports.Client = Client; -//# sourceMappingURL=client.js.map - -/***/ }), - -/***/ 54789: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CompressionAlgorithms = void 0; -var CompressionAlgorithms; -(function (CompressionAlgorithms) { - CompressionAlgorithms[CompressionAlgorithms["identity"] = 0] = "identity"; - CompressionAlgorithms[CompressionAlgorithms["deflate"] = 1] = "deflate"; - CompressionAlgorithms[CompressionAlgorithms["gzip"] = 2] = "gzip"; -})(CompressionAlgorithms || (exports.CompressionAlgorithms = CompressionAlgorithms = {})); -//# sourceMappingURL=compression-algorithms.js.map - -/***/ }), - -/***/ 47616: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CompressionFilterFactory = exports.CompressionFilter = void 0; -const zlib = __nccwpck_require__(59796); -const compression_algorithms_1 = __nccwpck_require__(54789); -const constants_1 = __nccwpck_require__(90634); -const filter_1 = __nccwpck_require__(43392); -const logging = __nccwpck_require__(35993); -const isCompressionAlgorithmKey = (key) => { - return (typeof key === 'number' && typeof compression_algorithms_1.CompressionAlgorithms[key] === 'string'); -}; -class CompressionHandler { - /** - * @param message Raw uncompressed message bytes - * @param compress Indicates whether the message should be compressed - * @return Framed message, compressed if applicable - */ - async writeMessage(message, compress) { - let messageBuffer = message; - if (compress) { - messageBuffer = await this.compressMessage(messageBuffer); - } - const output = Buffer.allocUnsafe(messageBuffer.length + 5); - output.writeUInt8(compress ? 1 : 0, 0); - output.writeUInt32BE(messageBuffer.length, 1); - messageBuffer.copy(output, 5); - return output; - } - /** - * @param data Framed message, possibly compressed - * @return Uncompressed message - */ - async readMessage(data) { - const compressed = data.readUInt8(0) === 1; - let messageBuffer = data.slice(5); - if (compressed) { - messageBuffer = await this.decompressMessage(messageBuffer); - } - return messageBuffer; - } -} -class IdentityHandler extends CompressionHandler { - async compressMessage(message) { - return message; - } - async writeMessage(message, compress) { - const output = Buffer.allocUnsafe(message.length + 5); - /* With "identity" compression, messages should always be marked as - * uncompressed */ - output.writeUInt8(0, 0); - output.writeUInt32BE(message.length, 1); - message.copy(output, 5); - return output; - } - decompressMessage(message) { - return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); - } -} -class DeflateHandler extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.deflate(message, (err, output) => { - if (err) { - reject(err); - } - else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createInflate(); - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } -} -class GzipHandler extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.gzip(message, (err, output) => { - if (err) { - reject(err); - } - else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createGunzip(); - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } -} -class UnknownHandler extends CompressionHandler { - constructor(compressionName) { - super(); - this.compressionName = compressionName; - } - compressMessage(message) { - return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); - } - decompressMessage(message) { - // This should be unreachable - return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); - } -} -function getCompressionHandler(compressionName, maxReceiveMessageSize) { - switch (compressionName) { - case 'identity': - return new IdentityHandler(); - case 'deflate': - return new DeflateHandler(maxReceiveMessageSize); - case 'gzip': - return new GzipHandler(maxReceiveMessageSize); - default: - return new UnknownHandler(compressionName); - } -} -class CompressionFilter extends filter_1.BaseFilter { - constructor(channelOptions, sharedFilterConfig) { - var _a, _b, _c; - super(); - this.sharedFilterConfig = sharedFilterConfig; - this.sendCompression = new IdentityHandler(); - this.receiveCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = 'identity'; - const compressionAlgorithmKey = channelOptions['grpc.default_compression_algorithm']; - this.maxReceiveMessageLength = (_a = channelOptions['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.maxSendMessageLength = (_b = channelOptions['grpc.max_send_message_length']) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - if (compressionAlgorithmKey !== undefined) { - if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { - const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; - const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === void 0 ? void 0 : _c.split(','); - /** - * There are two possible situations here: - * 1) We don't have any info yet from the server about what compression it supports - * In that case we should just use what the client tells us to use - * 2) We've previously received a response from the server including a grpc-accept-encoding header - * In that case we only want to use the encoding chosen by the client if the server supports it - */ - if (!serverSupportedEncodings || - serverSupportedEncodings.includes(clientSelectedEncoding)) { - this.currentCompressionAlgorithm = clientSelectedEncoding; - this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1); - } - } - else { - logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); - } - } - } - async sendMetadata(metadata) { - const headers = await metadata; - headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); - headers.set('accept-encoding', 'identity'); - // No need to send the header if it's "identity" - behavior is identical; save the bandwidth - if (this.currentCompressionAlgorithm === 'identity') { - headers.remove('grpc-encoding'); - } - else { - headers.set('grpc-encoding', this.currentCompressionAlgorithm); - } - return headers; - } - receiveMetadata(metadata) { - const receiveEncoding = metadata.get('grpc-encoding'); - if (receiveEncoding.length > 0) { - const encoding = receiveEncoding[0]; - if (typeof encoding === 'string') { - this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); - } - } - metadata.remove('grpc-encoding'); - /* Check to see if the compression we're using to send messages is supported by the server - * If not, reset the sendCompression filter and have it use the default IdentityHandler */ - const serverSupportedEncodingsHeader = metadata.get('grpc-accept-encoding')[0]; - if (serverSupportedEncodingsHeader) { - this.sharedFilterConfig.serverSupportedEncodingHeader = - serverSupportedEncodingsHeader; - const serverSupportedEncodings = serverSupportedEncodingsHeader.split(','); - if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { - this.sendCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = 'identity'; - } - } - metadata.remove('grpc-accept-encoding'); - return metadata; - } - async sendMessage(message) { - var _a; - /* This filter is special. The input message is the bare message bytes, - * and the output is a framed and possibly compressed message. For this - * reason, this filter should be at the bottom of the filter stack */ - const resolvedMessage = await message; - if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { - throw { - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` - }; - } - let compress; - if (this.sendCompression instanceof IdentityHandler) { - compress = false; - } - else { - compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2 /* WriteFlags.NoCompress */) === 0; - } - return { - message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), - flags: resolvedMessage.flags, - }; - } - async receiveMessage(message) { - /* This filter is also special. The input message is framed and possibly - * compressed, and the output message is deframed and uncompressed. So - * this is another reason that this filter should be at the bottom of the - * filter stack. */ - return this.receiveCompression.readMessage(await message); - } -} -exports.CompressionFilter = CompressionFilter; -class CompressionFilterFactory { - constructor(channel, options) { - this.options = options; - this.sharedFilterConfig = {}; - } - createFilter() { - return new CompressionFilter(this.options, this.sharedFilterConfig); - } -} -exports.CompressionFilterFactory = CompressionFilterFactory; -//# sourceMappingURL=compression-filter.js.map - -/***/ }), - -/***/ 80878: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ConnectivityState = void 0; -var ConnectivityState; -(function (ConnectivityState) { - ConnectivityState[ConnectivityState["IDLE"] = 0] = "IDLE"; - ConnectivityState[ConnectivityState["CONNECTING"] = 1] = "CONNECTING"; - ConnectivityState[ConnectivityState["READY"] = 2] = "READY"; - ConnectivityState[ConnectivityState["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; - ConnectivityState[ConnectivityState["SHUTDOWN"] = 4] = "SHUTDOWN"; -})(ConnectivityState || (exports.ConnectivityState = ConnectivityState = {})); -//# sourceMappingURL=connectivity-state.js.map - -/***/ }), - -/***/ 90634: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = void 0; -var Status; -(function (Status) { - Status[Status["OK"] = 0] = "OK"; - Status[Status["CANCELLED"] = 1] = "CANCELLED"; - Status[Status["UNKNOWN"] = 2] = "UNKNOWN"; - Status[Status["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; - Status[Status["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; - Status[Status["NOT_FOUND"] = 5] = "NOT_FOUND"; - Status[Status["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; - Status[Status["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; - Status[Status["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; - Status[Status["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; - Status[Status["ABORTED"] = 10] = "ABORTED"; - Status[Status["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; - Status[Status["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; - Status[Status["INTERNAL"] = 13] = "INTERNAL"; - Status[Status["UNAVAILABLE"] = 14] = "UNAVAILABLE"; - Status[Status["DATA_LOSS"] = 15] = "DATA_LOSS"; - Status[Status["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; -})(Status || (exports.Status = Status = {})); -var LogVerbosity; -(function (LogVerbosity) { - LogVerbosity[LogVerbosity["DEBUG"] = 0] = "DEBUG"; - LogVerbosity[LogVerbosity["INFO"] = 1] = "INFO"; - LogVerbosity[LogVerbosity["ERROR"] = 2] = "ERROR"; - LogVerbosity[LogVerbosity["NONE"] = 3] = "NONE"; -})(LogVerbosity || (exports.LogVerbosity = LogVerbosity = {})); -/** - * NOTE: This enum is not currently used in any implemented API in this - * library. It is included only for type parity with the other implementation. - */ -var Propagate; -(function (Propagate) { - Propagate[Propagate["DEADLINE"] = 1] = "DEADLINE"; - Propagate[Propagate["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; - Propagate[Propagate["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; - Propagate[Propagate["CANCELLATION"] = 8] = "CANCELLATION"; - // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43 - Propagate[Propagate["DEFAULTS"] = 65535] = "DEFAULTS"; -})(Propagate || (exports.Propagate = Propagate = {})); -// -1 means unlimited -exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; -// 4 MB default -exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 39129: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; -const constants_1 = __nccwpck_require__(90634); -const INAPPROPRIATE_CONTROL_PLANE_CODES = [ - constants_1.Status.OK, - constants_1.Status.INVALID_ARGUMENT, - constants_1.Status.NOT_FOUND, - constants_1.Status.ALREADY_EXISTS, - constants_1.Status.FAILED_PRECONDITION, - constants_1.Status.ABORTED, - constants_1.Status.OUT_OF_RANGE, - constants_1.Status.DATA_LOSS, -]; -function restrictControlPlaneStatusCode(code, details) { - if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { - return { - code: constants_1.Status.INTERNAL, - details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}`, - }; - } - else { - return { code, details }; - } -} -//# sourceMappingURL=control-plane-status.js.map - -/***/ }), - -/***/ 511: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.minDeadline = minDeadline; -exports.getDeadlineTimeoutString = getDeadlineTimeoutString; -exports.getRelativeTimeout = getRelativeTimeout; -exports.deadlineToString = deadlineToString; -exports.formatDateDifference = formatDateDifference; -function minDeadline(...deadlineList) { - let minValue = Infinity; - for (const deadline of deadlineList) { - const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; - if (deadlineMsecs < minValue) { - minValue = deadlineMsecs; - } - } - return minValue; -} -const units = [ - ['m', 1], - ['S', 1000], - ['M', 60 * 1000], - ['H', 60 * 60 * 1000], -]; -function getDeadlineTimeoutString(deadline) { - const now = new Date().getTime(); - if (deadline instanceof Date) { - deadline = deadline.getTime(); - } - const timeoutMs = Math.max(deadline - now, 0); - for (const [unit, factor] of units) { - const amount = timeoutMs / factor; - if (amount < 1e8) { - return String(Math.ceil(amount)) + unit; - } - } - throw new Error('Deadline is too far in the future'); -} -/** - * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args - * In particular, "When delay is larger than 2147483647 or less than 1, the - * delay will be set to 1. Non-integer delays are truncated to an integer." - * This number of milliseconds is almost 25 days. - */ -const MAX_TIMEOUT_TIME = 2147483647; -/** - * Get the timeout value that should be passed to setTimeout now for the timer - * to end at the deadline. For any deadline before now, the timer should end - * immediately, represented by a value of 0. For any deadline more than - * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will - * end at that time, so it is treated as infinitely far in the future. - * @param deadline - * @returns - */ -function getRelativeTimeout(deadline) { - const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; - const now = new Date().getTime(); - const timeout = deadlineMs - now; - if (timeout < 0) { - return 0; - } - else if (timeout > MAX_TIMEOUT_TIME) { - return Infinity; - } - else { - return timeout; - } -} -function deadlineToString(deadline) { - if (deadline instanceof Date) { - return deadline.toISOString(); - } - else { - const dateDeadline = new Date(deadline); - if (Number.isNaN(dateDeadline.getTime())) { - return '' + deadline; - } - else { - return dateDeadline.toISOString(); - } - } -} -/** - * Calculate the difference between two dates as a number of seconds and format - * it as a string. - * @param startDate - * @param endDate - * @returns - */ -function formatDateDifference(startDate, endDate) { - return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + 's'; -} -//# sourceMappingURL=deadline.js.map - -/***/ }), - -/***/ 62668: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.durationMessageToDuration = durationMessageToDuration; -exports.msToDuration = msToDuration; -exports.durationToMs = durationToMs; -exports.isDuration = isDuration; -exports.isDurationMessage = isDurationMessage; -exports.parseDuration = parseDuration; -exports.durationToString = durationToString; -function durationMessageToDuration(message) { - return { - seconds: Number.parseInt(message.seconds), - nanos: message.nanos - }; -} -function msToDuration(millis) { - return { - seconds: (millis / 1000) | 0, - nanos: ((millis % 1000) * 1000000) | 0, - }; -} -function durationToMs(duration) { - return (duration.seconds * 1000 + duration.nanos / 1000000) | 0; -} -function isDuration(value) { - return typeof value.seconds === 'number' && typeof value.nanos === 'number'; -} -function isDurationMessage(value) { - return typeof value.seconds === 'string' && typeof value.nanos === 'number'; -} -const durationRegex = /^(\d+)(?:\.(\d+))?s$/; -function parseDuration(value) { - const match = value.match(durationRegex); - if (!match) { - return null; - } - return { - seconds: Number.parseInt(match[1], 10), - nanos: match[2] ? Number.parseInt(match[2].padEnd(9, '0'), 10) : 0 - }; -} -function durationToString(duration) { - if (duration.nanos === 0) { - return `${duration.seconds}s`; - } - let scaleFactor; - if (duration.nanos % 1000000 === 0) { - scaleFactor = 1000000; - } - else if (duration.nanos % 1000 === 0) { - scaleFactor = 1000; - } - else { - scaleFactor = 1; - } - return `${duration.seconds}.${duration.nanos / scaleFactor}s`; -} -//# sourceMappingURL=duration.js.map - -/***/ }), - -/***/ 29160: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2024 gRPC 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 - * - * 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 _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; -exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : 'false') === 'true'; -//# sourceMappingURL=environment.js.map - -/***/ }), - -/***/ 22336: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getErrorMessage = getErrorMessage; -exports.getErrorCode = getErrorCode; -function getErrorMessage(error) { - if (error instanceof Error) { - return error.message; - } - else { - return String(error); - } -} -function getErrorCode(error) { - if (typeof error === 'object' && - error !== null && - 'code' in error && - typeof error.code === 'number') { - return error.code; - } - else { - return null; - } -} -//# sourceMappingURL=error.js.map - -/***/ }), - -/***/ 37626: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports.createCertificateProviderChannelCredentials = exports.FileWatcherCertificateProvider = exports.createCertificateProviderServerCredentials = exports.createServerCredentialsWithInterceptors = exports.BaseSubchannelWrapper = exports.registerAdminService = exports.FilterStackFactory = exports.BaseFilter = exports.statusOrFromError = exports.statusOrFromValue = exports.PickResultType = exports.QueuePicker = exports.UnavailablePicker = exports.ChildLoadBalancerHandler = exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.subchannelAddressToString = exports.LeafLoadBalancer = exports.isLoadBalancerNameRegistered = exports.parseLoadBalancingConfig = exports.selectLbConfigFromList = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = exports.BackoffTimeout = exports.parseDuration = exports.durationToMs = exports.splitHostPort = exports.uriToString = exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports.createResolver = exports.registerResolver = exports.log = exports.trace = void 0; -var logging_1 = __nccwpck_require__(35993); -Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return logging_1.trace; } })); -Object.defineProperty(exports, "log", ({ enumerable: true, get: function () { return logging_1.log; } })); -var resolver_1 = __nccwpck_require__(31594); -Object.defineProperty(exports, "registerResolver", ({ enumerable: true, get: function () { return resolver_1.registerResolver; } })); -Object.defineProperty(exports, "createResolver", ({ enumerable: true, get: function () { return resolver_1.createResolver; } })); -Object.defineProperty(exports, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", ({ enumerable: true, get: function () { return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY; } })); -var uri_parser_1 = __nccwpck_require__(65974); -Object.defineProperty(exports, "uriToString", ({ enumerable: true, get: function () { return uri_parser_1.uriToString; } })); -Object.defineProperty(exports, "splitHostPort", ({ enumerable: true, get: function () { return uri_parser_1.splitHostPort; } })); -var duration_1 = __nccwpck_require__(62668); -Object.defineProperty(exports, "durationToMs", ({ enumerable: true, get: function () { return duration_1.durationToMs; } })); -Object.defineProperty(exports, "parseDuration", ({ enumerable: true, get: function () { return duration_1.parseDuration; } })); -var backoff_timeout_1 = __nccwpck_require__(34186); -Object.defineProperty(exports, "BackoffTimeout", ({ enumerable: true, get: function () { return backoff_timeout_1.BackoffTimeout; } })); -var load_balancer_1 = __nccwpck_require__(52680); -Object.defineProperty(exports, "createChildChannelControlHelper", ({ enumerable: true, get: function () { return load_balancer_1.createChildChannelControlHelper; } })); -Object.defineProperty(exports, "registerLoadBalancerType", ({ enumerable: true, get: function () { return load_balancer_1.registerLoadBalancerType; } })); -Object.defineProperty(exports, "selectLbConfigFromList", ({ enumerable: true, get: function () { return load_balancer_1.selectLbConfigFromList; } })); -Object.defineProperty(exports, "parseLoadBalancingConfig", ({ enumerable: true, get: function () { return load_balancer_1.parseLoadBalancingConfig; } })); -Object.defineProperty(exports, "isLoadBalancerNameRegistered", ({ enumerable: true, get: function () { return load_balancer_1.isLoadBalancerNameRegistered; } })); -var load_balancer_pick_first_1 = __nccwpck_require__(38977); -Object.defineProperty(exports, "LeafLoadBalancer", ({ enumerable: true, get: function () { return load_balancer_pick_first_1.LeafLoadBalancer; } })); -var subchannel_address_1 = __nccwpck_require__(99905); -Object.defineProperty(exports, "subchannelAddressToString", ({ enumerable: true, get: function () { return subchannel_address_1.subchannelAddressToString; } })); -Object.defineProperty(exports, "endpointToString", ({ enumerable: true, get: function () { return subchannel_address_1.endpointToString; } })); -Object.defineProperty(exports, "endpointHasAddress", ({ enumerable: true, get: function () { return subchannel_address_1.endpointHasAddress; } })); -Object.defineProperty(exports, "EndpointMap", ({ enumerable: true, get: function () { return subchannel_address_1.EndpointMap; } })); -var load_balancer_child_handler_1 = __nccwpck_require__(17559); -Object.defineProperty(exports, "ChildLoadBalancerHandler", ({ enumerable: true, get: function () { return load_balancer_child_handler_1.ChildLoadBalancerHandler; } })); -var picker_1 = __nccwpck_require__(81611); -Object.defineProperty(exports, "UnavailablePicker", ({ enumerable: true, get: function () { return picker_1.UnavailablePicker; } })); -Object.defineProperty(exports, "QueuePicker", ({ enumerable: true, get: function () { return picker_1.QueuePicker; } })); -Object.defineProperty(exports, "PickResultType", ({ enumerable: true, get: function () { return picker_1.PickResultType; } })); -var call_interface_1 = __nccwpck_require__(78710); -Object.defineProperty(exports, "statusOrFromValue", ({ enumerable: true, get: function () { return call_interface_1.statusOrFromValue; } })); -Object.defineProperty(exports, "statusOrFromError", ({ enumerable: true, get: function () { return call_interface_1.statusOrFromError; } })); -var filter_1 = __nccwpck_require__(43392); -Object.defineProperty(exports, "BaseFilter", ({ enumerable: true, get: function () { return filter_1.BaseFilter; } })); -var filter_stack_1 = __nccwpck_require__(66450); -Object.defineProperty(exports, "FilterStackFactory", ({ enumerable: true, get: function () { return filter_stack_1.FilterStackFactory; } })); -var admin_1 = __nccwpck_require__(8258); -Object.defineProperty(exports, "registerAdminService", ({ enumerable: true, get: function () { return admin_1.registerAdminService; } })); -var subchannel_interface_1 = __nccwpck_require__(12258); -Object.defineProperty(exports, "BaseSubchannelWrapper", ({ enumerable: true, get: function () { return subchannel_interface_1.BaseSubchannelWrapper; } })); -var server_credentials_1 = __nccwpck_require__(63828); -Object.defineProperty(exports, "createServerCredentialsWithInterceptors", ({ enumerable: true, get: function () { return server_credentials_1.createServerCredentialsWithInterceptors; } })); -Object.defineProperty(exports, "createCertificateProviderServerCredentials", ({ enumerable: true, get: function () { return server_credentials_1.createCertificateProviderServerCredentials; } })); -var certificate_provider_1 = __nccwpck_require__(25649); -Object.defineProperty(exports, "FileWatcherCertificateProvider", ({ enumerable: true, get: function () { return certificate_provider_1.FileWatcherCertificateProvider; } })); -var channel_credentials_1 = __nccwpck_require__(44030); -Object.defineProperty(exports, "createCertificateProviderChannelCredentials", ({ enumerable: true, get: function () { return channel_credentials_1.createCertificateProviderChannelCredentials; } })); -var internal_channel_1 = __nccwpck_require__(69672); -Object.defineProperty(exports, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", ({ enumerable: true, get: function () { return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX; } })); -//# sourceMappingURL=experimental.js.map - -/***/ }), - -/***/ 66450: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FilterStackFactory = exports.FilterStack = void 0; -class FilterStack { - constructor(filters) { - this.filters = filters; - } - sendMetadata(metadata) { - let result = metadata; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMetadata(result); - } - return result; - } - receiveMetadata(metadata) { - let result = metadata; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMetadata(result); - } - return result; - } - sendMessage(message) { - let result = message; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMessage(result); - } - return result; - } - receiveMessage(message) { - let result = message; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMessage(result); - } - return result; - } - receiveTrailers(status) { - let result = status; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveTrailers(result); - } - return result; - } - push(filters) { - this.filters.unshift(...filters); - } - getFilters() { - return this.filters; - } -} -exports.FilterStack = FilterStack; -class FilterStackFactory { - constructor(factories) { - this.factories = factories; - } - push(filterFactories) { - this.factories.unshift(...filterFactories); - } - clone() { - return new FilterStackFactory([...this.factories]); - } - createFilter() { - return new FilterStack(this.factories.map(factory => factory.createFilter())); - } -} -exports.FilterStackFactory = FilterStackFactory; -//# sourceMappingURL=filter-stack.js.map - -/***/ }), - -/***/ 43392: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseFilter = void 0; -class BaseFilter { - async sendMetadata(metadata) { - return metadata; - } - receiveMetadata(metadata) { - return metadata; - } - async sendMessage(message) { - return message; - } - async receiveMessage(message) { - return message; - } - receiveTrailers(status) { - return status; - } -} -exports.BaseFilter = BaseFilter; -//# sourceMappingURL=filter.js.map - -/***/ }), - -/***/ 24000: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseCIDR = parseCIDR; -exports.mapProxyName = mapProxyName; -exports.getProxiedConnection = getProxiedConnection; -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const net_1 = __nccwpck_require__(41808); -const http = __nccwpck_require__(13685); -const logging = __nccwpck_require__(35993); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const url_1 = __nccwpck_require__(57310); -const resolver_dns_1 = __nccwpck_require__(54886); -const TRACER_NAME = 'proxy'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -function getProxyInfo() { - let proxyEnv = ''; - let envVar = ''; - /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. - * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The - * fallback behavior can be removed if there's a demand for it. - */ - if (process.env.grpc_proxy) { - envVar = 'grpc_proxy'; - proxyEnv = process.env.grpc_proxy; - } - else if (process.env.https_proxy) { - envVar = 'https_proxy'; - proxyEnv = process.env.https_proxy; - } - else if (process.env.http_proxy) { - envVar = 'http_proxy'; - proxyEnv = process.env.http_proxy; - } - else { - return {}; - } - let proxyUrl; - try { - proxyUrl = new url_1.URL(proxyEnv); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); - return {}; - } - if (proxyUrl.protocol !== 'http:') { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); - return {}; - } - let userCred = null; - if (proxyUrl.username) { - if (proxyUrl.password) { - (0, logging_1.log)(constants_1.LogVerbosity.INFO, 'userinfo found in proxy URI'); - userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); - } - else { - userCred = proxyUrl.username; - } - } - const hostname = proxyUrl.hostname; - let port = proxyUrl.port; - /* The proxy URL uses the scheme "http:", which has a default port number of - * 80. We need to set that explicitly here if it is omitted because otherwise - * it will use gRPC's default port 443. */ - if (port === '') { - port = '80'; - } - const result = { - address: `${hostname}:${port}`, - }; - if (userCred) { - result.creds = userCred; - } - trace('Proxy server ' + result.address + ' set by environment variable ' + envVar); - return result; -} -function getNoProxyHostList() { - /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ - let noProxyStr = process.env.no_grpc_proxy; - let envVar = 'no_grpc_proxy'; - if (!noProxyStr) { - noProxyStr = process.env.no_proxy; - envVar = 'no_proxy'; - } - if (noProxyStr) { - trace('No proxy server list set by environment variable ' + envVar); - return noProxyStr.split(','); - } - else { - return []; - } -} -/* - * The groups correspond to CIDR parts as follows: - * 1. ip - * 2. prefixLength - */ -function parseCIDR(cidrString) { - const splitRange = cidrString.split('/'); - if (splitRange.length !== 2) { - return null; - } - const prefixLength = parseInt(splitRange[1], 10); - if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { - return null; - } - return { - ip: ipToInt(splitRange[0]), - prefixLength: prefixLength - }; -} -function ipToInt(ip) { - return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); -} -function isIpInCIDR(cidr, serverHost) { - const ip = cidr.ip; - const mask = -1 << (32 - cidr.prefixLength); - const hostIP = ipToInt(serverHost); - return (hostIP & mask) === (ip & mask); -} -function hostMatchesNoProxyList(serverHost) { - for (const host of getNoProxyHostList()) { - const parsedCIDR = parseCIDR(host); - // host is a CIDR and serverHost is an IP address - if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { - return true; - } - else if (serverHost.endsWith(host)) { - // host is a single IP or a domain name suffix - return true; - } - } - return false; -} -function mapProxyName(target, options) { - var _a; - const noProxyResult = { - target: target, - extraOptions: {}, - }; - if (((_a = options['grpc.enable_http_proxy']) !== null && _a !== void 0 ? _a : 1) === 0) { - return noProxyResult; - } - if (target.scheme === 'unix') { - return noProxyResult; - } - const proxyInfo = getProxyInfo(); - if (!proxyInfo.address) { - return noProxyResult; - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (!hostPort) { - return noProxyResult; - } - const serverHost = hostPort.host; - if (hostMatchesNoProxyList(serverHost)) { - trace('Not using proxy for target in no_proxy list: ' + (0, uri_parser_1.uriToString)(target)); - return noProxyResult; - } - const extraOptions = { - 'grpc.http_connect_target': (0, uri_parser_1.uriToString)(target), - }; - if (proxyInfo.creds) { - extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; - } - return { - target: { - scheme: 'dns', - path: proxyInfo.address, - }, - extraOptions: extraOptions, - }; -} -function getProxiedConnection(address, channelOptions) { - var _a; - if (!('grpc.http_connect_target' in channelOptions)) { - return Promise.resolve(null); - } - const realTarget = channelOptions['grpc.http_connect_target']; - const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); - if (parsedTarget === null) { - return Promise.resolve(null); - } - const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); - if (splitHostPost === null) { - return Promise.resolve(null); - } - const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`; - const options = { - method: 'CONNECT', - path: hostPort, - }; - const headers = { - Host: hostPort, - }; - // Connect to the subchannel address as a proxy - if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { - options.host = address.host; - options.port = address.port; - } - else { - options.socketPath = address.path; - } - if ('grpc.http_connect_creds' in channelOptions) { - headers['Proxy-Authorization'] = - 'Basic ' + - Buffer.from(channelOptions['grpc.http_connect_creds']).toString('base64'); - } - options.headers = headers; - const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); - trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); - return new Promise((resolve, reject) => { - const request = http.request(options); - request.once('connect', (res, socket, head) => { - request.removeAllListeners(); - socket.removeAllListeners(); - if (res.statusCode === 200) { - trace('Successfully connected to ' + - options.path + - ' through proxy ' + - proxyAddressString); - // The HTTP client may have already read a few bytes of the proxied - // connection. If that's the case, put them back into the socket. - // See https://github.com/grpc/grpc-node/issues/2744. - if (head.length > 0) { - socket.unshift(head); - } - trace('Successfully established a plaintext connection to ' + - options.path + - ' through proxy ' + - proxyAddressString); - resolve(socket); - } - else { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to ' + - options.path + - ' through proxy ' + - proxyAddressString + - ' with status ' + - res.statusCode); - reject(); - } - }); - request.once('error', err => { - request.removeAllListeners(); - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to proxy ' + - proxyAddressString + - ' with error ' + - err.message); - reject(); - }); - request.end(); - }); -} -//# sourceMappingURL=http_proxy.js.map - -/***/ }), - -/***/ 7025: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.experimental = exports.ServerMetricRecorder = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = exports.addAdminServicesToServer = exports.getChannelzHandlers = exports.getChannelzServiceDefinition = exports.InterceptorConfigurationError = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.compressionAlgorithms = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = void 0; -const call_credentials_1 = __nccwpck_require__(21426); -Object.defineProperty(exports, "CallCredentials", ({ enumerable: true, get: function () { return call_credentials_1.CallCredentials; } })); -const channel_1 = __nccwpck_require__(13860); -Object.defineProperty(exports, "Channel", ({ enumerable: true, get: function () { return channel_1.ChannelImplementation; } })); -const compression_algorithms_1 = __nccwpck_require__(54789); -Object.defineProperty(exports, "compressionAlgorithms", ({ enumerable: true, get: function () { return compression_algorithms_1.CompressionAlgorithms; } })); -const connectivity_state_1 = __nccwpck_require__(80878); -Object.defineProperty(exports, "connectivityState", ({ enumerable: true, get: function () { return connectivity_state_1.ConnectivityState; } })); -const channel_credentials_1 = __nccwpck_require__(44030); -Object.defineProperty(exports, "ChannelCredentials", ({ enumerable: true, get: function () { return channel_credentials_1.ChannelCredentials; } })); -const client_1 = __nccwpck_require__(87172); -Object.defineProperty(exports, "Client", ({ enumerable: true, get: function () { return client_1.Client; } })); -const constants_1 = __nccwpck_require__(90634); -Object.defineProperty(exports, "logVerbosity", ({ enumerable: true, get: function () { return constants_1.LogVerbosity; } })); -Object.defineProperty(exports, "status", ({ enumerable: true, get: function () { return constants_1.Status; } })); -Object.defineProperty(exports, "propagate", ({ enumerable: true, get: function () { return constants_1.Propagate; } })); -const logging = __nccwpck_require__(35993); -const make_client_1 = __nccwpck_require__(38541); -Object.defineProperty(exports, "loadPackageDefinition", ({ enumerable: true, get: function () { return make_client_1.loadPackageDefinition; } })); -Object.defineProperty(exports, "makeClientConstructor", ({ enumerable: true, get: function () { return make_client_1.makeClientConstructor; } })); -Object.defineProperty(exports, "makeGenericClientConstructor", ({ enumerable: true, get: function () { return make_client_1.makeClientConstructor; } })); -const metadata_1 = __nccwpck_require__(83665); -Object.defineProperty(exports, "Metadata", ({ enumerable: true, get: function () { return metadata_1.Metadata; } })); -const server_1 = __nccwpck_require__(33389); -Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); -const server_credentials_1 = __nccwpck_require__(63828); -Object.defineProperty(exports, "ServerCredentials", ({ enumerable: true, get: function () { return server_credentials_1.ServerCredentials; } })); -const status_builder_1 = __nccwpck_require__(73155); -Object.defineProperty(exports, "StatusBuilder", ({ enumerable: true, get: function () { return status_builder_1.StatusBuilder; } })); -/**** Client Credentials ****/ -// Using assign only copies enumerable properties, which is what we want -exports.credentials = { - /** - * Combine a ChannelCredentials with any number of CallCredentials into a - * single ChannelCredentials object. - * @param channelCredentials The ChannelCredentials object. - * @param callCredentials Any number of CallCredentials objects. - * @return The resulting ChannelCredentials object. - */ - combineChannelCredentials: (channelCredentials, ...callCredentials) => { - return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); - }, - /** - * Combine any number of CallCredentials into a single CallCredentials - * object. - * @param first The first CallCredentials object. - * @param additional Any number of additional CallCredentials objects. - * @return The resulting CallCredentials object. - */ - combineCallCredentials: (first, ...additional) => { - return additional.reduce((acc, other) => acc.compose(other), first); - }, - // from channel-credentials.ts - createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, - createSsl: channel_credentials_1.ChannelCredentials.createSsl, - createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, - // from call-credentials.ts - createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, - createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, - createEmpty: call_credentials_1.CallCredentials.createEmpty, -}; -/** - * Close a Client object. - * @param client The client to close. - */ -const closeClient = (client) => client.close(); -exports.closeClient = closeClient; -const waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); -exports.waitForClientReady = waitForClientReady; -/* eslint-enable @typescript-eslint/no-explicit-any */ -/**** Unimplemented function stubs ****/ -/* eslint-disable @typescript-eslint/no-explicit-any */ -const loadObject = (value, options) => { - throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); -}; -exports.loadObject = loadObject; -const load = (filename, format, options) => { - throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); -}; -exports.load = load; -const setLogger = (logger) => { - logging.setLogger(logger); -}; -exports.setLogger = setLogger; -const setLogVerbosity = (verbosity) => { - logging.setLoggerVerbosity(verbosity); -}; -exports.setLogVerbosity = setLogVerbosity; -const getClientChannel = (client) => { - return client_1.Client.prototype.getChannel.call(client); -}; -exports.getClientChannel = getClientChannel; -var client_interceptors_1 = __nccwpck_require__(82127); -Object.defineProperty(exports, "ListenerBuilder", ({ enumerable: true, get: function () { return client_interceptors_1.ListenerBuilder; } })); -Object.defineProperty(exports, "RequesterBuilder", ({ enumerable: true, get: function () { return client_interceptors_1.RequesterBuilder; } })); -Object.defineProperty(exports, "InterceptingCall", ({ enumerable: true, get: function () { return client_interceptors_1.InterceptingCall; } })); -Object.defineProperty(exports, "InterceptorConfigurationError", ({ enumerable: true, get: function () { return client_interceptors_1.InterceptorConfigurationError; } })); -var channelz_1 = __nccwpck_require__(79975); -Object.defineProperty(exports, "getChannelzServiceDefinition", ({ enumerable: true, get: function () { return channelz_1.getChannelzServiceDefinition; } })); -Object.defineProperty(exports, "getChannelzHandlers", ({ enumerable: true, get: function () { return channelz_1.getChannelzHandlers; } })); -var admin_1 = __nccwpck_require__(8258); -Object.defineProperty(exports, "addAdminServicesToServer", ({ enumerable: true, get: function () { return admin_1.addAdminServicesToServer; } })); -var server_interceptors_1 = __nccwpck_require__(20998); -Object.defineProperty(exports, "ServerListenerBuilder", ({ enumerable: true, get: function () { return server_interceptors_1.ServerListenerBuilder; } })); -Object.defineProperty(exports, "ResponderBuilder", ({ enumerable: true, get: function () { return server_interceptors_1.ResponderBuilder; } })); -Object.defineProperty(exports, "ServerInterceptingCall", ({ enumerable: true, get: function () { return server_interceptors_1.ServerInterceptingCall; } })); -var orca_1 = __nccwpck_require__(31791); -Object.defineProperty(exports, "ServerMetricRecorder", ({ enumerable: true, get: function () { return orca_1.ServerMetricRecorder; } })); -const experimental = __nccwpck_require__(37626); -exports.experimental = experimental; -const resolver_dns = __nccwpck_require__(54886); -const resolver_uds = __nccwpck_require__(5252); -const resolver_ip = __nccwpck_require__(97902); -const load_balancer_pick_first = __nccwpck_require__(38977); -const load_balancer_round_robin = __nccwpck_require__(92787); -const load_balancer_outlier_detection = __nccwpck_require__(76828); -const load_balancer_weighted_round_robin = __nccwpck_require__(69544); -const channelz = __nccwpck_require__(79975); -(() => { - resolver_dns.setup(); - resolver_uds.setup(); - resolver_ip.setup(); - load_balancer_pick_first.setup(); - load_balancer_round_robin.setup(); - load_balancer_outlier_detection.setup(); - load_balancer_weighted_round_robin.setup(); - channelz.setup(); -})(); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 69672: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InternalChannel = exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0; -const channel_credentials_1 = __nccwpck_require__(44030); -const resolving_load_balancer_1 = __nccwpck_require__(19192); -const subchannel_pool_1 = __nccwpck_require__(87440); -const picker_1 = __nccwpck_require__(81611); -const metadata_1 = __nccwpck_require__(83665); -const constants_1 = __nccwpck_require__(90634); -const filter_stack_1 = __nccwpck_require__(66450); -const compression_filter_1 = __nccwpck_require__(47616); -const resolver_1 = __nccwpck_require__(31594); -const logging_1 = __nccwpck_require__(35993); -const http_proxy_1 = __nccwpck_require__(24000); -const uri_parser_1 = __nccwpck_require__(65974); -const connectivity_state_1 = __nccwpck_require__(80878); -const channelz_1 = __nccwpck_require__(79975); -const load_balancing_call_1 = __nccwpck_require__(776); -const deadline_1 = __nccwpck_require__(511); -const resolving_call_1 = __nccwpck_require__(39909); -const call_number_1 = __nccwpck_require__(70380); -const control_plane_status_1 = __nccwpck_require__(39129); -const retrying_call_1 = __nccwpck_require__(48159); -const subchannel_interface_1 = __nccwpck_require__(12258); -/** - * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args - */ -const MAX_TIMEOUT_TIME = 2147483647; -const MIN_IDLE_TIMEOUT_MS = 1000; -// 30 minutes -const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; -const RETRY_THROTTLER_MAP = new Map(); -const DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; // 16 MB -const DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; // 1 MB -class ChannelSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, channel) { - super(childSubchannel); - this.channel = channel; - this.refCount = 0; - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { - channel.throttleKeepalive(keepaliveTime); - }; - } - ref() { - if (this.refCount === 0) { - this.child.addConnectivityStateListener(this.subchannelStateListener); - this.channel.addWrappedSubchannel(this); - } - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - this.child.removeConnectivityStateListener(this.subchannelStateListener); - this.channel.removeWrappedSubchannel(this); - } - } -} -class ShutdownPicker { - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.DROP, - status: { - code: constants_1.Status.UNAVAILABLE, - details: 'Channel closed before call started', - metadata: new metadata_1.Metadata() - }, - subchannel: null, - onCallStarted: null, - onCallEnded: null - }; - } -} -exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = 'grpc.internal.no_subchannel'; -class ChannelzInfoTracker { - constructor(target) { - this.target = target; - this.trace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.state = connectivity_state_1.ConnectivityState.IDLE; - } - getChannelzInfoCallback() { - return () => { - return { - target: this.target, - state: this.state, - trace: this.trace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }; - }; - } -} -class InternalChannel { - constructor(target, credentials, options) { - var _a, _b, _c, _d, _e, _f; - this.credentials = credentials; - this.options = options; - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - this.currentPicker = new picker_1.UnavailablePicker(); - /** - * Calls queued up to get a call config. Should only be populated before the - * first time the resolver returns a result, which includes the ConfigSelector. - */ - this.configSelectionQueue = []; - this.pickQueue = []; - this.connectivityStateWatchers = []; - /** - * This timer does not do anything on its own. Its purpose is to hold the - * event loop open while there are any pending calls for the channel that - * have not yet been assigned to specific subchannels. In other words, - * the invariant is that callRefTimer is reffed if and only if pickQueue - * is non-empty. In addition, the timer is null while the state is IDLE or - * SHUTDOWN and there are no pending calls. - */ - this.callRefTimer = null; - this.configSelector = null; - /** - * This is the error from the name resolver if it failed most recently. It - * is only used to end calls that start while there is no config selector - * and the name resolver is in backoff, so it should be nulled if - * configSelector becomes set or the channel state becomes anything other - * than TRANSIENT_FAILURE. - */ - this.currentResolutionError = null; - this.wrappedSubchannels = new Set(); - this.callCount = 0; - this.idleTimer = null; - // Channelz info - this.channelzEnabled = true; - /** - * Randomly generated ID to be passed to the config selector, for use by - * ring_hash in xDS. An integer distributed approximately uniformly between - * 0 and MAX_SAFE_INTEGER. - */ - this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); - if (typeof target !== 'string') { - throw new TypeError('Channel target must be a string'); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError('Channel credentials must be a ChannelCredentials object'); - } - if (options) { - if (typeof options !== 'object') { - throw new TypeError('Channel options must be an object'); - } - } - this.channelzInfoTracker = new ChannelzInfoTracker(target); - const originalTargetUri = (0, uri_parser_1.parseUri)(target); - if (originalTargetUri === null) { - throw new Error(`Could not parse target name "${target}"`); - } - /* This ensures that the target has a scheme that is registered with the - * resolver */ - const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); - if (defaultSchemeMapResult === null) { - throw new Error(`Could not find a default scheme for target name "${target}"`); - } - if (this.options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - } - this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Channel created'); - } - if (this.options['grpc.default_authority']) { - this.defaultAuthority = this.options['grpc.default_authority']; - } - else { - this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); - } - const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); - this.target = proxyMapResult.target; - this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); - /* The global boolean parameter to getSubchannelPool has the inverse meaning to what - * the grpc.use_local_subchannel_pool channel option means. */ - this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options['grpc.use_local_subchannel_pool']) !== null && _a !== void 0 ? _a : 0) === 0); - this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options['grpc.retry_buffer_size']) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options['grpc.per_rpc_retry_buffer_size']) !== null && _c !== void 0 ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); - this.keepaliveTime = (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : -1; - this.idleTimeoutMs = Math.max((_e = this.options['grpc.client_idle_timeout_ms']) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); - const channelControlHelper = { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const finalSubchannelArgs = {}; - for (const [key, value] of Object.entries(subchannelArgs)) { - if (!key.startsWith(exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { - finalSubchannelArgs[key] = value; - } - } - const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials); - subchannel.throttleKeepalive(this.keepaliveTime); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Created subchannel or used existing subchannel', subchannel.getChannelzRef()); - } - const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); - return wrappedSubchannel; - }, - updateState: (connectivityState, picker) => { - this.currentPicker = picker; - const queueCopy = this.pickQueue.slice(); - this.pickQueue = []; - if (queueCopy.length > 0) { - this.callRefTimerUnref(); - } - for (const call of queueCopy) { - call.doPick(); - } - this.updateState(connectivityState); - }, - requestReresolution: () => { - // This should never be called. - throw new Error('Resolving load balancer should never call requestReresolution'); - }, - addChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.refChild(child); - } - }, - removeChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.unrefChild(child); - } - }, - }; - this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => { - var _a; - if (serviceConfig.retryThrottling) { - RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); - } - else { - RETRY_THROTTLER_MAP.delete(this.getTarget()); - } - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Address resolution succeeded'); - } - (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); - this.configSelector = configSelector; - this.currentResolutionError = null; - /* We process the queue asynchronously to ensure that the corresponding - * load balancer update has completed. */ - process.nextTick(() => { - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.getConfig(); - } - }); - }, status => { - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_WARNING', 'Address resolution failed with code ' + - status.code + - ' and details "' + - status.details + - '"'); - } - if (this.configSelectionQueue.length > 0) { - this.trace('Name resolution failed with calls queued for config selection'); - } - if (this.configSelector === null) { - this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); - } - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.reportResolverError(status); - } - }); - this.filterStackFactory = new filter_stack_1.FilterStackFactory([ - new compression_filter_1.CompressionFilterFactory(this, this.options), - ]); - this.trace('Channel constructed with options ' + - JSON.stringify(options, undefined, 2)); - const error = new Error(); - if ((0, logging_1.isTracerEnabled)('channel_stacktrace')) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'channel_stacktrace', '(' + - this.channelzRef.id + - ') ' + - 'Channel constructed \n' + - ((_f = error.stack) === null || _f === void 0 ? void 0 : _f.substring(error.stack.indexOf('\n') + 1))); - } - this.lastActivityTimestamp = new Date(); - } - trace(text, verbosityOverride) { - (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, 'channel', '(' + this.channelzRef.id + ') ' + (0, uri_parser_1.uriToString)(this.target) + ' ' + text); - } - callRefTimerRef() { - var _a, _b, _c, _d; - if (!this.callRefTimer) { - this.callRefTimer = setInterval(() => { }, MAX_TIMEOUT_TIME); - } - // If the hasRef function does not exist, always run the code - if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { - this.trace('callRefTimer.ref | configSelectionQueue.length=' + - this.configSelectionQueue.length + - ' pickQueue.length=' + - this.pickQueue.length); - (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); - } - } - callRefTimerUnref() { - var _a, _b, _c; - // If the timer or the hasRef function does not exist, always run the code - if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { - this.trace('callRefTimer.unref | configSelectionQueue.length=' + - this.configSelectionQueue.length + - ' pickQueue.length=' + - this.pickQueue.length); - (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - } - removeConnectivityStateWatcher(watcherObject) { - const watcherIndex = this.connectivityStateWatchers.findIndex(value => value === watcherObject); - if (watcherIndex >= 0) { - this.connectivityStateWatchers.splice(watcherIndex, 1); - } - } - updateState(newState) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'connectivity_state', '(' + - this.channelzRef.id + - ') ' + - (0, uri_parser_1.uriToString)(this.target) + - ' ' + - connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); - } - this.connectivityState = newState; - this.channelzInfoTracker.state = newState; - const watchersCopy = this.connectivityStateWatchers.slice(); - for (const watcherObject of watchersCopy) { - if (newState !== watcherObject.currentState) { - if (watcherObject.timer) { - clearTimeout(watcherObject.timer); - } - this.removeConnectivityStateWatcher(watcherObject); - watcherObject.callback(); - } - } - if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.currentResolutionError = null; - } - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - for (const wrappedSubchannel of this.wrappedSubchannels) { - wrappedSubchannel.throttleKeepalive(newKeepaliveTime); - } - } - } - addWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.add(wrappedSubchannel); - } - removeWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.delete(wrappedSubchannel); - } - doPick(metadata, extraPickInfo) { - return this.currentPicker.pick({ - metadata: metadata, - extraPickInfo: extraPickInfo, - }); - } - queueCallForPick(call) { - this.pickQueue.push(call); - this.callRefTimerRef(); - } - getConfig(method, metadata) { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { - this.resolvingLoadBalancer.exitIdle(); - } - if (this.configSelector) { - return { - type: 'SUCCESS', - config: this.configSelector.invoke(method, metadata, this.randomChannelId), - }; - } - else { - if (this.currentResolutionError) { - return { - type: 'ERROR', - error: this.currentResolutionError, - }; - } - else { - return { - type: 'NONE', - }; - } - } - } - queueCallForConfig(call) { - this.configSelectionQueue.push(call); - this.callRefTimerRef(); - } - enterIdle() { - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.IDLE); - this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); - if (this.idleTimer) { - clearTimeout(this.idleTimer); - this.idleTimer = null; - } - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - this.callRefTimer = null; - } - } - startIdleTimeout(timeoutMs) { - var _a, _b; - this.idleTimer = setTimeout(() => { - if (this.callCount > 0) { - /* If there is currently a call, the channel will not go idle for a - * period of at least idleTimeoutMs, so check again after that time. - */ - this.startIdleTimeout(this.idleTimeoutMs); - return; - } - const now = new Date(); - const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); - if (timeSinceLastActivity >= this.idleTimeoutMs) { - this.trace('Idle timer triggered after ' + - this.idleTimeoutMs + - 'ms of inactivity'); - this.enterIdle(); - } - else { - /* Whenever the timer fires with the latest activity being too recent, - * set the timer again for the time when the time since the last - * activity is equal to the timeout. This should result in the timer - * firing no more than once every idleTimeoutMs/2 on average. */ - this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); - } - }, timeoutMs); - (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - maybeStartIdleTimer() { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && - !this.idleTimer) { - this.startIdleTimeout(this.idleTimeoutMs); - } - } - onCallStart() { - if (this.channelzEnabled) { - this.channelzInfoTracker.callTracker.addCallStarted(); - } - this.callCount += 1; - } - onCallEnd(status) { - if (this.channelzEnabled) { - if (status.code === constants_1.Status.OK) { - this.channelzInfoTracker.callTracker.addCallSucceeded(); - } - else { - this.channelzInfoTracker.callTracker.addCallFailed(); - } - } - this.callCount -= 1; - this.lastActivityTimestamp = new Date(); - this.maybeStartIdleTimer(); - } - createLoadBalancingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createLoadBalancingCall [' + callNumber + '] method="' + method + '"'); - return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); - } - createRetryingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createRetryingCall [' + callNumber + '] method="' + method + '"'); - return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); - } - createResolvingCall(method, deadline, host, parentCall, propagateFlags) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createResolvingCall [' + - callNumber + - '] method="' + - method + - '", deadline=' + - (0, deadline_1.deadlineToString)(deadline)); - const finalOptions = { - deadline: deadline, - flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, - host: host !== null && host !== void 0 ? host : this.defaultAuthority, - parentCall: parentCall, - }; - const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber); - this.onCallStart(); - call.addStatusWatcher(status => { - this.onCallEnd(status); - }); - return call; - } - close() { - var _a; - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); - this.currentPicker = new ShutdownPicker(); - for (const call of this.configSelectionQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); - } - this.configSelectionQueue = []; - for (const call of this.pickQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); - } - this.pickQueue = []; - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - } - if (this.idleTimer) { - clearTimeout(this.idleTimer); - } - if (this.channelzEnabled) { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - this.subchannelPool.unrefUnusedSubchannels(); - (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); - this.configSelector = null; - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - const connectivityState = this.connectivityState; - if (tryToConnect) { - this.resolvingLoadBalancer.exitIdle(); - this.lastActivityTimestamp = new Date(); - this.maybeStartIdleTimer(); - } - return connectivityState; - } - watchConnectivityState(currentState, deadline, callback) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error('Channel has been shut down'); - } - let timer = null; - if (deadline !== Infinity) { - const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); - const now = new Date(); - if (deadline === -Infinity || deadlineDate <= now) { - process.nextTick(callback, new Error('Deadline passed without connectivity state change')); - return; - } - timer = setTimeout(() => { - this.removeConnectivityStateWatcher(watcherObject); - callback(new Error('Deadline passed without connectivity state change')); - }, deadlineDate.getTime() - now.getTime()); - } - const watcherObject = { - currentState, - callback, - timer, - }; - this.connectivityStateWatchers.push(watcherObject); - } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== 'string') { - throw new TypeError('Channel#createCall: method must be a string'); - } - if (!(typeof deadline === 'number' || deadline instanceof Date)) { - throw new TypeError('Channel#createCall: deadline must be a number or Date'); - } - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error('Channel has been shut down'); - } - return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); - } - getOptions() { - return this.options; - } -} -exports.InternalChannel = InternalChannel; -//# sourceMappingURL=internal-channel.js.map - -/***/ }), - -/***/ 17559: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2020 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChildLoadBalancerHandler = void 0; -const load_balancer_1 = __nccwpck_require__(52680); -const connectivity_state_1 = __nccwpck_require__(80878); -const TYPE_NAME = 'child_load_balancer_helper'; -class ChildLoadBalancerHandler { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.currentChild = null; - this.pendingChild = null; - this.latestConfig = null; - this.ChildPolicyHelper = class { - constructor(parent) { - this.parent = parent; - this.child = null; - } - createSubchannel(subchannelAddress, subchannelArgs) { - return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - } - updateState(connectivityState, picker, errorMessage) { - var _a; - if (this.calledByPendingChild()) { - if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { - return; - } - (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy(); - this.parent.currentChild = this.parent.pendingChild; - this.parent.pendingChild = null; - } - else if (!this.calledByCurrentChild()) { - return; - } - this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - requestReresolution() { - var _a; - const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild; - if (this.child === latestChild) { - this.parent.channelControlHelper.requestReresolution(); - } - } - setChild(newChild) { - this.child = newChild; - } - addChannelzChild(child) { - this.parent.channelControlHelper.addChannelzChild(child); - } - removeChannelzChild(child) { - this.parent.channelControlHelper.removeChannelzChild(child); - } - calledByPendingChild() { - return this.child === this.parent.pendingChild; - } - calledByCurrentChild() { - return this.child === this.parent.currentChild; - } - }; - } - configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { - return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); - } - /** - * Prerequisites: lbConfig !== null and lbConfig.name is registered - * @param endpointList - * @param lbConfig - * @param attributes - */ - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - let childToUpdate; - if (this.currentChild === null || - this.latestConfig === null || - this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { - const newHelper = new this.ChildPolicyHelper(this); - const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper); - newHelper.setChild(newChild); - if (this.currentChild === null) { - this.currentChild = newChild; - childToUpdate = this.currentChild; - } - else { - if (this.pendingChild) { - this.pendingChild.destroy(); - } - this.pendingChild = newChild; - childToUpdate = this.pendingChild; - } - } - else { - if (this.pendingChild === null) { - childToUpdate = this.currentChild; - } - else { - childToUpdate = this.pendingChild; - } - } - this.latestConfig = lbConfig; - return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); - } - exitIdle() { - if (this.currentChild) { - this.currentChild.exitIdle(); - if (this.pendingChild) { - this.pendingChild.exitIdle(); - } - } - } - resetBackoff() { - if (this.currentChild) { - this.currentChild.resetBackoff(); - if (this.pendingChild) { - this.pendingChild.resetBackoff(); - } - } - } - destroy() { - /* Note: state updates are only propagated from the child balancer if that - * object is equal to this.currentChild or this.pendingChild. Since this - * function sets both of those to null, no further state updates will - * occur after this function returns. */ - if (this.currentChild) { - this.currentChild.destroy(); - this.currentChild = null; - } - if (this.pendingChild) { - this.pendingChild.destroy(); - this.pendingChild = null; - } - } - getTypeName() { - return TYPE_NAME; - } -} -exports.ChildLoadBalancerHandler = ChildLoadBalancerHandler; -//# sourceMappingURL=load-balancer-child-handler.js.map - -/***/ }), - -/***/ 76828: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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 _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OutlierDetectionLoadBalancer = exports.OutlierDetectionLoadBalancingConfig = void 0; -exports.setup = setup; -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const duration_1 = __nccwpck_require__(62668); -const experimental_1 = __nccwpck_require__(37626); -const load_balancer_1 = __nccwpck_require__(52680); -const load_balancer_child_handler_1 = __nccwpck_require__(17559); -const picker_1 = __nccwpck_require__(81611); -const subchannel_address_1 = __nccwpck_require__(99905); -const subchannel_interface_1 = __nccwpck_require__(12258); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'outlier_detection'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'outlier_detection'; -const OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : 'true') === 'true'; -const defaultSuccessRateEjectionConfig = { - stdev_factor: 1900, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 100, -}; -const defaultFailurePercentageEjectionConfig = { - threshold: 85, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 50, -}; -function validateFieldType(obj, fieldName, expectedType, objectName) { - if (fieldName in obj && - obj[fieldName] !== undefined && - typeof obj[fieldName] !== expectedType) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } -} -function validatePositiveDuration(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - if (fieldName in obj && obj[fieldName] !== undefined) { - if (!(0, duration_1.isDuration)(obj[fieldName])) { - throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); - } - if (!(obj[fieldName].seconds >= 0 && - obj[fieldName].seconds <= 315576000000 && - obj[fieldName].nanos >= 0 && - obj[fieldName].nanos <= 999999999)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); - } - } -} -function validatePercentage(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - validateFieldType(obj, fieldName, 'number', objectName); - if (fieldName in obj && - obj[fieldName] !== undefined && - !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); - } -} -class OutlierDetectionLoadBalancingConfig { - constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { - this.childPolicy = childPolicy; - if (childPolicy.getLoadBalancerName() === 'pick_first') { - throw new Error('outlier_detection LB policy cannot have a pick_first child policy'); - } - this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 10000; - this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 30000; - this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 300000; - this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10; - this.successRateEjection = successRateEjection - ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; - this.failurePercentageEjection = failurePercentageEjection - ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - var _a, _b; - return { - outlier_detection: { - interval: (0, duration_1.msToDuration)(this.intervalMs), - base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), - max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), - max_ejection_percent: this.maxEjectionPercent, - success_rate_ejection: (_a = this.successRateEjection) !== null && _a !== void 0 ? _a : undefined, - failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : undefined, - child_policy: [this.childPolicy.toJsonObject()], - }, - }; - } - getIntervalMs() { - return this.intervalMs; - } - getBaseEjectionTimeMs() { - return this.baseEjectionTimeMs; - } - getMaxEjectionTimeMs() { - return this.maxEjectionTimeMs; - } - getMaxEjectionPercent() { - return this.maxEjectionPercent; - } - getSuccessRateEjectionConfig() { - return this.successRateEjection; - } - getFailurePercentageEjectionConfig() { - return this.failurePercentageEjection; - } - getChildPolicy() { - return this.childPolicy; - } - static createFromJson(obj) { - var _a; - validatePositiveDuration(obj, 'interval'); - validatePositiveDuration(obj, 'base_ejection_time'); - validatePositiveDuration(obj, 'max_ejection_time'); - validatePercentage(obj, 'max_ejection_percent'); - if ('success_rate_ejection' in obj && - obj.success_rate_ejection !== undefined) { - if (typeof obj.success_rate_ejection !== 'object') { - throw new Error('outlier detection config success_rate_ejection must be an object'); - } - validateFieldType(obj.success_rate_ejection, 'stdev_factor', 'number', 'success_rate_ejection'); - validatePercentage(obj.success_rate_ejection, 'enforcement_percentage', 'success_rate_ejection'); - validateFieldType(obj.success_rate_ejection, 'minimum_hosts', 'number', 'success_rate_ejection'); - validateFieldType(obj.success_rate_ejection, 'request_volume', 'number', 'success_rate_ejection'); - } - if ('failure_percentage_ejection' in obj && - obj.failure_percentage_ejection !== undefined) { - if (typeof obj.failure_percentage_ejection !== 'object') { - throw new Error('outlier detection config failure_percentage_ejection must be an object'); - } - validatePercentage(obj.failure_percentage_ejection, 'threshold', 'failure_percentage_ejection'); - validatePercentage(obj.failure_percentage_ejection, 'enforcement_percentage', 'failure_percentage_ejection'); - validateFieldType(obj.failure_percentage_ejection, 'minimum_hosts', 'number', 'failure_percentage_ejection'); - validateFieldType(obj.failure_percentage_ejection, 'request_volume', 'number', 'failure_percentage_ejection'); - } - if (!('child_policy' in obj) || !Array.isArray(obj.child_policy)) { - throw new Error('outlier detection config child_policy must be an array'); - } - const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); - if (!childPolicy) { - throw new Error('outlier detection config child_policy: no valid recognized policy found'); - } - return new OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a = obj.max_ejection_percent) !== null && _a !== void 0 ? _a : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); - } -} -exports.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; -class OutlierDetectionSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, mapEntry) { - super(childSubchannel); - this.mapEntry = mapEntry; - this.refCount = 0; - } - ref() { - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - if (this.mapEntry) { - const index = this.mapEntry.subchannelWrappers.indexOf(this); - if (index >= 0) { - this.mapEntry.subchannelWrappers.splice(index, 1); - } - } - } - } - eject() { - this.setHealthy(false); - } - uneject() { - this.setHealthy(true); - } - getMapEntry() { - return this.mapEntry; - } - getWrappedSubchannel() { - return this.child; - } -} -function createEmptyBucket() { - return { - success: 0, - failure: 0, - }; -} -class CallCounter { - constructor() { - this.activeBucket = createEmptyBucket(); - this.inactiveBucket = createEmptyBucket(); - } - addSuccess() { - this.activeBucket.success += 1; - } - addFailure() { - this.activeBucket.failure += 1; - } - switchBuckets() { - this.inactiveBucket = this.activeBucket; - this.activeBucket = createEmptyBucket(); - } - getLastSuccesses() { - return this.inactiveBucket.success; - } - getLastFailures() { - return this.inactiveBucket.failure; - } -} -class OutlierDetectionPicker { - constructor(wrappedPicker, countCalls) { - this.wrappedPicker = wrappedPicker; - this.countCalls = countCalls; - } - pick(pickArgs) { - const wrappedPick = this.wrappedPicker.pick(pickArgs); - if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { - const subchannelWrapper = wrappedPick.subchannel; - const mapEntry = subchannelWrapper.getMapEntry(); - if (mapEntry) { - let onCallEnded = wrappedPick.onCallEnded; - if (this.countCalls) { - onCallEnded = (statusCode, details, metadata) => { - var _a; - if (statusCode === constants_1.Status.OK) { - mapEntry.counter.addSuccess(); - } - else { - mapEntry.counter.addFailure(); - } - (_a = wrappedPick.onCallEnded) === null || _a === void 0 ? void 0 : _a.call(wrappedPick, statusCode, details, metadata); - }; - } - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded: onCallEnded }); - } - else { - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } - else { - return wrappedPick; - } - } -} -class OutlierDetectionLoadBalancer { - constructor(channelControlHelper) { - this.entryMap = new subchannel_address_1.EndpointMap(); - this.latestConfig = null; - this.timerStartTime = null; - this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); - const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); - if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) { - // If the address is ejected, propagate that to the new subchannel wrapper - subchannelWrapper.eject(); - } - mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper); - return subchannelWrapper; - }, - updateState: (connectivityState, picker, errorMessage) => { - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage); - } - else { - channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - }, - })); - this.ejectionTimer = setInterval(() => { }, 0); - clearInterval(this.ejectionTimer); - } - isCountingEnabled() { - return (this.latestConfig !== null && - (this.latestConfig.getSuccessRateEjectionConfig() !== null || - this.latestConfig.getFailurePercentageEjectionConfig() !== null)); - } - getCurrentEjectionPercent() { - let ejectionCount = 0; - for (const mapEntry of this.entryMap.values()) { - if (mapEntry.currentEjectionTimestamp !== null) { - ejectionCount += 1; - } - } - return (ejectionCount * 100) / this.entryMap.size; - } - runSuccessRateCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); - if (!successRateConfig) { - return; - } - trace('Running success rate check'); - // Step 1 - const targetRequestVolume = successRateConfig.request_volume; - let addresesWithTargetVolume = 0; - const successRates = []; - for (const [endpoint, mapEntry] of this.entryMap.entries()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace('Stats for ' + - (0, subchannel_address_1.endpointToString)(endpoint) + - ': successes=' + - successes + - ' failures=' + - failures + - ' targetRequestVolume=' + - targetRequestVolume); - if (successes + failures >= targetRequestVolume) { - addresesWithTargetVolume += 1; - successRates.push(successes / (successes + failures)); - } - } - trace('Found ' + - addresesWithTargetVolume + - ' success rate candidates; currentEjectionPercent=' + - this.getCurrentEjectionPercent() + - ' successRates=[' + - successRates + - ']'); - if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { - return; - } - // Step 2 - const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; - let successRateDeviationSum = 0; - for (const rate of successRates) { - const deviation = rate - successRateMean; - successRateDeviationSum += deviation * deviation; - } - const successRateVariance = successRateDeviationSum / successRates.length; - const successRateStdev = Math.sqrt(successRateVariance); - const ejectionThreshold = successRateMean - - successRateStdev * (successRateConfig.stdev_factor / 1000); - trace('stdev=' + successRateStdev + ' ejectionThreshold=' + ejectionThreshold); - // Step 3 - for (const [address, mapEntry] of this.entryMap.entries()) { - // Step 3.i - if (this.getCurrentEjectionPercent() >= - this.latestConfig.getMaxEjectionPercent()) { - break; - } - // Step 3.ii - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures < targetRequestVolume) { - continue; - } - // Step 3.iii - const successRate = successes / (successes + failures); - trace('Checking candidate ' + address + ' successRate=' + successRate); - if (successRate < ejectionThreshold) { - const randomNumber = Math.random() * 100; - trace('Candidate ' + - address + - ' randomNumber=' + - randomNumber + - ' enforcement_percentage=' + - successRateConfig.enforcement_percentage); - if (randomNumber < successRateConfig.enforcement_percentage) { - trace('Ejecting candidate ' + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - runFailurePercentageCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); - if (!failurePercentageConfig) { - return; - } - trace('Running failure percentage check. threshold=' + - failurePercentageConfig.threshold + - ' request volume threshold=' + - failurePercentageConfig.request_volume); - // Step 1 - let addressesWithTargetVolume = 0; - for (const mapEntry of this.entryMap.values()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures >= failurePercentageConfig.request_volume) { - addressesWithTargetVolume += 1; - } - } - if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { - return; - } - // Step 2 - for (const [address, mapEntry] of this.entryMap.entries()) { - // Step 2.i - if (this.getCurrentEjectionPercent() >= - this.latestConfig.getMaxEjectionPercent()) { - break; - } - // Step 2.ii - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace('Candidate successes=' + successes + ' failures=' + failures); - if (successes + failures < failurePercentageConfig.request_volume) { - continue; - } - // Step 2.iii - const failurePercentage = (failures * 100) / (failures + successes); - if (failurePercentage > failurePercentageConfig.threshold) { - const randomNumber = Math.random() * 100; - trace('Candidate ' + - address + - ' randomNumber=' + - randomNumber + - ' enforcement_percentage=' + - failurePercentageConfig.enforcement_percentage); - if (randomNumber < failurePercentageConfig.enforcement_percentage) { - trace('Ejecting candidate ' + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - eject(mapEntry, ejectionTimestamp) { - mapEntry.currentEjectionTimestamp = new Date(); - mapEntry.ejectionTimeMultiplier += 1; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.eject(); - } - } - uneject(mapEntry) { - mapEntry.currentEjectionTimestamp = null; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.uneject(); - } - } - switchAllBuckets() { - for (const mapEntry of this.entryMap.values()) { - mapEntry.counter.switchBuckets(); - } - } - startTimer(delayMs) { - var _a, _b; - this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); - (_b = (_a = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - runChecks() { - const ejectionTimestamp = new Date(); - trace('Ejection timer running'); - this.switchAllBuckets(); - if (!this.latestConfig) { - return; - } - this.timerStartTime = ejectionTimestamp; - this.startTimer(this.latestConfig.getIntervalMs()); - this.runSuccessRateCheck(ejectionTimestamp); - this.runFailurePercentageCheck(ejectionTimestamp); - for (const [address, mapEntry] of this.entryMap.entries()) { - if (mapEntry.currentEjectionTimestamp === null) { - if (mapEntry.ejectionTimeMultiplier > 0) { - mapEntry.ejectionTimeMultiplier -= 1; - } - } - else { - const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); - const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); - const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); - returnTime.setMilliseconds(returnTime.getMilliseconds() + - Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); - if (returnTime < new Date()) { - trace('Unejecting ' + address); - this.uneject(mapEntry); - } - } - } - } - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { - return false; - } - trace('Received update with config: ' + JSON.stringify(lbConfig.toJsonObject(), undefined, 2)); - if (endpointList.ok) { - for (const endpoint of endpointList.value) { - if (!this.entryMap.has(endpoint)) { - trace('Adding map entry for ' + (0, subchannel_address_1.endpointToString)(endpoint)); - this.entryMap.set(endpoint, { - counter: new CallCounter(), - currentEjectionTimestamp: null, - ejectionTimeMultiplier: 0, - subchannelWrappers: [], - }); - } - } - this.entryMap.deleteMissing(endpointList.value); - } - const childPolicy = lbConfig.getChildPolicy(); - this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); - if (lbConfig.getSuccessRateEjectionConfig() || - lbConfig.getFailurePercentageEjectionConfig()) { - if (this.timerStartTime) { - trace('Previous timer existed. Replacing timer'); - clearTimeout(this.ejectionTimer); - const remainingDelay = lbConfig.getIntervalMs() - - (new Date().getTime() - this.timerStartTime.getTime()); - this.startTimer(remainingDelay); - } - else { - trace('Starting new timer'); - this.timerStartTime = new Date(); - this.startTimer(lbConfig.getIntervalMs()); - this.switchAllBuckets(); - } - } - else { - trace('Counting disabled. Cancelling timer.'); - this.timerStartTime = null; - clearTimeout(this.ejectionTimer); - for (const mapEntry of this.entryMap.values()) { - this.uneject(mapEntry); - mapEntry.ejectionTimeMultiplier = 0; - } - } - this.latestConfig = lbConfig; - return true; - } - exitIdle() { - this.childBalancer.exitIdle(); - } - resetBackoff() { - this.childBalancer.resetBackoff(); - } - destroy() { - clearTimeout(this.ejectionTimer); - this.childBalancer.destroy(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; -function setup() { - if (OUTLIER_DETECTION_ENABLED) { - (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); - } -} -//# sourceMappingURL=load-balancer-outlier-detection.js.map - -/***/ }), - -/***/ 38977: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LeafLoadBalancer = exports.PickFirstLoadBalancer = exports.PickFirstLoadBalancingConfig = void 0; -exports.shuffled = shuffled; -exports.setup = setup; -const load_balancer_1 = __nccwpck_require__(52680); -const connectivity_state_1 = __nccwpck_require__(80878); -const picker_1 = __nccwpck_require__(81611); -const subchannel_address_1 = __nccwpck_require__(99905); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const subchannel_address_2 = __nccwpck_require__(99905); -const net_1 = __nccwpck_require__(41808); -const call_interface_1 = __nccwpck_require__(78710); -const TRACER_NAME = 'pick_first'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'pick_first'; -/** - * Delay after starting a connection on a subchannel before starting a - * connection on the next subchannel in the list, for Happy Eyeballs algorithm. - */ -const CONNECTION_DELAY_INTERVAL_MS = 250; -class PickFirstLoadBalancingConfig { - constructor(shuffleAddressList) { - this.shuffleAddressList = shuffleAddressList; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - [TYPE_NAME]: { - shuffleAddressList: this.shuffleAddressList, - }, - }; - } - getShuffleAddressList() { - return this.shuffleAddressList; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - if ('shuffleAddressList' in obj && - !(typeof obj.shuffleAddressList === 'boolean')) { - throw new Error('pick_first config field shuffleAddressList must be a boolean if provided'); - } - return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); - } -} -exports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; -/** - * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the - * picked subchannel. - */ -class PickFirstPicker { - constructor(subchannel) { - this.subchannel = subchannel; - } - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.COMPLETE, - subchannel: this.subchannel, - status: null, - onCallStarted: null, - onCallEnded: null, - }; - } -} -/** - * Return a new array with the elements of the input array in a random order - * @param list The input array - * @returns A shuffled array of the elements of list - */ -function shuffled(list) { - const result = list.slice(); - for (let i = result.length - 1; i > 1; i--) { - const j = Math.floor(Math.random() * (i + 1)); - const temp = result[i]; - result[i] = result[j]; - result[j] = temp; - } - return result; -} -/** - * Interleave addresses in addressList by family in accordance with RFC-8304 section 4 - * @param addressList - * @returns - */ -function interleaveAddressFamilies(addressList) { - if (addressList.length === 0) { - return []; - } - const result = []; - const ipv6Addresses = []; - const ipv4Addresses = []; - const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); - for (const address of addressList) { - if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { - ipv6Addresses.push(address); - } - else { - ipv4Addresses.push(address); - } - } - const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; - const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; - for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { - if (i < firstList.length) { - result.push(firstList[i]); - } - if (i < secondList.length) { - result.push(secondList[i]); - } - } - return result; -} -const REPORT_HEALTH_STATUS_OPTION_NAME = 'grpc-node.internal.pick-first.report_health_status'; -class PickFirstLoadBalancer { - /** - * Load balancer that attempts to connect to each backend in the address list - * in order, and picks the first one that connects, using it for every - * request. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - */ - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - /** - * The list of subchannels this load balancer is currently attempting to - * connect to. - */ - this.children = []; - /** - * The current connectivity state of the load balancer. - */ - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The index within the `subchannels` array of the subchannel with the most - * recently started connection attempt. - */ - this.currentSubchannelIndex = 0; - /** - * The currently picked subchannel used for making calls. Populated if - * and only if the load balancer's current state is READY. In that case, - * the subchannel's current state is also READY. - */ - this.currentPick = null; - /** - * Listener callback attached to each subchannel in the `subchannels` list - * while establishing a connection. - */ - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { - this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); - }; - this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); - /** - * The LB policy enters sticky TRANSIENT_FAILURE mode when all - * subchannels have failed to connect at least once, and it stays in that - * mode until a connection attempt is successful. While in sticky TF mode, - * the LB policy continuously attempts to connect to all of its subchannels. - */ - this.stickyTransientFailureMode = false; - this.reportHealthStatus = false; - /** - * The most recent error reported by any subchannel as it transitioned to - * TRANSIENT_FAILURE. - */ - this.lastError = null; - this.latestAddressList = null; - this.latestOptions = {}; - this.latestResolutionNote = ''; - this.connectionDelayTimeout = setTimeout(() => { }, 0); - clearTimeout(this.connectionDelayTimeout); - } - allChildrenHaveReportedTF() { - return this.children.every(child => child.hasReportedTransientFailure); - } - resetChildrenReportedTF() { - this.children.every(child => child.hasReportedTransientFailure = false); - } - calculateAndReportNewState() { - var _a; - if (this.currentPick) { - if (this.reportHealthStatus && !this.currentPick.isHealthy()) { - const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null); - } - } - else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - else { - if (this.stickyTransientFailureMode) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - } - } - requestReresolution() { - this.channelControlHelper.requestReresolution(); - } - maybeEnterStickyTransientFailureMode() { - if (!this.allChildrenHaveReportedTF()) { - return; - } - this.requestReresolution(); - this.resetChildrenReportedTF(); - if (this.stickyTransientFailureMode) { - this.calculateAndReportNewState(); - return; - } - this.stickyTransientFailureMode = true; - for (const { subchannel } of this.children) { - subchannel.startConnecting(); - } - this.calculateAndReportNewState(); - } - removeCurrentPick() { - if (this.currentPick !== null) { - this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); - this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()); - this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); - // Unref last, to avoid triggering listeners - this.currentPick.unref(); - this.currentPick = null; - } - } - onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { - var _a; - if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) { - if (newState !== connectivity_state_1.ConnectivityState.READY) { - this.removeCurrentPick(); - this.calculateAndReportNewState(); - } - return; - } - for (const [index, child] of this.children.entries()) { - if (subchannel.realSubchannelEquals(child.subchannel)) { - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(child.subchannel); - } - if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - if (errorMessage) { - this.lastError = errorMessage; - } - this.maybeEnterStickyTransientFailureMode(); - if (index === this.currentSubchannelIndex) { - this.startNextSubchannelConnecting(index + 1); - } - } - child.subchannel.startConnecting(); - return; - } - } - } - startNextSubchannelConnecting(startIndex) { - clearTimeout(this.connectionDelayTimeout); - for (const [index, child] of this.children.entries()) { - if (index >= startIndex) { - const subchannelState = child.subchannel.getConnectivityState(); - if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || - subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { - this.startConnecting(index); - return; - } - } - } - this.maybeEnterStickyTransientFailureMode(); - } - /** - * Have a single subchannel in the `subchannels` list start connecting. - * @param subchannelIndex The index into the `subchannels` list. - */ - startConnecting(subchannelIndex) { - var _a, _b; - clearTimeout(this.connectionDelayTimeout); - this.currentSubchannelIndex = subchannelIndex; - if (this.children[subchannelIndex].subchannel.getConnectivityState() === - connectivity_state_1.ConnectivityState.IDLE) { - trace('Start connecting to subchannel with address ' + - this.children[subchannelIndex].subchannel.getAddress()); - process.nextTick(() => { - var _a; - (_a = this.children[subchannelIndex]) === null || _a === void 0 ? void 0 : _a.subchannel.startConnecting(); - }); - } - this.connectionDelayTimeout = setTimeout(() => { - this.startNextSubchannelConnecting(subchannelIndex + 1); - }, CONNECTION_DELAY_INTERVAL_MS); - (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Declare that the specified subchannel should be used to make requests. - * This functions the same independent of whether subchannel is a member of - * this.children and whether it is equal to this.currentPick. - * Prerequisite: subchannel.getConnectivityState() === READY. - * @param subchannel - */ - pickSubchannel(subchannel) { - trace('Pick subchannel with address ' + subchannel.getAddress()); - this.stickyTransientFailureMode = false; - /* Ref before removeCurrentPick and resetSubchannelList to avoid the - * refcount dropping to 0 during this process. */ - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - this.removeCurrentPick(); - this.resetSubchannelList(); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); - this.currentPick = subchannel; - clearTimeout(this.connectionDelayTimeout); - this.calculateAndReportNewState(); - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - /* Always remoev the connectivity state listener. If the subchannel is - getting picked, it will be re-added then. */ - child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - /* Refs are counted independently for the children list and the - * currentPick, so we call unref whether or not the child is the - * currentPick. Channelz child references are also refcounted, so - * removeChannelzChild can be handled the same way. */ - child.subchannel.unref(); - this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); - } - this.currentSubchannelIndex = 0; - this.children = []; - } - connectToAddressList(addressList, options) { - trace('connectToAddressList([' + addressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); - const newChildrenList = addressList.map(address => ({ - subchannel: this.channelControlHelper.createSubchannel(address, options), - hasReportedTransientFailure: false, - })); - for (const { subchannel } of newChildrenList) { - if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(subchannel); - return; - } - } - /* Ref each subchannel before resetting the list, to ensure that - * subchannels shared between the list don't drop to 0 refs during the - * transition. */ - for (const { subchannel } of newChildrenList) { - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - } - this.resetSubchannelList(); - this.children = newChildrenList; - for (const { subchannel } of this.children) { - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - for (const child of this.children) { - if (child.subchannel.getConnectivityState() === - connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - } - } - this.startNextSubchannelConnecting(0); - this.calculateAndReportNewState(); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0 && this.currentPick === null) { - this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - let endpointList = maybeEndpointList.value; - this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; - /* Previously, an update would be discarded if it was identical to the - * previous update, to minimize churn. Now the DNS resolver is - * rate-limited, so that is less of a concern. */ - if (lbConfig.getShuffleAddressList()) { - endpointList = shuffled(endpointList); - } - const rawAddressList = [].concat(...endpointList.map(endpoint => endpoint.addresses)); - trace('updateAddressList([' + rawAddressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); - const addressList = interleaveAddressFamilies(rawAddressList); - this.latestAddressList = addressList; - this.latestOptions = options; - this.connectToAddressList(addressList, options); - this.latestResolutionNote = resolutionNote; - if (rawAddressList.length > 0) { - return true; - } - else { - this.lastError = 'No addresses resolved'; - return false; - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && - this.latestAddressList) { - this.connectToAddressList(this.latestAddressList, this.latestOptions); - } - } - resetBackoff() { - /* The pick first load balancer does not have a connection backoff, so this - * does nothing */ - } - destroy() { - this.resetSubchannelList(); - this.removeCurrentPick(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.PickFirstLoadBalancer = PickFirstLoadBalancer; -const LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); -/** - * This class handles the leaf load balancing operations for a single endpoint. - * It is a thin wrapper around a PickFirstLoadBalancer with a different API - * that more closely reflects how it will be used as a leaf balancer. - */ -class LeafLoadBalancer { - constructor(endpoint, channelControlHelper, options, resolutionNote) { - this.endpoint = endpoint; - this.options = options; - this.resolutionNote = resolutionNote; - this.latestState = connectivity_state_1.ConnectivityState.IDLE; - const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - this.latestState = connectivityState; - this.latestPicker = picker; - channelControlHelper.updateState(connectivityState, picker, errorMessage); - }, - }); - this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper); - this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); - } - startConnecting() { - this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote); - } - /** - * Update the endpoint associated with this LeafLoadBalancer to a new - * endpoint. Does not trigger connection establishment if a connection - * attempt is not already in progress. - * @param newEndpoint - */ - updateEndpoint(newEndpoint, newOptions) { - this.options = newOptions; - this.endpoint = newEndpoint; - if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { - this.startConnecting(); - } - } - getConnectivityState() { - return this.latestState; - } - getPicker() { - return this.latestPicker; - } - getEndpoint() { - return this.endpoint; - } - exitIdle() { - this.pickFirstBalancer.exitIdle(); - } - destroy() { - this.pickFirstBalancer.destroy(); - } -} -exports.LeafLoadBalancer = LeafLoadBalancer; -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); - (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); -} -//# sourceMappingURL=load-balancer-pick-first.js.map - -/***/ }), - -/***/ 92787: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RoundRobinLoadBalancer = void 0; -exports.setup = setup; -const load_balancer_1 = __nccwpck_require__(52680); -const connectivity_state_1 = __nccwpck_require__(80878); -const picker_1 = __nccwpck_require__(81611); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const subchannel_address_1 = __nccwpck_require__(99905); -const load_balancer_pick_first_1 = __nccwpck_require__(38977); -const TRACER_NAME = 'round_robin'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'round_robin'; -class RoundRobinLoadBalancingConfig { - getLoadBalancerName() { - return TYPE_NAME; - } - constructor() { } - toJsonObject() { - return { - [TYPE_NAME]: {}, - }; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - return new RoundRobinLoadBalancingConfig(); - } -} -class RoundRobinPicker { - constructor(children, nextIndex = 0) { - this.children = children; - this.nextIndex = nextIndex; - } - pick(pickArgs) { - const childPicker = this.children[this.nextIndex].picker; - this.nextIndex = (this.nextIndex + 1) % this.children.length; - return childPicker.pick(pickArgs); - } - /** - * Check what the next subchannel returned would be. Used by the load - * balancer implementation to preserve this part of the picker state if - * possible when a subchannel connects or disconnects. - */ - peekNextEndpoint() { - return this.children[this.nextIndex].endpoint; - } -} -function rotateArray(list, startIndex) { - return [...list.slice(startIndex), ...list.slice(0, startIndex)]; -} -class RoundRobinLoadBalancer { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.children = []; - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.currentReadyPicker = null; - this.updatesPaused = false; - this.lastError = null; - this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - /* Ensure that name resolution is requested again after active - * connections are dropped. This is more aggressive than necessary to - * accomplish that, so we are counting on resolvers to have - * reasonable rate limits. */ - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - }, - }); - } - countChildrenWithState(state) { - return this.children.filter(child => child.getConnectivityState() === state) - .length; - } - calculateAndUpdateState() { - if (this.updatesPaused) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const readyChildren = this.children.filter(child => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); - let index = 0; - if (this.currentReadyPicker !== null) { - const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); - index = readyChildren.findIndex(child => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); - if (index < 0) { - index = 0; - } - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map(child => ({ - endpoint: child.getEndpoint(), - picker: child.getPicker(), - })), index), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - /* round_robin should keep all children connected, this is how we do that. - * We can't do this more efficiently in the individual child's updateState - * callback because that doesn't have a reference to which child the state - * change is associated with. */ - for (const child of this.children) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.currentReadyPicker = picker; - } - else { - this.currentReadyPicker = null; - } - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - child.destroy(); - } - this.children = []; - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - const startIndex = (Math.random() * maybeEndpointList.value.length) | 0; - const endpointList = rotateArray(maybeEndpointList.value, startIndex); - this.resetSubchannelList(); - if (endpointList.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - } - trace('Connect to endpoint list ' + endpointList.map(subchannel_address_1.endpointToString)); - this.updatesPaused = true; - this.children = endpointList.map(endpoint => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, options, resolutionNote)); - for (const child of this.children) { - child.startConnecting(); - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - return true; - } - exitIdle() { - /* The round_robin LB policy is only in the IDLE state if it has no - * addresses to try to connect to and it has no picked subchannel. - * In that case, there is no meaningful action that can be taken here. */ - } - resetBackoff() { - // This LB policy has no backoff to reset - } - destroy() { - this.resetSubchannelList(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer; -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); -} -//# sourceMappingURL=load-balancer-round-robin.js.map - -/***/ }), - -/***/ 69544: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WeightedRoundRobinLoadBalancingConfig = void 0; -exports.setup = setup; -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const duration_1 = __nccwpck_require__(62668); -const load_balancer_1 = __nccwpck_require__(52680); -const load_balancer_pick_first_1 = __nccwpck_require__(38977); -const logging = __nccwpck_require__(35993); -const orca_1 = __nccwpck_require__(31791); -const picker_1 = __nccwpck_require__(81611); -const priority_queue_1 = __nccwpck_require__(38386); -const subchannel_address_1 = __nccwpck_require__(99905); -const TRACER_NAME = 'weighted_round_robin'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'weighted_round_robin'; -const DEFAULT_OOB_REPORTING_PERIOD_MS = 10000; -const DEFAULT_BLACKOUT_PERIOD_MS = 10000; -const DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 60000; -const DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1000; -const DEFAULT_ERROR_UTILIZATION_PENALTY = 1; -function validateFieldType(obj, fieldName, expectedType) { - if (fieldName in obj && - obj[fieldName] !== undefined && - typeof obj[fieldName] !== expectedType) { - throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } -} -function parseDurationField(obj, fieldName) { - if (fieldName in obj && obj[fieldName] !== undefined && obj[fieldName] !== null) { - let durationObject; - if ((0, duration_1.isDuration)(obj[fieldName])) { - durationObject = obj[fieldName]; - } - else if ((0, duration_1.isDurationMessage)(obj[fieldName])) { - durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]); - } - else if (typeof obj[fieldName] === 'string') { - const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]); - if (!parsedDuration) { - throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); - } - durationObject = parsedDuration; - } - else { - throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); - } - return (0, duration_1.durationToMs)(durationObject); - } - return null; -} -class WeightedRoundRobinLoadBalancingConfig { - constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) { - this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== void 0 ? enableOobLoadReport : false; - this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== void 0 ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS; - this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== void 0 ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS; - this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== void 0 ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; - this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== void 0 ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); - this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== void 0 ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - enable_oob_load_report: this.enableOobLoadReport, - oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)), - blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)), - weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)), - weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)), - error_utilization_penalty: this.errorUtilizationPenalty - }; - } - static createFromJson(obj) { - validateFieldType(obj, 'enable_oob_load_report', 'boolean'); - validateFieldType(obj, 'error_utilization_penalty', 'number'); - if (obj.error_utilization_penalty < 0) { - throw new Error('weighted round robin config error_utilization_penalty < 0'); - } - return new WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, 'oob_load_reporting_period'), parseDurationField(obj, 'blackout_period'), parseDurationField(obj, 'weight_expiration_period'), parseDurationField(obj, 'weight_update_period'), obj.error_utilization_penalty); - } - getEnableOobLoadReport() { - return this.enableOobLoadReport; - } - getOobLoadReportingPeriodMs() { - return this.oobLoadReportingPeriodMs; - } - getBlackoutPeriodMs() { - return this.blackoutPeriodMs; - } - getWeightExpirationPeriodMs() { - return this.weightExpirationPeriodMs; - } - getWeightUpdatePeriodMs() { - return this.weightUpdatePeriodMs; - } - getErrorUtilizationPenalty() { - return this.errorUtilizationPenalty; - } -} -exports.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig; -class WeightedRoundRobinPicker { - constructor(children, metricsHandler) { - this.metricsHandler = metricsHandler; - this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline); - const positiveWeight = children.filter(picker => picker.weight > 0); - let averageWeight; - if (positiveWeight.length < 2) { - averageWeight = 1; - } - else { - let weightSum = 0; - for (const { weight } of positiveWeight) { - weightSum += weight; - } - averageWeight = weightSum / positiveWeight.length; - } - for (const child of children) { - const period = child.weight > 0 ? 1 / child.weight : averageWeight; - this.queue.push({ - endpointName: child.endpointName, - picker: child.picker, - period: period, - deadline: Math.random() * period - }); - } - } - pick(pickArgs) { - const entry = this.queue.pop(); - this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period })); - const childPick = entry.picker.pick(pickArgs); - if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) { - if (this.metricsHandler) { - return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)(loadReport => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) }); - } - else { - const subchannelWrapper = childPick.subchannel; - return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } - else { - return childPick; - } - } -} -class WeightedRoundRobinLoadBalancer { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.latestConfig = null; - this.children = new Map(); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.updatesPaused = false; - this.lastError = null; - this.weightUpdateTimer = null; - } - countChildrenWithState(state) { - let count = 0; - for (const entry of this.children.values()) { - if (entry.child.getConnectivityState() === state) { - count += 1; - } - } - return count; - } - updateWeight(entry, loadReport) { - var _a, _b; - const qps = loadReport.rps_fractional; - let utilization = loadReport.application_utilization; - if (utilization > 0 && qps > 0) { - utilization += (loadReport.eps / qps) * ((_b = (_a = this.latestConfig) === null || _a === void 0 ? void 0 : _a.getErrorUtilizationPenalty()) !== null && _b !== void 0 ? _b : 0); - } - const newWeight = utilization === 0 ? 0 : qps / utilization; - if (newWeight === 0) { - return; - } - const now = new Date(); - if (entry.nonEmptySince === null) { - entry.nonEmptySince = now; - } - entry.lastUpdated = now; - entry.weight = newWeight; - } - getWeight(entry) { - if (!this.latestConfig) { - return 0; - } - const now = new Date().getTime(); - if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { - entry.nonEmptySince = null; - return 0; - } - const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); - if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { - return 0; - } - return entry.weight; - } - calculateAndUpdateState() { - if (this.updatesPaused || !this.latestConfig) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const weightedPickers = []; - for (const [endpoint, entry] of this.children) { - if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - continue; - } - weightedPickers.push({ - endpointName: endpoint, - picker: entry.child.getPicker(), - weight: this.getWeight(entry) - }); - } - trace('Created picker with weights: ' + weightedPickers.map(entry => entry.endpointName + ':' + entry.weight).join(',')); - let metricsHandler; - if (!this.latestConfig.getEnableOobLoadReport()) { - metricsHandler = (loadReport, endpointName) => { - const childEntry = this.children.get(endpointName); - if (childEntry) { - this.updateWeight(childEntry, loadReport); - } - }; - } - else { - metricsHandler = null; - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - /* round_robin should keep all children connected, this is how we do that. - * We can't do this more efficiently in the individual child's updateState - * callback because that doesn't have a reference to which child the state - * change is associated with. */ - for (const { child } of this.children.values()) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - var _a, _b; - if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.size === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - if (maybeEndpointList.value.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - return false; - } - trace('Connect to endpoint list ' + maybeEndpointList.value.map(subchannel_address_1.endpointToString)); - const now = new Date(); - const seenEndpointNames = new Set(); - this.updatesPaused = true; - this.latestConfig = lbConfig; - for (const endpoint of maybeEndpointList.value) { - const name = (0, subchannel_address_1.endpointToString)(endpoint); - seenEndpointNames.add(name); - let entry = this.children.get(name); - if (!entry) { - entry = { - child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - /* Ensure that name resolution is requested again after active - * connections are dropped. This is more aggressive than necessary to - * accomplish that, so we are counting on resolvers to have - * reasonable rate limits. */ - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - entry.nonEmptySince = null; - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - }, - createSubchannel: (subchannelAddress, subchannelArgs) => { - const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - if (entry === null || entry === void 0 ? void 0 : entry.oobMetricsListener) { - return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs()); - } - else { - return subchannel; - } - } - }), options, resolutionNote), - lastUpdated: now, - nonEmptySince: null, - weight: 0, - oobMetricsListener: null - }; - this.children.set(name, entry); - } - if (lbConfig.getEnableOobLoadReport()) { - entry.oobMetricsListener = loadReport => { - this.updateWeight(entry, loadReport); - }; - } - else { - entry.oobMetricsListener = null; - } - } - for (const [endpointName, entry] of this.children) { - if (seenEndpointNames.has(endpointName)) { - entry.child.startConnecting(); - } - else { - entry.child.destroy(); - this.children.delete(endpointName); - } - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - this.weightUpdateTimer = (_b = (_a = setInterval(() => { - if (this.currentState === connectivity_state_1.ConnectivityState.READY) { - this.calculateAndUpdateState(); - } - }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - return true; - } - exitIdle() { - /* The weighted_round_robin LB policy is only in the IDLE state if it has - * no addresses to try to connect to and it has no picked subchannel. - * In that case, there is no meaningful action that can be taken here. */ - } - resetBackoff() { - // This LB policy has no backoff to reset - } - destroy() { - for (const entry of this.children.values()) { - entry.child.destroy(); - } - this.children.clear(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - } - getTypeName() { - return TYPE_NAME; - } -} -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig); -} -//# sourceMappingURL=load-balancer-weighted-round-robin.js.map - -/***/ }), - -/***/ 52680: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChildChannelControlHelper = createChildChannelControlHelper; -exports.registerLoadBalancerType = registerLoadBalancerType; -exports.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; -exports.createLoadBalancer = createLoadBalancer; -exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; -exports.parseLoadBalancingConfig = parseLoadBalancingConfig; -exports.getDefaultConfig = getDefaultConfig; -exports.selectLbConfigFromList = selectLbConfigFromList; -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -/** - * Create a child ChannelControlHelper that overrides some methods of the - * parent while letting others pass through to the parent unmodified. This - * allows other code to create these children without needing to know about - * all of the methods to be passed through. - * @param parent - * @param overrides - */ -function createChildChannelControlHelper(parent, overrides) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - return { - createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent), - updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent), - requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent), - addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent), - removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent), - }; -} -const registeredLoadBalancerTypes = {}; -let defaultLoadBalancerType = null; -function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { - registeredLoadBalancerTypes[typeName] = { - LoadBalancer: loadBalancerType, - LoadBalancingConfig: loadBalancingConfigType, - }; -} -function registerDefaultLoadBalancerType(typeName) { - defaultLoadBalancerType = typeName; -} -function createLoadBalancer(config, channelControlHelper) { - const typeName = config.getLoadBalancerName(); - if (typeName in registeredLoadBalancerTypes) { - return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper); - } - else { - return null; - } -} -function isLoadBalancerNameRegistered(typeName) { - return typeName in registeredLoadBalancerTypes; -} -function parseLoadBalancingConfig(rawConfig) { - const keys = Object.keys(rawConfig); - if (keys.length !== 1) { - throw new Error('Provided load balancing config has multiple conflicting entries'); - } - const typeName = keys[0]; - if (typeName in registeredLoadBalancerTypes) { - try { - return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); - } - catch (e) { - throw new Error(`${typeName}: ${e.message}`); - } - } - else { - throw new Error(`Unrecognized load balancing config name ${typeName}`); - } -} -function getDefaultConfig() { - if (!defaultLoadBalancerType) { - throw new Error('No default load balancer type registered'); - } - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); -} -function selectLbConfigFromList(configs, fallbackTodefault = false) { - for (const config of configs) { - try { - return parseLoadBalancingConfig(config); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, 'Config parsing failed with error', e.message); - continue; - } - } - if (fallbackTodefault) { - if (defaultLoadBalancerType) { - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); - } - else { - return null; - } - } - else { - return null; - } -} -//# sourceMappingURL=load-balancer.js.map - -/***/ }), - -/***/ 776: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LoadBalancingCall = void 0; -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const deadline_1 = __nccwpck_require__(511); -const metadata_1 = __nccwpck_require__(83665); -const picker_1 = __nccwpck_require__(81611); -const uri_parser_1 = __nccwpck_require__(65974); -const logging = __nccwpck_require__(35993); -const control_plane_status_1 = __nccwpck_require__(39129); -const http2 = __nccwpck_require__(85158); -const TRACER_NAME = 'load_balancing_call'; -class LoadBalancingCall { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { - var _a, _b; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.metadata = null; - this.listener = null; - this.onCallEnded = null; - this.childStartTime = null; - const splitPath = this.methodName.split('/'); - let serviceName = ''; - /* The standard path format is "/{serviceName}/{methodName}", so if we split - * by '/', the first item should be empty and the second should be the - * service name */ - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; - /* Currently, call credentials are only allowed on HTTPS connections, so we - * can assume that the scheme is "https" */ - this.serviceUrl = `https://${hostname}/${serviceName}`; - this.startTime = new Date(); - } - getDeadlineInfo() { - var _a, _b; - const deadlineInfo = []; - if (this.childStartTime) { - if (this.childStartTime > this.startTime) { - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - deadlineInfo.push('wait_for_ready'); - } - deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); - } - deadlineInfo.push(...this.child.getDeadlineInfo()); - return deadlineInfo; - } - else { - if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) { - deadlineInfo.push('wait_for_ready'); - } - deadlineInfo.push('Waiting for LB pick'); - } - return deadlineInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - outputStatus(status, progress) { - var _a, _b; - if (!this.ended) { - this.ended = true; - this.trace('ended with status: code=' + - status.code + - ' details="' + - status.details + - '" start time=' + - this.startTime.toISOString()); - const finalStatus = Object.assign(Object.assign({}, status), { progress }); - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); - (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); - } - } - doPick() { - var _a, _b; - if (this.ended) { - return; - } - if (!this.metadata) { - throw new Error('doPick called before start'); - } - this.trace('Pick called'); - const finalMetadata = this.metadata.clone(); - const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); - const subchannelString = pickResult.subchannel - ? '(' + - pickResult.subchannel.getChannelzRef().id + - ') ' + - pickResult.subchannel.getAddress() - : '' + pickResult.subchannel; - this.trace('Pick result: ' + - picker_1.PickResultType[pickResult.pickResultType] + - ' subchannel: ' + - subchannelString + - ' status: ' + - ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + - ' ' + - ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); - switch (pickResult.pickResultType) { - case picker_1.PickResultType.COMPLETE: - const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); - combinedCallCredentials - .generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }) - .then(credsMetadata => { - var _a; - /* If this call was cancelled (e.g. by the deadline) before - * metadata generation finished, we shouldn't do anything with - * it. */ - if (this.ended) { - this.trace('Credentials metadata generation finished after call ended'); - return; - } - finalMetadata.merge(credsMetadata); - if (finalMetadata.get('authorization').length > 1) { - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: '"authorization" metadata cannot have multiple values', - metadata: new metadata_1.Metadata(), - }, 'PROCESSED'); - } - if (pickResult.subchannel.getConnectivityState() !== - connectivity_state_1.ConnectivityState.READY) { - this.trace('Picked subchannel ' + - subchannelString + - ' has state ' + - connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + - ' after getting credentials metadata. Retrying pick'); - this.doPick(); - return; - } - if (this.deadline !== Infinity) { - finalMetadata.set('grpc-timeout', (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); - } - try { - this.child = pickResult - .subchannel.getRealSubchannel() - .createCall(finalMetadata, this.host, this.methodName, { - onReceiveMetadata: metadata => { - this.trace('Received metadata'); - this.listener.onReceiveMetadata(metadata); - }, - onReceiveMessage: message => { - this.trace('Received message'); - this.listener.onReceiveMessage(message); - }, - onReceiveStatus: status => { - this.trace('Received status'); - if (status.rstCode === - http2.constants.NGHTTP2_REFUSED_STREAM) { - this.outputStatus(status, 'REFUSED'); - } - else { - this.outputStatus(status, 'PROCESSED'); - } - }, - }); - this.childStartTime = new Date(); - } - catch (error) { - this.trace('Failed to start call on picked subchannel ' + - subchannelString + - ' with error ' + - error.message); - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: 'Failed to start HTTP/2 stream with error ' + - error.message, - metadata: new metadata_1.Metadata(), - }, 'NOT_STARTED'); - return; - } - (_a = pickResult.onCallStarted) === null || _a === void 0 ? void 0 : _a.call(pickResult); - this.onCallEnded = pickResult.onCallEnded; - this.trace('Created child call [' + this.child.getCallNumber() + ']'); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (error) => { - // We assume the error code isn't 0 (Status.OK) - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); - this.outputStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }, 'PROCESSED'); - }); - break; - case picker_1.PickResultType.DROP: - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'DROP'); - }); - break; - case picker_1.PickResultType.TRANSIENT_FAILURE: - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForPick(this); - } - else { - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'PROCESSED'); - }); - } - break; - case picker_1.PickResultType.QUEUE: - this.channel.queueCallForPick(this); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ code: status, details: details, metadata: new metadata_1.Metadata() }, 'PROCESSED'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace('start called'); - this.listener = listener; - this.metadata = metadata; - this.doPick(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - if (this.child) { - this.child.sendMessageWithContext(context, message); - } - else { - this.pendingMessage = { context, message }; - } - } - startRead() { - this.trace('startRead called'); - if (this.child) { - this.child.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - this.trace('halfClose called'); - if (this.child) { - this.child.halfClose(); - } - else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - throw new Error('Method not implemented.'); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } - else { - return null; - } - } -} -exports.LoadBalancingCall = LoadBalancingCall; -//# sourceMappingURL=load-balancing-call.js.map - -/***/ }), - -/***/ 35993: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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 _a, _b, _c, _d; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = void 0; -exports.trace = trace; -exports.isTracerEnabled = isTracerEnabled; -const constants_1 = __nccwpck_require__(90634); -const process_1 = __nccwpck_require__(77282); -const clientVersion = (__nccwpck_require__(56569)/* .version */ .i8); -const DEFAULT_LOGGER = { - error: (message, ...optionalParams) => { - console.error('E ' + message, ...optionalParams); - }, - info: (message, ...optionalParams) => { - console.error('I ' + message, ...optionalParams); - }, - debug: (message, ...optionalParams) => { - console.error('D ' + message, ...optionalParams); - }, -}; -let _logger = DEFAULT_LOGGER; -let _logVerbosity = constants_1.LogVerbosity.ERROR; -const verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : ''; -switch (verbosityString.toUpperCase()) { - case 'DEBUG': - _logVerbosity = constants_1.LogVerbosity.DEBUG; - break; - case 'INFO': - _logVerbosity = constants_1.LogVerbosity.INFO; - break; - case 'ERROR': - _logVerbosity = constants_1.LogVerbosity.ERROR; - break; - case 'NONE': - _logVerbosity = constants_1.LogVerbosity.NONE; - break; - default: - // Ignore any other values -} -const getLogger = () => { - return _logger; -}; -exports.getLogger = getLogger; -const setLogger = (logger) => { - _logger = logger; -}; -exports.setLogger = setLogger; -const setLoggerVerbosity = (verbosity) => { - _logVerbosity = verbosity; -}; -exports.setLoggerVerbosity = setLoggerVerbosity; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const log = (severity, ...args) => { - let logFunction; - if (severity >= _logVerbosity) { - switch (severity) { - case constants_1.LogVerbosity.DEBUG: - logFunction = _logger.debug; - break; - case constants_1.LogVerbosity.INFO: - logFunction = _logger.info; - break; - case constants_1.LogVerbosity.ERROR: - logFunction = _logger.error; - break; - } - /* Fall back to _logger.error when other methods are not available for - * compatiblity with older behavior that always logged to _logger.error */ - if (!logFunction) { - logFunction = _logger.error; - } - if (logFunction) { - logFunction.bind(_logger)(...args); - } - } -}; -exports.log = log; -const tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : ''; -const enabledTracers = new Set(); -const disabledTracers = new Set(); -for (const tracerName of tracersString.split(',')) { - if (tracerName.startsWith('-')) { - disabledTracers.add(tracerName.substring(1)); - } - else { - enabledTracers.add(tracerName); - } -} -const allEnabled = enabledTracers.has('all'); -function trace(severity, tracer, text) { - if (isTracerEnabled(tracer)) { - (0, exports.log)(severity, new Date().toISOString() + - ' | v' + - clientVersion + - ' ' + - process_1.pid + - ' | ' + - tracer + - ' | ' + - text); - } -} -function isTracerEnabled(tracer) { - return (!disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer))); -} -//# sourceMappingURL=logging.js.map - -/***/ }), - -/***/ 38541: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.makeClientConstructor = makeClientConstructor; -exports.loadPackageDefinition = loadPackageDefinition; -const client_1 = __nccwpck_require__(87172); -/** - * Map with short names for each of the requester maker functions. Used in - * makeClientConstructor - * @private - */ -const requesterFuncs = { - unary: client_1.Client.prototype.makeUnaryRequest, - server_stream: client_1.Client.prototype.makeServerStreamRequest, - client_stream: client_1.Client.prototype.makeClientStreamRequest, - bidi: client_1.Client.prototype.makeBidiStreamRequest, -}; -/** - * Returns true, if given key is included in the blacklisted - * keys. - * @param key key for check, string. - */ -function isPrototypePolluted(key) { - return ['__proto__', 'prototype', 'constructor'].includes(key); -} -/** - * Creates a constructor for a client with the given methods, as specified in - * the methods argument. The resulting class will have an instance method for - * each method in the service, which is a partial application of one of the - * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` - * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` - * arguments predefined. - * @param methods An object mapping method names to - * method attributes - * @param serviceName The fully qualified name of the service - * @param classOptions An options object. - * @return New client constructor, which is a subclass of - * {@link grpc.Client}, and has the same arguments as that constructor. - */ -function makeClientConstructor(methods, serviceName, classOptions) { - if (!classOptions) { - classOptions = {}; - } - class ServiceClientImpl extends client_1.Client { - } - Object.keys(methods).forEach(name => { - if (isPrototypePolluted(name)) { - return; - } - const attrs = methods[name]; - let methodType; - // TODO(murgatroid99): Verify that we don't need this anymore - if (typeof name === 'string' && name.charAt(0) === '$') { - throw new Error('Method names cannot start with $'); - } - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = 'bidi'; - } - else { - methodType = 'client_stream'; - } - } - else { - if (attrs.responseStream) { - methodType = 'server_stream'; - } - else { - methodType = 'unary'; - } - } - const serialize = attrs.requestSerialize; - const deserialize = attrs.responseDeserialize; - const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); - ServiceClientImpl.prototype[name] = methodFunc; - // Associate all provided attributes with the method - Object.assign(ServiceClientImpl.prototype[name], attrs); - if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { - ServiceClientImpl.prototype[attrs.originalName] = - ServiceClientImpl.prototype[name]; - } - }); - ServiceClientImpl.service = methods; - ServiceClientImpl.serviceName = serviceName; - return ServiceClientImpl; -} -function partial(fn, path, serialize, deserialize) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function (...args) { - return fn.call(this, path, serialize, deserialize, ...args); - }; -} -function isProtobufTypeDefinition(obj) { - return 'format' in obj; -} -/** - * Load a gRPC package definition as a gRPC object hierarchy. - * @param packageDef The package definition object. - * @return The resulting gRPC object. - */ -function loadPackageDefinition(packageDef) { - const result = {}; - for (const serviceFqn in packageDef) { - if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { - const service = packageDef[serviceFqn]; - const nameComponents = serviceFqn.split('.'); - if (nameComponents.some((comp) => isPrototypePolluted(comp))) { - continue; - } - const serviceName = nameComponents[nameComponents.length - 1]; - let current = result; - for (const packageName of nameComponents.slice(0, -1)) { - if (!current[packageName]) { - current[packageName] = {}; - } - current = current[packageName]; - } - if (isProtobufTypeDefinition(service)) { - current[serviceName] = service; - } - else { - current[serviceName] = makeClientConstructor(service, serviceName, {}); - } - } - } - return result; -} -//# sourceMappingURL=make-client.js.map - -/***/ }), - -/***/ 83665: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Metadata = void 0; -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const error_1 = __nccwpck_require__(22336); -const LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; -const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; -function isLegalKey(key) { - return LEGAL_KEY_REGEX.test(key); -} -function isLegalNonBinaryValue(value) { - return LEGAL_NON_BINARY_VALUE_REGEX.test(value); -} -function isBinaryKey(key) { - return key.endsWith('-bin'); -} -function isCustomMetadata(key) { - return !key.startsWith('grpc-'); -} -function normalizeKey(key) { - return key.toLowerCase(); -} -function validate(key, value) { - if (!isLegalKey(key)) { - throw new Error('Metadata key "' + key + '" contains illegal characters'); - } - if (value !== null && value !== undefined) { - if (isBinaryKey(key)) { - if (!Buffer.isBuffer(value)) { - throw new Error("keys that end with '-bin' must have Buffer values"); - } - } - else { - if (Buffer.isBuffer(value)) { - throw new Error("keys that don't end with '-bin' must have String values"); - } - if (!isLegalNonBinaryValue(value)) { - throw new Error('Metadata string value "' + value + '" contains illegal characters'); - } - } - } -} -/** - * A class for storing metadata. Keys are normalized to lowercase ASCII. - */ -class Metadata { - constructor(options = {}) { - this.internalRepr = new Map(); - this.opaqueData = new Map(); - this.options = options; - } - /** - * Sets the given value for the given key by replacing any other values - * associated with that key. Normalizes the key. - * @param key The key to whose value should be set. - * @param value The value to set. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - set(key, value) { - key = normalizeKey(key); - validate(key, value); - this.internalRepr.set(key, [value]); - } - /** - * Adds the given value for the given key by appending to a list of previous - * values associated with that key. Normalizes the key. - * @param key The key for which a new value should be appended. - * @param value The value to add. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - add(key, value) { - key = normalizeKey(key); - validate(key, value); - const existingValue = this.internalRepr.get(key); - if (existingValue === undefined) { - this.internalRepr.set(key, [value]); - } - else { - existingValue.push(value); - } - } - /** - * Removes the given key and any associated values. Normalizes the key. - * @param key The key whose values should be removed. - */ - remove(key) { - key = normalizeKey(key); - // validate(key); - this.internalRepr.delete(key); - } - /** - * Gets a list of all values associated with the key. Normalizes the key. - * @param key The key whose value should be retrieved. - * @return A list of values associated with the given key. - */ - get(key) { - key = normalizeKey(key); - // validate(key); - return this.internalRepr.get(key) || []; - } - /** - * Gets a plain object mapping each key to the first value associated with it. - * This reflects the most common way that people will want to see metadata. - * @return A key/value mapping of the metadata. - */ - getMap() { - const result = {}; - for (const [key, values] of this.internalRepr) { - if (values.length > 0) { - const v = values[0]; - result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; - } - } - return result; - } - /** - * Clones the metadata object. - * @return The newly cloned object. - */ - clone() { - const newMetadata = new Metadata(this.options); - const newInternalRepr = newMetadata.internalRepr; - for (const [key, value] of this.internalRepr) { - const clonedValue = value.map(v => { - if (Buffer.isBuffer(v)) { - return Buffer.from(v); - } - else { - return v; - } - }); - newInternalRepr.set(key, clonedValue); - } - return newMetadata; - } - /** - * Merges all key-value pairs from a given Metadata object into this one. - * If both this object and the given object have values in the same key, - * values from the other Metadata object will be appended to this object's - * values. - * @param other A Metadata object. - */ - merge(other) { - for (const [key, values] of other.internalRepr) { - const mergedValue = (this.internalRepr.get(key) || []).concat(values); - this.internalRepr.set(key, mergedValue); - } - } - setOptions(options) { - this.options = options; - } - getOptions() { - return this.options; - } - /** - * Creates an OutgoingHttpHeaders object that can be used with the http2 API. - */ - toHttp2Headers() { - // NOTE: Node <8.9 formats http2 headers incorrectly. - const result = {}; - for (const [key, values] of this.internalRepr) { - if (key.startsWith(':')) { - continue; - } - // We assume that the user's interaction with this object is limited to - // through its public API (i.e. keys and values are already validated). - result[key] = values.map(bufToString); - } - return result; - } - /** - * This modifies the behavior of JSON.stringify to show an object - * representation of the metadata map. - */ - toJSON() { - const result = {}; - for (const [key, values] of this.internalRepr) { - result[key] = values; - } - return result; - } - /** - * Attach additional data of any type to the metadata object, which will not - * be included when sending headers. The data can later be retrieved with - * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this - * library. - * @param key - * @param value - */ - setOpaque(key, value) { - this.opaqueData.set(key, value); - } - /** - * Retrieve data previously added with `setOpaque`. - * @param key - * @returns - */ - getOpaque(key) { - return this.opaqueData.get(key); - } - /** - * Returns a new Metadata object based fields in a given IncomingHttpHeaders - * object. - * @param headers An IncomingHttpHeaders object. - */ - static fromHttp2Headers(headers) { - const result = new Metadata(); - for (const key of Object.keys(headers)) { - // Reserved headers (beginning with `:`) are not valid keys. - if (key.charAt(0) === ':') { - continue; - } - const values = headers[key]; - try { - if (isBinaryKey(key)) { - if (Array.isArray(values)) { - values.forEach(value => { - result.add(key, Buffer.from(value, 'base64')); - }); - } - else if (values !== undefined) { - if (isCustomMetadata(key)) { - values.split(',').forEach(v => { - result.add(key, Buffer.from(v.trim(), 'base64')); - }); - } - else { - result.add(key, Buffer.from(values, 'base64')); - } - } - } - else { - if (Array.isArray(values)) { - values.forEach(value => { - result.add(key, value); - }); - } - else if (values !== undefined) { - result.add(key, values); - } - } - } - catch (error) { - const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); - } - } - return result; - } -} -exports.Metadata = Metadata; -const bufToString = (val) => { - return Buffer.isBuffer(val) ? val.toString('base64') : val; -}; -//# sourceMappingURL=metadata.js.map - -/***/ }), - -/***/ 31791: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OrcaOobMetricsSubchannelWrapper = exports.GRPC_METRICS_HEADER = exports.ServerMetricRecorder = exports.PerRequestMetricRecorder = void 0; -exports.createOrcaClient = createOrcaClient; -exports.createMetricsReader = createMetricsReader; -const make_client_1 = __nccwpck_require__(38541); -const duration_1 = __nccwpck_require__(62668); -const channel_credentials_1 = __nccwpck_require__(44030); -const subchannel_interface_1 = __nccwpck_require__(12258); -const constants_1 = __nccwpck_require__(90634); -const backoff_timeout_1 = __nccwpck_require__(34186); -const connectivity_state_1 = __nccwpck_require__(80878); -const loadedOrcaProto = null; -function loadOrcaProto() { - if (loadedOrcaProto) { - return loadedOrcaProto; - } - /* The purpose of this complexity is to avoid loading @grpc/proto-loader at - * runtime for users who will not use/enable ORCA. */ - const loaderLoadSync = (__nccwpck_require__(48934)/* .loadSync */ .J_); - const loadedProto = loaderLoadSync('xds/service/orca/v3/orca.proto', { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [ - __nccwpck_require__.ab + "xds", - __nccwpck_require__.ab + "protoc-gen-validate" - ], - }); - return (0, make_client_1.loadPackageDefinition)(loadedProto); -} -/** - * ORCA metrics recorder for a single request - */ -class PerRequestMetricRecorder { - constructor() { - this.message = {}; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordRequestCostMetric(name, value) { - if (!this.message.request_cost) { - this.message.request_cost = {}; - } - this.message.request_cost[name] = value; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - /** - * Records an opaque named metric measurement for the call. - * @param name - * @param value - */ - recordNamedMetric(name, value) { - if (!this.message.named_metrics) { - this.message.named_metrics = {}; - } - this.message.named_metrics[name] = value; - } - /** - * Records the CPU utilization metric measurement for the call. - * @param value - */ - recordCPUUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordMemoryUtilizationMetric(value) { - this.message.mem_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - /** - * Records the queries per second measurement. - * @param value - */ - recordQpsMetric(value) { - this.message.rps_fractional = value; - } - /** - * Records the errors per second measurement. - * @param value - */ - recordEpsMetric(value) { - this.message.eps = value; - } - serialize() { - const orcaProto = loadOrcaProto(); - return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); - } -} -exports.PerRequestMetricRecorder = PerRequestMetricRecorder; -const DEFAULT_REPORT_INTERVAL_MS = 30000; -class ServerMetricRecorder { - constructor() { - this.message = {}; - this.serviceImplementation = { - StreamCoreMetrics: call => { - const reportInterval = call.request.report_interval ? - (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : - DEFAULT_REPORT_INTERVAL_MS; - const reportTimer = setInterval(() => { - call.write(this.message); - }, reportInterval); - call.on('cancelled', () => { - clearInterval(reportTimer); - }); - } - }; - } - putUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - setAllUtilizationMetrics(metrics) { - this.message.utilization = Object.assign({}, metrics); - } - deleteUtilizationMetric(name) { - var _a; - (_a = this.message.utilization) === null || _a === void 0 ? true : delete _a[name]; - } - setCpuUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - deleteCpuUtilizationMetric() { - delete this.message.cpu_utilization; - } - setApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - deleteApplicationUtilizationMetric() { - delete this.message.application_utilization; - } - setQpsMetric(value) { - this.message.rps_fractional = value; - } - deleteQpsMetric() { - delete this.message.rps_fractional; - } - setEpsMetric(value) { - this.message.eps = value; - } - deleteEpsMetric() { - delete this.message.eps; - } - addToServer(server) { - const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; - server.addService(serviceDefinition, this.serviceImplementation); - } -} -exports.ServerMetricRecorder = ServerMetricRecorder; -function createOrcaClient(channel) { - const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; - return new ClientClass('unused', channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel }); -} -exports.GRPC_METRICS_HEADER = 'endpoint-load-metrics-bin'; -const PARSED_LOAD_REPORT_KEY = 'grpc_orca_load_report'; -/** - * Create an onCallEnded callback for use in a picker. - * @param listener The listener to handle metrics, whenever they are provided. - * @param previousOnCallEnded The previous onCallEnded callback to propagate - * to, if applicable. - * @returns - */ -function createMetricsReader(listener, previousOnCallEnded) { - return (code, details, metadata) => { - let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY); - if (parsedLoadReport) { - listener(parsedLoadReport); - } - else { - const serializedLoadReport = metadata.get(exports.GRPC_METRICS_HEADER); - if (serializedLoadReport.length > 0) { - const orcaProto = loadOrcaProto(); - parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]); - listener(parsedLoadReport); - metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); - } - } - if (previousOnCallEnded) { - previousOnCallEnded(code, details, metadata); - } - }; -} -const DATA_PRODUCER_KEY = 'orca_oob_metrics'; -class OobMetricsDataWatcher { - constructor(metricsListener, intervalMs) { - this.metricsListener = metricsListener; - this.intervalMs = intervalMs; - this.dataProducer = null; - } - setSubchannel(subchannel) { - const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); - this.dataProducer = producer; - producer.addDataWatcher(this); - } - destroy() { - var _a; - (_a = this.dataProducer) === null || _a === void 0 ? void 0 : _a.removeDataWatcher(this); - } - getInterval() { - return this.intervalMs; - } - onMetricsUpdate(metrics) { - this.metricsListener(metrics); - } -} -class OobMetricsDataProducer { - constructor(subchannel) { - this.subchannel = subchannel; - this.dataWatchers = new Set(); - this.orcaSupported = true; - this.metricsCall = null; - this.currentInterval = Infinity; - this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription()); - this.subchannelStateListener = () => this.updateMetricsSubscription(); - const channel = subchannel.getChannel(); - this.client = createOrcaClient(channel); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - addDataWatcher(dataWatcher) { - this.dataWatchers.add(dataWatcher); - this.updateMetricsSubscription(); - } - removeDataWatcher(dataWatcher) { - var _a; - this.dataWatchers.delete(dataWatcher); - if (this.dataWatchers.size === 0) { - this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.metricsCall = null; - this.client.close(); - this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - } - else { - this.updateMetricsSubscription(); - } - } - updateMetricsSubscription() { - var _a; - if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - return; - } - const newInterval = Math.min(...Array.from(this.dataWatchers).map(watcher => watcher.getInterval())); - if (!this.metricsCall || newInterval !== this.currentInterval) { - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.currentInterval = newInterval; - const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) }); - this.metricsCall = metricsCall; - metricsCall.on('data', (report) => { - this.dataWatchers.forEach(watcher => { - watcher.onMetricsUpdate(report); - }); - }); - metricsCall.on('error', (error) => { - this.metricsCall = null; - if (error.code === constants_1.Status.UNIMPLEMENTED) { - this.orcaSupported = false; - return; - } - if (error.code === constants_1.Status.CANCELLED) { - return; - } - this.backoffTimer.runOnce(); - }); - } - } -} -class OrcaOobMetricsSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(child, metricsListener, intervalMs) { - super(child); - this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); - } - getWrappedSubchannel() { - return this.child; - } -} -exports.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper; -function createOobMetricsDataProducer(subchannel) { - return new OobMetricsDataProducer(subchannel); -} -//# sourceMappingURL=orca.js.map - -/***/ }), - -/***/ 81611: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = void 0; -const metadata_1 = __nccwpck_require__(83665); -const constants_1 = __nccwpck_require__(90634); -var PickResultType; -(function (PickResultType) { - PickResultType[PickResultType["COMPLETE"] = 0] = "COMPLETE"; - PickResultType[PickResultType["QUEUE"] = 1] = "QUEUE"; - PickResultType[PickResultType["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; - PickResultType[PickResultType["DROP"] = 3] = "DROP"; -})(PickResultType || (exports.PickResultType = PickResultType = {})); -/** - * A standard picker representing a load balancer in the TRANSIENT_FAILURE - * state. Always responds to every pick request with an UNAVAILABLE status. - */ -class UnavailablePicker { - constructor(status) { - this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: 'No connection established', metadata: new metadata_1.Metadata() }, status); - } - pick(pickArgs) { - return { - pickResultType: PickResultType.TRANSIENT_FAILURE, - subchannel: null, - status: this.status, - onCallStarted: null, - onCallEnded: null, - }; - } -} -exports.UnavailablePicker = UnavailablePicker; -/** - * A standard picker representing a load balancer in the IDLE or CONNECTING - * state. Always responds to every pick request with a QUEUE pick result - * indicating that the pick should be tried again with the next `Picker`. Also - * reports back to the load balancer that a connection should be established - * once any pick is attempted. - * If the childPicker is provided, delegate to it instead of returning the - * hardcoded QUEUE pick result, but still calls exitIdle. - */ -class QueuePicker { - // Constructed with a load balancer. Calls exitIdle on it the first time pick is called - constructor(loadBalancer, childPicker) { - this.loadBalancer = loadBalancer; - this.childPicker = childPicker; - this.calledExitIdle = false; - } - pick(pickArgs) { - if (!this.calledExitIdle) { - process.nextTick(() => { - this.loadBalancer.exitIdle(); - }); - this.calledExitIdle = true; - } - if (this.childPicker) { - return this.childPicker.pick(pickArgs); - } - else { - return { - pickResultType: PickResultType.QUEUE, - subchannel: null, - status: null, - onCallStarted: null, - onCallEnded: null, - }; - } - } -} -exports.QueuePicker = QueuePicker; -//# sourceMappingURL=picker.js.map - -/***/ }), - -/***/ 38386: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PriorityQueue = void 0; -const top = 0; -const parent = (i) => Math.floor(i / 2); -const left = (i) => i * 2 + 1; -const right = (i) => i * 2 + 2; -/** - * A generic priority queue implemented as an array-based binary heap. - * Adapted from https://stackoverflow.com/a/42919752/159388 - */ -class PriorityQueue { - /** - * - * @param comparator Returns true if the first argument should precede the - * second in the queue. Defaults to `(a, b) => a > b` - */ - constructor(comparator = (a, b) => a > b) { - this.comparator = comparator; - this.heap = []; - } - /** - * @returns The number of items currently in the queue - */ - size() { - return this.heap.length; - } - /** - * @returns True if there are no items in the queue, false otherwise - */ - isEmpty() { - return this.size() == 0; - } - /** - * Look at the front item that would be popped, without modifying the contents - * of the queue - * @returns The front item in the queue, or undefined if the queue is empty - */ - peek() { - return this.heap[top]; - } - /** - * Add the items to the queue - * @param values The items to add - * @returns The new size of the queue after adding the items - */ - push(...values) { - values.forEach(value => { - this.heap.push(value); - this.siftUp(); - }); - return this.size(); - } - /** - * Remove the front item in the queue and return it - * @returns The front item in the queue, or undefined if the queue is empty - */ - pop() { - const poppedValue = this.peek(); - const bottom = this.size() - 1; - if (bottom > top) { - this.swap(top, bottom); - } - this.heap.pop(); - this.siftDown(); - return poppedValue; - } - /** - * Simultaneously remove the front item in the queue and add the provided - * item. - * @param value The item to add - * @returns The front item in the queue, or undefined if the queue is empty - */ - replace(value) { - const replacedValue = this.peek(); - this.heap[top] = value; - this.siftDown(); - return replacedValue; - } - greater(i, j) { - return this.comparator(this.heap[i], this.heap[j]); - } - swap(i, j) { - [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; - } - siftUp() { - let node = this.size() - 1; - while (node > top && this.greater(node, parent(node))) { - this.swap(node, parent(node)); - node = parent(node); - } - } - siftDown() { - let node = top; - while ((left(node) < this.size() && this.greater(left(node), node)) || - (right(node) < this.size() && this.greater(right(node), node))) { - let maxChild = (right(node) < this.size() && this.greater(right(node), left(node))) ? right(node) : left(node); - this.swap(node, maxChild); - node = maxChild; - } - } -} -exports.PriorityQueue = PriorityQueue; -//# sourceMappingURL=priority-queue.js.map - -/***/ }), - -/***/ 54886: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_PORT = void 0; -exports.setup = setup; -const resolver_1 = __nccwpck_require__(31594); -const dns_1 = __nccwpck_require__(9523); -const service_config_1 = __nccwpck_require__(21761); -const constants_1 = __nccwpck_require__(90634); -const call_interface_1 = __nccwpck_require__(78710); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const constants_2 = __nccwpck_require__(90634); -const uri_parser_1 = __nccwpck_require__(65974); -const net_1 = __nccwpck_require__(41808); -const backoff_timeout_1 = __nccwpck_require__(34186); -const environment_1 = __nccwpck_require__(29160); -const TRACER_NAME = 'dns_resolver'; -function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); -} -/** - * The default TCP port to connect to if not explicitly specified in the target. - */ -exports.DEFAULT_PORT = 443; -const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30000; -/** - * Resolver implementation that handles DNS names and IP addresses. - */ -class DnsResolver { - constructor(target, listener, channelOptions) { - var _a, _b, _c; - this.target = target; - this.listener = listener; - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.continueResolving = false; - this.isNextResolutionTimerRunning = false; - this.isServiceConfigEnabled = true; - this.returnedIpResult = false; - this.alternativeResolver = new dns_1.promises.Resolver(); - trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); - if (target.authority) { - this.alternativeResolver.setServers([target.authority]); - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (hostPort === null) { - this.ipResult = null; - this.dnsHostname = null; - this.port = null; - } - else { - if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { - this.ipResult = [ - { - addresses: [ - { - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports.DEFAULT_PORT, - }, - ], - }, - ]; - this.dnsHostname = null; - this.port = null; - } - else { - this.ipResult = null; - this.dnsHostname = hostPort.host; - this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports.DEFAULT_PORT; - } - } - this.percentage = Math.random() * 100; - if (channelOptions['grpc.service_config_disable_resolution'] === 1) { - this.isServiceConfigEnabled = false; - } - this.defaultResolutionError = { - code: constants_1.Status.UNAVAILABLE, - details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, - metadata: new metadata_1.Metadata(), - }; - const backoffOptions = { - initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], - maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], - }; - this.backoff = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, backoffOptions); - this.backoff.unref(); - this.minTimeBetweenResolutionsMs = - (_c = channelOptions['grpc.dns_min_time_between_resolutions_ms']) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; - this.nextResolutionTimer = setTimeout(() => { }, 0); - clearTimeout(this.nextResolutionTimer); - } - /** - * If the target is an IP address, just provide that address as a result. - * Otherwise, initiate A, AAAA, and TXT lookups - */ - startResolution() { - if (this.ipResult !== null) { - if (!this.returnedIpResult) { - trace('Returning IP address for target ' + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, ''); - }); - this.returnedIpResult = true; - } - this.backoff.stop(); - this.backoff.reset(); - this.stopNextResolutionTimer(); - return; - } - if (this.dnsHostname === null) { - trace('Failed to parse DNS address ' + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}` - }), {}, null, ''); - }); - this.stopNextResolutionTimer(); - } - else { - if (this.pendingLookupPromise !== null) { - return; - } - trace('Looking up DNS hostname ' + this.dnsHostname); - /* We clear out latestLookupResult here to ensure that it contains the - * latest result since the last time we started resolving. That way, the - * TXT resolution handler can use it, but only if it finishes second. We - * don't clear out any previous service config results because it's - * better to use a service config that's slightly out of date than to - * revert to an effectively blank one. */ - this.latestLookupResult = null; - const hostname = this.dnsHostname; - this.pendingLookupPromise = this.lookup(hostname); - this.pendingLookupPromise.then(addressList => { - if (this.pendingLookupPromise === null) { - return; - } - this.pendingLookupPromise = null; - this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map(address => ({ - addresses: [address], - }))); - const allAddressesString = '[' + - addressList.map(addr => addr.host + ':' + addr.port).join(',') + - ']'; - trace('Resolved addresses for target ' + - (0, uri_parser_1.uriToString)(this.target) + - ': ' + - allAddressesString); - /* If the TXT lookup has not yet finished, both of the last two - * arguments will be null, which is the equivalent of getting an - * empty TXT response. When the TXT lookup does finish, its handler - * can update the service config by using the same address list */ - const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); - this.handleHealthStatus(healthStatus); - }, err => { - if (this.pendingLookupPromise === null) { - return; - } - trace('Resolution error for target ' + - (0, uri_parser_1.uriToString)(this.target) + - ': ' + - err.message); - this.pendingLookupPromise = null; - this.stopNextResolutionTimer(); - this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, ''); - }); - /* If there already is a still-pending TXT resolution, we can just use - * that result when it comes in */ - if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { - /* We handle the TXT query promise differently than the others because - * the name resolution attempt as a whole is a success even if the TXT - * lookup fails */ - this.pendingTxtPromise = this.resolveTxt(hostname); - this.pendingTxtPromise.then(txtRecord => { - if (this.pendingTxtPromise === null) { - return; - } - this.pendingTxtPromise = null; - let serviceConfig; - try { - serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); - if (serviceConfig) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig); - } - else { - this.latestServiceConfigResult = null; - } - } - catch (err) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Parsing service config failed with error ${err.message}` - }); - } - if (this.latestLookupResult !== null) { - /* We rely here on the assumption that calling this function with - * identical parameters will be essentialy idempotent, and calling - * it with the same address list and a different service config - * should result in a fast and seamless switchover. */ - this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); - } - }, err => { - /* If TXT lookup fails we should do nothing, which means that we - * continue to use the result of the most recent successful lookup, - * or the default null config object if there has never been a - * successful lookup. We do not set the latestServiceConfigError - * here because that is specifically used for response validation - * errors. We still need to handle this error so that it does not - * bubble up as an unhandled promise rejection. */ - }); - } - } - } - /** - * The ResolverListener returns a boolean indicating whether the LB policy - * accepted the resolution result. A false result on an otherwise successful - * resolution should be treated as a resolution failure. - * @param healthStatus - */ - handleHealthStatus(healthStatus) { - if (healthStatus) { - this.backoff.stop(); - this.backoff.reset(); - } - else { - this.continueResolving = true; - } - } - async lookup(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace('Using alternative DNS resolver.'); - const records = await Promise.allSettled([ - this.alternativeResolver.resolve4(hostname), - this.alternativeResolver.resolve6(hostname), - ]); - if (records.every(result => result.status === 'rejected')) { - throw new Error(records[0].reason); - } - return records - .reduce((acc, result) => { - return result.status === 'fulfilled' - ? [...acc, ...result.value] - : acc; - }, []) - .map(addr => ({ - host: addr, - port: +this.port, - })); - } - /* We lookup both address families here and then split them up later - * because when looking up a single family, dns.lookup outputs an error - * if the name exists but there are no records for that family, and that - * error is indistinguishable from other kinds of errors */ - const addressList = await dns_1.promises.lookup(hostname, { all: true }); - return addressList.map(addr => ({ host: addr.address, port: +this.port })); - } - async resolveTxt(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace('Using alternative DNS resolver.'); - return this.alternativeResolver.resolveTxt(hostname); - } - return dns_1.promises.resolveTxt(hostname); - } - startNextResolutionTimer() { - var _a, _b; - clearTimeout(this.nextResolutionTimer); - this.nextResolutionTimer = setTimeout(() => { - this.stopNextResolutionTimer(); - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, this.minTimeBetweenResolutionsMs); - (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - this.isNextResolutionTimerRunning = true; - } - stopNextResolutionTimer() { - clearTimeout(this.nextResolutionTimer); - this.isNextResolutionTimerRunning = false; - } - startResolutionWithBackoff() { - if (this.pendingLookupPromise === null) { - this.continueResolving = false; - this.backoff.runOnce(); - this.startNextResolutionTimer(); - this.startResolution(); - } - } - updateResolution() { - /* If there is a pending lookup, just let it finish. Otherwise, if the - * nextResolutionTimer or backoff timer is running, set the - * continueResolving flag to resolve when whichever of those timers - * fires. Otherwise, start resolving immediately. */ - if (this.pendingLookupPromise === null) { - if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { - if (this.isNextResolutionTimerRunning) { - trace('resolution update delayed by "min time between resolutions" rate limit'); - } - else { - trace('resolution update delayed by backoff timer until ' + - this.backoff.getEndTime().toISOString()); - } - this.continueResolving = true; - } - else { - this.startResolutionWithBackoff(); - } - } - } - /** - * Reset the resolver to the same state it had when it was created. In-flight - * DNS requests cannot be cancelled, but they are discarded and their results - * will be ignored. - */ - destroy() { - this.continueResolving = false; - this.backoff.reset(); - this.backoff.stop(); - this.stopNextResolutionTimer(); - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.returnedIpResult = false; - } - /** - * Get the default authority for the given target. For IP targets, that is - * the IP address. For DNS targets, it is the hostname. - * @param target - */ - static getDefaultAuthority(target) { - return target.path; - } -} -/** - * Set up the DNS resolver class by registering it as the handler for the - * "dns:" prefix and as the default resolver. - */ -function setup() { - (0, resolver_1.registerResolver)('dns', DnsResolver); - (0, resolver_1.registerDefaultScheme)('dns'); -} -//# sourceMappingURL=resolver-dns.js.map - -/***/ }), - -/***/ 97902: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setup = setup; -const net_1 = __nccwpck_require__(41808); -const call_interface_1 = __nccwpck_require__(78710); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const resolver_1 = __nccwpck_require__(31594); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'ip_resolver'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const IPV4_SCHEME = 'ipv4'; -const IPV6_SCHEME = 'ipv6'; -/** - * The default TCP port to connect to if not explicitly specified in the target. - */ -const DEFAULT_PORT = 443; -class IpResolver { - constructor(target, listener, channelOptions) { - var _a; - this.listener = listener; - this.endpoints = []; - this.error = null; - this.hasReturnedResult = false; - trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); - const addresses = []; - if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Unrecognized scheme ${target.scheme} in IP resolver`, - metadata: new metadata_1.Metadata(), - }; - return; - } - const pathList = target.path.split(','); - for (const path of pathList) { - const hostPort = (0, uri_parser_1.splitHostPort)(path); - if (hostPort === null) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata(), - }; - return; - } - if ((target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host)) || - (target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host))) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata(), - }; - return; - } - addresses.push({ - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT, - }); - } - this.endpoints = addresses.map(address => ({ addresses: [address] })); - trace('Parsed ' + target.scheme + ' address list ' + addresses.map(subchannel_address_1.subchannelAddressToString)); - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(() => { - if (this.error) { - this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, ''); - } - else { - this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); - } - }); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return target.path.split(',')[0]; - } -} -function setup() { - (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); - (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); -} -//# sourceMappingURL=resolver-ip.js.map - -/***/ }), - -/***/ 5252: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setup = setup; -const resolver_1 = __nccwpck_require__(31594); -const call_interface_1 = __nccwpck_require__(78710); -class UdsResolver { - constructor(target, listener, channelOptions) { - this.listener = listener; - this.hasReturnedResult = false; - this.endpoints = []; - let path; - if (target.authority === '') { - path = '/' + target.path; - } - else { - path = target.path; - } - this.endpoints = [{ addresses: [{ path }] }]; - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return 'localhost'; - } -} -function setup() { - (0, resolver_1.registerResolver)('unix', UdsResolver); -} -//# sourceMappingURL=resolver-uds.js.map - -/***/ }), - -/***/ 31594: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0; -exports.registerResolver = registerResolver; -exports.registerDefaultScheme = registerDefaultScheme; -exports.createResolver = createResolver; -exports.getDefaultAuthority = getDefaultAuthority; -exports.mapUriDefaultScheme = mapUriDefaultScheme; -const uri_parser_1 = __nccwpck_require__(65974); -exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = 'grpc.internal.config_selector'; -const registeredResolvers = {}; -let defaultScheme = null; -/** - * Register a resolver class to handle target names prefixed with the `prefix` - * string. This prefix should correspond to a URI scheme name listed in the - * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) - * @param prefix - * @param resolverClass - */ -function registerResolver(scheme, resolverClass) { - registeredResolvers[scheme] = resolverClass; -} -/** - * Register a default resolver to handle target names that do not start with - * any registered prefix. - * @param resolverClass - */ -function registerDefaultScheme(scheme) { - defaultScheme = scheme; -} -/** - * Create a name resolver for the specified target, if possible. Throws an - * error if no such name resolver can be created. - * @param target - * @param listener - */ -function createResolver(target, listener, options) { - if (target.scheme !== undefined && target.scheme in registeredResolvers) { - return new registeredResolvers[target.scheme](target, listener, options); - } - else { - throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); - } -} -/** - * Get the default authority for the specified target, if possible. Throws an - * error if no registered name resolver can parse that target string. - * @param target - */ -function getDefaultAuthority(target) { - if (target.scheme !== undefined && target.scheme in registeredResolvers) { - return registeredResolvers[target.scheme].getDefaultAuthority(target); - } - else { - throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); - } -} -function mapUriDefaultScheme(target) { - if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { - if (defaultScheme !== null) { - return { - scheme: defaultScheme, - authority: undefined, - path: (0, uri_parser_1.uriToString)(target), - }; - } - else { - return null; - } - } - return target; -} -//# sourceMappingURL=resolver.js.map - -/***/ }), - -/***/ 39909: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ResolvingCall = void 0; -const call_credentials_1 = __nccwpck_require__(21426); -const constants_1 = __nccwpck_require__(90634); -const deadline_1 = __nccwpck_require__(511); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const control_plane_status_1 = __nccwpck_require__(39129); -const TRACER_NAME = 'resolving_call'; -class ResolvingCall { - constructor(channel, method, options, filterStackFactory, callNumber) { - this.channel = channel; - this.method = method; - this.filterStackFactory = filterStackFactory; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.readFilterPending = false; - this.writeFilterPending = false; - this.pendingChildStatus = null; - this.metadata = null; - this.listener = null; - this.statusWatchers = []; - this.deadlineTimer = setTimeout(() => { }, 0); - this.filterStack = null; - this.deadlineStartTime = null; - this.configReceivedTime = null; - this.childStartTime = null; - /** - * Credentials configured for this specific call. Does not include - * call credentials associated with the channel credentials used to create - * the channel. - */ - this.credentials = call_credentials_1.CallCredentials.createEmpty(); - this.deadline = options.deadline; - this.host = options.host; - if (options.parentCall) { - if (options.flags & constants_1.Propagate.CANCELLATION) { - options.parentCall.on('cancelled', () => { - this.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled by parent call'); - }); - } - if (options.flags & constants_1.Propagate.DEADLINE) { - this.trace('Propagating deadline from parent: ' + - options.parentCall.getDeadline()); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); - } - } - this.trace('Created'); - this.runDeadlineTimer(); - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - runDeadlineTimer() { - clearTimeout(this.deadlineTimer); - this.deadlineStartTime = new Date(); - this.trace('Deadline: ' + (0, deadline_1.deadlineToString)(this.deadline)); - const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); - if (timeout !== Infinity) { - this.trace('Deadline will be reached in ' + timeout + 'ms'); - const handleDeadline = () => { - if (!this.deadlineStartTime) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - return; - } - const deadlineInfo = []; - const deadlineEndTime = new Date(); - deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); - if (this.configReceivedTime) { - if (this.configReceivedTime > this.deadlineStartTime) { - deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); - } - if (this.childStartTime) { - if (this.childStartTime > this.configReceivedTime) { - deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); - } - } - else { - deadlineInfo.push('waiting for metadata filters'); - } - } - else { - deadlineInfo.push('waiting for name resolution'); - } - if (this.child) { - deadlineInfo.push(...this.child.getDeadlineInfo()); - } - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(',')); - }; - if (timeout <= 0) { - process.nextTick(handleDeadline); - } - else { - this.deadlineTimer = setTimeout(handleDeadline, timeout); - } - } - } - outputStatus(status) { - if (!this.ended) { - this.ended = true; - if (!this.filterStack) { - this.filterStack = this.filterStackFactory.createFilter(); - } - clearTimeout(this.deadlineTimer); - const filteredStatus = this.filterStack.receiveTrailers(status); - this.trace('ended with status: code=' + - filteredStatus.code + - ' details="' + - filteredStatus.details + - '"'); - this.statusWatchers.forEach(watcher => watcher(filteredStatus)); - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus); - }); - } - } - sendMessageOnChild(context, message) { - if (!this.child) { - throw new Error('sendMessageonChild called with child not populated'); - } - const child = this.child; - this.writeFilterPending = true; - this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })).then(filteredMessage => { - this.writeFilterPending = false; - child.sendMessageWithContext(context, filteredMessage.message); - if (this.pendingHalfClose) { - child.halfClose(); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - } - getConfig() { - if (this.ended) { - return; - } - if (!this.metadata || !this.listener) { - throw new Error('getConfig called before start'); - } - const configResult = this.channel.getConfig(this.method, this.metadata); - if (configResult.type === 'NONE') { - this.channel.queueCallForConfig(this); - return; - } - else if (configResult.type === 'ERROR') { - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } - else { - this.outputStatus(configResult.error); - } - return; - } - // configResult.type === 'SUCCESS' - this.configReceivedTime = new Date(); - const config = configResult.config; - if (config.status !== constants_1.Status.OK) { - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, 'Failed to route call to method ' + this.method); - this.outputStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }); - return; - } - if (config.methodConfig.timeout) { - const configDeadline = new Date(); - configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); - configDeadline.setMilliseconds(configDeadline.getMilliseconds() + - config.methodConfig.timeout.nanos / 1000000); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); - this.runDeadlineTimer(); - } - this.filterStackFactory.push(config.dynamicFilterFactories); - this.filterStack = this.filterStackFactory.createFilter(); - this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then(filteredMetadata => { - this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); - this.trace('Created child [' + this.child.getCallNumber() + ']'); - this.childStartTime = new Date(); - this.child.start(filteredMetadata, { - onReceiveMetadata: metadata => { - this.trace('Received metadata'); - this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); - }, - onReceiveMessage: message => { - this.trace('Received message'); - this.readFilterPending = true; - this.filterStack.receiveMessage(message).then(filteredMesssage => { - this.trace('Finished filtering received message'); - this.readFilterPending = false; - this.listener.onReceiveMessage(filteredMesssage); - if (this.pendingChildStatus) { - this.outputStatus(this.pendingChildStatus); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - }, - onReceiveStatus: status => { - this.trace('Received status'); - if (this.readFilterPending) { - this.pendingChildStatus = status; - } - else { - this.outputStatus(status); - } - }, - }); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); - } - else if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (status) => { - this.outputStatus(status); - }); - } - reportResolverError(status) { - var _a; - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } - else { - this.outputStatus(status); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ - code: status, - details: details, - metadata: new metadata_1.Metadata(), - }); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace('start called'); - this.metadata = metadata.clone(); - this.listener = listener; - this.getConfig(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - if (this.child) { - this.sendMessageOnChild(context, message); - } - else { - this.pendingMessage = { context, message }; - } - } - startRead() { - this.trace('startRead called'); - if (this.child) { - this.child.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - this.trace('halfClose called'); - if (this.child && !this.writeFilterPending) { - this.child.halfClose(); - } - else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - this.credentials = credentials; - } - addStatusWatcher(watcher) { - this.statusWatchers.push(watcher); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } - else { - return null; - } - } -} -exports.ResolvingCall = ResolvingCall; -//# sourceMappingURL=resolving-call.js.map - -/***/ }), - -/***/ 19192: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ResolvingLoadBalancer = void 0; -const load_balancer_1 = __nccwpck_require__(52680); -const service_config_1 = __nccwpck_require__(21761); -const connectivity_state_1 = __nccwpck_require__(80878); -const resolver_1 = __nccwpck_require__(31594); -const picker_1 = __nccwpck_require__(81611); -const backoff_timeout_1 = __nccwpck_require__(34186); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const constants_2 = __nccwpck_require__(90634); -const uri_parser_1 = __nccwpck_require__(65974); -const load_balancer_child_handler_1 = __nccwpck_require__(17559); -const TRACER_NAME = 'resolving_load_balancer'; -function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); -} -/** - * Name match levels in order from most to least specific. This is the order in - * which searches will be performed. - */ -const NAME_MATCH_LEVEL_ORDER = [ - 'SERVICE_AND_METHOD', - 'SERVICE', - 'EMPTY', -]; -function hasMatchingName(service, method, methodConfig, matchLevel) { - for (const name of methodConfig.name) { - switch (matchLevel) { - case 'EMPTY': - if (!name.service && !name.method) { - return true; - } - break; - case 'SERVICE': - if (name.service === service && !name.method) { - return true; - } - break; - case 'SERVICE_AND_METHOD': - if (name.service === service && name.method === method) { - return true; - } - } - } - return false; -} -function findMatchingConfig(service, method, methodConfigs, matchLevel) { - for (const config of methodConfigs) { - if (hasMatchingName(service, method, config, matchLevel)) { - return config; - } - } - return null; -} -function getDefaultConfigSelector(serviceConfig) { - return { - invoke(methodName, metadata) { - var _a, _b; - const splitName = methodName.split('/').filter(x => x.length > 0); - const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ''; - const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ''; - if (serviceConfig && serviceConfig.methodConfig) { - /* Check for the following in order, and return the first method - * config that matches: - * 1. A name that exactly matches the service and method - * 2. A name with no method set that matches the service - * 3. An empty name - */ - for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { - const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); - if (matchingConfig) { - return { - methodConfig: matchingConfig, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [], - }; - } - } - } - return { - methodConfig: { name: [] }, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [], - }; - }, - unref() { } - }; -} -class ResolvingLoadBalancer { - /** - * Wrapper class that behaves like a `LoadBalancer` and also handles name - * resolution internally. - * @param target The address of the backend to connect to. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - * @param defaultServiceConfig The default service configuration to be used - * if none is provided by the name resolver. A `null` value indicates - * that the default behavior should be the default unconfigured behavior. - * In practice, that means using the "pick first" load balancer - * implmentation - */ - constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { - this.target = target; - this.channelControlHelper = channelControlHelper; - this.channelOptions = channelOptions; - this.onSuccessfulResolution = onSuccessfulResolution; - this.onFailedResolution = onFailedResolution; - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.latestChildErrorMessage = null; - /** - * This resolving load balancer's current connectivity state. - */ - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The service config object from the last successful resolution, if - * available. A value of null indicates that we have not yet received a valid - * service config from the resolver. - */ - this.previousServiceConfig = null; - /** - * Indicates whether we should attempt to resolve again after the backoff - * timer runs out. - */ - this.continueResolving = false; - if (channelOptions['grpc.service_config']) { - this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions['grpc.service_config'])); - } - else { - this.defaultServiceConfig = { - loadBalancingConfig: [], - methodConfig: [], - }; - } - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ - createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), - requestReresolution: () => { - /* If the backoffTimeout is running, we're still backing off from - * making resolve requests, so we shouldn't make another one here. - * In that case, the backoff timer callback will call - * updateResolution */ - if (this.backoffTimeout.isRunning()) { - trace('requestReresolution delayed by backoff timer until ' + - this.backoffTimeout.getEndTime().toISOString()); - this.continueResolving = true; - } - else { - this.updateResolution(); - } - }, - updateState: (newState, picker, errorMessage) => { - this.latestChildState = newState; - this.latestChildPicker = picker; - this.latestChildErrorMessage = errorMessage; - this.updateState(newState, picker, errorMessage); - }, - addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), - removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper), - }); - this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions); - const backoffOptions = { - initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], - maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.updateResolution(); - this.continueResolving = false; - } - else { - this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); - } - }, backoffOptions); - this.backoffTimeout.unref(); - } - handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) { - var _a, _b; - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - let resultAccepted = true; - let workingServiceConfig = null; - if (serviceConfig === null) { - workingServiceConfig = this.defaultServiceConfig; - } - else if (serviceConfig.ok) { - workingServiceConfig = serviceConfig.value; - } - else { - if (this.previousServiceConfig !== null) { - workingServiceConfig = this.previousServiceConfig; - } - else { - resultAccepted = false; - this.handleResolutionFailure(serviceConfig.error); - } - } - if (workingServiceConfig !== null) { - const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : []; - const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); - if (loadBalancingConfig === null) { - resultAccepted = false; - this.handleResolutionFailure({ - code: constants_1.Status.UNAVAILABLE, - details: 'All load balancer options in service config are not compatible', - metadata: new metadata_1.Metadata(), - }); - } - else { - resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote); - } - } - if (resultAccepted) { - this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== void 0 ? _b : getDefaultConfigSelector(workingServiceConfig)); - } - return resultAccepted; - } - updateResolution() { - this.innerResolver.updateResolution(); - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { - /* this.latestChildPicker is initialized as new QueuePicker(this), which - * is an appropriate value here if the child LB policy is unset. - * Otherwise, we want to delegate to the child here, in case that - * triggers something. */ - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); - } - this.backoffTimeout.runOnce(); - } - updateState(connectivityState, picker, errorMessage) { - trace((0, uri_parser_1.uriToString)(this.target) + - ' ' + - connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[connectivityState]); - // Ensure that this.exitIdle() is called by the picker - if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { - picker = new picker_1.QueuePicker(this, picker); - } - this.currentState = connectivityState; - this.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - handleResolutionFailure(error) { - if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error), error.details); - this.onFailedResolution(error); - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || - this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - if (this.backoffTimeout.isRunning()) { - this.continueResolving = true; - } - else { - this.updateResolution(); - } - } - this.childLoadBalancer.exitIdle(); - } - updateAddressList(endpointList, lbConfig) { - throw new Error('updateAddressList not supported on ResolvingLoadBalancer'); - } - resetBackoff() { - this.backoffTimeout.reset(); - this.childLoadBalancer.resetBackoff(); - } - destroy() { - this.childLoadBalancer.destroy(); - this.innerResolver.destroy(); - this.backoffTimeout.reset(); - this.backoffTimeout.stop(); - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.previousServiceConfig = null; - this.continueResolving = false; - } - getTypeName() { - return 'resolving_load_balancer'; - } -} -exports.ResolvingLoadBalancer = ResolvingLoadBalancer; -//# sourceMappingURL=resolving-load-balancer.js.map - -/***/ }), - -/***/ 48159: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RetryingCall = exports.MessageBufferTracker = exports.RetryThrottler = void 0; -const constants_1 = __nccwpck_require__(90634); -const deadline_1 = __nccwpck_require__(511); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'retrying_call'; -class RetryThrottler { - constructor(maxTokens, tokenRatio, previousRetryThrottler) { - this.maxTokens = maxTokens; - this.tokenRatio = tokenRatio; - if (previousRetryThrottler) { - /* When carrying over tokens from a previous config, rescale them to the - * new max value */ - this.tokens = - previousRetryThrottler.tokens * - (maxTokens / previousRetryThrottler.maxTokens); - } - else { - this.tokens = maxTokens; - } - } - addCallSucceeded() { - this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); - } - addCallFailed() { - this.tokens = Math.max(this.tokens - 1, 0); - } - canRetryCall() { - return this.tokens > (this.maxTokens / 2); - } -} -exports.RetryThrottler = RetryThrottler; -class MessageBufferTracker { - constructor(totalLimit, limitPerCall) { - this.totalLimit = totalLimit; - this.limitPerCall = limitPerCall; - this.totalAllocated = 0; - this.allocatedPerCall = new Map(); - } - allocate(size, callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.limitPerCall - currentPerCall < size || - this.totalLimit - this.totalAllocated < size) { - return false; - } - this.allocatedPerCall.set(callId, currentPerCall + size); - this.totalAllocated += size; - return true; - } - free(size, callId) { - var _a; - if (this.totalAllocated < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= size; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (currentPerCall < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); - } - this.allocatedPerCall.set(callId, currentPerCall - size); - } - freeAll(callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.totalAllocated < currentPerCall) { - throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= currentPerCall; - this.allocatedPerCall.delete(callId); - } -} -exports.MessageBufferTracker = MessageBufferTracker; -const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = 'grpc-previous-rpc-attempts'; -const DEFAULT_MAX_ATTEMPTS_LIMIT = 5; -class RetryingCall { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { - var _a; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.bufferTracker = bufferTracker; - this.retryThrottler = retryThrottler; - this.listener = null; - this.initialMetadata = null; - this.underlyingCalls = []; - this.writeBuffer = []; - /** - * The offset of message indices in the writeBuffer. For example, if - * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 - * is in writeBuffer[5]. - */ - this.writeBufferOffset = 0; - /** - * Tracks whether a read has been started, so that we know whether to start - * reads on new child calls. This only matters for the first read, because - * once a message comes in the child call becomes committed and there will - * be no new child calls. - */ - this.readStarted = false; - this.transparentRetryUsed = false; - /** - * Number of attempts so far - */ - this.attempts = 0; - this.hedgingTimer = null; - this.committedCallIndex = null; - this.initialRetryBackoffSec = 0; - this.nextRetryBackoffSec = 0; - const maxAttemptsLimit = (_a = channel.getOptions()['grpc-node.retry_max_attempts_limit']) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT; - if (channel.getOptions()['grpc.enable_retries'] === 0) { - this.state = 'NO_RETRY'; - this.maxAttempts = 1; - } - else if (callConfig.methodConfig.retryPolicy) { - this.state = 'RETRY'; - const retryPolicy = callConfig.methodConfig.retryPolicy; - this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); - this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); - } - else if (callConfig.methodConfig.hedgingPolicy) { - this.state = 'HEDGING'; - this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit); - } - else { - this.state = 'TRANSPARENT_ONLY'; - this.maxAttempts = 1; - } - this.startTime = new Date(); - } - getDeadlineInfo() { - if (this.underlyingCalls.length === 0) { - return []; - } - const deadlineInfo = []; - const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; - if (this.underlyingCalls.length > 1) { - deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); - } - if (latestCall.startTime > this.startTime) { - deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); - } - deadlineInfo.push(...latestCall.call.getDeadlineInfo()); - return deadlineInfo; - } - getCallNumber() { - return this.callNumber; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - reportStatus(statusObject) { - this.trace('ended with status: code=' + - statusObject.code + - ' details="' + - statusObject.details + - '" start time=' + - this.startTime.toISOString()); - this.bufferTracker.freeAll(this.callNumber); - this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; - this.writeBuffer = []; - process.nextTick(() => { - var _a; - // Explicitly construct status object to remove progress field - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({ - code: statusObject.code, - details: statusObject.details, - metadata: statusObject.metadata, - }); - }); - } - cancelWithStatus(status, details) { - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); - for (const { call } of this.underlyingCalls) { - call.cancelWithStatus(status, details); - } - } - getPeer() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getPeer(); - } - else { - return 'unknown'; - } - } - getBufferEntry(messageIndex) { - var _a; - return ((_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : { - entryType: 'FREED', - allocated: false, - }); - } - getNextBufferIndex() { - return this.writeBufferOffset + this.writeBuffer.length; - } - clearSentMessages() { - if (this.state !== 'COMMITTED') { - return; - } - let earliestNeededMessageIndex; - if (this.underlyingCalls[this.committedCallIndex].state === 'COMPLETED') { - /* If the committed call is completed, clear all messages, even if some - * have not been sent. */ - earliestNeededMessageIndex = this.getNextBufferIndex(); - } - else { - earliestNeededMessageIndex = - this.underlyingCalls[this.committedCallIndex].nextMessageToSend; - } - for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) { - const bufferEntry = this.getBufferEntry(messageIndex); - if (bufferEntry.allocated) { - this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); - } - } - this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); - this.writeBufferOffset = earliestNeededMessageIndex; - } - commitCall(index) { - var _a, _b; - if (this.state === 'COMMITTED') { - return; - } - this.trace('Committing call [' + - this.underlyingCalls[index].call.getCallNumber() + - '] at index ' + - index); - this.state = 'COMMITTED'; - (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); - this.committedCallIndex = index; - for (let i = 0; i < this.underlyingCalls.length; i++) { - if (i === index) { - continue; - } - if (this.underlyingCalls[i].state === 'COMPLETED') { - continue; - } - this.underlyingCalls[i].state = 'COMPLETED'; - this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, 'Discarded in favor of other hedged attempt'); - } - this.clearSentMessages(); - } - commitCallWithMostMessages() { - if (this.state === 'COMMITTED') { - return; - } - let mostMessages = -1; - let callWithMostMessages = -1; - for (const [index, childCall] of this.underlyingCalls.entries()) { - if (childCall.state === 'ACTIVE' && - childCall.nextMessageToSend > mostMessages) { - mostMessages = childCall.nextMessageToSend; - callWithMostMessages = index; - } - } - if (callWithMostMessages === -1) { - /* There are no active calls, disable retries to force the next call that - * is started to be committed. */ - this.state = 'TRANSPARENT_ONLY'; - } - else { - this.commitCall(callWithMostMessages); - } - } - isStatusCodeInList(list, code) { - return list.some(value => { - var _a; - return value === code || - value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); - }); - } - getNextRetryJitter() { - /* Jitter of +-20% is applied: https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff */ - return Math.random() * (1.2 - 0.8) + 0.8; - } - getNextRetryBackoffMs() { - var _a; - const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy; - if (!retryPolicy) { - return 0; - } - const jitter = this.getNextRetryJitter(); - const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1000; - const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); - this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); - return nextBackoffMs; - } - maybeRetryCall(pushback, callback) { - if (this.state !== 'RETRY') { - callback(false); - return; - } - if (this.attempts >= this.maxAttempts) { - callback(false); - return; - } - let retryDelayMs; - if (pushback === null) { - retryDelayMs = this.getNextRetryBackoffMs(); - } - else if (pushback < 0) { - this.state = 'TRANSPARENT_ONLY'; - callback(false); - return; - } - else { - retryDelayMs = pushback; - this.nextRetryBackoffSec = this.initialRetryBackoffSec; - } - setTimeout(() => { - var _a, _b; - if (this.state !== 'RETRY') { - callback(false); - return; - } - if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) { - callback(true); - this.attempts += 1; - this.startNewAttempt(); - } - else { - this.trace('Retry attempt denied by throttling policy'); - callback(false); - } - }, retryDelayMs); - } - countActiveCalls() { - let count = 0; - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE') { - count += 1; - } - } - return count; - } - handleProcessedStatus(status, callIndex, pushback) { - var _a, _b, _c; - switch (this.state) { - case 'COMMITTED': - case 'NO_RETRY': - case 'TRANSPARENT_ONLY': - this.commitCall(callIndex); - this.reportStatus(status); - break; - case 'HEDGING': - if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) { - (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed(); - let delayMs; - if (pushback === null) { - delayMs = 0; - } - else if (pushback < 0) { - this.state = 'TRANSPARENT_ONLY'; - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - else { - delayMs = pushback; - } - setTimeout(() => { - this.maybeStartHedgingAttempt(); - // If after trying to start a call there are no active calls, this was the last one - if (this.countActiveCalls() === 0) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }, delayMs); - } - else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - case 'RETRY': - if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { - (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed(); - this.maybeRetryCall(pushback, retried => { - if (!retried) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }); - } - else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - } - } - getPushback(metadata) { - const mdValue = metadata.get('grpc-retry-pushback-ms'); - if (mdValue.length === 0) { - return null; - } - try { - return parseInt(mdValue[0]); - } - catch (e) { - return -1; - } - } - handleChildStatus(status, callIndex) { - var _a; - if (this.underlyingCalls[callIndex].state === 'COMPLETED') { - return; - } - this.trace('state=' + - this.state + - ' handling status with progress ' + - status.progress + - ' from child [' + - this.underlyingCalls[callIndex].call.getCallNumber() + - '] in state ' + - this.underlyingCalls[callIndex].state); - this.underlyingCalls[callIndex].state = 'COMPLETED'; - if (status.code === constants_1.Status.OK) { - (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === 'NO_RETRY') { - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === 'COMMITTED') { - this.reportStatus(status); - return; - } - const pushback = this.getPushback(status.metadata); - switch (status.progress) { - case 'NOT_STARTED': - // RPC never leaves the client, always safe to retry - this.startNewAttempt(); - break; - case 'REFUSED': - // RPC reaches the server library, but not the server application logic - if (this.transparentRetryUsed) { - this.handleProcessedStatus(status, callIndex, pushback); - } - else { - this.transparentRetryUsed = true; - this.startNewAttempt(); - } - break; - case 'DROP': - this.commitCall(callIndex); - this.reportStatus(status); - break; - case 'PROCESSED': - this.handleProcessedStatus(status, callIndex, pushback); - break; - } - } - maybeStartHedgingAttempt() { - if (this.state !== 'HEDGING') { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - if (this.attempts >= this.maxAttempts) { - return; - } - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - maybeStartHedgingTimer() { - var _a, _b, _c; - if (this.hedgingTimer) { - clearTimeout(this.hedgingTimer); - } - if (this.state !== 'HEDGING') { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; - if (this.attempts >= this.maxAttempts) { - return; - } - const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : '0s'; - const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); - this.hedgingTimer = setTimeout(() => { - this.maybeStartHedgingAttempt(); - }, hedgingDelaySec * 1000); - (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - startNewAttempt() { - const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); - this.trace('Created child call [' + - child.getCallNumber() + - '] for attempt ' + - this.attempts); - const index = this.underlyingCalls.length; - this.underlyingCalls.push({ - state: 'ACTIVE', - call: child, - nextMessageToSend: 0, - startTime: new Date(), - }); - const previousAttempts = this.attempts - 1; - const initialMetadata = this.initialMetadata.clone(); - if (previousAttempts > 0) { - initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - let receivedMetadata = false; - child.start(initialMetadata, { - onReceiveMetadata: metadata => { - this.trace('Received metadata from child [' + child.getCallNumber() + ']'); - this.commitCall(index); - receivedMetadata = true; - if (previousAttempts > 0) { - metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - if (this.underlyingCalls[index].state === 'ACTIVE') { - this.listener.onReceiveMetadata(metadata); - } - }, - onReceiveMessage: message => { - this.trace('Received message from child [' + child.getCallNumber() + ']'); - this.commitCall(index); - if (this.underlyingCalls[index].state === 'ACTIVE') { - this.listener.onReceiveMessage(message); - } - }, - onReceiveStatus: status => { - this.trace('Received status from child [' + child.getCallNumber() + ']'); - if (!receivedMetadata && previousAttempts > 0) { - status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - this.handleChildStatus(status, index); - }, - }); - this.sendNextChildMessage(index); - if (this.readStarted) { - child.startRead(); - } - } - start(metadata, listener) { - this.trace('start called'); - this.listener = listener; - this.initialMetadata = metadata; - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - handleChildWriteCompleted(childIndex) { - var _a, _b; - const childCall = this.underlyingCalls[childIndex]; - const messageIndex = childCall.nextMessageToSend; - (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a); - this.clearSentMessages(); - childCall.nextMessageToSend += 1; - this.sendNextChildMessage(childIndex); - } - sendNextChildMessage(childIndex) { - const childCall = this.underlyingCalls[childIndex]; - if (childCall.state === 'COMPLETED') { - return; - } - if (this.getBufferEntry(childCall.nextMessageToSend)) { - const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend); - switch (bufferEntry.entryType) { - case 'MESSAGE': - childCall.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(childIndex); - }, - }, bufferEntry.message.message); - break; - case 'HALF_CLOSE': - childCall.nextMessageToSend += 1; - childCall.call.halfClose(); - break; - case 'FREED': - // Should not be possible - break; - } - } - } - sendMessageWithContext(context, message) { - var _a; - this.trace('write() called with message of length ' + message.length); - const writeObj = { - message, - flags: context.flags, - }; - const messageIndex = this.getNextBufferIndex(); - const bufferEntry = { - entryType: 'MESSAGE', - message: writeObj, - allocated: this.bufferTracker.allocate(message.length, this.callNumber), - }; - this.writeBuffer.push(bufferEntry); - if (bufferEntry.allocated) { - (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); - for (const [callIndex, call] of this.underlyingCalls.entries()) { - if (call.state === 'ACTIVE' && - call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(callIndex); - }, - }, message); - } - } - } - else { - this.commitCallWithMostMessages(); - // commitCallWithMostMessages can fail if we are between ping attempts - if (this.committedCallIndex === null) { - return; - } - const call = this.underlyingCalls[this.committedCallIndex]; - bufferEntry.callback = context.callback; - if (call.state === 'ACTIVE' && call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(this.committedCallIndex); - }, - }, message); - } - } - } - startRead() { - this.trace('startRead called'); - this.readStarted = true; - for (const underlyingCall of this.underlyingCalls) { - if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === 'ACTIVE') { - underlyingCall.call.startRead(); - } - } - } - halfClose() { - this.trace('halfClose called'); - const halfCloseIndex = this.getNextBufferIndex(); - this.writeBuffer.push({ - entryType: 'HALF_CLOSE', - allocated: false, - }); - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE' && - call.nextMessageToSend === halfCloseIndex) { - call.nextMessageToSend += 1; - call.call.halfClose(); - } - } - } - setCredentials(newCredentials) { - throw new Error('Method not implemented.'); - } - getMethod() { - return this.methodName; - } - getHost() { - return this.host; - } - getAuthContext() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getAuthContext(); - } - else { - return null; - } - } -} -exports.RetryingCall = RetryingCall; -//# sourceMappingURL=retrying-call.js.map - -/***/ }), - -/***/ 62533: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = void 0; -exports.serverErrorToStatus = serverErrorToStatus; -const events_1 = __nccwpck_require__(82361); -const stream_1 = __nccwpck_require__(12781); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -function serverErrorToStatus(error, overrideTrailers) { - var _a; - const status = { - code: constants_1.Status.UNKNOWN, - details: 'message' in error ? error.message : 'Unknown Error', - metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error.metadata) !== null && _a !== void 0 ? _a : null, - }; - if ('code' in error && - typeof error.code === 'number' && - Number.isInteger(error.code)) { - status.code = error.code; - if ('details' in error && typeof error.details === 'string') { - status.details = error.details; - } - } - return status; -} -class ServerUnaryCallImpl extends events_1.EventEmitter { - constructor(path, call, metadata, request) { - super(); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request; - this.cancelled = false; - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } -} -exports.ServerUnaryCallImpl = ServerUnaryCallImpl; -class ServerReadableStreamImpl extends stream_1.Readable { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.cancelled = false; - } - _read(size) { - this.call.startRead(); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } -} -exports.ServerReadableStreamImpl = ServerReadableStreamImpl; -class ServerWritableStreamImpl extends stream_1.Writable { - constructor(path, call, metadata, request) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request; - this.pendingStatus = { - code: constants_1.Status.OK, - details: 'OK', - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on('error', err => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _write(chunk, encoding, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } -} -exports.ServerWritableStreamImpl = ServerWritableStreamImpl; -class ServerDuplexStreamImpl extends stream_1.Duplex { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.pendingStatus = { - code: constants_1.Status.OK, - details: 'OK', - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on('error', err => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _read(size) { - this.call.startRead(); - } - _write(chunk, encoding, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } -} -exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl; -//# sourceMappingURL=server-call.js.map - -/***/ }), - -/***/ 63828: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ServerCredentials = void 0; -exports.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials; -exports.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors; -const tls_helpers_1 = __nccwpck_require__(86581); -class ServerCredentials { - constructor(serverConstructorOptions, contextOptions) { - this.serverConstructorOptions = serverConstructorOptions; - this.watchers = new Set(); - this.latestContextOptions = null; - this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null; - } - _addWatcher(watcher) { - this.watchers.add(watcher); - } - _removeWatcher(watcher) { - this.watchers.delete(watcher); - } - getWatcherCount() { - return this.watchers.size; - } - updateSecureContextOptions(options) { - this.latestContextOptions = options; - for (const watcher of this.watchers) { - watcher(this.latestContextOptions); - } - } - _isSecure() { - return this.serverConstructorOptions !== null; - } - _getSecureContextOptions() { - return this.latestContextOptions; - } - _getConstructorOptions() { - return this.serverConstructorOptions; - } - _getInterceptors() { - return []; - } - static createInsecure() { - return new InsecureServerCredentials(); - } - static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { - var _a; - if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { - throw new TypeError('rootCerts must be null or a Buffer'); - } - if (!Array.isArray(keyCertPairs)) { - throw new TypeError('keyCertPairs must be an array'); - } - if (typeof checkClientCertificate !== 'boolean') { - throw new TypeError('checkClientCertificate must be a boolean'); - } - const cert = []; - const key = []; - for (let i = 0; i < keyCertPairs.length; i++) { - const pair = keyCertPairs[i]; - if (pair === null || typeof pair !== 'object') { - throw new TypeError(`keyCertPair[${i}] must be an object`); - } - if (!Buffer.isBuffer(pair.private_key)) { - throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); - } - if (!Buffer.isBuffer(pair.cert_chain)) { - throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); - } - cert.push(pair.cert_chain); - key.push(pair.private_key); - } - return new SecureServerCredentials({ - requestCert: checkClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES, - }, { - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, - cert, - key, - }); - } -} -exports.ServerCredentials = ServerCredentials; -class InsecureServerCredentials extends ServerCredentials { - constructor() { - super(null); - } - _getSettings() { - return null; - } - _equals(other) { - return other instanceof InsecureServerCredentials; - } -} -class SecureServerCredentials extends ServerCredentials { - constructor(constructorOptions, contextOptions) { - super(constructorOptions, contextOptions); - this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions); - } - /** - * Checks equality by checking the options that are actually set by - * createSsl. - * @param other - * @returns - */ - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof SecureServerCredentials)) { - return false; - } - // options.ca equality check - if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { - if (!this.options.ca.equals(other.options.ca)) { - return false; - } - } - else { - if (this.options.ca !== other.options.ca) { - return false; - } - } - // options.cert equality check - if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { - if (this.options.cert.length !== other.options.cert.length) { - return false; - } - for (let i = 0; i < this.options.cert.length; i++) { - const thisCert = this.options.cert[i]; - const otherCert = other.options.cert[i]; - if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { - if (!thisCert.equals(otherCert)) { - return false; - } - } - else { - if (thisCert !== otherCert) { - return false; - } - } - } - } - else { - if (this.options.cert !== other.options.cert) { - return false; - } - } - // options.key equality check - if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { - if (this.options.key.length !== other.options.key.length) { - return false; - } - for (let i = 0; i < this.options.key.length; i++) { - const thisKey = this.options.key[i]; - const otherKey = other.options.key[i]; - if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { - if (!thisKey.equals(otherKey)) { - return false; - } - } - else { - if (thisKey !== otherKey) { - return false; - } - } - } - } - else { - if (this.options.key !== other.options.key) { - return false; - } - } - // options.requestCert equality check - if (this.options.requestCert !== other.options.requestCert) { - return false; - } - /* ciphers is derived from a value that is constant for the process, so no - * equality check is needed. */ - return true; - } -} -class CertificateProviderServerCredentials extends ServerCredentials { - constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) { - super({ - requestCert: caCertificateProvider !== null, - rejectUnauthorized: requireClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - this.identityCertificateProvider = identityCertificateProvider; - this.caCertificateProvider = caCertificateProvider; - this.requireClientCertificate = requireClientCertificate; - this.latestCaUpdate = null; - this.latestIdentityUpdate = null; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - } - _addWatcher(watcher) { - var _a; - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.addCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - super._addWatcher(watcher); - } - _removeWatcher(watcher) { - var _a; - super._removeWatcher(watcher); - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof CertificateProviderServerCredentials)) { - return false; - } - return (this.caCertificateProvider === other.caCertificateProvider && - this.identityCertificateProvider === other.identityCertificateProvider && - this.requireClientCertificate === other.requireClientCertificate); - } - calculateSecureContextOptions() { - var _a; - if (this.latestIdentityUpdate === null) { - return null; - } - if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { - return null; - } - return { - ca: (_a = this.latestCaUpdate) === null || _a === void 0 ? void 0 : _a.caCertificate, - cert: [this.latestIdentityUpdate.certificate], - key: [this.latestIdentityUpdate.privateKey], - }; - } - finalizeUpdate() { - const secureContextOptions = this.calculateSecureContextOptions(); - this.updateSecureContextOptions(secureContextOptions); - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.finalizeUpdate(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.finalizeUpdate(); - } -} -function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) { - return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate); -} -class InterceptorServerCredentials extends ServerCredentials { - constructor(childCredentials, interceptors) { - super({}); - this.childCredentials = childCredentials; - this.interceptors = interceptors; - } - _isSecure() { - return this.childCredentials._isSecure(); - } - _equals(other) { - if (!(other instanceof InterceptorServerCredentials)) { - return false; - } - if (!(this.childCredentials._equals(other.childCredentials))) { - return false; - } - if (this.interceptors.length !== other.interceptors.length) { - return false; - } - for (let i = 0; i < this.interceptors.length; i++) { - if (this.interceptors[i] !== other.interceptors[i]) { - return false; - } - } - return true; - } - _getInterceptors() { - return this.interceptors; - } - _addWatcher(watcher) { - this.childCredentials._addWatcher(watcher); - } - _removeWatcher(watcher) { - this.childCredentials._removeWatcher(watcher); - } - _getConstructorOptions() { - return this.childCredentials._getConstructorOptions(); - } - _getSecureContextOptions() { - return this.childCredentials._getSecureContextOptions(); - } -} -function createServerCredentialsWithInterceptors(credentials, interceptors) { - return new InterceptorServerCredentials(credentials, interceptors); -} -//# sourceMappingURL=server-credentials.js.map - -/***/ }), - -/***/ 20998: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2024 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseServerInterceptingCall = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = void 0; -exports.isInterceptingServerListener = isInterceptingServerListener; -exports.getServerInterceptingCall = getServerInterceptingCall; -const metadata_1 = __nccwpck_require__(83665); -const constants_1 = __nccwpck_require__(90634); -const http2 = __nccwpck_require__(85158); -const error_1 = __nccwpck_require__(22336); -const zlib = __nccwpck_require__(59796); -const stream_decoder_1 = __nccwpck_require__(16575); -const logging = __nccwpck_require__(35993); -const tls_1 = __nccwpck_require__(24404); -const orca_1 = __nccwpck_require__(31791); -const TRACER_NAME = 'server_call'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -class ServerListenerBuilder { - constructor() { - this.metadata = undefined; - this.message = undefined; - this.halfClose = undefined; - this.cancel = undefined; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveHalfClose(onReceiveHalfClose) { - this.halfClose = onReceiveHalfClose; - return this; - } - withOnCancel(onCancel) { - this.cancel = onCancel; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveHalfClose: this.halfClose, - onCancel: this.cancel, - }; - } -} -exports.ServerListenerBuilder = ServerListenerBuilder; -function isInterceptingServerListener(listener) { - return (listener.onReceiveMetadata !== undefined && - listener.onReceiveMetadata.length === 1); -} -class InterceptingServerListenerImpl { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - /** - * Once the call is cancelled, ignore all other events. - */ - this.cancelled = false; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.pendingMessage = null; - this.processingMessage = false; - this.hasPendingHalfClose = false; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingHalfClose() { - if (this.hasPendingHalfClose) { - this.nextListener.onReceiveHalfClose(); - this.hasPendingHalfClose = false; - } - } - onReceiveMetadata(metadata) { - if (this.cancelled) { - return; - } - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, interceptedMetadata => { - this.processingMetadata = false; - if (this.cancelled) { - return; - } - this.nextListener.onReceiveMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - onReceiveMessage(message) { - if (this.cancelled) { - return; - } - this.processingMessage = true; - this.listener.onReceiveMessage(message, msg => { - this.processingMessage = false; - if (this.cancelled) { - return; - } - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } - else { - this.nextListener.onReceiveMessage(msg); - this.processPendingHalfClose(); - } - }); - } - onReceiveHalfClose() { - if (this.cancelled) { - return; - } - this.listener.onReceiveHalfClose(() => { - if (this.cancelled) { - return; - } - if (this.processingMetadata || this.processingMessage) { - this.hasPendingHalfClose = true; - } - else { - this.nextListener.onReceiveHalfClose(); - } - }); - } - onCancel() { - this.cancelled = true; - this.listener.onCancel(); - this.nextListener.onCancel(); - } -} -class ResponderBuilder { - constructor() { - this.start = undefined; - this.metadata = undefined; - this.message = undefined; - this.status = undefined; - } - withStart(start) { - this.start = start; - return this; - } - withSendMetadata(sendMetadata) { - this.metadata = sendMetadata; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withSendStatus(sendStatus) { - this.status = sendStatus; - return this; - } - build() { - return { - start: this.start, - sendMetadata: this.metadata, - sendMessage: this.message, - sendStatus: this.status, - }; - } -} -exports.ResponderBuilder = ResponderBuilder; -const defaultServerListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveHalfClose: next => { - next(); - }, - onCancel: () => { }, -}; -const defaultResponder = { - start: next => { - next(); - }, - sendMetadata: (metadata, next) => { - next(metadata); - }, - sendMessage: (message, next) => { - next(message); - }, - sendStatus: (status, next) => { - next(status); - }, -}; -class ServerInterceptingCall { - constructor(nextCall, responder) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - this.processingMetadata = false; - this.sentMetadata = false; - this.processingMessage = false; - this.pendingMessage = null; - this.pendingMessageCallback = null; - this.pendingStatus = null; - this.responder = { - start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start, - sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata, - sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage, - sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus, - }; - } - processPendingMessage() { - if (this.pendingMessageCallback) { - this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); - this.pendingMessage = null; - this.pendingMessageCallback = null; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextCall.sendStatus(this.pendingStatus); - this.pendingStatus = null; - } - } - start(listener) { - this.responder.start(interceptedListener => { - var _a, _b, _c, _d; - const fullInterceptedListener = { - onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata, - onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage, - onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose, - onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel, - }; - const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); - this.nextCall.start(finalInterceptingListener); - }); - } - sendMetadata(metadata) { - this.processingMetadata = true; - this.sentMetadata = true; - this.responder.sendMetadata(metadata, interceptedMetadata => { - this.processingMetadata = false; - this.nextCall.sendMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - sendMessage(message, callback) { - this.processingMessage = true; - if (!this.sentMetadata) { - this.sendMetadata(new metadata_1.Metadata()); - } - this.responder.sendMessage(message, interceptedMessage => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = interceptedMessage; - this.pendingMessageCallback = callback; - } - else { - this.nextCall.sendMessage(interceptedMessage, callback); - } - }); - } - sendStatus(status) { - this.responder.sendStatus(status, interceptedStatus => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = interceptedStatus; - } - else { - this.nextCall.sendStatus(interceptedStatus); - } - }); - } - startRead() { - this.nextCall.startRead(); - } - getPeer() { - return this.nextCall.getPeer(); - } - getDeadline() { - return this.nextCall.getDeadline(); - } - getHost() { - return this.nextCall.getHost(); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } - getConnectionInfo() { - return this.nextCall.getConnectionInfo(); - } - getMetricsRecorder() { - return this.nextCall.getMetricsRecorder(); - } -} -exports.ServerInterceptingCall = ServerInterceptingCall; -const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding'; -const GRPC_ENCODING_HEADER = 'grpc-encoding'; -const GRPC_MESSAGE_HEADER = 'grpc-message'; -const GRPC_STATUS_HEADER = 'grpc-status'; -const GRPC_TIMEOUT_HEADER = 'grpc-timeout'; -const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; -const deadlineUnitsToMs = { - H: 3600000, - M: 60000, - S: 1000, - m: 1, - u: 0.001, - n: 0.000001, -}; -const defaultCompressionHeaders = { - // TODO(cjihrig): Remove these encoding headers from the default response - // once compression is integrated. - [GRPC_ACCEPT_ENCODING_HEADER]: 'identity,deflate,gzip', - [GRPC_ENCODING_HEADER]: 'identity', -}; -const defaultResponseHeaders = { - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, - [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', -}; -const defaultResponseOptions = { - waitForTrailers: true, -}; -class BaseServerInterceptingCall { - constructor(stream, headers, callEventTracker, handler, options) { - var _a, _b; - this.stream = stream; - this.callEventTracker = callEventTracker; - this.handler = handler; - this.listener = null; - this.deadlineTimer = null; - this.deadline = Infinity; - this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.cancelled = false; - this.metadataSent = false; - this.wantTrailers = false; - this.cancelNotified = false; - this.incomingEncoding = 'identity'; - this.readQueue = []; - this.isReadPending = false; - this.receivedHalfClose = false; - this.streamEnded = false; - this.metricsRecorder = new orca_1.PerRequestMetricRecorder(); - this.stream.once('error', (err) => { - /* We need an error handler to avoid uncaught error event exceptions, but - * there is nothing we can reasonably do here. Any error event should - * have a corresponding close event, which handles emitting the cancelled - * event. And the stream is now in a bad state, so we can't reasonably - * expect to be able to send an error over it. */ - }); - this.stream.once('close', () => { - var _a; - trace('Request to method ' + - ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + - ' stream closed with rstCode ' + - this.stream.rstCode); - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(false); - this.callEventTracker.onCallEnd({ - code: constants_1.Status.CANCELLED, - details: 'Stream closed before sending status', - metadata: null, - }); - } - this.notifyOnCancel(); - }); - this.stream.on('data', (data) => { - this.handleDataFrame(data); - }); - this.stream.pause(); - this.stream.on('end', () => { - this.handleEndEvent(); - }); - if ('grpc.max_send_message_length' in options) { - this.maxSendMessageSize = options['grpc.max_send_message_length']; - } - if ('grpc.max_receive_message_length' in options) { - this.maxReceiveMessageSize = options['grpc.max_receive_message_length']; - } - this.host = (_a = headers[':authority']) !== null && _a !== void 0 ? _a : headers.host; - this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize); - const metadata = metadata_1.Metadata.fromHttp2Headers(headers); - if (logging.isTracerEnabled(TRACER_NAME)) { - trace('Request to ' + - this.handler.path + - ' received headers ' + - JSON.stringify(metadata.toJSON())); - } - const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); - if (timeoutHeader.length > 0) { - this.handleTimeoutHeader(timeoutHeader[0]); - } - const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); - if (encodingHeader.length > 0) { - this.incomingEncoding = encodingHeader[0]; - } - // Remove several headers that should not be propagated to the application - metadata.remove(GRPC_TIMEOUT_HEADER); - metadata.remove(GRPC_ENCODING_HEADER); - metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); - metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); - metadata.remove(http2.constants.HTTP2_HEADER_TE); - metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); - this.metadata = metadata; - const socket = (_b = stream.session) === null || _b === void 0 ? void 0 : _b.socket; - this.connectionInfo = { - localAddress: socket === null || socket === void 0 ? void 0 : socket.localAddress, - localPort: socket === null || socket === void 0 ? void 0 : socket.localPort, - remoteAddress: socket === null || socket === void 0 ? void 0 : socket.remoteAddress, - remotePort: socket === null || socket === void 0 ? void 0 : socket.remotePort - }; - this.shouldSendMetrics = !!options['grpc.server_call_metric_recording']; - } - handleTimeoutHeader(timeoutHeader) { - const match = timeoutHeader.toString().match(DEADLINE_REGEX); - if (match === null) { - const status = { - code: constants_1.Status.INTERNAL, - details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, - metadata: null, - }; - // Wait for the constructor to complete before sending the error. - process.nextTick(() => { - this.sendStatus(status); - }); - return; - } - const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0; - const now = new Date(); - this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); - this.deadlineTimer = setTimeout(() => { - const status = { - code: constants_1.Status.DEADLINE_EXCEEDED, - details: 'Deadline exceeded', - metadata: null, - }; - this.sendStatus(status); - }, timeout); - } - checkCancelled() { - /* In some cases the stream can become destroyed before the close event - * fires. That creates a race condition that this check works around */ - if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { - this.notifyOnCancel(); - this.cancelled = true; - } - return this.cancelled; - } - notifyOnCancel() { - if (this.cancelNotified) { - return; - } - this.cancelNotified = true; - this.cancelled = true; - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel(); - }); - if (this.deadlineTimer) { - clearTimeout(this.deadlineTimer); - } - // Flush incoming data frames - this.stream.resume(); - } - /** - * A server handler can start sending messages without explicitly sending - * metadata. In that case, we need to send headers before sending any - * messages. This function does that if necessary. - */ - maybeSendMetadata() { - if (!this.metadataSent) { - this.sendMetadata(new metadata_1.Metadata()); - } - } - /** - * Serialize a message to a length-delimited byte string. - * @param value - * @returns - */ - serializeMessage(value) { - const messageBuffer = this.handler.serialize(value); - const byteLength = messageBuffer.byteLength; - const output = Buffer.allocUnsafe(byteLength + 5); - /* Note: response compression is currently not supported, so this - * compressed bit is always 0. */ - output.writeUInt8(0, 0); - output.writeUInt32BE(byteLength, 1); - messageBuffer.copy(output, 5); - return output; - } - decompressMessage(message, encoding) { - const messageContents = message.subarray(5); - if (encoding === 'identity') { - return messageContents; - } - else if (encoding === 'deflate' || encoding === 'gzip') { - let decompresser; - if (encoding === 'deflate') { - decompresser = zlib.createInflate(); - } - else { - decompresser = zlib.createGunzip(); - } - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(messageContents); - decompresser.end(); - }); - } - else { - return Promise.reject({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received message compressed with unsupported encoding "${encoding}"`, - }); - } - } - async decompressAndMaybePush(queueEntry) { - if (queueEntry.type !== 'COMPRESSED') { - throw new Error(`Invalid queue entry type: ${queueEntry.type}`); - } - const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; - const compressedMessageEncoding = compressed - ? this.incomingEncoding - : 'identity'; - let decompressedMessage; - try { - decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); - } - catch (err) { - this.sendStatus(err); - return; - } - try { - queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); - } - catch (err) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error deserializing request: ${err.message}`, - }); - return; - } - queueEntry.type = 'READABLE'; - this.maybePushNextMessage(); - } - maybePushNextMessage() { - if (this.listener && - this.isReadPending && - this.readQueue.length > 0 && - this.readQueue[0].type !== 'COMPRESSED') { - this.isReadPending = false; - const nextQueueEntry = this.readQueue.shift(); - if (nextQueueEntry.type === 'READABLE') { - this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); - } - else { - // nextQueueEntry.type === 'HALF_CLOSE' - this.listener.onReceiveHalfClose(); - } - } - } - handleDataFrame(data) { - var _a; - if (this.checkCancelled()) { - return; - } - trace('Request to ' + - this.handler.path + - ' received data frame of size ' + - data.length); - let rawMessages; - try { - rawMessages = this.decoder.write(data); - } - catch (e) { - this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message }); - return; - } - for (const messageBytes of rawMessages) { - this.stream.pause(); - const queueEntry = { - type: 'COMPRESSED', - compressedMessage: messageBytes, - parsedMessage: null, - }; - this.readQueue.push(queueEntry); - this.decompressAndMaybePush(queueEntry); - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived(); - } - } - handleEndEvent() { - this.readQueue.push({ - type: 'HALF_CLOSE', - compressedMessage: null, - parsedMessage: null, - }); - this.receivedHalfClose = true; - this.maybePushNextMessage(); - } - start(listener) { - trace('Request to ' + this.handler.path + ' start called'); - if (this.checkCancelled()) { - return; - } - this.listener = listener; - listener.onReceiveMetadata(this.metadata); - } - sendMetadata(metadata) { - if (this.checkCancelled()) { - return; - } - if (this.metadataSent) { - return; - } - this.metadataSent = true; - const custom = metadata ? metadata.toHttp2Headers() : null; - const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); - this.stream.respond(headers, defaultResponseOptions); - } - sendMessage(message, callback) { - if (this.checkCancelled()) { - return; - } - let response; - try { - response = this.serializeMessage(message); - } - catch (e) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, - metadata: null, - }); - return; - } - if (this.maxSendMessageSize !== -1 && - response.length - 5 > this.maxSendMessageSize) { - this.sendStatus({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, - metadata: null, - }); - return; - } - this.maybeSendMetadata(); - trace('Request to ' + - this.handler.path + - ' sent data frame of size ' + - response.length); - this.stream.write(response, error => { - var _a; - if (error) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`, - metadata: null, - }); - return; - } - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent(); - callback(); - }); - } - sendStatus(status) { - var _a, _b, _c; - if (this.checkCancelled()) { - return; - } - trace('Request to method ' + - ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + - ' ended with status code: ' + - constants_1.Status[status.code] + - ' details: ' + - status.details); - const statusMetadata = (_c = (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.clone()) !== null && _c !== void 0 ? _c : new metadata_1.Metadata(); - if (this.shouldSendMetrics) { - statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); - } - if (this.metadataSent) { - if (!this.wantTrailers) { - this.wantTrailers = true; - this.stream.once('wantTrailers', () => { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers()); - this.stream.sendTrailers(trailersToSend); - this.notifyOnCancel(); - }); - this.stream.end(); - } - else { - this.notifyOnCancel(); - } - } - else { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - // Trailers-only response - const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers()); - this.stream.respond(trailersToSend, { endStream: true }); - this.notifyOnCancel(); - } - } - startRead() { - trace('Request to ' + this.handler.path + ' startRead called'); - if (this.checkCancelled()) { - return; - } - this.isReadPending = true; - if (this.readQueue.length === 0) { - if (!this.receivedHalfClose) { - this.stream.resume(); - } - } - else { - this.maybePushNextMessage(); - } - } - getPeer() { - var _a; - const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket; - if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) { - if (socket.remotePort) { - return `${socket.remoteAddress}:${socket.remotePort}`; - } - else { - return socket.remoteAddress; - } - } - else { - return 'unknown'; - } - } - getDeadline() { - return this.deadline; - } - getHost() { - return this.host; - } - getAuthContext() { - var _a; - if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { - const peerCertificate = this.stream.session.socket.getPeerCertificate(); - return { - transportSecurityType: 'ssl', - sslPeerCertificate: peerCertificate.raw ? peerCertificate : undefined - }; - } - else { - return {}; - } - } - getConnectionInfo() { - return this.connectionInfo; - } - getMetricsRecorder() { - return this.metricsRecorder; - } -} -exports.BaseServerInterceptingCall = BaseServerInterceptingCall; -function getServerInterceptingCall(interceptors, stream, headers, callEventTracker, handler, options) { - const methodDefinition = { - path: handler.path, - requestStream: handler.type === 'clientStream' || handler.type === 'bidi', - responseStream: handler.type === 'serverStream' || handler.type === 'bidi', - requestDeserialize: handler.deserialize, - responseSerialize: handler.serialize, - }; - const baseCall = new BaseServerInterceptingCall(stream, headers, callEventTracker, handler, options); - return interceptors.reduce((call, interceptor) => { - return interceptor(methodDefinition, call); - }, baseCall); -} -//# sourceMappingURL=server-interceptors.js.map - -/***/ }), - -/***/ 33389: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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 __runInitializers = (this && this.__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; -}; -var __esDecorate = (this && this.__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; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Server = void 0; -const http2 = __nccwpck_require__(85158); -const util = __nccwpck_require__(73837); -const constants_1 = __nccwpck_require__(90634); -const server_call_1 = __nccwpck_require__(62533); -const server_credentials_1 = __nccwpck_require__(63828); -const resolver_1 = __nccwpck_require__(31594); -const logging = __nccwpck_require__(35993); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const channelz_1 = __nccwpck_require__(79975); -const server_interceptors_1 = __nccwpck_require__(20998); -const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); -const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); -const KEEPALIVE_TIMEOUT_MS = 20000; -const MAX_CONNECTION_IDLE_MS = ~(1 << 31); -const { HTTP2_HEADER_PATH } = http2.constants; -const TRACER_NAME = 'server'; -const kMaxAge = Buffer.from('max_age'); -function serverCallTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'server_call', text); -} -function noop() { } -/** - * Decorator to wrap a class method with util.deprecate - * @param message The message to output if the deprecated method is called - * @returns - */ -function deprecate(message) { - return function (target, context) { - return util.deprecate(target, message); - }; -} -function getUnimplementedStatusResponse(methodName) { - return { - code: constants_1.Status.UNIMPLEMENTED, - details: `The server does not implement the method ${methodName}`, - }; -} -function getDefaultHandler(handlerType, methodName) { - const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); - switch (handlerType) { - case 'unary': - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case 'clientStream': - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case 'serverStream': - return (call) => { - call.emit('error', unimplementedStatusResponse); - }; - case 'bidi': - return (call) => { - call.emit('error', unimplementedStatusResponse); - }; - default: - throw new Error(`Invalid handlerType ${handlerType}`); - } -} -let Server = (() => { - var _a; - let _instanceExtraInitializers = []; - let _start_decorators; - return _a = class Server { - constructor(options) { - var _b, _c, _d, _e, _f, _g; - this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), new Map()); - this.http2Servers = new Map(); - this.sessionIdleTimeouts = new Map(); - this.handlers = new Map(); - this.sessions = new Map(); - /** - * This field only exists to ensure that the start method throws an error if - * it is called twice, as it did previously. - */ - this.started = false; - this.shutdown = false; - this.serverAddressString = 'null'; - // Channelz Info - this.channelzEnabled = true; - this.options = options !== null && options !== void 0 ? options : {}; - if (this.options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - } - else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzServer)('server', () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace('CT_INFO', 'Server created'); - this.maxConnectionAgeMs = - (_b = this.options['grpc.max_connection_age_ms']) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS; - this.maxConnectionAgeGraceMs = - (_c = this.options['grpc.max_connection_age_grace_ms']) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS; - this.keepaliveTimeMs = - (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS; - this.keepaliveTimeoutMs = - (_e = this.options['grpc.keepalive_timeout_ms']) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS; - this.sessionIdleTimeout = - (_f = this.options['grpc.max_connection_idle_ms']) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS; - this.commonServerOptions = { - maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, - }; - if ('grpc-node.max_session_memory' in this.options) { - this.commonServerOptions.maxSessionMemory = - this.options['grpc-node.max_session_memory']; - } - else { - /* By default, set a very large max session memory limit, to effectively - * disable enforcement of the limit. Some testing indicates that Node's - * behavior degrades badly when this limit is reached, so we solve that - * by disabling the check entirely. */ - this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; - } - if ('grpc.max_concurrent_streams' in this.options) { - this.commonServerOptions.settings = { - maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], - }; - } - this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : []; - this.trace('Server constructed'); - } - getChannelzInfo() { - return { - trace: this.channelzTrace, - callTracker: this.callTracker, - listenerChildren: this.listenerChildrenTracker.getChildLists(), - sessionChildren: this.sessionChildrenTracker.getChildLists(), - }; - } - getChannelzSessionInfo(session) { - var _b, _c, _d; - const sessionInfo = this.sessions.get(session); - const sessionSocket = session.socket; - const remoteAddress = sessionSocket.remoteAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) - : null; - const localAddress = sessionSocket.localAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) - : null; - let tlsInfo; - if (session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && 'raw' in peerCertificate - ? peerCertificate.raw - : null, - }; - } - else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress: remoteAddress, - localAddress: localAddress, - security: tlsInfo, - remoteName: null, - streamsStarted: sessionInfo.streamTracker.callsStarted, - streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, - streamsFailed: sessionInfo.streamTracker.callsFailed, - messagesSent: sessionInfo.messagesSent, - messagesReceived: sessionInfo.messagesReceived, - keepAlivesSent: sessionInfo.keepAlivesSent, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, - lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, - localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null, - remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null, - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + this.channelzRef.id + ') ' + text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + this.channelzRef.id + ') ' + text); - } - addProtoService() { - throw new Error('Not implemented. Use addService() instead'); - } - addService(service, implementation) { - if (service === null || - typeof service !== 'object' || - implementation === null || - typeof implementation !== 'object') { - throw new Error('addService() requires two objects as arguments'); - } - const serviceKeys = Object.keys(service); - if (serviceKeys.length === 0) { - throw new Error('Cannot add an empty service to a server'); - } - serviceKeys.forEach(name => { - const attrs = service[name]; - let methodType; - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = 'bidi'; - } - else { - methodType = 'clientStream'; - } - } - else { - if (attrs.responseStream) { - methodType = 'serverStream'; - } - else { - methodType = 'unary'; - } - } - let implFn = implementation[name]; - let impl; - if (implFn === undefined && typeof attrs.originalName === 'string') { - implFn = implementation[attrs.originalName]; - } - if (implFn !== undefined) { - impl = implFn.bind(implementation); - } - else { - impl = getDefaultHandler(methodType, name); - } - const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); - if (success === false) { - throw new Error(`Method handler for ${attrs.path} already provided.`); - } - }); - } - removeService(service) { - if (service === null || typeof service !== 'object') { - throw new Error('removeService() requires object as argument'); - } - const serviceKeys = Object.keys(service); - serviceKeys.forEach(name => { - const attrs = service[name]; - this.unregister(attrs.path); - }); - } - bind(port, creds) { - throw new Error('Not implemented. Use bindAsync() instead'); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param boundAddress - * @returns - */ - experimentalRegisterListenerToChannelz(boundAddress) { - return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { - return { - localAddress: boundAddress, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null, - }; - }, this.channelzEnabled); - } - experimentalUnregisterListenerFromChannelz(channelzRef) { - (0, channelz_1.unregisterChannelzRef)(channelzRef); - } - createHttp2Server(credentials) { - let http2Server; - if (credentials._isSecure()) { - const constructorOptions = credentials._getConstructorOptions(); - const contextOptions = credentials._getSecureContextOptions(); - const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options['grpc-node.tls_enable_trace'] === 1 }); - let areCredentialsValid = contextOptions !== null; - this.trace('Initial credentials valid: ' + areCredentialsValid); - http2Server = http2.createSecureServer(secureServerOptions); - http2Server.prependListener('connection', (socket) => { - if (!areCredentialsValid) { - this.trace('Dropped connection from ' + JSON.stringify(socket.address()) + ' due to unloaded credentials'); - socket.destroy(); - } - }); - http2Server.on('secureConnection', (socket) => { - /* These errors need to be handled by the user of Http2SecureServer, - * according to https://github.com/nodejs/node/issues/35824 */ - socket.on('error', (e) => { - this.trace('An incoming TLS connection closed with error: ' + e.message); - }); - }); - const credsWatcher = options => { - if (options) { - const secureServer = http2Server; - try { - secureServer.setSecureContext(options); - } - catch (e) { - logging.log(constants_1.LogVerbosity.ERROR, 'Failed to set secure context with error ' + e.message); - options = null; - } - } - areCredentialsValid = options !== null; - this.trace('Post-update credentials valid: ' + areCredentialsValid); - }; - credentials._addWatcher(credsWatcher); - http2Server.on('close', () => { - credentials._removeWatcher(credsWatcher); - }); - } - else { - http2Server = http2.createServer(this.commonServerOptions); - } - http2Server.setTimeout(0, noop); - this._setupHandlers(http2Server, credentials._getInterceptors()); - return http2Server; - } - bindOneAddress(address, boundPortObject) { - this.trace('Attempting to bind ' + (0, subchannel_address_1.subchannelAddressToString)(address)); - const http2Server = this.createHttp2Server(boundPortObject.credentials); - return new Promise((resolve, reject) => { - const onError = (err) => { - this.trace('Failed to bind ' + - (0, subchannel_address_1.subchannelAddressToString)(address) + - ' with error ' + - err.message); - resolve({ - port: 'port' in address ? address.port : 1, - error: err.message, - }); - }; - http2Server.once('error', onError); - http2Server.listen(address, () => { - const boundAddress = http2Server.address(); - let boundSubchannelAddress; - if (typeof boundAddress === 'string') { - boundSubchannelAddress = { - path: boundAddress, - }; - } - else { - boundSubchannelAddress = { - host: boundAddress.address, - port: boundAddress.port, - }; - } - const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress); - this.listenerChildrenTracker.refChild(channelzRef); - this.http2Servers.set(http2Server, { - channelzRef: channelzRef, - sessions: new Set(), - ownsChannelzRef: true - }); - boundPortObject.listeningServers.add(http2Server); - this.trace('Successfully bound ' + - (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); - resolve({ - port: 'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1, - }); - http2Server.removeListener('error', onError); - }); - }); - } - async bindManyPorts(addressList, boundPortObject) { - if (addressList.length === 0) { - return { - count: 0, - port: 0, - errors: [], - }; - } - if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { - /* If binding to port 0, first try to bind the first address, then bind - * the rest of the address list to the specific port that it binds. */ - const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); - if (firstAddressResult.error) { - /* If the first address fails to bind, try the same operation starting - * from the second item in the list. */ - const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); - return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); - } - else { - const restAddresses = addressList - .slice(1) - .map(address => (0, subchannel_address_1.isTcpSubchannelAddress)(address) - ? { host: address.host, port: firstAddressResult.port } - : address); - const restAddressResult = await Promise.all(restAddresses.map(address => this.bindOneAddress(address, boundPortObject))); - const allResults = [firstAddressResult, ...restAddressResult]; - return { - count: allResults.filter(result => result.error === undefined).length, - port: firstAddressResult.port, - errors: allResults - .filter(result => result.error) - .map(result => result.error), - }; - } - } - else { - const allResults = await Promise.all(addressList.map(address => this.bindOneAddress(address, boundPortObject))); - return { - count: allResults.filter(result => result.error === undefined).length, - port: allResults[0].port, - errors: allResults - .filter(result => result.error) - .map(result => result.error), - }; - } - } - async bindAddressList(addressList, boundPortObject) { - const bindResult = await this.bindManyPorts(addressList, boundPortObject); - if (bindResult.count > 0) { - if (bindResult.count < addressList.length) { - logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); - } - return bindResult.port; - } - else { - const errorString = `No address added out of total ${addressList.length} resolved`; - logging.log(constants_1.LogVerbosity.ERROR, errorString); - throw new Error(`${errorString} errors: [${bindResult.errors.join(',')}]`); - } - } - resolvePort(port) { - return new Promise((resolve, reject) => { - let seenResolution = false; - const resolverListener = (endpointList, attributes, serviceConfig, resolutionNote) => { - if (seenResolution) { - return true; - } - seenResolution = true; - if (!endpointList.ok) { - reject(new Error(endpointList.error.details)); - return true; - } - const addressList = [].concat(...endpointList.value.map(endpoint => endpoint.addresses)); - if (addressList.length === 0) { - reject(new Error(`No addresses resolved for port ${port}`)); - return true; - } - resolve(addressList); - return true; - }; - const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); - resolver.updateResolution(); - }); - } - async bindPort(port, boundPortObject) { - const addressList = await this.resolvePort(port); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error('bindAsync operation cancelled by unbind call'); - } - const portNumber = await this.bindAddressList(addressList, boundPortObject); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error('bindAsync operation cancelled by unbind call'); - } - return portNumber; - } - normalizePort(port) { - const initialPortUri = (0, uri_parser_1.parseUri)(port); - if (initialPortUri === null) { - throw new Error(`Could not parse port "${port}"`); - } - const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); - if (portUri === null) { - throw new Error(`Could not get a default scheme for port "${port}"`); - } - return portUri; - } - bindAsync(port, creds, callback) { - if (this.shutdown) { - throw new Error('bindAsync called after shutdown'); - } - if (typeof port !== 'string') { - throw new TypeError('port must be a string'); - } - if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - if (typeof callback !== 'function') { - throw new TypeError('callback must be a function'); - } - this.trace('bindAsync port=' + port); - const portUri = this.normalizePort(port); - const deferredCallback = (error, port) => { - process.nextTick(() => callback(error, port)); - }; - /* First, if this port is already bound or that bind operation is in - * progress, use that result. */ - let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - if (!creds._equals(boundPortObject.credentials)) { - deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); - return; - } - /* If that operation has previously been cancelled by an unbind call, - * uncancel it. */ - boundPortObject.cancelled = false; - if (boundPortObject.completionPromise) { - boundPortObject.completionPromise.then(portNum => callback(null, portNum), error => callback(error, 0)); - } - else { - deferredCallback(null, boundPortObject.portNumber); - } - return; - } - boundPortObject = { - mapKey: (0, uri_parser_1.uriToString)(portUri), - originalUri: portUri, - completionPromise: null, - cancelled: false, - portNumber: 0, - credentials: creds, - listeningServers: new Set(), - }; - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - const completionPromise = this.bindPort(portUri, boundPortObject); - boundPortObject.completionPromise = completionPromise; - /* If the port number is 0, defer populating the map entry until after the - * bind operation completes and we have a specific port number. Otherwise, - * populate it immediately. */ - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - completionPromise.then(portNum => { - const finalUri = { - scheme: portUri.scheme, - authority: portUri.authority, - path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }), - }; - boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - callback(null, portNum); - }, error => { - callback(error, 0); - }); - } - else { - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - completionPromise.then(portNum => { - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - callback(null, portNum); - }, error => { - callback(error, 0); - }); - } - } - registerInjectorToChannelz() { - return (0, channelz_1.registerChannelzSocket)('injector', () => { - return { - localAddress: null, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null, - }; - }, this.channelzEnabled); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param credentials - * @param channelzRef - * @returns - */ - experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - if (this.channelzEnabled) { - this.listenerChildrenTracker.refChild(channelzRef); - } - const server = this.createHttp2Server(credentials); - const sessionsSet = new Set(); - this.http2Servers.set(server, { - channelzRef: channelzRef, - sessions: sessionsSet, - ownsChannelzRef - }); - return { - injectConnection: (connection) => { - server.emit('connection', connection); - }, - drain: (graceTimeMs) => { - var _b, _c; - for (const session of sessionsSet) { - this.closeSession(session); - } - (_c = (_b = setTimeout(() => { - for (const session of sessionsSet) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - }, - destroy: () => { - this.closeServer(server); - for (const session of sessionsSet) { - this.closeSession(session); - } - } - }; - } - createConnectionInjector(credentials) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - const channelzRef = this.registerInjectorToChannelz(); - return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); - } - closeServer(server, callback) { - this.trace('Closing server with address ' + JSON.stringify(server.address())); - const serverInfo = this.http2Servers.get(server); - server.close(() => { - if (serverInfo && serverInfo.ownsChannelzRef) { - this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); - (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); - } - this.http2Servers.delete(server); - callback === null || callback === void 0 ? void 0 : callback(); - }); - } - closeSession(session, callback) { - var _b; - this.trace('Closing session initiated by ' + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); - const sessionInfo = this.sessions.get(session); - const closeCallback = () => { - if (sessionInfo) { - this.sessionChildrenTracker.unrefChild(sessionInfo.ref); - (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); - } - callback === null || callback === void 0 ? void 0 : callback(); - }; - if (session.closed) { - queueMicrotask(closeCallback); - } - else { - session.close(closeCallback); - } - } - completeUnbind(boundPortObject) { - for (const server of boundPortObject.listeningServers) { - const serverInfo = this.http2Servers.get(server); - this.closeServer(server, () => { - boundPortObject.listeningServers.delete(server); - }); - if (serverInfo) { - for (const session of serverInfo.sessions) { - this.closeSession(session); - } - } - } - this.boundPorts.delete(boundPortObject.mapKey); - } - /** - * Unbind a previously bound port, or cancel an in-progress bindAsync - * operation. If port 0 was bound, only the actual bound port can be - * unbound. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be unbound as "localhost:54321". - * @param port - */ - unbind(port) { - this.trace('unbind port=' + port); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error('Cannot unbind port 0'); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - this.trace('unbinding ' + - boundPortObject.mapKey + - ' originally bound as ' + - (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); - /* If the bind operation is pending, the cancelled flag will trigger - * the unbind operation later. */ - if (boundPortObject.completionPromise) { - boundPortObject.cancelled = true; - } - else { - this.completeUnbind(boundPortObject); - } - } - } - /** - * Gracefully close all connections associated with a previously bound port. - * After the grace time, forcefully close all remaining open connections. - * - * If port 0 was bound, only the actual bound port can be - * drained. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be drained as "localhost:54321". - * @param port - * @param graceTimeMs - * @returns - */ - drain(port, graceTimeMs) { - var _b, _c; - this.trace('drain port=' + port + ' graceTimeMs=' + graceTimeMs); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error('Cannot drain port 0'); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (!boundPortObject) { - return; - } - const allSessions = new Set(); - for (const http2Server of boundPortObject.listeningServers) { - const serverEntry = this.http2Servers.get(http2Server); - if (serverEntry) { - for (const session of serverEntry.sessions) { - allSessions.add(session); - this.closeSession(session, () => { - allSessions.delete(session); - }); - } - } - } - /* After the grace time ends, send another goaway to all remaining sessions - * with the CANCEL code. */ - (_c = (_b = setTimeout(() => { - for (const session of allSessions) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - forceShutdown() { - for (const boundPortObject of this.boundPorts.values()) { - boundPortObject.cancelled = true; - } - this.boundPorts.clear(); - // Close the server if it is still running. - for (const server of this.http2Servers.keys()) { - this.closeServer(server); - } - // Always destroy any available sessions. It's possible that one or more - // tryShutdown() calls are in progress. Don't wait on them to finish. - this.sessions.forEach((channelzInfo, session) => { - this.closeSession(session); - // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to - // recognize destroy(code) as a valid signature. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - session.destroy(http2.constants.NGHTTP2_CANCEL); - }); - this.sessions.clear(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.shutdown = true; - } - register(name, handler, serialize, deserialize, type) { - if (this.handlers.has(name)) { - return false; - } - this.handlers.set(name, { - func: handler, - serialize, - deserialize, - type, - path: name, - }); - return true; - } - unregister(name) { - return this.handlers.delete(name); - } - /** - * @deprecated No longer needed as of version 1.10.x - */ - start() { - if (this.http2Servers.size === 0 || - [...this.http2Servers.keys()].every(server => !server.listening)) { - throw new Error('server must be bound in order to start'); - } - if (this.started === true) { - throw new Error('server is already started'); - } - this.started = true; - } - tryShutdown(callback) { - var _b; - const wrappedCallback = (error) => { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - callback(error); - }; - let pendingChecks = 0; - function maybeCallback() { - pendingChecks--; - if (pendingChecks === 0) { - wrappedCallback(); - } - } - this.shutdown = true; - for (const [serverKey, server] of this.http2Servers.entries()) { - pendingChecks++; - const serverString = server.channelzRef.name; - this.trace('Waiting for server ' + serverString + ' to close'); - this.closeServer(serverKey, () => { - this.trace('Server ' + serverString + ' finished closing'); - maybeCallback(); - }); - for (const session of server.sessions.keys()) { - pendingChecks++; - const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress; - this.trace('Waiting for session ' + sessionString + ' to close'); - this.closeSession(session, () => { - this.trace('Session ' + sessionString + ' finished closing'); - maybeCallback(); - }); - } - } - if (pendingChecks === 0) { - wrappedCallback(); - } - } - addHttp2Port() { - throw new Error('Not yet implemented'); - } - /** - * Get the channelz reference object for this server. The returned value is - * garbage if channelz is disabled for this server. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - _verifyContentType(stream, headers) { - const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; - if (typeof contentType !== 'string' || - !contentType.startsWith('application/grpc')) { - stream.respond({ - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, - }, { endStream: true }); - return false; - } - return true; - } - _retrieveHandler(path) { - serverCallTrace('Received call to method ' + - path + - ' at address ' + - this.serverAddressString); - const handler = this.handlers.get(path); - if (handler === undefined) { - serverCallTrace('No handler registered for method ' + - path + - '. Sending UNIMPLEMENTED status.'); - return null; - } - return handler; - } - _respondWithError(err, stream, channelzSessionInfo = null) { - var _b, _c; - const trailersToSend = Object.assign({ 'grpc-status': (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, 'grpc-message': err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto' }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers()); - stream.respond(trailersToSend, { endStream: true }); - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - } - _channelzHandler(extraInterceptors, stream, headers) { - // for handling idle timeout - this.onStreamOpened(stream); - const channelzSessionInfo = this.sessions.get(stream.session); - this.callTracker.addCallStarted(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); - if (!this._verifyContentType(stream, headers)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler = this._retrieveHandler(path); - if (!handler) { - this._respondWithError(getUnimplementedStatusResponse(path), stream, channelzSessionInfo); - return; - } - const callEventTracker = { - addMessageSent: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesSent += 1; - channelzSessionInfo.lastMessageSentTimestamp = new Date(); - } - }, - addMessageReceived: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesReceived += 1; - channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); - } - }, - onCallEnd: status => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } - else { - this.callTracker.addCallFailed(); - } - }, - onStreamEnd: success => { - if (channelzSessionInfo) { - if (success) { - channelzSessionInfo.streamTracker.addCallSucceeded(); - } - else { - channelzSessionInfo.streamTracker.addCallFailed(); - } - } - }, - }; - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, callEventTracker, handler, this.options); - if (!this._runHandlerForCall(call, handler)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler.type}`, - }); - } - } - _streamHandler(extraInterceptors, stream, headers) { - // for handling idle timeout - this.onStreamOpened(stream); - if (this._verifyContentType(stream, headers) !== true) { - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler = this._retrieveHandler(path); - if (!handler) { - this._respondWithError(getUnimplementedStatusResponse(path), stream, null); - return; - } - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, null, handler, this.options); - if (!this._runHandlerForCall(call, handler)) { - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler.type}`, - }); - } - } - _runHandlerForCall(call, handler) { - const { type } = handler; - if (type === 'unary') { - handleUnary(call, handler); - } - else if (type === 'clientStream') { - handleClientStreaming(call, handler); - } - else if (type === 'serverStream') { - handleServerStreaming(call, handler); - } - else if (type === 'bidi') { - handleBidiStreaming(call, handler); - } - else { - return false; - } - return true; - } - _setupHandlers(http2Server, extraInterceptors) { - if (http2Server === null) { - return; - } - const serverAddress = http2Server.address(); - let serverAddressString = 'null'; - if (serverAddress) { - if (typeof serverAddress === 'string') { - serverAddressString = serverAddress; - } - else { - serverAddressString = serverAddress.address + ':' + serverAddress.port; - } - } - this.serverAddressString = serverAddressString; - const handler = this.channelzEnabled - ? this._channelzHandler - : this._streamHandler; - const sessionHandler = this.channelzEnabled - ? this._channelzSessionHandler(http2Server) - : this._sessionHandler(http2Server); - http2Server.on('stream', handler.bind(this, extraInterceptors)); - http2Server.on('session', sessionHandler); - } - _sessionHandler(http2Server) { - return (session) => { - var _b, _c; - (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimer = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - // Apply a random jitter within a +/-10% range - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b, _c; - sessionClosedByServer = true; - this.trace('Connection dropped by max connection age: ' + - ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } - catch (e) { - // The goaway can't be sent because the session is already closed - session.destroy(); - return; - } - session.close(); - /* Allow a grace period after sending the GOAWAY before forcibly - * closing the connection. */ - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_c = connectionAgeGraceTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimer) { - clearTimeout(keepaliveTimer); - keepaliveTimer = null; - } - }; - const canSendPing = () => { - return (!session.destroyed && - this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && - this.keepaliveTimeMs > 0); - }; - /* eslint-disable-next-line prefer-const */ - let sendPing; // hoisted for use in maybeStartKeepalivePingTimer - const maybeStartKeepalivePingTimer = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); - }; - sendPing = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - let pingSendError = ''; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error: ' + err.message); - sessionClosedByServer = true; - session.close(); - } - else { - this.keepaliveTrace('Received ping response'); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = - (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.trace('Connection dropped due to ping send error: ' + pingSendError); - sessionClosedByServer = true; - session.close(); - return; - } - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace('Ping timeout passed without response'); - this.trace('Connection dropped by keepalive timeout'); - sessionClosedByServer = true; - session.close(); - }, this.keepaliveTimeoutMs); - (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); - }; - maybeStartKeepalivePingTimer(); - session.on('close', () => { - var _b, _c; - if (!sessionClosedByServer) { - this.trace(`Connection dropped by client ${(_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress}`); - } - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_c = this.http2Servers.get(http2Server)) === null || _c === void 0 ? void 0 : _c.sessions.delete(session); - }); - }; - } - _channelzSessionHandler(http2Server) { - return (session) => { - var _b, _c, _d, _e; - const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : 'unknown', this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); - const channelzSessionInfo = { - ref: channelzRef, - streamTracker: new channelz_1.ChannelzCallTracker(), - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - }; - (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session); - this.sessions.set(session, channelzSessionInfo); - const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; - this.channelzTrace.addTrace('CT_INFO', 'Connection established by client ' + clientAddress); - this.trace('Connection established by client ' + clientAddress); - this.sessionChildrenTracker.refChild(channelzRef); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimeout = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - // Apply a random jitter within a +/-10% range - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b; - sessionClosedByServer = true; - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by max connection age from ' + clientAddress); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } - catch (e) { - // The goaway can't be sent because the session is already closed - session.destroy(); - return; - } - session.close(); - /* Allow a grace period after sending the GOAWAY before forcibly - * closing the connection. */ - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_b = connectionAgeGraceTimer.unref) === null || _b === void 0 ? void 0 : _b.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimeout) { - clearTimeout(keepaliveTimeout); - keepaliveTimeout = null; - } - }; - const canSendPing = () => { - return (!session.destroyed && - this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && - this.keepaliveTimeMs > 0); - }; - /* eslint-disable-next-line prefer-const */ - let sendPing; // hoisted for use in maybeStartKeepalivePingTimer - const maybeStartKeepalivePingTimer = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); - }; - sendPing = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - let pingSendError = ''; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error: ' + err.message); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to error of a ping frame ' + - err.message + - ' return in ' + - duration); - sessionClosedByServer = true; - session.close(); - } - else { - this.keepaliveTrace('Received ping response'); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = - (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to ping send error: ' + pingSendError); - sessionClosedByServer = true; - session.close(); - return; - } - channelzSessionInfo.keepAlivesSent += 1; - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace('Ping timeout passed without response'); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by keepalive timeout from ' + clientAddress); - sessionClosedByServer = true; - session.close(); - }, this.keepaliveTimeoutMs); - (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); - }; - maybeStartKeepalivePingTimer(); - session.on('close', () => { - var _b; - if (!sessionClosedByServer) { - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by client ' + clientAddress); - } - this.sessionChildrenTracker.unrefChild(channelzRef); - (0, channelz_1.unregisterChannelzRef)(channelzRef); - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.delete(session); - this.sessions.delete(session); - }); - }; - } - enableIdleTimeout(session) { - var _b, _c; - if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { - return null; - } - const idleTimeoutObj = { - activeStreams: 0, - lastIdle: Date.now(), - onClose: this.onStreamClose.bind(this, session), - timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session), - }; - (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - this.sessionIdleTimeouts.set(session, idleTimeoutObj); - const { socket } = session; - this.trace('Enable idle timeout for ' + - socket.remoteAddress + - ':' + - socket.remotePort); - return idleTimeoutObj; - } - onIdleTimeout(ctx, session) { - const { socket } = session; - const sessionInfo = ctx.sessionIdleTimeouts.get(session); - // if it is called while we have activeStreams - timer will not be rescheduled - // until last active stream is closed, then it will call .refresh() on the timer - // important part is to not clearTimeout(timer) or it becomes unusable - // for future refreshes - if (sessionInfo !== undefined && - sessionInfo.activeStreams === 0) { - if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { - ctx.trace('Session idle timeout triggered for ' + - (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + - ':' + - (socket === null || socket === void 0 ? void 0 : socket.remotePort) + - ' last idle at ' + - sessionInfo.lastIdle); - ctx.closeSession(session); - } - else { - sessionInfo.timeout.refresh(); - } - } - } - onStreamOpened(stream) { - const session = stream.session; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams += 1; - stream.once('close', idleTimeoutObj.onClose); - } - } - onStreamClose(session) { - var _b, _c; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams -= 1; - if (idleTimeoutObj.activeStreams === 0) { - idleTimeoutObj.lastIdle = Date.now(); - idleTimeoutObj.timeout.refresh(); - this.trace('Session onStreamClose' + - ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + - ':' + - ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + - ' at ' + - idleTimeoutObj.lastIdle); - } - } - } - }, - (() => { - const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; - _start_decorators = [deprecate('Calling start() is no longer necessary. It can be safely omitted.')]; - __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: obj => "start" in obj, get: obj => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); - if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); - })(), - _a; -})(); -exports.Server = Server; -async function handleUnary(call, handler) { - let stream; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: 'OK', - metadata: trailer !== null && trailer !== void 0 ? trailer : null, - }); - }); - } - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); - try { - handler.func(stream, respond); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - } - }, - }); -} -function handleClientStreaming(call, handler) { - let stream; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: 'OK', - metadata: trailer !== null && trailer !== void 0 ? trailer : null, - }); - }); - } - call.start({ - onReceiveMetadata(metadata) { - stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); - try { - handler.func(stream, respond); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveHalfClose() { - stream.push(null); - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -function handleServerStreaming(call, handler) { - let stream; - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); - try { - handler.func(stream); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -function handleBidiStreaming(call, handler) { - let stream; - call.start({ - onReceiveMetadata(metadata) { - stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); - try { - handler.func(stream); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveHalfClose() { - stream.push(null); - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -//# sourceMappingURL=server.js.map - -/***/ }), - -/***/ 21761: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateRetryThrottling = validateRetryThrottling; -exports.validateServiceConfig = validateServiceConfig; -exports.extractAndSelectServiceConfig = extractAndSelectServiceConfig; -/* This file implements gRFC A2 and the service config spec: - * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md - * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each - * function here takes an object with unknown structure and returns its - * specific object type if the input has the right structure, and throws an - * error otherwise. */ -/* The any type is purposely used here. All functions validate their input at - * runtime */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -const os = __nccwpck_require__(22037); -const constants_1 = __nccwpck_require__(90634); -/** - * Recognizes a number with up to 9 digits after the decimal point, followed by - * an "s", representing a number of seconds. - */ -const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; -/** - * Client language name used for determining whether this client matches a - * `ServiceConfigCanaryConfig`'s `clientLanguage` list. - */ -const CLIENT_LANGUAGE_STRING = 'node'; -function validateName(obj) { - // In this context, and unset field and '' are considered the same - if ('service' in obj && obj.service !== '') { - if (typeof obj.service !== 'string') { - throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); - } - if ('method' in obj && obj.method !== '') { - if (typeof obj.method !== 'string') { - throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); - } - return { - service: obj.service, - method: obj.method, - }; - } - else { - return { - service: obj.service, - }; - } - } - else { - if ('method' in obj && obj.method !== undefined) { - throw new Error(`Invalid method config name: method set with empty or unset service`); - } - return {}; - } -} -function validateRetryPolicy(obj) { - if (!('maxAttempts' in obj) || - !Number.isInteger(obj.maxAttempts) || - obj.maxAttempts < 2) { - throw new Error('Invalid method config retry policy: maxAttempts must be an integer at least 2'); - } - if (!('initialBackoff' in obj) || - typeof obj.initialBackoff !== 'string' || - !DURATION_REGEX.test(obj.initialBackoff)) { - throw new Error('Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s'); - } - if (!('maxBackoff' in obj) || - typeof obj.maxBackoff !== 'string' || - !DURATION_REGEX.test(obj.maxBackoff)) { - throw new Error('Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s'); - } - if (!('backoffMultiplier' in obj) || - typeof obj.backoffMultiplier !== 'number' || - obj.backoffMultiplier <= 0) { - throw new Error('Invalid method config retry policy: backoffMultiplier must be a number greater than 0'); - } - if (!('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes))) { - throw new Error('Invalid method config retry policy: retryableStatusCodes is required'); - } - if (obj.retryableStatusCodes.length === 0) { - throw new Error('Invalid method config retry policy: retryableStatusCodes must be non-empty'); - } - for (const value of obj.retryableStatusCodes) { - if (typeof value === 'number') { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error('Invalid method config retry policy: retryableStatusCodes value not in status code range'); - } - } - else if (typeof value === 'string') { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error('Invalid method config retry policy: retryableStatusCodes value not a status code name'); - } - } - else { - throw new Error('Invalid method config retry policy: retryableStatusCodes value must be a string or number'); - } - } - return { - maxAttempts: obj.maxAttempts, - initialBackoff: obj.initialBackoff, - maxBackoff: obj.maxBackoff, - backoffMultiplier: obj.backoffMultiplier, - retryableStatusCodes: obj.retryableStatusCodes, - }; -} -function validateHedgingPolicy(obj) { - if (!('maxAttempts' in obj) || - !Number.isInteger(obj.maxAttempts) || - obj.maxAttempts < 2) { - throw new Error('Invalid method config hedging policy: maxAttempts must be an integer at least 2'); - } - if ('hedgingDelay' in obj && - (typeof obj.hedgingDelay !== 'string' || - !DURATION_REGEX.test(obj.hedgingDelay))) { - throw new Error('Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s'); - } - if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) { - for (const value of obj.nonFatalStatusCodes) { - if (typeof value === 'number') { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not in status code range'); - } - } - else if (typeof value === 'string') { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not a status code name'); - } - } - else { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number'); - } - } - } - const result = { - maxAttempts: obj.maxAttempts, - }; - if (obj.hedgingDelay) { - result.hedgingDelay = obj.hedgingDelay; - } - if (obj.nonFatalStatusCodes) { - result.nonFatalStatusCodes = obj.nonFatalStatusCodes; - } - return result; -} -function validateMethodConfig(obj) { - var _a; - const result = { - name: [], - }; - if (!('name' in obj) || !Array.isArray(obj.name)) { - throw new Error('Invalid method config: invalid name array'); - } - for (const name of obj.name) { - result.name.push(validateName(name)); - } - if ('waitForReady' in obj) { - if (typeof obj.waitForReady !== 'boolean') { - throw new Error('Invalid method config: invalid waitForReady'); - } - result.waitForReady = obj.waitForReady; - } - if ('timeout' in obj) { - if (typeof obj.timeout === 'object') { - if (!('seconds' in obj.timeout) || - !(typeof obj.timeout.seconds === 'number')) { - throw new Error('Invalid method config: invalid timeout.seconds'); - } - if (!('nanos' in obj.timeout) || - !(typeof obj.timeout.nanos === 'number')) { - throw new Error('Invalid method config: invalid timeout.nanos'); - } - result.timeout = obj.timeout; - } - else if (typeof obj.timeout === 'string' && - DURATION_REGEX.test(obj.timeout)) { - const timeoutParts = obj.timeout - .substring(0, obj.timeout.length - 1) - .split('.'); - result.timeout = { - seconds: timeoutParts[0] | 0, - nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0, - }; - } - else { - throw new Error('Invalid method config: invalid timeout'); - } - } - if ('maxRequestBytes' in obj) { - if (typeof obj.maxRequestBytes !== 'number') { - throw new Error('Invalid method config: invalid maxRequestBytes'); - } - result.maxRequestBytes = obj.maxRequestBytes; - } - if ('maxResponseBytes' in obj) { - if (typeof obj.maxResponseBytes !== 'number') { - throw new Error('Invalid method config: invalid maxRequestBytes'); - } - result.maxResponseBytes = obj.maxResponseBytes; - } - if ('retryPolicy' in obj) { - if ('hedgingPolicy' in obj) { - throw new Error('Invalid method config: retryPolicy and hedgingPolicy cannot both be specified'); - } - else { - result.retryPolicy = validateRetryPolicy(obj.retryPolicy); - } - } - else if ('hedgingPolicy' in obj) { - result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); - } - return result; -} -function validateRetryThrottling(obj) { - if (!('maxTokens' in obj) || - typeof obj.maxTokens !== 'number' || - obj.maxTokens <= 0 || - obj.maxTokens > 1000) { - throw new Error('Invalid retryThrottling: maxTokens must be a number in (0, 1000]'); - } - if (!('tokenRatio' in obj) || - typeof obj.tokenRatio !== 'number' || - obj.tokenRatio <= 0) { - throw new Error('Invalid retryThrottling: tokenRatio must be a number greater than 0'); - } - return { - maxTokens: +obj.maxTokens.toFixed(3), - tokenRatio: +obj.tokenRatio.toFixed(3), - }; -} -function validateLoadBalancingConfig(obj) { - if (!(typeof obj === 'object' && obj !== null)) { - throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); - } - const keys = Object.keys(obj); - if (keys.length > 1) { - throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); - } - if (keys.length === 0) { - throw new Error('Invalid loadBalancingConfig: load balancing policy name required'); - } - return { - [keys[0]]: obj[keys[0]], - }; -} -function validateServiceConfig(obj) { - const result = { - loadBalancingConfig: [], - methodConfig: [], - }; - if ('loadBalancingPolicy' in obj) { - if (typeof obj.loadBalancingPolicy === 'string') { - result.loadBalancingPolicy = obj.loadBalancingPolicy; - } - else { - throw new Error('Invalid service config: invalid loadBalancingPolicy'); - } - } - if ('loadBalancingConfig' in obj) { - if (Array.isArray(obj.loadBalancingConfig)) { - for (const config of obj.loadBalancingConfig) { - result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); - } - } - else { - throw new Error('Invalid service config: invalid loadBalancingConfig'); - } - } - if ('methodConfig' in obj) { - if (Array.isArray(obj.methodConfig)) { - for (const methodConfig of obj.methodConfig) { - result.methodConfig.push(validateMethodConfig(methodConfig)); - } - } - } - if ('retryThrottling' in obj) { - result.retryThrottling = validateRetryThrottling(obj.retryThrottling); - } - // Validate method name uniqueness - const seenMethodNames = []; - for (const methodConfig of result.methodConfig) { - for (const name of methodConfig.name) { - for (const seenName of seenMethodNames) { - if (name.service === seenName.service && - name.method === seenName.method) { - throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); - } - } - seenMethodNames.push(name); - } - } - return result; -} -function validateCanaryConfig(obj) { - if (!('serviceConfig' in obj)) { - throw new Error('Invalid service config choice: missing service config'); - } - const result = { - serviceConfig: validateServiceConfig(obj.serviceConfig), - }; - if ('clientLanguage' in obj) { - if (Array.isArray(obj.clientLanguage)) { - result.clientLanguage = []; - for (const lang of obj.clientLanguage) { - if (typeof lang === 'string') { - result.clientLanguage.push(lang); - } - else { - throw new Error('Invalid service config choice: invalid clientLanguage'); - } - } - } - else { - throw new Error('Invalid service config choice: invalid clientLanguage'); - } - } - if ('clientHostname' in obj) { - if (Array.isArray(obj.clientHostname)) { - result.clientHostname = []; - for (const lang of obj.clientHostname) { - if (typeof lang === 'string') { - result.clientHostname.push(lang); - } - else { - throw new Error('Invalid service config choice: invalid clientHostname'); - } - } - } - else { - throw new Error('Invalid service config choice: invalid clientHostname'); - } - } - if ('percentage' in obj) { - if (typeof obj.percentage === 'number' && - 0 <= obj.percentage && - obj.percentage <= 100) { - result.percentage = obj.percentage; - } - else { - throw new Error('Invalid service config choice: invalid percentage'); - } - } - // Validate that no unexpected fields are present - const allowedFields = [ - 'clientLanguage', - 'percentage', - 'clientHostname', - 'serviceConfig', - ]; - for (const field in obj) { - if (!allowedFields.includes(field)) { - throw new Error(`Invalid service config choice: unexpected field ${field}`); - } - } - return result; -} -function validateAndSelectCanaryConfig(obj, percentage) { - if (!Array.isArray(obj)) { - throw new Error('Invalid service config list'); - } - for (const config of obj) { - const validatedConfig = validateCanaryConfig(config); - /* For each field, we check if it is present, then only discard the - * config if the field value does not match the current client */ - if (typeof validatedConfig.percentage === 'number' && - percentage > validatedConfig.percentage) { - continue; - } - if (Array.isArray(validatedConfig.clientHostname)) { - let hostnameMatched = false; - for (const hostname of validatedConfig.clientHostname) { - if (hostname === os.hostname()) { - hostnameMatched = true; - } - } - if (!hostnameMatched) { - continue; - } - } - if (Array.isArray(validatedConfig.clientLanguage)) { - let languageMatched = false; - for (const language of validatedConfig.clientLanguage) { - if (language === CLIENT_LANGUAGE_STRING) { - languageMatched = true; - } - } - if (!languageMatched) { - continue; - } - } - return validatedConfig.serviceConfig; - } - throw new Error('No matching service config found'); -} -/** - * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, - * and select a service config with selection fields that all match this client. Most of these steps - * can fail with an error; the caller must handle any errors thrown this way. - * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt - * @param percentage A number chosen from the range [0, 100) that is used to select which config to use - * @return The service configuration to use, given the percentage value, or null if the service config - * data has a valid format but none of the options match the current client. - */ -function extractAndSelectServiceConfig(txtRecord, percentage) { - for (const record of txtRecord) { - if (record.length > 0 && record[0].startsWith('grpc_config=')) { - /* Treat the list of strings in this record as a single string and remove - * "grpc_config=" from the beginning. The rest should be a JSON string */ - const recordString = record.join('').substring('grpc_config='.length); - const recordJson = JSON.parse(recordString); - return validateAndSelectCanaryConfig(recordJson, percentage); - } - } - return null; -} -//# sourceMappingURL=service-config.js.map - -/***/ }), - -/***/ 28812: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SingleSubchannelChannel = void 0; -const call_number_1 = __nccwpck_require__(70380); -const channelz_1 = __nccwpck_require__(79975); -const compression_filter_1 = __nccwpck_require__(47616); -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const control_plane_status_1 = __nccwpck_require__(39129); -const deadline_1 = __nccwpck_require__(511); -const filter_stack_1 = __nccwpck_require__(66450); -const metadata_1 = __nccwpck_require__(83665); -const resolver_1 = __nccwpck_require__(31594); -const uri_parser_1 = __nccwpck_require__(65974); -class SubchannelCallWrapper { - constructor(subchannel, method, filterStackFactory, options, callNumber) { - var _a, _b; - this.subchannel = subchannel; - this.method = method; - this.options = options; - this.callNumber = callNumber; - this.childCall = null; - this.pendingMessage = null; - this.readPending = false; - this.halfClosePending = false; - this.pendingStatus = null; - this.readFilterPending = false; - this.writeFilterPending = false; - const splitPath = this.method.split('/'); - let serviceName = ''; - /* The standard path format is "/{serviceName}/{methodName}", so if we split - * by '/', the first item should be empty and the second should be the - * service name */ - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; - /* Currently, call credentials are only allowed on HTTPS connections, so we - * can assume that the scheme is "https" */ - this.serviceUrl = `https://${hostname}/${serviceName}`; - const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); - if (timeout !== Infinity) { - if (timeout <= 0) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - } - else { - setTimeout(() => { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - }, timeout); - } - } - this.filterStack = filterStackFactory.createFilter(); - } - cancelWithStatus(status, details) { - if (this.childCall) { - this.childCall.cancelWithStatus(status, details); - } - else { - this.pendingStatus = { - code: status, - details: details, - metadata: new metadata_1.Metadata() - }; - } - } - getPeer() { - var _a, _b; - return (_b = (_a = this.childCall) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.subchannel.getAddress(); - } - async start(metadata, listener) { - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - return; - } - if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - listener.onReceiveStatus({ - code: constants_1.Status.UNAVAILABLE, - details: 'Subchannel not ready', - metadata: new metadata_1.Metadata() - }); - return; - } - const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); - let credsMetadata; - try { - credsMetadata = await this.subchannel.getCallCredentials() - .generateMetadata({ method_name: this.method, service_url: this.serviceUrl }); - } - catch (e) { - const error = e; - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); - listener.onReceiveStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }); - return; - } - credsMetadata.merge(filteredMetadata); - const childListener = { - onReceiveMetadata: async (metadata) => { - listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata)); - }, - onReceiveMessage: async (message) => { - this.readFilterPending = true; - const filteredMessage = await this.filterStack.receiveMessage(message); - this.readFilterPending = false; - listener.onReceiveMessage(filteredMessage); - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - } - }, - onReceiveStatus: async (status) => { - const filteredStatus = await this.filterStack.receiveTrailers(status); - if (this.readFilterPending) { - this.pendingStatus = filteredStatus; - } - else { - listener.onReceiveStatus(filteredStatus); - } - } - }; - this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); - if (this.readPending) { - this.childCall.startRead(); - } - if (this.pendingMessage) { - this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.halfClosePending && !this.writeFilterPending) { - this.childCall.halfClose(); - } - } - async sendMessageWithContext(context, message) { - this.writeFilterPending = true; - const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })); - this.writeFilterPending = false; - if (this.childCall) { - this.childCall.sendMessageWithContext(context, filteredMessage.message); - if (this.halfClosePending) { - this.childCall.halfClose(); - } - } - else { - this.pendingMessage = { context, message: filteredMessage.message }; - } - } - startRead() { - if (this.childCall) { - this.childCall.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - if (this.childCall && !this.writeFilterPending) { - this.childCall.halfClose(); - } - else { - this.halfClosePending = true; - } - } - getCallNumber() { - return this.callNumber; - } - setCredentials(credentials) { - throw new Error("Method not implemented."); - } - getAuthContext() { - if (this.childCall) { - return this.childCall.getAuthContext(); - } - else { - return null; - } - } -} -class SingleSubchannelChannel { - constructor(subchannel, target, options) { - this.subchannel = subchannel; - this.target = target; - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.channelzEnabled = options['grpc.enable_channelz'] !== 0; - this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({ - target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`, - state: this.subchannel.getConnectivityState(), - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }), this.channelzEnabled); - if (this.channelzEnabled) { - this.childrenTracker.refChild(subchannel.getChannelzRef()); - } - this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]); - } - close() { - if (this.channelzEnabled) { - this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); - } - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - throw new Error("Method not implemented."); - } - watchConnectivityState(currentState, deadline, callback) { - throw new Error("Method not implemented."); - } - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline) { - const callOptions = { - deadline: deadline, - host: (0, resolver_1.getDefaultAuthority)(this.target), - flags: constants_1.Propagate.DEFAULTS, - parentCall: null - }; - return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)()); - } -} -exports.SingleSubchannelChannel = SingleSubchannelChannel; -//# sourceMappingURL=single-subchannel-channel.js.map - -/***/ }), - -/***/ 73155: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StatusBuilder = void 0; -/** - * A builder for gRPC status objects. - */ -class StatusBuilder { - constructor() { - this.code = null; - this.details = null; - this.metadata = null; - } - /** - * Adds a status code to the builder. - */ - withCode(code) { - this.code = code; - return this; - } - /** - * Adds details to the builder. - */ - withDetails(details) { - this.details = details; - return this; - } - /** - * Adds metadata to the builder. - */ - withMetadata(metadata) { - this.metadata = metadata; - return this; - } - /** - * Builds the status object. - */ - build() { - const status = {}; - if (this.code !== null) { - status.code = this.code; - } - if (this.details !== null) { - status.details = this.details; - } - if (this.metadata !== null) { - status.metadata = this.metadata; - } - return status; - } -} -exports.StatusBuilder = StatusBuilder; -//# sourceMappingURL=status-builder.js.map - -/***/ }), - -/***/ 16575: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StreamDecoder = void 0; -var ReadState; -(function (ReadState) { - ReadState[ReadState["NO_DATA"] = 0] = "NO_DATA"; - ReadState[ReadState["READING_SIZE"] = 1] = "READING_SIZE"; - ReadState[ReadState["READING_MESSAGE"] = 2] = "READING_MESSAGE"; -})(ReadState || (ReadState = {})); -class StreamDecoder { - constructor(maxReadMessageLength) { - this.maxReadMessageLength = maxReadMessageLength; - this.readState = ReadState.NO_DATA; - this.readCompressFlag = Buffer.alloc(1); - this.readPartialSize = Buffer.alloc(4); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readPartialMessage = []; - this.readMessageRemaining = 0; - } - write(data) { - let readHead = 0; - let toRead; - const result = []; - while (readHead < data.length) { - switch (this.readState) { - case ReadState.NO_DATA: - this.readCompressFlag = data.slice(readHead, readHead + 1); - readHead += 1; - this.readState = ReadState.READING_SIZE; - this.readPartialSize.fill(0); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readMessageRemaining = 0; - this.readPartialMessage = []; - break; - case ReadState.READING_SIZE: - toRead = Math.min(data.length - readHead, this.readSizeRemaining); - data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); - this.readSizeRemaining -= toRead; - readHead += toRead; - // readSizeRemaining >=0 here - if (this.readSizeRemaining === 0) { - this.readMessageSize = this.readPartialSize.readUInt32BE(0); - if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { - throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); - } - this.readMessageRemaining = this.readMessageSize; - if (this.readMessageRemaining > 0) { - this.readState = ReadState.READING_MESSAGE; - } - else { - const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); - this.readState = ReadState.NO_DATA; - result.push(message); - } - } - break; - case ReadState.READING_MESSAGE: - toRead = Math.min(data.length - readHead, this.readMessageRemaining); - this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); - this.readMessageRemaining -= toRead; - readHead += toRead; - // readMessageRemaining >=0 here - if (this.readMessageRemaining === 0) { - // At this point, we have read a full message - const framedMessageBuffers = [ - this.readCompressFlag, - this.readPartialSize, - ].concat(this.readPartialMessage); - const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); - this.readState = ReadState.NO_DATA; - result.push(framedMessage); - } - break; - default: - throw new Error('Unexpected read state'); - } - } - return result; - } -} -exports.StreamDecoder = StreamDecoder; -//# sourceMappingURL=stream-decoder.js.map - -/***/ }), - -/***/ 99905: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.EndpointMap = void 0; -exports.isTcpSubchannelAddress = isTcpSubchannelAddress; -exports.subchannelAddressEqual = subchannelAddressEqual; -exports.subchannelAddressToString = subchannelAddressToString; -exports.stringToSubchannelAddress = stringToSubchannelAddress; -exports.endpointEqual = endpointEqual; -exports.endpointToString = endpointToString; -exports.endpointHasAddress = endpointHasAddress; -const net_1 = __nccwpck_require__(41808); -function isTcpSubchannelAddress(address) { - return 'port' in address; -} -function subchannelAddressEqual(address1, address2) { - if (!address1 && !address2) { - return true; - } - if (!address1 || !address2) { - return false; - } - if (isTcpSubchannelAddress(address1)) { - return (isTcpSubchannelAddress(address2) && - address1.host === address2.host && - address1.port === address2.port); - } - else { - return !isTcpSubchannelAddress(address2) && address1.path === address2.path; - } -} -function subchannelAddressToString(address) { - if (isTcpSubchannelAddress(address)) { - if ((0, net_1.isIPv6)(address.host)) { - return '[' + address.host + ']:' + address.port; - } - else { - return address.host + ':' + address.port; - } - } - else { - return address.path; - } -} -const DEFAULT_PORT = 443; -function stringToSubchannelAddress(addressString, port) { - if ((0, net_1.isIP)(addressString)) { - return { - host: addressString, - port: port !== null && port !== void 0 ? port : DEFAULT_PORT, - }; - } - else { - return { - path: addressString, - }; - } -} -function endpointEqual(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (let i = 0; i < endpoint1.addresses.length; i++) { - if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { - return false; - } - } - return true; -} -function endpointToString(endpoint) { - return ('[' + endpoint.addresses.map(subchannelAddressToString).join(', ') + ']'); -} -function endpointHasAddress(endpoint, expectedAddress) { - for (const address of endpoint.addresses) { - if (subchannelAddressEqual(address, expectedAddress)) { - return true; - } - } - return false; -} -function endpointEqualUnordered(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (const address1 of endpoint1.addresses) { - let matchFound = false; - for (const address2 of endpoint2.addresses) { - if (subchannelAddressEqual(address1, address2)) { - matchFound = true; - break; - } - } - if (!matchFound) { - return false; - } - } - return true; -} -class EndpointMap { - constructor() { - this.map = new Set(); - } - get size() { - return this.map.size; - } - getForSubchannelAddress(address) { - for (const entry of this.map) { - if (endpointHasAddress(entry.key, address)) { - return entry.value; - } - } - return undefined; - } - /** - * Delete any entries in this map with keys that are not in endpoints - * @param endpoints - */ - deleteMissing(endpoints) { - const removedValues = []; - for (const entry of this.map) { - let foundEntry = false; - for (const endpoint of endpoints) { - if (endpointEqualUnordered(endpoint, entry.key)) { - foundEntry = true; - } - } - if (!foundEntry) { - removedValues.push(entry.value); - this.map.delete(entry); - } - } - return removedValues; - } - get(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - return entry.value; - } - } - return undefined; - } - set(endpoint, mapEntry) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - entry.value = mapEntry; - return; - } - } - this.map.add({ key: endpoint, value: mapEntry }); - } - delete(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - this.map.delete(entry); - return; - } - } - } - has(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - return true; - } - } - return false; - } - clear() { - this.map.clear(); - } - *keys() { - for (const entry of this.map) { - yield entry.key; - } - } - *values() { - for (const entry of this.map) { - yield entry.value; - } - } - *entries() { - for (const entry of this.map) { - yield [entry.key, entry.value]; - } - } -} -exports.EndpointMap = EndpointMap; -//# sourceMappingURL=subchannel-address.js.map - -/***/ }), - -/***/ 86940: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Http2SubchannelCall = void 0; -const http2 = __nccwpck_require__(85158); -const os = __nccwpck_require__(22037); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const stream_decoder_1 = __nccwpck_require__(16575); -const logging = __nccwpck_require__(35993); -const constants_2 = __nccwpck_require__(90634); -const TRACER_NAME = 'subchannel_call'; -/** - * Should do approximately the same thing as util.getSystemErrorName but the - * TypeScript types don't have that function for some reason so I just made my - * own. - * @param errno - */ -function getSystemErrorName(errno) { - for (const [name, num] of Object.entries(os.constants.errno)) { - if (num === errno) { - return name; - } - } - return 'Unknown system error ' + errno; -} -function mapHttpStatusCode(code) { - const details = `Received HTTP status code ${code}`; - let mappedStatusCode; - switch (code) { - // TODO(murgatroid99): handle 100 and 101 - case 400: - mappedStatusCode = constants_1.Status.INTERNAL; - break; - case 401: - mappedStatusCode = constants_1.Status.UNAUTHENTICATED; - break; - case 403: - mappedStatusCode = constants_1.Status.PERMISSION_DENIED; - break; - case 404: - mappedStatusCode = constants_1.Status.UNIMPLEMENTED; - break; - case 429: - case 502: - case 503: - case 504: - mappedStatusCode = constants_1.Status.UNAVAILABLE; - break; - default: - mappedStatusCode = constants_1.Status.UNKNOWN; - } - return { - code: mappedStatusCode, - details: details, - metadata: new metadata_1.Metadata() - }; -} -class Http2SubchannelCall { - constructor(http2Stream, callEventTracker, listener, transport, callId) { - var _a; - this.http2Stream = http2Stream; - this.callEventTracker = callEventTracker; - this.listener = listener; - this.transport = transport; - this.callId = callId; - this.isReadFilterPending = false; - this.isPushPending = false; - this.canPush = false; - /** - * Indicates that an 'end' event has come from the http2 stream, so there - * will be no more data events. - */ - this.readsClosed = false; - this.statusOutput = false; - this.unpushedReadMessages = []; - // This is populated (non-null) if and only if the call has ended - this.finalStatus = null; - this.internalError = null; - this.serverEndedCall = false; - this.connectionDropped = false; - const maxReceiveMessageLength = (_a = transport.getOptions()['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); - http2Stream.on('response', (headers, flags) => { - let headersString = ''; - for (const header of Object.keys(headers)) { - headersString += '\t\t' + header + ': ' + headers[header] + '\n'; - } - this.trace('Received server headers:\n' + headersString); - this.httpStatusCode = headers[':status']; - if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { - this.handleTrailers(headers); - } - else { - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } - catch (error) { - this.endCall({ - code: constants_1.Status.UNKNOWN, - details: error.message, - metadata: new metadata_1.Metadata(), - }); - return; - } - this.listener.onReceiveMetadata(metadata); - } - }); - http2Stream.on('trailers', (headers) => { - this.handleTrailers(headers); - }); - http2Stream.on('data', (data) => { - /* If the status has already been output, allow the http2 stream to - * drain without processing the data. */ - if (this.statusOutput) { - return; - } - this.trace('receive HTTP/2 data frame of length ' + data.length); - let messages; - try { - messages = this.decoder.write(data); - } - catch (e) { - /* Some servers send HTML error pages along with HTTP status codes. - * When the client attempts to parse this as a length-delimited - * message, the parsed message size is greater than the default limit, - * resulting in a message decoding error. In that situation, the HTTP - * error code information is more useful to the user than the - * RESOURCE_EXHAUSTED error is, so we report that instead. Normally, - * we delay processing the HTTP status until after the stream ends, to - * prioritize reporting the gRPC status from trailers if it is present, - * but when there is a message parsing error we end the stream early - * before processing trailers. */ - if (this.httpStatusCode !== undefined && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - this.cancelWithStatus(mappedStatus.code, mappedStatus.details); - } - else { - this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message); - } - return; - } - for (const message of messages) { - this.trace('parsed message of length ' + message.length); - this.callEventTracker.addMessageReceived(); - this.tryPush(message); - } - }); - http2Stream.on('end', () => { - this.readsClosed = true; - this.maybeOutputStatus(); - }); - http2Stream.on('close', () => { - this.serverEndedCall = true; - /* Use process.next tick to ensure that this code happens after any - * "error" event that may be emitted at about the same time, so that - * we can bubble up the error message from that event. */ - process.nextTick(() => { - var _a; - this.trace('HTTP/2 stream closed with code ' + http2Stream.rstCode); - /* If we have a final status with an OK status code, that means that - * we have received all of the messages and we have processed the - * trailers and the call completed successfully, so it doesn't matter - * how the stream ends after that */ - if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { - return; - } - let code; - let details = ''; - switch (http2Stream.rstCode) { - case http2.constants.NGHTTP2_NO_ERROR: - /* If we get a NO_ERROR code and we already have a status, the - * stream completed properly and we just haven't fully processed - * it yet */ - if (this.finalStatus !== null) { - return; - } - if (this.httpStatusCode && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - code = mappedStatus.code; - details = mappedStatus.details; - } - else { - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; - } - break; - case http2.constants.NGHTTP2_REFUSED_STREAM: - code = constants_1.Status.UNAVAILABLE; - details = 'Stream refused by server'; - break; - case http2.constants.NGHTTP2_CANCEL: - /* Bug reports indicate that Node synthesizes a NGHTTP2_CANCEL - * code from connection drops. We want to prioritize reporting - * an unavailable status when that happens. */ - if (this.connectionDropped) { - code = constants_1.Status.UNAVAILABLE; - details = 'Connection dropped'; - } - else { - code = constants_1.Status.CANCELLED; - details = 'Call cancelled'; - } - break; - case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: - code = constants_1.Status.RESOURCE_EXHAUSTED; - details = 'Bandwidth exhausted or memory limit exceeded'; - break; - case http2.constants.NGHTTP2_INADEQUATE_SECURITY: - code = constants_1.Status.PERMISSION_DENIED; - details = 'Protocol not secure enough'; - break; - case http2.constants.NGHTTP2_INTERNAL_ERROR: - code = constants_1.Status.INTERNAL; - if (this.internalError === null) { - /* This error code was previously handled in the default case, and - * there are several instances of it online, so I wanted to - * preserve the original error message so that people find existing - * information in searches, but also include the more recognizable - * "Internal server error" message. */ - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; - } - else { - if (this.internalError.code === 'ECONNRESET' || - this.internalError.code === 'ETIMEDOUT') { - code = constants_1.Status.UNAVAILABLE; - details = this.internalError.message; - } - else { - /* The "Received RST_STREAM with code ..." error is preserved - * here for continuity with errors reported online, but the - * error message at the end will probably be more relevant in - * most cases. */ - details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; - } - } - break; - default: - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode}`; - } - // This is a no-op if trailers were received at all. - // This is OK, because status codes emitted here correspond to more - // catastrophic issues that prevent us from receiving trailers in the - // first place. - this.endCall({ - code, - details, - metadata: new metadata_1.Metadata(), - rstCode: http2Stream.rstCode, - }); - }); - }); - http2Stream.on('error', (err) => { - /* We need an error handler here to stop "Uncaught Error" exceptions - * from bubbling up. However, errors here should all correspond to - * "close" events, where we will handle the error more granularly */ - /* Specifically looking for stream errors that were *not* constructed - * from a RST_STREAM response here: - * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267 - */ - if (err.code !== 'ERR_HTTP2_STREAM_ERROR') { - this.trace('Node error event: message=' + - err.message + - ' code=' + - err.code + - ' errno=' + - getSystemErrorName(err.errno) + - ' syscall=' + - err.syscall); - this.internalError = err; - } - this.callEventTracker.onStreamEnd(false); - }); - } - getDeadlineInfo() { - return [`remote_addr=${this.getPeer()}`]; - } - onDisconnect() { - this.connectionDropped = true; - /* Give the call an event loop cycle to finish naturally before reporting - * the disconnection as an error. */ - setImmediate(() => { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: 'Connection dropped', - metadata: new metadata_1.Metadata(), - }); - }); - } - outputStatus() { - /* Precondition: this.finalStatus !== null */ - if (!this.statusOutput) { - this.statusOutput = true; - this.trace('ended with status: code=' + - this.finalStatus.code + - ' details="' + - this.finalStatus.details + - '"'); - this.callEventTracker.onCallEnd(this.finalStatus); - /* We delay the actual action of bubbling up the status to insulate the - * cleanup code in this class from any errors that may be thrown in the - * upper layers as a result of bubbling up the status. In particular, - * if the status is not OK, the "error" event may be emitted - * synchronously at the top level, which will result in a thrown error if - * the user does not handle that event. */ - process.nextTick(() => { - this.listener.onReceiveStatus(this.finalStatus); - }); - /* Leave the http2 stream in flowing state to drain incoming messages, to - * ensure that the stream closure completes. The call stream already does - * not push more messages after the status is output, so the messages go - * nowhere either way. */ - this.http2Stream.resume(); - } - } - trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callId + '] ' + text); - } - /** - * On first call, emits a 'status' event with the given StatusObject. - * Subsequent calls are no-ops. - * @param status The status of the call. - */ - endCall(status) { - /* If the status is OK and a new status comes in (e.g. from a - * deserialization failure), that new status takes priority */ - if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { - this.finalStatus = status; - this.maybeOutputStatus(); - } - this.destroyHttp2Stream(); - } - maybeOutputStatus() { - if (this.finalStatus !== null) { - /* The combination check of readsClosed and that the two message buffer - * arrays are empty checks that there all incoming data has been fully - * processed */ - if (this.finalStatus.code !== constants_1.Status.OK || - (this.readsClosed && - this.unpushedReadMessages.length === 0 && - !this.isReadFilterPending && - !this.isPushPending)) { - this.outputStatus(); - } - } - } - push(message) { - this.trace('pushing to reader message of length ' + - (message instanceof Buffer ? message.length : null)); - this.canPush = false; - this.isPushPending = true; - process.nextTick(() => { - this.isPushPending = false; - /* If we have already output the status any later messages should be - * ignored, and can cause out-of-order operation errors higher up in the - * stack. Checking as late as possible here to avoid any race conditions. - */ - if (this.statusOutput) { - return; - } - this.listener.onReceiveMessage(message); - this.maybeOutputStatus(); - }); - } - tryPush(messageBytes) { - if (this.canPush) { - this.http2Stream.pause(); - this.push(messageBytes); - } - else { - this.trace('unpushedReadMessages.push message of length ' + messageBytes.length); - this.unpushedReadMessages.push(messageBytes); - } - } - handleTrailers(headers) { - this.serverEndedCall = true; - this.callEventTracker.onStreamEnd(true); - let headersString = ''; - for (const header of Object.keys(headers)) { - headersString += '\t\t' + header + ': ' + headers[header] + '\n'; - } - this.trace('Received server trailers:\n' + headersString); - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } - catch (e) { - metadata = new metadata_1.Metadata(); - } - const metadataMap = metadata.getMap(); - let status; - if (typeof metadataMap['grpc-status'] === 'string') { - const receivedStatus = Number(metadataMap['grpc-status']); - this.trace('received status code ' + receivedStatus + ' from server'); - metadata.remove('grpc-status'); - let details = ''; - if (typeof metadataMap['grpc-message'] === 'string') { - try { - details = decodeURI(metadataMap['grpc-message']); - } - catch (e) { - details = metadataMap['grpc-message']; - } - metadata.remove('grpc-message'); - this.trace('received status details string "' + details + '" from server'); - } - status = { - code: receivedStatus, - details: details, - metadata: metadata - }; - } - else if (this.httpStatusCode) { - status = mapHttpStatusCode(this.httpStatusCode); - status.metadata = metadata; - } - else { - status = { - code: constants_1.Status.UNKNOWN, - details: 'No status information received', - metadata: metadata - }; - } - // This is a no-op if the call was already ended when handling headers. - this.endCall(status); - } - destroyHttp2Stream() { - var _a; - // The http2 stream could already have been destroyed if cancelWithStatus - // is called in response to an internal http2 error. - if (this.http2Stream.destroyed) { - return; - } - /* If the server ended the call, sending an RST_STREAM is redundant, so we - * just half close on the client side instead to finish closing the stream. - */ - if (this.serverEndedCall) { - this.http2Stream.end(); - } - else { - /* If the call has ended with an OK status, communicate that when closing - * the stream, partly to avoid a situation in which we detect an error - * RST_STREAM as a result after we have the status */ - let code; - if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { - code = http2.constants.NGHTTP2_NO_ERROR; - } - else { - code = http2.constants.NGHTTP2_CANCEL; - } - this.trace('close http2 stream with code ' + code); - this.http2Stream.close(code); - } - } - cancelWithStatus(status, details) { - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); - } - getStatus() { - return this.finalStatus; - } - getPeer() { - return this.transport.getPeerName(); - } - getCallNumber() { - return this.callId; - } - getAuthContext() { - return this.transport.getAuthContext(); - } - startRead() { - /* If the stream has ended with an error, we should not emit any more - * messages and we should communicate that the stream has ended */ - if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { - this.readsClosed = true; - this.maybeOutputStatus(); - return; - } - this.canPush = true; - if (this.unpushedReadMessages.length > 0) { - const nextMessage = this.unpushedReadMessages.shift(); - this.push(nextMessage); - return; - } - /* Only resume reading from the http2Stream if we don't have any pending - * messages to emit */ - this.http2Stream.resume(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - const cb = (error) => { - /* nextTick here ensures that no stream action can be taken in the call - * stack of the write callback, in order to hopefully work around - * https://github.com/nodejs/node/issues/49147 */ - process.nextTick(() => { - var _a; - let code = constants_1.Status.UNAVAILABLE; - if ((error === null || error === void 0 ? void 0 : error.code) === - 'ERR_STREAM_WRITE_AFTER_END') { - code = constants_1.Status.INTERNAL; - } - if (error) { - this.cancelWithStatus(code, `Write error: ${error.message}`); - } - (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); - }); - }; - this.trace('sending data chunk of length ' + message.length); - this.callEventTracker.addMessageSent(); - try { - this.http2Stream.write(message, cb); - } - catch (error) { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: `Write failed with error ${error.message}`, - metadata: new metadata_1.Metadata(), - }); - } - } - halfClose() { - this.trace('end() called'); - this.trace('calling end() on HTTP/2 stream'); - this.http2Stream.end(); - } -} -exports.Http2SubchannelCall = Http2SubchannelCall; -//# sourceMappingURL=subchannel-call.js.map - -/***/ }), - -/***/ 12258: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseSubchannelWrapper = void 0; -class BaseSubchannelWrapper { - constructor(child) { - this.child = child; - this.healthy = true; - this.healthListeners = new Set(); - this.refcount = 0; - this.dataWatchers = new Set(); - child.addHealthStateWatcher(childHealthy => { - /* A change to the child health state only affects this wrapper's overall - * health state if this wrapper is reporting healthy. */ - if (this.healthy) { - this.updateHealthListeners(); - } - }); - } - updateHealthListeners() { - for (const listener of this.healthListeners) { - listener(this.isHealthy()); - } - } - getConnectivityState() { - return this.child.getConnectivityState(); - } - addConnectivityStateListener(listener) { - this.child.addConnectivityStateListener(listener); - } - removeConnectivityStateListener(listener) { - this.child.removeConnectivityStateListener(listener); - } - startConnecting() { - this.child.startConnecting(); - } - getAddress() { - return this.child.getAddress(); - } - throttleKeepalive(newKeepaliveTime) { - this.child.throttleKeepalive(newKeepaliveTime); - } - ref() { - this.child.ref(); - this.refcount += 1; - } - unref() { - this.child.unref(); - this.refcount -= 1; - if (this.refcount === 0) { - this.destroy(); - } - } - destroy() { - for (const watcher of this.dataWatchers) { - watcher.destroy(); - } - } - getChannelzRef() { - return this.child.getChannelzRef(); - } - isHealthy() { - return this.healthy && this.child.isHealthy(); - } - addHealthStateWatcher(listener) { - this.healthListeners.add(listener); - } - removeHealthStateWatcher(listener) { - this.healthListeners.delete(listener); - } - addDataWatcher(dataWatcher) { - dataWatcher.setSubchannel(this.getRealSubchannel()); - this.dataWatchers.add(dataWatcher); - } - setHealthy(healthy) { - if (healthy !== this.healthy) { - this.healthy = healthy; - /* A change to this wrapper's health state only affects the overall - * reported health state if the child is healthy. */ - if (this.child.isHealthy()) { - this.updateHealthListeners(); - } - } - } - getRealSubchannel() { - return this.child.getRealSubchannel(); - } - realSubchannelEquals(other) { - return this.getRealSubchannel() === other.getRealSubchannel(); - } - getCallCredentials() { - return this.child.getCallCredentials(); - } - getChannel() { - return this.child.getChannel(); - } -} -exports.BaseSubchannelWrapper = BaseSubchannelWrapper; -//# sourceMappingURL=subchannel-interface.js.map - -/***/ }), - -/***/ 87440: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SubchannelPool = void 0; -exports.getSubchannelPool = getSubchannelPool; -const channel_options_1 = __nccwpck_require__(99810); -const subchannel_1 = __nccwpck_require__(84764); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const transport_1 = __nccwpck_require__(46690); -// 10 seconds in milliseconds. This value is arbitrary. -/** - * The amount of time in between checks for dropping subchannels that have no - * other references - */ -const REF_CHECK_INTERVAL = 10000; -class SubchannelPool { - /** - * A pool of subchannels use for making connections. Subchannels with the - * exact same parameters will be reused. - */ - constructor() { - this.pool = Object.create(null); - /** - * A timer of a task performing a periodic subchannel cleanup. - */ - this.cleanupTimer = null; - } - /** - * Unrefs all unused subchannels and cancels the cleanup task if all - * subchannels have been unrefed. - */ - unrefUnusedSubchannels() { - let allSubchannelsUnrefed = true; - /* These objects are created with Object.create(null), so they do not - * have a prototype, which means that for (... in ...) loops over them - * do not need to be filtered */ - // eslint-disable-disable-next-line:forin - for (const channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - const refedSubchannels = subchannelObjArray.filter(value => !value.subchannel.unrefIfOneRef()); - if (refedSubchannels.length > 0) { - allSubchannelsUnrefed = false; - } - /* For each subchannel in the pool, try to unref it if it has - * exactly one ref (which is the ref from the pool itself). If that - * does happen, remove the subchannel from the pool */ - this.pool[channelTarget] = refedSubchannels; - } - /* Currently we do not delete keys with empty values. If that results - * in significant memory usage we should change it. */ - // Cancel the cleanup task if all subchannels have been unrefed. - if (allSubchannelsUnrefed && this.cleanupTimer !== null) { - clearInterval(this.cleanupTimer); - this.cleanupTimer = null; - } - } - /** - * Ensures that the cleanup task is spawned. - */ - ensureCleanupTask() { - var _a, _b; - if (this.cleanupTimer === null) { - this.cleanupTimer = setInterval(() => { - this.unrefUnusedSubchannels(); - }, REF_CHECK_INTERVAL); - // Unref because this timer should not keep the event loop running. - // Call unref only if it exists to address electron/electron#21162 - (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Get a subchannel if one already exists with exactly matching parameters. - * Otherwise, create and save a subchannel with those parameters. - * @param channelTarget - * @param subchannelTarget - * @param channelArguments - * @param channelCredentials - */ - getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { - this.ensureCleanupTask(); - const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); - if (channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - for (const subchannelObj of subchannelObjArray) { - if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && - (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && - channelCredentials._equals(subchannelObj.channelCredentials)) { - return subchannelObj.subchannel; - } - } - } - // If we get here, no matching subchannel was found - const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); - if (!(channelTarget in this.pool)) { - this.pool[channelTarget] = []; - } - this.pool[channelTarget].push({ - subchannelAddress: subchannelTarget, - channelArguments, - channelCredentials, - subchannel, - }); - subchannel.ref(); - return subchannel; - } -} -exports.SubchannelPool = SubchannelPool; -const globalSubchannelPool = new SubchannelPool(); -/** - * Get either the global subchannel pool, or a new subchannel pool. - * @param global - */ -function getSubchannelPool(global) { - if (global) { - return globalSubchannelPool; - } - else { - return new SubchannelPool(); - } -} -//# sourceMappingURL=subchannel-pool.js.map - -/***/ }), - -/***/ 84764: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Subchannel = void 0; -const connectivity_state_1 = __nccwpck_require__(80878); -const backoff_timeout_1 = __nccwpck_require__(34186); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const uri_parser_1 = __nccwpck_require__(65974); -const subchannel_address_1 = __nccwpck_require__(99905); -const channelz_1 = __nccwpck_require__(79975); -const single_subchannel_channel_1 = __nccwpck_require__(28812); -const TRACER_NAME = 'subchannel'; -/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't - * have a constant for the max signed 32 bit integer, so this is a simple way - * to calculate it */ -const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); -class Subchannel { - /** - * A class representing a connection to a single backend. - * @param channelTarget The target string for the channel as a whole - * @param subchannelAddress The address for the backend that this subchannel - * will connect to - * @param options The channel options, plus any specific subchannel options - * for this subchannel - * @param credentials The channel credentials used to establish this - * connection - */ - constructor(channelTarget, subchannelAddress, options, credentials, connector) { - var _a; - this.channelTarget = channelTarget; - this.subchannelAddress = subchannelAddress; - this.options = options; - this.connector = connector; - /** - * The subchannel's current connectivity state. Invariant: `session` === `null` - * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. - */ - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The underlying http2 session used to make requests. - */ - this.transport = null; - /** - * Indicates that the subchannel should transition from TRANSIENT_FAILURE to - * CONNECTING instead of IDLE when the backoff timeout ends. - */ - this.continueConnecting = false; - /** - * A list of listener functions that will be called whenever the connectivity - * state changes. Will be modified by `addConnectivityStateListener` and - * `removeConnectivityStateListener` - */ - this.stateListeners = new Set(); - /** - * Tracks channels and subchannel pools with references to this subchannel - */ - this.refcount = 0; - // Channelz info - this.channelzEnabled = true; - this.dataProducers = new Map(); - this.subchannelChannel = null; - const backoffOptions = { - initialDelay: options['grpc.initial_reconnect_backoff_ms'], - maxDelay: options['grpc.max_reconnect_backoff_ms'], - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - this.handleBackoffTimer(); - }, backoffOptions); - this.backoffTimeout.unref(); - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - this.keepaliveTime = (_a = options['grpc.keepalive_time_ms']) !== null && _a !== void 0 ? _a : -1; - if (options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } - else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace('CT_INFO', 'Subchannel created'); - this.trace('Subchannel constructed with options ' + - JSON.stringify(options, undefined, 2)); - this.secureConnector = credentials._createSecureConnector(channelTarget, options); - } - getChannelzInfo() { - return { - state: this.connectivityState, - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists(), - target: this.subchannelAddressString, - }; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - refTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'subchannel_refcount', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - handleBackoffTimer() { - if (this.continueConnecting) { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - } - else { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); - } - } - /** - * Start a backoff timer with the current nextBackoff timeout - */ - startBackoff() { - this.backoffTimeout.runOnce(); - } - stopBackoff() { - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - } - startConnectingInternal() { - let options = this.options; - if (options['grpc.keepalive_time_ms']) { - const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); - options = Object.assign(Object.assign({}, options), { 'grpc.keepalive_time_ms': adjustedKeepaliveTime }); - } - this.connector - .connect(this.subchannelAddress, this.secureConnector, options) - .then(transport => { - if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { - this.transport = transport; - if (this.channelzEnabled) { - this.childrenTracker.refChild(transport.getChannelzRef()); - } - transport.addDisconnectListener(tooManyPings => { - this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - if (tooManyPings && this.keepaliveTime > 0) { - this.keepaliveTime *= 2; - logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); - } - }); - } - else { - /* If we can't transition from CONNECTING to READY here, we will - * not be using this transport, so release its resources. */ - transport.shutdown(); - } - }, error => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`); - }); - } - /** - * Initiate a state transition from any element of oldStates to the new - * state. If the current connectivityState is not in oldStates, do nothing. - * @param oldStates The set of states to transition from - * @param newState The state to transition to - * @returns True if the state changed, false otherwise - */ - transitionToState(oldStates, newState, errorMessage) { - var _a, _b; - if (oldStates.indexOf(this.connectivityState) === -1) { - return false; - } - if (errorMessage) { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState] + - ' with error "' + errorMessage + '"'); - } - else { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - } - if (this.channelzEnabled) { - this.channelzTrace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); - } - const previousState = this.connectivityState; - this.connectivityState = newState; - switch (newState) { - case connectivity_state_1.ConnectivityState.READY: - this.stopBackoff(); - break; - case connectivity_state_1.ConnectivityState.CONNECTING: - this.startBackoff(); - this.startConnectingInternal(); - this.continueConnecting = false; - break; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown(); - this.transport = null; - /* If the backoff timer has already ended by the time we get to the - * TRANSIENT_FAILURE state, we want to immediately transition out of - * TRANSIENT_FAILURE as though the backoff timer is ending right now */ - if (!this.backoffTimeout.isRunning()) { - process.nextTick(() => { - this.handleBackoffTimer(); - }); - } - break; - case connectivity_state_1.ConnectivityState.IDLE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown(); - this.transport = null; - break; - default: - throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); - } - for (const listener of this.stateListeners) { - listener(this, previousState, newState, this.keepaliveTime, errorMessage); - } - return true; - } - ref() { - this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount + 1)); - this.refcount += 1; - } - unref() { - this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount - 1)); - this.refcount -= 1; - if (this.refcount === 0) { - this.channelzTrace.addTrace('CT_INFO', 'Shutting down'); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.secureConnector.destroy(); - process.nextTick(() => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - }); - } - } - unrefIfOneRef() { - if (this.refcount === 1) { - this.unref(); - return true; - } - return false; - } - createCall(metadata, host, method, listener) { - if (!this.transport) { - throw new Error('Cannot create call, subchannel not READY'); - } - let statsTracker; - if (this.channelzEnabled) { - this.callTracker.addCallStarted(); - this.streamTracker.addCallStarted(); - statsTracker = { - onCallEnd: status => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } - else { - this.callTracker.addCallFailed(); - } - }, - }; - } - else { - statsTracker = {}; - } - return this.transport.createCall(metadata, host, method, listener, statsTracker); - } - /** - * If the subchannel is currently IDLE, start connecting and switch to the - * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, - * the next time it would transition to IDLE, start connecting again instead. - * Otherwise, do nothing. - */ - startConnecting() { - process.nextTick(() => { - /* First, try to transition from IDLE to connecting. If that doesn't happen - * because the state is not currently IDLE, check if it is - * TRANSIENT_FAILURE, and if so indicate that it should go back to - * connecting after the backoff timer ends. Otherwise do nothing */ - if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.continueConnecting = true; - } - } - }); - } - /** - * Get the subchannel's current connectivity state. - */ - getConnectivityState() { - return this.connectivityState; - } - /** - * Add a listener function to be called whenever the subchannel's - * connectivity state changes. - * @param listener - */ - addConnectivityStateListener(listener) { - this.stateListeners.add(listener); - } - /** - * Remove a listener previously added with `addConnectivityStateListener` - * @param listener A reference to a function previously passed to - * `addConnectivityStateListener` - */ - removeConnectivityStateListener(listener) { - this.stateListeners.delete(listener); - } - /** - * Reset the backoff timeout, and immediately start connecting if in backoff. - */ - resetBackoff() { - process.nextTick(() => { - this.backoffTimeout.reset(); - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - }); - } - getAddress() { - return this.subchannelAddressString; - } - getChannelzRef() { - return this.channelzRef; - } - isHealthy() { - return true; - } - addHealthStateWatcher(listener) { - // Do nothing with the listener - } - removeHealthStateWatcher(listener) { - // Do nothing with the listener - } - getRealSubchannel() { - return this; - } - realSubchannelEquals(other) { - return other.getRealSubchannel() === this; - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - } - } - getCallCredentials() { - return this.secureConnector.getCallCredentials(); - } - getChannel() { - if (!this.subchannelChannel) { - this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options); - } - return this.subchannelChannel; - } - addDataWatcher(dataWatcher) { - throw new Error('Not implemented'); - } - getOrCreateDataProducer(name, createDataProducer) { - const existingProducer = this.dataProducers.get(name); - if (existingProducer) { - return existingProducer; - } - const newProducer = createDataProducer(this); - this.dataProducers.set(name, newProducer); - return newProducer; - } - removeDataProducer(name) { - this.dataProducers.delete(name); - } -} -exports.Subchannel = Subchannel; -//# sourceMappingURL=subchannel.js.map - -/***/ }), - -/***/ 86581: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CIPHER_SUITES = void 0; -exports.getDefaultRootsData = getDefaultRootsData; -const fs = __nccwpck_require__(57147); -exports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; -const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; -let defaultRootsData = null; -function getDefaultRootsData() { - if (DEFAULT_ROOTS_FILE_PATH) { - if (defaultRootsData === null) { - defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); - } - return defaultRootsData; - } - return null; -} -//# sourceMappingURL=tls-helpers.js.map - -/***/ }), - -/***/ 46690: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2023 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Http2SubchannelConnector = void 0; -const http2 = __nccwpck_require__(85158); -const tls_1 = __nccwpck_require__(24404); -const channelz_1 = __nccwpck_require__(79975); -const constants_1 = __nccwpck_require__(90634); -const http_proxy_1 = __nccwpck_require__(24000); -const logging = __nccwpck_require__(35993); -const resolver_1 = __nccwpck_require__(31594); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const net = __nccwpck_require__(41808); -const subchannel_call_1 = __nccwpck_require__(86940); -const call_number_1 = __nccwpck_require__(70380); -const TRACER_NAME = 'transport'; -const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; -const clientVersion = (__nccwpck_require__(56569)/* .version */ .i8); -const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT, } = http2.constants; -const KEEPALIVE_TIMEOUT_MS = 20000; -const tooManyPingsData = Buffer.from('too_many_pings', 'ascii'); -class Http2Transport { - constructor(session, subchannelAddress, options, - /** - * Name of the remote server, if it is not the same as the subchannel - * address, i.e. if connecting through an HTTP CONNECT proxy. - */ - remoteName) { - this.session = session; - this.options = options; - this.remoteName = remoteName; - /** - * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. - */ - this.keepaliveTimer = null; - /** - * Indicates that the keepalive timer ran out while there were no active - * calls, and a ping should be sent the next time a call starts. - */ - this.pendingSendKeepalivePing = false; - this.activeCalls = new Set(); - this.disconnectListeners = []; - this.disconnectHandled = false; - this.channelzEnabled = true; - this.keepalivesSent = 0; - this.messagesSent = 0; - this.messagesReceived = 0; - this.lastMessageSentTimestamp = null; - this.lastMessageReceivedTimestamp = null; - /* Populate subchannelAddressString and channelzRef before doing anything - * else, because they are used in the trace methods. */ - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - if (options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } - else { - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - // Build user-agent string. - this.userAgent = [ - options['grpc.primary_user_agent'], - `grpc-node-js/${clientVersion}`, - options['grpc.secondary_user_agent'], - ] - .filter(e => e) - .join(' '); // remove falsey values first - if ('grpc.keepalive_time_ms' in options) { - this.keepaliveTimeMs = options['grpc.keepalive_time_ms']; - } - else { - this.keepaliveTimeMs = -1; - } - if ('grpc.keepalive_timeout_ms' in options) { - this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']; - } - else { - this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; - } - if ('grpc.keepalive_permit_without_calls' in options) { - this.keepaliveWithoutCalls = - options['grpc.keepalive_permit_without_calls'] === 1; - } - else { - this.keepaliveWithoutCalls = false; - } - session.once('close', () => { - this.trace('session closed'); - this.handleDisconnect(); - }); - session.once('goaway', (errorCode, lastStreamID, opaqueData) => { - let tooManyPings = false; - /* See the last paragraph of - * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ - if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && - opaqueData && - opaqueData.equals(tooManyPingsData)) { - tooManyPings = true; - } - this.trace('connection closed by GOAWAY with code ' + - errorCode + - ' and data ' + - (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); - this.reportDisconnectToOwner(tooManyPings); - }); - session.once('error', error => { - this.trace('connection closed with error ' + error.message); - this.handleDisconnect(); - }); - session.socket.once('close', (hadError) => { - this.trace('connection closed. hadError=' + hadError); - this.handleDisconnect(); - }); - if (logging.isTracerEnabled(TRACER_NAME)) { - session.on('remoteSettings', (settings) => { - this.trace('new settings received' + - (this.session !== session ? ' on the old connection' : '') + - ': ' + - JSON.stringify(settings)); - }); - session.on('localSettings', (settings) => { - this.trace('local settings acknowledged by remote' + - (this.session !== session ? ' on the old connection' : '') + - ': ' + - JSON.stringify(settings)); - }); - } - /* Start the keepalive timer last, because this can trigger trace logs, - * which should only happen after everything else is set up. */ - if (this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - if (session.socket instanceof tls_1.TLSSocket) { - this.authContext = { - transportSecurityType: 'ssl', - sslPeerCertificate: session.socket.getPeerCertificate() - }; - } - else { - this.authContext = {}; - } - } - getChannelzInfo() { - var _a, _b, _c; - const sessionSocket = this.session.socket; - const remoteAddress = sessionSocket.remoteAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) - : null; - const localAddress = sessionSocket.localAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) - : null; - let tlsInfo; - if (this.session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && 'raw' in peerCertificate - ? peerCertificate.raw - : null, - }; - } - else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress: remoteAddress, - localAddress: localAddress, - security: tlsInfo, - remoteName: this.remoteName, - streamsStarted: this.streamTracker.callsStarted, - streamsSucceeded: this.streamTracker.callsSucceeded, - streamsFailed: this.streamTracker.callsFailed, - messagesSent: this.messagesSent, - messagesReceived: this.messagesReceived, - keepAlivesSent: this.keepalivesSent, - lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: this.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, - localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, - remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null, - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - flowControlTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - internalsTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'transport_internals', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - /** - * Indicate to the owner of this object that this transport should no longer - * be used. That happens if the connection drops, or if the server sends a - * GOAWAY. - * @param tooManyPings If true, this was triggered by a GOAWAY with data - * indicating that the session was closed becaues the client sent too many - * pings. - * @returns - */ - reportDisconnectToOwner(tooManyPings) { - if (this.disconnectHandled) { - return; - } - this.disconnectHandled = true; - this.disconnectListeners.forEach(listener => listener(tooManyPings)); - } - /** - * Handle connection drops, but not GOAWAYs. - */ - handleDisconnect() { - this.clearKeepaliveTimeout(); - this.reportDisconnectToOwner(false); - for (const call of this.activeCalls) { - call.onDisconnect(); - } - // Wait an event loop cycle before destroying the connection - setImmediate(() => { - this.session.destroy(); - }); - } - addDisconnectListener(listener) { - this.disconnectListeners.push(listener); - } - canSendPing() { - return (!this.session.destroyed && - this.keepaliveTimeMs > 0 && - (this.keepaliveWithoutCalls || this.activeCalls.size > 0)); - } - maybeSendPing() { - var _a, _b; - if (!this.canSendPing()) { - this.pendingSendKeepalivePing = true; - return; - } - if (this.keepaliveTimer) { - console.error('keepaliveTimeout is not null'); - return; - } - if (this.channelzEnabled) { - this.keepalivesSent += 1; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.keepaliveTrace('Ping timeout passed without response'); - this.handleDisconnect(); - }, this.keepaliveTimeoutMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - let pingSendError = ''; - try { - const pingSentSuccessfully = this.session.ping((err, duration, payload) => { - this.clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error ' + err.message); - this.handleDisconnect(); - } - else { - this.keepaliveTrace('Received ping response'); - this.maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.handleDisconnect(); - } - } - /** - * Starts the keepalive ping timer if appropriate. If the timer already ran - * out while there were no active requests, instead send a ping immediately. - * If the ping timer is already running or a ping is currently in flight, - * instead do nothing and wait for them to resolve. - */ - maybeStartKeepalivePingTimer() { - var _a, _b; - if (!this.canSendPing()) { - return; - } - if (this.pendingSendKeepalivePing) { - this.pendingSendKeepalivePing = false; - this.maybeSendPing(); - } - else if (!this.keepaliveTimer) { - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.maybeSendPing(); - }, this.keepaliveTimeMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /* Otherwise, there is already either a keepalive timer or a ping pending, - * wait for those to resolve. */ - } - /** - * Clears whichever keepalive timeout is currently active, if any. - */ - clearKeepaliveTimeout() { - if (this.keepaliveTimer) { - clearTimeout(this.keepaliveTimer); - this.keepaliveTimer = null; - } - } - removeActiveCall(call) { - this.activeCalls.delete(call); - if (this.activeCalls.size === 0) { - this.session.unref(); - } - } - addActiveCall(call) { - this.activeCalls.add(call); - if (this.activeCalls.size === 1) { - this.session.ref(); - if (!this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - } - } - createCall(metadata, host, method, listener, subchannelCallStatsTracker) { - const headers = metadata.toHttp2Headers(); - headers[HTTP2_HEADER_AUTHORITY] = host; - headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; - headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; - headers[HTTP2_HEADER_METHOD] = 'POST'; - headers[HTTP2_HEADER_PATH] = method; - headers[HTTP2_HEADER_TE] = 'trailers'; - let http2Stream; - /* In theory, if an error is thrown by session.request because session has - * become unusable (e.g. because it has received a goaway), this subchannel - * should soon see the corresponding close or goaway event anyway and leave - * READY. But we have seen reports that this does not happen - * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) - * so for defense in depth, we just discard the session when we see an - * error here. - */ - try { - http2Stream = this.session.request(headers); - } - catch (e) { - this.handleDisconnect(); - throw e; - } - this.flowControlTrace('local window size: ' + - this.session.state.localWindowSize + - ' remote window size: ' + - this.session.state.remoteWindowSize); - this.internalsTrace('session.closed=' + - this.session.closed + - ' session.destroyed=' + - this.session.destroyed + - ' session.socket.destroyed=' + - this.session.socket.destroyed); - let eventTracker; - // eslint-disable-next-line prefer-const - let call; - if (this.channelzEnabled) { - this.streamTracker.addCallStarted(); - eventTracker = { - addMessageSent: () => { - var _a; - this.messagesSent += 1; - this.lastMessageSentTimestamp = new Date(); - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - this.messagesReceived += 1; - this.lastMessageReceivedTimestamp = new Date(); - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: status => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: success => { - var _a; - if (success) { - this.streamTracker.addCallSucceeded(); - } - else { - this.streamTracker.addCallFailed(); - } - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - }, - }; - } - else { - eventTracker = { - addMessageSent: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: status => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: success => { - var _a; - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - }, - }; - } - call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); - this.addActiveCall(call); - return call; - } - getChannelzRef() { - return this.channelzRef; - } - getPeerName() { - return this.subchannelAddressString; - } - getOptions() { - return this.options; - } - getAuthContext() { - return this.authContext; - } - shutdown() { - this.session.close(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } -} -class Http2SubchannelConnector { - constructor(channelTarget) { - this.channelTarget = channelTarget; - this.session = null; - this.isShutdown = false; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + ' ' + text); - } - createSession(secureConnectResult, address, options) { - if (this.isShutdown) { - return Promise.reject(); - } - if (secureConnectResult.socket.closed) { - return Promise.reject('Connection closed before starting HTTP/2 handshake'); - } - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e, _f, _g; - let remoteName = null; - let realTarget = this.channelTarget; - if ('grpc.http_connect_target' in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); - if (parsedTarget) { - realTarget = parsedTarget; - remoteName = (0, uri_parser_1.uriToString)(parsedTarget); - } - } - const scheme = secureConnectResult.secure ? 'https' : 'http'; - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const closeHandler = () => { - var _a; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); - this.session = null; - // Leave time for error event to happen before rejecting - setImmediate(() => { - if (!reportedError) { - reportedError = true; - reject(`${errorMessage.trim()} (${new Date().toISOString()})`); - } - }); - }; - const errorHandler = (error) => { - var _a; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); - errorMessage = error.message; - this.trace('connection failed with error ' + errorMessage); - if (!reportedError) { - reportedError = true; - reject(`${errorMessage} (${new Date().toISOString()})`); - } - }; - const sessionOptions = { - createConnection: (authority, option) => { - return secureConnectResult.socket; - }, - settings: { - initialWindowSize: (_d = (_a = options['grpc-node.flow_control_window']) !== null && _a !== void 0 ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === void 0 ? void 0 : _b.call(http2)) === null || _c === void 0 ? void 0 : _c.initialWindowSize) !== null && _d !== void 0 ? _d : 65535, - } - }; - const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); - // Prepare window size configuration for remoteSettings handler - const defaultWin = (_g = (_f = (_e = http2.getDefaultSettings) === null || _e === void 0 ? void 0 : _e.call(http2)) === null || _f === void 0 ? void 0 : _f.initialWindowSize) !== null && _g !== void 0 ? _g : 65535; // 65 535 B - const connWin = options['grpc-node.flow_control_window']; - this.session = session; - let errorMessage = 'Failed to connect'; - let reportedError = false; - session.unref(); - session.once('remoteSettings', () => { - var _a; - // Send WINDOW_UPDATE now to avoid 65 KB start-window stall. - if (connWin && connWin > defaultWin) { - try { - // Node ≄ 14.18 - session.setLocalWindowSize(connWin); - } - catch (_b) { - // Older Node: bump by the delta - const delta = connWin - ((_a = session.state.localWindowSize) !== null && _a !== void 0 ? _a : defaultWin); - if (delta > 0) - session.incrementWindowSize(delta); - } - } - session.removeAllListeners(); - secureConnectResult.socket.removeListener('close', closeHandler); - secureConnectResult.socket.removeListener('error', errorHandler); - resolve(new Http2Transport(session, address, options, remoteName)); - this.session = null; - }); - session.once('close', closeHandler); - session.once('error', errorHandler); - secureConnectResult.socket.once('close', closeHandler); - secureConnectResult.socket.once('error', errorHandler); - }); - } - tcpConnect(address, options) { - return (0, http_proxy_1.getProxiedConnection)(address, options).then(proxiedSocket => { - if (proxiedSocket) { - return proxiedSocket; - } - else { - return new Promise((resolve, reject) => { - const closeCallback = () => { - reject(new Error('Socket closed')); - }; - const errorCallback = (error) => { - reject(error); - }; - const socket = net.connect(address, () => { - socket.removeListener('close', closeCallback); - socket.removeListener('error', errorCallback); - resolve(socket); - }); - socket.once('close', closeCallback); - socket.once('error', errorCallback); - }); - } - }); - } - async connect(address, secureConnector, options) { - if (this.isShutdown) { - return Promise.reject(); - } - let tcpConnection = null; - let secureConnectResult = null; - const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); - try { - this.trace(addressString + ' Waiting for secureConnector to be ready'); - await secureConnector.waitForReady(); - this.trace(addressString + ' secureConnector is ready'); - tcpConnection = await this.tcpConnect(address, options); - tcpConnection.setNoDelay(); - this.trace(addressString + ' Established TCP connection'); - secureConnectResult = await secureConnector.connect(tcpConnection); - this.trace(addressString + ' Established secure connection'); - return this.createSession(secureConnectResult, address, options); - } - catch (e) { - tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); - secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy(); - throw e; - } - } - shutdown() { - var _a; - this.isShutdown = true; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.close(); - this.session = null; - } -} -exports.Http2SubchannelConnector = Http2SubchannelConnector; -//# sourceMappingURL=transport.js.map - -/***/ }), - -/***/ 65974: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2020 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseUri = parseUri; -exports.splitHostPort = splitHostPort; -exports.combineHostPort = combineHostPort; -exports.uriToString = uriToString; -/* - * The groups correspond to URI parts as follows: - * 1. scheme - * 2. authority - * 3. path - */ -const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; -function parseUri(uriString) { - const parsedUri = URI_REGEX.exec(uriString); - if (parsedUri === null) { - return null; - } - return { - scheme: parsedUri[1], - authority: parsedUri[2], - path: parsedUri[3], - }; -} -const NUMBER_REGEX = /^\d+$/; -function splitHostPort(path) { - if (path.startsWith('[')) { - const hostEnd = path.indexOf(']'); - if (hostEnd === -1) { - return null; - } - const host = path.substring(1, hostEnd); - /* Only an IPv6 address should be in bracketed notation, and an IPv6 - * address should have at least one colon */ - if (host.indexOf(':') === -1) { - return null; - } - if (path.length > hostEnd + 1) { - if (path[hostEnd + 1] === ':') { - const portString = path.substring(hostEnd + 2); - if (NUMBER_REGEX.test(portString)) { - return { - host: host, - port: +portString, - }; - } - else { - return null; - } - } - else { - return null; - } - } - else { - return { - host, - }; - } - } - else { - const splitPath = path.split(':'); - /* Exactly one colon means that this is host:port. Zero colons means that - * there is no port. And multiple colons means that this is a bare IPv6 - * address with no port */ - if (splitPath.length === 2) { - if (NUMBER_REGEX.test(splitPath[1])) { - return { - host: splitPath[0], - port: +splitPath[1], - }; - } - else { - return null; - } - } - else { - return { - host: path, - }; - } - } -} -function combineHostPort(hostPort) { - if (hostPort.port === undefined) { - return hostPort.host; - } - else { - // Only an IPv6 host should include a colon - if (hostPort.host.includes(':')) { - return `[${hostPort.host}]:${hostPort.port}`; - } - else { - return `${hostPort.host}:${hostPort.port}`; - } - } -} -function uriToString(uri) { - let result = ''; - if (uri.scheme !== undefined) { - result += uri.scheme + ':'; - } - if (uri.authority !== undefined) { - result += '//' + uri.authority + '/'; - } - result += uri.path; - return result; -} -//# sourceMappingURL=uri-parser.js.map - -/***/ }), - -/***/ 48934: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var __webpack_unused_export__; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -__webpack_unused_export__ = ({ value: true }); -__webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = exports.J_ = __webpack_unused_export__ = exports.Cp = __webpack_unused_export__ = __webpack_unused_export__ = void 0; -const camelCase = __nccwpck_require__(7994); -const Protobuf = __nccwpck_require__(85881); -const descriptor = __nccwpck_require__(21629); -const util_1 = __nccwpck_require__(32358); -const Long = __nccwpck_require__(52694); -__webpack_unused_export__ = Long; -function isAnyExtension(obj) { - return ('@type' in obj) && (typeof obj['@type'] === 'string'); -} -__webpack_unused_export__ = isAnyExtension; -var IdempotencyLevel; -(function (IdempotencyLevel) { - IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; -})(IdempotencyLevel = exports.Cp || (exports.Cp = {})); -const descriptorOptions = { - longs: String, - enums: String, - bytes: String, - defaults: true, - oneofs: true, - json: true, -}; -function joinName(baseName, name) { - if (baseName === '') { - return name; - } - else { - return baseName + '.' + name; - } -} -function isHandledReflectionObject(obj) { - return (obj instanceof Protobuf.Service || - obj instanceof Protobuf.Type || - obj instanceof Protobuf.Enum); -} -function isNamespaceBase(obj) { - return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; -} -function getAllHandledReflectionObjects(obj, parentName) { - const objName = joinName(parentName, obj.name); - if (isHandledReflectionObject(obj)) { - return [[objName, obj]]; - } - else { - if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { - return Object.keys(obj.nested) - .map(name => { - return getAllHandledReflectionObjects(obj.nested[name], objName); - }) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - } - } - return []; -} -function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; -} -function createSerializer(cls) { - return function serialize(arg) { - if (Array.isArray(arg)) { - throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); - } - const message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; -} -function mapMethodOptions(options) { - return (options || []).reduce((obj, item) => { - for (const [key, value] of Object.entries(item)) { - switch (key) { - case 'uninterpreted_option': - obj.uninterpreted_option.push(item.uninterpreted_option); - break; - default: - obj[key] = value; - } - } - return obj; - }, { - deprecated: false, - idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, - uninterpreted_option: [], - }); -} -function createMethodDefinition(method, serviceName, options, fileDescriptors) { - /* This is only ever called after the corresponding root.resolveAll(), so we - * can assume that the resolved request and response types are non-null */ - const requestType = method.resolvedRequestType; - const responseType = method.resolvedResponseType; - return { - path: '/' + serviceName + '/' + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(requestType), - requestDeserialize: createDeserializer(requestType, options), - responseSerialize: createSerializer(responseType), - responseDeserialize: createDeserializer(responseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: camelCase(method.name), - requestType: createMessageDefinition(requestType, options, fileDescriptors), - responseType: createMessageDefinition(responseType, options, fileDescriptors), - options: mapMethodOptions(method.parsedOptions), - }; -} -function createServiceDefinition(service, name, options, fileDescriptors) { - const def = {}; - for (const method of service.methodsArray) { - def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); - } - return def; -} -function createMessageDefinition(message, options, fileDescriptors) { - const messageDescriptor = message.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 DescriptorProto', - type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - serialize: createSerializer(message), - deserialize: createDeserializer(message, options) - }; -} -function createEnumDefinition(enumType, fileDescriptors) { - const enumDescriptor = enumType.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 EnumDescriptorProto', - type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - }; -} -/** - * function createDefinition(obj: Protobuf.Service, name: string, options: - * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, - * name: string, options: Options): MessageTypeDefinition; function - * createDefinition(obj: Protobuf.Enum, name: string, options: Options): - * EnumTypeDefinition; - */ -function createDefinition(obj, name, options, fileDescriptors) { - if (obj instanceof Protobuf.Service) { - return createServiceDefinition(obj, name, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Type) { - return createMessageDefinition(obj, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Enum) { - return createEnumDefinition(obj, fileDescriptors); - } - else { - throw new Error('Type mismatch in reflection object handling'); - } -} -function createPackageDefinition(root, options) { - const def = {}; - root.resolveAll(); - const descriptorList = root.toDescriptor('proto3').file; - const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); - for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { - def[name] = createDefinition(obj, name, options, bufferList); - } - return def; -} -function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { - options = options || {}; - const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); - root.resolveAll(); - return createPackageDefinition(root, options); -} -/** - * Load a .proto file with the specified options. - * @param filename One or multiple file paths to load. Can be an absolute path - * or relative to an include path. - * @param options.keepCase Preserve field names. The default is to change them - * to camel case. - * @param options.longs The type that should be used to represent `long` values. - * Valid options are `Number` and `String`. Defaults to a `Long` object type - * from a library. - * @param options.enums The type that should be used to represent `enum` values. - * The only valid option is `String`. Defaults to the numeric value. - * @param options.bytes The type that should be used to represent `bytes` - * values. Valid options are `Array` and `String`. The default is to use - * `Buffer`. - * @param options.defaults Set default values on output objects. Defaults to - * `false`. - * @param options.arrays Set empty arrays for missing array values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.objects Set empty objects for missing object values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.oneofs Set virtual oneof properties to the present field's - * name - * @param options.json Represent Infinity and NaN as strings in float fields, - * and automatically decode google.protobuf.Any values. - * @param options.includeDirs Paths to search for imported `.proto` files. - */ -function load(filename, options) { - return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { - return createPackageDefinition(loadedRoot, options); - }); -} -__webpack_unused_export__ = load; -function loadSync(filename, options) { - const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); - return createPackageDefinition(loadedRoot, options); -} -exports.J_ = loadSync; -function fromJSON(json, options) { - options = options || {}; - const loadedRoot = Protobuf.Root.fromJSON(json); - loadedRoot.resolveAll(); - return createPackageDefinition(loadedRoot, options); -} -__webpack_unused_export__ = fromJSON; -function loadFileDescriptorSetFromBuffer(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -__webpack_unused_export__ = loadFileDescriptorSetFromBuffer; -function loadFileDescriptorSetFromObject(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -__webpack_unused_export__ = loadFileDescriptorSetFromObject; -(0, util_1.addCommonProtos)(); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 32358: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; -const fs = __nccwpck_require__(57147); -const path = __nccwpck_require__(71017); -const Protobuf = __nccwpck_require__(85881); -function addIncludePathResolver(root, includePaths) { - const originalResolvePath = root.resolvePath; - root.resolvePath = (origin, target) => { - if (path.isAbsolute(target)) { - return target; - } - for (const directory of includePaths) { - const fullPath = path.join(directory, target); - try { - fs.accessSync(fullPath, fs.constants.R_OK); - return fullPath; - } - catch (err) { - continue; - } - } - process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); - return originalResolvePath(origin, target); - }; -} -async function loadProtosWithOptions(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - return Promise.reject(new Error('The includeDirs option must be an array')); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = await root.load(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptions = loadProtosWithOptions; -function loadProtosWithOptionsSync(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - throw new Error('The includeDirs option must be an array'); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; -/** - * Load Google's well-known proto files that aren't exposed by Protobuf.js. - */ -function addCommonProtos() { - // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, - // and wrappers. compiler/plugin is excluded in Protobuf.js and here. - // Using constant strings for compatibility with tools like Webpack - const apiDescriptor = __nccwpck_require__(44784); - const descriptorDescriptor = __nccwpck_require__(43571); - const sourceContextDescriptor = __nccwpck_require__(73342); - const typeDescriptor = __nccwpck_require__(58783); - Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); -} -exports.addCommonProtos = addCommonProtos; -//# sourceMappingURL=util.js.map - -/***/ }), - -/***/ 98171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = void 0; -const camelCase = __nccwpck_require__(7994); -const Protobuf = __nccwpck_require__(85881); -const descriptor = __nccwpck_require__(21629); -const util_1 = __nccwpck_require__(13245); -const Long = __nccwpck_require__(52694); -exports.Long = Long; -function isAnyExtension(obj) { - return ('@type' in obj) && (typeof obj['@type'] === 'string'); -} -exports.isAnyExtension = isAnyExtension; -var IdempotencyLevel; -(function (IdempotencyLevel) { - IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; -})(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {})); -const descriptorOptions = { - longs: String, - enums: String, - bytes: String, - defaults: true, - oneofs: true, - json: true, -}; -function joinName(baseName, name) { - if (baseName === '') { - return name; - } - else { - return baseName + '.' + name; - } -} -function isHandledReflectionObject(obj) { - return (obj instanceof Protobuf.Service || - obj instanceof Protobuf.Type || - obj instanceof Protobuf.Enum); -} -function isNamespaceBase(obj) { - return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; -} -function getAllHandledReflectionObjects(obj, parentName) { - const objName = joinName(parentName, obj.name); - if (isHandledReflectionObject(obj)) { - return [[objName, obj]]; - } - else { - if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { - return Object.keys(obj.nested) - .map(name => { - return getAllHandledReflectionObjects(obj.nested[name], objName); - }) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - } - } - return []; -} -function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; -} -function createSerializer(cls) { - return function serialize(arg) { - if (Array.isArray(arg)) { - throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); - } - const message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; -} -function mapMethodOptions(options) { - return (options || []).reduce((obj, item) => { - for (const [key, value] of Object.entries(item)) { - switch (key) { - case 'uninterpreted_option': - obj.uninterpreted_option.push(item.uninterpreted_option); - break; - default: - obj[key] = value; - } - } - return obj; - }, { - deprecated: false, - idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, - uninterpreted_option: [], - }); -} -function createMethodDefinition(method, serviceName, options, fileDescriptors) { - /* This is only ever called after the corresponding root.resolveAll(), so we - * can assume that the resolved request and response types are non-null */ - const requestType = method.resolvedRequestType; - const responseType = method.resolvedResponseType; - return { - path: '/' + serviceName + '/' + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(requestType), - requestDeserialize: createDeserializer(requestType, options), - responseSerialize: createSerializer(responseType), - responseDeserialize: createDeserializer(responseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: camelCase(method.name), - requestType: createMessageDefinition(requestType, fileDescriptors), - responseType: createMessageDefinition(responseType, fileDescriptors), - options: mapMethodOptions(method.parsedOptions), - }; -} -function createServiceDefinition(service, name, options, fileDescriptors) { - const def = {}; - for (const method of service.methodsArray) { - def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); - } - return def; -} -function createMessageDefinition(message, fileDescriptors) { - const messageDescriptor = message.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 DescriptorProto', - type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - }; -} -function createEnumDefinition(enumType, fileDescriptors) { - const enumDescriptor = enumType.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 EnumDescriptorProto', - type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - }; -} -/** - * function createDefinition(obj: Protobuf.Service, name: string, options: - * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, - * name: string, options: Options): MessageTypeDefinition; function - * createDefinition(obj: Protobuf.Enum, name: string, options: Options): - * EnumTypeDefinition; - */ -function createDefinition(obj, name, options, fileDescriptors) { - if (obj instanceof Protobuf.Service) { - return createServiceDefinition(obj, name, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Type) { - return createMessageDefinition(obj, fileDescriptors); - } - else if (obj instanceof Protobuf.Enum) { - return createEnumDefinition(obj, fileDescriptors); - } - else { - throw new Error('Type mismatch in reflection object handling'); - } -} -function createPackageDefinition(root, options) { - const def = {}; - root.resolveAll(); - const descriptorList = root.toDescriptor('proto3').file; - const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); - for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { - def[name] = createDefinition(obj, name, options, bufferList); - } - return def; -} -function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { - options = options || {}; - const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); - root.resolveAll(); - return createPackageDefinition(root, options); -} -/** - * Load a .proto file with the specified options. - * @param filename One or multiple file paths to load. Can be an absolute path - * or relative to an include path. - * @param options.keepCase Preserve field names. The default is to change them - * to camel case. - * @param options.longs The type that should be used to represent `long` values. - * Valid options are `Number` and `String`. Defaults to a `Long` object type - * from a library. - * @param options.enums The type that should be used to represent `enum` values. - * The only valid option is `String`. Defaults to the numeric value. - * @param options.bytes The type that should be used to represent `bytes` - * values. Valid options are `Array` and `String`. The default is to use - * `Buffer`. - * @param options.defaults Set default values on output objects. Defaults to - * `false`. - * @param options.arrays Set empty arrays for missing array values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.objects Set empty objects for missing object values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.oneofs Set virtual oneof properties to the present field's - * name - * @param options.json Represent Infinity and NaN as strings in float fields, - * and automatically decode google.protobuf.Any values. - * @param options.includeDirs Paths to search for imported `.proto` files. - */ -function load(filename, options) { - return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { - return createPackageDefinition(loadedRoot, options); - }); -} -exports.load = load; -function loadSync(filename, options) { - const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); - return createPackageDefinition(loadedRoot, options); -} -exports.loadSync = loadSync; -function fromJSON(json, options) { - options = options || {}; - const loadedRoot = Protobuf.Root.fromJSON(json); - loadedRoot.resolveAll(); - return createPackageDefinition(loadedRoot, options); -} -exports.fromJSON = fromJSON; -function loadFileDescriptorSetFromBuffer(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; -function loadFileDescriptorSetFromObject(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; -(0, util_1.addCommonProtos)(); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 13245: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; -const fs = __nccwpck_require__(57147); -const path = __nccwpck_require__(71017); -const Protobuf = __nccwpck_require__(85881); -function addIncludePathResolver(root, includePaths) { - const originalResolvePath = root.resolvePath; - root.resolvePath = (origin, target) => { - if (path.isAbsolute(target)) { - return target; - } - for (const directory of includePaths) { - const fullPath = path.join(directory, target); - try { - fs.accessSync(fullPath, fs.constants.R_OK); - return fullPath; - } - catch (err) { - continue; - } - } - process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); - return originalResolvePath(origin, target); - }; -} -async function loadProtosWithOptions(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - return Promise.reject(new Error('The includeDirs option must be an array')); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = await root.load(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptions = loadProtosWithOptions; -function loadProtosWithOptionsSync(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - throw new Error('The includeDirs option must be an array'); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; -/** - * Load Google's well-known proto files that aren't exposed by Protobuf.js. - */ -function addCommonProtos() { - // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, - // and wrappers. compiler/plugin is excluded in Protobuf.js and here. - // Using constant strings for compatibility with tools like Webpack - const apiDescriptor = __nccwpck_require__(44784); - const descriptorDescriptor = __nccwpck_require__(43571); - const sourceContextDescriptor = __nccwpck_require__(73342); - const typeDescriptor = __nccwpck_require__(58783); - Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); -} -exports.addCommonProtos = addCommonProtos; -//# sourceMappingURL=util.js.map - -/***/ }), - -/***/ 12592: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "t", ({ - value: true -})); - -class TreeNode { - constructor(t, e, s = 1) { - this.i = undefined; - this.h = undefined; - this.o = undefined; - this.u = t; - this.l = e; - this.p = s; - } - I() { - let t = this; - const e = t.o.o === t; - if (e && t.p === 1) { - t = t.h; - } else if (t.i) { - t = t.i; - while (t.h) { - t = t.h; - } - } else { - if (e) { - return t.o; - } - let s = t.o; - while (s.i === t) { - t = s; - s = t.o; - } - t = s; - } - return t; - } - B() { - let t = this; - if (t.h) { - t = t.h; - while (t.i) { - t = t.i; - } - return t; - } else { - let e = t.o; - while (e.h === t) { - t = e; - e = t.o; - } - if (t.h !== e) { - return e; - } else return t; - } - } - _() { - const t = this.o; - const e = this.h; - const s = e.i; - if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; - e.o = t; - e.i = this; - this.o = e; - this.h = s; - if (s) s.o = this; - return e; - } - g() { - const t = this.o; - const e = this.i; - const s = e.h; - if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; - e.o = t; - e.h = this; - this.o = e; - this.i = s; - if (s) s.o = this; - return e; - } -} - -class TreeNodeEnableIndex extends TreeNode { - constructor() { - super(...arguments); - this.M = 1; - } - _() { - const t = super._(); - this.O(); - t.O(); - return t; - } - g() { - const t = super.g(); - this.O(); - t.O(); - return t; - } - O() { - this.M = 1; - if (this.i) { - this.M += this.i.M; - } - if (this.h) { - this.M += this.h.M; - } - } -} - -class ContainerIterator { - constructor(t = 0) { - this.iteratorType = t; - } - equals(t) { - return this.T === t.T; - } -} - -class Base { - constructor() { - this.m = 0; - } - get length() { - return this.m; - } - size() { - return this.m; - } - empty() { - return this.m === 0; - } -} - -class Container extends Base {} - -function throwIteratorAccessError() { - throw new RangeError("Iterator access denied!"); -} - -class TreeContainer extends Container { - constructor(t = function(t, e) { - if (t < e) return -1; - if (t > e) return 1; - return 0; - }, e = false) { - super(); - this.v = undefined; - this.A = t; - this.enableIndex = e; - this.N = e ? TreeNodeEnableIndex : TreeNode; - this.C = new this.N; - } - R(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - t = t.h; - } else if (i > 0) { - s = t; - t = t.i; - } else return t; - } - return s; - } - K(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i <= 0) { - t = t.h; - } else { - s = t; - t = t.i; - } - } - return s; - } - L(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else if (i > 0) { - t = t.i; - } else return t; - } - return s; - } - k(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else { - t = t.i; - } - } - return s; - } - P(t) { - while (true) { - const e = t.o; - if (e === this.C) return; - if (t.p === 1) { - t.p = 0; - return; - } - if (t === e.i) { - const s = e.h; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e._(); - } else e._(); - } else { - if (s.h && s.h.p === 1) { - s.p = e.p; - e.p = 0; - s.h.p = 0; - if (e === this.v) { - this.v = e._(); - } else e._(); - return; - } else if (s.i && s.i.p === 1) { - s.p = 1; - s.i.p = 0; - s.g(); - } else { - s.p = 1; - t = e; - } - } - } else { - const s = e.i; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - } else { - if (s.i && s.i.p === 1) { - s.p = e.p; - e.p = 0; - s.i.p = 0; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - return; - } else if (s.h && s.h.p === 1) { - s.p = 1; - s.h.p = 0; - s._(); - } else { - s.p = 1; - t = e; - } - } - } - } - } - S(t) { - if (this.m === 1) { - this.clear(); - return; - } - let e = t; - while (e.i || e.h) { - if (e.h) { - e = e.h; - while (e.i) e = e.i; - } else { - e = e.i; - } - const s = t.u; - t.u = e.u; - e.u = s; - const i = t.l; - t.l = e.l; - e.l = i; - t = e; - } - if (this.C.i === e) { - this.C.i = e.o; - } else if (this.C.h === e) { - this.C.h = e.o; - } - this.P(e); - let s = e.o; - if (e === s.i) { - s.i = undefined; - } else s.h = undefined; - this.m -= 1; - this.v.p = 0; - if (this.enableIndex) { - while (s !== this.C) { - s.M -= 1; - s = s.o; - } - } - } - U(t) { - const e = typeof t === "number" ? t : undefined; - const s = typeof t === "function" ? t : undefined; - const i = typeof t === "undefined" ? [] : undefined; - let r = 0; - let n = this.v; - const h = []; - while (h.length || n) { - if (n) { - h.push(n); - n = n.i; - } else { - n = h.pop(); - if (r === e) return n; - i && i.push(n); - s && s(n, r, this); - r += 1; - n = n.h; - } - } - return i; - } - j(t) { - while (true) { - const e = t.o; - if (e.p === 0) return; - const s = e.o; - if (e === s.i) { - const i = s.h; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.h) { - t.p = 0; - if (t.i) { - t.i.o = e; - } - if (t.h) { - t.h.o = s; - } - e.h = t.i; - s.i = t.h; - t.i = e; - t.h = s; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e = s.o; - if (e.i === s) { - e.i = t; - } else e.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s.g(); - } else s.g(); - s.p = 1; - return; - } - } else { - const i = s.i; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.i) { - t.p = 0; - if (t.i) { - t.i.o = s; - } - if (t.h) { - t.h.o = e; - } - s.h = t.i; - e.i = t.h; - t.i = s; - t.h = e; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e = s.o; - if (e.i === s) { - e.i = t; - } else e.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s._(); - } else s._(); - s.p = 1; - return; - } - } - if (this.enableIndex) { - e.O(); - s.O(); - t.O(); - } - return; - } - } - q(t, e, s) { - if (this.v === undefined) { - this.m += 1; - this.v = new this.N(t, e, 0); - this.v.o = this.C; - this.C.o = this.C.i = this.C.h = this.v; - return this.m; - } - let i; - const r = this.C.i; - const n = this.A(r.u, t); - if (n === 0) { - r.l = e; - return this.m; - } else if (n > 0) { - r.i = new this.N(t, e); - r.i.o = r; - i = r.i; - this.C.i = i; - } else { - const r = this.C.h; - const n = this.A(r.u, t); - if (n === 0) { - r.l = e; - return this.m; - } else if (n < 0) { - r.h = new this.N(t, e); - r.h.o = r; - i = r.h; - this.C.h = i; - } else { - if (s !== undefined) { - const r = s.T; - if (r !== this.C) { - const s = this.A(r.u, t); - if (s === 0) { - r.l = e; - return this.m; - } else if (s > 0) { - const s = r.I(); - const n = this.A(s.u, t); - if (n === 0) { - s.l = e; - return this.m; - } else if (n < 0) { - i = new this.N(t, e); - if (s.h === undefined) { - s.h = i; - i.o = s; - } else { - r.i = i; - i.o = r; - } - } - } - } - } - if (i === undefined) { - i = this.v; - while (true) { - const s = this.A(i.u, t); - if (s > 0) { - if (i.i === undefined) { - i.i = new this.N(t, e); - i.i.o = i; - i = i.i; - break; - } - i = i.i; - } else if (s < 0) { - if (i.h === undefined) { - i.h = new this.N(t, e); - i.h.o = i; - i = i.h; - break; - } - i = i.h; - } else { - i.l = e; - return this.m; - } - } - } - } - } - if (this.enableIndex) { - let t = i.o; - while (t !== this.C) { - t.M += 1; - t = t.o; - } - } - this.j(i); - this.m += 1; - return this.m; - } - H(t, e) { - while (t) { - const s = this.A(t.u, e); - if (s < 0) { - t = t.h; - } else if (s > 0) { - t = t.i; - } else return t; - } - return t || this.C; - } - clear() { - this.m = 0; - this.v = undefined; - this.C.o = undefined; - this.C.i = this.C.h = undefined; - } - updateKeyByIterator(t, e) { - const s = t.T; - if (s === this.C) { - throwIteratorAccessError(); - } - if (this.m === 1) { - s.u = e; - return true; - } - const i = s.B().u; - if (s === this.C.i) { - if (this.A(i, e) > 0) { - s.u = e; - return true; - } - return false; - } - const r = s.I().u; - if (s === this.C.h) { - if (this.A(r, e) < 0) { - s.u = e; - return true; - } - return false; - } - if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; - s.u = e; - return true; - } - eraseElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError; - } - const e = this.U(t); - this.S(e); - return this.m; - } - eraseElementByKey(t) { - if (this.m === 0) return false; - const e = this.H(this.v, t); - if (e === this.C) return false; - this.S(e); - return true; - } - eraseElementByIterator(t) { - const e = t.T; - if (e === this.C) { - throwIteratorAccessError(); - } - const s = e.h === undefined; - const i = t.iteratorType === 0; - if (i) { - if (s) t.next(); - } else { - if (!s || e.i === undefined) t.next(); - } - this.S(e); - return t; - } - getHeight() { - if (this.m === 0) return 0; - function traversal(t) { - if (!t) return 0; - return Math.max(traversal(t.i), traversal(t.h)) + 1; - } - return traversal(this.v); - } -} - -class TreeIterator extends ContainerIterator { - constructor(t, e, s) { - super(s); - this.T = t; - this.C = e; - if (this.iteratorType === 0) { - this.pre = function() { - if (this.T === this.C.i) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - } else { - this.pre = function() { - if (this.T === this.C.h) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - } - } - get index() { - let t = this.T; - const e = this.C.o; - if (t === this.C) { - if (e) { - return e.M - 1; - } - return 0; - } - let s = 0; - if (t.i) { - s += t.i.M; - } - while (t !== e) { - const e = t.o; - if (t === e.h) { - s += 1; - if (e.i) { - s += e.i.M; - } - } - t = e; - } - return s; - } - isAccessible() { - return this.T !== this.C; - } -} - -class OrderedMapIterator extends TreeIterator { - constructor(t, e, s, i) { - super(t, e, i); - this.container = s; - } - get pointer() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - const t = this; - return new Proxy([], { - get(e, s) { - if (s === "0") return t.T.u; else if (s === "1") return t.T.l; - e[0] = t.T.u; - e[1] = t.T.l; - return e[s]; - }, - set(e, s, i) { - if (s !== "1") { - throw new TypeError("prop must be 1"); - } - t.T.l = i; - return true; - } - }); - } - copy() { - return new OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); - } -} - -class OrderedMap extends TreeContainer { - constructor(t = [], e, s) { - super(e, s); - const i = this; - t.forEach((function(t) { - i.setElement(t[0], t[1]); - })); - } - begin() { - return new OrderedMapIterator(this.C.i || this.C, this.C, this); - } - end() { - return new OrderedMapIterator(this.C, this.C, this); - } - rBegin() { - return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); - } - rEnd() { - return new OrderedMapIterator(this.C, this.C, this, 1); - } - front() { - if (this.m === 0) return; - const t = this.C.i; - return [ t.u, t.l ]; - } - back() { - if (this.m === 0) return; - const t = this.C.h; - return [ t.u, t.l ]; - } - lowerBound(t) { - const e = this.R(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - upperBound(t) { - const e = this.K(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseLowerBound(t) { - const e = this.L(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseUpperBound(t) { - const e = this.k(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - forEach(t) { - this.U((function(e, s, i) { - t([ e.u, e.l ], s, i); - })); - } - setElement(t, e, s) { - return this.q(t, e, s); - } - getElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError; - } - const e = this.U(t); - return [ e.u, e.l ]; - } - find(t) { - const e = this.H(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - getElementByKey(t) { - const e = this.H(this.v, t); - return e.l; - } - union(t) { - const e = this; - t.forEach((function(t) { - e.setElement(t[0], t[1]); - })); - return this.m; - } - * [Symbol.iterator]() { - const t = this.m; - const e = this.U(); - for (let s = 0; s < t; ++s) { - const t = e[s]; - yield [ t.u, t.l ]; - } - } -} - -exports.OrderedMap = OrderedMap; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 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 index_exports = {}; -__export(index_exports, { - Octokit: () => Octokit -}); -module.exports = __toCommonJS(index_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.2.2"; - -// pkg/dist-src/index.js -var noop = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop; - } - if (typeof logger.info !== "function") { - logger.info = noop; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; -} -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 = createLogger(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.6"; - -// 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+)|(?:(? 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(/(? { - 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 index_exports = {}; -__export(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest -}); -module.exports = __toCommonJS(index_exports); -var import_request3 = __nccwpck_require__(36234); -var import_universal_user_agent = __nccwpck_require__(45030); - -// pkg/dist-src/version.js -var VERSION = "7.1.1"; - -// 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); - - -/***/ }), - -/***/ 64193: -/***/ ((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, { - composePaginateRest: () => composePaginateRest, - isPaginatingEndpoint: () => isPaginatingEndpoint, - paginateRest: () => paginateRest, - paginatingEndpoints: () => paginatingEndpoints -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "9.2.2"; - -// pkg/dist-src/normalize-paginated-list-response.js -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) - return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - return response; -} - -// pkg/dist-src/iterator.js -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) - return { done: true }; - try { - const response = await requestMethod({ method, url, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - return { value: normalizedResponse }; - } catch (error) { - if (error.status !== 409) - throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - }) - }; -} - -// pkg/dist-src/paginate.js -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); -} -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); -} - -// pkg/dist-src/compose-paginate.js -var composePaginateRest = Object.assign(paginate, { - iterator -}); - -// pkg/dist-src/generated/paginating-endpoints.js -var paginatingEndpoints = [ - "GET /advisories", - "GET /app/hook/deliveries", - "GET /app/installation-requests", - "GET /app/installations", - "GET /assignments/{assignment_id}/accepted_assignments", - "GET /classrooms", - "GET /classrooms/{classroom_id}/assignments", - "GET /enterprises/{enterprise}/dependabot/alerts", - "GET /enterprises/{enterprise}/secret-scanning/alerts", - "GET /events", - "GET /gists", - "GET /gists/public", - "GET /gists/starred", - "GET /gists/{gist_id}/comments", - "GET /gists/{gist_id}/commits", - "GET /gists/{gist_id}/forks", - "GET /installation/repositories", - "GET /issues", - "GET /licenses", - "GET /marketplace_listing/plans", - "GET /marketplace_listing/plans/{plan_id}/accounts", - "GET /marketplace_listing/stubbed/plans", - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", - "GET /networks/{owner}/{repo}/events", - "GET /notifications", - "GET /organizations", - "GET /orgs/{org}/actions/cache/usage-by-repository", - "GET /orgs/{org}/actions/permissions/repositories", - "GET /orgs/{org}/actions/runners", - "GET /orgs/{org}/actions/secrets", - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", - "GET /orgs/{org}/actions/variables", - "GET /orgs/{org}/actions/variables/{name}/repositories", - "GET /orgs/{org}/blocks", - "GET /orgs/{org}/code-scanning/alerts", - "GET /orgs/{org}/codespaces", - "GET /orgs/{org}/codespaces/secrets", - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", - "GET /orgs/{org}/copilot/billing/seats", - "GET /orgs/{org}/dependabot/alerts", - "GET /orgs/{org}/dependabot/secrets", - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", - "GET /orgs/{org}/events", - "GET /orgs/{org}/failed_invitations", - "GET /orgs/{org}/hooks", - "GET /orgs/{org}/hooks/{hook_id}/deliveries", - "GET /orgs/{org}/installations", - "GET /orgs/{org}/invitations", - "GET /orgs/{org}/invitations/{invitation_id}/teams", - "GET /orgs/{org}/issues", - "GET /orgs/{org}/members", - "GET /orgs/{org}/members/{username}/codespaces", - "GET /orgs/{org}/migrations", - "GET /orgs/{org}/migrations/{migration_id}/repositories", - "GET /orgs/{org}/organization-roles/{role_id}/teams", - "GET /orgs/{org}/organization-roles/{role_id}/users", - "GET /orgs/{org}/outside_collaborators", - "GET /orgs/{org}/packages", - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - "GET /orgs/{org}/personal-access-token-requests", - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", - "GET /orgs/{org}/personal-access-tokens", - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", - "GET /orgs/{org}/projects", - "GET /orgs/{org}/properties/values", - "GET /orgs/{org}/public_members", - "GET /orgs/{org}/repos", - "GET /orgs/{org}/rulesets", - "GET /orgs/{org}/rulesets/rule-suites", - "GET /orgs/{org}/secret-scanning/alerts", - "GET /orgs/{org}/security-advisories", - "GET /orgs/{org}/teams", - "GET /orgs/{org}/teams/{team_slug}/discussions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/invitations", - "GET /orgs/{org}/teams/{team_slug}/members", - "GET /orgs/{org}/teams/{team_slug}/projects", - "GET /orgs/{org}/teams/{team_slug}/repos", - "GET /orgs/{org}/teams/{team_slug}/teams", - "GET /projects/columns/{column_id}/cards", - "GET /projects/{project_id}/collaborators", - "GET /projects/{project_id}/columns", - "GET /repos/{owner}/{repo}/actions/artifacts", - "GET /repos/{owner}/{repo}/actions/caches", - "GET /repos/{owner}/{repo}/actions/organization-secrets", - "GET /repos/{owner}/{repo}/actions/organization-variables", - "GET /repos/{owner}/{repo}/actions/runners", - "GET /repos/{owner}/{repo}/actions/runs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", - "GET /repos/{owner}/{repo}/actions/secrets", - "GET /repos/{owner}/{repo}/actions/variables", - "GET /repos/{owner}/{repo}/actions/workflows", - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", - "GET /repos/{owner}/{repo}/activity", - "GET /repos/{owner}/{repo}/assignees", - "GET /repos/{owner}/{repo}/branches", - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", - "GET /repos/{owner}/{repo}/code-scanning/alerts", - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - "GET /repos/{owner}/{repo}/code-scanning/analyses", - "GET /repos/{owner}/{repo}/codespaces", - "GET /repos/{owner}/{repo}/codespaces/devcontainers", - "GET /repos/{owner}/{repo}/codespaces/secrets", - "GET /repos/{owner}/{repo}/collaborators", - "GET /repos/{owner}/{repo}/comments", - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/commits", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", - "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", - "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", - "GET /repos/{owner}/{repo}/commits/{ref}/status", - "GET /repos/{owner}/{repo}/commits/{ref}/statuses", - "GET /repos/{owner}/{repo}/contributors", - "GET /repos/{owner}/{repo}/dependabot/alerts", - "GET /repos/{owner}/{repo}/dependabot/secrets", - "GET /repos/{owner}/{repo}/deployments", - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", - "GET /repos/{owner}/{repo}/environments", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", - "GET /repos/{owner}/{repo}/events", - "GET /repos/{owner}/{repo}/forks", - "GET /repos/{owner}/{repo}/hooks", - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", - "GET /repos/{owner}/{repo}/invitations", - "GET /repos/{owner}/{repo}/issues", - "GET /repos/{owner}/{repo}/issues/comments", - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/issues/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", - "GET /repos/{owner}/{repo}/issues/{issue_number}/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", - "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", - "GET /repos/{owner}/{repo}/keys", - "GET /repos/{owner}/{repo}/labels", - "GET /repos/{owner}/{repo}/milestones", - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", - "GET /repos/{owner}/{repo}/notifications", - "GET /repos/{owner}/{repo}/pages/builds", - "GET /repos/{owner}/{repo}/projects", - "GET /repos/{owner}/{repo}/pulls", - "GET /repos/{owner}/{repo}/pulls/comments", - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", - "GET /repos/{owner}/{repo}/releases", - "GET /repos/{owner}/{repo}/releases/{release_id}/assets", - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", - "GET /repos/{owner}/{repo}/rules/branches/{branch}", - "GET /repos/{owner}/{repo}/rulesets", - "GET /repos/{owner}/{repo}/rulesets/rule-suites", - "GET /repos/{owner}/{repo}/secret-scanning/alerts", - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", - "GET /repos/{owner}/{repo}/security-advisories", - "GET /repos/{owner}/{repo}/stargazers", - "GET /repos/{owner}/{repo}/subscribers", - "GET /repos/{owner}/{repo}/tags", - "GET /repos/{owner}/{repo}/teams", - "GET /repos/{owner}/{repo}/topics", - "GET /repositories", - "GET /repositories/{repository_id}/environments/{environment_name}/secrets", - "GET /repositories/{repository_id}/environments/{environment_name}/variables", - "GET /search/code", - "GET /search/commits", - "GET /search/issues", - "GET /search/labels", - "GET /search/repositories", - "GET /search/topics", - "GET /search/users", - "GET /teams/{team_id}/discussions", - "GET /teams/{team_id}/discussions/{discussion_number}/comments", - "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /teams/{team_id}/discussions/{discussion_number}/reactions", - "GET /teams/{team_id}/invitations", - "GET /teams/{team_id}/members", - "GET /teams/{team_id}/projects", - "GET /teams/{team_id}/repos", - "GET /teams/{team_id}/teams", - "GET /user/blocks", - "GET /user/codespaces", - "GET /user/codespaces/secrets", - "GET /user/emails", - "GET /user/followers", - "GET /user/following", - "GET /user/gpg_keys", - "GET /user/installations", - "GET /user/installations/{installation_id}/repositories", - "GET /user/issues", - "GET /user/keys", - "GET /user/marketplace_purchases", - "GET /user/marketplace_purchases/stubbed", - "GET /user/memberships/orgs", - "GET /user/migrations", - "GET /user/migrations/{migration_id}/repositories", - "GET /user/orgs", - "GET /user/packages", - "GET /user/packages/{package_type}/{package_name}/versions", - "GET /user/public_emails", - "GET /user/repos", - "GET /user/repository_invitations", - "GET /user/social_accounts", - "GET /user/ssh_signing_keys", - "GET /user/starred", - "GET /user/subscriptions", - "GET /user/teams", - "GET /users", - "GET /users/{username}/events", - "GET /users/{username}/events/orgs/{org}", - "GET /users/{username}/events/public", - "GET /users/{username}/followers", - "GET /users/{username}/following", - "GET /users/{username}/gists", - "GET /users/{username}/gpg_keys", - "GET /users/{username}/keys", - "GET /users/{username}/orgs", - "GET /users/{username}/packages", - "GET /users/{username}/projects", - "GET /users/{username}/received_events", - "GET /users/{username}/received_events/public", - "GET /users/{username}/repos", - "GET /users/{username}/social_accounts", - "GET /users/{username}/ssh_signing_keys", - "GET /users/{username}/starred", - "GET /users/{username}/subscriptions" -]; - -// pkg/dist-src/paginating-endpoints.js -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } -} - -// pkg/dist-src/index.js -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 83044: -/***/ ((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, { - legacyRestEndpointMethods: () => legacyRestEndpointMethods, - restEndpointMethods: () => restEndpointMethods -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "10.4.1"; - -// pkg/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repositories/{repository_id}/environments/{environment_name}/variables" - ], - createOrUpdateEnvironmentSecret: [ - "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteEnvironmentSecret: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables" - ], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: [ - "DELETE /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" - } - ], - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getCommitAuthors: [ - "GET /repos/{owner}/{repo}/import/authors", - {}, - { - deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" - } - ], - getImportStatus: [ - "GET /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" - } - ], - getLargeFiles: [ - "GET /repos/{owner}/{repo}/import/large_files", - {}, - { - deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" - } - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - mapCommitAuthor: [ - "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", - {}, - { - deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" - } - ], - setLfsPreference: [ - "PATCH /repos/{owner}/{repo}/import/lfs", - {}, - { - deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" - } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: [ - "PUT /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" - } - ], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ], - updateImport: [ - "PATCH /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" - } - ] - }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] - }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}" - ], - assignTeamToOrgRole: [ - "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - assignUserToOrgRole: [ - "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], - createInvitation: ["POST /orgs/{org}/invitations"], - createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], - createOrUpdateCustomPropertiesValuesForRepos: [ - "PATCH /orgs/{org}/properties/values" - ], - createOrUpdateCustomProperty: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - createWebhook: ["POST /orgs/{org}/hooks"], - delete: ["DELETE /orgs/{org}"], - deleteCustomOrganizationRole: [ - "DELETE /orgs/{org}/organization-roles/{role_id}" - ], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - enableOrDisableSecurityProductOnAllOrgRepos: [ - "POST /orgs/{org}/{security_product}/{enablement}" - ], - get: ["GET /orgs/{org}"], - getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], - getCustomProperty: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], - listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], - listOrgRoles: ["GET /orgs/{org}/organization-roles"], - listOrganizationFineGrainedPermissions: [ - "GET /orgs/{org}/organization-fine-grained-permissions" - ], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - patchCustomOrganizationRole: [ - "PATCH /orgs/{org}/organization-roles/{role_id}" - ], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeCustomProperty: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}" - ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - revokeAllOrgRolesTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" - ], - revokeAllOrgRolesUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}" - ], - revokeOrgRoleTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - revokeOrgRoleUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" - ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" - ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" - ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" - ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } - ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } - ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" - ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" - ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" - ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" - ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" - ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], - createCard: ["POST /projects/columns/{column_id}/cards"], - createColumn: ["POST /projects/{project_id}/columns"], - createForAuthenticatedUser: ["POST /user/projects"], - createForOrg: ["POST /orgs/{org}/projects"], - createForRepo: ["POST /repos/{owner}/{repo}/projects"], - delete: ["DELETE /projects/{project_id}"], - deleteCard: ["DELETE /projects/columns/cards/{card_id}"], - deleteColumn: ["DELETE /projects/columns/{column_id}"], - get: ["GET /projects/{project_id}"], - getCard: ["GET /projects/columns/cards/{card_id}"], - getColumn: ["GET /projects/columns/{column_id}"], - getPermissionForUser: [ - "GET /projects/{project_id}/collaborators/{username}/permission" - ], - listCards: ["GET /projects/columns/{column_id}/cards"], - listCollaborators: ["GET /projects/{project_id}/collaborators"], - listColumns: ["GET /projects/{project_id}/columns"], - listForOrg: ["GET /orgs/{org}/projects"], - listForRepo: ["GET /repos/{owner}/{repo}/projects"], - listForUser: ["GET /users/{username}/projects"], - moveCard: ["POST /projects/columns/cards/{card_id}/moves"], - moveColumn: ["POST /projects/columns/{column_id}/moves"], - removeCollaborator: [ - "DELETE /projects/{project_id}/collaborators/{username}" - ], - update: ["PATCH /projects/{project_id}"], - updateCard: ["PATCH /projects/columns/cards/{card_id}"], - updateColumn: ["PATCH /projects/columns/{column_id}"] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" - ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" - ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" - ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" - ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" - ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" - ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" - ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" - ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" - ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" - ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } - ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" - ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - cancelPagesDeployment: [ - "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" - ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" - ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" - ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" - ], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateCustomPropertiesValues: [ - "PATCH /repos/{owner}/{repo}/properties/values" - ], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" - ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" - ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } - ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" - ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" - ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" - ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" - ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteTagProtection: [ - "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" - ], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" - ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" - ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } - ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" - ], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" - ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" - ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" - ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" - ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" - ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" - ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" - ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" - ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesDeployment: [ - "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" - ], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" - ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" - ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" - ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" - ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" - ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" - ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" - ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" - ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" - ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" - ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" - ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } - ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/secret-scanning/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ] - }, - securityAdvisories: { - createFork: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" - ], - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" - ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" - ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" - ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - addOrUpdateProjectPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - checkPermissionsForProjectInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" - ], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - removeProjectInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", - {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } - ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } - ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } - ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } - ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } - ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } - ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } - ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } - ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - list: ["GET /users"], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } - ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } - ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } - ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } - ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } - ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } - ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } - ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" - ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// pkg/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url - }, - defaults - ); - if (!endpointMethodsMap.has(scope)) { - endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope).set(methodName, { - scope, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope }, methodName) { - return endpointMethodsMap.get(scope).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope }) { - return [...endpointMethodsMap.get(scope).keys()]; - }, - set(target, methodName, value) { - return target.cache[methodName] = value; - }, - get({ octokit, scope, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args) { - let options = requestWithDefaults.endpoint.merge(...args); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// pkg/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION; -// 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( - /(? { - -"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.4.1"; - -// 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, _d; - 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, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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); - - -/***/ }), - -/***/ 252: -/***/ ((module) => { - -"use strict"; - -module.exports = asPromise; - -/** - * Callback as used by {@link util.asPromise}. - * @typedef asPromiseCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {...*} params Additional arguments - * @returns {undefined} - */ - -/** - * Returns a promise from a node-style callback function. - * @memberof util - * @param {asPromiseCallback} fn Function to call - * @param {*} ctx Function context - * @param {...*} params Function arguments - * @returns {Promise<*>} Promisified function - */ -function asPromise(fn, ctx/*, varargs */) { - var params = new Array(arguments.length - 1), - offset = 0, - index = 2, - pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err/*, varargs */) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params = new Array(arguments.length - 1), - offset = 0; - while (offset < params.length) - params[offset++] = arguments[offset]; - resolve.apply(null, params); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } - } - }); -} - - -/***/ }), - -/***/ 26718: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal base64 implementation for number arrays. - * @memberof util - * @namespace - */ -var base64 = exports; - -/** - * Calculates the byte length of a base64 encoded string. - * @param {string} string Base64 encoded string - * @returns {number} Byte length - */ -base64.length = function length(string) { - var p = string.length; - if (!p) - return 0; - var n = 0; - while (--p % 4 > 1 && string.charAt(p) === "=") - ++n; - return Math.ceil(string.length * 3) / 4 - n; -}; - -// Base64 encoding table -var b64 = new Array(64); - -// Base64 decoding table -var s64 = new Array(123); - -// 65..90, 97..122, 48..57, 43, 47 -for (var i = 0; i < 64;) - s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; - -/** - * Encodes a buffer to a base64 encoded string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} Base64 encoded string - */ -base64.encode = function encode(buffer, start, end) { - var parts = null, - chunk = []; - var i = 0, // output index - j = 0, // goto index - t; // temporary - while (start < end) { - var b = buffer[start++]; - switch (j) { - case 0: - chunk[i++] = b64[b >> 2]; - t = (b & 3) << 4; - j = 1; - break; - case 1: - chunk[i++] = b64[t | b >> 4]; - t = (b & 15) << 2; - j = 2; - break; - case 2: - chunk[i++] = b64[t | b >> 6]; - chunk[i++] = b64[b & 63]; - j = 0; - break; - } - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (j) { - chunk[i++] = b64[t]; - chunk[i++] = 61; - if (j === 1) - chunk[i++] = 61; - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -var invalidEncoding = "invalid encoding"; - -/** - * Decodes a base64 encoded string to a buffer. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Number of bytes written - * @throws {Error} If encoding is invalid - */ -base64.decode = function decode(string, buffer, offset) { - var start = offset; - var j = 0, // goto index - t; // temporary - for (var i = 0; i < string.length;) { - var c = string.charCodeAt(i++); - if (c === 61 && j > 1) - break; - if ((c = s64[c]) === undefined) - throw Error(invalidEncoding); - switch (j) { - case 0: - t = c; - j = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c & 48) >> 4; - t = c; - j = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; - t = c; - j = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c; - j = 0; - break; - } - } - if (j === 1) - throw Error(invalidEncoding); - return offset - start; -}; - -/** - * Tests if the specified string appears to be base64 encoded. - * @param {string} string String to test - * @returns {boolean} `true` if probably base64 encoded, otherwise false - */ -base64.test = function test(string) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); -}; - - -/***/ }), - -/***/ 58882: -/***/ ((module) => { - -"use strict"; - -module.exports = codegen; - -/** - * Begins generating a function. - * @memberof util - * @param {string[]} functionParams Function parameter names - * @param {string} [functionName] Function name if not anonymous - * @returns {Codegen} Appender that appends code to the function's body - */ -function codegen(functionParams, functionName) { - - /* istanbul ignore if */ - if (typeof functionParams === "string") { - functionName = functionParams; - functionParams = undefined; - } - - var body = []; - - /** - * Appends code to the function's body or finishes generation. - * @typedef Codegen - * @type {function} - * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any - * @param {...*} [formatParams] Format parameters - * @returns {Codegen|Function} Itself or the generated function if finished - * @throws {Error} If format parameter counts do not match - */ - - function Codegen(formatStringOrScope) { - // note that explicit array handling below makes this ~50% faster - - // finish the function - if (typeof formatStringOrScope !== "string") { - var source = toString(); - if (codegen.verbose) - console.log("codegen: " + source); // eslint-disable-line no-console - source = "return " + source; - if (formatStringOrScope) { - var scopeKeys = Object.keys(formatStringOrScope), - scopeParams = new Array(scopeKeys.length + 1), - scopeValues = new Array(scopeKeys.length), - scopeOffset = 0; - while (scopeOffset < scopeKeys.length) { - scopeParams[scopeOffset] = scopeKeys[scopeOffset]; - scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; - } - scopeParams[scopeOffset] = source; - return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func - } - return Function(source)(); // eslint-disable-line no-new-func - } - - // otherwise append to body - var formatParams = new Array(arguments.length - 1), - formatOffset = 0; - while (formatOffset < formatParams.length) - formatParams[formatOffset] = arguments[++formatOffset]; - formatOffset = 0; - formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { - var value = formatParams[formatOffset++]; - switch ($1) { - case "d": case "f": return String(Number(value)); - case "i": return String(Math.floor(value)); - case "j": return JSON.stringify(value); - case "s": return String(value); - } - return "%"; - }); - if (formatOffset !== formatParams.length) - throw Error("parameter count mismatch"); - body.push(formatStringOrScope); - return Codegen; - } - - function toString(functionNameOverride) { - return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; - } - - Codegen.toString = toString; - return Codegen; -} - -/** - * Begins generating a function. - * @memberof util - * @function codegen - * @param {string} [functionName] Function name if not anonymous - * @returns {Codegen} Appender that appends code to the function's body - * @variation 2 - */ - -/** - * When set to `true`, codegen will log generated code to console. Useful for debugging. - * @name util.codegen.verbose - * @type {boolean} - */ -codegen.verbose = false; - - -/***/ }), - -/***/ 86850: -/***/ ((module) => { - -"use strict"; - -module.exports = EventEmitter; - -/** - * Constructs a new event emitter instance. - * @classdesc A minimal event emitter. - * @memberof util - * @constructor - */ -function EventEmitter() { - - /** - * Registered listeners. - * @type {Object.} - * @private - */ - this._listeners = {}; -} - -/** - * Registers an event listener. - * @param {string} evt Event name - * @param {function} fn Listener - * @param {*} [ctx] Listener context - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn : fn, - ctx : ctx || this - }); - return this; -}; - -/** - * Removes an event listener or any matching listeners if arguments are omitted. - * @param {string} [evt] Event name. Removes all listeners if omitted. - * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.off = function off(evt, fn) { - if (evt === undefined) - this._listeners = {}; - else { - if (fn === undefined) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i = 0; i < listeners.length;) - if (listeners[i].fn === fn) - listeners.splice(i, 1); - else - ++i; - } - } - return this; -}; - -/** - * Emits an event by calling its listeners with the specified arguments. - * @param {string} evt Event name - * @param {...*} args Arguments - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], - i = 1; - for (; i < arguments.length;) - args.push(arguments[i++]); - for (i = 0; i < listeners.length;) - listeners[i].fn.apply(listeners[i++].ctx, args); - } - return this; -}; - - -/***/ }), - -/***/ 50663: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = fetch; - -var asPromise = __nccwpck_require__(252), - inquire = __nccwpck_require__(60094); - -var fs = inquire("fs"); - -/** - * Node-style callback as used by {@link util.fetch}. - * @typedef FetchCallback - * @type {function} - * @param {?Error} error Error, if any, otherwise `null` - * @param {string} [contents] File contents, if there hasn't been an error - * @returns {undefined} - */ - -/** - * Options as used by {@link util.fetch}. - * @typedef FetchOptions - * @type {Object} - * @property {boolean} [binary=false] Whether expecting a binary response - * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest - */ - -/** - * Fetches the contents of a file. - * @memberof util - * @param {string} filename File path or url - * @param {FetchOptions} options Fetch options - * @param {FetchCallback} callback Callback function - * @returns {undefined} - */ -function fetch(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } else if (!options) - options = {}; - - if (!callback) - return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this - - // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. - if (!options.xhr && fs && fs.readFile) - return fs.readFile(filename, function fetchReadFileCallback(err, contents) { - return err && typeof XMLHttpRequest !== "undefined" - ? fetch.xhr(filename, options, callback) - : err - ? callback(err) - : callback(null, options.binary ? contents : contents.toString("utf8")); - }); - - // use the XHR version otherwise. - return fetch.xhr(filename, options, callback); -} - -/** - * Fetches the contents of a file. - * @name util.fetch - * @function - * @param {string} path File path or url - * @param {FetchCallback} callback Callback function - * @returns {undefined} - * @variation 2 - */ - -/** - * Fetches the contents of a file. - * @name util.fetch - * @function - * @param {string} path File path or url - * @param {FetchOptions} [options] Fetch options - * @returns {Promise} Promise - * @variation 3 - */ - -/**/ -fetch.xhr = function fetch_xhr(filename, options, callback) { - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { - - if (xhr.readyState !== 4) - return undefined; - - // local cors security errors return status 0 / empty string, too. afaik this cannot be - // reliably distinguished from an actually empty file for security reasons. feel free - // to send a pull request if you are aware of a solution. - if (xhr.status !== 0 && xhr.status !== 200) - return callback(Error("status " + xhr.status)); - - // if binary data is expected, make sure that some sort of array is returned, even if - // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. - if (options.binary) { - var buffer = xhr.response; - if (!buffer) { - buffer = []; - for (var i = 0; i < xhr.responseText.length; ++i) - buffer.push(xhr.responseText.charCodeAt(i) & 255); - } - return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); - } - return callback(null, xhr.responseText); - }; - - if (options.binary) { - // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers - if ("overrideMimeType" in xhr) - xhr.overrideMimeType("text/plain; charset=x-user-defined"); - xhr.responseType = "arraybuffer"; - } - - xhr.open("GET", filename); - xhr.send(); -}; - - -/***/ }), - -/***/ 21843: -/***/ ((module) => { - -"use strict"; - - -module.exports = factory(factory); - -/** - * Reads / writes floats / doubles from / to buffers. - * @name util.float - * @namespace - */ - -/** - * Writes a 32 bit float to a buffer using little endian byte order. - * @name util.float.writeFloatLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 32 bit float to a buffer using big endian byte order. - * @name util.float.writeFloatBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 32 bit float from a buffer using little endian byte order. - * @name util.float.readFloatLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 32 bit float from a buffer using big endian byte order. - * @name util.float.readFloatBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Writes a 64 bit double to a buffer using little endian byte order. - * @name util.float.writeDoubleLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 64 bit double to a buffer using big endian byte order. - * @name util.float.writeDoubleBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 64 bit double from a buffer using little endian byte order. - * @name util.float.readDoubleLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 64 bit double from a buffer using big endian byte order. - * @name util.float.readDoubleBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -// Factory function for the purpose of node-based testing in modified global environments -function factory(exports) { - - // float: typed array - if (typeof Float32Array !== "undefined") (function() { - - var f32 = new Float32Array([ -0 ]), - f8b = new Uint8Array(f32.buffer), - le = f8b[3] === 128; - - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - /* istanbul ignore next */ - exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos ]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - - /* istanbul ignore next */ - exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - /* istanbul ignore next */ - exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - - // float: ieee754 - })(); else (function() { - - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 3.4028234663852886e+38) // +-Infinity - writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 1.1754943508222875e-38) // denormal - writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), - mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } - } - - exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), - sign = (uint >> 31) * 2 + 1, - exponent = uint >>> 23 & 255, - mantissa = uint & 8388607; - return exponent === 255 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 1.401298464324817e-45 * mantissa - : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); - } - - exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - - })(); - - // double: typed array - if (typeof Float64Array !== "undefined") (function() { - - var f64 = new Float64Array([-0]), - f8b = new Uint8Array(f64.buffer), - le = f8b[7] === 128; - - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - /* istanbul ignore next */ - exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos ]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - - /* istanbul ignore next */ - exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - /* istanbul ignore next */ - exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - - // double: ieee754 - })(); else (function() { - - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 1.7976931348623157e+308) { // +-Infinity - writeUint(0, buf, pos + off0); - writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 2.2250738585072014e-308) { // denormal - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - - exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), - hi = readUint(buf, pos + off1); - var sign = (hi >> 31) * 2 + 1, - exponent = hi >>> 20 & 2047, - mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 5e-324 * mantissa - : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - - exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - - })(); - - return exports; -} - -// uint helpers - -function writeUintLE(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; -} - -function writeUintBE(val, buf, pos) { - buf[pos ] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; -} - -function readUintLE(buf, pos) { - return (buf[pos ] - | buf[pos + 1] << 8 - | buf[pos + 2] << 16 - | buf[pos + 3] << 24) >>> 0; -} - -function readUintBE(buf, pos) { - return (buf[pos ] << 24 - | buf[pos + 1] << 16 - | buf[pos + 2] << 8 - | buf[pos + 3]) >>> 0; -} - - -/***/ }), - -/***/ 60094: -/***/ ((module) => { - -"use strict"; - -module.exports = inquire; - -/** - * Requires a module only if available. - * @memberof util - * @param {string} moduleName Module to require - * @returns {?Object} Required module if available and not empty, otherwise `null` - */ -function inquire(moduleName) { - try { - var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval - if (mod && (mod.length || Object.keys(mod).length)) - return mod; - } catch (e) {} // eslint-disable-line no-empty - return null; -} - - -/***/ }), - -/***/ 24761: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal path module to resolve Unix, Windows and URL paths alike. - * @memberof util - * @namespace - */ -var path = exports; - -var isAbsolute = -/** - * Tests if the specified path is absolute. - * @param {string} path Path to test - * @returns {boolean} `true` if path is absolute - */ -path.isAbsolute = function isAbsolute(path) { - return /^(?:\/|\w+:)/.test(path); -}; - -var normalize = -/** - * Normalizes the specified path. - * @param {string} path Path to normalize - * @returns {string} Normalized path - */ -path.normalize = function normalize(path) { - path = path.replace(/\\/g, "/") - .replace(/\/{2,}/g, "/"); - var parts = path.split("/"), - absolute = isAbsolute(path), - prefix = ""; - if (absolute) - prefix = parts.shift() + "/"; - for (var i = 0; i < parts.length;) { - if (parts[i] === "..") { - if (i > 0 && parts[i - 1] !== "..") - parts.splice(--i, 2); - else if (absolute) - parts.splice(i, 1); - else - ++i; - } else if (parts[i] === ".") - parts.splice(i, 1); - else - ++i; - } - return prefix + parts.join("/"); -}; - -/** - * Resolves the specified include path against the specified origin path. - * @param {string} originPath Path to the origin file - * @param {string} includePath Include path relative to origin path - * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized - * @returns {string} Path to the include file - */ -path.resolve = function resolve(originPath, includePath, alreadyNormalized) { - if (!alreadyNormalized) - includePath = normalize(includePath); - if (isAbsolute(includePath)) - return includePath; - if (!alreadyNormalized) - originPath = normalize(originPath); - return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; -}; - - -/***/ }), - -/***/ 47743: -/***/ ((module) => { - -"use strict"; - -module.exports = pool; - -/** - * An allocator as used by {@link util.pool}. - * @typedef PoolAllocator - * @type {function} - * @param {number} size Buffer size - * @returns {Uint8Array} Buffer - */ - -/** - * A slicer as used by {@link util.pool}. - * @typedef PoolSlicer - * @type {function} - * @param {number} start Start offset - * @param {number} end End offset - * @returns {Uint8Array} Buffer slice - * @this {Uint8Array} - */ - -/** - * A general purpose buffer pool. - * @memberof util - * @function - * @param {PoolAllocator} alloc Allocator - * @param {PoolSlicer} slice Slicer - * @param {number} [size=8192] Slab size - * @returns {PoolAllocator} Pooled allocator - */ -function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size) { - if (size < 1 || size > MAX) - return alloc(size); - if (offset + size > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size); - if (offset & 7) // align to 32 bit - offset = (offset | 7) + 1; - return buf; - }; -} - - -/***/ }), - -/***/ 99049: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal UTF8 implementation for number arrays. - * @memberof util - * @namespace - */ -var utf8 = exports; - -/** - * Calculates the UTF8 byte length of a string. - * @param {string} string String - * @returns {number} Byte length - */ -utf8.length = function utf8_length(string) { - var len = 0, - c = 0; - for (var i = 0; i < string.length; ++i) { - c = string.charCodeAt(i); - if (c < 128) - len += 1; - else if (c < 2048) - len += 2; - else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { - ++i; - len += 4; - } else - len += 3; - } - return len; -}; - -/** - * Reads UTF8 bytes as a string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} String read - */ -utf8.read = function utf8_read(buffer, start, end) { - var len = end - start; - if (len < 1) - return ""; - var parts = null, - chunk = [], - i = 0, // char offset - t; // temporary - while (start < end) { - t = buffer[start++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; - chunk[i++] = 0xD800 + (t >> 10); - chunk[i++] = 0xDC00 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -/** - * Writes a string as UTF8 bytes. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Bytes written - */ -utf8.write = function utf8_write(string, buffer, offset) { - var start = offset, - c1, // character 1 - c2; // character 2 - for (var i = 0; i < string.length; ++i) { - c1 = string.charCodeAt(i); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { - c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); - ++i; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } - } - return offset - start; -}; - - -/***/ }), - -/***/ 79809: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(96575)); -const AuthAdminApi = GoTrueAdminApi_1.default; -exports["default"] = AuthAdminApi; -//# sourceMappingURL=AuthAdminApi.js.map - -/***/ }), - -/***/ 34525: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(20313)); -const AuthClient = GoTrueClient_1.default; -exports["default"] = AuthClient; -//# sourceMappingURL=AuthClient.js.map - -/***/ }), - -/***/ 96575: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const fetch_1 = __nccwpck_require__(17072); -const helpers_1 = __nccwpck_require__(54044); -const types_1 = __nccwpck_require__(1852); -const errors_1 = __nccwpck_require__(99938); -class GoTrueAdminApi { - constructor({ url = '', headers = {}, fetch, }) { - this.url = url; - this.headers = headers; - this.fetch = (0, helpers_1.resolveFetch)(fetch); - this.mfa = { - listFactors: this._listFactors.bind(this), - deleteFactor: this._deleteFactor.bind(this), - }; - this.oauth = { - listClients: this._listOAuthClients.bind(this), - createClient: this._createOAuthClient.bind(this), - getClient: this._getOAuthClient.bind(this), - updateClient: this._updateOAuthClient.bind(this), - deleteClient: this._deleteOAuthClient.bind(this), - regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this), - }; - } - /** - * Removes a logged-in session. - * @param jwt A valid, logged-in JWT. - * @param scope The logout sope. - */ - async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) { - if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) { - throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`); - } - try { - await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { - headers: this.headers, - jwt, - noResolveJson: true, - }); - return { data: null, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Sends an invite link to an email address. - * @param email The email address of the user. - * @param options Additional options to be included when inviting. - */ - async inviteUserByEmail(email, options = {}) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, { - body: { email, data: options.data }, - headers: this.headers, - redirectTo: options.redirectTo, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Generates email links and OTPs to be sent via a custom email provider. - * @param email The user's email. - * @param options.password User password. For signup only. - * @param options.data Optional user metadata. For signup only. - * @param options.redirectTo The redirect url which should be appended to the generated link - */ - async generateLink(params) { - try { - const { options } = params, rest = tslib_1.__rest(params, ["options"]); - const body = Object.assign(Object.assign({}, rest), options); - if ('newEmail' in rest) { - // replace newEmail with new_email in request body - body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; - delete body['newEmail']; - } - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, { - body: body, - headers: this.headers, - xform: fetch_1._generateLinkResponse, - redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { - data: { - properties: null, - user: null, - }, - error, - }; - } - throw error; - } - } - // User Admin API - /** - * Creates a new user. - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async createUser(attributes) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, { - body: attributes, - headers: this.headers, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Get a list of users. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. - */ - async listUsers(params) { - var _a, _b, _c, _d, _e, _f, _g; - try { - const pagination = { nextPage: null, lastPage: 0, total: 0 }; - const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, { - headers: this.headers, - noResolveJson: true, - query: { - page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', - per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', - }, - xform: fetch_1._noResolveJsonResponse, - }); - if (response.error) - throw response.error; - const users = await response.json(); - const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; - const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; - if (links.length > 0) { - links.forEach((link) => { - const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); - const rel = JSON.parse(link.split(';')[1].split('=')[1]); - pagination[`${rel}Page`] = page; - }); - pagination.total = parseInt(total); - } - return { data: Object.assign(Object.assign({}, users), pagination), error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { users: [] }, error }; - } - throw error; - } - } - /** - * Get user by id. - * - * @param uid The user's unique identifier - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async getUserById(uid) { - (0, helpers_1.validateUUID)(uid); - try { - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { - headers: this.headers, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Updates the user data. - * - * @param attributes The data you want to update. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async updateUserById(uid, attributes) { - (0, helpers_1.validateUUID)(uid); - try { - return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { - body: attributes, - headers: this.headers, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Delete a user. Requires a `service_role` key. - * - * @param id The user id you want to remove. - * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. - * Defaults to false for backward compatibility. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async deleteUser(id, shouldSoftDelete = false) { - (0, helpers_1.validateUUID)(id); - try { - return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { - headers: this.headers, - body: { - should_soft_delete: shouldSoftDelete, - }, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - async _listFactors(params) { - (0, helpers_1.validateUUID)(params.userId); - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { - headers: this.headers, - xform: (factors) => { - return { data: { factors }, error: null }; - }, - }); - return { data, error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async _deleteFactor(params) { - (0, helpers_1.validateUUID)(params.userId); - (0, helpers_1.validateUUID)(params.id); - try { - const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Lists all OAuth clients with optional pagination. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _listOAuthClients(params) { - var _a, _b, _c, _d, _e, _f, _g; - try { - const pagination = { nextPage: null, lastPage: 0, total: 0 }; - const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, { - headers: this.headers, - noResolveJson: true, - query: { - page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', - per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', - }, - xform: fetch_1._noResolveJsonResponse, - }); - if (response.error) - throw response.error; - const clients = await response.json(); - const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; - const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; - if (links.length > 0) { - links.forEach((link) => { - const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); - const rel = JSON.parse(link.split(';')[1].split('=')[1]); - pagination[`${rel}Page`] = page; - }); - pagination.total = parseInt(total); - } - return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { clients: [] }, error }; - } - throw error; - } - } - /** - * Creates a new OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _createOAuthClient(params) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, { - body: params, - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Gets details of a specific OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _getOAuthClient(clientId) { - try { - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, { - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Updates an existing OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _updateOAuthClient(clientId, params) { - try { - return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, { - body: params, - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Deletes an OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _deleteOAuthClient(clientId) { - try { - await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, { - headers: this.headers, - noResolveJson: true, - }); - return { data: null, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Regenerates the secret for an OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _regenerateOAuthClientSecret(clientId) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } -} -exports["default"] = GoTrueAdminApi; -//# sourceMappingURL=GoTrueAdminApi.js.map - -/***/ }), - -/***/ 20313: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(96575)); -const constants_1 = __nccwpck_require__(90518); -const errors_1 = __nccwpck_require__(99938); -const fetch_1 = __nccwpck_require__(17072); -const helpers_1 = __nccwpck_require__(54044); -const local_storage_1 = __nccwpck_require__(81479); -const locks_1 = __nccwpck_require__(60163); -const polyfills_1 = __nccwpck_require__(81897); -const version_1 = __nccwpck_require__(86677); -const base64url_1 = __nccwpck_require__(6677); -const ethereum_1 = __nccwpck_require__(51418); -const webauthn_1 = __nccwpck_require__(59451); -(0, polyfills_1.polyfillGlobalThis)(); // Make "globalThis" available -const DEFAULT_OPTIONS = { - url: constants_1.GOTRUE_URL, - storageKey: constants_1.STORAGE_KEY, - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true, - headers: constants_1.DEFAULT_HEADERS, - flowType: 'implicit', - debug: false, - hasCustomAuthorizationHeader: false, -}; -async function lockNoOp(name, acquireTimeout, fn) { - return await fn(); -} -/** - * Caches JWKS values for all clients created in the same environment. This is - * especially useful for shared-memory execution environments such as Vercel's - * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how - * many clients are created, if they share the same storage key they will use - * the same JWKS cache, significantly speeding up getClaims() with asymmetric - * JWTs. - */ -const GLOBAL_JWKS = {}; -class GoTrueClient { - /** - * The JWKS used for verifying asymmetric JWTs - */ - get jwks() { - var _a, _b; - return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; - } - set jwks(value) { - GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); - } - get jwks_cached_at() { - var _a, _b; - return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; - } - set jwks_cached_at(value) { - GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); - } - /** - * Create a new client for use in the browser. - */ - constructor(options) { - var _a, _b; - /** - * @experimental - */ - this.userStorage = null; - this.memoryStorage = null; - this.stateChangeEmitters = new Map(); - this.autoRefreshTicker = null; - this.visibilityChangedCallback = null; - this.refreshingDeferred = null; - /** - * Keeps track of the async client initialization. - * When null or not yet resolved the auth state is `unknown` - * Once resolved the auth state is known and it's safe to call any further client methods. - * Keep extra care to never reject or throw uncaught errors - */ - this.initializePromise = null; - this.detectSessionInUrl = true; - this.hasCustomAuthorizationHeader = false; - this.suppressGetSessionWarning = false; - this.lockAcquired = false; - this.pendingInLock = []; - /** - * Used to broadcast state change events to other tabs listening. - */ - this.broadcastChannel = null; - this.logger = console.log; - this.instanceID = GoTrueClient.nextInstanceID; - GoTrueClient.nextInstanceID += 1; - if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { - console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'); - } - const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); - this.logDebugMessages = !!settings.debug; - if (typeof settings.debug === 'function') { - this.logger = settings.debug; - } - this.persistSession = settings.persistSession; - this.storageKey = settings.storageKey; - this.autoRefreshToken = settings.autoRefreshToken; - this.admin = new GoTrueAdminApi_1.default({ - url: settings.url, - headers: settings.headers, - fetch: settings.fetch, - }); - this.url = settings.url; - this.headers = settings.headers; - this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); - this.lock = settings.lock || lockNoOp; - this.detectSessionInUrl = settings.detectSessionInUrl; - this.flowType = settings.flowType; - this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; - if (settings.lock) { - this.lock = settings.lock; - } - else if ((0, helpers_1.isBrowser)() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) { - this.lock = locks_1.navigatorLock; - } - else { - this.lock = lockNoOp; - } - if (!this.jwks) { - this.jwks = { keys: [] }; - this.jwks_cached_at = Number.MIN_SAFE_INTEGER; - } - this.mfa = { - verify: this._verify.bind(this), - enroll: this._enroll.bind(this), - unenroll: this._unenroll.bind(this), - challenge: this._challenge.bind(this), - listFactors: this._listFactors.bind(this), - challengeAndVerify: this._challengeAndVerify.bind(this), - getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), - webauthn: new webauthn_1.WebAuthnApi(this), - }; - this.oauth = { - getAuthorizationDetails: this._getAuthorizationDetails.bind(this), - approveAuthorization: this._approveAuthorization.bind(this), - denyAuthorization: this._denyAuthorization.bind(this), - }; - if (this.persistSession) { - if (settings.storage) { - this.storage = settings.storage; - } - else { - if ((0, helpers_1.supportsLocalStorage)()) { - this.storage = globalThis.localStorage; - } - else { - this.memoryStorage = {}; - this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); - } - } - if (settings.userStorage) { - this.userStorage = settings.userStorage; - } - } - else { - this.memoryStorage = {}; - this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); - } - if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { - try { - this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); - } - catch (e) { - console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); - } - (_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener('message', async (event) => { - this._debug('received broadcast notification from other tab or client', event); - await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages - }); - } - this.initialize(); - } - _debug(...args) { - if (this.logDebugMessages) { - this.logger(`GoTrueClient@${this.instanceID} (${version_1.version}) ${new Date().toISOString()}`, ...args); - } - return this; - } - /** - * Initializes the client session either from the url or from storage. - * This method is automatically called when instantiating the client, but should also be called - * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). - */ - async initialize() { - if (this.initializePromise) { - return await this.initializePromise; - } - this.initializePromise = (async () => { - return await this._acquireLock(-1, async () => { - return await this._initialize(); - }); - })(); - return await this.initializePromise; - } - /** - * IMPORTANT: - * 1. Never throw in this method, as it is called from the constructor - * 2. Never return a session from this method as it would be cached over - * the whole lifetime of the client - */ - async _initialize() { - var _a; - try { - const params = (0, helpers_1.parseParametersFromURL)(window.location.href); - let callbackUrlType = 'none'; - if (this._isImplicitGrantCallback(params)) { - callbackUrlType = 'implicit'; - } - else if (await this._isPKCECallback(params)) { - callbackUrlType = 'pkce'; - } - /** - * Attempt to get the session from the URL only if these conditions are fulfilled - * - * Note: If the URL isn't one of the callback url types (implicit or pkce), - * then there could be an existing session so we don't want to prematurely remove it - */ - if ((0, helpers_1.isBrowser)() && this.detectSessionInUrl && callbackUrlType !== 'none') { - const { data, error } = await this._getSessionFromURL(params, callbackUrlType); - if (error) { - this._debug('#_initialize()', 'error detecting session from URL', error); - if ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) { - const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; - if (errorCode === 'identity_already_exists' || - errorCode === 'identity_not_found' || - errorCode === 'single_identity_not_deletable') { - return { error }; - } - } - // failed login attempt via url, - // remove old session as in verifyOtp, signUp and signInWith* - await this._removeSession(); - return { error }; - } - const { session, redirectType } = data; - this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); - await this._saveSession(session); - setTimeout(async () => { - if (redirectType === 'recovery') { - await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); - } - else { - await this._notifyAllSubscribers('SIGNED_IN', session); - } - }, 0); - return { error: null }; - } - // no login attempt via callback url try to recover session from storage - await this._recoverAndRefresh(); - return { error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { error }; - } - return { - error: new errors_1.AuthUnknownError('Unexpected error during initialization', error), - }; - } - finally { - await this._handleVisibilityChange(); - this._debug('#_initialize()', 'end'); - } - } - /** - * Creates a new anonymous user. - * - * @returns A session where the is_anonymous claim in the access token JWT set to true - */ - async signInAnonymously(credentials) { - var _a, _b, _c; - try { - const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - body: { - data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, - gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - const { data, error } = res; - if (error || !data) { - return { data: { user: null, session: null }, error: error }; - } - const session = data.session; - const user = data.user; - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Creates a new user. - * - * Be aware that if a user account exists in the system you may get back an - * error message that attempts to hide this information from the user. - * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. - * - * @returns A logged-in session if the server has "autoconfirm" ON - * @returns A user if the server has "autoconfirm" OFF - */ - async signUp(credentials) { - var _a, _b, _c; - try { - let res; - if ('email' in credentials) { - const { email, password, options } = credentials; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - body: { - email, - password, - data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - }, - xform: fetch_1._sessionResponse, - }); - } - else if ('phone' in credentials) { - const { phone, password, options } = credentials; - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - body: { - phone, - password, - data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, - channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - } - else { - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); - } - const { data, error } = res; - if (error || !data) { - return { data: { user: null, session: null }, error: error }; - } - const session = data.session; - const user = data.user; - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in an existing user with an email and password or phone and password. - * - * Be aware that you may get back an error message that will not distinguish - * between the cases where the account does not exist or that the - * email/phone and password combination is wrong or that the account can only - * be accessed via social login. - */ - async signInWithPassword(credentials) { - try { - let res; - if ('email' in credentials) { - const { email, password, options } = credentials; - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { - headers: this.headers, - body: { - email, - password, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponsePassword, - }); - } - else if ('phone' in credentials) { - const { phone, password, options } = credentials; - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { - headers: this.headers, - body: { - phone, - password, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponsePassword, - }); - } - else { - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); - } - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { data: { user: null, session: null }, error: new errors_1.AuthInvalidTokenResponseError() }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { - data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), - error, - }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in an existing user via a third-party provider. - * This method supports the PKCE flow. - */ - async signInWithOAuth(credentials) { - var _a, _b, _c, _d; - return await this._handleProviderSignIn(credentials.provider, { - redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, - scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, - queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, - skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, - }); - } - /** - * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. - */ - async exchangeCodeForSession(authCode) { - await this.initializePromise; - return this._acquireLock(-1, async () => { - return this._exchangeCodeForSession(authCode); - }); - } - /** - * Signs in a user by verifying a message signed by the user's private key. - * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, - * both of which derive from the EIP-4361 standard - * With slight variation on Solana's side. - * @reference https://eips.ethereum.org/EIPS/eip-4361 - */ - async signInWithWeb3(credentials) { - const { chain } = credentials; - switch (chain) { - case 'ethereum': - return await this.signInWithEthereum(credentials); - case 'solana': - return await this.signInWithSolana(credentials); - default: - throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); - } - } - async signInWithEthereum(credentials) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; - // TODO: flatten type - let message; - let signature; - if ('message' in credentials) { - message = credentials.message; - signature = credentials.signature; - } - else { - const { chain, wallet, statement, options } = credentials; - let resolvedWallet; - if (!(0, helpers_1.isBrowser)()) { - if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { - throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); - } - resolvedWallet = wallet; - } - else if (typeof wallet === 'object') { - resolvedWallet = wallet; - } - else { - const windowAny = window; - if ('ethereum' in windowAny && - typeof windowAny.ethereum === 'object' && - 'request' in windowAny.ethereum && - typeof windowAny.ethereum.request === 'function') { - resolvedWallet = windowAny.ethereum; - } - else { - throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); - } - } - const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); - const accounts = await resolvedWallet - .request({ - method: 'eth_requestAccounts', - }) - .then((accs) => accs) - .catch(() => { - throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); - }); - if (!accounts || accounts.length === 0) { - throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); - } - const address = (0, ethereum_1.getAddress)(accounts[0]); - let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; - if (!chainId) { - const chainIdHex = await resolvedWallet.request({ - method: 'eth_chainId', - }); - chainId = (0, ethereum_1.fromHex)(chainIdHex); - } - const siweMessage = { - domain: url.host, - address: address, - statement: statement, - uri: url.href, - version: '1', - chainId: chainId, - nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, - issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : new Date(), - expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, - notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, - requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, - resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources, - }; - message = (0, ethereum_1.createSiweMessage)(siweMessage); - // Sign message - signature = (await resolvedWallet.request({ - method: 'personal_sign', - params: [(0, ethereum_1.toHex)(message), address], - })); - } - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { - headers: this.headers, - body: Object.assign({ chain: 'ethereum', message, - signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) - ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } - : null)), - xform: fetch_1._sessionResponse, - }); - if (error) { - throw error; - } - if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data: Object.assign({}, data), error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - async signInWithSolana(credentials) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; - let message; - let signature; - if ('message' in credentials) { - message = credentials.message; - signature = credentials.signature; - } - else { - const { chain, wallet, statement, options } = credentials; - let resolvedWallet; - if (!(0, helpers_1.isBrowser)()) { - if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { - throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); - } - resolvedWallet = wallet; - } - else if (typeof wallet === 'object') { - resolvedWallet = wallet; - } - else { - const windowAny = window; - if ('solana' in windowAny && - typeof windowAny.solana === 'object' && - (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || - ('signMessage' in windowAny.solana && - typeof windowAny.solana.signMessage === 'function'))) { - resolvedWallet = windowAny.solana; - } - else { - throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); - } - } - const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); - if ('signIn' in resolvedWallet && resolvedWallet.signIn) { - const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { - // non-overridable properties - version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null))); - let outputToProcess; - if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { - outputToProcess = output[0]; - } - else if (output && - typeof output === 'object' && - 'signedMessage' in output && - 'signature' in output) { - outputToProcess = output; - } - else { - throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value'); - } - if ('signedMessage' in outputToProcess && - 'signature' in outputToProcess && - (typeof outputToProcess.signedMessage === 'string' || - outputToProcess.signedMessage instanceof Uint8Array) && - outputToProcess.signature instanceof Uint8Array) { - message = - typeof outputToProcess.signedMessage === 'string' - ? outputToProcess.signedMessage - : new TextDecoder().decode(outputToProcess.signedMessage); - signature = outputToProcess.signature; - } - else { - throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'); - } - } - else { - if (!('signMessage' in resolvedWallet) || - typeof resolvedWallet.signMessage !== 'function' || - !('publicKey' in resolvedWallet) || - typeof resolvedWallet !== 'object' || - !resolvedWallet.publicKey || - !('toBase58' in resolvedWallet.publicKey) || - typeof resolvedWallet.publicKey.toBase58 !== 'function') { - throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'); - } - message = [ - `${url.host} wants you to sign in with your Solana account:`, - resolvedWallet.publicKey.toBase58(), - ...(statement ? ['', statement, ''] : ['']), - 'Version: 1', - `URI: ${url.href}`, - `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`, - ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) - ? [`Not Before: ${options.signInWithSolana.notBefore}`] - : []), - ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) - ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] - : []), - ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) - ? [`Chain ID: ${options.signInWithSolana.chainId}`] - : []), - ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), - ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) - ? [`Request ID: ${options.signInWithSolana.requestId}`] - : []), - ...(((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) - ? [ - 'Resources', - ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), - ] - : []), - ].join('\n'); - const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8'); - if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { - throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value'); - } - signature = maybeSignature; - } - } - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { - headers: this.headers, - body: Object.assign({ chain: 'solana', message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) - ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } - : null)), - xform: fetch_1._sessionResponse, - }); - if (error) { - throw error; - } - if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data: Object.assign({}, data), error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - async _exchangeCodeForSession(authCode) { - const storageItem = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { - headers: this.headers, - body: { - auth_code: authCode, - code_verifier: codeVerifier, - }, - xform: fetch_1._sessionResponse, - }); - await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - if (error) { - throw error; - } - if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null, redirectType: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null, redirectType: null }, error }; - } - throw error; - } - } - /** - * Allows signing in with an OIDC ID token. The authentication provider used - * should be enabled and configured. - */ - async signInWithIdToken(credentials) { - try { - const { options, provider, token, access_token, nonce } = credentials; - const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { - headers: this.headers, - body: { - provider, - id_token: token, - access_token, - nonce, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data, error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in a user using magiclink or a one-time password (OTP). - * - * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. - * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. - * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. - * - * Be aware that you may get back an error message that will not distinguish - * between the cases where the account does not exist or, that the account - * can only be accessed via social login. - * - * Do note that you will need to configure a Whatsapp sender on Twilio - * if you are using phone sign in with the 'whatsapp' channel. The whatsapp - * channel is not supported on other providers - * at this time. - * This method supports PKCE when an email is passed. - */ - async signInWithOtp(credentials) { - var _a, _b, _c, _d, _e; - try { - if ('email' in credentials) { - const { email, options } = credentials; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - const { error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { - headers: this.headers, - body: { - email, - data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, - create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - }, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - }); - return { data: { user: null, session: null }, error }; - } - if ('phone' in credentials) { - const { phone, options } = credentials; - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { - headers: this.headers, - body: { - phone, - data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, - create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', - }, - }); - return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; - } - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number.'); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in a user given a User supplied OTP or TokenHash received through mobile or email. - */ - async verifyOtp(params) { - var _a, _b; - try { - let redirectTo = undefined; - let captchaToken = undefined; - if ('options' in params) { - redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; - captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; - } - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/verify`, { - headers: this.headers, - body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), - redirectTo, - xform: fetch_1._sessionResponse, - }); - if (error) { - throw error; - } - if (!data) { - throw new Error('An error occurred on token verification.'); - } - const session = data.session; - const user = data.user; - if (session === null || session === void 0 ? void 0 : session.access_token) { - await this._saveSession(session); - await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Attempts a single-sign on using an enterprise Identity Provider. A - * successful SSO attempt will redirect the current page to the identity - * provider authorization page. The redirect URL is implementation and SSO - * protocol specific. - * - * You can use it by providing a SSO domain. Typically you can extract this - * domain by asking users for their email address. If this domain is - * registered on the Auth instance the redirect will use that organization's - * currently active SSO Identity Provider for the login. - * - * If you have built an organization-specific login page, you can use the - * organization's SSO Identity Provider UUID directly instead. - */ - async signInWithSSO(params) { - var _a, _b, _c; - try { - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/sso`, { - body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) - ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } - : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), - headers: this.headers, - xform: fetch_1._ssoResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Sends a reauthentication OTP to the user's email or phone number. - * Requires the user to be signed-in. - */ - async reauthenticate() { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._reauthenticate(); - }); - } - async _reauthenticate() { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) - throw sessionError; - if (!session) - throw new errors_1.AuthSessionMissingError(); - const { error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/reauthenticate`, { - headers: this.headers, - jwt: session.access_token, - }); - return { data: { user: null, session: null }, error }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. - */ - async resend(credentials) { - try { - const endpoint = `${this.url}/resend`; - if ('email' in credentials) { - const { email, type, options } = credentials; - const { error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { - headers: this.headers, - body: { - email, - type, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - }); - return { data: { user: null, session: null }, error }; - } - else if ('phone' in credentials) { - const { phone, type, options } = credentials; - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { - headers: this.headers, - body: { - phone, - type, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - }); - return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; - } - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Returns the session, refreshing it if necessary. - * - * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. - * - * **IMPORTANT:** This method loads values directly from the storage attached - * to the client. If that storage is based on request cookies for example, - * the values in it may not be authentic and therefore it's strongly advised - * against using this method and its results in such circumstances. A warning - * will be emitted if this is detected. Use {@link #getUser()} instead. - */ - async getSession() { - await this.initializePromise; - const result = await this._acquireLock(-1, async () => { - return this._useSession(async (result) => { - return result; - }); - }); - return result; - } - /** - * Acquires a global lock based on the storage key. - */ - async _acquireLock(acquireTimeout, fn) { - this._debug('#_acquireLock', 'begin', acquireTimeout); - try { - if (this.lockAcquired) { - const last = this.pendingInLock.length - ? this.pendingInLock[this.pendingInLock.length - 1] - : Promise.resolve(); - const result = (async () => { - await last; - return await fn(); - })(); - this.pendingInLock.push((async () => { - try { - await result; - } - catch (e) { - // we just care if it finished - } - })()); - return result; - } - return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { - this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); - try { - this.lockAcquired = true; - const result = fn(); - this.pendingInLock.push((async () => { - try { - await result; - } - catch (e) { - // we just care if it finished - } - })()); - await result; - // keep draining the queue until there's nothing to wait on - while (this.pendingInLock.length) { - const waitOn = [...this.pendingInLock]; - await Promise.all(waitOn); - this.pendingInLock.splice(0, waitOn.length); - } - return await result; - } - finally { - this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); - this.lockAcquired = false; - } - }); - } - finally { - this._debug('#_acquireLock', 'end'); - } - } - /** - * Use instead of {@link #getSession} inside the library. It is - * semantically usually what you want, as getting a session involves some - * processing afterwards that requires only one client operating on the - * session at once across multiple tabs or processes. - */ - async _useSession(fn) { - this._debug('#_useSession', 'begin'); - try { - // the use of __loadSession here is the only correct use of the function! - const result = await this.__loadSession(); - return await fn(result); - } - finally { - this._debug('#_useSession', 'end'); - } - } - /** - * NEVER USE DIRECTLY! - * - * Always use {@link #_useSession}. - */ - async __loadSession() { - this._debug('#__loadSession()', 'begin'); - if (!this.lockAcquired) { - this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); - } - try { - let currentSession = null; - const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); - this._debug('#getSession()', 'session from storage', maybeSession); - if (maybeSession !== null) { - if (this._isValidSession(maybeSession)) { - currentSession = maybeSession; - } - else { - this._debug('#getSession()', 'session from storage is not valid'); - await this._removeSession(); - } - } - if (!currentSession) { - return { data: { session: null }, error: null }; - } - // A session is considered expired before the access token _actually_ - // expires. When the autoRefreshToken option is off (or when the tab is - // in the background), very eager users of getSession() -- like - // realtime-js -- might send a valid JWT which will expire by the time it - // reaches the server. - const hasExpired = currentSession.expires_at - ? currentSession.expires_at * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS - : false; - this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); - if (!hasExpired) { - if (this.userStorage) { - const maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); - if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { - currentSession.user = maybeUser.user; - } - else { - currentSession.user = (0, helpers_1.userNotAvailableProxy)(); - } - } - // Wrap the user object with a warning proxy on the server - // This warns when properties of the user are accessed, not when session.user itself is accessed - if (this.storage.isServer && - currentSession.user && - !currentSession.user.__isUserNotAvailableProxy) { - const suppressWarningRef = { value: this.suppressGetSessionWarning }; - currentSession.user = (0, helpers_1.insecureUserWarningProxy)(currentSession.user, suppressWarningRef); - // Update the client-level suppression flag when the proxy suppresses the warning - if (suppressWarningRef.value) { - this.suppressGetSessionWarning = true; - } - } - return { data: { session: currentSession }, error: null }; - } - const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { session: null }, error }; - } - return { data: { session }, error: null }; - } - finally { - this._debug('#__loadSession()', 'end'); - } - } - /** - * Gets the current user details if there is an existing session. This method - * performs a network request to the Supabase Auth server, so the returned - * value is authentic and can be used to base authorization rules on. - * - * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. - */ - async getUser(jwt) { - if (jwt) { - return await this._getUser(jwt); - } - await this.initializePromise; - const result = await this._acquireLock(-1, async () => { - return await this._getUser(); - }); - return result; - } - async _getUser(jwt) { - try { - if (jwt) { - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { - headers: this.headers, - jwt: jwt, - xform: fetch_1._userResponse, - }); - } - return await this._useSession(async (result) => { - var _a, _b, _c; - const { data, error } = result; - if (error) { - throw error; - } - // returns an error if there is no access_token or custom authorization header - if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { - return { data: { user: null }, error: new errors_1.AuthSessionMissingError() }; - } - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { - headers: this.headers, - jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, - xform: fetch_1._userResponse, - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - if ((0, errors_1.isAuthSessionMissingError)(error)) { - // JWT contains a `session_id` which does not correspond to an active - // session in the database, indicating the user is signed out. - await this._removeSession(); - await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - } - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Updates user data for a logged in user. - */ - async updateUser(attributes, options = {}) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._updateUser(attributes, options); - }); - } - async _updateUser(attributes, options = {}) { - try { - return await this._useSession(async (result) => { - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - throw sessionError; - } - if (!sessionData.session) { - throw new errors_1.AuthSessionMissingError(); - } - const session = sessionData.session; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce' && attributes.email != null) { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - const { data, error: userError } = await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/user`, { - headers: this.headers, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), - jwt: session.access_token, - xform: fetch_1._userResponse, - }); - if (userError) - throw userError; - session.user = data.user; - await this._saveSession(session); - await this._notifyAllSubscribers('USER_UPDATED', session); - return { data: { user: session.user }, error: null }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. - * If the refresh token or access token in the current session is invalid, an error will be thrown. - * @param currentSession The current session that minimally contains an access token and refresh token. - */ - async setSession(currentSession) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._setSession(currentSession); - }); - } - async _setSession(currentSession) { - try { - if (!currentSession.access_token || !currentSession.refresh_token) { - throw new errors_1.AuthSessionMissingError(); - } - const timeNow = Date.now() / 1000; - let expiresAt = timeNow; - let hasExpired = true; - let session = null; - const { payload } = (0, helpers_1.decodeJWT)(currentSession.access_token); - if (payload.exp) { - expiresAt = payload.exp; - hasExpired = expiresAt <= timeNow; - } - if (hasExpired) { - const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { user: null, session: null }, error: error }; - } - if (!refreshedSession) { - return { data: { user: null, session: null }, error: null }; - } - session = refreshedSession; - } - else { - const { data, error } = await this._getUser(currentSession.access_token); - if (error) { - throw error; - } - session = { - access_token: currentSession.access_token, - refresh_token: currentSession.refresh_token, - user: data.user, - token_type: 'bearer', - expires_in: expiresAt - timeNow, - expires_at: expiresAt, - }; - await this._saveSession(session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user: session.user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { session: null, user: null }, error }; - } - throw error; - } - } - /** - * Returns a new session, regardless of expiry status. - * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). - * If the current session's refresh token is invalid, an error will be thrown. - * @param currentSession The current session. If passed in, it must contain a refresh token. - */ - async refreshSession(currentSession) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._refreshSession(currentSession); - }); - } - async _refreshSession(currentSession) { - try { - return await this._useSession(async (result) => { - var _a; - if (!currentSession) { - const { data, error } = result; - if (error) { - throw error; - } - currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; - } - if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { - throw new errors_1.AuthSessionMissingError(); - } - const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { user: null, session: null }, error: error }; - } - if (!session) { - return { data: { user: null, session: null }, error: null }; - } - return { data: { user: session.user, session }, error: null }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Gets the session data from a URL string - */ - async _getSessionFromURL(params, callbackUrlType) { - try { - if (!(0, helpers_1.isBrowser)()) - throw new errors_1.AuthImplicitGrantRedirectError('No browser detected.'); - // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. - if (params.error || params.error_description || params.error_code) { - // The error class returned implies that the redirect is from an implicit grant flow - // but it could also be from a redirect error from a PKCE flow. - throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { - error: params.error || 'unspecified_error', - code: params.error_code || 'unspecified_code', - }); - } - // Checks for mismatches between the flowType initialised in the client and the URL parameters - switch (callbackUrlType) { - case 'implicit': - if (this.flowType === 'pkce') { - throw new errors_1.AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); - } - break; - case 'pkce': - if (this.flowType === 'implicit') { - throw new errors_1.AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); - } - break; - default: - // there's no mismatch so we continue - } - // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange - if (callbackUrlType === 'pkce') { - this._debug('#_initialize()', 'begin', 'is PKCE flow', true); - if (!params.code) - throw new errors_1.AuthPKCEGrantCodeExchangeError('No code detected.'); - const { data, error } = await this._exchangeCodeForSession(params.code); - if (error) - throw error; - const url = new URL(window.location.href); - url.searchParams.delete('code'); - window.history.replaceState(window.history.state, '', url.toString()); - return { data: { session: data.session, redirectType: null }, error: null }; - } - const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; - if (!access_token || !expires_in || !refresh_token || !token_type) { - throw new errors_1.AuthImplicitGrantRedirectError('No session defined in URL'); - } - const timeNow = Math.round(Date.now() / 1000); - const expiresIn = parseInt(expires_in); - let expiresAt = timeNow + expiresIn; - if (expires_at) { - expiresAt = parseInt(expires_at); - } - const actuallyExpiresIn = expiresAt - timeNow; - if (actuallyExpiresIn * 1000 <= constants_1.AUTO_REFRESH_TICK_DURATION_MS) { - console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); - } - const issuedAt = expiresAt - expiresIn; - if (timeNow - issuedAt >= 120) { - console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); - } - else if (timeNow - issuedAt < 0) { - console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); - } - const { data, error } = await this._getUser(access_token); - if (error) - throw error; - const session = { - provider_token, - provider_refresh_token, - access_token, - expires_in: expiresIn, - expires_at: expiresAt, - refresh_token, - token_type: token_type, - user: data.user, - }; - // Remove tokens from URL - window.location.hash = ''; - this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); - return { data: { session, redirectType: params.type }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { session: null, redirectType: null }, error }; - } - throw error; - } - } - /** - * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) - */ - _isImplicitGrantCallback(params) { - return Boolean(params.access_token || params.error_description); - } - /** - * Checks if the current URL and backing storage contain parameters given by a PKCE flow - */ - async _isPKCECallback(params) { - const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - return !!(params.code && currentStorageContent); - } - /** - * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. - * - * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. - * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. - * - * If using `others` scope, no `SIGNED_OUT` event is fired! - */ - async signOut(options = { scope: 'global' }) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._signOut(options); - }); - } - async _signOut({ scope } = { scope: 'global' }) { - return await this._useSession(async (result) => { - var _a; - const { data, error: sessionError } = result; - if (sessionError) { - return { error: sessionError }; - } - const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; - if (accessToken) { - const { error } = await this.admin.signOut(accessToken, scope); - if (error) { - // ignore 404s since user might not exist anymore - // ignore 401s since an invalid or expired JWT should sign out the current session - if (!((0, errors_1.isAuthApiError)(error) && - (error.status === 404 || error.status === 401 || error.status === 403))) { - return { error }; - } - } - } - if (scope !== 'others') { - await this._removeSession(); - await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - } - return { error: null }; - }); - } - onAuthStateChange(callback) { - const id = (0, helpers_1.uuid)(); - const subscription = { - id, - callback, - unsubscribe: () => { - this._debug('#unsubscribe()', 'state change callback with id removed', id); - this.stateChangeEmitters.delete(id); - }, - }; - this._debug('#onAuthStateChange()', 'registered callback with id', id); - this.stateChangeEmitters.set(id, subscription); - (async () => { - await this.initializePromise; - await this._acquireLock(-1, async () => { - this._emitInitialSession(id); - }); - })(); - return { data: { subscription } }; - } - async _emitInitialSession(id) { - return await this._useSession(async (result) => { - var _a, _b; - try { - const { data: { session }, error, } = result; - if (error) - throw error; - await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); - this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); - } - catch (err) { - await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); - this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); - console.error(err); - } - }); - } - /** - * Sends a password reset request to an email address. This method supports the PKCE flow. - * - * @param email The email address of the user. - * @param options.redirectTo The URL to send the user to after they click the password reset link. - * @param options.captchaToken Verification token received when the user completes the captcha on the site. - */ - async resetPasswordForEmail(email, options = {}) { - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey, true // isPasswordRecovery - ); - } - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/recover`, { - body: { - email, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - gotrue_meta_security: { captcha_token: options.captchaToken }, - }, - headers: this.headers, - redirectTo: options.redirectTo, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Gets all the identities linked to a user. - */ - async getUserIdentities() { - var _a; - try { - const { data, error } = await this.getUser(); - if (error) - throw error; - return { data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async linkIdentity(credentials) { - if ('token' in credentials) { - return this.linkIdentityIdToken(credentials); - } - return this.linkIdentityOAuth(credentials); - } - async linkIdentityOAuth(credentials) { - var _a; - try { - const { data, error } = await this._useSession(async (result) => { - var _a, _b, _c, _d, _e; - const { data, error } = result; - if (error) - throw error; - const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { - redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, - scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, - queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, - skipBrowserRedirect: true, - }); - return await (0, fetch_1._request)(this.fetch, 'GET', url, { - headers: this.headers, - jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, - }); - }); - if (error) - throw error; - if ((0, helpers_1.isBrowser)() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { - window.location.assign(data === null || data === void 0 ? void 0 : data.url); - } - return { data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { provider: credentials.provider, url: null }, error }; - } - throw error; - } - } - async linkIdentityIdToken(credentials) { - return await this._useSession(async (result) => { - var _a; - try { - const { error: sessionError, data: { session }, } = result; - if (sessionError) - throw sessionError; - const { options, provider, token, access_token, nonce } = credentials; - const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { - headers: this.headers, - jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined, - body: { - provider, - id_token: token, - access_token, - nonce, - link_identity: true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('USER_UPDATED', data.session); - } - return { data, error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - }); - } - /** - * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. - */ - async unlinkIdentity(identity) { - try { - return await this._useSession(async (result) => { - var _a, _b; - const { data, error } = result; - if (error) { - throw error; - } - return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { - headers: this.headers, - jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Generates a new JWT. - * @param refreshToken A valid refresh token that was returned on login. - */ - async _refreshAccessToken(refreshToken) { - const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; - this._debug(debugName, 'begin'); - try { - const startedAt = Date.now(); - // will attempt to refresh the token with exponential backoff - return await (0, helpers_1.retryable)(async (attempt) => { - if (attempt > 0) { - await (0, helpers_1.sleep)(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... - } - this._debug(debugName, 'refreshing attempt', attempt); - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { - body: { refresh_token: refreshToken }, - headers: this.headers, - xform: fetch_1._sessionResponse, - }); - }, (attempt, error) => { - const nextBackOffInterval = 200 * Math.pow(2, attempt); - return (error && - (0, errors_1.isAuthRetryableFetchError)(error) && - // retryable only if the request can be sent before the backoff overflows the tick duration - Date.now() + nextBackOffInterval - startedAt < constants_1.AUTO_REFRESH_TICK_DURATION_MS); - }); - } - catch (error) { - this._debug(debugName, 'error', error); - if ((0, errors_1.isAuthError)(error)) { - return { data: { session: null, user: null }, error }; - } - throw error; - } - finally { - this._debug(debugName, 'end'); - } - } - _isValidSession(maybeSession) { - const isValidSession = typeof maybeSession === 'object' && - maybeSession !== null && - 'access_token' in maybeSession && - 'refresh_token' in maybeSession && - 'expires_at' in maybeSession; - return isValidSession; - } - async _handleProviderSignIn(provider, options) { - const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { - redirectTo: options.redirectTo, - scopes: options.scopes, - queryParams: options.queryParams, - }); - this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); - // try to open on the browser - if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { - window.location.assign(url); - } - return { data: { provider, url }, error: null }; - } - /** - * Recovers the session from LocalStorage and refreshes the token - * Note: this method is async to accommodate for AsyncStorage e.g. in React native. - */ - async _recoverAndRefresh() { - var _a, _b; - const debugName = '#_recoverAndRefresh()'; - this._debug(debugName, 'begin'); - try { - const currentSession = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey)); - if (currentSession && this.userStorage) { - let maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); - if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { - // storage and userStorage are the same storage medium, for example - // window.localStorage if userStorage does not have the user from - // storage stored, store it first thereby migrating the user object - // from storage -> userStorage - maybeUser = { user: currentSession.user }; - await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', maybeUser); - } - currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : (0, helpers_1.userNotAvailableProxy)(); - } - else if (currentSession && !currentSession.user) { - // user storage is not set, let's check if it was previously enabled so - // we bring back the storage as it should be - if (!currentSession.user) { - // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key - const separateUser = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey + '-user')); - if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { - currentSession.user = separateUser.user; - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); - await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); - } - else { - currentSession.user = (0, helpers_1.userNotAvailableProxy)(); - } - } - } - this._debug(debugName, 'session from storage', currentSession); - if (!this._isValidSession(currentSession)) { - this._debug(debugName, 'session is not valid'); - if (currentSession !== null) { - await this._removeSession(); - } - return; - } - const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS; - this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${constants_1.EXPIRY_MARGIN_MS}s`); - if (expiresWithMargin) { - if (this.autoRefreshToken && currentSession.refresh_token) { - const { error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - console.error(error); - if (!(0, errors_1.isAuthRetryableFetchError)(error)) { - this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); - await this._removeSession(); - } - } - } - } - else if (currentSession.user && - currentSession.user.__isUserNotAvailableProxy === true) { - // If we have a proxy user, try to get the real user data - try { - const { data, error: userError } = await this._getUser(currentSession.access_token); - if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { - currentSession.user = data.user; - await this._saveSession(currentSession); - await this._notifyAllSubscribers('SIGNED_IN', currentSession); - } - else { - this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification'); - } - } - catch (getUserError) { - console.error('Error getting user data:', getUserError); - this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError); - } - } - else { - // no need to persist currentSession again, as we just loaded it from - // local storage; persisting it again may overwrite a value saved by - // another client with access to the same local storage - await this._notifyAllSubscribers('SIGNED_IN', currentSession); - } - } - catch (err) { - this._debug(debugName, 'error', err); - console.error(err); - return; - } - finally { - this._debug(debugName, 'end'); - } - } - async _callRefreshToken(refreshToken) { - var _a, _b; - if (!refreshToken) { - throw new errors_1.AuthSessionMissingError(); - } - // refreshing is already in progress - if (this.refreshingDeferred) { - return this.refreshingDeferred.promise; - } - const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; - this._debug(debugName, 'begin'); - try { - this.refreshingDeferred = new helpers_1.Deferred(); - const { data, error } = await this._refreshAccessToken(refreshToken); - if (error) - throw error; - if (!data.session) - throw new errors_1.AuthSessionMissingError(); - await this._saveSession(data.session); - await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); - const result = { data: data.session, error: null }; - this.refreshingDeferred.resolve(result); - return result; - } - catch (error) { - this._debug(debugName, 'error', error); - if ((0, errors_1.isAuthError)(error)) { - const result = { data: null, error }; - if (!(0, errors_1.isAuthRetryableFetchError)(error)) { - await this._removeSession(); - } - (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); - return result; - } - (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); - throw error; - } - finally { - this.refreshingDeferred = null; - this._debug(debugName, 'end'); - } - } - async _notifyAllSubscribers(event, session, broadcast = true) { - const debugName = `#_notifyAllSubscribers(${event})`; - this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); - try { - if (this.broadcastChannel && broadcast) { - this.broadcastChannel.postMessage({ event, session }); - } - const errors = []; - const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { - try { - await x.callback(event, session); - } - catch (e) { - errors.push(e); - } - }); - await Promise.all(promises); - if (errors.length > 0) { - for (let i = 0; i < errors.length; i += 1) { - console.error(errors[i]); - } - throw errors[0]; - } - } - finally { - this._debug(debugName, 'end'); - } - } - /** - * set currentSession and currentUser - * process to _startAutoRefreshToken if possible - */ - async _saveSession(session) { - this._debug('#_saveSession()', session); - // _saveSession is always called whenever a new session has been acquired - // so we can safely suppress the warning returned by future getSession calls - this.suppressGetSessionWarning = true; - // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere - const sessionToProcess = Object.assign({}, session); - const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; - if (this.userStorage) { - if (!userIsProxy && sessionToProcess.user) { - // If it's a real user object, save it to userStorage. - await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', { - user: sessionToProcess.user, - }); - } - else if (userIsProxy) { - // If it's the proxy, it means user was not found in userStorage. - // We should ensure no stale user data for this key exists in userStorage if we were to save null, - // or simply not save the proxy. For now, we don't save the proxy here. - // If there's a need to clear userStorage if user becomes proxy, that logic would go here. - } - // Prepare the main session data for primary storage: remove the user property before cloning - // This is important because the original session.user might be the proxy - const mainSessionData = Object.assign({}, sessionToProcess); - delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage - const clonedMainSessionData = (0, helpers_1.deepClone)(mainSessionData); - await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedMainSessionData); - } - else { - // No userStorage is configured. - // In this case, session.user should ideally not be a proxy. - // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here - const clonedSession = (0, helpers_1.deepClone)(sessionToProcess); // sessionToProcess still has its original user property - await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedSession); - } - } - async _removeSession() { - this._debug('#_removeSession()'); - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-code-verifier'); - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); - if (this.userStorage) { - await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + '-user'); - } - await this._notifyAllSubscribers('SIGNED_OUT', null); - } - /** - * Removes any registered visibilitychange callback. - * - * {@see #startAutoRefresh} - * {@see #stopAutoRefresh} - */ - _removeVisibilityChangedCallback() { - this._debug('#_removeVisibilityChangedCallback()'); - const callback = this.visibilityChangedCallback; - this.visibilityChangedCallback = null; - try { - if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { - window.removeEventListener('visibilitychange', callback); - } - } - catch (e) { - console.error('removing visibilitychange callback failed', e); - } - } - /** - * This is the private implementation of {@link #startAutoRefresh}. Use this - * within the library. - */ - async _startAutoRefresh() { - await this._stopAutoRefresh(); - this._debug('#_startAutoRefresh()'); - const ticker = setInterval(() => this._autoRefreshTokenTick(), constants_1.AUTO_REFRESH_TICK_DURATION_MS); - this.autoRefreshTicker = ticker; - if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { - // ticker is a NodeJS Timeout object that has an `unref` method - // https://nodejs.org/api/timers.html#timeoutunref - // When auto refresh is used in NodeJS (like for testing) the - // `setInterval` is preventing the process from being marked as - // finished and tests run endlessly. This can be prevented by calling - // `unref()` on the returned object. - ticker.unref(); - // @ts-expect-error TS has no context of Deno - } - else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { - // similar like for NodeJS, but with the Deno API - // https://deno.land/api@latest?unstable&s=Deno.unrefTimer - // @ts-expect-error TS has no context of Deno - Deno.unrefTimer(ticker); - } - // run the tick immediately, but in the next pass of the event loop so that - // #_initialize can be allowed to complete without recursively waiting on - // itself - setTimeout(async () => { - await this.initializePromise; - await this._autoRefreshTokenTick(); - }, 0); - } - /** - * This is the private implementation of {@link #stopAutoRefresh}. Use this - * within the library. - */ - async _stopAutoRefresh() { - this._debug('#_stopAutoRefresh()'); - const ticker = this.autoRefreshTicker; - this.autoRefreshTicker = null; - if (ticker) { - clearInterval(ticker); - } - } - /** - * Starts an auto-refresh process in the background. The session is checked - * every few seconds. Close to the time of expiration a process is started to - * refresh the session. If refreshing fails it will be retried for as long as - * necessary. - * - * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need - * to call this function, it will be called for you. - * - * On browsers the refresh process works only when the tab/window is in the - * foreground to conserve resources as well as prevent race conditions and - * flooding auth with requests. If you call this method any managed - * visibility change callback will be removed and you must manage visibility - * changes on your own. - * - * On non-browser platforms the refresh process works *continuously* in the - * background, which may not be desirable. You should hook into your - * platform's foreground indication mechanism and call these methods - * appropriately to conserve resources. - * - * {@see #stopAutoRefresh} - */ - async startAutoRefresh() { - this._removeVisibilityChangedCallback(); - await this._startAutoRefresh(); - } - /** - * Stops an active auto refresh process running in the background (if any). - * - * If you call this method any managed visibility change callback will be - * removed and you must manage visibility changes on your own. - * - * See {@link #startAutoRefresh} for more details. - */ - async stopAutoRefresh() { - this._removeVisibilityChangedCallback(); - await this._stopAutoRefresh(); - } - /** - * Runs the auto refresh token tick. - */ - async _autoRefreshTokenTick() { - this._debug('#_autoRefreshTokenTick()', 'begin'); - try { - await this._acquireLock(0, async () => { - try { - const now = Date.now(); - try { - return await this._useSession(async (result) => { - const { data: { session }, } = result; - if (!session || !session.refresh_token || !session.expires_at) { - this._debug('#_autoRefreshTokenTick()', 'no session'); - return; - } - // session will expire in this many ticks (or has already expired if <= 0) - const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS); - this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`); - if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) { - await this._callRefreshToken(session.refresh_token); - } - }); - } - catch (e) { - console.error('Auto refresh tick failed with error. This is likely a transient error.', e); - } - } - finally { - this._debug('#_autoRefreshTokenTick()', 'end'); - } - }); - } - catch (e) { - if (e.isAcquireTimeout || e instanceof locks_1.LockAcquireTimeoutError) { - this._debug('auto refresh token tick lock not available'); - } - else { - throw e; - } - } - } - /** - * Registers callbacks on the browser / platform, which in-turn run - * algorithms when the browser window/tab are in foreground. On non-browser - * platforms it assumes always foreground. - */ - async _handleVisibilityChange() { - this._debug('#_handleVisibilityChange()'); - if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { - if (this.autoRefreshToken) { - // in non-browser environments the refresh token ticker runs always - this.startAutoRefresh(); - } - return false; - } - try { - this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); - window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); - // now immediately call the visbility changed callback to setup with the - // current visbility state - await this._onVisibilityChanged(true); // initial call - } - catch (error) { - console.error('_handleVisibilityChange', error); - } - } - /** - * Callback registered with `window.addEventListener('visibilitychange')`. - */ - async _onVisibilityChanged(calledFromInitialize) { - const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; - this._debug(methodName, 'visibilityState', document.visibilityState); - if (document.visibilityState === 'visible') { - if (this.autoRefreshToken) { - // in browser environments the refresh token ticker runs only on focused tabs - // which prevents race conditions - this._startAutoRefresh(); - } - if (!calledFromInitialize) { - // called when the visibility has changed, i.e. the browser - // transitioned from hidden -> visible so we need to see if the session - // should be recovered immediately... but to do that we need to acquire - // the lock first asynchronously - await this.initializePromise; - await this._acquireLock(-1, async () => { - if (document.visibilityState !== 'visible') { - this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); - // visibility has changed while waiting for the lock, abort - return; - } - // recover the session - await this._recoverAndRefresh(); - }); - } - } - else if (document.visibilityState === 'hidden') { - if (this.autoRefreshToken) { - this._stopAutoRefresh(); - } - } - } - /** - * Generates the relevant login URL for a third-party provider. - * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. - * @param options.scopes A space-separated list of scopes granted to the OAuth application. - * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. - */ - async _getUrlForProvider(url, provider, options) { - const urlParams = [`provider=${encodeURIComponent(provider)}`]; - if (options === null || options === void 0 ? void 0 : options.redirectTo) { - urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); - } - if (options === null || options === void 0 ? void 0 : options.scopes) { - urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); - } - if (this.flowType === 'pkce') { - const [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - const flowParams = new URLSearchParams({ - code_challenge: `${encodeURIComponent(codeChallenge)}`, - code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, - }); - urlParams.push(flowParams.toString()); - } - if (options === null || options === void 0 ? void 0 : options.queryParams) { - const query = new URLSearchParams(options.queryParams); - urlParams.push(query.toString()); - } - if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { - urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); - } - return `${url}?${urlParams.join('&')}`; - } - async _unenroll(params) { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async _enroll(params) { - try { - return await this._useSession(async (result) => { - var _a, _b; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' - ? { phone: params.phone } - : params.factorType === 'totp' - ? { issuer: params.issuer } - : {})); - const { data, error } = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors`, { - body, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - })); - if (error) { - return { data: null, error }; - } - if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { - data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; - } - return { data, error: null }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async _verify(params) { - return this._acquireLock(-1, async () => { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params - ? { - webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create' - ? (0, webauthn_1.serializeCredentialCreationResponse)(params.webauthn.credential_response) - : (0, webauthn_1.serializeCredentialRequestResponse)(params.webauthn.credential_response) }), - } - : { code: params.code })); - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { - body, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - if (error) { - return { data: null, error }; - } - await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); - await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); - return { data, error }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - async _challenge(params) { - return this._acquireLock(-1, async () => { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const response = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { - body: params, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - })); - if (response.error) { - return response; - } - const { data } = response; - if (data.type !== 'webauthn') { - return { data, error: null }; - } - switch (data.webauthn.type) { - case 'create': - return { - data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialCreationOptions)(data.webauthn.credential_options.publicKey) }) }) }), - error: null, - }; - case 'request': - return { - data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialRequestOptions)(data.webauthn.credential_options.publicKey) }) }) }), - error: null, - }; - } - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * {@see GoTrueMFAApi#challengeAndVerify} - */ - async _challengeAndVerify(params) { - // both _challenge and _verify independently acquire the lock, so no need - // to acquire it here - const { data: challengeData, error: challengeError } = await this._challenge({ - factorId: params.factorId, - }); - if (challengeError) { - return { data: null, error: challengeError }; - } - return await this._verify({ - factorId: params.factorId, - challengeId: challengeData.id, - code: params.code, - }); - } - /** - * {@see GoTrueMFAApi#listFactors} - */ - async _listFactors() { - var _a; - // use #getUser instead of #_getUser as the former acquires a lock - const { data: { user }, error: userError, } = await this.getUser(); - if (userError) { - return { data: null, error: userError }; - } - const data = { - all: [], - phone: [], - totp: [], - webauthn: [], - }; - // loop over the factors ONCE - for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) { - data.all.push(factor); - if (factor.status === 'verified') { - ; - data[factor.factor_type].push(factor); - } - } - return { - data, - error: null, - }; - } - /** - * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} - */ - async _getAuthenticatorAssuranceLevel() { - var _a, _b; - const { data: { session }, error: sessionError, } = await this.getSession(); - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { - data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, - error: null, - }; - } - const { payload } = (0, helpers_1.decodeJWT)(session.access_token); - let currentLevel = null; - if (payload.aal) { - currentLevel = payload.aal; - } - let nextLevel = currentLevel; - const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; - if (verifiedFactors.length > 0) { - nextLevel = 'aal2'; - } - const currentAuthenticationMethods = payload.amr || []; - return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; - } - /** - * Retrieves details about an OAuth authorization request. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * Returns authorization details including client info, scopes, and user information. - * If the API returns a redirect_uri, it means consent was already given - the caller - * should handle the redirect manually if needed. - */ - async _getAuthorizationDetails(authorizationId) { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { data: null, error: new errors_1.AuthSessionMissingError() }; - } - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, { - headers: this.headers, - jwt: session.access_token, - xform: (data) => ({ data, error: null }), - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Approves an OAuth authorization request. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - */ - async _approveAuthorization(authorizationId, options) { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { data: null, error: new errors_1.AuthSessionMissingError() }; - } - const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { - headers: this.headers, - jwt: session.access_token, - body: { action: 'approve' }, - xform: (data) => ({ data, error: null }), - }); - if (response.data && response.data.redirect_url) { - // Automatically redirect in browser unless skipBrowserRedirect is true - if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { - window.location.assign(response.data.redirect_url); - } - } - return response; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Denies an OAuth authorization request. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - */ - async _denyAuthorization(authorizationId, options) { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { data: null, error: new errors_1.AuthSessionMissingError() }; - } - const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { - headers: this.headers, - jwt: session.access_token, - body: { action: 'deny' }, - xform: (data) => ({ data, error: null }), - }); - if (response.data && response.data.redirect_url) { - // Automatically redirect in browser unless skipBrowserRedirect is true - if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { - window.location.assign(response.data.redirect_url); - } - } - return response; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async fetchJwk(kid, jwks = { keys: [] }) { - // try fetching from the supplied jwks - let jwk = jwks.keys.find((key) => key.kid === kid); - if (jwk) { - return jwk; - } - const now = Date.now(); - // try fetching from cache - jwk = this.jwks.keys.find((key) => key.kid === kid); - // jwk exists and jwks isn't stale - if (jwk && this.jwks_cached_at + constants_1.JWKS_TTL > now) { - return jwk; - } - // jwk isn't cached in memory so we need to fetch it from the well-known endpoint - const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, { - headers: this.headers, - }); - if (error) { - throw error; - } - if (!data.keys || data.keys.length === 0) { - return null; - } - this.jwks = data; - this.jwks_cached_at = now; - // Find the signing key - jwk = data.keys.find((key) => key.kid === kid); - if (!jwk) { - return null; - } - return jwk; - } - /** - * Extracts the JWT claims present in the access token by first verifying the - * JWT against the server's JSON Web Key Set endpoint - * `/.well-known/jwks.json` which is often cached, resulting in significantly - * faster responses. Prefer this method over {@link #getUser} which always - * sends a request to the Auth server for each JWT. - * - * If the project is not using an asymmetric JWT signing key (like ECC or - * RSA) it always sends a request to the Auth server (similar to {@link - * #getUser}) to verify the JWT. - * - * @param jwt An optional specific JWT you wish to verify, not the one you - * can obtain from {@link #getSession}. - * @param options Various additional options that allow you to customize the - * behavior of this method. - */ - async getClaims(jwt, options = {}) { - try { - let token = jwt; - if (!token) { - const { data, error } = await this.getSession(); - if (error || !data.session) { - return { data: null, error }; - } - token = data.session.access_token; - } - const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = (0, helpers_1.decodeJWT)(token); - if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { - // Reject expired JWTs should only happen if jwt argument was passed - (0, helpers_1.validateExp)(payload.exp); - } - const signingKey = !header.alg || - header.alg.startsWith('HS') || - !header.kid || - !('crypto' in globalThis && 'subtle' in globalThis.crypto) - ? null - : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); - // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser() - if (!signingKey) { - const { error } = await this.getUser(token); - if (error) { - throw error; - } - // getUser succeeds so the claims in the JWT can be trusted - return { - data: { - claims: payload, - header, - signature, - }, - error: null, - }; - } - const algorithm = (0, helpers_1.getAlgorithm)(header.alg); - // Convert JWK to CryptoKey - const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [ - 'verify', - ]); - // Verify the signature - const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, (0, base64url_1.stringToUint8Array)(`${rawHeader}.${rawPayload}`)); - if (!isValid) { - throw new errors_1.AuthInvalidJwtError('Invalid JWT signature'); - } - // If verification succeeds, decode and return claims - return { - data: { - claims: payload, - header, - signature, - }, - error: null, - }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } -} -GoTrueClient.nextInstanceID = 0; -exports["default"] = GoTrueClient; -//# sourceMappingURL=GoTrueClient.js.map - -/***/ }), - -/***/ 66748: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; -const tslib_1 = __nccwpck_require__(4351); -const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(96575)); -exports.GoTrueAdminApi = GoTrueAdminApi_1.default; -const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(20313)); -exports.GoTrueClient = GoTrueClient_1.default; -const AuthAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(79809)); -exports.AuthAdminApi = AuthAdminApi_1.default; -const AuthClient_1 = tslib_1.__importDefault(__nccwpck_require__(34525)); -exports.AuthClient = AuthClient_1.default; -tslib_1.__exportStar(__nccwpck_require__(1852), exports); -tslib_1.__exportStar(__nccwpck_require__(99938), exports); -var locks_1 = __nccwpck_require__(60163); -Object.defineProperty(exports, "navigatorLock", ({ enumerable: true, get: function () { return locks_1.navigatorLock; } })); -Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", ({ enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } })); -Object.defineProperty(exports, "lockInternals", ({ enumerable: true, get: function () { return locks_1.internals; } })); -Object.defineProperty(exports, "processLock", ({ enumerable: true, get: function () { return locks_1.processLock; } })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 6677: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/** - * Avoid modifying this file. It's part of - * https://github.com/supabase-community/base64url-js. Submit all fixes on - * that repo! - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.byteToBase64URL = byteToBase64URL; -exports.byteFromBase64URL = byteFromBase64URL; -exports.stringToBase64URL = stringToBase64URL; -exports.stringFromBase64URL = stringFromBase64URL; -exports.codepointToUTF8 = codepointToUTF8; -exports.stringToUTF8 = stringToUTF8; -exports.stringFromUTF8 = stringFromUTF8; -exports.base64UrlToUint8Array = base64UrlToUint8Array; -exports.stringToUint8Array = stringToUint8Array; -exports.bytesToBase64URL = bytesToBase64URL; -/** - * An array of characters that encode 6 bits into a Base64-URL alphabet - * character. - */ -const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split(''); -/** - * An array of characters that can appear in a Base64-URL encoded string but - * should be ignored. - */ -const IGNORE_BASE64URL = ' \t\n\r='.split(''); -/** - * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2 - * used to skip the character, or if -1 used to error out. - */ -const FROM_BASE64URL = (() => { - const charMap = new Array(128); - for (let i = 0; i < charMap.length; i += 1) { - charMap[i] = -1; - } - for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { - charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2; - } - for (let i = 0; i < TO_BASE64URL.length; i += 1) { - charMap[TO_BASE64URL[i].charCodeAt(0)] = i; - } - return charMap; -})(); -/** - * Converts a byte to a Base64-URL string. - * - * @param byte The byte to convert, or null to flush at the end of the byte sequence. - * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. - * @param emit A function called with the next Base64 character when ready. - */ -function byteToBase64URL(byte, state, emit) { - if (byte !== null) { - state.queue = (state.queue << 8) | byte; - state.queuedBits += 8; - while (state.queuedBits >= 6) { - const pos = (state.queue >> (state.queuedBits - 6)) & 63; - emit(TO_BASE64URL[pos]); - state.queuedBits -= 6; - } - } - else if (state.queuedBits > 0) { - state.queue = state.queue << (6 - state.queuedBits); - state.queuedBits = 6; - while (state.queuedBits >= 6) { - const pos = (state.queue >> (state.queuedBits - 6)) & 63; - emit(TO_BASE64URL[pos]); - state.queuedBits -= 6; - } - } -} -/** - * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. - * - * @param charCode The char code of the JavaScript string. - * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. - * @param emit A function called with the next byte. - */ -function byteFromBase64URL(charCode, state, emit) { - const bits = FROM_BASE64URL[charCode]; - if (bits > -1) { - // valid Base64-URL character - state.queue = (state.queue << 6) | bits; - state.queuedBits += 6; - while (state.queuedBits >= 8) { - emit((state.queue >> (state.queuedBits - 8)) & 0xff); - state.queuedBits -= 8; - } - } - else if (bits === -2) { - // ignore spaces, tabs, newlines, = - return; - } - else { - throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); - } -} -/** - * Converts a JavaScript string (which may include any valid character) into a - * Base64-URL encoded string. The string is first encoded in UTF-8 which is - * then encoded as Base64-URL. - * - * @param str The string to convert. - */ -function stringToBase64URL(str) { - const base64 = []; - const emitter = (char) => { - base64.push(char); - }; - const state = { queue: 0, queuedBits: 0 }; - stringToUTF8(str, (byte) => { - byteToBase64URL(byte, state, emitter); - }); - byteToBase64URL(null, state, emitter); - return base64.join(''); -} -/** - * Converts a Base64-URL encoded string into a JavaScript string. It is assumed - * that the underlying string has been encoded as UTF-8. - * - * @param str The Base64-URL encoded string. - */ -function stringFromBase64URL(str) { - const conv = []; - const utf8Emit = (codepoint) => { - conv.push(String.fromCodePoint(codepoint)); - }; - const utf8State = { - utf8seq: 0, - codepoint: 0, - }; - const b64State = { queue: 0, queuedBits: 0 }; - const byteEmit = (byte) => { - stringFromUTF8(byte, utf8State, utf8Emit); - }; - for (let i = 0; i < str.length; i += 1) { - byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit); - } - return conv.join(''); -} -/** - * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. - * - * @param codepoint The Unicode codepoint. - * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. - */ -function codepointToUTF8(codepoint, emit) { - if (codepoint <= 0x7f) { - emit(codepoint); - return; - } - else if (codepoint <= 0x7ff) { - emit(0xc0 | (codepoint >> 6)); - emit(0x80 | (codepoint & 0x3f)); - return; - } - else if (codepoint <= 0xffff) { - emit(0xe0 | (codepoint >> 12)); - emit(0x80 | ((codepoint >> 6) & 0x3f)); - emit(0x80 | (codepoint & 0x3f)); - return; - } - else if (codepoint <= 0x10ffff) { - emit(0xf0 | (codepoint >> 18)); - emit(0x80 | ((codepoint >> 12) & 0x3f)); - emit(0x80 | ((codepoint >> 6) & 0x3f)); - emit(0x80 | (codepoint & 0x3f)); - return; - } - throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); -} -/** - * Converts a JavaScript string to a sequence of UTF-8 bytes. - * - * @param str The string to convert to UTF-8. - * @param emit Function which will be called for each UTF-8 byte of the string. - */ -function stringToUTF8(str, emit) { - for (let i = 0; i < str.length; i += 1) { - let codepoint = str.charCodeAt(i); - if (codepoint > 0xd7ff && codepoint <= 0xdbff) { - // most UTF-16 codepoints are Unicode codepoints, except values in this - // range where the next UTF-16 codepoint needs to be combined with the - // current one to get the Unicode codepoint - const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff; - const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff; - codepoint = (lowSurrogate | highSurrogate) + 0x10000; - i += 1; - } - codepointToUTF8(codepoint, emit); - } -} -/** - * Converts a UTF-8 byte to a Unicode codepoint. - * - * @param byte The UTF-8 byte next in the sequence. - * @param state The shared state between consecutive UTF-8 bytes in the - * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. - * @param emit Function which will be called for each codepoint. - */ -function stringFromUTF8(byte, state, emit) { - if (state.utf8seq === 0) { - if (byte <= 0x7f) { - emit(byte); - return; - } - // count the number of 1 leading bits until you reach 0 - for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { - if (((byte >> (7 - leadingBit)) & 1) === 0) { - state.utf8seq = leadingBit; - break; - } - } - if (state.utf8seq === 2) { - state.codepoint = byte & 31; - } - else if (state.utf8seq === 3) { - state.codepoint = byte & 15; - } - else if (state.utf8seq === 4) { - state.codepoint = byte & 7; - } - else { - throw new Error('Invalid UTF-8 sequence'); - } - state.utf8seq -= 1; - } - else if (state.utf8seq > 0) { - if (byte <= 0x7f) { - throw new Error('Invalid UTF-8 sequence'); - } - state.codepoint = (state.codepoint << 6) | (byte & 63); - state.utf8seq -= 1; - if (state.utf8seq === 0) { - emit(state.codepoint); - } - } -} -/** - * Helper functions to convert different types of strings to Uint8Array - */ -function base64UrlToUint8Array(str) { - const result = []; - const state = { queue: 0, queuedBits: 0 }; - const onByte = (byte) => { - result.push(byte); - }; - for (let i = 0; i < str.length; i += 1) { - byteFromBase64URL(str.charCodeAt(i), state, onByte); - } - return new Uint8Array(result); -} -function stringToUint8Array(str) { - const result = []; - stringToUTF8(str, (byte) => result.push(byte)); - return new Uint8Array(result); -} -function bytesToBase64URL(bytes) { - const result = []; - const state = { queue: 0, queuedBits: 0 }; - const onChar = (char) => { - result.push(char); - }; - bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); - // always call with `null` after processing all bytes - byteToBase64URL(null, state, onChar); - return result.join(''); -} -//# sourceMappingURL=base64url.js.map - -/***/ }), - -/***/ 90518: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0; -const version_1 = __nccwpck_require__(86677); -/** Current session will be checked for refresh at this interval. */ -exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000; -/** - * A token refresh will be attempted this many ticks before the current session expires. */ -exports.AUTO_REFRESH_TICK_THRESHOLD = 3; -/* - * Earliest time before an access token expires that the session should be refreshed. - */ -exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS; -exports.GOTRUE_URL = 'http://localhost:9999'; -exports.STORAGE_KEY = 'supabase.auth.token'; -exports.AUDIENCE = ''; -exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` }; -exports.NETWORK_FAILURE = { - MAX_RETRIES: 10, - RETRY_INTERVAL: 2, // in deciseconds -}; -exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; -exports.API_VERSIONS = { - '2024-01-01': { - timestamp: Date.parse('2024-01-01T00:00:00.0Z'), - name: '2024-01-01', - }, -}; -exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; -exports.JWKS_TTL = 10 * 60 * 1000; // 10 minutes -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 99938: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0; -exports.isAuthError = isAuthError; -exports.isAuthApiError = isAuthApiError; -exports.isAuthSessionMissingError = isAuthSessionMissingError; -exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError; -exports.isAuthRetryableFetchError = isAuthRetryableFetchError; -exports.isAuthWeakPasswordError = isAuthWeakPasswordError; -class AuthError extends Error { - constructor(message, status, code) { - super(message); - this.__isAuthError = true; - this.name = 'AuthError'; - this.status = status; - this.code = code; - } -} -exports.AuthError = AuthError; -function isAuthError(error) { - return typeof error === 'object' && error !== null && '__isAuthError' in error; -} -class AuthApiError extends AuthError { - constructor(message, status, code) { - super(message, status, code); - this.name = 'AuthApiError'; - this.status = status; - this.code = code; - } -} -exports.AuthApiError = AuthApiError; -function isAuthApiError(error) { - return isAuthError(error) && error.name === 'AuthApiError'; -} -class AuthUnknownError extends AuthError { - constructor(message, originalError) { - super(message); - this.name = 'AuthUnknownError'; - this.originalError = originalError; - } -} -exports.AuthUnknownError = AuthUnknownError; -class CustomAuthError extends AuthError { - constructor(message, name, status, code) { - super(message, status, code); - this.name = name; - this.status = status; - } -} -exports.CustomAuthError = CustomAuthError; -class AuthSessionMissingError extends CustomAuthError { - constructor() { - super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); - } -} -exports.AuthSessionMissingError = AuthSessionMissingError; -function isAuthSessionMissingError(error) { - return isAuthError(error) && error.name === 'AuthSessionMissingError'; -} -class AuthInvalidTokenResponseError extends CustomAuthError { - constructor() { - super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); - } -} -exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; -class AuthInvalidCredentialsError extends CustomAuthError { - constructor(message) { - super(message, 'AuthInvalidCredentialsError', 400, undefined); - } -} -exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; -class AuthImplicitGrantRedirectError extends CustomAuthError { - constructor(message, details = null) { - super(message, 'AuthImplicitGrantRedirectError', 500, undefined); - this.details = null; - this.details = details; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - details: this.details, - }; - } -} -exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; -function isAuthImplicitGrantRedirectError(error) { - return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError'; -} -class AuthPKCEGrantCodeExchangeError extends CustomAuthError { - constructor(message, details = null) { - super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); - this.details = null; - this.details = details; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - details: this.details, - }; - } -} -exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; -class AuthRetryableFetchError extends CustomAuthError { - constructor(message, status) { - super(message, 'AuthRetryableFetchError', status, undefined); - } -} -exports.AuthRetryableFetchError = AuthRetryableFetchError; -function isAuthRetryableFetchError(error) { - return isAuthError(error) && error.name === 'AuthRetryableFetchError'; -} -/** - * This error is thrown on certain methods when the password used is deemed - * weak. Inspect the reasons to identify what password strength rules are - * inadequate. - */ -class AuthWeakPasswordError extends CustomAuthError { - constructor(message, status, reasons) { - super(message, 'AuthWeakPasswordError', status, 'weak_password'); - this.reasons = reasons; - } -} -exports.AuthWeakPasswordError = AuthWeakPasswordError; -function isAuthWeakPasswordError(error) { - return isAuthError(error) && error.name === 'AuthWeakPasswordError'; -} -class AuthInvalidJwtError extends CustomAuthError { - constructor(message) { - super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt'); - } -} -exports.AuthInvalidJwtError = AuthInvalidJwtError; -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 17072: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.handleError = handleError; -exports._request = _request; -exports._sessionResponse = _sessionResponse; -exports._sessionResponsePassword = _sessionResponsePassword; -exports._userResponse = _userResponse; -exports._ssoResponse = _ssoResponse; -exports._generateLinkResponse = _generateLinkResponse; -exports._noResolveJsonResponse = _noResolveJsonResponse; -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(90518); -const helpers_1 = __nccwpck_require__(54044); -const errors_1 = __nccwpck_require__(99938); -const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); -const NETWORK_ERROR_CODES = [502, 503, 504]; -async function handleError(error) { - var _a; - if (!(0, helpers_1.looksLikeFetchResponse)(error)) { - throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); - } - if (NETWORK_ERROR_CODES.includes(error.status)) { - // status in 500...599 range - server had an error, request might be retryed. - throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); - } - let data; - try { - data = await error.json(); - } - catch (e) { - throw new errors_1.AuthUnknownError(_getErrorMessage(e), e); - } - let errorCode = undefined; - const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error); - if (responseAPIVersion && - responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp && - typeof data === 'object' && - data && - typeof data.code === 'string') { - errorCode = data.code; - } - else if (typeof data === 'object' && data && typeof data.error_code === 'string') { - errorCode = data.error_code; - } - if (!errorCode) { - // Legacy support for weak password errors, when there were no error codes - if (typeof data === 'object' && - data && - typeof data.weak_password === 'object' && - data.weak_password && - Array.isArray(data.weak_password.reasons) && - data.weak_password.reasons.length && - data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { - throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); - } - } - else if (errorCode === 'weak_password') { - throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); - } - else if (errorCode === 'session_not_found') { - // The `session_id` inside the JWT does not correspond to a row in the - // `sessions` table. This usually means the user has signed out, has been - // deleted, or their session has somehow been terminated. - throw new errors_1.AuthSessionMissingError(); - } - throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); -} -const _getRequestParams = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET') { - return params; - } - params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); - params.body = JSON.stringify(body); - return Object.assign(Object.assign({}, params), parameters); -}; -async function _request(fetcher, method, url, options) { - var _a; - const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); - if (!headers[constants_1.API_VERSION_HEADER_NAME]) { - headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name; - } - if (options === null || options === void 0 ? void 0 : options.jwt) { - headers['Authorization'] = `Bearer ${options.jwt}`; - } - const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; - if (options === null || options === void 0 ? void 0 : options.redirectTo) { - qs['redirect_to'] = options.redirectTo; - } - const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; - const data = await _handleRequest(fetcher, method, url + queryString, { - headers, - noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, - }, {}, options === null || options === void 0 ? void 0 : options.body); - return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; -} -async function _handleRequest(fetcher, method, url, options, parameters, body) { - const requestParams = _getRequestParams(method, options, parameters, body); - let result; - try { - result = await fetcher(url, Object.assign({}, requestParams)); - } - catch (e) { - console.error(e); - // fetch failed, likely due to a network or CORS error - throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0); - } - if (!result.ok) { - await handleError(result); - } - if (options === null || options === void 0 ? void 0 : options.noResolveJson) { - return result; - } - try { - return await result.json(); - } - catch (e) { - await handleError(e); - } -} -function _sessionResponse(data) { - var _a; - let session = null; - if (hasSession(data)) { - session = Object.assign({}, data); - if (!data.expires_at) { - session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); - } - } - const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; - return { data: { session, user }, error: null }; -} -function _sessionResponsePassword(data) { - const response = _sessionResponse(data); - if (!response.error && - data.weak_password && - typeof data.weak_password === 'object' && - Array.isArray(data.weak_password.reasons) && - data.weak_password.reasons.length && - data.weak_password.message && - typeof data.weak_password.message === 'string' && - data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { - response.data.weak_password = data.weak_password; - } - return response; -} -function _userResponse(data) { - var _a; - const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; - return { data: { user }, error: null }; -} -function _ssoResponse(data) { - return { data, error: null }; -} -function _generateLinkResponse(data) { - const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); - const properties = { - action_link, - email_otp, - hashed_token, - redirect_to, - verification_type, - }; - const user = Object.assign({}, rest); - return { - data: { - properties, - user, - }, - error: null, - }; -} -function _noResolveJsonResponse(data) { - return data; -} -/** - * hasSession checks if the response object contains a valid session - * @param data A response object - * @returns true if a session is in the response - */ -function hasSession(data) { - return data.access_token && data.refresh_token && data.expires_in; -} -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 54044: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0; -exports.expiresAt = expiresAt; -exports.uuid = uuid; -exports.parseParametersFromURL = parseParametersFromURL; -exports.decodeJWT = decodeJWT; -exports.sleep = sleep; -exports.retryable = retryable; -exports.generatePKCEVerifier = generatePKCEVerifier; -exports.generatePKCEChallenge = generatePKCEChallenge; -exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod; -exports.parseResponseAPIVersion = parseResponseAPIVersion; -exports.validateExp = validateExp; -exports.getAlgorithm = getAlgorithm; -exports.validateUUID = validateUUID; -exports.userNotAvailableProxy = userNotAvailableProxy; -exports.insecureUserWarningProxy = insecureUserWarningProxy; -exports.deepClone = deepClone; -const constants_1 = __nccwpck_require__(90518); -const errors_1 = __nccwpck_require__(99938); -const base64url_1 = __nccwpck_require__(6677); -function expiresAt(expiresIn) { - const timeNow = Math.round(Date.now() / 1000); - return timeNow + expiresIn; -} -function uuid() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -} -const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'; -exports.isBrowser = isBrowser; -const localStorageWriteTests = { - tested: false, - writable: false, -}; -/** - * Checks whether localStorage is supported on this browser. - */ -const supportsLocalStorage = () => { - if (!(0, exports.isBrowser)()) { - return false; - } - try { - if (typeof globalThis.localStorage !== 'object') { - return false; - } - } - catch (e) { - // DOM exception when accessing `localStorage` - return false; - } - if (localStorageWriteTests.tested) { - return localStorageWriteTests.writable; - } - const randomKey = `lswt-${Math.random()}${Math.random()}`; - try { - globalThis.localStorage.setItem(randomKey, randomKey); - globalThis.localStorage.removeItem(randomKey); - localStorageWriteTests.tested = true; - localStorageWriteTests.writable = true; - } - catch (e) { - // localStorage can't be written to - // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document - localStorageWriteTests.tested = true; - localStorageWriteTests.writable = false; - } - return localStorageWriteTests.writable; -}; -exports.supportsLocalStorage = supportsLocalStorage; -/** - * Extracts parameters encoded in the URL both in the query and fragment. - */ -function parseParametersFromURL(href) { - const result = {}; - const url = new URL(href); - if (url.hash && url.hash[0] === '#') { - try { - const hashSearchParams = new URLSearchParams(url.hash.substring(1)); - hashSearchParams.forEach((value, key) => { - result[key] = value; - }); - } - catch (e) { - // hash is not a query string - } - } - // search parameters take precedence over hash parameters - url.searchParams.forEach((value, key) => { - result[key] = value; - }); - return result; -} -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => __importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -const looksLikeFetchResponse = (maybeResponse) => { - return (typeof maybeResponse === 'object' && - maybeResponse !== null && - 'status' in maybeResponse && - 'ok' in maybeResponse && - 'json' in maybeResponse && - typeof maybeResponse.json === 'function'); -}; -exports.looksLikeFetchResponse = looksLikeFetchResponse; -// Storage helpers -const setItemAsync = async (storage, key, data) => { - await storage.setItem(key, JSON.stringify(data)); -}; -exports.setItemAsync = setItemAsync; -const getItemAsync = async (storage, key) => { - const value = await storage.getItem(key); - if (!value) { - return null; - } - try { - return JSON.parse(value); - } - catch (_a) { - return value; - } -}; -exports.getItemAsync = getItemAsync; -const removeItemAsync = async (storage, key) => { - await storage.removeItem(key); -}; -exports.removeItemAsync = removeItemAsync; -/** - * A deferred represents some asynchronous work that is not yet finished, which - * may or may not culminate in a value. - * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts - */ -class Deferred { - constructor() { - // eslint-disable-next-line @typescript-eslint/no-extra-semi - ; - this.promise = new Deferred.promiseConstructor((res, rej) => { - // eslint-disable-next-line @typescript-eslint/no-extra-semi - ; - this.resolve = res; - this.reject = rej; - }); - } -} -exports.Deferred = Deferred; -Deferred.promiseConstructor = Promise; -function decodeJWT(token) { - const parts = token.split('.'); - if (parts.length !== 3) { - throw new errors_1.AuthInvalidJwtError('Invalid JWT structure'); - } - // Regex checks for base64url format - for (let i = 0; i < parts.length; i++) { - if (!constants_1.BASE64URL_REGEX.test(parts[i])) { - throw new errors_1.AuthInvalidJwtError('JWT not in base64url format'); - } - } - const data = { - // using base64url lib - header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])), - payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])), - signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]), - raw: { - header: parts[0], - payload: parts[1], - }, - }; - return data; -} -/** - * Creates a promise that resolves to null after some time. - */ -async function sleep(time) { - return await new Promise((accept) => { - setTimeout(() => accept(null), time); - }); -} -/** - * Converts the provided async function into a retryable function. Each result - * or thrown error is sent to the isRetryable function which should return true - * if the function should run again. - */ -function retryable(fn, isRetryable) { - const promise = new Promise((accept, reject) => { - // eslint-disable-next-line @typescript-eslint/no-extra-semi - ; - (async () => { - for (let attempt = 0; attempt < Infinity; attempt++) { - try { - const result = await fn(attempt); - if (!isRetryable(attempt, null, result)) { - accept(result); - return; - } - } - catch (e) { - if (!isRetryable(attempt, e)) { - reject(e); - return; - } - } - } - })(); - }); - return promise; -} -function dec2hex(dec) { - return ('0' + dec.toString(16)).substr(-2); -} -// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs -function generatePKCEVerifier() { - const verifierLength = 56; - const array = new Uint32Array(verifierLength); - if (typeof crypto === 'undefined') { - const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; - const charSetLen = charSet.length; - let verifier = ''; - for (let i = 0; i < verifierLength; i++) { - verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); - } - return verifier; - } - crypto.getRandomValues(array); - return Array.from(array, dec2hex).join(''); -} -async function sha256(randomString) { - const encoder = new TextEncoder(); - const encodedData = encoder.encode(randomString); - const hash = await crypto.subtle.digest('SHA-256', encodedData); - const bytes = new Uint8Array(hash); - return Array.from(bytes) - .map((c) => String.fromCharCode(c)) - .join(''); -} -async function generatePKCEChallenge(verifier) { - const hasCryptoSupport = typeof crypto !== 'undefined' && - typeof crypto.subtle !== 'undefined' && - typeof TextEncoder !== 'undefined'; - if (!hasCryptoSupport) { - console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); - return verifier; - } - const hashed = await sha256(verifier); - return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); -} -async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { - const codeVerifier = generatePKCEVerifier(); - let storedCodeVerifier = codeVerifier; - if (isPasswordRecovery) { - storedCodeVerifier += '/PASSWORD_RECOVERY'; - } - await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier); - const codeChallenge = await generatePKCEChallenge(codeVerifier); - const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; - return [codeChallenge, codeChallengeMethod]; -} -/** Parses the API version which is 2YYY-MM-DD. */ -const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; -function parseResponseAPIVersion(response) { - const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME); - if (!apiVersion) { - return null; - } - if (!apiVersion.match(API_VERSION_REGEX)) { - return null; - } - try { - const date = new Date(`${apiVersion}T00:00:00.0Z`); - return date; - } - catch (e) { - return null; - } -} -function validateExp(exp) { - if (!exp) { - throw new Error('Missing exp claim'); - } - const timeNow = Math.floor(Date.now() / 1000); - if (exp <= timeNow) { - throw new Error('JWT has expired'); - } -} -function getAlgorithm(alg) { - switch (alg) { - case 'RS256': - return { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: 'SHA-256' }, - }; - case 'ES256': - return { - name: 'ECDSA', - namedCurve: 'P-256', - hash: { name: 'SHA-256' }, - }; - default: - throw new Error('Invalid alg claim'); - } -} -const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; -function validateUUID(str) { - if (!UUID_REGEX.test(str)) { - throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not'); - } -} -function userNotAvailableProxy() { - const proxyTarget = {}; - return new Proxy(proxyTarget, { - get: (target, prop) => { - if (prop === '__isUserNotAvailableProxy') { - return true; - } - // Preventative check for common problematic symbols during cloning/inspection - // These symbols might be accessed by structuredClone or other internal mechanisms. - if (typeof prop === 'symbol') { - const sProp = prop.toString(); - if (sProp === 'Symbol(Symbol.toPrimitive)' || - sProp === 'Symbol(Symbol.toStringTag)' || - sProp === 'Symbol(util.inspect.custom)') { - // Node.js util.inspect - return undefined; - } - } - throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); - }, - set: (_target, prop) => { - throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); - }, - deleteProperty: (_target, prop) => { - throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); - }, - }); -} -/** - * Creates a proxy around a user object that warns when properties are accessed on the server. - * This is used to alert developers that using user data from getSession() on the server is insecure. - * - * @param user The actual user object to wrap - * @param suppressWarningRef An object with a 'value' property that controls warning suppression - * @returns A proxied user object that warns on property access - */ -function insecureUserWarningProxy(user, suppressWarningRef) { - return new Proxy(user, { - get: (target, prop, receiver) => { - // Allow internal checks without warning - if (prop === '__isInsecureUserWarningProxy') { - return true; - } - // Preventative check for common problematic symbols during cloning/inspection - // These symbols might be accessed by structuredClone or other internal mechanisms - if (typeof prop === 'symbol') { - const sProp = prop.toString(); - if (sProp === 'Symbol(Symbol.toPrimitive)' || - sProp === 'Symbol(Symbol.toStringTag)' || - sProp === 'Symbol(util.inspect.custom)' || - sProp === 'Symbol(nodejs.util.inspect.custom)') { - // Return the actual value for these symbols to allow proper inspection - return Reflect.get(target, prop, receiver); - } - } - // Emit warning on first property access - if (!suppressWarningRef.value && typeof prop === 'string') { - console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); - suppressWarningRef.value = true; - } - return Reflect.get(target, prop, receiver); - }, - }); -} -/** - * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). - * Note: Only works for JSON-safe data. - */ -function deepClone(obj) { - return JSON.parse(JSON.stringify(obj)); -} -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 81479: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter; -/** - * Returns a localStorage-like object that stores the key-value pairs in - * memory. - */ -function memoryLocalStorageAdapter(store = {}) { - return { - getItem: (key) => { - return store[key] || null; - }, - setItem: (key, value) => { - store[key] = value; - }, - removeItem: (key) => { - delete store[key]; - }, - }; -} -//# sourceMappingURL=local-storage.js.map - -/***/ }), - -/***/ 60163: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0; -exports.navigatorLock = navigatorLock; -exports.processLock = processLock; -const helpers_1 = __nccwpck_require__(54044); -/** - * @experimental - */ -exports.internals = { - /** - * @experimental - */ - debug: !!(globalThis && - (0, helpers_1.supportsLocalStorage)() && - globalThis.localStorage && - globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), -}; -/** - * An error thrown when a lock cannot be acquired after some amount of time. - * - * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. - */ -class LockAcquireTimeoutError extends Error { - constructor(message) { - super(message); - this.isAcquireTimeout = true; - } -} -exports.LockAcquireTimeoutError = LockAcquireTimeoutError; -class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { -} -exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; -class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { -} -exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError; -/** - * Implements a global exclusive lock using the Navigator LockManager API. It - * is available on all browsers released after 2022-03-15 with Safari being the - * last one to release support. If the API is not available, this function will - * throw. Make sure you check availablility before configuring {@link - * GoTrueClient}. - * - * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` - * local storage item to `true`. - * - * Internals: - * - * Since the LockManager API does not preserve stack traces for the async - * function passed in the `request` method, a trick is used where acquiring the - * lock releases a previously started promise to run the operation in the `fn` - * function. The lock waits for that promise to finish (with or without error), - * while the function will finally wait for the result anyway. - * - * @param name Name of the lock to be acquired. - * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if - * the lock can't be acquired without waiting. If positive, the lock acquire - * will time out after so many milliseconds. An error is - * a timeout if it has `isAcquireTimeout` set to true. - * @param fn The operation to run once the lock is acquired. - */ -async function navigatorLock(name, acquireTimeout, fn) { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); - } - const abortController = new globalThis.AbortController(); - if (acquireTimeout > 0) { - setTimeout(() => { - abortController.abort(); - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); - } - }, acquireTimeout); - } - // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request - // Wrapping navigator.locks.request() with a plain Promise is done as some - // libraries like zone.js patch the Promise object to track the execution - // context. However, it appears that most browsers use an internal promise - // implementation when using the navigator.locks.request() API causing them - // to lose context and emit confusing log messages or break certain features. - // This wrapping is believed to help zone.js track the execution context - // better. - return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 - ? { - mode: 'exclusive', - ifAvailable: true, - } - : { - mode: 'exclusive', - signal: abortController.signal, - }, async (lock) => { - if (lock) { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); - } - try { - return await fn(); - } - finally { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); - } - } - } - else { - if (acquireTimeout === 0) { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); - } - throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); - } - else { - if (exports.internals.debug) { - try { - const result = await globalThis.navigator.locks.query(); - console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); - } - catch (e) { - console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); - } - } - // Browser is not following the Navigator LockManager spec, it - // returned a null lock when we didn't use ifAvailable. So we can - // pretend the lock is acquired in the name of backward compatibility - // and user experience and just run the function. - console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); - return await fn(); - } - } - })); -} -const PROCESS_LOCKS = {}; -/** - * Implements a global exclusive lock that works only in the current process. - * Useful for environments like React Native or other non-browser - * single-process (i.e. no concept of "tabs") environments. - * - * Use {@link #navigatorLock} in browser environments. - * - * @param name Name of the lock to be acquired. - * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if - * the lock can't be acquired without waiting. If positive, the lock acquire - * will time out after so many milliseconds. An error is - * a timeout if it has `isAcquireTimeout` set to true. - * @param fn The operation to run once the lock is acquired. - */ -async function processLock(name, acquireTimeout, fn) { - var _a; - const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve(); - const currentOperation = Promise.race([ - previousOperation.catch(() => { - // ignore error of previous operation that we're waiting to finish - return null; - }), - acquireTimeout >= 0 - ? new Promise((_, reject) => { - setTimeout(() => { - reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); - }, acquireTimeout); - }) - : null, - ].filter((x) => x)) - .catch((e) => { - if (e && e.isAcquireTimeout) { - throw e; - } - return null; - }) - .then(async () => { - // previous operations finished and we didn't get a race on the acquire - // timeout, so the current operation can finally start - return await fn(); - }); - PROCESS_LOCKS[name] = currentOperation.catch(async (e) => { - if (e && e.isAcquireTimeout) { - // if the current operation timed out, it doesn't mean that the previous - // operation finished, so we need contnue waiting for it to finish - await previousOperation; - return null; - } - throw e; - }); - // finally wait for the current operation to finish successfully, with an - // error or with an acquire timeout error - return await currentOperation; -} -//# sourceMappingURL=locks.js.map - -/***/ }), - -/***/ 81897: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.polyfillGlobalThis = polyfillGlobalThis; -/** - * https://mathiasbynens.be/notes/globalthis - */ -function polyfillGlobalThis() { - if (typeof globalThis === 'object') - return; - try { - Object.defineProperty(Object.prototype, '__magic__', { - get: function () { - return this; - }, - configurable: true, - }); - // @ts-expect-error 'Allow access to magic' - __magic__.globalThis = __magic__; - // @ts-expect-error 'Allow access to magic' - delete Object.prototype.__magic__; - } - catch (e) { - if (typeof self !== 'undefined') { - // @ts-expect-error 'Allow access to globals' - self.globalThis = self; - } - } -} -//# sourceMappingURL=polyfills.js.map - -/***/ }), - -/***/ 1852: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SIGN_OUT_SCOPES = void 0; -const WeakPasswordReasons = (/* unused pure expression or super */ null && (['length', 'characters', 'pwned'])); -const AMRMethods = (/* unused pure expression or super */ null && ([ - 'password', - 'otp', - 'oauth', - 'totp', - 'mfa/totp', - 'mfa/phone', - 'mfa/webauthn', - 'anonymous', - 'sso/saml', - 'magiclink', - 'web3', -])); -const FactorTypes = (/* unused pure expression or super */ null && (['totp', 'phone', 'webauthn'])); -const FactorVerificationStatuses = (/* unused pure expression or super */ null && (['verified', 'unverified'])); -const MFATOTPChannels = (/* unused pure expression or super */ null && (['sms', 'whatsapp'])); -exports.SIGN_OUT_SCOPES = ['global', 'local', 'others']; -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 86677: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 51418: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// types and functions copied over from viem so this library doesn't depend on it -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAddress = getAddress; -exports.fromHex = fromHex; -exports.toHex = toHex; -exports.createSiweMessage = createSiweMessage; -function getAddress(address) { - if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { - throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); - } - return address.toLowerCase(); -} -function fromHex(hex) { - return parseInt(hex, 16); -} -function toHex(value) { - const bytes = new TextEncoder().encode(value); - const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); - return ('0x' + hex); -} -/** - * Creates EIP-4361 formatted message. - */ -function createSiweMessage(parameters) { - var _a; - const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters; - // Validate fields - { - if (!Number.isInteger(chainId)) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); - if (!domain) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); - if (nonce && nonce.length < 8) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); - if (!uri) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); - if (version !== '1') - throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`); - if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n')) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); - } - // Construct message - const address = getAddress(parameters.address); - const origin = scheme ? `${scheme}://${domain}` : domain; - const statement = parameters.statement ? `${parameters.statement}\n` : ''; - const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`; - let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`; - if (expirationTime) - suffix += `\nExpiration Time: ${expirationTime.toISOString()}`; - if (notBefore) - suffix += `\nNot Before: ${notBefore.toISOString()}`; - if (requestId) - suffix += `\nRequest ID: ${requestId}`; - if (resources) { - let content = '\nResources:'; - for (const resource of resources) { - if (!resource || typeof resource !== 'string') - throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); - content += `\n- ${resource}`; - } - suffix += content; - } - return `${prefix}\n${suffix}`; -} -//# sourceMappingURL=ethereum.js.map - -/***/ }), - -/***/ 97906: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* eslint-disable @typescript-eslint/ban-ts-comment */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebAuthnUnknownError = exports.WebAuthnError = void 0; -exports.isWebAuthnError = isWebAuthnError; -exports.identifyRegistrationError = identifyRegistrationError; -exports.identifyAuthenticationError = identifyAuthenticationError; -const webauthn_1 = __nccwpck_require__(59451); -/** - * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented - * errors in the spec was raised after calling `navigator.credentials.create()` or - * `navigator.credentials.get()`: - * - * - `AbortError` - * - `ConstraintError` - * - `InvalidStateError` - * - `NotAllowedError` - * - `NotSupportedError` - * - `SecurityError` - * - `TypeError` - * - `UnknownError` - * - * Error messages were determined through investigation of the spec to determine under which - * scenarios a given error would be raised. - */ -class WebAuthnError extends Error { - constructor({ message, code, cause, name, }) { - var _a; - // @ts-ignore: help Rollup understand that `cause` is okay to set - super(message, { cause }); - this.__isWebAuthnError = true; - this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error'; - this.code = code; - } -} -exports.WebAuthnError = WebAuthnError; -/** - * Error class for unknown WebAuthn errors. - * Wraps unexpected errors that don't match known WebAuthn error conditions. - */ -class WebAuthnUnknownError extends WebAuthnError { - constructor(message, originalError) { - super({ - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: originalError, - message, - }); - this.name = 'WebAuthnUnknownError'; - this.originalError = originalError; - } -} -exports.WebAuthnUnknownError = WebAuthnUnknownError; -/** - * Type guard to check if an error is a WebAuthnError. - * @param {unknown} error - The error to check - * @returns {boolean} True if the error is a WebAuthnError - */ -function isWebAuthnError(error) { - return typeof error === 'object' && error !== null && '__isWebAuthnError' in error; -} -/** - * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. - * Maps browser errors to specific WebAuthn error codes for better debugging. - * @param {Object} params - Error identification parameters - * @param {Error} params.error - The error thrown by the browser - * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() - * @returns {WebAuthnError} A WebAuthnError with a specific error code - * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} - */ -function identifyRegistrationError({ error, options, }) { - var _a, _b, _c; - const { publicKey } = options; - if (!publicKey) { - throw Error('options was missing required publicKey property'); - } - if (error.name === 'AbortError') { - if (options.signal instanceof AbortSignal) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) - return new WebAuthnError({ - message: 'Registration ceremony was sent an abort signal', - code: 'ERROR_CEREMONY_ABORTED', - cause: error, - }); - } - } - else if (error.name === 'ConstraintError') { - if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) { - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) - return new WebAuthnError({ - message: 'Discoverable credentials were required but no available authenticator supported it', - code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', - cause: error, - }); - } - else if ( - // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 - options.mediation === 'conditional' && - ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') { - // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4) - return new WebAuthnError({ - message: 'User verification was required during automatic registration but it could not be performed', - code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE', - cause: error, - }); - } - else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') { - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) - return new WebAuthnError({ - message: 'User verification was required but no available authenticator supported it', - code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', - cause: error, - }); - } - } - else if (error.name === 'InvalidStateError') { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) - return new WebAuthnError({ - message: 'The authenticator was previously registered', - code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', - cause: error, - }); - } - else if (error.name === 'NotAllowedError') { - /** - * Pass the error directly through. Platforms are overloading this error beyond what the spec - * defines and we don't want to overwrite potentially useful error messages. - */ - return new WebAuthnError({ - message: error.message, - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); - } - else if (error.name === 'NotSupportedError') { - const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key'); - if (validPubKeyCredParams.length === 0) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) - return new WebAuthnError({ - message: 'No entry in pubKeyCredParams was of type "public-key"', - code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', - cause: error, - }); - } - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) - return new WebAuthnError({ - message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms', - code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', - cause: error, - }); - } - else if (error.name === 'SecurityError') { - const effectiveDomain = window.location.hostname; - if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) - return new WebAuthnError({ - message: `${window.location.hostname} is an invalid domain`, - code: 'ERROR_INVALID_DOMAIN', - cause: error, - }); - } - else if (publicKey.rp.id !== effectiveDomain) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) - return new WebAuthnError({ - message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, - code: 'ERROR_INVALID_RP_ID', - cause: error, - }); - } - } - else if (error.name === 'TypeError') { - if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) - return new WebAuthnError({ - message: 'User ID was not between 1 and 64 characters', - code: 'ERROR_INVALID_USER_ID_LENGTH', - cause: error, - }); - } - } - else if (error.name === 'UnknownError') { - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) - return new WebAuthnError({ - message: 'The authenticator was unable to process the specified options, or could not create a new credential', - code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', - cause: error, - }); - } - return new WebAuthnError({ - message: 'a Non-Webauthn related error has occurred', - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); -} -/** - * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. - * Maps browser errors to specific WebAuthn error codes for better debugging. - * @param {Object} params - Error identification parameters - * @param {Error} params.error - The error thrown by the browser - * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() - * @returns {WebAuthnError} A WebAuthnError with a specific error code - * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} - */ -function identifyAuthenticationError({ error, options, }) { - const { publicKey } = options; - if (!publicKey) { - throw Error('options was missing required publicKey property'); - } - if (error.name === 'AbortError') { - if (options.signal instanceof AbortSignal) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) - return new WebAuthnError({ - message: 'Authentication ceremony was sent an abort signal', - code: 'ERROR_CEREMONY_ABORTED', - cause: error, - }); - } - } - else if (error.name === 'NotAllowedError') { - /** - * Pass the error directly through. Platforms are overloading this error beyond what the spec - * defines and we don't want to overwrite potentially useful error messages. - */ - return new WebAuthnError({ - message: error.message, - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); - } - else if (error.name === 'SecurityError') { - const effectiveDomain = window.location.hostname; - if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { - // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) - return new WebAuthnError({ - message: `${window.location.hostname} is an invalid domain`, - code: 'ERROR_INVALID_DOMAIN', - cause: error, - }); - } - else if (publicKey.rpId !== effectiveDomain) { - // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) - return new WebAuthnError({ - message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, - code: 'ERROR_INVALID_RP_ID', - cause: error, - }); - } - } - else if (error.name === 'UnknownError') { - // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) - // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) - return new WebAuthnError({ - message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature', - code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', - cause: error, - }); - } - return new WebAuthnError({ - message: 'a Non-Webauthn related error has occurred', - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); -} -//# sourceMappingURL=webauthn.errors.js.map - -/***/ }), - -/***/ 59451: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0; -exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions; -exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions; -exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse; -exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse; -exports.isValidDomain = isValidDomain; -exports.createCredential = createCredential; -exports.getCredential = getCredential; -exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions; -exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions; -const tslib_1 = __nccwpck_require__(4351); -const base64url_1 = __nccwpck_require__(6677); -const errors_1 = __nccwpck_require__(99938); -const helpers_1 = __nccwpck_require__(54044); -const webauthn_errors_1 = __nccwpck_require__(97906); -Object.defineProperty(exports, "identifyAuthenticationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } })); -Object.defineProperty(exports, "identifyRegistrationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } })); -Object.defineProperty(exports, "isWebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } })); -Object.defineProperty(exports, "WebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } })); -/** - * WebAuthn abort service to manage ceremony cancellation. - * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. - * - * @experimental This class is experimental and may change in future releases - * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} - */ -class WebAuthnAbortService { - /** - * Create an abort signal for a new WebAuthn operation. - * Automatically cancels any existing operation. - * - * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} - */ - createNewAbortSignal() { - // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() - if (this.controller) { - const abortError = new Error('Cancelling existing WebAuthn API call for new one'); - abortError.name = 'AbortError'; - this.controller.abort(abortError); - } - const newController = new AbortController(); - this.controller = newController; - return newController.signal; - } - /** - * Manually cancel the current WebAuthn operation. - * Useful for cleaning up when user cancels or navigates away. - * - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} - */ - cancelCeremony() { - if (this.controller) { - const abortError = new Error('Manually cancelling existing WebAuthn API call'); - abortError.name = 'AbortError'; - this.controller.abort(abortError); - this.controller = undefined; - } - } -} -exports.WebAuthnAbortService = WebAuthnAbortService; -/** - * Singleton instance to ensure only one WebAuthn ceremony is active at a time. - * This prevents "operation already in progress" errors when retrying WebAuthn operations. - * - * @experimental This instance is experimental and may change in future releases - */ -exports.webAuthnAbortService = new WebAuthnAbortService(); -/** - * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers - * as required by the WebAuthn browser API. - * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. - * - * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields - * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() - * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} - */ -function deserializeCredentialCreationOptions(options) { - if (!options) { - throw new Error('Credential creation options are required'); - } - // Check if the native parseCreationOptionsFromJSON method is available - if (typeof PublicKeyCredential !== 'undefined' && - 'parseCreationOptionsFromJSON' in PublicKeyCredential && - typeof PublicKeyCredential - .parseCreationOptionsFromJSON === 'function') { - // Use the native WebAuthn Level 3 method - return PublicKeyCredential.parseCreationOptionsFromJSON( - /** we assert the options here as typescript still doesn't know about future webauthn types */ - options); - } - // Fallback to manual parsing for browsers that don't support the native method - // Destructure to separate fields that need transformation - const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest(options - // Convert challenge from base64url to ArrayBuffer - , ["challenge", "user", "excludeCredentials"]); - // Convert challenge from base64url to ArrayBuffer - const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; - // Convert user.id from base64url to ArrayBuffer - const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer }); - // Build the result object - const result = Object.assign(Object.assign({}, restOptions), { challenge, - user }); - // Only add excludeCredentials if it exists - if (excludeCredentials && excludeCredentials.length > 0) { - result.excludeCredentials = new Array(excludeCredentials.length); - for (let i = 0; i < excludeCredentials.length; i++) { - const cred = excludeCredentials[i]; - result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', - // Cast transports to handle future transport types like "cable" - transports: cred.transports }); - } - } - return result; -} -/** - * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers - * as required by the WebAuthn browser API. - * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. - * - * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields - * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() - * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} - */ -function deserializeCredentialRequestOptions(options) { - if (!options) { - throw new Error('Credential request options are required'); - } - // Check if the native parseRequestOptionsFromJSON method is available - if (typeof PublicKeyCredential !== 'undefined' && - 'parseRequestOptionsFromJSON' in PublicKeyCredential && - typeof PublicKeyCredential - .parseRequestOptionsFromJSON === 'function') { - // Use the native WebAuthn Level 3 method - return PublicKeyCredential.parseRequestOptionsFromJSON(options); - } - // Fallback to manual parsing for browsers that don't support the native method - // Destructure to separate fields that need transformation - const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest(options - // Convert challenge from base64url to ArrayBuffer - , ["challenge", "allowCredentials"]); - // Convert challenge from base64url to ArrayBuffer - const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; - // Build the result object - const result = Object.assign(Object.assign({}, restOptions), { challenge }); - // Only add allowCredentials if it exists - if (allowCredentials && allowCredentials.length > 0) { - result.allowCredentials = new Array(allowCredentials.length); - for (let i = 0; i < allowCredentials.length; i++) { - const cred = allowCredentials[i]; - result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', - // Cast transports to handle future transport types like "cable" - transports: cred.transports }); - } - } - return result; -} -/** - * Convert a registration/enrollment credential response to server format. - * Serializes binary fields to base64url for JSON transmission. - * Supports both native WebAuthn Level 3 toJSON and manual fallback. - * - * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() - * @returns {RegistrationResponseJSON} JSON-serializable credential for server - * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} - */ -function serializeCredentialCreationResponse(credential) { - var _a; - // Check if the credential instance has the toJSON method - if ('toJSON' in credential && typeof credential.toJSON === 'function') { - // Use the native WebAuthn Level 3 method - return credential.toJSON(); - } - const credentialWithAttachment = credential; - return { - id: credential.id, - rawId: credential.id, - response: { - attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)), - clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)), - }, - type: 'public-key', - clientExtensionResults: credential.getClientExtensionResults(), - // Convert null to undefined and cast to AuthenticatorAttachment type - authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), - }; -} -/** - * Convert an authentication/verification credential response to server format. - * Serializes binary fields to base64url for JSON transmission. - * Supports both native WebAuthn Level 3 toJSON and manual fallback. - * - * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() - * @returns {AuthenticationResponseJSON} JSON-serializable credential for server - * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} - */ -function serializeCredentialRequestResponse(credential) { - var _a; - // Check if the credential instance has the toJSON method - if ('toJSON' in credential && typeof credential.toJSON === 'function') { - // Use the native WebAuthn Level 3 method - return credential.toJSON(); - } - // Fallback to manual conversion for browsers that don't support toJSON - // Access authenticatorAttachment via type assertion to handle TypeScript version differences - // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't - const credentialWithAttachment = credential; - const clientExtensionResults = credential.getClientExtensionResults(); - const assertionResponse = credential.response; - return { - id: credential.id, - rawId: credential.id, // W3C spec expects rawId to match id for JSON format - response: { - authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)), - clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)), - signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)), - userHandle: assertionResponse.userHandle - ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle)) - : undefined, - }, - type: 'public-key', - clientExtensionResults, - // Convert null to undefined and cast to AuthenticatorAttachment type - authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), - }; -} -/** - * A simple test to determine if a hostname is a properly-formatted domain name. - * Considers localhost valid for development environments. - * - * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain - * - * Regex sourced from here: - * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html - * - * @param {string} hostname - The hostname to validate - * @returns {boolean} True if valid domain or localhost - * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} - */ -function isValidDomain(hostname) { - return ( - // Consider localhost valid as well since it's okay wrt Secure Contexts - hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname)); -} -/** - * Determine if the browser is capable of WebAuthn. - * Checks for necessary Web APIs: PublicKeyCredential and Credential Management. - * - * @returns {boolean} True if browser supports WebAuthn - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility} - */ -function browserSupportsWebAuthn() { - var _a, _b; - return !!((0, helpers_1.isBrowser)() && - 'PublicKeyCredential' in window && - window.PublicKeyCredential && - 'credentials' in navigator && - typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' && - typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function'); -} -/** - * Create a WebAuthn credential using the browser's credentials API. - * Wraps navigator.credentials.create() with error handling. - * - * @param {CredentialCreationOptions} options - Options including publicKey parameters - * @returns {Promise>} Created credential or error - * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} - */ -async function createCredential(options) { - try { - const response = await navigator.credentials.create( - /** we assert the type here until typescript types are updated */ - options); - if (!response) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), - }; - } - if (!(response instanceof PublicKeyCredential)) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), - }; - } - return { data: response, error: null }; - } - catch (err) { - return { - data: null, - error: (0, webauthn_errors_1.identifyRegistrationError)({ - error: err, - options, - }), - }; - } -} -/** - * Get a WebAuthn credential using the browser's credentials API. - * Wraps navigator.credentials.get() with error handling. - * - * @param {CredentialRequestOptions} options - Options including publicKey parameters - * @returns {Promise>} Retrieved credential or error - * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} - */ -async function getCredential(options) { - try { - const response = await navigator.credentials.get( - /** we assert the type here until typescript types are updated */ - options); - if (!response) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), - }; - } - if (!(response instanceof PublicKeyCredential)) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), - }; - } - return { data: response, error: null }; - } - catch (err) { - return { - data: null, - error: (0, webauthn_errors_1.identifyAuthenticationError)({ - error: err, - options, - }), - }; - } -} -exports.DEFAULT_CREATION_OPTIONS = { - hints: ['security-key'], - authenticatorSelection: { - authenticatorAttachment: 'cross-platform', - requireResidentKey: false, - /** set to preferred because older yubikeys don't have PIN/Biometric */ - userVerification: 'preferred', - residentKey: 'discouraged', - }, - attestation: 'none', -}; -exports.DEFAULT_REQUEST_OPTIONS = { - /** set to preferred because older yubikeys don't have PIN/Biometric */ - userVerification: 'preferred', - hints: ['security-key'], -}; -function deepMerge(...sources) { - const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val); - const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); - const result = {}; - for (const source of sources) { - if (!source) - continue; - for (const key in source) { - const value = source[key]; - if (value === undefined) - continue; - if (Array.isArray(value)) { - // preserve array reference, including unions like AuthenticatorTransport[] - result[key] = value; - } - else if (isArrayBufferLike(value)) { - result[key] = value; - } - else if (isObject(value)) { - const existing = result[key]; - if (isObject(existing)) { - result[key] = deepMerge(existing, value); - } - else { - result[key] = deepMerge(value); - } - } - else { - result[key] = value; - } - } - } - return result; -} -/** - * Merges WebAuthn credential creation options with overrides. - * Sets sensible defaults for authenticator selection and extensions. - * - * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server - * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply - * @param {string} friendlyName - Optional friendly name for the credential - * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options - * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} - */ -function mergeCredentialCreationOptions(baseOptions, overrides) { - return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); -} -/** - * Merges WebAuthn credential request options with overrides. - * Sets sensible defaults for user verification and hints. - * - * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server - * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply - * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options - * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} - */ -function mergeCredentialRequestOptions(baseOptions, overrides) { - return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); -} -/** - * WebAuthn API wrapper for Supabase Auth. - * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. - * - * @experimental This API is experimental and may change in future releases - * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} - */ -class WebAuthnApi { - constructor(client) { - this.client = client; - // Bind all methods so they can be destructured - this.enroll = this._enroll.bind(this); - this.challenge = this._challenge.bind(this); - this.verify = this._verify.bind(this); - this.authenticate = this._authenticate.bind(this); - this.register = this._register.bind(this); - } - /** - * Enroll a new WebAuthn factor. - * Creates an unverified WebAuthn factor that must be verified with a credential. - * - * @experimental This method is experimental and may change in future releases - * @param {Omit} params - Enrollment parameters (friendlyName required) - * @returns {Promise} Enrolled factor details or error - * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} - */ - async _enroll(params) { - return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' })); - } - /** - * Challenge for WebAuthn credential creation or authentication. - * Combines server challenge with browser credential operations. - * Handles both registration (create) and authentication (request) flows. - * - * @experimental This method is experimental and may change in future releases - * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId - * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials - * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation - * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request - * @returns {Promise} Challenge response with credential or error - * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} - * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} - */ - async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) { - try { - // Get challenge from server using the client's MFA methods - const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ - factorId, - webauthn, - }); - if (!challengeResponse) { - return { data: null, error: challengeError }; - } - const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal(); - /** webauthn will fail if either of the name/displayname are blank */ - if (challengeResponse.webauthn.type === 'create') { - const { user } = challengeResponse.webauthn.credential_options.publicKey; - if (!user.name) { - user.name = `${user.id}:${friendlyName}`; - } - if (!user.displayName) { - user.displayName = user.name; - } - } - switch (challengeResponse.webauthn.type) { - case 'create': { - const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); - const { data, error } = await createCredential({ - publicKey: options, - signal: abortSignal, - }); - if (data) { - return { - data: { - factorId, - challengeId: challengeResponse.id, - webauthn: { - type: challengeResponse.webauthn.type, - credential_response: data, - }, - }, - error: null, - }; - } - return { data: null, error }; - } - case 'request': { - const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); - const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); - if (data) { - return { - data: { - factorId, - challengeId: challengeResponse.id, - webauthn: { - type: challengeResponse.webauthn.type, - credential_response: data, - }, - }, - error: null, - }; - } - return { data: null, error }; - } - } - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - return { - data: null, - error: new errors_1.AuthUnknownError('Unexpected error in challenge', error), - }; - } - } - /** - * Verify a WebAuthn credential with the server. - * Completes the WebAuthn ceremony by sending the credential to the server for verification. - * - * @experimental This method is experimental and may change in future releases - * @param {Object} params - Verification parameters - * @param {string} params.challengeId - ID of the challenge being verified - * @param {string} params.factorId - ID of the WebAuthn factor - * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response - * @returns {Promise} Verification result with session or error - * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} - * */ - async _verify({ challengeId, factorId, webauthn, }) { - return this.client.mfa.verify({ - factorId, - challengeId, - webauthn: webauthn, - }); - } - /** - * Complete WebAuthn authentication flow. - * Performs challenge and verification in a single operation for existing credentials. - * - * @experimental This method is experimental and may change in future releases - * @param {Object} params - Authentication parameters - * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with - * @param {Object} params.webauthn - WebAuthn configuration - * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) - * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) - * @param {AbortSignal} params.webauthn.signal - Optional abort signal - * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get - * @returns {Promise>} Authentication result - * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} - */ - async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, }, overrides) { - if (!rpId) { - return { - data: null, - error: new errors_1.AuthError('rpId is required for WebAuthn authentication'), - }; - } - try { - if (!browserSupportsWebAuthn()) { - return { - data: null, - error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), - }; - } - // Get challenge and credential - const { data: challengeResponse, error: challengeError } = await this.challenge({ - factorId, - webauthn: { rpId, rpOrigins }, - signal, - }, { request: overrides }); - if (!challengeResponse) { - return { data: null, error: challengeError }; - } - const { webauthn } = challengeResponse; - // Verify credential - return this._verify({ - factorId, - challengeId: challengeResponse.challengeId, - webauthn: { - type: webauthn.type, - rpId, - rpOrigins, - credential_response: webauthn.credential_response, - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - return { - data: null, - error: new errors_1.AuthUnknownError('Unexpected error in authenticate', error), - }; - } - } - /** - * Complete WebAuthn registration flow. - * Performs enrollment, challenge, and verification in a single operation for new credentials. - * - * @experimental This method is experimental and may change in future releases - * @param {Object} params - Registration parameters - * @param {string} params.friendlyName - User-friendly name for the credential - * @param {string} params.rpId - Relying Party ID (defaults to current hostname) - * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) - * @param {AbortSignal} params.signal - Optional abort signal - * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create - * @returns {Promise>} Registration result - * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} - */ - async _register({ friendlyName, rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, overrides) { - if (!rpId) { - return { - data: null, - error: new errors_1.AuthError('rpId is required for WebAuthn registration'), - }; - } - try { - if (!browserSupportsWebAuthn()) { - return { - data: null, - error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), - }; - } - // Enroll factor - const { data: factor, error: enrollError } = await this._enroll({ - friendlyName, - }); - if (!factor) { - await this.client.mfa - .listFactors() - .then((factors) => { - var _a; - return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' && - v.friendly_name === friendlyName && - v.status !== 'unverified'); - }) - .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0)); - return { data: null, error: enrollError }; - } - // Get challenge and create credential - const { data: challengeResponse, error: challengeError } = await this._challenge({ - factorId: factor.id, - friendlyName: factor.friendly_name, - webauthn: { rpId, rpOrigins }, - signal, - }, { - create: overrides, - }); - if (!challengeResponse) { - return { data: null, error: challengeError }; - } - return this._verify({ - factorId: factor.id, - challengeId: challengeResponse.challengeId, - webauthn: { - rpId, - rpOrigins, - type: challengeResponse.webauthn.type, - credential_response: challengeResponse.webauthn.credential_response, - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - return { - data: null, - error: new errors_1.AuthUnknownError('Unexpected error in register', error), - }; - } - } -} -exports.WebAuthnApi = WebAuthnApi; -//# sourceMappingURL=webauthn.js.map - -/***/ }), - -/***/ 89904: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FunctionsClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -const helper_1 = __nccwpck_require__(90618); -const types_1 = __nccwpck_require__(93136); -class FunctionsClient { - constructor(url, { headers = {}, customFetch, region = types_1.FunctionRegion.Any, } = {}) { - this.url = url; - this.headers = headers; - this.region = region; - this.fetch = (0, helper_1.resolveFetch)(customFetch); - } - /** - * Updates the authorization header - * @param token - the new jwt token sent in the authorisation header - */ - setAuth(token) { - this.headers.Authorization = `Bearer ${token}`; - } - /** - * Invokes a function - * @param functionName - The name of the Function to invoke. - * @param options - Options for invoking the Function. - */ - invoke(functionName_1) { - return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) { - var _a; - try { - const { headers, method, body: functionArgs, signal } = options; - let _headers = {}; - let { region } = options; - if (!region) { - region = this.region; - } - // Add region as query parameter using URL API - const url = new URL(`${this.url}/${functionName}`); - if (region && region !== 'any') { - _headers['x-region'] = region; - url.searchParams.set('forceFunctionRegion', region); - } - let body; - if (functionArgs && - ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { - if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || - functionArgs instanceof ArrayBuffer) { - // will work for File as File inherits Blob - // also works for ArrayBuffer as it is the same underlying structure as a Blob - _headers['Content-Type'] = 'application/octet-stream'; - body = functionArgs; - } - else if (typeof functionArgs === 'string') { - // plain string - _headers['Content-Type'] = 'text/plain'; - body = functionArgs; - } - else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { - // don't set content-type headers - // Request will automatically add the right boundary value - body = functionArgs; - } - else { - // default, assume this is JSON - _headers['Content-Type'] = 'application/json'; - body = JSON.stringify(functionArgs); - } - } - else { - // if the Content-Type was supplied, simply set the body - body = functionArgs; - } - const response = yield this.fetch(url.toString(), { - method: method || 'POST', - // headers priority is (high to low): - // 1. invoke-level headers - // 2. client-level headers - // 3. default Content-Type header - headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), - body, - signal, - }).catch((fetchError) => { - if (fetchError.name === 'AbortError') { - throw fetchError; - } - throw new types_1.FunctionsFetchError(fetchError); - }); - const isRelayError = response.headers.get('x-relay-error'); - if (isRelayError && isRelayError === 'true') { - throw new types_1.FunctionsRelayError(response); - } - if (!response.ok) { - throw new types_1.FunctionsHttpError(response); - } - let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); - let data; - if (responseType === 'application/json') { - data = yield response.json(); - } - else if (responseType === 'application/octet-stream' || - responseType === 'application/pdf') { - data = yield response.blob(); - } - else if (responseType === 'text/event-stream') { - data = response; - } - else if (responseType === 'multipart/form-data') { - data = yield response.formData(); - } - else { - // default to text - data = yield response.text(); - } - return { data, error: null, response }; - } - catch (error) { - if (error instanceof Error && error.name === 'AbortError') { - return { data: null, error: new types_1.FunctionsFetchError(error) }; - } - return { - data: null, - error, - response: error instanceof types_1.FunctionsHttpError || error instanceof types_1.FunctionsRelayError - ? error.context - : undefined, - }; - } - }); - } -} -exports.FunctionsClient = FunctionsClient; -//# sourceMappingURL=FunctionsClient.js.map - -/***/ }), - -/***/ 90618: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveFetch = void 0; -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => __importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -//# sourceMappingURL=helper.js.map - -/***/ }), - -/***/ 38519: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FunctionRegion = exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; -var FunctionsClient_1 = __nccwpck_require__(89904); -Object.defineProperty(exports, "FunctionsClient", ({ enumerable: true, get: function () { return FunctionsClient_1.FunctionsClient; } })); -var types_1 = __nccwpck_require__(93136); -Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return types_1.FunctionsError; } })); -Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return types_1.FunctionsFetchError; } })); -Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return types_1.FunctionsHttpError; } })); -Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return types_1.FunctionsRelayError; } })); -Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return types_1.FunctionRegion; } })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 93136: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; -class FunctionsError extends Error { - constructor(message, name = 'FunctionsError', context) { - super(message); - this.name = name; - this.context = context; - } -} -exports.FunctionsError = FunctionsError; -class FunctionsFetchError extends FunctionsError { - constructor(context) { - super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); - } -} -exports.FunctionsFetchError = FunctionsFetchError; -class FunctionsRelayError extends FunctionsError { - constructor(context) { - super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); - } -} -exports.FunctionsRelayError = FunctionsRelayError; -class FunctionsHttpError extends FunctionsError { - constructor(context) { - super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); - } -} -exports.FunctionsHttpError = FunctionsHttpError; -// Define the enum for the 'region' property -var FunctionRegion; -(function (FunctionRegion) { - FunctionRegion["Any"] = "any"; - FunctionRegion["ApNortheast1"] = "ap-northeast-1"; - FunctionRegion["ApNortheast2"] = "ap-northeast-2"; - FunctionRegion["ApSouth1"] = "ap-south-1"; - FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; - FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; - FunctionRegion["CaCentral1"] = "ca-central-1"; - FunctionRegion["EuCentral1"] = "eu-central-1"; - FunctionRegion["EuWest1"] = "eu-west-1"; - FunctionRegion["EuWest2"] = "eu-west-2"; - FunctionRegion["EuWest3"] = "eu-west-3"; - FunctionRegion["SaEast1"] = "sa-east-1"; - FunctionRegion["UsEast1"] = "us-east-1"; - FunctionRegion["UsWest1"] = "us-west-1"; - FunctionRegion["UsWest2"] = "us-west-2"; -})(FunctionRegion || (exports.FunctionRegion = FunctionRegion = {})); -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 93149: -/***/ ((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__(28665)); -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; - -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) { - { - 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; - - -/***/ }), - -/***/ 91049: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -// @ts-ignore -const node_fetch_1 = tslib_1.__importDefault(__nccwpck_require__(93149)); -const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(47317)); -class PostgrestBuilder { - constructor(builder) { - var _a, _b; - this.shouldThrowOnError = false; - this.method = builder.method; - this.url = builder.url; - this.headers = new Headers(builder.headers); - this.schema = builder.schema; - this.body = builder.body; - this.shouldThrowOnError = (_a = builder.shouldThrowOnError) !== null && _a !== void 0 ? _a : false; - this.signal = builder.signal; - this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false; - if (builder.fetch) { - this.fetch = builder.fetch; - } - else if (typeof fetch === 'undefined') { - this.fetch = node_fetch_1.default; - } - else { - this.fetch = fetch; - } - } - /** - * If there's an error with the query, throwOnError will reject the promise by - * throwing the error instead of returning it as part of a successful response. - * - * {@link https://github.com/supabase/supabase-js/issues/92} - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Set an HTTP header for the request. - */ - setHeader(name, value) { - this.headers = new Headers(this.headers); - this.headers.set(name, value); - return this; - } - then(onfulfilled, onrejected) { - // https://postgrest.org/en/stable/api.html#switching-schemas - if (this.schema === undefined) { - // skip - } - else if (['GET', 'HEAD'].includes(this.method)) { - this.headers.set('Accept-Profile', this.schema); - } - else { - this.headers.set('Content-Profile', this.schema); - } - if (this.method !== 'GET' && this.method !== 'HEAD') { - this.headers.set('Content-Type', 'application/json'); - } - // NOTE: Invoke w/o `this` to avoid illegal invocation error. - // https://github.com/supabase/postgrest-js/pull/247 - const _fetch = this.fetch; - let res = _fetch(this.url.toString(), { - method: this.method, - headers: this.headers, - body: JSON.stringify(this.body), - signal: this.signal, - }).then(async (res) => { - var _a, _b, _c, _d; - let error = null; - let data = null; - let count = null; - let status = res.status; - let statusText = res.statusText; - if (res.ok) { - if (this.method !== 'HEAD') { - const body = await res.text(); - if (body === '') { - // Prefer: return=minimal - } - else if (this.headers.get('Accept') === 'text/csv') { - data = body; - } - else if (this.headers.get('Accept') && - ((_a = this.headers.get('Accept')) === null || _a === void 0 ? void 0 : _a.includes('application/vnd.pgrst.plan+text'))) { - data = body; - } - else { - data = JSON.parse(body); - } - } - const countHeader = (_b = this.headers.get('Prefer')) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/); - const contentRange = (_c = res.headers.get('content-range')) === null || _c === void 0 ? void 0 : _c.split('/'); - if (countHeader && contentRange && contentRange.length > 1) { - count = parseInt(contentRange[1]); - } - // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 - // Issue persists e.g. for `.insert([...]).select().maybeSingle()` - if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { - if (data.length > 1) { - error = { - // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 - code: 'PGRST116', - details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, - hint: null, - message: 'JSON object requested, multiple (or no) rows returned', - }; - data = null; - count = null; - status = 406; - statusText = 'Not Acceptable'; - } - else if (data.length === 1) { - data = data[0]; - } - else { - data = null; - } - } - } - else { - const body = await res.text(); - try { - error = JSON.parse(body); - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (Array.isArray(error) && res.status === 404) { - data = []; - error = null; - status = 200; - statusText = 'OK'; - } - } - catch (_e) { - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (res.status === 404 && body === '') { - status = 204; - statusText = 'No Content'; - } - else { - error = { - message: body, - }; - } - } - if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes('0 rows'))) { - error = null; - status = 200; - statusText = 'OK'; - } - if (error && this.shouldThrowOnError) { - throw new PostgrestError_1.default(error); - } - } - const postgrestResponse = { - error, - data, - count, - status, - statusText, - }; - return postgrestResponse; - }); - if (!this.shouldThrowOnError) { - res = res.catch((fetchError) => { - var _a, _b, _c; - return ({ - error: { - message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, - details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, - hint: '', - code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, - }, - data: null, - count: null, - status: 0, - statusText: '', - }); - }); - } - return res.then(onfulfilled, onrejected); - } - /** - * Override the type of the returned `data`. - * - * @typeParam NewResult - The new result type to override with - * @deprecated Use overrideTypes() method at the end of your call chain instead - */ - returns() { - /* istanbul ignore next */ - return this; - } - /** - * Override the type of the returned `data` field in the response. - * - * @typeParam NewResult - The new type to cast the response data to - * @typeParam Options - Optional type configuration (defaults to { merge: true }) - * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) - * @example - * ```typescript - * // Merge with existing types (default behavior) - * const query = supabase - * .from('users') - * .select() - * .overrideTypes<{ custom_field: string }>() - * - * // Replace existing types completely - * const replaceQuery = supabase - * .from('users') - * .select() - * .overrideTypes<{ id: number; name: string }, { merge: false }>() - * ``` - * @returns A PostgrestBuilder instance with the new type - */ - overrideTypes() { - return this; - } -} -exports["default"] = PostgrestBuilder; -//# sourceMappingURL=PostgrestBuilder.js.map - -/***/ }), - -/***/ 11526: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50050)); -const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); -/** - * PostgREST client. - * - * @typeParam Database - Types for the schema from the [type - * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) - * - * @typeParam SchemaName - Postgres schema to switch to. Must be a string - * literal, the same one passed to the constructor. If the schema is not - * `"public"`, this must be supplied manually. - */ -class PostgrestClient { - // TODO: Add back shouldThrowOnError once we figure out the typings - /** - * Creates a PostgREST client. - * - * @param url - URL of the PostgREST endpoint - * @param options - Named parameters - * @param options.headers - Custom headers - * @param options.schema - Postgres schema to switch to - * @param options.fetch - Custom fetch - */ - constructor(url, { headers = {}, schema, fetch, } = {}) { - this.url = url; - this.headers = new Headers(headers); - this.schemaName = schema; - this.fetch = fetch; - } - /** - * Perform a query on a table or a view. - * - * @param relation - The table or view name to query - */ - from(relation) { - const url = new URL(`${this.url}/${relation}`); - return new PostgrestQueryBuilder_1.default(url, { - headers: new Headers(this.headers), - schema: this.schemaName, - fetch: this.fetch, - }); - } - /** - * Select a schema to query or perform an function (rpc) call. - * - * The schema needs to be on the list of exposed schemas inside Supabase. - * - * @param schema - The schema to query - */ - schema(schema) { - return new PostgrestClient(this.url, { - headers: this.headers, - schema, - fetch: this.fetch, - }); - } - /** - * Perform a function call. - * - * @param fn - The function name to call - * @param args - The arguments to pass to the function call - * @param options - Named parameters - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * @param options.get - When set to `true`, the function will be called with - * read-only access mode. - * @param options.count - Count algorithm to use to count rows returned by the - * function. Only applicable for [set-returning - * functions](https://www.postgresql.org/docs/current/functions-srf.html). - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - rpc(fn, args = {}, { head = false, get = false, count, } = {}) { - var _a; - let method; - const url = new URL(`${this.url}/rpc/${fn}`); - let body; - if (head || get) { - method = head ? 'HEAD' : 'GET'; - Object.entries(args) - // params with undefined value needs to be filtered out, otherwise it'll - // show up as `?param=undefined` - .filter(([_, value]) => value !== undefined) - // array values need special syntax - .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) - .forEach(([name, value]) => { - url.searchParams.append(name, value); - }); - } - else { - method = 'POST'; - body = args; - } - const headers = new Headers(this.headers); - if (count) { - headers.set('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url, - headers, - schema: this.schemaName, - body, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } -} -exports["default"] = PostgrestClient; -//# sourceMappingURL=PostgrestClient.js.map - -/***/ }), - -/***/ 47317: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Error format - * - * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} - */ -class PostgrestError extends Error { - constructor(context) { - super(context.message); - this.name = 'PostgrestError'; - this.details = context.details; - this.hint = context.hint; - this.code = context.code; - } -} -exports["default"] = PostgrestError; -//# sourceMappingURL=PostgrestError.js.map - -/***/ }), - -/***/ 6671: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(81566)); -const PostgrestReservedCharsRegexp = new RegExp('[,()]'); -class PostgrestFilterBuilder extends PostgrestTransformBuilder_1.default { - /** - * Match only rows where `column` is equal to `value`. - * - * To check if the value of `column` is NULL, you should use `.is()` instead. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - eq(column, value) { - this.url.searchParams.append(column, `eq.${value}`); - return this; - } - /** - * Match only rows where `column` is not equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - neq(column, value) { - this.url.searchParams.append(column, `neq.${value}`); - return this; - } - /** - * Match only rows where `column` is greater than `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - gt(column, value) { - this.url.searchParams.append(column, `gt.${value}`); - return this; - } - /** - * Match only rows where `column` is greater than or equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - gte(column, value) { - this.url.searchParams.append(column, `gte.${value}`); - return this; - } - /** - * Match only rows where `column` is less than `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - lt(column, value) { - this.url.searchParams.append(column, `lt.${value}`); - return this; - } - /** - * Match only rows where `column` is less than or equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - lte(column, value) { - this.url.searchParams.append(column, `lte.${value}`); - return this; - } - /** - * Match only rows where `column` matches `pattern` case-sensitively. - * - * @param column - The column to filter on - * @param pattern - The pattern to match with - */ - like(column, pattern) { - this.url.searchParams.append(column, `like.${pattern}`); - return this; - } - /** - * Match only rows where `column` matches all of `patterns` case-sensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - likeAllOf(column, patterns) { - this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches any of `patterns` case-sensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - likeAnyOf(column, patterns) { - this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches `pattern` case-insensitively. - * - * @param column - The column to filter on - * @param pattern - The pattern to match with - */ - ilike(column, pattern) { - this.url.searchParams.append(column, `ilike.${pattern}`); - return this; - } - /** - * Match only rows where `column` matches all of `patterns` case-insensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - ilikeAllOf(column, patterns) { - this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches any of `patterns` case-insensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - ilikeAnyOf(column, patterns) { - this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` IS `value`. - * - * For non-boolean columns, this is only relevant for checking if the value of - * `column` is NULL by setting `value` to `null`. - * - * For boolean columns, you can also set `value` to `true` or `false` and it - * will behave the same way as `.eq()`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - is(column, value) { - this.url.searchParams.append(column, `is.${value}`); - return this; - } - /** - * Match only rows where `column` is included in the `values` array. - * - * @param column - The column to filter on - * @param values - The values array to filter with - */ - in(column, values) { - const cleanedValues = Array.from(new Set(values)) - .map((s) => { - // handle postgrest reserved characters - // https://postgrest.org/en/v7.0.0/api.html#reserved-characters - if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) - return `"${s}"`; - else - return `${s}`; - }) - .join(','); - this.url.searchParams.append(column, `in.(${cleanedValues})`); - return this; - } - /** - * Only relevant for jsonb, array, and range columns. Match only rows where - * `column` contains every element appearing in `value`. - * - * @param column - The jsonb, array, or range column to filter on - * @param value - The jsonb, array, or range value to filter with - */ - contains(column, value) { - if (typeof value === 'string') { - // range types can be inclusive '[', ']' or exclusive '(', ')' so just - // keep it simple and accept a string - this.url.searchParams.append(column, `cs.${value}`); - } - else if (Array.isArray(value)) { - // array - this.url.searchParams.append(column, `cs.{${value.join(',')}}`); - } - else { - // json - this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); - } - return this; - } - /** - * Only relevant for jsonb, array, and range columns. Match only rows where - * every element appearing in `column` is contained by `value`. - * - * @param column - The jsonb, array, or range column to filter on - * @param value - The jsonb, array, or range value to filter with - */ - containedBy(column, value) { - if (typeof value === 'string') { - // range - this.url.searchParams.append(column, `cd.${value}`); - } - else if (Array.isArray(value)) { - // array - this.url.searchParams.append(column, `cd.{${value.join(',')}}`); - } - else { - // json - this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); - } - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is greater than any element in `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeGt(column, range) { - this.url.searchParams.append(column, `sr.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is either contained in `range` or greater than any element in - * `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeGte(column, range) { - this.url.searchParams.append(column, `nxl.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is less than any element in `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeLt(column, range) { - this.url.searchParams.append(column, `sl.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is either contained in `range` or less than any element in - * `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeLte(column, range) { - this.url.searchParams.append(column, `nxr.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where `column` is - * mutually exclusive to `range` and there can be no element between the two - * ranges. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeAdjacent(column, range) { - this.url.searchParams.append(column, `adj.${range}`); - return this; - } - /** - * Only relevant for array and range columns. Match only rows where - * `column` and `value` have an element in common. - * - * @param column - The array or range column to filter on - * @param value - The array or range value to filter with - */ - overlaps(column, value) { - if (typeof value === 'string') { - // range - this.url.searchParams.append(column, `ov.${value}`); - } - else { - // array - this.url.searchParams.append(column, `ov.{${value.join(',')}}`); - } - return this; - } - /** - * Only relevant for text and tsvector columns. Match only rows where - * `column` matches the query string in `query`. - * - * @param column - The text or tsvector column to filter on - * @param query - The query text to match with - * @param options - Named parameters - * @param options.config - The text search configuration to use - * @param options.type - Change how the `query` text is interpreted - */ - textSearch(column, query, { config, type } = {}) { - let typePart = ''; - if (type === 'plain') { - typePart = 'pl'; - } - else if (type === 'phrase') { - typePart = 'ph'; - } - else if (type === 'websearch') { - typePart = 'w'; - } - const configPart = config === undefined ? '' : `(${config})`; - this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); - return this; - } - /** - * Match only rows where each column in `query` keys is equal to its - * associated value. Shorthand for multiple `.eq()`s. - * - * @param query - The object to filter with, with column names as keys mapped - * to their filter values - */ - match(query) { - Object.entries(query).forEach(([column, value]) => { - this.url.searchParams.append(column, `eq.${value}`); - }); - return this; - } - /** - * Match only rows which doesn't satisfy the filter. - * - * Unlike most filters, `opearator` and `value` are used as-is and need to - * follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure they are properly sanitized. - * - * @param column - The column to filter on - * @param operator - The operator to be negated to filter with, following - * PostgREST syntax - * @param value - The value to filter with, following PostgREST syntax - */ - not(column, operator, value) { - this.url.searchParams.append(column, `not.${operator}.${value}`); - return this; - } - /** - * Match only rows which satisfy at least one of the filters. - * - * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure it's properly sanitized. - * - * It's currently not possible to do an `.or()` filter across multiple tables. - * - * @param filters - The filters to use, following PostgREST syntax - * @param options - Named parameters - * @param options.referencedTable - Set this to filter on referenced tables - * instead of the parent table - * @param options.foreignTable - Deprecated, use `referencedTable` instead - */ - or(filters, { foreignTable, referencedTable = foreignTable, } = {}) { - const key = referencedTable ? `${referencedTable}.or` : 'or'; - this.url.searchParams.append(key, `(${filters})`); - return this; - } - /** - * Match only rows which satisfy the filter. This is an escape hatch - you - * should use the specific filter methods wherever possible. - * - * Unlike most filters, `opearator` and `value` are used as-is and need to - * follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure they are properly sanitized. - * - * @param column - The column to filter on - * @param operator - The operator to filter with, following PostgREST syntax - * @param value - The value to filter with, following PostgREST syntax - */ - filter(column, operator, value) { - this.url.searchParams.append(column, `${operator}.${value}`); - return this; - } -} -exports["default"] = PostgrestFilterBuilder; -//# sourceMappingURL=PostgrestFilterBuilder.js.map - -/***/ }), - -/***/ 50050: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); -class PostgrestQueryBuilder { - constructor(url, { headers = {}, schema, fetch, }) { - this.url = url; - this.headers = new Headers(headers); - this.schema = schema; - this.fetch = fetch; - } - /** - * Perform a SELECT query on the table or view. - * - * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` - * - * @param options - Named parameters - * - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * - * @param options.count - Count algorithm to use to count rows in the table or view. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - select(columns, options) { - const { head = false, count } = options !== null && options !== void 0 ? options : {}; - const method = head ? 'HEAD' : 'GET'; - // Remove whitespaces except when quoted - let quoted = false; - const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') - .split('') - .map((c) => { - if (/\s/.test(c) && !quoted) { - return ''; - } - if (c === '"') { - quoted = !quoted; - } - return c; - }) - .join(''); - this.url.searchParams.set('select', cleanedColumns); - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - fetch: this.fetch, - }); - } - /** - * Perform an INSERT into the table or view. - * - * By default, inserted rows are not returned. To return it, chain the call - * with `.select()`. - * - * @param values - The values to insert. Pass an object to insert a single row - * or an array to insert multiple rows. - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count inserted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - * - * @param options.defaultToNull - Make missing fields default to `null`. - * Otherwise, use the default value for the column. Only applies for bulk - * inserts. - */ - insert(values, { count, defaultToNull = true, } = {}) { - var _a; - const method = 'POST'; - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - if (!defaultToNull) { - this.headers.append('Prefer', `missing=default`); - } - if (Array.isArray(values)) { - const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); - if (columns.length > 0) { - const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); - this.url.searchParams.set('columns', uniqueColumns.join(',')); - } - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } - /** - * Perform an UPSERT on the table or view. Depending on the column(s) passed - * to `onConflict`, `.upsert()` allows you to perform the equivalent of - * `.insert()` if a row with the corresponding `onConflict` columns doesn't - * exist, or if it does exist, perform an alternative action depending on - * `ignoreDuplicates`. - * - * By default, upserted rows are not returned. To return it, chain the call - * with `.select()`. - * - * @param values - The values to upsert with. Pass an object to upsert a - * single row or an array to upsert multiple rows. - * - * @param options - Named parameters - * - * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how - * duplicate rows are determined. Two rows are duplicates if all the - * `onConflict` columns are equal. - * - * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If - * `false`, duplicate rows are merged with existing rows. - * - * @param options.count - Count algorithm to use to count upserted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - * - * @param options.defaultToNull - Make missing fields default to `null`. - * Otherwise, use the default value for the column. This only applies when - * inserting new rows, not when merging with existing rows under - * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. - */ - upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { - var _a; - const method = 'POST'; - this.headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`); - if (onConflict !== undefined) - this.url.searchParams.set('on_conflict', onConflict); - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - if (!defaultToNull) { - this.headers.append('Prefer', 'missing=default'); - } - if (Array.isArray(values)) { - const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); - if (columns.length > 0) { - const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); - this.url.searchParams.set('columns', uniqueColumns.join(',')); - } - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } - /** - * Perform an UPDATE on the table or view. - * - * By default, updated rows are not returned. To return it, chain the call - * with `.select()` after filters. - * - * @param values - The values to update with - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count updated rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - update(values, { count, } = {}) { - var _a; - const method = 'PATCH'; - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } - /** - * Perform a DELETE on the table or view. - * - * By default, deleted rows are not returned. To return it, chain the call - * with `.select()` after filters. - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count deleted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - delete({ count, } = {}) { - var _a; - const method = 'DELETE'; - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } -} -exports["default"] = PostgrestQueryBuilder; -//# sourceMappingURL=PostgrestQueryBuilder.js.map - -/***/ }), - -/***/ 81566: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(91049)); -class PostgrestTransformBuilder extends PostgrestBuilder_1.default { - /** - * Perform a SELECT on the query result. - * - * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not - * return modified rows. By calling this method, modified rows are returned in - * `data`. - * - * @param columns - The columns to retrieve, separated by commas - */ - select(columns) { - // Remove whitespaces except when quoted - let quoted = false; - const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') - .split('') - .map((c) => { - if (/\s/.test(c) && !quoted) { - return ''; - } - if (c === '"') { - quoted = !quoted; - } - return c; - }) - .join(''); - this.url.searchParams.set('select', cleanedColumns); - this.headers.append('Prefer', 'return=representation'); - return this; - } - /** - * Order the query result by `column`. - * - * You can call this method multiple times to order by multiple columns. - * - * You can order referenced tables, but it only affects the ordering of the - * parent table if you use `!inner` in the query. - * - * @param column - The column to order by - * @param options - Named parameters - * @param options.ascending - If `true`, the result will be in ascending order - * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, - * `null`s appear last. - * @param options.referencedTable - Set this to order a referenced table by - * its columns - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) { - const key = referencedTable ? `${referencedTable}.order` : 'order'; - const existingOrder = this.url.searchParams.get(key); - this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); - return this; - } - /** - * Limit the query result by `count`. - * - * @param count - The maximum number of rows to return - * @param options - Named parameters - * @param options.referencedTable - Set this to limit rows of referenced - * tables instead of the parent table - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - limit(count, { foreignTable, referencedTable = foreignTable, } = {}) { - const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; - this.url.searchParams.set(key, `${count}`); - return this; - } - /** - * Limit the query result by starting at an offset `from` and ending at the offset `to`. - * Only records within this range are returned. - * This respects the query order and if there is no order clause the range could behave unexpectedly. - * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third - * and fourth rows of the query. - * - * @param from - The starting index from which to limit the result - * @param to - The last index to which to limit the result - * @param options - Named parameters - * @param options.referencedTable - Set this to limit rows of referenced - * tables instead of the parent table - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) { - const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`; - const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; - this.url.searchParams.set(keyOffset, `${from}`); - // Range is inclusive, so add 1 - this.url.searchParams.set(keyLimit, `${to - from + 1}`); - return this; - } - /** - * Set the AbortSignal for the fetch request. - * - * @param signal - The AbortSignal to use for the fetch request - */ - abortSignal(signal) { - this.signal = signal; - return this; - } - /** - * Return `data` as a single object instead of an array of objects. - * - * Query result must be one row (e.g. using `.limit(1)`), otherwise this - * returns an error. - */ - single() { - this.headers.set('Accept', 'application/vnd.pgrst.object+json'); - return this; - } - /** - * Return `data` as a single object instead of an array of objects. - * - * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise - * this returns an error. - */ - maybeSingle() { - // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 - // Issue persists e.g. for `.insert([...]).select().maybeSingle()` - if (this.method === 'GET') { - this.headers.set('Accept', 'application/json'); - } - else { - this.headers.set('Accept', 'application/vnd.pgrst.object+json'); - } - this.isMaybeSingle = true; - return this; - } - /** - * Return `data` as a string in CSV format. - */ - csv() { - this.headers.set('Accept', 'text/csv'); - return this; - } - /** - * Return `data` as an object in [GeoJSON](https://geojson.org) format. - */ - geojson() { - this.headers.set('Accept', 'application/geo+json'); - return this; - } - /** - * Return `data` as the EXPLAIN plan for the query. - * - * You need to enable the - * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) - * setting before using this method. - * - * @param options - Named parameters - * - * @param options.analyze - If `true`, the query will be executed and the - * actual run time will be returned - * - * @param options.verbose - If `true`, the query identifier will be returned - * and `data` will include the output columns of the query - * - * @param options.settings - If `true`, include information on configuration - * parameters that affect query planning - * - * @param options.buffers - If `true`, include information on buffer usage - * - * @param options.wal - If `true`, include information on WAL record generation - * - * @param options.format - The format of the output, can be `"text"` (default) - * or `"json"` - */ - explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { - var _a; - const options = [ - analyze ? 'analyze' : null, - verbose ? 'verbose' : null, - settings ? 'settings' : null, - buffers ? 'buffers' : null, - wal ? 'wal' : null, - ] - .filter(Boolean) - .join('|'); - // An Accept header can carry multiple media types but postgrest-js always sends one - const forMediatype = (_a = this.headers.get('Accept')) !== null && _a !== void 0 ? _a : 'application/json'; - this.headers.set('Accept', `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`); - if (format === 'json') { - return this; - } - else { - return this; - } - } - /** - * Rollback the query. - * - * `data` will still be returned, but the query is not committed. - */ - rollback() { - this.headers.append('Prefer', 'tx=rollback'); - return this; - } - /** - * Override the type of the returned `data`. - * - * @typeParam NewResult - The new result type to override with - * @deprecated Use overrideTypes() method at the end of your call chain instead - */ - returns() { - return this; - } - /** - * Set the maximum number of rows that can be affected by the query. - * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. - * - * @param value - The maximum number of rows that can be affected - */ - maxAffected(value) { - this.headers.append('Prefer', 'handling=strict'); - this.headers.append('Prefer', `max-affected=${value}`); - return this; - } -} -exports["default"] = PostgrestTransformBuilder; -//# sourceMappingURL=PostgrestTransformBuilder.js.map - -/***/ }), - -/***/ 31178: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -// Always update wrapper.mjs when updating this file. -const PostgrestClient_1 = tslib_1.__importDefault(__nccwpck_require__(11526)); -exports.PostgrestClient = PostgrestClient_1.default; -const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50050)); -exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; -const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); -exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; -const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(81566)); -exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; -const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(91049)); -exports.PostgrestBuilder = PostgrestBuilder_1.default; -const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(47317)); -exports.PostgrestError = PostgrestError_1.default; -exports["default"] = { - PostgrestClient: PostgrestClient_1.default, - PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, - PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, - PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, - PostgrestBuilder: PostgrestBuilder_1.default, - PostgrestError: PostgrestError_1.default, -}; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 39911: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(50088); -const push_1 = tslib_1.__importDefault(__nccwpck_require__(82292)); -const timer_1 = tslib_1.__importDefault(__nccwpck_require__(12983)); -const RealtimePresence_1 = tslib_1.__importDefault(__nccwpck_require__(75583)); -const Transformers = tslib_1.__importStar(__nccwpck_require__(1140)); -const transformers_1 = __nccwpck_require__(1140); -var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; -(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; -})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); -var REALTIME_LISTEN_TYPES; -(function (REALTIME_LISTEN_TYPES) { - REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; - REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; - REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; - REALTIME_LISTEN_TYPES["SYSTEM"] = "system"; -})(REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = REALTIME_LISTEN_TYPES = {})); -var REALTIME_SUBSCRIBE_STATES; -(function (REALTIME_SUBSCRIBE_STATES) { - REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; - REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; - REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; - REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; -})(REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = REALTIME_SUBSCRIBE_STATES = {})); -exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES; -/** A channel is the basic building block of Realtime - * and narrows the scope of data flow to subscribed clients. - * You can think of a channel as a chatroom where participants are able to see who's online - * and send and receive messages. - */ -class RealtimeChannel { - constructor( - /** Topic name can be any string. */ - topic, params = { config: {} }, socket) { - var _a, _b; - this.topic = topic; - this.params = params; - this.socket = socket; - this.bindings = {}; - this.state = constants_1.CHANNEL_STATES.closed; - this.joinedOnce = false; - this.pushBuffer = []; - this.subTopic = topic.replace(/^realtime:/i, ''); - this.params.config = Object.assign({ - broadcast: { ack: false, self: false }, - presence: { key: '', enabled: false }, - private: false, - }, params.config); - this.timeout = this.socket.timeout; - this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); - this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); - this.joinPush.receive('ok', () => { - this.state = constants_1.CHANNEL_STATES.joined; - this.rejoinTimer.reset(); - this.pushBuffer.forEach((pushEvent) => pushEvent.send()); - this.pushBuffer = []; - }); - this._onClose(() => { - this.rejoinTimer.reset(); - this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); - this.state = constants_1.CHANNEL_STATES.closed; - this.socket._remove(this); - }); - this._onError((reason) => { - if (this._isLeaving() || this._isClosed()) { - return; - } - this.socket.log('channel', `error ${this.topic}`, reason); - this.state = constants_1.CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this.joinPush.receive('timeout', () => { - if (!this._isJoining()) { - return; - } - this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); - this.state = constants_1.CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this.joinPush.receive('error', (reason) => { - if (this._isLeaving() || this._isClosed()) { - return; - } - this.socket.log('channel', `error ${this.topic}`, reason); - this.state = constants_1.CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { - this._trigger(this._replyEventName(ref), payload); - }); - this.presence = new RealtimePresence_1.default(this); - this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint); - this.private = this.params.config.private || false; - if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { - throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; - } - } - /** Subscribe registers your client with the server */ - subscribe(callback, timeout = this.timeout) { - var _a, _b, _c; - if (!this.socket.isConnected()) { - this.socket.connect(); - } - if (this.state == constants_1.CHANNEL_STATES.closed) { - const { config: { broadcast, presence, private: isPrivate }, } = this.params; - const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []; - const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && - this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) || - ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; - const accessTokenPayload = {}; - const config = { - broadcast, - presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), - postgres_changes, - private: isPrivate, - }; - if (this.socket.accessTokenValue) { - accessTokenPayload.access_token = this.socket.accessTokenValue; - } - this._onError((e) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, e)); - this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CLOSED)); - this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); - this.joinedOnce = true; - this._rejoin(timeout); - this.joinPush - .receive('ok', async ({ postgres_changes }) => { - var _a; - this.socket.setAuth(); - if (postgres_changes === undefined) { - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); - return; - } - else { - const clientPostgresBindings = this.bindings.postgres_changes; - const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; - const newPostgresBindings = []; - for (let i = 0; i < bindingsLen; i++) { - const clientPostgresBinding = clientPostgresBindings[i]; - const { filter: { event, schema, table, filter }, } = clientPostgresBinding; - const serverPostgresFilter = postgres_changes && postgres_changes[i]; - if (serverPostgresFilter && - serverPostgresFilter.event === event && - serverPostgresFilter.schema === schema && - serverPostgresFilter.table === table && - serverPostgresFilter.filter === filter) { - newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); - } - else { - this.unsubscribe(); - this.state = constants_1.CHANNEL_STATES.errored; - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error('mismatch between server and client bindings for postgres changes')); - return; - } - } - this.bindings.postgres_changes = newPostgresBindings; - callback && callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); - return; - } - }) - .receive('error', (error) => { - this.state = constants_1.CHANNEL_STATES.errored; - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); - return; - }) - .receive('timeout', () => { - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.TIMED_OUT); - return; - }); - } - return this; - } - presenceState() { - return this.presence.state; - } - async track(payload, opts = {}) { - return await this.send({ - type: 'presence', - event: 'track', - payload, - }, opts.timeout || this.timeout); - } - async untrack(opts = {}) { - return await this.send({ - type: 'presence', - event: 'untrack', - }, opts); - } - on(type, filter, callback) { - if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) { - this.socket.log('channel', `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); - this.unsubscribe().then(() => this.subscribe()); - } - return this._on(type, filter, callback); - } - /** - * Sends a broadcast message explicitly via REST API. - * - * This method always uses the REST API endpoint regardless of WebSocket connection state. - * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. - * - * @param event The name of the broadcast event - * @param payload Payload to be sent (required) - * @param opts Options including timeout - * @returns Promise resolving to object with success status, and error details if failed - */ - async httpSend(event, payload, opts = {}) { - var _a; - const authorization = this.socket.accessTokenValue - ? `Bearer ${this.socket.accessTokenValue}` - : ''; - if (payload === undefined || payload === null) { - return Promise.reject('Payload is required for httpSend()'); - } - const options = { - method: 'POST', - headers: { - Authorization: authorization, - apikey: this.socket.apiKey ? this.socket.apiKey : '', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - messages: [ - { - topic: this.subTopic, - event, - payload: payload, - private: this.private, - }, - ], - }), - }; - const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); - if (response.status === 202) { - return { success: true }; - } - let errorMessage = response.statusText; - try { - const errorBody = await response.json(); - errorMessage = errorBody.error || errorBody.message || errorMessage; - } - catch (_b) { } - return Promise.reject(new Error(errorMessage)); - } - /** - * Sends a message into the channel. - * - * @param args Arguments to send to channel - * @param args.type The type of event to send - * @param args.event The name of the event being sent - * @param args.payload Payload to be sent - * @param opts Options to be used during the send process - */ - async send(args, opts = {}) { - var _a, _b; - if (!this._canPush() && args.type === 'broadcast') { - console.warn('Realtime send() is automatically falling back to REST API. ' + - 'This behavior will be deprecated in the future. ' + - 'Please use httpSend() explicitly for REST delivery.'); - const { event, payload: endpoint_payload } = args; - const authorization = this.socket.accessTokenValue - ? `Bearer ${this.socket.accessTokenValue}` - : ''; - const options = { - method: 'POST', - headers: { - Authorization: authorization, - apikey: this.socket.apiKey ? this.socket.apiKey : '', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - messages: [ - { - topic: this.subTopic, - event, - payload: endpoint_payload, - private: this.private, - }, - ], - }), - }; - try { - const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); - await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); - return response.ok ? 'ok' : 'error'; - } - catch (error) { - if (error.name === 'AbortError') { - return 'timed out'; - } - else { - return 'error'; - } - } - } - else { - return new Promise((resolve) => { - var _a, _b, _c; - const push = this._push(args.type, args, opts.timeout || this.timeout); - if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { - resolve('ok'); - } - push.receive('ok', () => resolve('ok')); - push.receive('error', () => resolve('error')); - push.receive('timeout', () => resolve('timed out')); - }); - } - } - updateJoinPayload(payload) { - this.joinPush.updatePayload(payload); - } - /** - * Leaves the channel. - * - * Unsubscribes from server events, and instructs channel to terminate on server. - * Triggers onClose() hooks. - * - * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: - * channel.unsubscribe().receive("ok", () => alert("left!") ) - */ - unsubscribe(timeout = this.timeout) { - this.state = constants_1.CHANNEL_STATES.leaving; - const onClose = () => { - this.socket.log('channel', `leave ${this.topic}`); - this._trigger(constants_1.CHANNEL_EVENTS.close, 'leave', this._joinRef()); - }; - this.joinPush.destroy(); - let leavePush = null; - return new Promise((resolve) => { - leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); - leavePush - .receive('ok', () => { - onClose(); - resolve('ok'); - }) - .receive('timeout', () => { - onClose(); - resolve('timed out'); - }) - .receive('error', () => { - resolve('error'); - }); - leavePush.send(); - if (!this._canPush()) { - leavePush.trigger('ok', {}); - } - }).finally(() => { - leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); - }); - } - /** - * Teardown the channel. - * - * Destroys and stops related timers. - */ - teardown() { - this.pushBuffer.forEach((push) => push.destroy()); - this.pushBuffer = []; - this.rejoinTimer.reset(); - this.joinPush.destroy(); - this.state = constants_1.CHANNEL_STATES.closed; - this.bindings = {}; - } - /** @internal */ - async _fetchWithTimeout(url, options, timeout) { - const controller = new AbortController(); - const id = setTimeout(() => controller.abort(), timeout); - const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); - clearTimeout(id); - return response; - } - /** @internal */ - _push(event, payload, timeout = this.timeout) { - if (!this.joinedOnce) { - throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; - } - let pushEvent = new push_1.default(this, event, payload, timeout); - if (this._canPush()) { - pushEvent.send(); - } - else { - this._addToPushBuffer(pushEvent); - } - return pushEvent; - } - /** @internal */ - _addToPushBuffer(pushEvent) { - pushEvent.startTimeout(); - this.pushBuffer.push(pushEvent); - // Enforce buffer size limit - if (this.pushBuffer.length > constants_1.MAX_PUSH_BUFFER_SIZE) { - const removedPush = this.pushBuffer.shift(); - if (removedPush) { - removedPush.destroy(); - this.socket.log('channel', `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); - } - } - } - /** - * Overridable message hook - * - * Receives all events for specialized message handling before dispatching to the channel callbacks. - * Must return the payload, modified or unmodified. - * - * @internal - */ - _onMessage(_event, payload, _ref) { - return payload; - } - /** @internal */ - _isMember(topic) { - return this.topic === topic; - } - /** @internal */ - _joinRef() { - return this.joinPush.ref; - } - /** @internal */ - _trigger(type, payload, ref) { - var _a, _b; - const typeLower = type.toLocaleLowerCase(); - const { close, error, leave, join } = constants_1.CHANNEL_EVENTS; - const events = [close, error, leave, join]; - if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { - return; - } - let handledPayload = this._onMessage(typeLower, payload, ref); - if (payload && !handledPayload) { - throw 'channel onMessage callbacks must return the payload, modified or unmodified'; - } - if (['insert', 'update', 'delete'].includes(typeLower)) { - (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { - var _a, _b, _c; - return ((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; - }).map((bind) => bind.callback(handledPayload, ref)); - } - else { - (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { - var _a, _b, _c, _d, _e, _f; - if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { - if ('id' in bind) { - const bindId = bind.id; - const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; - return (bindId && - ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && - (bindEvent === '*' || - (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); - } - else { - const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); - return bindEvent === '*' || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); - } - } - else { - return bind.type.toLocaleLowerCase() === typeLower; - } - }).map((bind) => { - if (typeof handledPayload === 'object' && 'ids' in handledPayload) { - const postgresChanges = handledPayload.data; - const { schema, table, commit_timestamp, type, errors } = postgresChanges; - const enrichedPayload = { - schema: schema, - table: table, - commit_timestamp: commit_timestamp, - eventType: type, - new: {}, - old: {}, - errors: errors, - }; - handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); - } - bind.callback(handledPayload, ref); - }); - } - } - /** @internal */ - _isClosed() { - return this.state === constants_1.CHANNEL_STATES.closed; - } - /** @internal */ - _isJoined() { - return this.state === constants_1.CHANNEL_STATES.joined; - } - /** @internal */ - _isJoining() { - return this.state === constants_1.CHANNEL_STATES.joining; - } - /** @internal */ - _isLeaving() { - return this.state === constants_1.CHANNEL_STATES.leaving; - } - /** @internal */ - _replyEventName(ref) { - return `chan_reply_${ref}`; - } - /** @internal */ - _on(type, filter, callback) { - const typeLower = type.toLocaleLowerCase(); - const binding = { - type: typeLower, - filter: filter, - callback: callback, - }; - if (this.bindings[typeLower]) { - this.bindings[typeLower].push(binding); - } - else { - this.bindings[typeLower] = [binding]; - } - return this; - } - /** @internal */ - _off(type, filter) { - const typeLower = type.toLocaleLowerCase(); - if (this.bindings[typeLower]) { - this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { - var _a; - return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && - RealtimeChannel.isEqual(bind.filter, filter)); - }); - } - return this; - } - /** @internal */ - static isEqual(obj1, obj2) { - if (Object.keys(obj1).length !== Object.keys(obj2).length) { - return false; - } - for (const k in obj1) { - if (obj1[k] !== obj2[k]) { - return false; - } - } - return true; - } - /** @internal */ - _rejoinUntilConnected() { - this.rejoinTimer.scheduleTimeout(); - if (this.socket.isConnected()) { - this._rejoin(); - } - } - /** - * Registers a callback that will be executed when the channel closes. - * - * @internal - */ - _onClose(callback) { - this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); - } - /** - * Registers a callback that will be executed when the channel encounteres an error. - * - * @internal - */ - _onError(callback) { - this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); - } - /** - * Returns `true` if the socket is connected and the channel has been joined. - * - * @internal - */ - _canPush() { - return this.socket.isConnected() && this._isJoined(); - } - /** @internal */ - _rejoin(timeout = this.timeout) { - if (this._isLeaving()) { - return; - } - this.socket._leaveOpenTopic(this.topic); - this.state = constants_1.CHANNEL_STATES.joining; - this.joinPush.resend(timeout); - } - /** @internal */ - _getPayloadRecords(payload) { - const records = { - new: {}, - old: {}, - }; - if (payload.type === 'INSERT' || payload.type === 'UPDATE') { - records.new = Transformers.convertChangeData(payload.columns, payload.record); - } - if (payload.type === 'UPDATE' || payload.type === 'DELETE') { - records.old = Transformers.convertChangeData(payload.columns, payload.old_record); - } - return records; - } -} -exports["default"] = RealtimeChannel; -//# sourceMappingURL=RealtimeChannel.js.map - -/***/ }), - -/***/ 9103: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(43478)); -const constants_1 = __nccwpck_require__(50088); -const serializer_1 = tslib_1.__importDefault(__nccwpck_require__(25360)); -const timer_1 = tslib_1.__importDefault(__nccwpck_require__(12983)); -const transformers_1 = __nccwpck_require__(1140); -const RealtimeChannel_1 = tslib_1.__importDefault(__nccwpck_require__(39911)); -const noop = () => { }; -// Connection-related constants -const CONNECTION_TIMEOUTS = { - HEARTBEAT_INTERVAL: 25000, - RECONNECT_DELAY: 10, - HEARTBEAT_TIMEOUT_FALLBACK: 100, -}; -const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000]; -const DEFAULT_RECONNECT_FALLBACK = 10000; -const WORKER_SCRIPT = ` - addEventListener("message", (e) => { - if (e.data.event === "start") { - setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); - } - });`; -class RealtimeClient { - /** - * Initializes the Socket. - * - * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) - * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) - * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation - * @param options.timeout The default timeout in milliseconds to trigger push timeouts. - * @param options.params The optional params to pass when connecting. - * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. - * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. - * @param options.heartbeatCallback The optional function to handle heartbeat status. - * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } - * @param options.logLevel Sets the log level for Realtime - * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) - * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. - * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. - * @param options.worker Use Web Worker to set a side flow. Defaults to false. - * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. - */ - constructor(endPoint, options) { - var _a; - this.accessTokenValue = null; - this.apiKey = null; - this.channels = new Array(); - this.endPoint = ''; - this.httpEndpoint = ''; - /** @deprecated headers cannot be set on websocket connections */ - this.headers = {}; - this.params = {}; - this.timeout = constants_1.DEFAULT_TIMEOUT; - this.transport = null; - this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; - this.heartbeatTimer = undefined; - this.pendingHeartbeatRef = null; - this.heartbeatCallback = noop; - this.ref = 0; - this.reconnectTimer = null; - this.logger = noop; - this.conn = null; - this.sendBuffer = []; - this.serializer = new serializer_1.default(); - this.stateChangeCallbacks = { - open: [], - close: [], - error: [], - message: [], - }; - this.accessToken = null; - this._connectionState = 'disconnected'; - this._wasManualDisconnect = false; - this._authPromise = null; - /** - * Use either custom fetch, if provided, or default fetch to make HTTP requests - * - * @internal - */ - this._resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - // Node.js environment without native fetch - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s))).then(({ default: fetch }) => fetch(...args)) - .catch((error) => { - throw new Error(`Failed to load @supabase/node-fetch: ${error.message}. ` + - `This is required for HTTP requests in Node.js environments without native fetch.`); - }); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); - }; - // Validate required parameters - if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) { - throw new Error('API key is required to connect to Realtime'); - } - this.apiKey = options.params.apikey; - // Initialize endpoint URLs - this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; - this.httpEndpoint = (0, transformers_1.httpEndpointURL)(endPoint); - this._initializeOptions(options); - this._setupReconnectionTimer(); - this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); - } - /** - * Connects the socket, unless already connected. - */ - connect() { - // Skip if already connecting, disconnecting, or connected - if (this.isConnecting() || - this.isDisconnecting() || - (this.conn !== null && this.isConnected())) { - return; - } - this._setConnectionState('connecting'); - this._setAuthSafely('connect'); - // Establish WebSocket connection - if (this.transport) { - // Use custom transport if provided - this.conn = new this.transport(this.endpointURL()); - } - else { - // Try to use native WebSocket - try { - this.conn = websocket_factory_1.default.createWebSocket(this.endpointURL()); - } - catch (error) { - this._setConnectionState('disconnected'); - const errorMessage = error.message; - // Provide helpful error message based on environment - if (errorMessage.includes('Node.js')) { - throw new Error(`${errorMessage}\n\n` + - 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' + - 'Option 1: Use Node.js 22+ which has native WebSocket support\n' + - 'Option 2: Install and provide the "ws" package:\n\n' + - ' npm install ws\n\n' + - ' import ws from "ws"\n' + - ' const client = new RealtimeClient(url, {\n' + - ' ...options,\n' + - ' transport: ws\n' + - ' })'); - } - throw new Error(`WebSocket not available: ${errorMessage}`); - } - } - this._setupConnectionHandlers(); - } - /** - * Returns the URL of the websocket. - * @returns string The URL of the websocket. - */ - endpointURL() { - return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: constants_1.VSN })); - } - /** - * Disconnects the socket. - * - * @param code A numeric status code to send on disconnect. - * @param reason A custom reason for the disconnect. - */ - disconnect(code, reason) { - if (this.isDisconnecting()) { - return; - } - this._setConnectionState('disconnecting', true); - if (this.conn) { - // Setup fallback timer to prevent hanging in disconnecting state - const fallbackTimer = setTimeout(() => { - this._setConnectionState('disconnected'); - }, 100); - this.conn.onclose = () => { - clearTimeout(fallbackTimer); - this._setConnectionState('disconnected'); - }; - // Close the WebSocket connection - if (code) { - this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); - } - else { - this.conn.close(); - } - this._teardownConnection(); - } - else { - this._setConnectionState('disconnected'); - } - } - /** - * Returns all created channels - */ - getChannels() { - return this.channels; - } - /** - * Unsubscribes and removes a single channel - * @param channel A RealtimeChannel instance - */ - async removeChannel(channel) { - const status = await channel.unsubscribe(); - if (this.channels.length === 0) { - this.disconnect(); - } - return status; - } - /** - * Unsubscribes and removes all channels - */ - async removeAllChannels() { - const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); - this.channels = []; - this.disconnect(); - return values_1; - } - /** - * Logs the message. - * - * For customized logging, `this.logger` can be overridden. - */ - log(kind, msg, data) { - this.logger(kind, msg, data); - } - /** - * Returns the current state of the socket. - */ - connectionState() { - switch (this.conn && this.conn.readyState) { - case constants_1.SOCKET_STATES.connecting: - return constants_1.CONNECTION_STATE.Connecting; - case constants_1.SOCKET_STATES.open: - return constants_1.CONNECTION_STATE.Open; - case constants_1.SOCKET_STATES.closing: - return constants_1.CONNECTION_STATE.Closing; - default: - return constants_1.CONNECTION_STATE.Closed; - } - } - /** - * Returns `true` is the connection is open. - */ - isConnected() { - return this.connectionState() === constants_1.CONNECTION_STATE.Open; - } - /** - * Returns `true` if the connection is currently connecting. - */ - isConnecting() { - return this._connectionState === 'connecting'; - } - /** - * Returns `true` if the connection is currently disconnecting. - */ - isDisconnecting() { - return this._connectionState === 'disconnecting'; - } - channel(topic, params = { config: {} }) { - const realtimeTopic = `realtime:${topic}`; - const exists = this.getChannels().find((c) => c.topic === realtimeTopic); - if (!exists) { - const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); - this.channels.push(chan); - return chan; - } - else { - return exists; - } - } - /** - * Push out a message if the socket is connected. - * - * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. - */ - push(data) { - const { topic, event, payload, ref } = data; - const callback = () => { - this.encode(data, (result) => { - var _a; - (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); - }); - }; - this.log('push', `${topic} ${event} (${ref})`, payload); - if (this.isConnected()) { - callback(); - } - else { - this.sendBuffer.push(callback); - } - } - /** - * Sets the JWT access token used for channel subscription authorization and Realtime RLS. - * - * If param is null it will use the `accessToken` callback function or the token set on the client. - * - * On callback used, it will set the value of the token internal to the client. - * - * @param token A JWT string to override the token set on the client. - */ - async setAuth(token = null) { - this._authPromise = this._performAuth(token); - try { - await this._authPromise; - } - finally { - this._authPromise = null; - } - } - /** - * Sends a heartbeat message if the socket is connected. - */ - async sendHeartbeat() { - var _a; - if (!this.isConnected()) { - try { - this.heartbeatCallback('disconnected'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - return; - } - // Handle heartbeat timeout and force reconnection if needed - if (this.pendingHeartbeatRef) { - this.pendingHeartbeatRef = null; - this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); - try { - this.heartbeatCallback('timeout'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - // Force reconnection after heartbeat timeout - this._wasManualDisconnect = false; - (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, 'heartbeat timeout'); - setTimeout(() => { - var _a; - if (!this.isConnected()) { - (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); - } - }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); - return; - } - // Send heartbeat message to server - this.pendingHeartbeatRef = this._makeRef(); - this.push({ - topic: 'phoenix', - event: 'heartbeat', - payload: {}, - ref: this.pendingHeartbeatRef, - }); - try { - this.heartbeatCallback('sent'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - this._setAuthSafely('heartbeat'); - } - onHeartbeat(callback) { - this.heartbeatCallback = callback; - } - /** - * Flushes send buffer - */ - flushSendBuffer() { - if (this.isConnected() && this.sendBuffer.length > 0) { - this.sendBuffer.forEach((callback) => callback()); - this.sendBuffer = []; - } - } - /** - * Return the next message ref, accounting for overflows - * - * @internal - */ - _makeRef() { - let newRef = this.ref + 1; - if (newRef === this.ref) { - this.ref = 0; - } - else { - this.ref = newRef; - } - return this.ref.toString(); - } - /** - * Unsubscribe from channels with the specified topic. - * - * @internal - */ - _leaveOpenTopic(topic) { - let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); - if (dupChannel) { - this.log('transport', `leaving duplicate topic "${topic}"`); - dupChannel.unsubscribe(); - } - } - /** - * Removes a subscription from the socket. - * - * @param channel An open subscription. - * - * @internal - */ - _remove(channel) { - this.channels = this.channels.filter((c) => c.topic !== channel.topic); - } - /** @internal */ - _onConnMessage(rawMessage) { - this.decode(rawMessage.data, (msg) => { - // Handle heartbeat responses - if (msg.topic === 'phoenix' && msg.event === 'phx_reply') { - try { - this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - } - // Handle pending heartbeat reference cleanup - if (msg.ref && msg.ref === this.pendingHeartbeatRef) { - this.pendingHeartbeatRef = null; - } - // Log incoming message - const { topic, event, payload, ref } = msg; - const refString = ref ? `(${ref})` : ''; - const status = payload.status || ''; - this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload); - // Route message to appropriate channels - this.channels - .filter((channel) => channel._isMember(topic)) - .forEach((channel) => channel._trigger(event, payload, ref)); - this._triggerStateCallbacks('message', msg); - }); - } - /** - * Clear specific timer - * @internal - */ - _clearTimer(timer) { - var _a; - if (timer === 'heartbeat' && this.heartbeatTimer) { - clearInterval(this.heartbeatTimer); - this.heartbeatTimer = undefined; - } - else if (timer === 'reconnect') { - (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset(); - } - } - /** - * Clear all timers - * @internal - */ - _clearAllTimers() { - this._clearTimer('heartbeat'); - this._clearTimer('reconnect'); - } - /** - * Setup connection handlers for WebSocket events - * @internal - */ - _setupConnectionHandlers() { - if (!this.conn) - return; - // Set binary type if supported (browsers and most WebSocket implementations) - if ('binaryType' in this.conn) { - ; - this.conn.binaryType = 'arraybuffer'; - } - this.conn.onopen = () => this._onConnOpen(); - this.conn.onerror = (error) => this._onConnError(error); - this.conn.onmessage = (event) => this._onConnMessage(event); - this.conn.onclose = (event) => this._onConnClose(event); - } - /** - * Teardown connection and cleanup resources - * @internal - */ - _teardownConnection() { - if (this.conn) { - this.conn.onopen = null; - this.conn.onerror = null; - this.conn.onmessage = null; - this.conn.onclose = null; - this.conn = null; - } - this._clearAllTimers(); - this.channels.forEach((channel) => channel.teardown()); - } - /** @internal */ - _onConnOpen() { - this._setConnectionState('connected'); - this.log('transport', `connected to ${this.endpointURL()}`); - this.flushSendBuffer(); - this._clearTimer('reconnect'); - if (!this.worker) { - this._startHeartbeat(); - } - else { - if (!this.workerRef) { - this._startWorkerHeartbeat(); - } - } - this._triggerStateCallbacks('open'); - } - /** @internal */ - _startHeartbeat() { - this.heartbeatTimer && clearInterval(this.heartbeatTimer); - this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); - } - /** @internal */ - _startWorkerHeartbeat() { - if (this.workerUrl) { - this.log('worker', `starting worker for from ${this.workerUrl}`); - } - else { - this.log('worker', `starting default worker`); - } - const objectUrl = this._workerObjectUrl(this.workerUrl); - this.workerRef = new Worker(objectUrl); - this.workerRef.onerror = (error) => { - this.log('worker', 'worker error', error.message); - this.workerRef.terminate(); - }; - this.workerRef.onmessage = (event) => { - if (event.data.event === 'keepAlive') { - this.sendHeartbeat(); - } - }; - this.workerRef.postMessage({ - event: 'start', - interval: this.heartbeatIntervalMs, - }); - } - /** @internal */ - _onConnClose(event) { - var _a; - this._setConnectionState('disconnected'); - this.log('transport', 'close', event); - this._triggerChanError(); - this._clearTimer('heartbeat'); - // Only schedule reconnection if it wasn't a manual disconnect - if (!this._wasManualDisconnect) { - (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); - } - this._triggerStateCallbacks('close', event); - } - /** @internal */ - _onConnError(error) { - this._setConnectionState('disconnected'); - this.log('transport', `${error}`); - this._triggerChanError(); - this._triggerStateCallbacks('error', error); - } - /** @internal */ - _triggerChanError() { - this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); - } - /** @internal */ - _appendParams(url, params) { - if (Object.keys(params).length === 0) { - return url; - } - const prefix = url.match(/\?/) ? '&' : '?'; - const query = new URLSearchParams(params); - return `${url}${prefix}${query}`; - } - _workerObjectUrl(url) { - let result_url; - if (url) { - result_url = url; - } - else { - const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' }); - result_url = URL.createObjectURL(blob); - } - return result_url; - } - /** - * Set connection state with proper state management - * @internal - */ - _setConnectionState(state, manual = false) { - this._connectionState = state; - if (state === 'connecting') { - this._wasManualDisconnect = false; - } - else if (state === 'disconnecting') { - this._wasManualDisconnect = manual; - } - } - /** - * Perform the actual auth operation - * @internal - */ - async _performAuth(token = null) { - let tokenToSend; - if (token) { - tokenToSend = token; - } - else if (this.accessToken) { - // Always call the accessToken callback to get fresh token - tokenToSend = await this.accessToken(); - } - else { - tokenToSend = this.accessTokenValue; - } - if (this.accessTokenValue != tokenToSend) { - this.accessTokenValue = tokenToSend; - this.channels.forEach((channel) => { - const payload = { - access_token: tokenToSend, - version: constants_1.DEFAULT_VERSION, - }; - tokenToSend && channel.updateJoinPayload(payload); - if (channel.joinedOnce && channel._isJoined()) { - channel._push(constants_1.CHANNEL_EVENTS.access_token, { - access_token: tokenToSend, - }); - } - }); - } - } - /** - * Wait for any in-flight auth operations to complete - * @internal - */ - async _waitForAuthIfNeeded() { - if (this._authPromise) { - await this._authPromise; - } - } - /** - * Safely call setAuth with standardized error handling - * @internal - */ - _setAuthSafely(context = 'general') { - this.setAuth().catch((e) => { - this.log('error', `error setting auth in ${context}`, e); - }); - } - /** - * Trigger state change callbacks with proper error handling - * @internal - */ - _triggerStateCallbacks(event, data) { - try { - this.stateChangeCallbacks[event].forEach((callback) => { - try { - callback(data); - } - catch (e) { - this.log('error', `error in ${event} callback`, e); - } - }); - } - catch (e) { - this.log('error', `error triggering ${event} callbacks`, e); - } - } - /** - * Setup reconnection timer with proper configuration - * @internal - */ - _setupReconnectionTimer() { - this.reconnectTimer = new timer_1.default(async () => { - setTimeout(async () => { - await this._waitForAuthIfNeeded(); - if (!this.isConnected()) { - this.connect(); - } - }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); - }, this.reconnectAfterMs); - } - /** - * Initialize client options with defaults - * @internal - */ - _initializeOptions(options) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j; - // Set defaults - this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null; - this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT; - this.heartbeatIntervalMs = - (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; - this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; - this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null; - this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; - // Handle special cases - if (options === null || options === void 0 ? void 0 : options.params) - this.params = options.params; - if (options === null || options === void 0 ? void 0 : options.logger) - this.logger = options.logger; - if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { - this.logLevel = options.logLevel || options.log_level; - this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); - } - // Set up functions with defaults - this.reconnectAfterMs = - (_g = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _g !== void 0 ? _g : ((tries) => { - return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; - }); - this.encode = - (_h = options === null || options === void 0 ? void 0 : options.encode) !== null && _h !== void 0 ? _h : ((payload, callback) => { - return callback(JSON.stringify(payload)); - }); - this.decode = (_j = options === null || options === void 0 ? void 0 : options.decode) !== null && _j !== void 0 ? _j : this.serializer.decode.bind(this.serializer); - // Handle worker setup - if (this.worker) { - if (typeof window !== 'undefined' && !window.Worker) { - throw new Error('Web Worker is not supported'); - } - this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; - } - } -} -exports["default"] = RealtimeClient; -//# sourceMappingURL=RealtimeClient.js.map - -/***/ }), - -/***/ 75583: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js - License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; -var REALTIME_PRESENCE_LISTEN_EVENTS; -(function (REALTIME_PRESENCE_LISTEN_EVENTS) { - REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; - REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; - REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; -})(REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS = {})); -class RealtimePresence { - /** - * Initializes the Presence. - * - * @param channel - The RealtimeChannel - * @param opts - The options, - * for example `{events: {state: 'state', diff: 'diff'}}` - */ - constructor(channel, opts) { - this.channel = channel; - this.state = {}; - this.pendingDiffs = []; - this.joinRef = null; - this.enabled = false; - this.caller = { - onJoin: () => { }, - onLeave: () => { }, - onSync: () => { }, - }; - const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { - state: 'presence_state', - diff: 'presence_diff', - }; - this.channel._on(events.state, {}, (newState) => { - const { onJoin, onLeave, onSync } = this.caller; - this.joinRef = this.channel._joinRef(); - this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); - this.pendingDiffs.forEach((diff) => { - this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); - }); - this.pendingDiffs = []; - onSync(); - }); - this.channel._on(events.diff, {}, (diff) => { - const { onJoin, onLeave, onSync } = this.caller; - if (this.inPendingSyncState()) { - this.pendingDiffs.push(diff); - } - else { - this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); - onSync(); - } - }); - this.onJoin((key, currentPresences, newPresences) => { - this.channel._trigger('presence', { - event: 'join', - key, - currentPresences, - newPresences, - }); - }); - this.onLeave((key, currentPresences, leftPresences) => { - this.channel._trigger('presence', { - event: 'leave', - key, - currentPresences, - leftPresences, - }); - }); - this.onSync(() => { - this.channel._trigger('presence', { event: 'sync' }); - }); - } - /** - * Used to sync the list of presences on the server with the - * client's state. - * - * An optional `onJoin` and `onLeave` callback can be provided to - * react to changes in the client's local presences across - * disconnects and reconnects with the server. - * - * @internal - */ - static syncState(currentState, newState, onJoin, onLeave) { - const state = this.cloneDeep(currentState); - const transformedState = this.transformState(newState); - const joins = {}; - const leaves = {}; - this.map(state, (key, presences) => { - if (!transformedState[key]) { - leaves[key] = presences; - } - }); - this.map(transformedState, (key, newPresences) => { - const currentPresences = state[key]; - if (currentPresences) { - const newPresenceRefs = newPresences.map((m) => m.presence_ref); - const curPresenceRefs = currentPresences.map((m) => m.presence_ref); - const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); - const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); - if (joinedPresences.length > 0) { - joins[key] = joinedPresences; - } - if (leftPresences.length > 0) { - leaves[key] = leftPresences; - } - } - else { - joins[key] = newPresences; - } - }); - return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); - } - /** - * Used to sync a diff of presence join and leave events from the - * server, as they happen. - * - * Like `syncState`, `syncDiff` accepts optional `onJoin` and - * `onLeave` callbacks to react to a user joining or leaving from a - * device. - * - * @internal - */ - static syncDiff(state, diff, onJoin, onLeave) { - const { joins, leaves } = { - joins: this.transformState(diff.joins), - leaves: this.transformState(diff.leaves), - }; - if (!onJoin) { - onJoin = () => { }; - } - if (!onLeave) { - onLeave = () => { }; - } - this.map(joins, (key, newPresences) => { - var _a; - const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; - state[key] = this.cloneDeep(newPresences); - if (currentPresences.length > 0) { - const joinedPresenceRefs = state[key].map((m) => m.presence_ref); - const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); - state[key].unshift(...curPresences); - } - onJoin(key, currentPresences, newPresences); - }); - this.map(leaves, (key, leftPresences) => { - let currentPresences = state[key]; - if (!currentPresences) - return; - const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); - currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); - state[key] = currentPresences; - onLeave(key, currentPresences, leftPresences); - if (currentPresences.length === 0) - delete state[key]; - }); - return state; - } - /** @internal */ - static map(obj, func) { - return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); - } - /** - * Remove 'metas' key - * Change 'phx_ref' to 'presence_ref' - * Remove 'phx_ref' and 'phx_ref_prev' - * - * @example - * // returns { - * abc123: [ - * { presence_ref: '2', user_id: 1 }, - * { presence_ref: '3', user_id: 2 } - * ] - * } - * RealtimePresence.transformState({ - * abc123: { - * metas: [ - * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, - * { phx_ref: '3', user_id: 2 } - * ] - * } - * }) - * - * @internal - */ - static transformState(state) { - state = this.cloneDeep(state); - return Object.getOwnPropertyNames(state).reduce((newState, key) => { - const presences = state[key]; - if ('metas' in presences) { - newState[key] = presences.metas.map((presence) => { - presence['presence_ref'] = presence['phx_ref']; - delete presence['phx_ref']; - delete presence['phx_ref_prev']; - return presence; - }); - } - else { - newState[key] = presences; - } - return newState; - }, {}); - } - /** @internal */ - static cloneDeep(obj) { - return JSON.parse(JSON.stringify(obj)); - } - /** @internal */ - onJoin(callback) { - this.caller.onJoin = callback; - } - /** @internal */ - onLeave(callback) { - this.caller.onLeave = callback; - } - /** @internal */ - onSync(callback) { - this.caller.onSync = callback; - } - /** @internal */ - inPendingSyncState() { - return !this.joinRef || this.joinRef !== this.channel._joinRef(); - } -} -exports["default"] = RealtimePresence; -//# sourceMappingURL=RealtimePresence.js.map - -/***/ }), - -/***/ 60442: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; -const tslib_1 = __nccwpck_require__(4351); -const RealtimeClient_1 = tslib_1.__importDefault(__nccwpck_require__(9103)); -exports.RealtimeClient = RealtimeClient_1.default; -const RealtimeChannel_1 = tslib_1.__importStar(__nccwpck_require__(39911)); -exports.RealtimeChannel = RealtimeChannel_1.default; -Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_LISTEN_TYPES; } })); -Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } })); -Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; } })); -Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_CHANNEL_STATES; } })); -const RealtimePresence_1 = tslib_1.__importStar(__nccwpck_require__(75583)); -exports.RealtimePresence = RealtimePresence_1.default; -Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", ({ enumerable: true, get: function () { return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; } })); -const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(43478)); -exports.WebSocketFactory = websocket_factory_1.default; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 50088: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.VSN = exports.DEFAULT_VERSION = void 0; -const version_1 = __nccwpck_require__(50318); -exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`; -exports.VSN = '1.0.0'; -exports.VERSION = version_1.version; -exports.DEFAULT_TIMEOUT = 10000; -exports.WS_CLOSE_NORMAL = 1000; -exports.MAX_PUSH_BUFFER_SIZE = 100; -var SOCKET_STATES; -(function (SOCKET_STATES) { - SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; - SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; - SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; - SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; -})(SOCKET_STATES || (exports.SOCKET_STATES = SOCKET_STATES = {})); -var CHANNEL_STATES; -(function (CHANNEL_STATES) { - CHANNEL_STATES["closed"] = "closed"; - CHANNEL_STATES["errored"] = "errored"; - CHANNEL_STATES["joined"] = "joined"; - CHANNEL_STATES["joining"] = "joining"; - CHANNEL_STATES["leaving"] = "leaving"; -})(CHANNEL_STATES || (exports.CHANNEL_STATES = CHANNEL_STATES = {})); -var CHANNEL_EVENTS; -(function (CHANNEL_EVENTS) { - CHANNEL_EVENTS["close"] = "phx_close"; - CHANNEL_EVENTS["error"] = "phx_error"; - CHANNEL_EVENTS["join"] = "phx_join"; - CHANNEL_EVENTS["reply"] = "phx_reply"; - CHANNEL_EVENTS["leave"] = "phx_leave"; - CHANNEL_EVENTS["access_token"] = "access_token"; -})(CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = CHANNEL_EVENTS = {})); -var TRANSPORTS; -(function (TRANSPORTS) { - TRANSPORTS["websocket"] = "websocket"; -})(TRANSPORTS || (exports.TRANSPORTS = TRANSPORTS = {})); -var CONNECTION_STATE; -(function (CONNECTION_STATE) { - CONNECTION_STATE["Connecting"] = "connecting"; - CONNECTION_STATE["Open"] = "open"; - CONNECTION_STATE["Closing"] = "closing"; - CONNECTION_STATE["Closed"] = "closed"; -})(CONNECTION_STATE || (exports.CONNECTION_STATE = CONNECTION_STATE = {})); -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 82292: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const constants_1 = __nccwpck_require__(50088); -class Push { - /** - * Initializes the Push - * - * @param channel The Channel - * @param event The event, for example `"phx_join"` - * @param payload The payload, for example `{user_id: 123}` - * @param timeout The push timeout in milliseconds - */ - constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { - this.channel = channel; - this.event = event; - this.payload = payload; - this.timeout = timeout; - this.sent = false; - this.timeoutTimer = undefined; - this.ref = ''; - this.receivedResp = null; - this.recHooks = []; - this.refEvent = null; - } - resend(timeout) { - this.timeout = timeout; - this._cancelRefEvent(); - this.ref = ''; - this.refEvent = null; - this.receivedResp = null; - this.sent = false; - this.send(); - } - send() { - if (this._hasReceived('timeout')) { - return; - } - this.startTimeout(); - this.sent = true; - this.channel.socket.push({ - topic: this.channel.topic, - event: this.event, - payload: this.payload, - ref: this.ref, - join_ref: this.channel._joinRef(), - }); - } - updatePayload(payload) { - this.payload = Object.assign(Object.assign({}, this.payload), payload); - } - receive(status, callback) { - var _a; - if (this._hasReceived(status)) { - callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); - } - this.recHooks.push({ status, callback }); - return this; - } - startTimeout() { - if (this.timeoutTimer) { - return; - } - this.ref = this.channel.socket._makeRef(); - this.refEvent = this.channel._replyEventName(this.ref); - const callback = (payload) => { - this._cancelRefEvent(); - this._cancelTimeout(); - this.receivedResp = payload; - this._matchReceive(payload); - }; - this.channel._on(this.refEvent, {}, callback); - this.timeoutTimer = setTimeout(() => { - this.trigger('timeout', {}); - }, this.timeout); - } - trigger(status, response) { - if (this.refEvent) - this.channel._trigger(this.refEvent, { status, response }); - } - destroy() { - this._cancelRefEvent(); - this._cancelTimeout(); - } - _cancelRefEvent() { - if (!this.refEvent) { - return; - } - this.channel._off(this.refEvent, {}); - } - _cancelTimeout() { - clearTimeout(this.timeoutTimer); - this.timeoutTimer = undefined; - } - _matchReceive({ status, response }) { - this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)); - } - _hasReceived(status) { - return this.receivedResp && this.receivedResp.status === status; - } -} -exports["default"] = Push; -//# sourceMappingURL=push.js.map - -/***/ }), - -/***/ 25360: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe -// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md -Object.defineProperty(exports, "__esModule", ({ value: true })); -class Serializer { - constructor() { - this.HEADER_LENGTH = 1; - } - decode(rawPayload, callback) { - if (rawPayload.constructor === ArrayBuffer) { - return callback(this._binaryDecode(rawPayload)); - } - if (typeof rawPayload === 'string') { - return callback(JSON.parse(rawPayload)); - } - return callback({}); - } - _binaryDecode(buffer) { - const view = new DataView(buffer); - const decoder = new TextDecoder(); - return this._decodeBroadcast(buffer, view, decoder); - } - _decodeBroadcast(buffer, view, decoder) { - const topicSize = view.getUint8(1); - const eventSize = view.getUint8(2); - let offset = this.HEADER_LENGTH + 2; - const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); - offset = offset + topicSize; - const event = decoder.decode(buffer.slice(offset, offset + eventSize)); - offset = offset + eventSize; - const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength))); - return { ref: null, topic: topic, event: event, payload: data }; - } -} -exports["default"] = Serializer; -//# sourceMappingURL=serializer.js.map - -/***/ }), - -/***/ 12983: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. - * - * @example - * let reconnectTimer = new Timer(() => this.connect(), function(tries){ - * return [1000, 5000, 10000][tries - 1] || 10000 - * }) - * reconnectTimer.scheduleTimeout() // fires after 1000 - * reconnectTimer.scheduleTimeout() // fires after 5000 - * reconnectTimer.reset() - * reconnectTimer.scheduleTimeout() // fires after 1000 - */ -class Timer { - constructor(callback, timerCalc) { - this.callback = callback; - this.timerCalc = timerCalc; - this.timer = undefined; - this.tries = 0; - this.callback = callback; - this.timerCalc = timerCalc; - } - reset() { - this.tries = 0; - clearTimeout(this.timer); - this.timer = undefined; - } - // Cancels any previous scheduleTimeout and schedules callback - scheduleTimeout() { - clearTimeout(this.timer); - this.timer = setTimeout(() => { - this.tries = this.tries + 1; - this.callback(); - }, this.timerCalc(this.tries + 1)); - } -} -exports["default"] = Timer; -//# sourceMappingURL=timer.js.map - -/***/ }), - -/***/ 1140: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/** - * Helpers to convert the change Payload into native JS types. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.httpEndpointURL = exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; -// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under -// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE -var PostgresTypes; -(function (PostgresTypes) { - PostgresTypes["abstime"] = "abstime"; - PostgresTypes["bool"] = "bool"; - PostgresTypes["date"] = "date"; - PostgresTypes["daterange"] = "daterange"; - PostgresTypes["float4"] = "float4"; - PostgresTypes["float8"] = "float8"; - PostgresTypes["int2"] = "int2"; - PostgresTypes["int4"] = "int4"; - PostgresTypes["int4range"] = "int4range"; - PostgresTypes["int8"] = "int8"; - PostgresTypes["int8range"] = "int8range"; - PostgresTypes["json"] = "json"; - PostgresTypes["jsonb"] = "jsonb"; - PostgresTypes["money"] = "money"; - PostgresTypes["numeric"] = "numeric"; - PostgresTypes["oid"] = "oid"; - PostgresTypes["reltime"] = "reltime"; - PostgresTypes["text"] = "text"; - PostgresTypes["time"] = "time"; - PostgresTypes["timestamp"] = "timestamp"; - PostgresTypes["timestamptz"] = "timestamptz"; - PostgresTypes["timetz"] = "timetz"; - PostgresTypes["tsrange"] = "tsrange"; - PostgresTypes["tstzrange"] = "tstzrange"; -})(PostgresTypes || (exports.PostgresTypes = PostgresTypes = {})); -/** - * Takes an array of columns and an object of string values then converts each string value - * to its mapped type. - * - * @param {{name: String, type: String}[]} columns - * @param {Object} record - * @param {Object} options The map of various options that can be applied to the mapper - * @param {Array} options.skipTypes The array of types that should not be converted - * - * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) - * //=>{ first_name: 'Paul', age: 33 } - */ -const convertChangeData = (columns, record, options = {}) => { - var _a; - const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; - if (!record) { - return {}; - } - return Object.keys(record).reduce((acc, rec_key) => { - acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); - return acc; - }, {}); -}; -exports.convertChangeData = convertChangeData; -/** - * Converts the value of an individual column. - * - * @param {String} columnName The column that you want to convert - * @param {{name: String, type: String}[]} columns All of the columns - * @param {Object} record The map of string values - * @param {Array} skipTypes An array of types that should not be converted - * @return {object} Useless information - * - * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) - * //=> 33 - * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) - * //=> "33" - */ -const convertColumn = (columnName, columns, record, skipTypes) => { - const column = columns.find((x) => x.name === columnName); - const colType = column === null || column === void 0 ? void 0 : column.type; - const value = record[columnName]; - if (colType && !skipTypes.includes(colType)) { - return (0, exports.convertCell)(colType, value); - } - return noop(value); -}; -exports.convertColumn = convertColumn; -/** - * If the value of the cell is `null`, returns null. - * Otherwise converts the string value to the correct type. - * @param {String} type A postgres column type - * @param {String} value The cell value - * - * @example convertCell('bool', 't') - * //=> true - * @example convertCell('int8', '10') - * //=> 10 - * @example convertCell('_int4', '{1,2,3,4}') - * //=> [1,2,3,4] - */ -const convertCell = (type, value) => { - // if data type is an array - if (type.charAt(0) === '_') { - const dataType = type.slice(1, type.length); - return (0, exports.toArray)(value, dataType); - } - // If not null, convert to correct type. - switch (type) { - case PostgresTypes.bool: - return (0, exports.toBoolean)(value); - case PostgresTypes.float4: - case PostgresTypes.float8: - case PostgresTypes.int2: - case PostgresTypes.int4: - case PostgresTypes.int8: - case PostgresTypes.numeric: - case PostgresTypes.oid: - return (0, exports.toNumber)(value); - case PostgresTypes.json: - case PostgresTypes.jsonb: - return (0, exports.toJson)(value); - case PostgresTypes.timestamp: - return (0, exports.toTimestampString)(value); // Format to be consistent with PostgREST - case PostgresTypes.abstime: // To allow users to cast it based on Timezone - case PostgresTypes.date: // To allow users to cast it based on Timezone - case PostgresTypes.daterange: - case PostgresTypes.int4range: - case PostgresTypes.int8range: - case PostgresTypes.money: - case PostgresTypes.reltime: // To allow users to cast it based on Timezone - case PostgresTypes.text: - case PostgresTypes.time: // To allow users to cast it based on Timezone - case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone - case PostgresTypes.timetz: // To allow users to cast it based on Timezone - case PostgresTypes.tsrange: - case PostgresTypes.tstzrange: - return noop(value); - default: - // Return the value for remaining types - return noop(value); - } -}; -exports.convertCell = convertCell; -const noop = (value) => { - return value; -}; -const toBoolean = (value) => { - switch (value) { - case 't': - return true; - case 'f': - return false; - default: - return value; - } -}; -exports.toBoolean = toBoolean; -const toNumber = (value) => { - if (typeof value === 'string') { - const parsedValue = parseFloat(value); - if (!Number.isNaN(parsedValue)) { - return parsedValue; - } - } - return value; -}; -exports.toNumber = toNumber; -const toJson = (value) => { - if (typeof value === 'string') { - try { - return JSON.parse(value); - } - catch (error) { - console.log(`JSON parse error: ${error}`); - return value; - } - } - return value; -}; -exports.toJson = toJson; -/** - * Converts a Postgres Array into a native JS array - * - * @example toArray('{}', 'int4') - * //=> [] - * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') - * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] - * @example toArray([1,2,3,4], 'int4') - * //=> [1,2,3,4] - */ -const toArray = (value, type) => { - if (typeof value !== 'string') { - return value; - } - const lastIdx = value.length - 1; - const closeBrace = value[lastIdx]; - const openBrace = value[0]; - // Confirm value is a Postgres array by checking curly brackets - if (openBrace === '{' && closeBrace === '}') { - let arr; - const valTrim = value.slice(1, lastIdx); - // TODO: find a better solution to separate Postgres array data - try { - arr = JSON.parse('[' + valTrim + ']'); - } - catch (_) { - // WARNING: splitting on comma does not cover all edge cases - arr = valTrim ? valTrim.split(',') : []; - } - return arr.map((val) => (0, exports.convertCell)(type, val)); - } - return value; -}; -exports.toArray = toArray; -/** - * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' - * See https://github.com/supabase/supabase/issues/18 - * - * @example toTimestampString('2019-09-10 00:00:00') - * //=> '2019-09-10T00:00:00' - */ -const toTimestampString = (value) => { - if (typeof value === 'string') { - return value.replace(' ', 'T'); - } - return value; -}; -exports.toTimestampString = toTimestampString; -const httpEndpointURL = (socketUrl) => { - const wsUrl = new URL(socketUrl); - wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http'); - wsUrl.pathname = wsUrl.pathname - .replace(/\/+$/, '') // remove all trailing slashes - .replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path - .replace(/\/socket$/i, '') // remove the socket path - .replace(/\/websocket$/i, ''); // remove the websocket path - if (wsUrl.pathname === '' || wsUrl.pathname === '/') { - wsUrl.pathname = '/api/broadcast'; - } - else { - wsUrl.pathname = wsUrl.pathname + '/api/broadcast'; - } - return wsUrl.href; -}; -exports.httpEndpointURL = httpEndpointURL; -//# sourceMappingURL=transformers.js.map - -/***/ }), - -/***/ 50318: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 43478: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebSocketFactory = void 0; -class WebSocketFactory { - static detectEnvironment() { - var _a; - if (typeof WebSocket !== 'undefined') { - return { type: 'native', constructor: WebSocket }; - } - if (typeof globalThis !== 'undefined' && typeof globalThis.WebSocket !== 'undefined') { - return { type: 'native', constructor: globalThis.WebSocket }; - } - if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') { - return { type: 'native', constructor: global.WebSocket }; - } - if (typeof globalThis !== 'undefined' && - typeof globalThis.WebSocketPair !== 'undefined' && - typeof globalThis.WebSocket === 'undefined') { - return { - type: 'cloudflare', - error: 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.', - workaround: 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.', - }; - } - if ((typeof globalThis !== 'undefined' && globalThis.EdgeRuntime) || - (typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) { - return { - type: 'unsupported', - error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.', - workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.', - }; - } - if (typeof process !== 'undefined') { - // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings - const processVersions = process['versions']; - if (processVersions && processVersions['node']) { - // Remove 'v' prefix if present and parse the major version - const versionString = processVersions['node']; - const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]); - // Node.js 22+ should have native WebSocket - if (nodeVersion >= 22) { - // Check if native WebSocket is available (should be in Node.js 22+) - if (typeof globalThis.WebSocket !== 'undefined') { - return { type: 'native', constructor: globalThis.WebSocket }; - } - // If not available, user needs to provide it - return { - type: 'unsupported', - error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, - workaround: 'Provide a WebSocket implementation via the transport option.', - }; - } - // Node.js < 22 doesn't have native WebSocket - return { - type: 'unsupported', - error: `Node.js ${nodeVersion} detected without native WebSocket support.`, - workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' + - 'import ws from "ws"\n' + - 'new RealtimeClient(url, { transport: ws })', - }; - } - } - return { - type: 'unsupported', - error: 'Unknown JavaScript runtime without WebSocket support.', - workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.", - }; - } - static getWebSocketConstructor() { - const env = this.detectEnvironment(); - if (env.constructor) { - return env.constructor; - } - let errorMessage = env.error || 'WebSocket not supported in this environment.'; - if (env.workaround) { - errorMessage += `\n\nSuggested solution: ${env.workaround}`; - } - throw new Error(errorMessage); - } - static createWebSocket(url, protocols) { - const WS = this.getWebSocketConstructor(); - return new WS(url, protocols); - } - static isWebSocketSupported() { - try { - const env = this.detectEnvironment(); - return env.type === 'native' || env.type === 'ws'; - } - catch (_a) { - return false; - } - } -} -exports.WebSocketFactory = WebSocketFactory; -exports["default"] = WebSocketFactory; -//# sourceMappingURL=websocket-factory.js.map - -/***/ }), - -/***/ 44249: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -const StorageFileApi_1 = tslib_1.__importDefault(__nccwpck_require__(80710)); -const StorageBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(33528)); -const StorageAnalyticsApi_1 = tslib_1.__importDefault(__nccwpck_require__(27339)); -const vectors_1 = __nccwpck_require__(99380); -class StorageClient extends StorageBucketApi_1.default { - constructor(url, headers = {}, fetch, opts) { - super(url, headers, fetch, opts); - } - /** - * Perform file operation in a bucket. - * - * @param id The bucket id to operate on. - */ - from(id) { - return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch); - } - /** - * Access vector storage operations. - * - * @returns A StorageVectorsClient instance configured with the current storage settings. - */ - get vectors() { - return new vectors_1.StorageVectorsClient(this.url + '/vector', { - headers: this.headers, - fetch: this.fetch, - }); - } - /** - * Access analytics storage operations using Iceberg tables. - * - * @returns A StorageAnalyticsApi instance configured with the current storage settings. - * @example - * ```typescript - * const client = createClient(url, key) - * const analytics = client.storage.analytics - * - * // Create an analytics bucket - * await analytics.createBucket('my-analytics-bucket') - * - * // List all analytics buckets - * const { data: buckets } = await analytics.listBuckets() - * - * // Delete an analytics bucket - * await analytics.deleteBucket('old-analytics-bucket') - * ``` - */ - get analytics() { - return new StorageAnalyticsApi_1.default(this.url + '/iceberg', this.headers, this.fetch); - } -} -exports.StorageClient = StorageClient; -//# sourceMappingURL=StorageClient.js.map - -/***/ }), - -/***/ 45852: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageAnalyticsApi = exports.StorageClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -var StorageClient_1 = __nccwpck_require__(44249); -Object.defineProperty(exports, "StorageClient", ({ enumerable: true, get: function () { return StorageClient_1.StorageClient; } })); -var StorageAnalyticsApi_1 = __nccwpck_require__(27339); -Object.defineProperty(exports, "StorageAnalyticsApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(StorageAnalyticsApi_1).default; } })); -tslib_1.__exportStar(__nccwpck_require__(57222), exports); -tslib_1.__exportStar(__nccwpck_require__(42758), exports); -tslib_1.__exportStar(__nccwpck_require__(99380), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 79754: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_HEADERS = void 0; -const version_1 = __nccwpck_require__(54499); -exports.DEFAULT_HEADERS = { - 'X-Client-Info': `storage-js/${version_1.version}`, -}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 42758: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageUnknownError = exports.StorageApiError = exports.StorageError = void 0; -exports.isStorageError = isStorageError; -class StorageError extends Error { - constructor(message) { - super(message); - this.__isStorageError = true; - this.name = 'StorageError'; - } -} -exports.StorageError = StorageError; -function isStorageError(error) { - return typeof error === 'object' && error !== null && '__isStorageError' in error; -} -class StorageApiError extends StorageError { - constructor(message, status, statusCode) { - super(message); - this.name = 'StorageApiError'; - this.status = status; - this.statusCode = statusCode; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - statusCode: this.statusCode, - }; - } -} -exports.StorageApiError = StorageApiError; -class StorageUnknownError extends StorageError { - constructor(message, originalError) { - super(message); - this.name = 'StorageUnknownError'; - this.originalError = originalError; - } -} -exports.StorageUnknownError = StorageUnknownError; -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 73146: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.get = get; -exports.post = post; -exports.put = put; -exports.head = head; -exports.remove = remove; -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -const helpers_1 = __nccwpck_require__(5430); -const _getErrorMessage = (err) => { - var _a; - return err.msg || - err.message || - err.error_description || - (typeof err.error === 'string' ? err.error : (_a = err.error) === null || _a === void 0 ? void 0 : _a.message) || - JSON.stringify(err); -}; -const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - const Res = yield (0, helpers_1.resolveResponse)(); - if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { - error - .json() - .then((err) => { - const status = error.status || 500; - const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || status + ''; - reject(new errors_1.StorageApiError(_getErrorMessage(err), status, statusCode)); - }) - .catch((err) => { - reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err)); - }); - } - else { - reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error)); - } -}); -const _getRequestParams = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET' || !body) { - return params; - } - if ((0, helpers_1.isPlainObject)(body)) { - params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); - params.body = JSON.stringify(body); - } - else { - params.body = body; - } - if (options === null || options === void 0 ? void 0 : options.duplex) { - params.duplex = options.duplex; - } - return Object.assign(Object.assign({}, params), parameters); -}; -function _handleRequest(fetcher, method, url, options, parameters, body) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - fetcher(url, _getRequestParams(method, options, parameters, body)) - .then((result) => { - if (!result.ok) - throw result; - if (options === null || options === void 0 ? void 0 : options.noResolveJson) - return result; - return result.json(); - }) - .then((data) => resolve(data)) - .catch((error) => handleError(error, reject, options)); - }); - }); -} -function get(fetcher, url, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'GET', url, options, parameters); - }); -} -function post(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'POST', url, options, parameters, body); - }); -} -function put(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'PUT', url, options, parameters, body); - }); -} -function head(fetcher, url, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); - }); -} -function remove(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); - }); -} -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 5430: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isPlainObject = exports.recursiveToCamel = exports.resolveResponse = exports.resolveFetch = void 0; -const tslib_1 = __nccwpck_require__(4351); -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -const resolveResponse = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - if (typeof Response === 'undefined') { - // @ts-ignore - return (yield Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s)))).Response; - } - return Response; -}); -exports.resolveResponse = resolveResponse; -const recursiveToCamel = (item) => { - if (Array.isArray(item)) { - return item.map((el) => (0, exports.recursiveToCamel)(el)); - } - else if (typeof item === 'function' || item !== Object(item)) { - return item; - } - const result = {}; - Object.entries(item).forEach(([key, value]) => { - const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, '')); - result[newKey] = (0, exports.recursiveToCamel)(value); - }); - return result; -}; -exports.recursiveToCamel = recursiveToCamel; -/** - * Determine if input is a plain object - * An object is plain if it's created by either {}, new Object(), or Object.create(null) - * source: https://github.com/sindresorhus/is-plain-obj - */ -const isPlainObject = (value) => { - if (typeof value !== 'object' || value === null) { - return false; - } - const prototype = Object.getPrototypeOf(value); - return ((prototype === null || - prototype === Object.prototype || - Object.getPrototypeOf(prototype) === null) && - !(Symbol.toStringTag in value) && - !(Symbol.iterator in value)); -}; -exports.isPlainObject = isPlainObject; -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 57222: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 59403: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -const VectorIndexApi_1 = tslib_1.__importDefault(__nccwpck_require__(79623)); -const VectorDataApi_1 = tslib_1.__importDefault(__nccwpck_require__(93073)); -const VectorBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(44268)); -/** - * Main client for interacting with S3 Vectors API - * Provides access to bucket, index, and vector data operations - * - * **Usage Patterns:** - * - * 1. **Via StorageClient (recommended for most use cases):** - * ```typescript - * import { StorageClient } from '@supabase/storage-js' - * - * const storageClient = new StorageClient(url, headers) - * const vectors = storageClient.vectors - * - * // Use vector operations - * await vectors.createBucket('embeddings-prod') - * const bucket = vectors.from('embeddings-prod') - * await bucket.createIndex({ ... }) - * ``` - * - * 2. **Standalone (for vector-only applications):** - * ```typescript - * import { StorageVectorsClient } from '@supabase/storage-js' - * - * const vectorsClient = new StorageVectorsClient('https://api.example.com', { - * headers: { 'Authorization': 'Bearer token' } - * }) - * - * // Access bucket operations - * await vectorsClient.createBucket('embeddings-prod') - * - * // Access index operations via buckets - * const bucket = vectorsClient.from('embeddings-prod') - * await bucket.createIndex({ - * indexName: 'documents', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine' - * }) - * - * // Access vector operations via index - * const index = bucket.index('documents') - * await index.putVectors({ - * vectors: [ - * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } - * ] - * }) - * - * // Query similar vectors - * const { data } = await index.queryVectors({ - * queryVector: { float32: [...] }, - * topK: 5, - * returnDistance: true - * }) - * ``` - */ -class StorageVectorsClient extends VectorBucketApi_1.default { - constructor(url, options = {}) { - super(url, options.headers || {}, options.fetch); - } - /** - * Access operations for a specific vector bucket - * Returns a scoped client for index and vector operations within the bucket - * - * @param vectorBucketName - Name of the vector bucket - * @returns Bucket-scoped client with index and vector operations - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * - * // Create an index in this bucket - * await bucket.createIndex({ - * indexName: 'documents-openai', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine' - * }) - * - * // List indexes in this bucket - * const { data } = await bucket.listIndexes() - * ``` - */ - from(vectorBucketName) { - return new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch); - } -} -exports.StorageVectorsClient = StorageVectorsClient; -/** - * Scoped client for operations within a specific vector bucket - * Provides index management and access to vector operations - */ -class VectorBucketScope extends VectorIndexApi_1.default { - constructor(url, headers, vectorBucketName, fetch) { - super(url, headers, fetch); - this.vectorBucketName = vectorBucketName; - } - /** - * Creates a new vector index in this bucket - * Convenience method that automatically includes the bucket name - * - * @param options - Index configuration (vectorBucketName is automatically set) - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * await bucket.createIndex({ - * indexName: 'documents-openai', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine', - * metadataConfiguration: { - * nonFilterableMetadataKeys: ['raw_text'] - * } - * }) - * ``` - */ - createIndex(options) { - const _super = Object.create(null, { - createIndex: { get: () => super.createIndex } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.createIndex.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); - }); - } - /** - * Lists indexes in this bucket - * Convenience method that automatically includes the bucket name - * - * @param options - Listing options (vectorBucketName is automatically set) - * @returns Promise with list of indexes or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * const { data } = await bucket.listIndexes({ prefix: 'documents-' }) - * ``` - */ - listIndexes() { - const _super = Object.create(null, { - listIndexes: { get: () => super.listIndexes } - }); - return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { - return _super.listIndexes.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); - }); - } - /** - * Retrieves metadata for a specific index in this bucket - * Convenience method that automatically includes the bucket name - * - * @param indexName - Name of the index to retrieve - * @returns Promise with index metadata or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * const { data } = await bucket.getIndex('documents-openai') - * console.log('Dimension:', data?.index.dimension) - * ``` - */ - getIndex(indexName) { - const _super = Object.create(null, { - getIndex: { get: () => super.getIndex } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.getIndex.call(this, this.vectorBucketName, indexName); - }); - } - /** - * Deletes an index from this bucket - * Convenience method that automatically includes the bucket name - * - * @param indexName - Name of the index to delete - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * await bucket.deleteIndex('old-index') - * ``` - */ - deleteIndex(indexName) { - const _super = Object.create(null, { - deleteIndex: { get: () => super.deleteIndex } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.deleteIndex.call(this, this.vectorBucketName, indexName); - }); - } - /** - * Access operations for a specific index within this bucket - * Returns a scoped client for vector data operations - * - * @param indexName - Name of the index - * @returns Index-scoped client with vector data operations - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * - * // Insert vectors - * await index.putVectors({ - * vectors: [ - * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } - * ] - * }) - * - * // Query similar vectors - * const { data } = await index.queryVectors({ - * queryVector: { float32: [...] }, - * topK: 5 - * }) - * ``` - */ - index(indexName) { - return new VectorIndexScope(this.url, this.headers, this.vectorBucketName, indexName, this.fetch); - } -} -exports.VectorBucketScope = VectorBucketScope; -/** - * Scoped client for operations within a specific vector index - * Provides vector data operations (put, get, list, query, delete) - */ -class VectorIndexScope extends VectorDataApi_1.default { - constructor(url, headers, vectorBucketName, indexName, fetch) { - super(url, headers, fetch); - this.vectorBucketName = vectorBucketName; - this.indexName = indexName; - } - /** - * Inserts or updates vectors in this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Vector insertion options (bucket and index names automatically set) - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * await index.putVectors({ - * vectors: [ - * { - * key: 'doc-1', - * data: { float32: [0.1, 0.2, ...] }, - * metadata: { title: 'Introduction', page: 1 } - * } - * ] - * }) - * ``` - */ - putVectors(options) { - const _super = Object.create(null, { - putVectors: { get: () => super.putVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.putVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Retrieves vectors by keys from this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Vector retrieval options (bucket and index names automatically set) - * @returns Promise with array of vectors or error - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * const { data } = await index.getVectors({ - * keys: ['doc-1', 'doc-2'], - * returnMetadata: true - * }) - * ``` - */ - getVectors(options) { - const _super = Object.create(null, { - getVectors: { get: () => super.getVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.getVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Lists vectors in this index with pagination - * Convenience method that automatically includes bucket and index names - * - * @param options - Listing options (bucket and index names automatically set) - * @returns Promise with array of vectors and pagination token - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * const { data } = await index.listVectors({ - * maxResults: 500, - * returnMetadata: true - * }) - * ``` - */ - listVectors() { - const _super = Object.create(null, { - listVectors: { get: () => super.listVectors } - }); - return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { - return _super.listVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Queries for similar vectors in this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Query options (bucket and index names automatically set) - * @returns Promise with array of similar vectors ordered by distance - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * const { data } = await index.queryVectors({ - * queryVector: { float32: [0.1, 0.2, ...] }, - * topK: 5, - * filter: { category: 'technical' }, - * returnDistance: true, - * returnMetadata: true - * }) - * ``` - */ - queryVectors(options) { - const _super = Object.create(null, { - queryVectors: { get: () => super.queryVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.queryVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Deletes vectors by keys from this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Deletion options (bucket and index names automatically set) - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * await index.deleteVectors({ - * keys: ['doc-1', 'doc-2', 'doc-3'] - * }) - * ``` - */ - deleteVectors(options) { - const _super = Object.create(null, { - deleteVectors: { get: () => super.deleteVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.deleteVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } -} -exports.VectorIndexScope = VectorIndexScope; -//# sourceMappingURL=StorageVectorsClient.js.map - -/***/ }), - -/***/ 44268: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(36876); -const errors_1 = __nccwpck_require__(93071); -const fetch_1 = __nccwpck_require__(2593); -const helpers_1 = __nccwpck_require__(21176); -/** - * API class for managing Vector Buckets - * Provides methods for creating, reading, listing, and deleting vector buckets - */ -class VectorBucketApi { - /** - * Creates a new VectorBucketApi instance - * @param url - The base URL for the storage vectors API - * @param headers - HTTP headers to include in requests - * @param fetch - Optional custom fetch implementation - */ - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - * @example - * ```typescript - * const client = new VectorBucketApi(url, headers) - * client.throwOnError() - * const { data } = await client.createBucket('my-bucket') // throws on error - * ``` - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Creates a new vector bucket - * Vector buckets are containers for vector indexes and their data - * - * @param vectorBucketName - Unique name for the vector bucket - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorConflictException` if bucket already exists (HTTP 409) - * - `S3VectorMaxBucketsExceeded` if quota exceeded (HTTP 400) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.createBucket('embeddings-prod') - * if (error) { - * console.error('Failed to create bucket:', error.message) - * } - * ``` - */ - createBucket(vectorBucketName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateVectorBucket`, { vectorBucketName }, { headers: this.headers }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves metadata for a specific vector bucket - * Returns bucket configuration including encryption settings and creation time - * - * @param vectorBucketName - Name of the vector bucket to retrieve - * @returns Promise with bucket metadata or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.getBucket('embeddings-prod') - * if (data) { - * console.log('Bucket created at:', new Date(data.vectorBucket.creationTime! * 1000)) - * } - * ``` - */ - getBucket(vectorBucketName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectorBucket`, { vectorBucketName }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Lists vector buckets with optional filtering and pagination - * Supports prefix-based filtering and paginated results - * - * @param options - Listing options - * @param options.prefix - Filter buckets by name prefix - * @param options.maxResults - Maximum results per page (default: 100) - * @param options.nextToken - Pagination token from previous response - * @returns Promise with list of buckets and pagination token - * - * @throws {StorageVectorsApiError} With code: - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // List all buckets with prefix 'prod-' - * const { data, error } = await client.listBuckets({ prefix: 'prod-' }) - * if (data) { - * console.log('Found buckets:', data.buckets.length) - * // Fetch next page if available - * if (data.nextToken) { - * const next = await client.listBuckets({ nextToken: data.nextToken }) - * } - * } - * ``` - */ - listBuckets() { - return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectorBuckets`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes a vector bucket - * Bucket must be empty before deletion (all indexes must be removed first) - * - * @param vectorBucketName - Name of the vector bucket to delete - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorBucketNotEmpty` if bucket contains indexes (HTTP 400) - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Delete all indexes first, then delete bucket - * const { error } = await client.deleteBucket('old-bucket') - * if (error?.statusCode === 'S3VectorBucketNotEmpty') { - * console.error('Must delete all indexes first') - * } - * ``` - */ - deleteBucket(vectorBucketName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectorBucket`, { vectorBucketName }, { headers: this.headers }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = VectorBucketApi; -//# sourceMappingURL=VectorBucketApi.js.map - -/***/ }), - -/***/ 93073: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(36876); -const errors_1 = __nccwpck_require__(93071); -const fetch_1 = __nccwpck_require__(2593); -const helpers_1 = __nccwpck_require__(21176); -/** - * API class for managing Vector Data within Vector Indexes - * Provides methods for inserting, querying, listing, and deleting vector embeddings - */ -class VectorDataApi { - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - * @example - * ```typescript - * const client = new VectorDataApi(url, headers) - * client.throwOnError() - * const { data } = await client.putVectors(options) // throws on error - * ``` - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Inserts or updates vectors in batch (upsert operation) - * Accepts 1-500 vectors per request. Larger batches should be split - * - * @param options - Vector insertion options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the target index - * @param options.vectors - Array of vectors to insert/update (1-500 items) - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorConflictException` if duplicate key conflict occurs (HTTP 409) - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.putVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * vectors: [ - * { - * key: 'doc-1', - * data: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions - * metadata: { title: 'Introduction', page: 1 } - * }, - * { - * key: 'doc-2', - * data: { float32: [0.4, 0.5, 0.6, ...] }, - * metadata: { title: 'Conclusion', page: 42 } - * } - * ] - * }) - * ``` - */ - putVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Validate batch size - if (options.vectors.length < 1 || options.vectors.length > 500) { - throw new Error('Vector batch size must be between 1 and 500 items'); - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/PutVectors`, options, { - headers: this.headers, - }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves vectors by their keys in batch - * Optionally includes vector data and/or metadata in response - * Additional permissions required when returning data or metadata - * - * @param options - Vector retrieval options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.keys - Array of vector keys to retrieve - * @param options.returnData - Whether to include vector embeddings (requires permission) - * @param options.returnMetadata - Whether to include metadata (requires permission) - * @returns Promise with array of vectors or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.getVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * keys: ['doc-1', 'doc-2', 'doc-3'], - * returnData: false, // Don't return embeddings - * returnMetadata: true // Return metadata only - * }) - * if (data) { - * data.vectors.forEach(v => console.log(v.key, v.metadata)) - * } - * ``` - */ - getVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectors`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Lists/scans vectors in an index with pagination - * Supports parallel scanning via segment configuration for high-throughput scenarios - * Additional permissions required when returning data or metadata - * - * @param options - Vector listing options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.maxResults - Maximum results per page (default: 500, max: 1000) - * @param options.nextToken - Pagination token from previous response - * @param options.returnData - Whether to include vector embeddings (requires permission) - * @param options.returnMetadata - Whether to include metadata (requires permission) - * @param options.segmentCount - Total parallel segments (1-16) for distributed scanning - * @param options.segmentIndex - Zero-based segment index (0 to segmentCount-1) - * @returns Promise with array of vectors, pagination token, or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Simple pagination - * let nextToken: string | undefined - * do { - * const { data, error } = await client.listVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * maxResults: 500, - * nextToken, - * returnMetadata: true - * }) - * if (error) break - * console.log('Batch:', data.vectors.length) - * nextToken = data.nextToken - * } while (nextToken) - * - * // Parallel scanning (4 concurrent workers) - * const workers = [0, 1, 2, 3].map(async (segmentIndex) => { - * const { data } = await client.listVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * segmentCount: 4, - * segmentIndex, - * returnMetadata: true - * }) - * return data?.vectors || [] - * }) - * const results = await Promise.all(workers) - * ``` - */ - listVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Validate segment configuration - if (options.segmentCount !== undefined) { - if (options.segmentCount < 1 || options.segmentCount > 16) { - throw new Error('segmentCount must be between 1 and 16'); - } - if (options.segmentIndex !== undefined) { - if (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) { - throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`); - } - } - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectors`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Queries for similar vectors using approximate nearest neighbor (ANN) search - * Returns top-K most similar vectors based on the configured distance metric - * Supports optional metadata filtering (requires GetVectors permission) - * - * @param options - Query options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.queryVector - Query embedding to find similar vectors - * @param options.topK - Number of nearest neighbors to return (default: 10) - * @param options.filter - Optional JSON filter for metadata (requires GetVectors permission) - * @param options.returnDistance - Whether to include similarity distances - * @param options.returnMetadata - Whether to include metadata (requires GetVectors permission) - * @returns Promise with array of similar vectors ordered by distance - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Semantic search with filtering - * const { data, error } = await client.queryVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * queryVector: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions - * topK: 5, - * filter: { - * category: 'technical', - * published: true - * }, - * returnDistance: true, - * returnMetadata: true - * }) - * if (data) { - * data.matches.forEach(match => { - * console.log(`${match.key}: distance=${match.distance}`) - * console.log('Metadata:', match.metadata) - * }) - * } - * ``` - */ - queryVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/QueryVectors`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes vectors by their keys in batch - * Accepts 1-500 keys per request - * - * @param options - Vector deletion options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.keys - Array of vector keys to delete (1-500 items) - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { error } = await client.deleteVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * keys: ['doc-1', 'doc-2', 'doc-3'] - * }) - * if (!error) { - * console.log('Vectors deleted successfully') - * } - * ``` - */ - deleteVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Validate batch size - if (options.keys.length < 1 || options.keys.length > 500) { - throw new Error('Keys batch size must be between 1 and 500 items'); - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectors`, options, { - headers: this.headers, - }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = VectorDataApi; -//# sourceMappingURL=VectorDataApi.js.map - -/***/ }), - -/***/ 79623: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(36876); -const errors_1 = __nccwpck_require__(93071); -const fetch_1 = __nccwpck_require__(2593); -const helpers_1 = __nccwpck_require__(21176); -/** - * API class for managing Vector Indexes within Vector Buckets - * Provides methods for creating, reading, listing, and deleting vector indexes - */ -class VectorIndexApi { - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - * @example - * ```typescript - * const client = new VectorIndexApi(url, headers) - * client.throwOnError() - * const { data } = await client.createIndex(options) // throws on error - * ``` - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Creates a new vector index within a bucket - * Defines the schema for vectors including dimensionality, distance metric, and metadata config - * - * @param options - Index configuration - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Unique name for the index within the bucket - * @param options.dataType - Data type for vector components (currently only 'float32') - * @param options.dimension - Dimensionality of vectors (e.g., 384, 768, 1536) - * @param options.distanceMetric - Similarity metric ('cosine', 'euclidean', 'dotproduct') - * @param options.metadataConfiguration - Optional config for non-filterable metadata keys - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorConflictException` if index already exists (HTTP 409) - * - `S3VectorMaxIndexesExceeded` if quota exceeded (HTTP 400) - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.createIndex({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine', - * metadataConfiguration: { - * nonFilterableMetadataKeys: ['raw_text', 'internal_id'] - * } - * }) - * ``` - */ - createIndex(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateIndex`, options, { - headers: this.headers, - }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves metadata for a specific vector index - * Returns index configuration including dimension, distance metric, and metadata settings - * - * @param vectorBucketName - Name of the parent vector bucket - * @param indexName - Name of the index to retrieve - * @returns Promise with index metadata or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.getIndex('embeddings-prod', 'documents-openai-small') - * if (data) { - * console.log('Index dimension:', data.index.dimension) - * console.log('Distance metric:', data.index.distanceMetric) - * } - * ``` - */ - getIndex(vectorBucketName, indexName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetIndex`, { vectorBucketName, indexName }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Lists vector indexes within a bucket with optional filtering and pagination - * Supports prefix-based filtering and paginated results - * - * @param options - Listing options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.prefix - Filter indexes by name prefix - * @param options.maxResults - Maximum results per page (default: 100) - * @param options.nextToken - Pagination token from previous response - * @returns Promise with list of indexes and pagination token - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // List all indexes in a bucket - * const { data, error } = await client.listIndexes({ - * vectorBucketName: 'embeddings-prod', - * prefix: 'documents-' - * }) - * if (data) { - * console.log('Found indexes:', data.indexes.map(i => i.indexName)) - * // Fetch next page if available - * if (data.nextToken) { - * const next = await client.listIndexes({ - * vectorBucketName: 'embeddings-prod', - * nextToken: data.nextToken - * }) - * } - * } - * ``` - */ - listIndexes(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListIndexes`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes a vector index and all its data - * This operation removes the index schema and all vectors stored in the index - * - * @param vectorBucketName - Name of the parent vector bucket - * @param indexName - Name of the index to delete - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Delete an index and all its vectors - * const { error } = await client.deleteIndex('embeddings-prod', 'old-index') - * if (!error) { - * console.log('Index deleted successfully') - * } - * ``` - */ - deleteIndex(vectorBucketName, indexName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteIndex`, { vectorBucketName, indexName }, { headers: this.headers }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = VectorIndexApi; -//# sourceMappingURL=VectorIndexApi.js.map - -/***/ }), - -/***/ 36876: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_HEADERS = void 0; -const version_1 = __nccwpck_require__(54499); -exports.DEFAULT_HEADERS = { - 'X-Client-Info': `storage-js/${version_1.version}`, - 'Content-Type': 'application/json', -}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 93071: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = void 0; -exports.isStorageVectorsError = isStorageVectorsError; -/** - * Base error class for all Storage Vectors errors - */ -class StorageVectorsError extends Error { - constructor(message) { - super(message); - this.__isStorageVectorsError = true; - this.name = 'StorageVectorsError'; - } -} -exports.StorageVectorsError = StorageVectorsError; -/** - * Type guard to check if an error is a StorageVectorsError - * @param error - The error to check - * @returns True if the error is a StorageVectorsError - */ -function isStorageVectorsError(error) { - return typeof error === 'object' && error !== null && '__isStorageVectorsError' in error; -} -/** - * API error returned from S3 Vectors service - * Includes HTTP status code and service-specific error code - */ -class StorageVectorsApiError extends StorageVectorsError { - constructor(message, status, statusCode) { - super(message); - this.name = 'StorageVectorsApiError'; - this.status = status; - this.statusCode = statusCode; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - statusCode: this.statusCode, - }; - } -} -exports.StorageVectorsApiError = StorageVectorsApiError; -/** - * Unknown error that doesn't match expected error patterns - * Wraps the original error for debugging - */ -class StorageVectorsUnknownError extends StorageVectorsError { - constructor(message, originalError) { - super(message); - this.name = 'StorageVectorsUnknownError'; - this.originalError = originalError; - } -} -exports.StorageVectorsUnknownError = StorageVectorsUnknownError; -/** - * Error codes specific to S3 Vectors API - * Maps AWS service errors to application-friendly error codes - */ -var StorageVectorsErrorCode; -(function (StorageVectorsErrorCode) { - /** Internal server fault (HTTP 500) */ - StorageVectorsErrorCode["InternalError"] = "InternalError"; - /** Resource already exists / conflict (HTTP 409) */ - StorageVectorsErrorCode["S3VectorConflictException"] = "S3VectorConflictException"; - /** Resource not found (HTTP 404) */ - StorageVectorsErrorCode["S3VectorNotFoundException"] = "S3VectorNotFoundException"; - /** Delete bucket while not empty (HTTP 400) */ - StorageVectorsErrorCode["S3VectorBucketNotEmpty"] = "S3VectorBucketNotEmpty"; - /** Exceeds bucket quota/limit (HTTP 400) */ - StorageVectorsErrorCode["S3VectorMaxBucketsExceeded"] = "S3VectorMaxBucketsExceeded"; - /** Exceeds index quota/limit (HTTP 400) */ - StorageVectorsErrorCode["S3VectorMaxIndexesExceeded"] = "S3VectorMaxIndexesExceeded"; -})(StorageVectorsErrorCode || (exports.StorageVectorsErrorCode = StorageVectorsErrorCode = {})); -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 2593: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.get = get; -exports.post = post; -exports.put = put; -exports.remove = remove; -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(93071); -const helpers_1 = __nccwpck_require__(21176); -/** - * Extracts error message from various error response formats - * @param err - Error object from API - * @returns Human-readable error message - */ -const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); -/** - * Handles fetch errors and converts them to StorageVectors error types - * @param error - The error caught from fetch - * @param reject - Promise rejection function - * @param options - Fetch options that may affect error handling - */ -const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - // Check if error is a Response-like object (has status and ok properties) - // This is more reliable than instanceof which can fail across realms - const isResponseLike = error && - typeof error === 'object' && - 'status' in error && - 'ok' in error && - typeof error.status === 'number'; - if (isResponseLike && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { - const status = error.status || 500; - const responseError = error; - // Try to parse JSON body if available - if (typeof responseError.json === 'function') { - responseError - .json() - .then((err) => { - const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || (err === null || err === void 0 ? void 0 : err.code) || status + ''; - reject(new errors_1.StorageVectorsApiError(_getErrorMessage(err), status, statusCode)); - }) - .catch(() => { - // If JSON parsing fails, create an ApiError with the HTTP status code - const statusCode = status + ''; - const message = responseError.statusText || `HTTP ${status} error`; - reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); - }); - } - else { - // No json() method available, create error from status - const statusCode = status + ''; - const message = responseError.statusText || `HTTP ${status} error`; - reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); - } - } - else { - reject(new errors_1.StorageVectorsUnknownError(_getErrorMessage(error), error)); - } -}); -/** - * Builds request parameters for fetch calls - * @param method - HTTP method - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters like AbortSignal - * @param body - Request body (will be JSON stringified if plain object) - * @returns Complete fetch request parameters - */ -const _getRequestParams = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET' || !body) { - return params; - } - if ((0, helpers_1.isPlainObject)(body)) { - params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); - params.body = JSON.stringify(body); - } - else { - params.body = body; - } - return Object.assign(Object.assign({}, params), parameters); -}; -/** - * Internal request handler that wraps fetch with error handling - * @param fetcher - Fetch function to use - * @param method - HTTP method - * @param url - Request URL - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @param body - Request body - * @returns Promise with parsed response or error - */ -function _handleRequest(fetcher, method, url, options, parameters, body) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - fetcher(url, _getRequestParams(method, options, parameters, body)) - .then((result) => { - if (!result.ok) - throw result; - if (options === null || options === void 0 ? void 0 : options.noResolveJson) - return result; - // Handle empty responses (204, empty body) - const contentType = result.headers.get('content-type'); - if (!contentType || !contentType.includes('application/json')) { - return {}; - } - return result.json(); - }) - .then((data) => resolve(data)) - .catch((error) => handleError(error, reject, options)); - }); - }); -} -/** - * Performs a GET request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function get(fetcher, url, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'GET', url, options, parameters); - }); -} -/** - * Performs a POST request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param body - Request body to be JSON stringified - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function post(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'POST', url, options, parameters, body); - }); -} -/** - * Performs a PUT request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param body - Request body to be JSON stringified - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function put(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'PUT', url, options, parameters, body); - }); -} -/** - * Performs a DELETE request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param body - Request body to be JSON stringified - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function remove(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); - }); -} -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 21176: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = void 0; -const tslib_1 = __nccwpck_require__(4351); -/** - * Resolves the fetch implementation to use - * Uses custom fetch if provided, otherwise falls back to: - * - Native fetch in browser/modern environments - * - @supabase/node-fetch polyfill in Node.js environments without fetch - * - * @param customFetch - Optional custom fetch implementation - * @returns Resolved fetch function - */ -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -/** - * Resolves the Response constructor to use - * Uses native Response in browser/modern environments - * Falls back to @supabase/node-fetch polyfill in Node.js environments - * - * @returns Response constructor - */ -const resolveResponse = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - if (typeof Response === 'undefined') { - // @ts-ignore - return (yield Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s)))).Response; - } - return Response; -}); -exports.resolveResponse = resolveResponse; -/** - * Determine if input is a plain object - * An object is plain if it's created by either {}, new Object(), or Object.create(null) - * - * @param value - Value to check - * @returns True if value is a plain object - * @source https://github.com/sindresorhus/is-plain-obj - */ -const isPlainObject = (value) => { - if (typeof value !== 'object' || value === null) { - return false; - } - const prototype = Object.getPrototypeOf(value); - return ((prototype === null || - prototype === Object.prototype || - Object.getPrototypeOf(prototype) === null) && - !(Symbol.toStringTag in value) && - !(Symbol.iterator in value)); -}; -exports.isPlainObject = isPlainObject; -/** - * Normalizes a number array to float32 format - * Ensures all vector values are valid 32-bit floats - * - * @param values - Array of numbers to normalize - * @returns Normalized float32 array - */ -const normalizeToFloat32 = (values) => { - // Use Float32Array to ensure proper precision - return Array.from(new Float32Array(values)); -}; -exports.normalizeToFloat32 = normalizeToFloat32; -/** - * Validates vector dimensions match expected dimension - * Throws error if dimensions don't match - * - * @param vector - Vector data to validate - * @param expectedDimension - Expected vector dimension - * @throws Error if dimensions don't match - */ -const validateVectorDimension = (vector, expectedDimension) => { - if (expectedDimension !== undefined && vector.float32.length !== expectedDimension) { - throw new Error(`Vector dimension mismatch: expected ${expectedDimension}, got ${vector.float32.length}`); - } -}; -exports.validateVectorDimension = validateVectorDimension; -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 99380: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = exports.isStorageVectorsError = exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = exports.VectorDataApi = exports.VectorIndexApi = exports.VectorBucketApi = exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -// Main client -var StorageVectorsClient_1 = __nccwpck_require__(59403); -Object.defineProperty(exports, "StorageVectorsClient", ({ enumerable: true, get: function () { return StorageVectorsClient_1.StorageVectorsClient; } })); -Object.defineProperty(exports, "VectorBucketScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorBucketScope; } })); -Object.defineProperty(exports, "VectorIndexScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorIndexScope; } })); -// API classes (for advanced usage) -var VectorBucketApi_1 = __nccwpck_require__(44268); -Object.defineProperty(exports, "VectorBucketApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorBucketApi_1).default; } })); -var VectorIndexApi_1 = __nccwpck_require__(79623); -Object.defineProperty(exports, "VectorIndexApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorIndexApi_1).default; } })); -var VectorDataApi_1 = __nccwpck_require__(93073); -Object.defineProperty(exports, "VectorDataApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorDataApi_1).default; } })); -// Errors -var errors_1 = __nccwpck_require__(93071); -Object.defineProperty(exports, "StorageVectorsError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsError; } })); -Object.defineProperty(exports, "StorageVectorsApiError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsApiError; } })); -Object.defineProperty(exports, "StorageVectorsUnknownError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsUnknownError; } })); -Object.defineProperty(exports, "StorageVectorsErrorCode", ({ enumerable: true, get: function () { return errors_1.StorageVectorsErrorCode; } })); -Object.defineProperty(exports, "isStorageVectorsError", ({ enumerable: true, get: function () { return errors_1.isStorageVectorsError; } })); -// Helper utilities -var helpers_1 = __nccwpck_require__(21176); -Object.defineProperty(exports, "resolveFetch", ({ enumerable: true, get: function () { return helpers_1.resolveFetch; } })); -Object.defineProperty(exports, "resolveResponse", ({ enumerable: true, get: function () { return helpers_1.resolveResponse; } })); -Object.defineProperty(exports, "isPlainObject", ({ enumerable: true, get: function () { return helpers_1.isPlainObject; } })); -Object.defineProperty(exports, "normalizeToFloat32", ({ enumerable: true, get: function () { return helpers_1.normalizeToFloat32; } })); -Object.defineProperty(exports, "validateVectorDimension", ({ enumerable: true, get: function () { return helpers_1.validateVectorDimension; } })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 54499: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 98475: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -const StreamDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(7023)); -class BlobDownloadBuilder { - constructor(downloadFn, shouldThrowOnError) { - this.downloadFn = downloadFn; - this.shouldThrowOnError = shouldThrowOnError; - this[_a] = 'BlobDownloadBuilder'; - this.promise = null; - } - asStream() { - return new StreamDownloadBuilder_1.default(this.downloadFn, this.shouldThrowOnError); - } - then(onfulfilled, onrejected) { - return this.getPromise().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.getPromise().catch(onrejected); - } - finally(onfinally) { - return this.getPromise().finally(onfinally); - } - getPromise() { - if (!this.promise) { - this.promise = this.execute(); - } - return this.promise; - } - execute() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const result = yield this.downloadFn(); - return { - data: yield result.blob(), - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -_a = Symbol.toStringTag; -exports["default"] = BlobDownloadBuilder; -//# sourceMappingURL=BlobDownloadBuilder.js.map - -/***/ }), - -/***/ 27339: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(79754); -const errors_1 = __nccwpck_require__(42758); -const fetch_1 = __nccwpck_require__(73146); -const helpers_1 = __nccwpck_require__(5430); -/** - * API class for managing Analytics Buckets using Iceberg tables - * Provides methods for creating, listing, and deleting analytics buckets - */ -class StorageAnalyticsApi { - /** - * Creates a new StorageAnalyticsApi instance - * @param url - The base URL for the storage API - * @param headers - HTTP headers to include in requests - * @param fetch - Optional custom fetch implementation - */ - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Creates a new analytics bucket using Iceberg tables - * Analytics buckets are optimized for analytical queries and data processing - * - * @param name A unique name for the bucket you are creating - * @returns Promise with newly created bucket name or error - * - * @example - * ```typescript - * const { data, error } = await storage.analytics.createBucket('analytics-data') - * if (error) { - * console.error('Failed to create analytics bucket:', error.message) - * } else { - * console.log('Created bucket:', data.name) - * } - * ``` - */ - createBucket(name) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { name }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves the details of all Analytics Storage buckets within an existing project - * Only returns buckets of type 'ANALYTICS' - * - * @param options Query parameters for listing buckets - * @param options.limit Maximum number of buckets to return - * @param options.offset Number of buckets to skip - * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at') - * @param options.sortOrder Sort order ('asc' or 'desc') - * @param options.search Search term to filter bucket names - * @returns Promise with list of analytics buckets or error - * - * @example - * ```typescript - * const { data, error } = await storage.analytics.listBuckets({ - * limit: 10, - * offset: 0, - * sortColumn: 'created_at', - * sortOrder: 'desc', - * search: 'analytics' - * }) - * if (data) { - * console.log('Found analytics buckets:', data.length) - * data.forEach(bucket => console.log(`- ${bucket.name}`)) - * } - * ``` - */ - listBuckets(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Build query string from options - const queryParams = new URLSearchParams(); - if ((options === null || options === void 0 ? void 0 : options.limit) !== undefined) - queryParams.set('limit', options.limit.toString()); - if ((options === null || options === void 0 ? void 0 : options.offset) !== undefined) - queryParams.set('offset', options.offset.toString()); - if (options === null || options === void 0 ? void 0 : options.sortColumn) - queryParams.set('sortColumn', options.sortColumn); - if (options === null || options === void 0 ? void 0 : options.sortOrder) - queryParams.set('sortOrder', options.sortOrder); - if (options === null || options === void 0 ? void 0 : options.search) - queryParams.set('search', options.search); - const queryString = queryParams.toString(); - const url = queryString ? `${this.url}/bucket?${queryString}` : `${this.url}/bucket`; - const data = yield (0, fetch_1.get)(this.fetch, url, { headers: this.headers }); - return { data: data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes an existing analytics bucket - * A bucket can't be deleted with existing objects inside it - * You must first empty the bucket before deletion - * - * @param bucketId The unique identifier of the bucket you would like to delete - * @returns Promise with success message or error - * - * @example - * ```typescript - * const { data, error } = await analyticsApi.deleteBucket('old-analytics-bucket') - * if (error) { - * console.error('Failed to delete bucket:', error.message) - * } else { - * console.log('Bucket deleted successfully:', data.message) - * } - * ``` - */ - deleteBucket(bucketId) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${bucketId}`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = StorageAnalyticsApi; -//# sourceMappingURL=StorageAnalyticsApi.js.map - -/***/ }), - -/***/ 33528: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(79754); -const errors_1 = __nccwpck_require__(42758); -const fetch_1 = __nccwpck_require__(73146); -const helpers_1 = __nccwpck_require__(5430); -class StorageBucketApi { - constructor(url, headers = {}, fetch, opts) { - this.shouldThrowOnError = false; - const baseUrl = new URL(url); - // if legacy uri is used, replace with new storage host (disables request buffering to allow > 50GB uploads) - // "project-ref.supabase.co" becomes "project-ref.storage.supabase.co" - if (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) { - const isSupabaseHost = /supabase\.(co|in|red)$/.test(baseUrl.hostname); - if (isSupabaseHost && !baseUrl.hostname.includes('storage.supabase.')) { - baseUrl.hostname = baseUrl.hostname.replace('supabase.', 'storage.supabase.'); - } - } - this.url = baseUrl.href.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them. - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Retrieves the details of all Storage buckets within an existing project. - */ - listBuckets(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const queryString = this.listBucketOptionsToQueryString(options); - const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket${queryString}`, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves the details of an existing Storage bucket. - * - * @param id The unique identifier of the bucket you would like to retrieve. - */ - getBucket(id) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a new Storage bucket - * - * @param id A unique identifier for the bucket you are creating. - * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. - * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. - * The global file size limit takes precedence over this value. - * The default value is null, which doesn't set a per bucket file size limit. - * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. - * The default value is null, which allows files with all mime types to be uploaded. - * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. - * @returns newly created bucket id - * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details. - * - default bucket type is `STANDARD` - */ - createBucket(id_1) { - return tslib_1.__awaiter(this, arguments, void 0, function* (id, options = { - public: false, - }) { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { - id, - name: id, - type: options.type, - public: options.public, - file_size_limit: options.fileSizeLimit, - allowed_mime_types: options.allowedMimeTypes, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Updates a Storage bucket - * - * @param id A unique identifier for the bucket you are updating. - * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. - * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. - * The global file size limit takes precedence over this value. - * The default value is null, which doesn't set a per bucket file size limit. - * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. - * The default value is null, which allows files with all mime types to be uploaded. - * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. - */ - updateBucket(id, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, { - id, - name: id, - public: options.public, - file_size_limit: options.fileSizeLimit, - allowed_mime_types: options.allowedMimeTypes, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Removes all objects inside a single bucket. - * - * @param id The unique identifier of the bucket you would like to empty. - */ - emptyBucket(id) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. - * You must first `empty()` the bucket. - * - * @param id The unique identifier of the bucket you would like to delete. - */ - deleteBucket(id) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - listBucketOptionsToQueryString(options) { - const params = {}; - if (options) { - if ('limit' in options) { - params.limit = String(options.limit); - } - if ('offset' in options) { - params.offset = String(options.offset); - } - if (options.search) { - params.search = options.search; - } - if (options.sortColumn) { - params.sortColumn = options.sortColumn; - } - if (options.sortOrder) { - params.sortOrder = options.sortOrder; - } - } - return Object.keys(params).length > 0 ? '?' + new URLSearchParams(params).toString() : ''; - } -} -exports["default"] = StorageBucketApi; -//# sourceMappingURL=StorageBucketApi.js.map - -/***/ }), - -/***/ 80710: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -const fetch_1 = __nccwpck_require__(73146); -const helpers_1 = __nccwpck_require__(5430); -const BlobDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(98475)); -const DEFAULT_SEARCH_OPTIONS = { - limit: 100, - offset: 0, - sortBy: { - column: 'name', - order: 'asc', - }, -}; -const DEFAULT_FILE_OPTIONS = { - cacheControl: '3600', - contentType: 'text/plain;charset=UTF-8', - upsert: false, -}; -class StorageFileApi { - constructor(url, headers = {}, bucketId, fetch) { - this.shouldThrowOnError = false; - this.url = url; - this.headers = headers; - this.bucketId = bucketId; - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them. - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. - * - * @param method HTTP method. - * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param fileBody The body of the file to be stored in the bucket. - */ - uploadOrUpdate(method, path, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - let body; - const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); - let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); - const metadata = options.metadata; - if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { - body = new FormData(); - body.append('cacheControl', options.cacheControl); - if (metadata) { - body.append('metadata', this.encodeMetadata(metadata)); - } - body.append('', fileBody); - } - else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { - body = fileBody; - body.append('cacheControl', options.cacheControl); - if (metadata) { - body.append('metadata', this.encodeMetadata(metadata)); - } - } - else { - body = fileBody; - headers['cache-control'] = `max-age=${options.cacheControl}`; - headers['content-type'] = options.contentType; - if (metadata) { - headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata)); - } - } - if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { - headers = Object.assign(Object.assign({}, headers), fileOptions.headers); - } - const cleanPath = this._removeEmptyFolders(path); - const _path = this._getFinalPath(cleanPath); - const data = yield (method == 'PUT' ? fetch_1.put : fetch_1.post)(this.fetch, `${this.url}/object/${_path}`, body, Object.assign({ headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); - return { - data: { path: cleanPath, id: data.Id, fullPath: data.Key }, - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Uploads a file to an existing bucket. - * - * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param fileBody The body of the file to be stored in the bucket. - */ - upload(path, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return this.uploadOrUpdate('POST', path, fileBody, fileOptions); - }); - } - /** - * Upload a file with a token generated from `createSignedUploadUrl`. - * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param token The token generated from `createSignedUploadUrl` - * @param fileBody The body of the file to be stored in the bucket. - */ - uploadToSignedUrl(path, token, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const cleanPath = this._removeEmptyFolders(path); - const _path = this._getFinalPath(cleanPath); - const url = new URL(this.url + `/object/upload/sign/${_path}`); - url.searchParams.set('token', token); - try { - let body; - const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); - const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); - if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { - body = new FormData(); - body.append('cacheControl', options.cacheControl); - body.append('', fileBody); - } - else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { - body = fileBody; - body.append('cacheControl', options.cacheControl); - } - else { - body = fileBody; - headers['cache-control'] = `max-age=${options.cacheControl}`; - headers['content-type'] = options.contentType; - } - const data = yield (0, fetch_1.put)(this.fetch, url.toString(), body, { headers }); - return { - data: { path: cleanPath, fullPath: data.Key }, - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a signed upload URL. - * Signed upload URLs can be used to upload files to the bucket without further authentication. - * They are valid for 2 hours. - * @param path The file path, including the current file name. For example `folder/image.png`. - * @param options.upsert If set to true, allows the file to be overwritten if it already exists. - */ - createSignedUploadUrl(path, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - let _path = this._getFinalPath(path); - const headers = Object.assign({}, this.headers); - if (options === null || options === void 0 ? void 0 : options.upsert) { - headers['x-upsert'] = 'true'; - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); - const url = new URL(this.url + data.url); - const token = url.searchParams.get('token'); - if (!token) { - throw new errors_1.StorageError('No token returned by API'); - } - return { data: { signedUrl: url.toString(), path, token }, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Replaces an existing file at the specified path with a new one. - * - * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. - * @param fileBody The body of the file to be stored in the bucket. - */ - update(path, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); - }); - } - /** - * Moves an existing file to a new path in the same bucket. - * - * @param fromPath The original file path, including the current file name. For example `folder/image.png`. - * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. - * @param options The destination options. - */ - move(fromPath, toPath, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, { - bucketId: this.bucketId, - sourceKey: fromPath, - destinationKey: toPath, - destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Copies an existing file to a new path in the same bucket. - * - * @param fromPath The original file path, including the current file name. For example `folder/image.png`. - * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. - * @param options The destination options. - */ - copy(fromPath, toPath, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, { - bucketId: this.bucketId, - sourceKey: fromPath, - destinationKey: toPath, - destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, - }, { headers: this.headers }); - return { data: { path: data.Key }, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. - * - * @param path The file path, including the current file name. For example `folder/image.png`. - * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. - * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - * @param options.transform Transform the asset before serving it to the client. - */ - createSignedUrl(path, expiresIn, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - let _path = this._getFinalPath(path); - let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `&download=${options.download === true ? '' : options.download}` - : ''; - const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); - data = { signedUrl }; - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. - * - * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. - * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. - * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - */ - createSignedUrls(paths, expiresIn, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `&download=${options.download === true ? '' : options.download}` - : ''; - return { - data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL - ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) - : null }))), - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. - * - * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. - * @param options.transform Transform the asset before serving it to the client. - */ - download(path, options) { - const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; - const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; - const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); - const queryString = transformationQuery ? `?${transformationQuery}` : ''; - const _path = this._getFinalPath(path); - const downloadFn = () => (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { - headers: this.headers, - noResolveJson: true, - }); - return new BlobDownloadBuilder_1.default(downloadFn, this.shouldThrowOnError); - } - /** - * Retrieves the details of an existing file. - * @param path - */ - info(path) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const _path = this._getFinalPath(path); - try { - const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, { - headers: this.headers, - }); - return { data: (0, helpers_1.recursiveToCamel)(data), error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Checks the existence of a file. - * @param path - */ - exists(path) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const _path = this._getFinalPath(path); - try { - yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, { - headers: this.headers, - }); - return { data: true, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) { - const originalError = error.originalError; - if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { - return { data: false, error }; - } - } - throw error; - } - }); - } - /** - * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. - * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. - * - * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. - * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - * @param options.transform Transform the asset before serving it to the client. - */ - getPublicUrl(path, options) { - const _path = this._getFinalPath(path); - const _queryString = []; - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `download=${options.download === true ? '' : options.download}` - : ''; - if (downloadQueryParam !== '') { - _queryString.push(downloadQueryParam); - } - const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; - const renderPath = wantsTransformation ? 'render/image' : 'object'; - const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); - if (transformationQuery !== '') { - _queryString.push(transformationQuery); - } - let queryString = _queryString.join('&'); - if (queryString !== '') { - queryString = `?${queryString}`; - } - return { - data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, - }; - } - /** - * Deletes files within the same bucket - * - * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. - */ - remove(paths) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Get file metadata - * @param id the file id to retrieve metadata - */ - // async getMetadata( - // id: string - // ): Promise< - // | { - // data: Metadata - // error: null - // } - // | { - // data: null - // error: StorageError - // } - // > { - // try { - // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) - // return { data, error: null } - // } catch (error) { - // if (isStorageError(error)) { - // return { data: null, error } - // } - // throw error - // } - // } - /** - * Update file metadata - * @param id the file id to update metadata - * @param meta the new file metadata - */ - // async updateMetadata( - // id: string, - // meta: Metadata - // ): Promise< - // | { - // data: Metadata - // error: null - // } - // | { - // data: null - // error: StorageError - // } - // > { - // try { - // const data = await post( - // this.fetch, - // `${this.url}/metadata/${id}`, - // { ...meta }, - // { headers: this.headers } - // ) - // return { data, error: null } - // } catch (error) { - // if (isStorageError(error)) { - // return { data: null, error } - // } - // throw error - // } - // } - /** - * Lists all the files and folders within a path of the bucket. - * @param path The folder path. - * @param options Search options including limit (defaults to 100), offset, sortBy, and search - */ - list(path, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * @experimental this method signature might change in the future - * @param options search options - * @param parameters - */ - listV2(options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const body = Object.assign({}, options); - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list-v2/${this.bucketId}`, body, { headers: this.headers }, parameters); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - encodeMetadata(metadata) { - return JSON.stringify(metadata); - } - toBase64(data) { - if (typeof Buffer !== 'undefined') { - return Buffer.from(data).toString('base64'); - } - return btoa(data); - } - _getFinalPath(path) { - return `${this.bucketId}/${path.replace(/^\/+/, '')}`; - } - _removeEmptyFolders(path) { - return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); - } - transformOptsToQueryString(transform) { - const params = []; - if (transform.width) { - params.push(`width=${transform.width}`); - } - if (transform.height) { - params.push(`height=${transform.height}`); - } - if (transform.resize) { - params.push(`resize=${transform.resize}`); - } - if (transform.format) { - params.push(`format=${transform.format}`); - } - if (transform.quality) { - params.push(`quality=${transform.quality}`); - } - return params.join('&'); - } -} -exports["default"] = StorageFileApi; -//# sourceMappingURL=StorageFileApi.js.map - -/***/ }), - -/***/ 7023: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -class StreamDownloadBuilder { - constructor(downloadFn, shouldThrowOnError) { - this.downloadFn = downloadFn; - this.shouldThrowOnError = shouldThrowOnError; - } - then(onfulfilled, onrejected) { - return this.execute().then(onfulfilled, onrejected); - } - execute() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const result = yield this.downloadFn(); - return { - data: result.body, - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = StreamDownloadBuilder; -//# sourceMappingURL=StreamDownloadBuilder.js.map - -/***/ }), - -/***/ 71807: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const functions_js_1 = __nccwpck_require__(38519); -const postgrest_js_1 = __nccwpck_require__(31178); -const realtime_js_1 = __nccwpck_require__(60442); -const storage_js_1 = __nccwpck_require__(45852); -const constants_1 = __nccwpck_require__(94868); -const fetch_1 = __nccwpck_require__(50785); -const helpers_1 = __nccwpck_require__(3575); -const SupabaseAuthClient_1 = __nccwpck_require__(87620); -/** - * Supabase Client. - * - * An isomorphic Javascript client for interacting with Postgres. - */ -class SupabaseClient { - /** - * Create a new client for use in the browser. - * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. - * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. - * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. - * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. - * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. - * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. - * @param options.realtime Options passed along to realtime-js constructor. - * @param options.storage Options passed along to the storage-js constructor. - * @param options.global.fetch A custom fetch implementation. - * @param options.global.headers Any additional headers to send with each network request. - */ - constructor(supabaseUrl, supabaseKey, options) { - var _a, _b, _c; - this.supabaseUrl = supabaseUrl; - this.supabaseKey = supabaseKey; - const baseUrl = (0, helpers_1.validateSupabaseUrl)(supabaseUrl); - if (!supabaseKey) - throw new Error('supabaseKey is required.'); - this.realtimeUrl = new URL('realtime/v1', baseUrl); - this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws'); - this.authUrl = new URL('auth/v1', baseUrl); - this.storageUrl = new URL('storage/v1', baseUrl); - this.functionsUrl = new URL('functions/v1', baseUrl); - // default storage key uses the supabase project ref as a namespace - const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`; - const DEFAULTS = { - db: constants_1.DEFAULT_DB_OPTIONS, - realtime: constants_1.DEFAULT_REALTIME_OPTIONS, - auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), - global: constants_1.DEFAULT_GLOBAL_OPTIONS, - }; - const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); - this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; - this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; - if (!settings.accessToken) { - this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); - } - else { - this.accessToken = settings.accessToken; - this.auth = new Proxy({}, { - get: (_, prop) => { - throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); - }, - }); - } - this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); - this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); - this.rest = new postgrest_js_1.PostgrestClient(new URL('rest/v1', baseUrl).href, { - headers: this.headers, - schema: settings.db.schema, - fetch: this.fetch, - }); - this.storage = new storage_js_1.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); - if (!settings.accessToken) { - this._listenForAuthEvents(); - } - } - /** - * Supabase Functions allows you to deploy and invoke edge functions. - */ - get functions() { - return new functions_js_1.FunctionsClient(this.functionsUrl.href, { - headers: this.headers, - customFetch: this.fetch, - }); - } - /** - * Perform a query on a table or a view. - * - * @param relation - The table or view name to query - */ - from(relation) { - return this.rest.from(relation); - } - // NOTE: signatures must be kept in sync with PostgrestClient.schema - /** - * Select a schema to query or perform an function (rpc) call. - * - * The schema needs to be on the list of exposed schemas inside Supabase. - * - * @param schema - The schema to query - */ - schema(schema) { - return this.rest.schema(schema); - } - // NOTE: signatures must be kept in sync with PostgrestClient.rpc - /** - * Perform a function call. - * - * @param fn - The function name to call - * @param args - The arguments to pass to the function call - * @param options - Named parameters - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * @param options.get - When set to `true`, the function will be called with - * read-only access mode. - * @param options.count - Count algorithm to use to count rows returned by the - * function. Only applicable for [set-returning - * functions](https://www.postgresql.org/docs/current/functions-srf.html). - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - rpc(fn, args = {}, options = { - head: false, - get: false, - count: undefined, - }) { - return this.rest.rpc(fn, args, options); - } - /** - * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. - * - * @param {string} name - The name of the Realtime channel. - * @param {Object} opts - The options to pass to the Realtime channel. - * - */ - channel(name, opts = { config: {} }) { - return this.realtime.channel(name, opts); - } - /** - * Returns all Realtime channels. - */ - getChannels() { - return this.realtime.getChannels(); - } - /** - * Unsubscribes and removes Realtime channel from Realtime client. - * - * @param {RealtimeChannel} channel - The name of the Realtime channel. - * - */ - removeChannel(channel) { - return this.realtime.removeChannel(channel); - } - /** - * Unsubscribes and removes all Realtime channels from Realtime client. - */ - removeAllChannels() { - return this.realtime.removeAllChannels(); - } - async _getAccessToken() { - var _a, _b; - if (this.accessToken) { - return await this.accessToken(); - } - const { data } = await this.auth.getSession(); - return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; - } - _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, }, headers, fetch) { - const authHeaders = { - Authorization: `Bearer ${this.supabaseKey}`, - apikey: `${this.supabaseKey}`, - }; - return new SupabaseAuthClient_1.SupabaseAuthClient({ - url: this.authUrl.href, - headers: Object.assign(Object.assign({}, authHeaders), headers), - storageKey: storageKey, - autoRefreshToken, - persistSession, - detectSessionInUrl, - storage, - userStorage, - flowType, - lock, - debug, - fetch, - // auth checks if there is a custom authorizaiton header using this flag - // so it knows whether to return an error when getUser is called with no session - hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === 'authorization'), - }); - } - _initRealtimeClient(options) { - return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); - } - _listenForAuthEvents() { - const data = this.auth.onAuthStateChange((event, session) => { - this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); - }); - return data; - } - _handleTokenChanged(event, source, token) { - if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && - this.changedAccessToken !== token) { - this.changedAccessToken = token; - this.realtime.setAuth(token); - } - else if (event === 'SIGNED_OUT') { - this.realtime.setAuth(); - if (source == 'STORAGE') - this.auth.signOut(); - this.changedAccessToken = undefined; - } - } -} -exports["default"] = SupabaseClient; -//# sourceMappingURL=SupabaseClient.js.map - -/***/ }), - -/***/ 91206: -/***/ (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 __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); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0; -const SupabaseClient_1 = __importDefault(__nccwpck_require__(71807)); -__exportStar(__nccwpck_require__(66748), exports); -var postgrest_js_1 = __nccwpck_require__(31178); -Object.defineProperty(exports, "PostgrestError", ({ enumerable: true, get: function () { return postgrest_js_1.PostgrestError; } })); -var functions_js_1 = __nccwpck_require__(38519); -Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsHttpError; } })); -Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsFetchError; } })); -Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsRelayError; } })); -Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsError; } })); -Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return functions_js_1.FunctionRegion; } })); -__exportStar(__nccwpck_require__(60442), exports); -var SupabaseClient_2 = __nccwpck_require__(71807); -Object.defineProperty(exports, "SupabaseClient", ({ enumerable: true, get: function () { return __importDefault(SupabaseClient_2).default; } })); -/** - * Creates a new Supabase Client. - */ -const createClient = (supabaseUrl, supabaseKey, options) => { - return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); -}; -exports.createClient = createClient; -// Check for Node.js <= 18 deprecation -function shouldShowDeprecationWarning() { - // Skip in browser environments - if (typeof window !== 'undefined') { - return false; - } - // Skip if process is not available (e.g., Edge Runtime) - if (typeof process === 'undefined') { - return false; - } - // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings - const processVersion = process['version']; - if (processVersion === undefined || processVersion === null) { - return false; - } - const versionMatch = processVersion.match(/^v(\d+)\./); - if (!versionMatch) { - return false; - } - const majorVersion = parseInt(versionMatch[1], 10); - return majorVersion <= 18; -} -if (shouldShowDeprecationWarning()) { - console.warn(`āš ļø Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` + - `Please upgrade to Node.js 20 or later. ` + - `For more information, visit: https://github.com/orgs/supabase/discussions/37217`); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 87620: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SupabaseAuthClient = void 0; -const auth_js_1 = __nccwpck_require__(66748); -class SupabaseAuthClient extends auth_js_1.AuthClient { - constructor(options) { - super(options); - } -} -exports.SupabaseAuthClient = SupabaseAuthClient; -//# sourceMappingURL=SupabaseAuthClient.js.map - -/***/ }), - -/***/ 94868: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0; -const version_1 = __nccwpck_require__(86136); -let JS_ENV = ''; -// @ts-ignore -if (typeof Deno !== 'undefined') { - JS_ENV = 'deno'; -} -else if (typeof document !== 'undefined') { - JS_ENV = 'web'; -} -else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { - JS_ENV = 'react-native'; -} -else { - JS_ENV = 'node'; -} -exports.DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version_1.version}` }; -exports.DEFAULT_GLOBAL_OPTIONS = { - headers: exports.DEFAULT_HEADERS, -}; -exports.DEFAULT_DB_OPTIONS = { - schema: 'public', -}; -exports.DEFAULT_AUTH_OPTIONS = { - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true, - flowType: 'implicit', -}; -exports.DEFAULT_REALTIME_OPTIONS = {}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 50785: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; -// @ts-ignore -const node_fetch_1 = __importStar(__nccwpck_require__(93149)); -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = node_fetch_1.default; - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -const resolveHeadersConstructor = () => { - if (typeof Headers === 'undefined') { - return node_fetch_1.Headers; - } - return Headers; -}; -exports.resolveHeadersConstructor = resolveHeadersConstructor; -const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { - const fetch = (0, exports.resolveFetch)(customFetch); - const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); - return async (input, init) => { - var _a; - const accessToken = (_a = (await getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; - let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); - if (!headers.has('apikey')) { - headers.set('apikey', supabaseKey); - } - if (!headers.has('Authorization')) { - headers.set('Authorization', `Bearer ${accessToken}`); - } - return fetch(input, Object.assign(Object.assign({}, init), { headers })); - }; -}; -exports.fetchWithAuth = fetchWithAuth; -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 3575: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBrowser = void 0; -exports.uuid = uuid; -exports.ensureTrailingSlash = ensureTrailingSlash; -exports.applySettingDefaults = applySettingDefaults; -exports.validateSupabaseUrl = validateSupabaseUrl; -function uuid() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -} -function ensureTrailingSlash(url) { - return url.endsWith('/') ? url : url + '/'; -} -const isBrowser = () => typeof window !== 'undefined'; -exports.isBrowser = isBrowser; -function applySettingDefaults(options, defaults) { - var _a, _b; - const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; - const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; - const result = { - db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), - auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), - realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), - storage: {}, - global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, ((_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {})), ((_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {})) }), - accessToken: async () => '', - }; - if (options.accessToken) { - result.accessToken = options.accessToken; - } - else { - // hack around Required<> - delete result.accessToken; - } - return result; -} -/** - * Validates a Supabase client URL - * - * @param {string} supabaseUrl - The Supabase client URL string. - * @returns {URL} - The validated base URL. - * @throws {Error} - */ -function validateSupabaseUrl(supabaseUrl) { - const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); - if (!trimmedUrl) { - throw new Error('supabaseUrl is required.'); - } - if (!trimmedUrl.match(/^https?:\/\//i)) { - throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.'); - } - try { - return new URL(ensureTrailingSlash(trimmedUrl)); - } - catch (_a) { - throw Error('Invalid supabaseUrl: Provided URL is malformed.'); - } -} -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 86136: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 22225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const stringWidth = __nccwpck_require__(95537) - -function ansiAlign (text, opts) { - if (!text) return text - - opts = opts || {} - const align = opts.align || 'center' - - // short-circuit `align: 'left'` as no-op - if (align === 'left') return text - - const split = opts.split || '\n' - const pad = opts.pad || ' ' - const widthDiffFn = align !== 'right' ? halfDiff : fullDiff - - let returnString = false - if (!Array.isArray(text)) { - returnString = true - text = String(text).split(split) - } - - let width - let maxWidth = 0 - text = text.map(function (str) { - str = String(str) - width = stringWidth(str) - maxWidth = Math.max(width, maxWidth) - return { - str, - width - } - }).map(function (obj) { - return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str - }) - - return returnString ? text.join(split) : text -} - -ansiAlign.left = function left (text) { - return ansiAlign(text, { align: 'left' }) -} - -ansiAlign.center = function center (text) { - return ansiAlign(text, { align: 'center' }) -} - -ansiAlign.right = function right (text) { - return ansiAlign(text, { align: 'right' }) -} - -module.exports = ansiAlign - -function halfDiff (maxWidth, curWidth) { - return Math.floor((maxWidth - curWidth) / 2) -} - -function fullDiff (maxWidth, curWidth) { - return maxWidth - curWidth -} - - -/***/ }), - -/***/ 50140: -/***/ ((module) => { - -"use strict"; - - -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; - - -/***/ }), - -/***/ 13652: -/***/ ((module) => { - -"use strict"; - - -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; -}; - - -/***/ }), - -/***/ 95537: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const stripAnsi = __nccwpck_require__(91411); -const isFullwidthCodePoint = __nccwpck_require__(64882); -const emojiRegex = __nccwpck_require__(13652); - -const stringWidth = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; -}; - -module.exports = stringWidth; -// TODO: remove this in the next major version -module.exports["default"] = stringWidth; - - -/***/ }), - -/***/ 91411: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const ansiRegex = __nccwpck_require__(50140); - -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; - - -/***/ }), - -/***/ 99348: -/***/ ((module) => { - -// 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 - -}; - - -/***/ }), - -/***/ 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); -} - - -/***/ }), - -/***/ 91403: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -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 Stream = (__nccwpck_require__(12781).Stream); -var crypto = __nccwpck_require__(6113); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var setToStringTag = __nccwpck_require__(11770); -var hasOwn = __nccwpck_require__(62157); -var populate = __nccwpck_require__(47027); - -/** - * 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(options); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); - - options = options || {}; // eslint-disable-line no-param-reassign - for (var option in options) { // eslint-disable-line no-restricted-syntax - this[option] = options[option]; - } -} - -// make it a Stream -util.inherits(FormData, CombinedStream); - -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function (field, value, options) { - options = options || {}; // eslint-disable-line no-param-reassign - - // allow filename as single option - if (typeof options === 'string') { - options = { filename: options }; // eslint-disable-line no-param-reassign - } - - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value === 'number' || value == null) { - value = String(value); // eslint-disable-line no-param-reassign - } - - // https://github.com/felixge/node-form-data/issues/38 - if (Array.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 += Number(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 or not a stream - if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')) && !(value instanceof Stream))) { - return; - } - - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; - -FormData.prototype._lengthRetriever = function (value, callback) { - if (hasOwn(value, '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)); // eslint-disable-line callback-return - - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function (err, stat) { - if (err) { - callback(err); - return; - } - - // update final size based on the range options - var fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - - // or http response - } else if (hasOwn(value, 'httpVersion')) { - callback(null, Number(value.headers['content-length'])); // eslint-disable-line callback-return - - // or request stream http://github.com/mikeal/request - } else if (hasOwn(value, 'httpModule')) { - // wait till response come back - value.on('response', function (response) { - value.pause(); - callback(null, Number(response.headers['content-length'])); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); // eslint-disable-line callback-return - } -}; - -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) { // eslint-disable-line no-restricted-syntax - if (hasOwn(headers, prop)) { - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; // eslint-disable-line no-restricted-syntax, no-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) { // eslint-disable-line consistent-return - var filename; - - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || (value && (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 && (value.name || value.path))); - } else if (value && value.readable && hasOwn(value, 'httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } - - if (filename) { - return 'filename="' + filename + '"'; - } -}; - -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 && value.name) { - contentType = mime.lookup(value.name); - } - - // or try `path` from fs-, request- streams - if (!contentType && value && value.path) { - contentType = mime.lookup(value.path); - } - - // or if it's http-reponse - if (!contentType && value && value.readable && hasOwn(value, '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 && value && 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) { // eslint-disable-line no-restricted-syntax - if (hasOwn(userHeaders, header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - - return formHeaders; -}; - -FormData.prototype.setBoundary = function (boundary) { - if (typeof boundary !== 'string') { - throw new TypeError('FormData boundary must be a string'); - } - this._boundary = boundary; -}; - -FormData.prototype.getBoundary = function () { - if (!this._boundary) { - this._generateBoundary(); - } - - return this._boundary; -}; - -FormData.prototype.getBuffer = function () { - var dataBuffer = new Buffer.alloc(0); // eslint-disable-line new-cap - var boundary = this.getBoundary(); - - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - // Add content to the buffer. - if (Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); - } else { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); - } - - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData.LINE_BREAK)]); - } - } - } - - // Add the footer and return the Buffer object. - return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); -}; - -FormData.prototype._generateBoundary = function () { - // This generates a 50 character boundary similar to those used by Firefox. - - // They are optimized for boyer-moore parsing. - this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); -}; - -// 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; - var options; - var defaults = { method: 'post' }; - - // parse provided url if it's string or treat it as options object - if (typeof params === 'string') { - params = parseUrl(params); // eslint-disable-line no-param-reassign - /* eslint sort-keys: 0 */ - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - } else { // use custom params - 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 && err !== 'Unknown stream') { - this._error(err); - return; - } - - // add content length - if (length) { - request.setHeader('Content-Length', length); - } - - this.pipe(request); - if (cb) { - var onResponse; - - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); - - return cb.call(this, error, responce); // eslint-disable-line no-invalid-this - }; - - onResponse = callback.bind(this, null); - - request.on('error', callback); - request.on('response', onResponse); - } - }.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]'; -}; -setToStringTag(FormData, 'FormData'); - -// Public API -module.exports = FormData; - - -/***/ }), - -/***/ 47027: -/***/ ((module) => { - -"use strict"; - - -// populates missing values -module.exports = function (dst, src) { - Object.keys(src).forEach(function (prop) { - dst[prop] = dst[prop] || src[prop]; // eslint-disable-line no-param-reassign - }); - - return dst; -}; - - -/***/ }), - -/***/ 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); -} - - -/***/ }), - -/***/ 23664: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Buffer } = __nccwpck_require__(14300) -const symbol = Symbol.for('BufferList') - -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) - } - - BufferList._init.call(this, buf) -} - -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) - - this._bufs = [] - this.length = 0 - - if (buf) { - this.append(buf) - } -} - -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) -} - -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] - } - - let tot = 0 - - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] - } - tot = _t - } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] - - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - - return offset -} - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - - const offset = this._offset(index) - - return this._bufs[offset[0]][offset[1]] -} - -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length - } - - if (typeof end === 'number' && end < 0) { - end += this.length - } - - return this.copy(null, 0, start, end) -} - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } - - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } - - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } - - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } - - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] - - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } - - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } - - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start - - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } - - bytes -= l - - if (start) { - start = 0 - } - } - - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) - - return dst -} - -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - - if (start < 0) { - start += this.length - } - - if (end < 0) { - end += this.length - } - - if (start === end) { - return this._new() - } - - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - - if (endOffset[1] === 0) { - buffers.pop() - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) - } - - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } - - return this._new(buffers) -} - -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} - -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this - - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } - - return this -} - -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() - - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) - } - - return copy -} - -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this - } - - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() - } - - this._appendBuffer(Buffer.from(buf)) - } - - return this -} - -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} - -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } - - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - - offset = Number(offset || 0) - - if (isNaN(offset)) { - offset = 0 - } - - if (offset < 0) { - offset = this.length + offset - } - - if (offset < 0) { - offset = 0 - } - - if (search.length === 0) { - return offset > this.length ? this.length : offset - } - - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on - - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] - - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset - - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) - - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } - - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) - - if (this._match(revOffset, search)) { - return revOffset - } - - buffOffset++ - } - } - - buffOffset = 0 - } - - return -1 -} - -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } - - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false - } - } - return true -} - -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - } - - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) - -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) -} - -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] -} - -module.exports = BufferList - - -/***/ }), - -/***/ 20336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const DuplexStream = (__nccwpck_require__(51642).Duplex) -const inherits = __nccwpck_require__(44124) -const BufferList = __nccwpck_require__(23664) - -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) - } - - if (typeof callback === 'function') { - this._callback = callback - - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) - - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - - callback = null - } - - BufferList._init.call(this, callback) - DuplexStream.call(this) -} - -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) - -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) -} - -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback === 'function') { - callback() - } -} - -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } - - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} - -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} - -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} - -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} - -BufferListStream.isBufferList = BufferList.isBufferList - -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList - - -/***/ }), - -/***/ 19227: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var bind = __nccwpck_require__(88334); - -var $apply = __nccwpck_require__(54177); -var $call = __nccwpck_require__(2808); -var $reflectApply = __nccwpck_require__(48309); - -/** @type {import('./actualApply')} */ -module.exports = $reflectApply || bind.call($call, $apply); - - -/***/ }), - -/***/ 54177: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./functionApply')} */ -module.exports = Function.prototype.apply; - - -/***/ }), - -/***/ 2808: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./functionCall')} */ -module.exports = Function.prototype.call; - - -/***/ }), - -/***/ 86815: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var bind = __nccwpck_require__(88334); -var $TypeError = __nccwpck_require__(6361); - -var $call = __nccwpck_require__(2808); -var $actualApply = __nccwpck_require__(19227); - -/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ -module.exports = function callBindBasic(args) { - if (args.length < 1 || typeof args[0] !== 'function') { - throw new $TypeError('a function is required'); - } - return $actualApply(bind, $call, args); -}; - - -/***/ }), - -/***/ 48309: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./reflectApply')} */ -module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; - - -/***/ }), - -/***/ 82983: -/***/ ((module, exports) => { - -// Chance.js 1.1.12 -// https://chancejs.com -// (c) 2013 Victor Quinn -// Chance may be freely distributed or modified under the MIT license. - -(function () { - - // Constants - var MAX_INT = 9007199254740992; - var MIN_INT = -MAX_INT; - var NUMBERS = '0123456789'; - var CHARS_LOWER = 'abcdefghijklmnopqrstuvwxyz'; - var CHARS_UPPER = CHARS_LOWER.toUpperCase(); - var HEX_POOL = NUMBERS + "abcdef"; - - // Errors - function UnsupportedError(message) { - this.name = 'UnsupportedError'; - this.message = message || 'This feature is not supported on this platform'; - } - - UnsupportedError.prototype = new Error(); - UnsupportedError.prototype.constructor = UnsupportedError; - - // Cached array helpers - var slice = Array.prototype.slice; - - // Constructor - function Chance (seed) { - if (!(this instanceof Chance)) { - if (!seed) { seed = null; } // handle other non-truthy seeds, as described in issue #322 - return seed === null ? new Chance() : new Chance(seed); - } - - // if user has provided a function, use that as the generator - if (typeof seed === 'function') { - this.random = seed; - return this; - } - - if (arguments.length) { - // set a starting value of zero so we can add to it - this.seed = 0; - } - - // otherwise, leave this.seed blank so that MT will receive a blank - - for (var i = 0; i < arguments.length; i++) { - var seedling = 0; - if (Object.prototype.toString.call(arguments[i]) === '[object String]') { - for (var j = 0; j < arguments[i].length; j++) { - // create a numeric hash for each argument, add to seedling - var hash = 0; - for (var k = 0; k < arguments[i].length; k++) { - hash = arguments[i].charCodeAt(k) + (hash << 6) + (hash << 16) - hash; - } - seedling += hash; - } - } else { - seedling = arguments[i]; - } - this.seed += (arguments.length - i) * seedling; - } - - // If no generator function was provided, use our MT - this.mt = this.mersenne_twister(this.seed); - this.bimd5 = this.blueimp_md5(); - this.random = function () { - return this.mt.random(this.seed); - }; - - return this; - } - - Chance.prototype.VERSION = "1.1.13"; - - // Random helper functions - function initOptions(options, defaults) { - options = options || {}; - - if (defaults) { - for (var i in defaults) { - if (typeof options[i] === 'undefined') { - options[i] = defaults[i]; - } - } - } - - return options; - } - - function range(size) { - return Array.apply(null, Array(size)).map(function (_, i) {return i;}); - } - - function testRange(test, errorMessage) { - if (test) { - throw new RangeError(errorMessage); - } - } - - /** - * Encode the input string with Base64. - */ - var base64 = function() { - throw new Error('No Base64 encoder available.'); - }; - - // Select proper Base64 encoder. - (function determineBase64Encoder() { - if (typeof btoa === 'function') { - base64 = btoa; - } else if (typeof Buffer === 'function') { - base64 = function(input) { - return new Buffer(input).toString('base64'); - }; - } - })(); - - // -- Basics -- - - /** - * Return a random bool, either true or false - * - * @param {Object} [options={ likelihood: 50 }] alter the likelihood of - * receiving a true or false value back. - * @throws {RangeError} if the likelihood is out of bounds - * @returns {Bool} either true or false - */ - Chance.prototype.bool = function (options) { - // likelihood of success (true) - options = initOptions(options, {likelihood : 50}); - - // Note, we could get some minor perf optimizations by checking range - // prior to initializing defaults, but that makes code a bit messier - // and the check more complicated as we have to check existence of - // the object then existence of the key before checking constraints. - // Since the options initialization should be minor computationally, - // decision made for code cleanliness intentionally. This is mentioned - // here as it's the first occurrence, will not be mentioned again. - testRange( - options.likelihood < 0 || options.likelihood > 100, - "Chance: Likelihood accepts values from 0 to 100." - ); - - return this.random() * 100 < options.likelihood; - }; - - Chance.prototype.falsy = function (options) { - // return a random falsy value - options = initOptions(options, {pool: [false, null, 0, NaN, '', undefined]}) - var pool = options.pool, - index = this.integer({min: 0, max: pool.length - 1}), - value = pool[index]; - - return value; - } - - Chance.prototype.animal = function (options){ - //returns a random animal - options = initOptions(options); - - if(typeof options.type !== 'undefined'){ - //if user does not put in a valid animal type, user will get an error - testRange( - !this.get("animals")[options.type.toLowerCase()], - "Please pick from desert, ocean, grassland, forest, zoo, pets, farm." - ); - //if user does put in valid animal type, will return a random animal of that type - return this.pick(this.get("animals")[options.type.toLowerCase()]); - } - //if user does not put in any animal type, will return a random animal regardless - var animalTypeArray = ["desert","forest","ocean","zoo","farm","pet","grassland"]; - return this.pick(this.get("animals")[this.pick(animalTypeArray)]); - }; - - /** - * Return a random character. - * - * @param {Object} [options={}] can specify a character pool or alpha, - * numeric, symbols and casing (lower or upper) - * @returns {String} a single random character - */ - Chance.prototype.character = function (options) { - options = initOptions(options); - - var symbols = "!@#$%^&*()[]", - letters, pool; - - if (options.casing === 'lower') { - letters = CHARS_LOWER; - } else if (options.casing === 'upper') { - letters = CHARS_UPPER; - } else { - letters = CHARS_LOWER + CHARS_UPPER; - } - - if (options.pool) { - pool = options.pool; - } else { - pool = ''; - if (options.alpha) { - pool += letters; - } - if (options.numeric) { - pool += NUMBERS; - } - if (options.symbols) { - pool += symbols; - } - if (!pool) { - pool = letters + NUMBERS + symbols; - } - } - - return pool.charAt(this.natural({max: (pool.length - 1)})); - }; - - // Note, wanted to use "float" or "double" but those are both JS reserved words. - - // Note, fixed means N OR LESS digits after the decimal. This because - // It could be 14.9000 but in JavaScript, when this is cast as a number, - // the trailing zeroes are dropped. Left to the consumer if trailing zeroes are - // needed - /** - * Return a random floating point number - * - * @param {Object} [options={}] can specify a fixed precision, min, max - * @returns {Number} a single floating point number - * @throws {RangeError} Can only specify fixed or precision, not both. Also - * min cannot be greater than max - */ - Chance.prototype.floating = function (options) { - options = initOptions(options, {fixed : 4}); - testRange( - options.fixed && options.precision, - "Chance: Cannot specify both fixed and precision." - ); - - var num; - var fixed = Math.pow(10, options.fixed); - - var max = MAX_INT / fixed; - var min = -max; - - testRange( - options.min && options.fixed && options.min < min, - "Chance: Min specified is out of range with fixed. Min should be, at least, " + min - ); - testRange( - options.max && options.fixed && options.max > max, - "Chance: Max specified is out of range with fixed. Max should be, at most, " + max - ); - - options = initOptions(options, { min : min, max : max }); - - // Todo - Make this work! - // options.precision = (typeof options.precision !== "undefined") ? options.precision : false; - - num = this.integer({min: options.min * fixed, max: options.max * fixed}); - var num_fixed = (num / fixed).toFixed(options.fixed); - - return parseFloat(num_fixed); - }; - - /** - * Return a random integer - * - * NOTE the max and min are INCLUDED in the range. So: - * chance.integer({min: 1, max: 3}); - * would return either 1, 2, or 3. - * - * @param {Object} [options={}] can specify a min and/or max - * @returns {Number} a single random integer number - * @throws {RangeError} min cannot be greater than max - */ - Chance.prototype.integer = function (options) { - // 9007199254740992 (2^53) is the max integer number in JavaScript - // See: http://vq.io/132sa2j - options = initOptions(options, {min: MIN_INT, max: MAX_INT}); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - return Math.floor(this.random() * (options.max - options.min + 1) + options.min); - }; - - /** - * Return a random natural - * - * NOTE the max and min are INCLUDED in the range. So: - * chance.natural({min: 1, max: 3}); - * would return either 1, 2, or 3. - * - * @param {Object} [options={}] can specify a min and/or max or a numerals count. - * @returns {Number} a single random integer number - * @throws {RangeError} min cannot be greater than max - */ - Chance.prototype.natural = function (options) { - options = initOptions(options, {min: 0, max: MAX_INT}); - if (typeof options.numerals === 'number'){ - testRange(options.numerals < 1, "Chance: Numerals cannot be less than one."); - options.min = Math.pow(10, options.numerals - 1); - options.max = Math.pow(10, options.numerals) - 1; - } - testRange(options.min < 0, "Chance: Min cannot be less than zero."); - - if (options.exclude) { - testRange(!Array.isArray(options.exclude), "Chance: exclude must be an array.") - - for (var exclusionIndex in options.exclude) { - testRange(!Number.isInteger(options.exclude[exclusionIndex]), "Chance: exclude must be numbers.") - } - - var random = options.min + this.natural({max: options.max - options.min - options.exclude.length}) - var sortedExclusions = options.exclude.sort((a, b) => a - b); - for (var sortedExclusionIndex in sortedExclusions) { - if (random < sortedExclusions[sortedExclusionIndex]) { - break - } - random++ - } - return random - } - return this.integer(options); - }; - - /** - * Return a random prime number - * - * NOTE the max and min are INCLUDED in the range. - * - * @param {Object} [options={}] can specify a min and/or max - * @returns {Number} a single random prime number - * @throws {RangeError} min cannot be greater than max nor negative - */ - Chance.prototype.prime = function (options) { - options = initOptions(options, {min: 0, max: 10000}); - testRange(options.min < 0, "Chance: Min cannot be less than zero."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - var lastPrime = data.primes[data.primes.length - 1]; - if (options.max > lastPrime) { - for (var i = lastPrime + 2; i <= options.max; ++i) { - if (this.is_prime(i)) { - data.primes.push(i); - } - } - } - var targetPrimes = data.primes.filter(function (prime) { - return prime >= options.min && prime <= options.max; - }); - return this.pick(targetPrimes); - }; - - /** - * Determine whether a given number is prime or not. - */ - Chance.prototype.is_prime = function (n) { - if (n % 1 || n < 2) { - return false; - } - if (n % 2 === 0) { - return n === 2; - } - if (n % 3 === 0) { - return n === 3; - } - var m = Math.sqrt(n); - for (var i = 5; i <= m; i += 6) { - if (n % i === 0 || n % (i + 2) === 0) { - return false; - } - } - return true; - }; - - /** - * Return a random hex number as string - * - * NOTE the max and min are INCLUDED in the range. So: - * chance.hex({min: '9', max: 'B'}); - * would return either '9', 'A' or 'B'. - * - * @param {Object} [options={}] can specify a min and/or max and/or casing - * @returns {String} a single random string hex number - * @throws {RangeError} min cannot be greater than max - */ - Chance.prototype.hex = function (options) { - options = initOptions(options, {min: 0, max: MAX_INT, casing: 'lower'}); - testRange(options.min < 0, "Chance: Min cannot be less than zero."); - var integer = this.natural({min: options.min, max: options.max}); - if (options.casing === 'upper') { - return integer.toString(16).toUpperCase(); - } - return integer.toString(16); - }; - - Chance.prototype.letter = function(options) { - options = initOptions(options, {casing: 'lower'}); - var pool = "abcdefghijklmnopqrstuvwxyz"; - var letter = this.character({pool: pool}); - if (options.casing === 'upper') { - letter = letter.toUpperCase(); - } - return letter; - } - - /** - * Return a random string - * - * @param {Object} [options={}] can specify a length or min and max - * @returns {String} a string of random length - * @throws {RangeError} length cannot be less than zero - */ - Chance.prototype.string = function (options) { - options = initOptions(options, { min: 5, max: 20 }); - - if (options.length !== 0 && !options.length) { - options.length = this.natural({ min: options.min, max: options.max }) - } - - testRange(options.length < 0, "Chance: Length cannot be less than zero."); - var length = options.length, - text = this.n(this.character, length, options); - - return text.join(""); - }; - - function CopyToken(c) { - this.c = c - } - - CopyToken.prototype = { - substitute: function () { - return this.c - } - } - - function EscapeToken(c) { - this.c = c - } - - EscapeToken.prototype = { - substitute: function () { - if (!/[{}\\]/.test(this.c)) { - throw new Error('Invalid escape sequence: "\\' + this.c + '".') - } - return this.c - } - } - - function ReplaceToken(c) { - this.c = c - } - - ReplaceToken.prototype = { - replacers: { - '#': function (chance) { return chance.character({ pool: NUMBERS }) }, - 'A': function (chance) { return chance.character({ pool: CHARS_UPPER }) }, - 'a': function (chance) { return chance.character({ pool: CHARS_LOWER }) }, - }, - - substitute: function (chance) { - var replacer = this.replacers[this.c] - if (!replacer) { - throw new Error('Invalid replacement character: "' + this.c + '".') - } - return replacer(chance) - } - } - - function parseTemplate(template) { - var tokens = [] - var mode = 'identity' - for (var i = 0; i MAX_DUPLICATES) { - throw new RangeError("Chance: num is likely too large for sample set"); - } - } - return arr; - }; - - /** - * Gives an array of n random terms - * - * @param {Function} fn the function that generates something random - * @param {Number} n number of terms to generate - * @returns {Array} an array of length `n` with items generated by `fn` - * - * There can be more parameters after these. All additional parameters are provided to the given function - */ - Chance.prototype.n = function(fn, n) { - testRange( - typeof fn !== "function", - "Chance: The first argument must be a function." - ); - - if (typeof n === 'undefined') { - n = 1; - } - var i = n, arr = [], params = slice.call(arguments, 2); - - // Providing a negative count should result in a noop. - i = Math.max( 0, i ); - - for (null; i--; null) { - arr.push(fn.apply(this, params)); - } - - return arr; - }; - - // H/T to SO for this one: http://vq.io/OtUrZ5 - Chance.prototype.pad = function (number, width, pad) { - // Default pad to 0 if none provided - pad = pad || '0'; - // Convert number to a string - number = number + ''; - return number.length >= width ? number : new Array(width - number.length + 1).join(pad) + number; - }; - - // DEPRECATED on 2015-10-01 - Chance.prototype.pick = function (arr, count) { - if (arr.length === 0) { - throw new RangeError("Chance: Cannot pick() from an empty array"); - } - if (!count || count === 1) { - return arr[this.natural({max: arr.length - 1})]; - } else { - return this.shuffle(arr).slice(0, count); - } - }; - - // Given an array, returns a single random element - Chance.prototype.pickone = function (arr) { - if (arr.length === 0) { - throw new RangeError("Chance: Cannot pickone() from an empty array"); - } - return arr[this.natural({max: arr.length - 1})]; - }; - - // Given an array, returns a random set with 'count' elements - Chance.prototype.pickset = function (arr, count) { - if (count === 0) { - return []; - } - if (arr.length === 0) { - throw new RangeError("Chance: Cannot pickset() from an empty array"); - } - if (count < 0) { - throw new RangeError("Chance: Count must be a positive number"); - } - if (!count || count === 1) { - return [ this.pickone(arr) ]; - } else { - var array = arr.slice(0); - var end = array.length; - - return this.n(function () { - var index = this.natural({max: --end}); - var value = array[index]; - array[index] = array[end]; - return value; - }, Math.min(end, count)); - } - }; - - Chance.prototype.shuffle = function (arr) { - var new_array = [], - j = 0, - length = Number(arr.length), - source_indexes = range(length), - last_source_index = length - 1, - selected_source_index; - - for (var i = 0; i < length; i++) { - // Pick a random index from the array - selected_source_index = this.natural({max: last_source_index}); - j = source_indexes[selected_source_index]; - - // Add it to the new array - new_array[i] = arr[j]; - - // Mark the source index as used - source_indexes[selected_source_index] = source_indexes[last_source_index]; - last_source_index -= 1; - } - - return new_array; - }; - - // Returns a single item from an array with relative weighting of odds - Chance.prototype.weighted = function (arr, weights, trim) { - if (arr.length !== weights.length) { - throw new RangeError("Chance: Length of array and weights must match"); - } - - // scan weights array and sum valid entries - var sum = 0; - var val; - for (var weightIndex = 0; weightIndex < weights.length; ++weightIndex) { - val = weights[weightIndex]; - if (isNaN(val)) { - throw new RangeError("Chance: All weights must be numbers"); - } - - if (val > 0) { - sum += val; - } - } - - if (sum === 0) { - throw new RangeError("Chance: No valid entries in array weights"); - } - - // select a value within range - var selected = this.random() * sum; - - // find array entry corresponding to selected value - var total = 0; - var lastGoodIdx = -1; - var chosenIdx; - for (weightIndex = 0; weightIndex < weights.length; ++weightIndex) { - val = weights[weightIndex]; - total += val; - if (val > 0) { - if (selected <= total) { - chosenIdx = weightIndex; - break; - } - lastGoodIdx = weightIndex; - } - - // handle any possible rounding error comparison to ensure something is picked - if (weightIndex === (weights.length - 1)) { - chosenIdx = lastGoodIdx; - } - } - - var chosen = arr[chosenIdx]; - trim = (typeof trim === 'undefined') ? false : trim; - if (trim) { - arr.splice(chosenIdx, 1); - weights.splice(chosenIdx, 1); - } - - return chosen; - }; - - // -- End Helpers -- - - // -- Text -- - - Chance.prototype.paragraph = function (options) { - options = initOptions(options); - - var sentences = options.sentences || this.natural({min: 3, max: 7}), - sentence_array = this.n(this.sentence, sentences), - separator = options.linebreak === true ? '\n' : ' '; - - return sentence_array.join(separator); - }; - - // Could get smarter about this than generating random words and - // chaining them together. Such as: http://vq.io/1a5ceOh - Chance.prototype.sentence = function (options) { - options = initOptions(options); - - var words = options.words || this.natural({min: 12, max: 18}), - punctuation = options.punctuation, - text, word_array = this.n(this.word, words); - - text = word_array.join(' '); - - // Capitalize first letter of sentence - text = this.capitalize(text); - - // Make sure punctuation has a usable value - if (punctuation !== false && !/^[.?;!:]$/.test(punctuation)) { - punctuation = '.'; - } - - // Add punctuation mark - if (punctuation) { - text += punctuation; - } - - return text; - }; - - Chance.prototype.syllable = function (options) { - options = initOptions(options); - - var length = options.length || this.natural({min: 2, max: 3}), - consonants = 'bcdfghjklmnprstvwz', // consonants except hard to speak ones - vowels = 'aeiou', // vowels - all = consonants + vowels, // all - text = '', - chr; - - // I'm sure there's a more elegant way to do this, but this works - // decently well. - for (var i = 0; i < length; i++) { - if (i === 0) { - // First character can be anything - chr = this.character({pool: all}); - } else if (consonants.indexOf(chr) === -1) { - // Last character was a vowel, now we want a consonant - chr = this.character({pool: consonants}); - } else { - // Last character was a consonant, now we want a vowel - chr = this.character({pool: vowels}); - } - - text += chr; - } - - if (options.capitalize) { - text = this.capitalize(text); - } - - return text; - }; - - Chance.prototype.word = function (options) { - options = initOptions(options); - - testRange( - options.syllables && options.length, - "Chance: Cannot specify both syllables AND length." - ); - - var syllables = options.syllables || this.natural({min: 1, max: 3}), - text = ''; - - if (options.length) { - // Either bound word by length - do { - text += this.syllable(); - } while (text.length < options.length); - text = text.substring(0, options.length); - } else { - // Or by number of syllables - for (var i = 0; i < syllables; i++) { - text += this.syllable(); - } - } - - if (options.capitalize) { - text = this.capitalize(text); - } - - return text; - }; - - Chance.prototype.emoji = function (options) { - options = initOptions(options, { category: "all", length: 1 }); - - testRange( - options.length < 1 || BigInt(options.length) > BigInt(MAX_INT), - "Chance: length must be between 1 and " + String(MAX_INT) - ); - - var emojis = this.get("emojis"); - - if (options.category === "all") { - options.category = this.pickone(Object.keys(emojis)); - } - - var emojisForCategory = emojis[options.category]; - - testRange( - emojisForCategory === undefined, - "Chance: Unrecognised emoji category: [" + options.category + "]." - ); - - return this.pickset(emojisForCategory, options.length) - .map(function (codePoint) { - return String.fromCodePoint(codePoint); - }).join(""); - }; - - // -- End Text -- - - // -- Person -- - - Chance.prototype.age = function (options) { - options = initOptions(options); - var ageRange; - - switch (options.type) { - case 'child': - ageRange = {min: 0, max: 12}; - break; - case 'teen': - ageRange = {min: 13, max: 19}; - break; - case 'adult': - ageRange = {min: 18, max: 65}; - break; - case 'senior': - ageRange = {min: 65, max: 100}; - break; - case 'all': - ageRange = {min: 0, max: 100}; - break; - default: - ageRange = {min: 18, max: 65}; - break; - } - - return this.natural(ageRange); - }; - - Chance.prototype.birthday = function (options) { - var age = this.age(options); - var now = new Date() - var currentYear = now.getFullYear(); - - if (options && options.type) { - var min = new Date(); - var max = new Date(); - min.setFullYear(currentYear - age - 1); - max.setFullYear(currentYear - age); - - options = initOptions(options, { - min: min, - max: max - }); - } else if (options && ((options.minAge !== undefined) || (options.maxAge !== undefined))) { - testRange(options.minAge < 0, "Chance: MinAge cannot be less than zero."); - testRange(options.minAge > options.maxAge, "Chance: MinAge cannot be greater than MaxAge."); - - var minAge = options.minAge !== undefined ? options.minAge : 0; - var maxAge = options.maxAge !== undefined ? options.maxAge : 100; - - var minDate = new Date(currentYear - maxAge - 1, now.getMonth(), now.getDate()); - var maxDate = new Date(currentYear - minAge, now.getMonth(), now.getDate()); - - minDate.setDate(minDate.getDate() +1); - - maxDate.setDate(maxDate.getDate() +1); - maxDate.setMilliseconds(maxDate.getMilliseconds() -1); - - options = initOptions(options, { - min: minDate, - max: maxDate - }); - } else { - options = initOptions(options, { - year: currentYear - age - }); - } - - return this.date(options); - }; - - // CPF; ID to identify taxpayers in Brazil - Chance.prototype.cpf = function (options) { - options = initOptions(options, { - formatted: true - }); - - var n = this.n(this.natural, 9, { max: 9 }); - var d1 = n[8]*2+n[7]*3+n[6]*4+n[5]*5+n[4]*6+n[3]*7+n[2]*8+n[1]*9+n[0]*10; - d1 = 11 - (d1 % 11); - if (d1>=10) { - d1 = 0; - } - var d2 = d1*2+n[8]*3+n[7]*4+n[6]*5+n[5]*6+n[4]*7+n[3]*8+n[2]*9+n[1]*10+n[0]*11; - d2 = 11 - (d2 % 11); - if (d2>=10) { - d2 = 0; - } - var cpf = ''+n[0]+n[1]+n[2]+'.'+n[3]+n[4]+n[5]+'.'+n[6]+n[7]+n[8]+'-'+d1+d2; - return options.formatted ? cpf : cpf.replace(/\D/g,''); - }; - - // CNPJ: ID to identify companies in Brazil - Chance.prototype.cnpj = function (options) { - options = initOptions(options, { - formatted: true - }); - - var n = this.n(this.natural, 12, { max: 12 }); - var d1 = n[11]*2+n[10]*3+n[9]*4+n[8]*5+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; - d1 = 11 - (d1 % 11); - if (d1<2) { - d1 = 0; - } - var d2 = d1*2+n[11]*3+n[10]*4+n[9]*5+n[8]*6+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; - d2 = 11 - (d2 % 11); - if (d2<2) { - d2 = 0; - } - var cnpj = ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/'+n[8]+n[9]+n[10]+n[11]+'-'+d1+d2; - return options.formatted ? cnpj : cnpj.replace(/\D/g,''); - }; - - Chance.prototype.first = function (options) { - options = initOptions(options, {gender: this.gender(), nationality: 'en'}); - return this.pick(this.get("firstNames")[options.gender.toLowerCase()][options.nationality.toLowerCase()]); - }; - - Chance.prototype.profession = function (options) { - options = initOptions(options); - if(options.rank){ - return this.pick(['Apprentice ', 'Junior ', 'Senior ', 'Lead ']) + this.pick(this.get("profession")); - } else{ - return this.pick(this.get("profession")); - } - }; - - Chance.prototype.company = function (){ - return this.pick(this.get("company")); - }; - - Chance.prototype.gender = function (options) { - options = initOptions(options, {extraGenders: []}); - return this.pick(['Male', 'Female'].concat(options.extraGenders)); - }; - - Chance.prototype.last = function (options) { - options = initOptions(options, {nationality: '*'}); - if (options.nationality === "*") { - var allLastNames = [] - var lastNames = this.get("lastNames") - Object.keys(lastNames).forEach(function(key){ - allLastNames = allLastNames.concat(lastNames[key]) - }) - return this.pick(allLastNames) - } - else { - return this.pick(this.get("lastNames")[options.nationality.toLowerCase()]); - } - - }; - - Chance.prototype.israelId=function(){ - var x=this.string({pool: '0123456789',length:8}); - var y=0; - for (var i=0;i hex - * -> rgb - * -> rgba - * -> 0x - * -> named color - * - * #Examples: - * =============================================== - * * Geerate random hex color - * chance.color() => '#79c157' / 'rgb(110,52,164)' / '0x67ae0b' / '#e2e2e2' / '#29CFA7' - * - * * Generate Hex based color value - * chance.color({format: 'hex'}) => '#d67118' - * - * * Generate simple rgb value - * chance.color({format: 'rgb'}) => 'rgb(110,52,164)' - * - * * Generate Ox based color value - * chance.color({format: '0x'}) => '0x67ae0b' - * - * * Generate graiscale based value - * chance.color({grayscale: true}) => '#e2e2e2' - * - * * Return valide color name - * chance.color({format: 'name'}) => 'red' - * - * * Make color uppercase - * chance.color({casing: 'upper'}) => '#29CFA7' - * - * * Min Max values for RGBA - * var light_red = chance.color({format: 'hex', min_red: 200, max_red: 255, max_green: 0, max_blue: 0, min_alpha: .2, max_alpha: .3}); - * - * @param [object] options - * @return [string] color value - */ - Chance.prototype.color = function (options) { - function gray(value, delimiter) { - return [value, value, value].join(delimiter || ''); - } - - function rgb(hasAlpha) { - var rgbValue = (hasAlpha) ? 'rgba' : 'rgb'; - var alphaChannel = (hasAlpha) ? (',' + this.floating({min:min_alpha, max:max_alpha})) : ""; - var colorValue = (isGrayscale) ? (gray(this.natural({min: min_rgb, max: max_rgb}), ',')) : (this.natural({min: min_green, max: max_green}) + ',' + this.natural({min: min_blue, max: max_blue}) + ',' + this.natural({max: 255})); - return rgbValue + '(' + colorValue + alphaChannel + ')'; - } - - function hex(start, end, withHash) { - var symbol = (withHash) ? "#" : ""; - var hexstring = ""; - - if (isGrayscale) { - hexstring = gray(this.pad(this.hex({min: min_rgb, max: max_rgb}), 2)); - if (options.format === "shorthex") { - hexstring = gray(this.hex({min: 0, max: 15})); - } - } - else { - if (options.format === "shorthex") { - hexstring = this.pad(this.hex({min: Math.floor(min_red / 16), max: Math.floor(max_red / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_green / 16), max: Math.floor(max_green / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_blue / 16), max: Math.floor(max_blue / 16)}), 1); - } - else if (min_red !== undefined || max_red !== undefined || min_green !== undefined || max_green !== undefined || min_blue !== undefined || max_blue !== undefined) { - hexstring = this.pad(this.hex({min: min_red, max: max_red}), 2) + this.pad(this.hex({min: min_green, max: max_green}), 2) + this.pad(this.hex({min: min_blue, max: max_blue}), 2); - } - else { - hexstring = this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2); - } - } - - return symbol + hexstring; - } - - options = initOptions(options, { - format: this.pick(['hex', 'shorthex', 'rgb', 'rgba', '0x', 'name']), - grayscale: false, - casing: 'lower', - min: 0, - max: 255, - min_red: undefined, - max_red: undefined, - min_green: undefined, - max_green: undefined, - min_blue: undefined, - max_blue: undefined, - min_alpha: 0, - max_alpha: 1 - }); - - var isGrayscale = options.grayscale; - var min_rgb = options.min; - var max_rgb = options.max; - var min_red = options.min_red; - var max_red = options.max_red; - var min_green = options.min_green; - var max_green = options.max_green; - var min_blue = options.min_blue; - var max_blue = options.max_blue; - var min_alpha = options.min_alpha; - var max_alpha = options.max_alpha; - if (options.min_red === undefined) { min_red = min_rgb; } - if (options.max_red === undefined) { max_red = max_rgb; } - if (options.min_green === undefined) { min_green = min_rgb; } - if (options.max_green === undefined) { max_green = max_rgb; } - if (options.min_blue === undefined) { min_blue = min_rgb; } - if (options.max_blue === undefined) { max_blue = max_rgb; } - if (options.min_alpha === undefined) { min_alpha = 0; } - if (options.max_alpha === undefined) { max_alpha = 1; } - if (isGrayscale && min_rgb === 0 && max_rgb === 255 && min_red !== undefined && max_red !== undefined) { - min_rgb = ((min_red + min_green + min_blue) / 3); - max_rgb = ((max_red + max_green + max_blue) / 3); - } - var colorValue; - - if (options.format === 'hex') { - colorValue = hex.call(this, 2, 6, true); - } - else if (options.format === 'shorthex') { - colorValue = hex.call(this, 1, 3, true); - } - else if (options.format === 'rgb') { - colorValue = rgb.call(this, false); - } - else if (options.format === 'rgba') { - colorValue = rgb.call(this, true); - } - else if (options.format === '0x') { - colorValue = '0x' + hex.call(this, 2, 6); - } - else if(options.format === 'name') { - return this.pick(this.get("colorNames")); - } - else { - throw new RangeError('Invalid format provided. Please provide one of "hex", "shorthex", "rgb", "rgba", "0x" or "name".'); - } - - if (options.casing === 'upper' ) { - colorValue = colorValue.toUpperCase(); - } - - return colorValue; - }; - - Chance.prototype.domain = function (options) { - options = initOptions(options); - return this.word() + '.' + (options.tld || this.tld()); - }; - - Chance.prototype.email = function (options) { - options = initOptions(options); - return this.word({length: options.length}) + '@' + (options.domain || this.domain()); - }; - - /** - * #Description: - * =============================================== - * Generate a random Facebook id, aka fbid. - * - * NOTE: At the moment (Sep 2017), Facebook ids are - * "numeric strings" of length 16. - * However, Facebook Graph API documentation states that - * "it is extremely likely to change over time". - * @see https://developers.facebook.com/docs/graph-api/overview/ - * - * #Examples: - * =============================================== - * chance.fbid() => '1000035231661304' - * - * @return [string] facebook id - */ - Chance.prototype.fbid = function () { - return '10000' + this.string({pool: "1234567890", length: 11}); - }; - - Chance.prototype.google_analytics = function () { - var account = this.pad(this.natural({max: 999999}), 6); - var property = this.pad(this.natural({max: 99}), 2); - - return 'UA-' + account + '-' + property; - }; - - Chance.prototype.hashtag = function () { - return '#' + this.word(); - }; - - Chance.prototype.ip = function () { - // Todo: This could return some reserved IPs. See http://vq.io/137dgYy - // this should probably be updated to account for that rare as it may be - return this.natural({min: 1, max: 254}) + '.' + - this.natural({max: 255}) + '.' + - this.natural({max: 255}) + '.' + - this.natural({min: 1, max: 254}); - }; - - Chance.prototype.ipv6 = function () { - var ip_addr = this.n(this.hash, 8, {length: 4}); - - return ip_addr.join(":"); - }; - - Chance.prototype.klout = function () { - return this.natural({min: 1, max: 99}); - }; - - Chance.prototype.mac = function (options) { - // Todo: This could also be extended to EUI-64 based MACs - // (https://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml#ethernet-numbers-4) - // Todo: This can return some reserved MACs (similar to IP function) - // this should probably be updated to account for that rare as it may be - options = initOptions(options, { delimiter: ':' }); - return this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2); - }; - - Chance.prototype.semver = function (options) { - options = initOptions(options, { include_prerelease: true }); - - var range = this.pickone(["^", "~", "<", ">", "<=", ">=", "="]); - if (options.range) { - range = options.range; - } - - var prerelease = ""; - if (options.include_prerelease) { - prerelease = this.weighted(["", "-dev", "-beta", "-alpha"], [50, 10, 5, 1]); - } - return range + this.rpg('3d10').join('.') + prerelease; - }; - - Chance.prototype.tlds = function () { - return ['com', 'org', 'edu', 'gov', 'co.uk', 'net', 'io', 'ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as', 'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bv', 'bw', 'by', 'bz', 'ca', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr', 'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'ee', 'eg', 'eh', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo', 'fr', 'ga', 'gb', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht', 'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je', 'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw', 'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv', 'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo', 'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om', 'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt', 'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sj', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st', 'su', 'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us', 'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye', 'yt', 'za', 'zm', 'zw']; - }; - - Chance.prototype.tld = function () { - return this.pick(this.tlds()); - }; - - Chance.prototype.twitter = function () { - return '@' + this.word(); - }; - - Chance.prototype.url = function (options) { - options = initOptions(options, { protocol: "http", domain: this.domain(options), domain_prefix: "", path: this.word(), extensions: []}); - - var extension = options.extensions.length > 0 ? "." + this.pick(options.extensions) : ""; - var domain = options.domain_prefix ? options.domain_prefix + "." + options.domain : options.domain; - - return options.protocol + "://" + domain + "/" + options.path + extension; - }; - - Chance.prototype.port = function() { - return this.integer({min: 0, max: 65535}); - }; - - Chance.prototype.locale = function (options) { - options = initOptions(options); - if (options.region){ - return this.pick(this.get("locale_regions")); - } else { - return this.pick(this.get("locale_languages")); - } - }; - - Chance.prototype.locales = function (options) { - options = initOptions(options); - if (options.region){ - return this.get("locale_regions"); - } else { - return this.get("locale_languages"); - } - }; - - Chance.prototype.loremPicsum = function (options) { - options = initOptions(options, { width: 500, height: 500, greyscale: false, blurred: false }); - - var greyscale = options.greyscale ? 'g/' : ''; - var query = options.blurred ? '/?blur' : '/?random'; - - return 'https://picsum.photos/' + greyscale + options.width + '/' + options.height + query; - } - - // -- End Web -- - - // -- Location -- - - Chance.prototype.address = function (options) { - options = initOptions(options); - return this.natural({min: 5, max: 2000}) + ' ' + this.street(options); - }; - - Chance.prototype.altitude = function (options) { - options = initOptions(options, {fixed: 5, min: 0, max: 8848}); - return this.floating({ - min: options.min, - max: options.max, - fixed: options.fixed - }); - }; - - Chance.prototype.areacode = function (options) { - options = initOptions(options, {parens : true}); - // Don't want area codes to start with 1, or have a 9 as the second digit - var areacode = options.exampleNumber ? - "555" : - this.natural({min: 2, max: 9}).toString() + - this.natural({min: 0, max: 8}).toString() + - this.natural({min: 0, max: 9}).toString(); - - return options.parens ? '(' + areacode + ')' : areacode; - }; - - Chance.prototype.city = function () { - return this.capitalize(this.word({syllables: 3})); - }; - - Chance.prototype.coordinates = function (options) { - return this.latitude(options) + ', ' + this.longitude(options); - }; - - Chance.prototype.countries = function () { - return this.get("countries"); - }; - - Chance.prototype.country = function (options) { - options = initOptions(options); - var country = this.pick(this.countries()); - return options.raw ? country : options.full ? country.name : country.abbreviation; - }; - - Chance.prototype.depth = function (options) { - options = initOptions(options, {fixed: 5, min: -10994, max: 0}); - return this.floating({ - min: options.min, - max: options.max, - fixed: options.fixed - }); - }; - - Chance.prototype.geohash = function (options) { - options = initOptions(options, { length: 7 }); - return this.string({ length: options.length, pool: '0123456789bcdefghjkmnpqrstuvwxyz' }); - }; - - Chance.prototype.geojson = function (options) { - return this.latitude(options) + ', ' + this.longitude(options) + ', ' + this.altitude(options); - }; - - Chance.prototype.latitude = function (options) { - // Constants - Formats - var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; - - options = initOptions( -options, - options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? - {min: 0, max: 89, fixed: 4} : - {fixed: 5, min: -90, max: 90, format: DD} -); - - var format = options.format.toLowerCase(); - - if (format === DDM || format === DMS) { - testRange(options.min < 0 || options.min > 89, "Chance: Min specified is out of range. Should be between 0 - 89"); - testRange(options.max < 0 || options.max > 89, "Chance: Max specified is out of range. Should be between 0 - 89"); - testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); - } - - switch (format) { - case DDM: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.floating({min: 0, max: 59, fixed: options.fixed}); - } - case DMS: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.integer({min: 0, max: 59}) + '’' + - this.floating({min: 0, max: 59, fixed: options.fixed}) + 'ā€'; - } - case DD: - default: { - return this.floating({min: options.min, max: options.max, fixed: options.fixed}); - } - } - }; - - Chance.prototype.longitude = function (options) { - // Constants - Formats - var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; - - options = initOptions( -options, - options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? - {min: 0, max: 179, fixed: 4} : - {fixed: 5, min: -180, max: 180, format: DD} -); - - var format = options.format.toLowerCase(); - - if (format === DDM || format === DMS) { - testRange(options.min < 0 || options.min > 179, "Chance: Min specified is out of range. Should be between 0 - 179"); - testRange(options.max < 0 || options.max > 179, "Chance: Max specified is out of range. Should be between 0 - 179"); - testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); - } - - switch (format) { - case DDM: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.floating({min: 0, max: 59.9999, fixed: options.fixed}) - } - case DMS: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.integer({min: 0, max: 59}) + '’' + - this.floating({min: 0, max: 59.9999, fixed: options.fixed}) + 'ā€'; - } - case DD: - default: { - return this.floating({min: options.min, max: options.max, fixed: options.fixed}); - } - } - }; - - Chance.prototype.phone = function (options) { - var self = this, - numPick, - ukNum = function (parts) { - var section = []; - //fills the section part of the phone number with random numbers. - parts.sections.forEach(function(n) { - section.push(self.string({ pool: '0123456789', length: n})); - }); - return parts.area + section.join(' '); - }; - options = initOptions(options, { - formatted: true, - country: 'us', - mobile: false, - exampleNumber: false, - }); - if (!options.formatted) { - options.parens = false; - } - var phone; - switch (options.country) { - case 'fr': - if (!options.mobile) { - numPick = this.pick([ - // Valid zone and dĆ©partement codes. - '01' + this.pick(['30', '34', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '53', '55', '56', '58', '60', '64', '69', '70', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83']) + self.string({ pool: '0123456789', length: 6}), - '02' + this.pick(['14', '18', '22', '23', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '40', '41', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '56', '57', '61', '62', '69', '72', '76', '77', '78', '85', '90', '96', '97', '98', '99']) + self.string({ pool: '0123456789', length: 6}), - '03' + this.pick(['10', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '39', '44', '45', '51', '52', '54', '55', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90']) + self.string({ pool: '0123456789', length: 6}), - '04' + this.pick(['11', '13', '15', '20', '22', '26', '27', '30', '32', '34', '37', '42', '43', '44', '50', '56', '57', '63', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '88', '89', '90', '91', '92', '93', '94', '95', '97', '98']) + self.string({ pool: '0123456789', length: 6}), - '05' + this.pick(['08', '16', '17', '19', '24', '31', '32', '33', '34', '35', '40', '45', '46', '47', '49', '53', '55', '56', '57', '58', '59', '61', '62', '63', '64', '65', '67', '79', '81', '82', '86', '87', '90', '94']) + self.string({ pool: '0123456789', length: 6}), - '09' + self.string({ pool: '0123456789', length: 8}), - ]); - phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; - } else { - numPick = this.pick(['06', '07']) + self.string({ pool: '0123456789', length: 8}); - phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; - } - break; - case 'uk': - if (!options.mobile) { - numPick = this.pick([ - //valid area codes of major cities/counties followed by random numbers in required format. - - { area: '01' + this.character({ pool: '234569' }) + '1 ', sections: [3,4] }, - { area: '020 ' + this.character({ pool: '378' }), sections: [3,4] }, - { area: '023 ' + this.character({ pool: '89' }), sections: [3,4] }, - { area: '024 7', sections: [3,4] }, - { area: '028 ' + this.pick(['25','28','37','71','82','90','92','95']), sections: [2,4] }, - { area: '012' + this.pick(['04','08','54','76','97','98']) + ' ', sections: [6] }, - { area: '013' + this.pick(['63','64','84','86']) + ' ', sections: [6] }, - { area: '014' + this.pick(['04','20','60','61','80','88']) + ' ', sections: [6] }, - { area: '015' + this.pick(['24','27','62','66']) + ' ', sections: [6] }, - { area: '016' + this.pick(['06','29','35','47','59','95']) + ' ', sections: [6] }, - { area: '017' + this.pick(['26','44','50','68']) + ' ', sections: [6] }, - { area: '018' + this.pick(['27','37','84','97']) + ' ', sections: [6] }, - { area: '019' + this.pick(['00','05','35','46','49','63','95']) + ' ', sections: [6] } - ]); - phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', '', 'g'); - } else { - numPick = this.pick([ - { area: '07' + this.pick(['4','5','7','8','9']), sections: [2,6] }, - { area: '07624 ', sections: [6] } - ]); - phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', ''); - } - break; - case 'za': - if (!options.mobile) { - numPick = this.pick([ - '01' + this.pick(['0', '1', '2', '3', '4', '5', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), - '02' + this.pick(['1', '2', '3', '4', '7', '8']) + self.string({ pool: '0123456789', length: 7}), - '03' + this.pick(['1', '2', '3', '5', '6', '9']) + self.string({ pool: '0123456789', length: 7}), - '04' + this.pick(['1', '2', '3', '4', '5','6','7', '8','9']) + self.string({ pool: '0123456789', length: 7}), - '05' + this.pick(['1', '3', '4', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), - ]); - phone = options.formatted || numPick; - } else { - numPick = this.pick([ - '060' + this.pick(['3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), - '061' + this.pick(['0','1','2','3','4','5','8']) + self.string({ pool: '0123456789', length: 6}), - '06' + self.string({ pool: '0123456789', length: 7}), - '071' + this.pick(['0','1','2','3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), - '07' + this.pick(['2','3','4','6','7','8','9']) + self.string({ pool: '0123456789', length: 7}), - '08' + this.pick(['0','1','2','3','4','5']) + self.string({ pool: '0123456789', length: 7}), - ]); - phone = options.formatted || numPick; - } - break; - case 'us': - var areacode = this.areacode(options).toString(); - var exchange = this.natural({ min: 2, max: 9 }).toString() + - this.natural({ min: 0, max: 9 }).toString() + - this.natural({ min: 0, max: 9 }).toString(); - var subscriber = this.natural({ min: 1000, max: 9999 }).toString(); // this could be random [0-9]{4} - phone = options.formatted ? areacode + ' ' + exchange + '-' + subscriber : areacode + exchange + subscriber; - break; - case 'br': - var areaCode = this.pick(["11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "24", "27", "28", "31", "32", "33", "34", "35", "37", "38", "41", "42", "43", "44", "45", "46", "47", "48", "49", "51", "53", "54", "55", "61", "62", "63", "64", "65", "66", "67", "68", "69", "71", "73", "74", "75", "77", "79", "81", "82", "83", "84", "85", "86", "87", "88", "89", "91", "92", "93", "94", "95", "96", "97", "98", "99"]); - var prefix; - if (options.mobile) { - // Brasilian official reference (mobile): http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=330 - prefix = '9' + self.string({ pool: '0123456789', length: 4}); - } else { - // Brasilian official reference: http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=331 - prefix = this.natural({ min: 2000, max: 5999 }).toString(); - } - var mcdu = self.string({ pool: '0123456789', length: 4}); - phone = options.formatted ? '(' + areaCode + ') ' + prefix + '-' + mcdu : areaCode + prefix + mcdu; - break; - } - return phone; - }; - - Chance.prototype.postal = function () { - // Postal District - var pd = this.character({pool: "XVTSRPNKLMHJGECBA"}); - // Forward Sortation Area (FSA) - var fsa = pd + this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}); - // Local Delivery Unut (LDU) - var ldu = this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}) + this.natural({max: 9}); - - return fsa + " " + ldu; - }; - - Chance.prototype.postcode = function () { - // Area - var area = this.pick(this.get("postcodeAreas")).code; - // District - var district = this.natural({max: 9}); - // Sub-District - var subDistrict = this.bool() ? this.character({alpha: true, casing: "upper"}) : ""; - // Outward Code - var outward = area + district + subDistrict; - // Sector - var sector = this.natural({max: 9}); - // Unit - var unit = this.character({alpha: true, casing: "upper"}) + this.character({alpha: true, casing: "upper"}); - // Inward Code - var inward = sector + unit; - - return outward + " " + inward; - }; - - Chance.prototype.counties = function (options) { - options = initOptions(options, { country: 'uk' }); - return this.get("counties")[options.country.toLowerCase()]; - }; - - Chance.prototype.county = function (options) { - return this.pick(this.counties(options)).name; - }; - - Chance.prototype.provinces = function (options) { - options = initOptions(options, { country: 'ca' }); - return this.get("provinces")[options.country.toLowerCase()]; - }; - - Chance.prototype.province = function (options) { - return (options && options.full) ? - this.pick(this.provinces(options)).name : - this.pick(this.provinces(options)).abbreviation; - }; - - Chance.prototype.state = function (options) { - return (options && options.full) ? - this.pick(this.states(options)).name : - this.pick(this.states(options)).abbreviation; - }; - - Chance.prototype.states = function (options) { - options = initOptions(options, { country: 'us', us_states_and_dc: true } ); - - var states; - - switch (options.country.toLowerCase()) { - case 'us': - var us_states_and_dc = this.get("us_states_and_dc"), - territories = this.get("territories"), - armed_forces = this.get("armed_forces"); - - states = []; - - if (options.us_states_and_dc) { - states = states.concat(us_states_and_dc); - } - if (options.territories) { - states = states.concat(territories); - } - if (options.armed_forces) { - states = states.concat(armed_forces); - } - break; - case 'it': - case 'mx': - states = this.get("country_regions")[options.country.toLowerCase()]; - break; - case 'uk': - states = this.get("counties")[options.country.toLowerCase()]; - break; - } - - return states; - }; - - Chance.prototype.street = function (options) { - options = initOptions(options, { country: 'us', syllables: 2 }); - var street; - - switch (options.country.toLowerCase()) { - case 'us': - street = this.word({ syllables: options.syllables }); - street = this.capitalize(street); - street += ' '; - street += options.short_suffix ? - this.street_suffix(options).abbreviation : - this.street_suffix(options).name; - break; - case 'it': - street = this.word({ syllables: options.syllables }); - street = this.capitalize(street); - street = (options.short_suffix ? - this.street_suffix(options).abbreviation : - this.street_suffix(options).name) + " " + street; - break; - } - return street; - }; - - Chance.prototype.street_suffix = function (options) { - options = initOptions(options, { country: 'us' }); - return this.pick(this.street_suffixes(options)); - }; - - Chance.prototype.street_suffixes = function (options) { - options = initOptions(options, { country: 'us' }); - // These are the most common suffixes. - return this.get("street_suffixes")[options.country.toLowerCase()]; - }; - - // Note: only returning US zip codes, internationalization will be a whole - // other beast to tackle at some point. - Chance.prototype.zip = function (options) { - var zip = this.n(this.natural, 5, {max: 9}); - - if (options && options.plusfour === true) { - zip.push('-'); - zip = zip.concat(this.n(this.natural, 4, {max: 9})); - } - - return zip.join(""); - }; - - // -- End Location -- - - // -- Time - - Chance.prototype.ampm = function () { - return this.bool() ? 'am' : 'pm'; - }; - - Chance.prototype.date = function (options) { - var date_string, date; - - // If interval is specified we ignore preset - if(options && (options.min || options.max)) { - options = initOptions(options, { - american: true, - string: false - }); - var min = typeof options.min !== "undefined" ? options.min.getTime() : 1; - // 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. http://es5.github.io/#x15.9.1.1 - var max = typeof options.max !== "undefined" ? options.max.getTime() : 8640000000000000; - - date = new Date(this.integer({min: min, max: max})); - } else { - var m = this.month({raw: true}); - var daysInMonth = m.days; - - if(options && options.month) { - // Mod 12 to allow months outside range of 0-11 (not encouraged, but also not prevented). - daysInMonth = this.get('months')[((options.month % 12) + 12) % 12].days; - } - - options = initOptions(options, { - year: parseInt(this.year(), 10), - // Necessary to subtract 1 because Date() 0-indexes month but not day or year - // for some reason. - month: m.numeric - 1, - day: this.natural({min: 1, max: daysInMonth}), - hour: this.hour({twentyfour: true}), - minute: this.minute(), - second: this.second(), - millisecond: this.millisecond(), - american: true, - string: false - }); - - date = new Date(options.year, options.month, options.day, options.hour, options.minute, options.second, options.millisecond); - } - - if (options.american) { - // Adding 1 to the month is necessary because Date() 0-indexes - // months but not day for some odd reason. - date_string = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); - } else { - date_string = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); - } - - return options.string ? date_string : date; - }; - - Chance.prototype.hammertime = function (options) { - return this.date(options).getTime(); - }; - - Chance.prototype.hour = function (options) { - options = initOptions(options, { - min: options && options.twentyfour ? 0 : 1, - max: options && options.twentyfour ? 23 : 12 - }); - - testRange(options.min < 0, "Chance: Min cannot be less than 0."); - testRange(options.twentyfour && options.max > 23, "Chance: Max cannot be greater than 23 for twentyfour option."); - testRange(!options.twentyfour && options.max > 12, "Chance: Max cannot be greater than 12."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - return this.natural({min: options.min, max: options.max}); - }; - - Chance.prototype.millisecond = function () { - return this.natural({max: 999}); - }; - - Chance.prototype.minute = Chance.prototype.second = function (options) { - options = initOptions(options, {min: 0, max: 59}); - - testRange(options.min < 0, "Chance: Min cannot be less than 0."); - testRange(options.max > 59, "Chance: Max cannot be greater than 59."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - return this.natural({min: options.min, max: options.max}); - }; - - Chance.prototype.month = function (options) { - options = initOptions(options, {min: 1, max: 12}); - - testRange(options.min < 1, "Chance: Min cannot be less than 1."); - testRange(options.max > 12, "Chance: Max cannot be greater than 12."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - var month = this.pick(this.months().slice(options.min - 1, options.max)); - return options.raw ? month : month.name; - }; - - Chance.prototype.months = function () { - return this.get("months"); - }; - - Chance.prototype.second = function () { - return this.natural({max: 59}); - }; - - Chance.prototype.timestamp = function () { - return this.natural({min: 1, max: parseInt(new Date().getTime() / 1000, 10)}); - }; - - Chance.prototype.weekday = function (options) { - options = initOptions(options, {weekday_only: false}); - var weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; - if (!options.weekday_only) { - weekdays.push("Saturday"); - weekdays.push("Sunday"); - } - return this.pickone(weekdays); - }; - - Chance.prototype.year = function (options) { - // Default to current year as min if none specified - options = initOptions(options, {min: new Date().getFullYear()}); - - // Default to one century after current year as max if none specified - options.max = (typeof options.max !== "undefined") ? options.max : options.min + 100; - - return this.natural(options).toString(); - }; - - // -- End Time - - // -- Finance -- - - Chance.prototype.cc = function (options) { - options = initOptions(options); - - var type, number, to_generate; - - type = (options.type) ? - this.cc_type({ name: options.type, raw: true }) : - this.cc_type({ raw: true }); - - number = type.prefix.split(""); - to_generate = type.length - type.prefix.length - 1; - - // Generates n - 1 digits - number = number.concat(this.n(this.integer, to_generate, {min: 0, max: 9})); - - // Generates the last digit according to Luhn algorithm - number.push(this.luhn_calculate(number.join(""))); - - return number.join(""); - }; - - Chance.prototype.cc_types = function () { - // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 - return this.get("cc_types"); - }; - - Chance.prototype.cc_type = function (options) { - options = initOptions(options); - var types = this.cc_types(), - type = null; - - if (options.name) { - for (var i = 0; i < types.length; i++) { - // Accept either name or short_name to specify card type - if (types[i].name === options.name || types[i].short_name === options.name) { - type = types[i]; - break; - } - } - if (type === null) { - throw new RangeError("Chance: Credit card type '" + options.name + "' is not supported"); - } - } else { - type = this.pick(types); - } - - return options.raw ? type : type.name; - }; - - // return all world currency by ISO 4217 - Chance.prototype.currency_types = function () { - return this.get("currency_types"); - }; - - // return random world currency by ISO 4217 - Chance.prototype.currency = function () { - return this.pick(this.currency_types()); - }; - - // return all timezones available - Chance.prototype.timezones = function () { - return this.get("timezones"); - }; - - // return random timezone - Chance.prototype.timezone = function () { - return this.pick(this.timezones()); - }; - - //Return random correct currency exchange pair (e.g. EUR/USD) or array of currency code - Chance.prototype.currency_pair = function (returnAsString) { - var currencies = this.unique(this.currency, 2, { - comparator: function(arr, val) { - - return arr.reduce(function(acc, item) { - // If a match has been found, short circuit check and just return - return acc || (item.code === val.code); - }, false); - } - }); - - if (returnAsString) { - return currencies[0].code + '/' + currencies[1].code; - } else { - return currencies; - } - }; - - Chance.prototype.dollar = function (options) { - // By default, a somewhat more sane max for dollar than all available numbers - options = initOptions(options, {max : 10000, min : 0}); - - var dollar = this.floating({min: options.min, max: options.max, fixed: 2}).toString(), - cents = dollar.split('.')[1]; - - if (cents === undefined) { - dollar += '.00'; - } else if (cents.length < 2) { - dollar = dollar + '0'; - } - - if (dollar < 0) { - return '-$' + dollar.replace('-', ''); - } else { - return '$' + dollar; - } - }; - - Chance.prototype.euro = function (options) { - return Number(this.dollar(options).replace("$", "")).toLocaleString() + "€"; - }; - - Chance.prototype.exp = function (options) { - options = initOptions(options); - var exp = {}; - - exp.year = this.exp_year(); - - // If the year is this year, need to ensure month is greater than the - // current month or this expiration will not be valid - if (exp.year === (new Date().getFullYear()).toString()) { - exp.month = this.exp_month({future: true}); - } else { - exp.month = this.exp_month(); - } - - return options.raw ? exp : exp.month + '/' + exp.year; - }; - - Chance.prototype.exp_month = function (options) { - options = initOptions(options); - var month, month_int, - // Date object months are 0 indexed - curMonth = new Date().getMonth() + 1; - - if (options.future && (curMonth !== 12)) { - do { - month = this.month({raw: true}).numeric; - month_int = parseInt(month, 10); - } while (month_int <= curMonth); - } else { - month = this.month({raw: true}).numeric; - } - - return month; - }; - - Chance.prototype.exp_year = function () { - var curMonth = new Date().getMonth() + 1, - curYear = new Date().getFullYear(); - - return this.year({min: ((curMonth === 12) ? (curYear + 1) : curYear), max: (curYear + 10)}); - }; - - Chance.prototype.vat = function (options) { - options = initOptions(options, { country: 'it' }); - switch (options.country.toLowerCase()) { - case 'it': - return this.it_vat(); - } - }; - - /** - * Generate a string matching IBAN pattern (https://en.wikipedia.org/wiki/International_Bank_Account_Number). - * No country-specific formats support (yet) - */ - Chance.prototype.iban = function () { - var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - var alphanum = alpha + '0123456789'; - var iban = - this.string({ length: 2, pool: alpha }) + - this.pad(this.integer({ min: 0, max: 99 }), 2) + - this.string({ length: 4, pool: alphanum }) + - this.pad(this.natural(), this.natural({ min: 6, max: 26 })); - return iban; - }; - - // -- End Finance - - // -- Regional - - Chance.prototype.it_vat = function () { - var it_vat = this.natural({min: 1, max: 1800000}); - - it_vat = this.pad(it_vat, 7) + this.pad(this.pick(this.provinces({ country: 'it' })).code, 3); - return it_vat + this.luhn_calculate(it_vat); - }; - - /* - * this generator is written following the official algorithm - * all data can be passed explicitely or randomized by calling chance.cf() without options - * the code does not check that the input data is valid (it goes beyond the scope of the generator) - * - * @param [Object] options = { first: first name, - * last: last name, - * gender: female|male, - birthday: JavaScript date object, - city: string(4), 1 letter + 3 numbers - } - * @return [string] codice fiscale - * - */ - Chance.prototype.cf = function (options) { - options = options || {}; - var gender = !!options.gender ? options.gender : this.gender(), - first = !!options.first ? options.first : this.first( { gender: gender, nationality: 'it'} ), - last = !!options.last ? options.last : this.last( { nationality: 'it'} ), - birthday = !!options.birthday ? options.birthday : this.birthday(), - city = !!options.city ? options.city : this.pickone(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L', 'M', 'Z']) + this.pad(this.natural({max:999}), 3), - cf = [], - name_generator = function(name, isLast) { - var temp, - return_value = []; - - if (name.length < 3) { - return_value = name.split("").concat("XXX".split("")).splice(0,3); - } - else { - temp = name.toUpperCase().split('').map(function(c){ - return ("BCDFGHJKLMNPRSTVWZ".indexOf(c) !== -1) ? c : undefined; - }).join(''); - if (temp.length > 3) { - if (isLast) { - temp = temp.substr(0,3); - } else { - temp = temp[0] + temp.substr(2,2); - } - } - if (temp.length < 3) { - return_value = temp; - temp = name.toUpperCase().split('').map(function(c){ - return ("AEIOU".indexOf(c) !== -1) ? c : undefined; - }).join('').substr(0, 3 - return_value.length); - } - return_value = return_value + temp; - } - - return return_value; - }, - date_generator = function(birthday, gender, that) { - var lettermonths = ['A', 'B', 'C', 'D', 'E', 'H', 'L', 'M', 'P', 'R', 'S', 'T']; - - return birthday.getFullYear().toString().substr(2) + - lettermonths[birthday.getMonth()] + - that.pad(birthday.getDate() + ((gender.toLowerCase() === "female") ? 40 : 0), 2); - }, - checkdigit_generator = function(cf) { - var range1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", - range2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ", - evens = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - odds = "BAKPLCQDREVOSFTGUHMINJWZYX", - digit = 0; - - - for(var i = 0; i < 15; i++) { - if (i % 2 !== 0) { - digit += evens.indexOf(range2[range1.indexOf(cf[i])]); - } - else { - digit += odds.indexOf(range2[range1.indexOf(cf[i])]); - } - } - return evens[digit % 26]; - }; - - cf = cf.concat(name_generator(last, true), name_generator(first), date_generator(birthday, gender, this), city.toUpperCase().split("")).join(""); - cf += checkdigit_generator(cf.toUpperCase(), this); - - return cf.toUpperCase(); - }; - - Chance.prototype.pl_pesel = function () { - var number = this.natural({min: 1, max: 9999999999}); - var arr = this.pad(number, 10).split(''); - for (var i = 0; i < arr.length; i++) { - arr[i] = parseInt(arr[i]); - } - - var controlNumber = (1 * arr[0] + 3 * arr[1] + 7 * arr[2] + 9 * arr[3] + 1 * arr[4] + 3 * arr[5] + 7 * arr[6] + 9 * arr[7] + 1 * arr[8] + 3 * arr[9]) % 10; - if(controlNumber !== 0) { - controlNumber = 10 - controlNumber; - } - - return arr.join('') + controlNumber; - }; - - Chance.prototype.pl_nip = function () { - var number = this.natural({min: 1, max: 999999999}); - var arr = this.pad(number, 9).split(''); - for (var i = 0; i < arr.length; i++) { - arr[i] = parseInt(arr[i]); - } - - var controlNumber = (6 * arr[0] + 5 * arr[1] + 7 * arr[2] + 2 * arr[3] + 3 * arr[4] + 4 * arr[5] + 5 * arr[6] + 6 * arr[7] + 7 * arr[8]) % 11; - if(controlNumber === 10) { - return this.pl_nip(); - } - - return arr.join('') + controlNumber; - }; - - Chance.prototype.pl_regon = function () { - var number = this.natural({min: 1, max: 99999999}); - var arr = this.pad(number, 8).split(''); - for (var i = 0; i < arr.length; i++) { - arr[i] = parseInt(arr[i]); - } - - var controlNumber = (8 * arr[0] + 9 * arr[1] + 2 * arr[2] + 3 * arr[3] + 4 * arr[4] + 5 * arr[5] + 6 * arr[6] + 7 * arr[7]) % 11; - if(controlNumber === 10) { - controlNumber = 0; - } - - return arr.join('') + controlNumber; - }; - - // -- End Regional - - // -- Music -- - - // Genre choices: - // Rock,Pop,Hip-Hop,Jazz,Classical,Electronic,Country,R&B,Reggae, - // Blues,Metal,Folk,Alternative,Punk,Disco,Funk,Techno, - // Indie,Gospel,Dance,Children's,World - - Chance.prototype.music_genre = function (genre = 'general') { - if (!(genre.toLowerCase() in data.music_genres)) { - throw new Error(`Unsupported genre: ${genre}`); - } - - const genres = data.music_genres[genre.toLowerCase()]; - const randomIndex = this.integer({ min: 0, max: genres.length - 1 }); - - return genres[randomIndex]; - }; - - Chance.prototype.note = function(options) { - // choices for 'notes' option: - // flatKey - chromatic scale with flat notes (default) - // sharpKey - chromatic scale with sharp notes - // flats - just flat notes - // sharps - just sharp notes - // naturals - just natural notes - // all - naturals, sharps and flats - options = initOptions(options, { notes : 'flatKey'}); - var scales = { - naturals: ['C', 'D', 'E', 'F', 'G', 'A', 'B'], - flats: ['Dā™­', 'Eā™­', 'Gā™­', 'Aā™­', 'Bā™­'], - sharps: ['C♯', 'D♯', 'F♯', 'G♯', 'A♯'] - }; - scales.all = scales.naturals.concat(scales.flats.concat(scales.sharps)) - scales.flatKey = scales.naturals.concat(scales.flats) - scales.sharpKey = scales.naturals.concat(scales.sharps) - return this.pickone(scales[options.notes]); - } - - Chance.prototype.midi_note = function(options) { - var min = 0; - var max = 127; - options = initOptions(options, { min : min, max : max }); - return this.integer({min: options.min, max: options.max}); - } - - Chance.prototype.chord_quality = function(options) { - options = initOptions(options, { jazz: true }); - var chord_qualities = ['maj', 'min', 'aug', 'dim']; - if (options.jazz){ - chord_qualities = [ - 'maj7', - 'min7', - '7', - 'sus', - 'dim', - 'Ćø' - ]; - } - return this.pickone(chord_qualities); - } - - Chance.prototype.chord = function (options) { - options = initOptions(options); - return this.note(options) + this.chord_quality(options); - } - - Chance.prototype.tempo = function (options) { - var min = 40; - var max = 320; - options = initOptions(options, {min: min, max: max}); - return this.integer({min: options.min, max: options.max}); - } - - // -- End Music - - // -- Miscellaneous -- - - // Coin - Flip, flip, flipadelphia - Chance.prototype.coin = function() { - return this.bool() ? "heads" : "tails"; - } - - // Dice - For all the board game geeks out there, myself included ;) - function diceFn (range) { - return function () { - return this.natural(range); - }; - } - Chance.prototype.d4 = diceFn({min: 1, max: 4}); - Chance.prototype.d6 = diceFn({min: 1, max: 6}); - Chance.prototype.d8 = diceFn({min: 1, max: 8}); - Chance.prototype.d10 = diceFn({min: 1, max: 10}); - Chance.prototype.d12 = diceFn({min: 1, max: 12}); - Chance.prototype.d20 = diceFn({min: 1, max: 20}); - Chance.prototype.d30 = diceFn({min: 1, max: 30}); - Chance.prototype.d100 = diceFn({min: 1, max: 100}); - - Chance.prototype.rpg = function (thrown, options) { - options = initOptions(options); - if (!thrown) { - throw new RangeError("Chance: A type of die roll must be included"); - } else { - var bits = thrown.toLowerCase().split("d"), - rolls = []; - - if (bits.length !== 2 || !parseInt(bits[0], 10) || !parseInt(bits[1], 10)) { - throw new Error("Chance: Invalid format provided. Please provide #d# where the first # is the number of dice to roll, the second # is the max of each die"); - } - for (var i = bits[0]; i > 0; i--) { - rolls[i - 1] = this.natural({min: 1, max: bits[1]}); - } - return (typeof options.sum !== 'undefined' && options.sum) ? rolls.reduce(function (p, c) { return p + c; }) : rolls; - } - }; - - // Guid - Chance.prototype.guid = function (options) { - options = initOptions(options, { version: 5 }); - - var guid_pool = "abcdef1234567890", - variant_pool = "ab89", - guid = this.string({ pool: guid_pool, length: 8 }) + '-' + - this.string({ pool: guid_pool, length: 4 }) + '-' + - // The Version - options.version + - this.string({ pool: guid_pool, length: 3 }) + '-' + - // The Variant - this.string({ pool: variant_pool, length: 1 }) + - this.string({ pool: guid_pool, length: 3 }) + '-' + - this.string({ pool: guid_pool, length: 12 }); - return guid; - }; - - // Hash - Chance.prototype.hash = function (options) { - options = initOptions(options, {length : 40, casing: 'lower'}); - var pool = options.casing === 'upper' ? HEX_POOL.toUpperCase() : HEX_POOL; - return this.string({pool: pool, length: options.length}); - }; - - Chance.prototype.luhn_check = function (num) { - var str = num.toString(); - var checkDigit = +str.substring(str.length - 1); - return checkDigit === this.luhn_calculate(+str.substring(0, str.length - 1)); - }; - - Chance.prototype.luhn_calculate = function (num) { - var digits = num.toString().split("").reverse(); - var sum = 0; - var digit; - - for (var i = 0, l = digits.length; l > i; ++i) { - digit = +digits[i]; - if (i % 2 === 0) { - digit *= 2; - if (digit > 9) { - digit -= 9; - } - } - sum += digit; - } - return (sum * 9) % 10; - }; - - // MD5 Hash - Chance.prototype.md5 = function(options) { - var opts = { str: '', key: null, raw: false }; - - if (!options) { - opts.str = this.string(); - options = {}; - } - else if (typeof options === 'string') { - opts.str = options; - options = {}; - } - else if (typeof options !== 'object') { - return null; - } - else if(options.constructor === 'Array') { - return null; - } - - opts = initOptions(options, opts); - - if(!opts.str){ - throw new Error('A parameter is required to return an md5 hash.'); - } - - return this.bimd5.md5(opts.str, opts.key, opts.raw); - }; - - /** - * #Description: - * ===================================================== - * Generate random file name with extension - * - * The argument provide extension type - * -> raster - * -> vector - * -> 3d - * -> document - * - * If nothing is provided the function return random file name with random - * extension type of any kind - * - * The user can validate the file name length range - * If nothing provided the generated file name is random - * - * #Extension Pool : - * * Currently the supported extensions are - * -> some of the most popular raster image extensions - * -> some of the most popular vector image extensions - * -> some of the most popular 3d image extensions - * -> some of the most popular document extensions - * - * #Examples : - * ===================================================== - * - * Return random file name with random extension. The file extension - * is provided by a predefined collection of extensions. More about the extension - * pool can be found in #Extension Pool section - * - * chance.file() - * => dsfsdhjf.xml - * - * In order to generate a file name with specific length, specify the - * length property and integer value. The extension is going to be random - * - * chance.file({length : 10}) - * => asrtineqos.pdf - * - * In order to generate file with extension from some of the predefined groups - * of the extension pool just specify the extension pool category in fileType property - * - * chance.file({fileType : 'raster'}) - * => dshgssds.psd - * - * You can provide specific extension for your files - * chance.file({extension : 'html'}) - * => djfsd.html - * - * Or you could pass custom collection of extensions by array or by object - * chance.file({extensions : [...]}) - * => dhgsdsd.psd - * - * chance.file({extensions : { key : [...], key : [...]}}) - * => djsfksdjsd.xml - * - * @param [collection] options - * @return [string] - * - */ - Chance.prototype.file = function(options) { - - var fileOptions = options || {}; - var poolCollectionKey = "fileExtension"; - var typeRange = Object.keys(this.get("fileExtension"));//['raster', 'vector', '3d', 'document']; - var fileName; - var fileExtension; - - // Generate random file name - fileName = this.word({length : fileOptions.length}); - - // Generate file by specific extension provided by the user - if(fileOptions.extension) { - - fileExtension = fileOptions.extension; - return (fileName + '.' + fileExtension); - } - - // Generate file by specific extension collection - if(fileOptions.extensions) { - - if(Array.isArray(fileOptions.extensions)) { - - fileExtension = this.pickone(fileOptions.extensions); - return (fileName + '.' + fileExtension); - } - else if(fileOptions.extensions.constructor === Object) { - - var extensionObjectCollection = fileOptions.extensions; - var keys = Object.keys(extensionObjectCollection); - - fileExtension = this.pickone(extensionObjectCollection[this.pickone(keys)]); - return (fileName + '.' + fileExtension); - } - - throw new Error("Chance: Extensions must be an Array or Object"); - } - - // Generate file extension based on specific file type - if(fileOptions.fileType) { - - var fileType = fileOptions.fileType; - if(typeRange.indexOf(fileType) !== -1) { - - fileExtension = this.pickone(this.get(poolCollectionKey)[fileType]); - return (fileName + '.' + fileExtension); - } - - throw new RangeError("Chance: Expect file type value to be 'raster', 'vector', '3d' or 'document'"); - } - - // Generate random file name if no extension options are passed - fileExtension = this.pickone(this.get(poolCollectionKey)[this.pickone(typeRange)]); - return (fileName + '.' + fileExtension); - }; - - /** - * Generates file data of random bytes using the chance.file method for the file name - * - * @param {object} - * fileName: String - * fileExtention: String - * fileSize: Number <- in bytes - * @returns {object} fileName: String, fileData: Buffer - */ - Chance.prototype.fileWithContent = function (options){ - var fileOptions = options || {}; - var fileName = 'fileName' in fileOptions ? fileOptions.fileName : this.file().split(".")[0]; - fileName += "." + ('fileExtension' in fileOptions ? fileOptions.fileExtension : this.file().split(".")[1]); - - - if (typeof fileOptions.fileSize !== "number") { - throw new Error('File size must be an integer') - } - var file = { - fileData: this.buffer({length: fileOptions.fileSize}), - fileName: fileName, - }; - return file; - } - - var data = { - - firstNames: { - "male": { - "en": ["James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "George", "Donald", "Anthony", "Paul", "Mark", "Edward", "Steven", "Kenneth", "Andrew", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Frank", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Jonathan", "Scott", "Raymond", "Justin", "Brandon", "Gregory", "Samuel", "Benjamin", "Patrick", "Jack", "Henry", "Walter", "Dennis", "Jerry", "Alexander", "Peter", "Tyler", "Douglas", "Harold", "Aaron", "Jose", "Adam", "Arthur", "Zachary", "Carl", "Nathan", "Albert", "Kyle", "Lawrence", "Joe", "Willie", "Gerald", "Roger", "Keith", "Jeremy", "Terry", "Harry", "Ralph", "Sean", "Jesse", "Roy", "Louis", "Billy", "Austin", "Bruce", "Eugene", "Christian", "Bryan", "Wayne", "Russell", "Howard", "Fred", "Ethan", "Jordan", "Philip", "Alan", "Juan", "Randy", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Victor", "Clarence", "Ernest", "Martin", "Craig", "Stanley", "Shawn", "Travis", "Bradley", "Leonard", "Earl", "Gabriel", "Jimmy", "Francis", "Todd", "Noah", "Danny", "Dale", "Cody", "Carlos", "Allen", "Frederick", "Logan", "Curtis", "Alex", "Joel", "Luis", "Norman", "Marvin", "Glenn", "Tony", "Nathaniel", "Rodney", "Melvin", "Alfred", "Steve", "Cameron", "Chad", "Edwin", "Caleb", "Evan", "Antonio", "Lee", "Herbert", "Jeffery", "Isaac", "Derek", "Ricky", "Marcus", "Theodore", "Elijah", "Luke", "Jesus", "Eddie", "Troy", "Mike", "Dustin", "Ray", "Adrian", "Bernard", "Leroy", "Angel", "Randall", "Wesley", "Ian", "Jared", "Mason", "Hunter", "Calvin", "Oscar", "Clifford", "Jay", "Shane", "Ronnie", "Barry", "Lucas", "Corey", "Manuel", "Leo", "Tommy", "Warren", "Jackson", "Isaiah", "Connor", "Don", "Dean", "Jon", "Julian", "Miguel", "Bill", "Lloyd", "Charlie", "Mitchell", "Leon", "Jerome", "Darrell", "Jeremiah", "Alvin", "Brett", "Seth", "Floyd", "Jim", "Blake", "Micheal", "Gordon", "Trevor", "Lewis", "Erik", "Edgar", "Vernon", "Devin", "Gavin", "Jayden", "Chris", "Clyde", "Tom", "Derrick", "Mario", "Brent", "Marc", "Herman", "Chase", "Dominic", "Ricardo", "Franklin", "Maurice", "Max", "Aiden", "Owen", "Lester", "Gilbert", "Elmer", "Gene", "Francisco", "Glen", "Cory", "Garrett", "Clayton", "Sam", "Jorge", "Chester", "Alejandro", "Jeff", "Harvey", "Milton", "Cole", "Ivan", "Andre", "Duane", "Landon"], - // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0163 - "it": ["Adolfo", "Alberto", "Aldo", "Alessandro", "Alessio", "Alfredo", "Alvaro", "Andrea", "Angelo", "Angiolo", "Antonino", "Antonio", "Attilio", "Benito", "Bernardo", "Bruno", "Carlo", "Cesare", "Christian", "Claudio", "Corrado", "Cosimo", "Cristian", "Cristiano", "Daniele", "Dario", "David", "Davide", "Diego", "Dino", "Domenico", "Duccio", "Edoardo", "Elia", "Elio", "Emanuele", "Emiliano", "Emilio", "Enrico", "Enzo", "Ettore", "Fabio", "Fabrizio", "Federico", "Ferdinando", "Fernando", "Filippo", "Francesco", "Franco", "Gabriele", "Giacomo", "Giampaolo", "Giampiero", "Giancarlo", "Gianfranco", "Gianluca", "Gianmarco", "Gianni", "Gino", "Giorgio", "Giovanni", "Giuliano", "Giulio", "Giuseppe", "Graziano", "Gregorio", "Guido", "Iacopo", "Jacopo", "Lapo", "Leonardo", "Lorenzo", "Luca", "Luciano", "Luigi", "Manuel", "Marcello", "Marco", "Marino", "Mario", "Massimiliano", "Massimo", "Matteo", "Mattia", "Maurizio", "Mauro", "Michele", "Mirko", "Mohamed", "Nello", "Neri", "Niccolò", "Nicola", "Osvaldo", "Otello", "Paolo", "Pier Luigi", "Piero", "Pietro", "Raffaele", "Remo", "Renato", "Renzo", "Riccardo", "Roberto", "Rolando", "Romano", "Salvatore", "Samuele", "Sandro", "Sergio", "Silvano", "Simone", "Stefano", "Thomas", "Tommaso", "Ubaldo", "Ugo", "Umberto", "Valerio", "Valter", "Vasco", "Vincenzo", "Vittorio"], - // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html - "nl": ["Aaron","Abel","Adam","Adriaan","Albert","Alexander","Ali","Arjen","Arno","Bart","Bas","Bastiaan","Benjamin","Bob", "Boris","Bram","Brent","Cas","Casper","Chris","Christiaan","Cornelis","Daan","Daley","Damian","Dani","Daniel","DaniĆ«l","David","Dean","Dirk","Dylan","Egbert","Elijah","Erik","Erwin","Evert","Ezra","Fabian","Fedde","Finn","Florian","Floris","Frank","Frans","Frederik","Freek","Geert","Gerard","Gerben","Gerrit","Gijs","Guus","Hans","Hendrik","Henk","Herman","Hidde","Hugo","Jaap","Jan Jaap","Jan-Willem","Jack","Jacob","Jan","Jason","Jasper","Jayden","Jelle","Jelte","Jens","Jeroen","Jesse","Jim","Job","Joep","Johannes","John","Jonathan","Joris","Joshua","JoĆ«l","Julian","Kees","Kevin","Koen","Lars","Laurens","Leendert","Lennard","Lodewijk","Luc","Luca","Lucas","Lukas","Luuk","Maarten","Marcus","Martijn","Martin","Matthijs","Maurits","Max","Mees","Melle","Mick","Mika","Milan","Mohamed","Mohammed","Morris","Muhammed","Nathan","Nick","Nico","Niek","Niels","Noah","Noud","Olivier","Oscar","Owen","Paul","Pepijn","Peter","Pieter","Pim","Quinten","Reinier","Rens","Robin","Ruben","Sam","Samuel","Sander","Sebastiaan","Sem","Sep","Sepp","Siem","Simon","Stan","Stef","Steven","Stijn","Sven","Teun","Thijmen","Thijs","Thomas","Tijn","Tim","Timo","Tobias","Tom","Victor","Vince","Willem","Wim","Wouter","Yusuf"], - // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie - "fr": ["Aaron","Abdon","Abel","AbĆ©lard","Abelin","Abondance","Abraham","Absalon","Acace","Achaire","Achille","Adalard","Adalbald","AdalbĆ©ron","Adalbert","Adalric","Adam","Adegrin","Adel","Adelin","Andelin","Adelphe","Adam","AdĆ©odat","AdhĆ©mar","Adjutor","Adolphe","Adonis","Adon","Adrien","Agapet","Agathange","Agathon","Agilbert","AgĆ©nor","Agnan","Aignan","Agrippin","Aimable","AimĆ©","Alain","Alban","Albin","Aubin","AlbĆ©ric","Albert","Albertet","Alcibiade","Alcide","AlcĆ©e","Alcime","Aldonce","Aldric","AldĆ©ric","Aleaume","Alexandre","Alexis","Alix","Alliaume","Aleaume","Almine","Almire","AloĆÆs","AlphĆ©e","Alphonse","Alpinien","AlverĆØde","Amalric","Amaury","Amandin","Amant","Ambroise","AmĆ©dĆ©e","AmĆ©lien","Amiel","Amour","AnaĆ«l","Anastase","Anatole","Ancelin","AndĆ©ol","Andoche","AndrĆ©","Andoche","Ange","Angelin","Angilbe","Anglebert","Angoustan","Anicet","Anne","Annibal","Ansbert","Anselme","Anthelme","Antheaume","Anthime","Antide","Antoine","Antonius","Antonin","Apollinaire","Apollon","Aquilin","Arcade","Archambaud","Archambeau","Archange","Archibald","Arian","Ariel","Ariste","Aristide","Armand","Armel","Armin","Arnould","Arnaud","Arolde","ArsĆØne","ArsinoĆ©","Arthaud","ArthĆØme","Arthur","Ascelin","Athanase","Aubry","Audebert","Audouin","Audran","Audric","Auguste","Augustin","AurĆØle","AurĆ©lien","Aurian","Auxence","Axel","Aymard","Aymeric","Aymon","Aymond","Balthazar","Baptiste","BarnabĆ©","BarthĆ©lemy","BartimĆ©e","Basile","Bastien","Baudouin","BĆ©nigne","Benjamin","BenoĆ®t","BĆ©renger","BĆ©rard","Bernard","Bertrand","Blaise","Bon","Boniface","Bouchard","Brice","Brieuc","Bruno","Brunon","Calixte","Calliste","CamĆ©lien","Camille","Camillien","Candide","Caribert","Carloman","Cassandre","Cassien","CĆ©dric","CĆ©leste","CĆ©lestin","CĆ©lien","CĆ©saire","CĆ©sar","Charles","Charlemagne","Childebert","ChilpĆ©ric","ChrĆ©tien","Christian","Christodule","Christophe","Chrysostome","Clarence","Claude","Claudien","ClĆ©andre","ClĆ©ment","Clotaire","CĆ“me","Constance","Constant","Constantin","Corentin","Cyprien","Cyriaque","Cyrille","Cyril","Damien","Daniel","David","Delphin","Denis","DĆ©sirĆ©","Didier","DieudonnĆ©","Dimitri","Dominique","Dorian","DorothĆ©e","Edgard","Edmond","Ɖdouard","ƉleuthĆØre","Ɖlie","ƉlisĆ©e","Ɖmeric","Ɖmile","Ɖmilien","Emmanuel","Enguerrand","Ɖpiphane","Ɖric","Esprit","Ernest","Ɖtienne","Eubert","Eudes","Eudoxe","EugĆØne","EusĆØbe","Eustache","Ɖvariste","Ɖvrard","Fabien","Fabrice","Falba","FĆ©licitĆ©","FĆ©lix","Ferdinand","Fiacre","FidĆØle","Firmin","Flavien","Flodoard","Florent","Florentin","Florestan","Florian","FortunĆ©","Foulques","Francisque","FranƧois","FranƧais","Franciscus","Francs","FrĆ©dĆ©ric","Fulbert","Fulcran","Fulgence","Gabin","Gabriel","GaĆ«l","Garnier","Gaston","Gaspard","Gatien","Gaud","Gautier","GĆ©dĆ©on","Geoffroy","Georges","GĆ©raud","GĆ©rard","Gerbert","Germain","Gervais","Ghislain","Gilbert","Gilles","Girart","Gislebert","Gondebaud","Gonthier","Gontran","Gonzague","GrĆ©goire","GuĆ©rin","Gui","Guillaume","Gustave","Guy","Guyot","Hardouin","Hector","HĆ©delin","HĆ©lier","Henri","Herbert","Herluin","HervĆ©","Hilaire","Hildebert","Hincmar","Hippolyte","HonorĆ©","Hubert","Hugues","Innocent","Isabeau","Isidore","Jacques","Japhet","Jason","Jean","Jeannel","Jeannot","JĆ©rĆ©mie","JĆ©rĆ“me","Joachim","Joanny","Job","Jocelyn","JoĆ«l","Johan","Jonas","Jonathan","Joseph","Josse","Josselin","Jourdain","Jude","JudicaĆ«l","Jules","Julien","Juste","Justin","Lambert","Landry","Laurent","Lazare","LĆ©andre","LĆ©on","LĆ©onard","LĆ©opold","Leu","Loup","Leufroy","LibĆØre","LiĆ©tald","Lionel","LoĆÆc","Longin","Lorrain","Lorraine","Lothaire","Louis","Loup","Luc","Lucas","Lucien","Ludolphe","Ludovic","Macaire","Malo","Mamert","ManassĆ©","Marc","Marceau","Marcel","Marcelin","Marius","Marseille","Martial","Martin","Mathurin","Matthias","Mathias","Matthieu","Maugis","Maurice","Mauricet","Maxence","Maxime","Maximilien","Mayeul","MĆ©dĆ©ric","Melchior","Mence","Merlin","MĆ©rovĆ©e","MichaĆ«l","Michel","MoĆÆse","Morgan","Nathan","NathanaĆ«l","Narcisse","NĆ©hĆ©mie","Nestor","Nestor","NicĆ©phore","Nicolas","NoĆ©","NoĆ«l","Norbert","Normand","Normands","Octave","Odilon","Odon","Oger","Olivier","Oury","PacĆ“me","PalĆ©mon","Parfait","Pascal","Paterne","Patrice","Paul","PĆ©pin","Perceval","PhilĆ©mon","Philibert","Philippe","PhilothĆ©e","Pie","Pierre","Pierrick","Prosper","Quentin","Raoul","RaphaĆ«l","Raymond","RĆ©gis","RĆ©jean","RĆ©mi","Renaud","RenĆ©","Reybaud","Richard","Robert","Roch","Rodolphe","Rodrigue","Roger","Roland","Romain","Romuald","RomĆ©o","Rome","Ronan","Roselin","Salomon","Samuel","Savin","Savinien","Scholastique","SĆ©bastien","SĆ©raphin","Serge","SĆ©verin","Sidoine","Sigebert","Sigismond","SilvĆØre","Simon","SimĆ©on","Sixte","Stanislas","StĆ©phane","Stephan","Sylvain","Sylvestre","TancrĆØde","Tanguy","Taurin","ThĆ©odore","ThĆ©odose","ThĆ©ophile","ThĆ©ophraste","Thibault","Thibert","Thierry","Thomas","TimolĆ©on","TimothĆ©e","Titien","Tonnin","Toussaint","Trajan","Tristan","Turold","Tim","Ulysse","Urbain","Valentin","ValĆØre","ValĆ©ry","Venance","Venant","Venceslas","Vianney","Victor","Victorien","Victorin","Vigile","Vincent","Vital","Vitalien","Vivien","Waleran","Wandrille","Xavier","XĆ©nophon","Yves","Zacharie","ZachĆ©","ZĆ©phirin"] - }, - - "female": { - "en": ["Mary", "Emma", "Elizabeth", "Minnie", "Margaret", "Ida", "Alice", "Bertha", "Sarah", "Annie", "Clara", "Ella", "Florence", "Cora", "Martha", "Laura", "Nellie", "Grace", "Carrie", "Maude", "Mabel", "Bessie", "Jennie", "Gertrude", "Julia", "Hattie", "Edith", "Mattie", "Rose", "Catherine", "Lillian", "Ada", "Lillie", "Helen", "Jessie", "Louise", "Ethel", "Lula", "Myrtle", "Eva", "Frances", "Lena", "Lucy", "Edna", "Maggie", "Pearl", "Daisy", "Fannie", "Josephine", "Dora", "Rosa", "Katherine", "Agnes", "Marie", "Nora", "May", "Mamie", "Blanche", "Stella", "Ellen", "Nancy", "Effie", "Sallie", "Nettie", "Della", "Lizzie", "Flora", "Susie", "Maud", "Mae", "Etta", "Harriet", "Sadie", "Caroline", "Katie", "Lydia", "Elsie", "Kate", "Susan", "Mollie", "Alma", "Addie", "Georgia", "Eliza", "Lulu", "Nannie", "Lottie", "Amanda", "Belle", "Charlotte", "Rebecca", "Ruth", "Viola", "Olive", "Amelia", "Hannah", "Jane", "Virginia", "Emily", "Matilda", "Irene", "Kathryn", "Esther", "Willie", "Henrietta", "Ollie", "Amy", "Rachel", "Sara", "Estella", "Theresa", "Augusta", "Ora", "Pauline", "Josie", "Lola", "Sophia", "Leona", "Anne", "Mildred", "Ann", "Beulah", "Callie", "Lou", "Delia", "Eleanor", "Barbara", "Iva", "Louisa", "Maria", "Mayme", "Evelyn", "Estelle", "Nina", "Betty", "Marion", "Bettie", "Dorothy", "Luella", "Inez", "Lela", "Rosie", "Allie", "Millie", "Janie", "Cornelia", "Victoria", "Ruby", "Winifred", "Alta", "Celia", "Christine", "Beatrice", "Birdie", "Harriett", "Mable", "Myra", "Sophie", "Tillie", "Isabel", "Sylvia", "Carolyn", "Isabelle", "Leila", "Sally", "Ina", "Essie", "Bertie", "Nell", "Alberta", "Katharine", "Lora", "Rena", "Mina", "Rhoda", "Mathilda", "Abbie", "Eula", "Dollie", "Hettie", "Eunice", "Fanny", "Ola", "Lenora", "Adelaide", "Christina", "Lelia", "Nelle", "Sue", "Johanna", "Lilly", "Lucinda", "Minerva", "Lettie", "Roxie", "Cynthia", "Helena", "Hilda", "Hulda", "Bernice", "Genevieve", "Jean", "Cordelia", "Marian", "Francis", "Jeanette", "Adeline", "Gussie", "Leah", "Lois", "Lura", "Mittie", "Hallie", "Isabella", "Olga", "Phoebe", "Teresa", "Hester", "Lida", "Lina", "Winnie", "Claudia", "Marguerite", "Vera", "Cecelia", "Bess", "Emilie", "Rosetta", "Verna", "Myrtie", "Cecilia", "Elva", "Olivia", "Ophelia", "Georgie", "Elnora", "Violet", "Adele", "Lily", "Linnie", "Loretta", "Madge", "Polly", "Virgie", "Eugenia", "Lucile", "Lucille", "Mabelle", "Rosalie"], - // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0162 - "it": ["Ada", "Adriana", "Alessandra", "Alessia", "Alice", "Angela", "Anna", "Anna Maria", "Annalisa", "Annita", "Annunziata", "Antonella", "Arianna", "Asia", "Assunta", "Aurora", "Barbara", "Beatrice", "Benedetta", "Bianca", "Bruna", "Camilla", "Carla", "Carlotta", "Carmela", "Carolina", "Caterina", "Catia", "Cecilia", "Chiara", "Cinzia", "Clara", "Claudia", "Costanza", "Cristina", "Daniela", "Debora", "Diletta", "Dina", "Donatella", "Elena", "Eleonora", "Elisa", "Elisabetta", "Emanuela", "Emma", "Eva", "Federica", "Fernanda", "Fiorella", "Fiorenza", "Flora", "Franca", "Francesca", "Gabriella", "Gaia", "Gemma", "Giada", "Gianna", "Gina", "Ginevra", "Giorgia", "Giovanna", "Giulia", "Giuliana", "Giuseppa", "Giuseppina", "Grazia", "Graziella", "Greta", "Ida", "Ilaria", "Ines", "Iolanda", "Irene", "Irma", "Isabella", "Jessica", "Laura", "Lea", "Letizia", "Licia", "Lidia", "Liliana", "Lina", "Linda", "Lisa", "Livia", "Loretta", "Luana", "Lucia", "Luciana", "Lucrezia", "Luisa", "Manuela", "Mara", "Marcella", "Margherita", "Maria", "Maria Cristina", "Maria Grazia", "Maria Luisa", "Maria Pia", "Maria Teresa", "Marina", "Marisa", "Marta", "Martina", "Marzia", "Matilde", "Melissa", "Michela", "Milena", "Mirella", "Monica", "Natalina", "Nella", "Nicoletta", "Noemi", "Olga", "Paola", "Patrizia", "Piera", "Pierina", "Raffaella", "Rebecca", "Renata", "Rina", "Rita", "Roberta", "Rosa", "Rosanna", "Rossana", "Rossella", "Sabrina", "Sandra", "Sara", "Serena", "Silvana", "Silvia", "Simona", "Simonetta", "Sofia", "Sonia", "Stefania", "Susanna", "Teresa", "Tina", "Tiziana", "Tosca", "Valentina", "Valeria", "Vanda", "Vanessa", "Vanna", "Vera", "Veronica", "Vilma", "Viola", "Virginia", "Vittoria"], - // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html - "nl": ["Ada", "Arianne", "Afke", "Amanda", "Amber", "Amy", "Aniek", "Anita", "Anja", "Anna", "Anne", "Annelies", "Annemarie", "Annette", "Anouk", "Astrid", "Aukje", "Barbara", "Bianca", "Carla", "Carlijn", "Carolien", "Chantal", "Charlotte", "Claudia", "DaniĆ«lle", "Debora", "Diane", "Dora", "Eline", "Elise", "Ella", "Ellen", "Emma", "Esmee", "Evelien", "Esther", "Erica", "Eva", "Femke", "Fleur", "Floor", "Froukje", "Gea", "Gerda", "Hanna", "Hanneke", "Heleen", "Hilde", "Ilona", "Ina", "Inge", "Ingrid", "Iris", "Isabel", "Isabelle", "Janneke", "Jasmijn", "Jeanine", "Jennifer", "Jessica", "Johanna", "Joke", "Julia", "Julie", "Karen", "Karin", "Katja", "Kim", "Lara", "Laura", "Lena", "Lianne", "Lieke", "Lilian", "Linda", "Lisa", "Lisanne", "Lotte", "Louise", "Maaike", "Manon", "Marga", "Maria", "Marissa", "Marit", "Marjolein", "Martine", "Marleen", "Melissa", "Merel", "Miranda", "Michelle", "Mirjam", "Mirthe", "Naomi", "Natalie", 'Nienke', "Nina", "Noortje", "Olivia", "Patricia", "Paula", "Paulien", "Ramona", "Ria", "Rianne", "Roos", "Rosanne", "Ruth", "Sabrina", "Sandra", "Sanne", "Sara", "Saskia", "Silvia", "Sofia", "Sophie", "Sonja", "Suzanne", "Tamara", "Tess", "Tessa", "Tineke", "Valerie", "Vanessa", "Veerle", "Vera", "Victoria", "Wendy", "Willeke", "Yvonne", "ZoĆ«"], - // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie - "fr": ["Abdon","Abel","AbigaĆ«lle","AbigaĆÆl","Acacius","Acanthe","Adalbert","Adalsinde","Adegrine","AdĆ©laĆÆde","AdĆØle","AdĆ©lie","Adeline","Adeltrude","Adolphe","Adonis","AdrastĆ©e","Adrehilde","Adrienne","Agathe","Agilbert","AglaĆ©","Aignan","AgneflĆØte","AgnĆØs","Agrippine","AimĆ©","Alaine","AlaĆÆs","Albane","AlbĆ©rade","Alberte","Alcide","Alcine","Alcyone","Aldegonde","Aleth","Alexandrine","Alexine","Alice","AliĆ©nor","Aliette","Aline","Alix","AlizĆ©","AloĆÆse","Aloyse","Alphonsine","AlthĆ©e","Amaliane","AmalthĆ©e","Amande","Amandine","Amant","Amarande","Amaranthe","Amaryllis","Ambre","Ambroisie","AmĆ©lie","AmĆ©thyste","Aminte","AnaĆ«l","AnaĆÆs","Anastasie","Anatole","Ancelin","AndrĆ©e","AnĆ©mone","AngadrĆŖme","AngĆØle","Angeline","AngĆ©lique","Angilbert","Anicet","Annabelle","Anne","Annette","Annick","Annie","Annonciade","Ansbert","Anstrudie","Anthelme","Antigone","Antoinette","Antonine","AphĆ©lie","Apolline","Apollonie","Aquiline","Arabelle","Arcadie","Archange","Argine","Ariane","Aricie","Ariel","Arielle","Arlette","Armance","Armande","Armandine","Armelle","Armide","Armelle","Armin","Arnaud","ArsĆØne","ArsinoĆ©","ArtĆ©mis","Arthur","Ascelin","Ascension","Assomption","AstartĆ©","AstĆ©rie","AstrĆ©e","Astrid","Athalie","Athanasie","Athina","Aube","Albert","Aude","Audrey","Augustine","Aure","AurĆ©lie","AurĆ©lien","AurĆØle","Aurore","Auxence","Aveline","AbigaĆ«lle","Avoye","Axelle","Aymard","AzalĆ©e","AdĆØle","Adeline","Barbe","Basilisse","Bathilde","BĆ©atrice","BĆ©atrix","BĆ©nĆ©dicte","BĆ©rengĆØre","Bernadette","Berthe","Bertille","Beuve","Blanche","Blanc","Blandine","Brigitte","Brune","Brunehilde","Callista","Camille","Capucine","Carine","Caroline","Cassandre","Catherine","CĆ©cile","CĆ©leste","CĆ©lestine","CĆ©line","Chantal","CharlĆØne","Charline","Charlotte","ChloĆ©","Christelle","Christiane","Christine","Claire","Clara","Claude","Claudine","Clarisse","ClĆ©mence","ClĆ©mentine","ClĆ©o","Clio","Clotilde","Coline","Conception","Constance","Coralie","Coraline","Corentine","Corinne","Cyrielle","Daniel","Daniel","DaphnĆ©","DĆ©bora","Delphine","Denise","Diane","DieudonnĆ©","Dominique","Doriane","DorothĆ©e","Douce","Ɖdith","EdmĆ©e","ƉlĆ©onore","Ɖliane","Ɖlia","Ɖliette","Ɖlisabeth","Ɖlise","Ella","Ɖlodie","ƉloĆÆse","Elsa","Ɖmeline","ƉmĆ©rance","ƉmĆ©rentienne","ƉmĆ©rencie","Ɖmilie","Emma","Emmanuelle","Emmelie","Ernestine","Esther","Estelle","Eudoxie","EugĆ©nie","Eulalie","Euphrasie","EusĆ©bie","ƉvangĆ©line","Eva","ƈve","Ɖvelyne","Fanny","Fantine","Faustine","FĆ©licie","Fernande","Flavie","Fleur","Flore","Florence","Florie","FortunĆ©","France","Francia","FranƧoise","Francine","Gabrielle","GaĆ«lle","Garance","GeneviĆØve","Georgette","Gerberge","Germaine","Gertrude","GisĆØle","GueniĆØvre","Guilhemine","Guillemette","Gustave","Gwenael","HĆ©lĆØne","HĆ©loĆÆse","Henriette","Hermine","Hermione","Hippolyte","Honorine","Hortense","Huguette","Ines","IrĆØne","Irina","Iris","Isabeau","Isabelle","Iseult","Isolde","IsmĆ©rie","Jacinthe","Jacqueline","Jade","Janine","Jeanne","Jocelyne","JoĆ«lle","JosĆ©phine","Judith","Julia","Julie","Jules","Juliette","Justine","Katy","Kathy","Katie","Laura","Laure","Laureline","Laurence","Laurene","Lauriane","Laurianne","Laurine","LĆ©a","LĆ©na","LĆ©onie","LĆ©on","LĆ©ontine","Lorraine","Lucie","Lucienne","Lucille","Ludivine","Lydie","Lydie","Megane","Madeleine","Magali","Maguelone","Mallaury","Manon","Marceline","Margot","Marguerite","Marianne","Marie","Myriam","Marie","Marine","Marion","MarlĆØne","Marthe","Martine","Mathilde","Maud","Maureen","Mauricette","Maxime","MĆ©lanie","Melissa","MĆ©lissandre","MĆ©lisande","MĆ©lodie","Michel","Micheline","Mireille","Miriam","MoĆÆse","Monique","Morgane","Muriel","MylĆØne","NadĆØge","Nadine","Nathalie","Nicole","Nicolette","Nine","NoĆ«l","NoĆ©mie","OcĆ©ane","Odette","Odile","Olive","Olivia","Olympe","Ombline","Ombeline","OphĆ©lie","Oriande","Oriane","Ozanne","Pascale","Pascaline","Paule","Paulette","Pauline","Priscille","Prisca","Prisque","PĆ©cine","PĆ©lagie","PĆ©nĆ©lope","Perrine","PĆ©tronille","Philippine","PhilomĆØne","PhilothĆ©e","Primerose","Prudence","PulchĆ©rie","Quentine","QuiĆ©ta","Quintia","Quintilla","Rachel","RaphaĆ«lle","Raymonde","Rebecca","RĆ©gine","RĆ©jeanne","RenĆ©","Rita","Rita","Rolande","Romane","Rosalie","Rose","Roseline","Sabine","SalomĆ©","Sandra","Sandrine","Sarah","SĆ©golĆØne","SĆ©verine","Sibylle","Simone","Sixt","Solange","Soline","SolĆØne","Sophie","StĆ©phanie","Suzanne","Sylvain","Sylvie","Tatiana","ThaĆÆs","ThĆ©odora","ThĆ©rĆØse","Tiphaine","Ursule","Valentine","ValĆ©rie","VĆ©ronique","Victoire","Victorine","Vinciane","Violette","Virginie","Viviane","XaviĆØre","Yolande","Ysaline","Yvette","Yvonne","ZĆ©lie","Zita","ZoĆ©"] - } - }, - - lastNames: { - "en": ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis', 'Miller', 'Wilson', 'Moore', 'Taylor', 'Anderson', 'Thomas', 'Jackson', 'White', 'Harris', 'Martin', 'Thompson', 'Garcia', 'Martinez', 'Robinson', 'Clark', 'Rodriguez', 'Lewis', 'Lee', 'Walker', 'Hall', 'Allen', 'Young', 'Hernandez', 'King', 'Wright', 'Lopez', 'Hill', 'Scott', 'Green', 'Adams', 'Baker', 'Gonzalez', 'Nelson', 'Carter', 'Mitchell', 'Perez', 'Roberts', 'Turner', 'Phillips', 'Campbell', 'Parker', 'Evans', 'Edwards', 'Collins', 'Stewart', 'Sanchez', 'Morris', 'Rogers', 'Reed', 'Cook', 'Morgan', 'Bell', 'Murphy', 'Bailey', 'Rivera', 'Cooper', 'Richardson', 'Cox', 'Howard', 'Ward', 'Torres', 'Peterson', 'Gray', 'Ramirez', 'James', 'Watson', 'Brooks', 'Kelly', 'Sanders', 'Price', 'Bennett', 'Wood', 'Barnes', 'Ross', 'Henderson', 'Coleman', 'Jenkins', 'Perry', 'Powell', 'Long', 'Patterson', 'Hughes', 'Flores', 'Washington', 'Butler', 'Simmons', 'Foster', 'Gonzales', 'Bryant', 'Alexander', 'Russell', 'Griffin', 'Diaz', 'Hayes', 'Myers', 'Ford', 'Hamilton', 'Graham', 'Sullivan', 'Wallace', 'Woods', 'Cole', 'West', 'Jordan', 'Owens', 'Reynolds', 'Fisher', 'Ellis', 'Harrison', 'Gibson', 'McDonald', 'Cruz', 'Marshall', 'Ortiz', 'Gomez', 'Murray', 'Freeman', 'Wells', 'Webb', 'Simpson', 'Stevens', 'Tucker', 'Porter', 'Hunter', 'Hicks', 'Crawford', 'Henry', 'Boyd', 'Mason', 'Morales', 'Kennedy', 'Warren', 'Dixon', 'Ramos', 'Reyes', 'Burns', 'Gordon', 'Shaw', 'Holmes', 'Rice', 'Robertson', 'Hunt', 'Black', 'Daniels', 'Palmer', 'Mills', 'Nichols', 'Grant', 'Knight', 'Ferguson', 'Rose', 'Stone', 'Hawkins', 'Dunn', 'Perkins', 'Hudson', 'Spencer', 'Gardner', 'Stephens', 'Payne', 'Pierce', 'Berry', 'Matthews', 'Arnold', 'Wagner', 'Willis', 'Ray', 'Watkins', 'Olson', 'Carroll', 'Duncan', 'Snyder', 'Hart', 'Cunningham', 'Bradley', 'Lane', 'Andrews', 'Ruiz', 'Harper', 'Fox', 'Riley', 'Armstrong', 'Carpenter', 'Weaver', 'Greene', 'Lawrence', 'Elliott', 'Chavez', 'Sims', 'Austin', 'Peters', 'Kelley', 'Franklin', 'Lawson', 'Fields', 'Gutierrez', 'Ryan', 'Schmidt', 'Carr', 'Vasquez', 'Castillo', 'Wheeler', 'Chapman', 'Oliver', 'Montgomery', 'Richards', 'Williamson', 'Johnston', 'Banks', 'Meyer', 'Bishop', 'McCoy', 'Howell', 'Alvarez', 'Morrison', 'Hansen', 'Fernandez', 'Garza', 'Harvey', 'Little', 'Burton', 'Stanley', 'Nguyen', 'George', 'Jacobs', 'Reid', 'Kim', 'Fuller', 'Lynch', 'Dean', 'Gilbert', 'Garrett', 'Romero', 'Welch', 'Larson', 'Frazier', 'Burke', 'Hanson', 'Day', 'Mendoza', 'Moreno', 'Bowman', 'Medina', 'Fowler', 'Brewer', 'Hoffman', 'Carlson', 'Silva', 'Pearson', 'Holland', 'Douglas', 'Fleming', 'Jensen', 'Vargas', 'Byrd', 'Davidson', 'Hopkins', 'May', 'Terry', 'Herrera', 'Wade', 'Soto', 'Walters', 'Curtis', 'Neal', 'Caldwell', 'Lowe', 'Jennings', 'Barnett', 'Graves', 'Jimenez', 'Horton', 'Shelton', 'Barrett', 'Obrien', 'Castro', 'Sutton', 'Gregory', 'McKinney', 'Lucas', 'Miles', 'Craig', 'Rodriquez', 'Chambers', 'Holt', 'Lambert', 'Fletcher', 'Watts', 'Bates', 'Hale', 'Rhodes', 'Pena', 'Beck', 'Newman', 'Haynes', 'McDaniel', 'Mendez', 'Bush', 'Vaughn', 'Parks', 'Dawson', 'Santiago', 'Norris', 'Hardy', 'Love', 'Steele', 'Curry', 'Powers', 'Schultz', 'Barker', 'Guzman', 'Page', 'Munoz', 'Ball', 'Keller', 'Chandler', 'Weber', 'Leonard', 'Walsh', 'Lyons', 'Ramsey', 'Wolfe', 'Schneider', 'Mullins', 'Benson', 'Sharp', 'Bowen', 'Daniel', 'Barber', 'Cummings', 'Hines', 'Baldwin', 'Griffith', 'Valdez', 'Hubbard', 'Salazar', 'Reeves', 'Warner', 'Stevenson', 'Burgess', 'Santos', 'Tate', 'Cross', 'Garner', 'Mann', 'Mack', 'Moss', 'Thornton', 'Dennis', 'McGee', 'Farmer', 'Delgado', 'Aguilar', 'Vega', 'Glover', 'Manning', 'Cohen', 'Harmon', 'Rodgers', 'Robbins', 'Newton', 'Todd', 'Blair', 'Higgins', 'Ingram', 'Reese', 'Cannon', 'Strickland', 'Townsend', 'Potter', 'Goodwin', 'Walton', 'Rowe', 'Hampton', 'Ortega', 'Patton', 'Swanson', 'Joseph', 'Francis', 'Goodman', 'Maldonado', 'Yates', 'Becker', 'Erickson', 'Hodges', 'Rios', 'Conner', 'Adkins', 'Webster', 'Norman', 'Malone', 'Hammond', 'Flowers', 'Cobb', 'Moody', 'Quinn', 'Blake', 'Maxwell', 'Pope', 'Floyd', 'Osborne', 'Paul', 'McCarthy', 'Guerrero', 'Lindsey', 'Estrada', 'Sandoval', 'Gibbs', 'Tyler', 'Gross', 'Fitzgerald', 'Stokes', 'Doyle', 'Sherman', 'Saunders', 'Wise', 'Colon', 'Gill', 'Alvarado', 'Greer', 'Padilla', 'Simon', 'Waters', 'Nunez', 'Ballard', 'Schwartz', 'McBride', 'Houston', 'Christensen', 'Klein', 'Pratt', 'Briggs', 'Parsons', 'McLaughlin', 'Zimmerman', 'French', 'Buchanan', 'Moran', 'Copeland', 'Roy', 'Pittman', 'Brady', 'McCormick', 'Holloway', 'Brock', 'Poole', 'Frank', 'Logan', 'Owen', 'Bass', 'Marsh', 'Drake', 'Wong', 'Jefferson', 'Park', 'Morton', 'Abbott', 'Sparks', 'Patrick', 'Norton', 'Huff', 'Clayton', 'Massey', 'Lloyd', 'Figueroa', 'Carson', 'Bowers', 'Roberson', 'Barton', 'Tran', 'Lamb', 'Harrington', 'Casey', 'Boone', 'Cortez', 'Clarke', 'Mathis', 'Singleton', 'Wilkins', 'Cain', 'Bryan', 'Underwood', 'Hogan', 'McKenzie', 'Collier', 'Luna', 'Phelps', 'McGuire', 'Allison', 'Bridges', 'Wilkerson', 'Nash', 'Summers', 'Atkins'], - // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0164 (first 1000) - "it": ["Acciai", "Aglietti", "Agostini", "Agresti", "Ahmed", "Aiazzi", "Albanese", "Alberti", "Alessi", "Alfani", "Alinari", "Alterini", "Amato", "Ammannati", "Ancillotti", "Andrei", "Andreini", "Andreoni", "Angeli", "Anichini", "Antonelli", "Antonini", "Arena", "Ariani", "Arnetoli", "Arrighi", "Baccani", "Baccetti", "Bacci", "Bacherini", "Badii", "Baggiani", "Baglioni", "Bagni", "Bagnoli", "Baldassini", "Baldi", "Baldini", "Ballerini", "Balli", "Ballini", "Balloni", "Bambi", "Banchi", "Bandinelli", "Bandini", "Bani", "Barbetti", "Barbieri", "Barchielli", "Bardazzi", "Bardelli", "Bardi", "Barducci", "Bargellini", "Bargiacchi", "Barni", "Baroncelli", "Baroncini", "Barone", "Baroni", "Baronti", "Bartalesi", "Bartoletti", "Bartoli", "Bartolini", "Bartoloni", "Bartolozzi", "Basagni", "Basile", "Bassi", "Batacchi", "Battaglia", "Battaglini", "Bausi", "Becagli", "Becattini", "Becchi", "Becucci", "Bellandi", "Bellesi", "Belli", "Bellini", "Bellucci", "Bencini", "Benedetti", "Benelli", "Beni", "Benini", "Bensi", "Benucci", "Benvenuti", "Berlincioni", "Bernacchioni", "Bernardi", "Bernardini", "Berni", "Bernini", "Bertelli", "Berti", "Bertini", "Bessi", "Betti", "Bettini", "Biagi", "Biagini", "Biagioni", "Biagiotti", "Biancalani", "Bianchi", "Bianchini", "Bianco", "Biffoli", "Bigazzi", "Bigi", "Biliotti", "Billi", "Binazzi", "Bindi", "Bini", "Biondi", "Bizzarri", "Bocci", "Bogani", "Bolognesi", "Bonaiuti", "Bonanni", "Bonciani", "Boncinelli", "Bondi", "Bonechi", "Bongini", "Boni", "Bonini", "Borchi", "Boretti", "Borghi", "Borghini", "Borgioli", "Borri", "Borselli", "Boschi", "Bottai", "Bracci", "Braccini", "Brandi", "Braschi", "Bravi", "Brazzini", "Breschi", "Brilli", "Brizzi", "Brogelli", "Brogi", "Brogioni", "Brunelli", "Brunetti", "Bruni", "Bruno", "Brunori", "Bruschi", "Bucci", "Bucciarelli", "Buccioni", "Bucelli", "Bulli", "Burberi", "Burchi", "Burgassi", "Burroni", "Bussotti", "Buti", "Caciolli", "Caiani", "Calabrese", "Calamai", "Calamandrei", "Caldini", "Calo'", "Calonaci", "Calosi", "Calvelli", "Cambi", "Camiciottoli", "Cammelli", "Cammilli", "Campolmi", "Cantini", "Capanni", "Capecchi", "Caponi", "Cappelletti", "Cappelli", "Cappellini", "Cappugi", "Capretti", "Caputo", "Carbone", "Carboni", "Cardini", "Carlesi", "Carletti", "Carli", "Caroti", "Carotti", "Carrai", "Carraresi", "Carta", "Caruso", "Casalini", "Casati", "Caselli", "Casini", "Castagnoli", "Castellani", "Castelli", "Castellucci", "Catalano", "Catarzi", "Catelani", "Cavaciocchi", "Cavallaro", "Cavallini", "Cavicchi", "Cavini", "Ceccarelli", "Ceccatelli", "Ceccherelli", "Ceccherini", "Cecchi", "Cecchini", "Cecconi", "Cei", "Cellai", "Celli", "Cellini", "Cencetti", "Ceni", "Cenni", "Cerbai", "Cesari", "Ceseri", "Checcacci", "Checchi", "Checcucci", "Cheli", "Chellini", "Chen", "Cheng", "Cherici", "Cherubini", "Chiaramonti", "Chiarantini", "Chiarelli", "Chiari", "Chiarini", "Chiarugi", "Chiavacci", "Chiesi", "Chimenti", "Chini", "Chirici", "Chiti", "Ciabatti", "Ciampi", "Cianchi", "Cianfanelli", "Cianferoni", "Ciani", "Ciapetti", "Ciappi", "Ciardi", "Ciatti", "Cicali", "Ciccone", "Cinelli", "Cini", "Ciobanu", "Ciolli", "Cioni", "Cipriani", "Cirillo", "Cirri", "Ciucchi", "Ciuffi", "Ciulli", "Ciullini", "Clemente", "Cocchi", "Cognome", "Coli", "Collini", "Colombo", "Colzi", "Comparini", "Conforti", "Consigli", "Conte", "Conti", "Contini", "Coppini", "Coppola", "Corsi", "Corsini", "Corti", "Cortini", "Cosi", "Costa", "Costantini", "Costantino", "Cozzi", "Cresci", "Crescioli", "Cresti", "Crini", "Curradi", "D'Agostino", "D'Alessandro", "D'Amico", "D'Angelo", "Daddi", "Dainelli", "Dallai", "Danti", "Davitti", "De Angelis", "De Luca", "De Marco", "De Rosa", "De Santis", "De Simone", "De Vita", "Degl'Innocenti", "Degli Innocenti", "Dei", "Del Lungo", "Del Re", "Di Marco", "Di Stefano", "Dini", "Diop", "Dobre", "Dolfi", "Donati", "Dondoli", "Dong", "Donnini", "Ducci", "Dumitru", "Ermini", "Esposito", "Evangelisti", "Fabbri", "Fabbrini", "Fabbrizzi", "Fabbroni", "Fabbrucci", "Fabiani", "Facchini", "Faggi", "Fagioli", "Failli", "Faini", "Falciani", "Falcini", "Falcone", "Fallani", "Falorni", "Falsini", "Falugiani", "Fancelli", "Fanelli", "Fanetti", "Fanfani", "Fani", "Fantappie'", "Fantechi", "Fanti", "Fantini", "Fantoni", "Farina", "Fattori", "Favilli", "Fedi", "Fei", "Ferrante", "Ferrara", "Ferrari", "Ferraro", "Ferretti", "Ferri", "Ferrini", "Ferroni", "Fiaschi", "Fibbi", "Fiesoli", "Filippi", "Filippini", "Fini", "Fioravanti", "Fiore", "Fiorentini", "Fiorini", "Fissi", "Focardi", "Foggi", "Fontana", "Fontanelli", "Fontani", "Forconi", "Formigli", "Forte", "Forti", "Fortini", "Fossati", "Fossi", "Francalanci", "Franceschi", "Franceschini", "Franchi", "Franchini", "Franci", "Francini", "Francioni", "Franco", "Frassineti", "Frati", "Fratini", "Frilli", "Frizzi", "Frosali", "Frosini", "Frullini", "Fusco", "Fusi", "Gabbrielli", "Gabellini", "Gagliardi", "Galanti", "Galardi", "Galeotti", "Galletti", "Galli", "Gallo", "Gallori", "Gambacciani", "Gargani", "Garofalo", "Garuglieri", "Gashi", "Gasperini", "Gatti", "Gelli", "Gensini", "Gentile", "Gentili", "Geri", "Gerini", "Gheri", "Ghini", "Giachetti", "Giachi", "Giacomelli", "Gianassi", "Giani", "Giannelli", "Giannetti", "Gianni", "Giannini", "Giannoni", "Giannotti", "Giannozzi", "Gigli", "Giordano", "Giorgetti", "Giorgi", "Giovacchini", "Giovannelli", "Giovannetti", "Giovannini", "Giovannoni", "Giuliani", "Giunti", "Giuntini", "Giusti", "Gonnelli", "Goretti", "Gori", "Gradi", "Gramigni", "Grassi", "Grasso", "Graziani", "Grazzini", "Greco", "Grifoni", "Grillo", "Grimaldi", "Grossi", "Gualtieri", "Guarducci", "Guarino", "Guarnieri", "Guasti", "Guerra", "Guerri", "Guerrini", "Guidi", "Guidotti", "He", "Hoxha", "Hu", "Huang", "Iandelli", "Ignesti", "Innocenti", "Jin", "La Rosa", "Lai", "Landi", "Landini", "Lanini", "Lapi", "Lapini", "Lari", "Lascialfari", "Lastrucci", "Latini", "Lazzeri", "Lazzerini", "Lelli", "Lenzi", "Leonardi", "Leoncini", "Leone", "Leoni", "Lepri", "Li", "Liao", "Lin", "Linari", "Lippi", "Lisi", "Livi", "Lombardi", "Lombardini", "Lombardo", "Longo", "Lopez", "Lorenzi", "Lorenzini", "Lorini", "Lotti", "Lu", "Lucchesi", "Lucherini", "Lunghi", "Lupi", "Madiai", "Maestrini", "Maffei", "Maggi", "Maggini", "Magherini", "Magini", "Magnani", "Magnelli", "Magni", "Magnolfi", "Magrini", "Malavolti", "Malevolti", "Manca", "Mancini", "Manetti", "Manfredi", "Mangani", "Mannelli", "Manni", "Mannini", "Mannucci", "Manuelli", "Manzini", "Marcelli", "Marchese", "Marchetti", "Marchi", "Marchiani", "Marchionni", "Marconi", "Marcucci", "Margheri", "Mari", "Mariani", "Marilli", "Marinai", "Marinari", "Marinelli", "Marini", "Marino", "Mariotti", "Marsili", "Martelli", "Martinelli", "Martini", "Martino", "Marzi", "Masi", "Masini", "Masoni", "Massai", "Materassi", "Mattei", "Matteini", "Matteucci", "Matteuzzi", "Mattioli", "Mattolini", "Matucci", "Mauro", "Mazzanti", "Mazzei", "Mazzetti", "Mazzi", "Mazzini", "Mazzocchi", "Mazzoli", "Mazzoni", "Mazzuoli", "Meacci", "Mecocci", "Meini", "Melani", "Mele", "Meli", "Mengoni", "Menichetti", "Meoni", "Merlini", "Messeri", "Messina", "Meucci", "Miccinesi", "Miceli", "Micheli", "Michelini", "Michelozzi", "Migliori", "Migliorini", "Milani", "Miniati", "Misuri", "Monaco", "Montagnani", "Montagni", "Montanari", "Montelatici", "Monti", "Montigiani", "Montini", "Morandi", "Morandini", "Morelli", "Moretti", "Morganti", "Mori", "Morini", "Moroni", "Morozzi", "Mugnai", "Mugnaini", "Mustafa", "Naldi", "Naldini", "Nannelli", "Nanni", "Nannini", "Nannucci", "Nardi", "Nardini", "Nardoni", "Natali", "Ndiaye", "Nencetti", "Nencini", "Nencioni", "Neri", "Nesi", "Nesti", "Niccolai", "Niccoli", "Niccolini", "Nigi", "Nistri", "Nocentini", "Noferini", "Novelli", "Nucci", "Nuti", "Nutini", "Oliva", "Olivieri", "Olmi", "Orlandi", "Orlandini", "Orlando", "Orsini", "Ortolani", "Ottanelli", "Pacciani", "Pace", "Paci", "Pacini", "Pagani", "Pagano", "Paggetti", "Pagliai", "Pagni", "Pagnini", "Paladini", "Palagi", "Palchetti", "Palloni", "Palmieri", "Palumbo", "Pampaloni", "Pancani", "Pandolfi", "Pandolfini", "Panerai", "Panichi", "Paoletti", "Paoli", "Paolini", "Papi", "Papini", "Papucci", "Parenti", "Parigi", "Parisi", "Parri", "Parrini", "Pasquini", "Passeri", "Pecchioli", "Pecorini", "Pellegrini", "Pepi", "Perini", "Perrone", "Peruzzi", "Pesci", "Pestelli", "Petri", "Petrini", "Petrucci", "Pettini", "Pezzati", "Pezzatini", "Piani", "Piazza", "Piazzesi", "Piazzini", "Piccardi", "Picchi", "Piccini", "Piccioli", "Pieraccini", "Pieraccioni", "Pieralli", "Pierattini", "Pieri", "Pierini", "Pieroni", "Pietrini", "Pini", "Pinna", "Pinto", "Pinzani", "Pinzauti", "Piras", "Pisani", "Pistolesi", "Poggesi", "Poggi", "Poggiali", "Poggiolini", "Poli", "Pollastri", "Porciani", "Pozzi", "Pratellesi", "Pratesi", "Prosperi", "Pruneti", "Pucci", "Puccini", "Puccioni", "Pugi", "Pugliese", "Puliti", "Querci", "Quercioli", "Raddi", "Radu", "Raffaelli", "Ragazzini", "Ranfagni", "Ranieri", "Rastrelli", "Raugei", "Raveggi", "Renai", "Renzi", "Rettori", "Ricci", "Ricciardi", "Ridi", "Ridolfi", "Rigacci", "Righi", "Righini", "Rinaldi", "Risaliti", "Ristori", "Rizzo", "Rocchi", "Rocchini", "Rogai", "Romagnoli", "Romanelli", "Romani", "Romano", "Romei", "Romeo", "Romiti", "Romoli", "Romolini", "Rontini", "Rosati", "Roselli", "Rosi", "Rossetti", "Rossi", "Rossini", "Rovai", "Ruggeri", "Ruggiero", "Russo", "Sabatini", "Saccardi", "Sacchetti", "Sacchi", "Sacco", "Salerno", "Salimbeni", "Salucci", "Salvadori", "Salvestrini", "Salvi", "Salvini", "Sanesi", "Sani", "Sanna", "Santi", "Santini", "Santoni", "Santoro", "Santucci", "Sardi", "Sarri", "Sarti", "Sassi", "Sbolci", "Scali", "Scarpelli", "Scarselli", "Scopetani", "Secci", "Selvi", "Senatori", "Senesi", "Serafini", "Sereni", "Serra", "Sestini", "Sguanci", "Sieni", "Signorini", "Silvestri", "Simoncini", "Simonetti", "Simoni", "Singh", "Sodi", "Soldi", "Somigli", "Sorbi", "Sorelli", "Sorrentino", "Sottili", "Spina", "Spinelli", "Staccioli", "Staderini", "Stefanelli", "Stefani", "Stefanini", "Stella", "Susini", "Tacchi", "Tacconi", "Taddei", "Tagliaferri", "Tamburini", "Tanganelli", "Tani", "Tanini", "Tapinassi", "Tarchi", "Tarchiani", "Targioni", "Tassi", "Tassini", "Tempesti", "Terzani", "Tesi", "Testa", "Testi", "Tilli", "Tinti", "Tirinnanzi", "Toccafondi", "Tofanari", "Tofani", "Tognaccini", "Tonelli", "Tonini", "Torelli", "Torrini", "Tosi", "Toti", "Tozzi", "Trambusti", "Trapani", "Tucci", "Turchi", "Ugolini", "Ulivi", "Valente", "Valenti", "Valentini", "Vangelisti", "Vanni", "Vannini", "Vannoni", "Vannozzi", "Vannucchi", "Vannucci", "Ventura", "Venturi", "Venturini", "Vestri", "Vettori", "Vichi", "Viciani", "Vieri", "Vigiani", "Vignoli", "Vignolini", "Vignozzi", "Villani", "Vinci", "Visani", "Vitale", "Vitali", "Viti", "Viviani", "Vivoli", "Volpe", "Volpi", "Wang", "Wu", "Xu", "Yang", "Ye", "Zagli", "Zani", "Zanieri", "Zanobini", "Zecchi", "Zetti", "Zhang", "Zheng", "Zhou", "Zhu", "Zingoni", "Zini", "Zoppi"], - // http://www.voornamelijk.nl/meest-voorkomende-achternamen-in-nederland-en-amsterdam/ - "nl":["Albers", "Alblas", "Appelman", "Baars", "Baas", "Bakker", "Blank", "Bleeker", "Blok", "Blom", "Boer", "Boers", "Boldewijn", "Boon", "Boot", "Bos", "Bosch", "Bosma", "Bosman", "Bouma", "Bouman", "Bouwman", "Brands", "Brouwer", "Burger", "Buijs", "Buitenhuis", "Ceder", "Cohen", "Dekker", "Dekkers", "Dijkman", "Dijkstra", "Driessen", "Drost", "Engel", "Evers", "Faber", "Franke", "Gerritsen", "Goedhart", "Goossens", "Groen", "Groenenberg", "Groot", "Haan", "Hart", "Heemskerk", "Hendriks", "Hermans", "Hoekstra", "Hofman", "Hopman", "Huisman", "Jacobs", "Jansen", "Janssen", "Jonker", "Jaspers", "Keijzer", "Klaassen", "Klein", "Koek", "Koenders", "Kok", "Kool", "Koopman", "Koopmans", "Koning", "Koster", "Kramer", "Kroon", "Kuijpers", "Kuiper", "Kuipers", "Kurt", "Koster", "Kwakman", "Los", "Lubbers", "Maas", "Markus", "Martens", "Meijer", "Mol", "Molenaar", "Mulder", "Nieuwenhuis", "Peeters", "Peters", "Pengel", "Pieters", "Pool", "Post", "Postma", "Prins", "Pronk", "Reijnders", "Rietveld", "Roest", "Roos", "Sanders", "Schaap", "Scheffer", "Schenk", "Schilder", "Schipper", "Schmidt", "Scholten", "Schouten", "Schut", "Schutte", "Schuurman", "Simons", "Smeets", "Smit", "Smits", "Snel", "Swinkels", "Tas", "Terpstra", "Timmermans", "Tol", "Tromp", "Troost", "Valk", "Veenstra", "Veldkamp", "Verbeek", "Verheul", "Verhoeven", "Vermeer", "Vermeulen", "Verweij", "Vink", "Visser", "Voorn", "Vos", "Wagenaar", "Wiersema", "Willems", "Willemsen", "Witteveen", "Wolff", "Wolters", "Zijlstra", "Zwart", "de Beer", "de Boer", "de Bruijn", "de Bruin", "de Graaf", "de Groot", "de Haan", "de Haas", "de Jager", "de Jong", "de Jonge", "de Koning", "de Lange", "de Leeuw", "de Ridder", "de Rooij", "de Ruiter", "de Vos", "de Vries", "de Waal", "de Wit", "de Zwart", "van Beek", "van Boven", "van Dam", "van Dijk", "van Dongen", "van Doorn", "van Egmond", "van Eijk", "van Es", "van Gelder", "van Gelderen", "van Houten", "van Hulst", "van Kempen", "van Kesteren", "van Leeuwen", "van Loon", "van Mill", "van Noord", "van Ommen", "van Ommeren", "van Oosten", "van Oostveen", "van Rijn", "van Schaik", "van Veen", "van Vliet", "van Wijk", "van Wijngaarden", "van den Poel", "van de Pol", "van den Ploeg", "van de Ven", "van den Berg", "van den Bosch", "van den Brink", "van den Broek", "van den Heuvel", "van der Heijden", "van der Horst", "van der Hulst", "van der Kroon", "van der Laan", "van der Linden", "van der Meer", "van der Meij", "van der Meulen", "van der Molen", "van der Sluis", "van der Spek", "van der Veen", "van der Velde", "van der Velden", "van der Vliet", "van der Wal"], - // https://surnames.behindthename.com/top/lists/england-wales/1991 - "uk":["Smith","Jones","Williams","Taylor","Brown","Davies","Evans","Wilson","Thomas","Johnson","Roberts","Robinson","Thompson","Wright","Walker","White","Edwards","Hughes","Green","Hall","Lewis","Harris","Clarke","Patel","Jackson","Wood","Turner","Martin","Cooper","Hill","Ward","Morris","Moore","Clark","Lee","King","Baker","Harrison","Morgan","Allen","James","Scott","Phillips","Watson","Davis","Parker","Price","Bennett","Young","Griffiths","Mitchell","Kelly","Cook","Carter","Richardson","Bailey","Collins","Bell","Shaw","Murphy","Miller","Cox","Richards","Khan","Marshall","Anderson","Simpson","Ellis","Adams","Singh","Begum","Wilkinson","Foster","Chapman","Powell","Webb","Rogers","Gray","Mason","Ali","Hunt","Hussain","Campbell","Matthews","Owen","Palmer","Holmes","Mills","Barnes","Knight","Lloyd","Butler","Russell","Barker","Fisher","Stevens","Jenkins","Murray","Dixon","Harvey","Graham","Pearson","Ahmed","Fletcher","Walsh","Kaur","Gibson","Howard","Andrews","Stewart","Elliott","Reynolds","Saunders","Payne","Fox","Ford","Pearce","Day","Brooks","West","Lawrence","Cole","Atkinson","Bradley","Spencer","Gill","Dawson","Ball","Burton","O'brien","Watts","Rose","Booth","Perry","Ryan","Grant","Wells","Armstrong","Francis","Rees","Hayes","Hart","Hudson","Newman","Barrett","Webster","Hunter","Gregory","Carr","Lowe","Page","Marsh","Riley","Dunn","Woods","Parsons","Berry","Stone","Reid","Holland","Hawkins","Harding","Porter","Robertson","Newton","Oliver","Reed","Kennedy","Williamson","Bird","Gardner","Shah","Dean","Lane","Cooke","Bates","Henderson","Parry","Burgess","Bishop","Walton","Burns","Nicholson","Shepherd","Ross","Cross","Long","Freeman","Warren","Nicholls","Hamilton","Byrne","Sutton","Mcdonald","Yates","Hodgson","Robson","Curtis","Hopkins","O'connor","Harper","Coleman","Watkins","Moss","Mccarthy","Chambers","O'neill","Griffin","Sharp","Hardy","Wheeler","Potter","Osborne","Johnston","Gordon","Doyle","Wallace","George","Jordan","Hutchinson","Rowe","Burke","May","Pritchard","Gilbert","Willis","Higgins","Read","Miles","Stevenson","Stephenson","Hammond","Arnold","Buckley","Walters","Hewitt","Barber","Nelson","Slater","Austin","Sullivan","Whitehead","Mann","Frost","Lambert","Stephens","Blake","Akhtar","Lynch","Goodwin","Barton","Woodward","Thomson","Cunningham","Quinn","Barnett","Baxter","Bibi","Clayton","Nash","Greenwood","Jennings","Holt","Kemp","Poole","Gallagher","Bond","Stokes","Tucker","Davidson","Fowler","Heath","Norman","Middleton","Lawson","Banks","French","Stanley","Jarvis","Gibbs","Ferguson","Hayward","Carroll","Douglas","Dickinson","Todd","Barlow","Peters","Lucas","Knowles","Hartley","Miah","Simmons","Morton","Alexander","Field","Morrison","Norris","Townsend","Preston","Hancock","Thornton","Baldwin","Burrows","Briggs","Parkinson","Reeves","Macdonald","Lamb","Black","Abbott","Sanders","Thorpe","Holden","Tomlinson","Perkins","Ashton","Rhodes","Fuller","Howe","Bryant","Vaughan","Dale","Davey","Weston","Bartlett","Whittaker","Davison","Kent","Skinner","Birch","Morley","Daniels","Glover","Howell","Cartwright","Pugh","Humphreys","Goddard","Brennan","Wall","Kirby","Bowen","Savage","Bull","Wong","Dobson","Smart","Wilkins","Kirk","Fraser","Duffy","Hicks","Patterson","Bradshaw","Little","Archer","Warner","Waters","O'sullivan","Farrell","Brookes","Atkins","Kay","Dodd","Bentley","Flynn","John","Schofield","Short","Haynes","Wade","Butcher","Henry","Sanderson","Crawford","Sheppard","Bolton","Coates","Giles","Gould","Houghton","Gibbons","Pratt","Manning","Law","Hooper","Noble","Dyer","Rahman","Clements","Moran","Sykes","Chan","Doherty","Connolly","Joyce","Franklin","Hobbs","Coles","Herbert","Steele","Kerr","Leach","Winter","Owens","Duncan","Naylor","Fleming","Horton","Finch","Fitzgerald","Randall","Carpenter","Marsden","Browne","Garner","Pickering","Hale","Dennis","Vincent","Chadwick","Chandler","Sharpe","Nolan","Lyons","Hurst","Collier","Peacock","Howarth","Faulkner","Rice","Pollard","Welch","Norton","Gough","Sinclair","Blackburn","Bryan","Conway","Power","Cameron","Daly","Allan","Hanson","Gardiner","Boyle","Myers","Turnbull","Wallis","Mahmood","Sims","Swift","Iqbal","Pope","Brady","Chamberlain","Rowley","Tyler","Farmer","Metcalfe","Hilton","Godfrey","Holloway","Parkin","Bray","Talbot","Donnelly","Nixon","Charlton","Benson","Whitehouse","Barry","Hope","Lord","North","Storey","Connor","Potts","Bevan","Hargreaves","Mclean","Mistry","Bruce","Howells","Hyde","Parkes","Wyatt","Fry","Lees","O'donnell","Craig","Forster","Mckenzie","Humphries","Mellor","Carey","Ingram","Summers","Leonard"], - // https://surnames.behindthename.com/top/lists/germany/2017 - "de": ["Müller","Schmidt","Schneider","Fischer","Weber","Meyer","Wagner","Becker","Schulz","Hoffmann","SchƤfer","Koch","Bauer","Richter","Klein","Wolf","Schrƶder","Neumann","Schwarz","Zimmermann","Braun","Krüger","Hofmann","Hartmann","Lange","Schmitt","Werner","Schmitz","Krause","Meier","Lehmann","Schmid","Schulze","Maier","Kƶhler","Herrmann","Kƶnig","Walter","Mayer","Huber","Kaiser","Fuchs","Peters","Lang","Scholz","Mƶller","Weiß","Jung","Hahn","Schubert","Vogel","Friedrich","Keller","Günther","Frank","Berger","Winkler","Roth","Beck","Lorenz","Baumann","Franke","Albrecht","Schuster","Simon","Ludwig","Bƶhm","Winter","Kraus","Martin","Schumacher","KrƤmer","Vogt","Stein","JƤger","Otto","Sommer","Groß","Seidel","Heinrich","Brandt","Haas","Schreiber","Graf","Schulte","Dietrich","Ziegler","Kuhn","Kühn","Pohl","Engel","Horn","Busch","Bergmann","Thomas","Voigt","Sauer","Arnold","Wolff","Pfeiffer"], - // http://www.japantimes.co.jp/life/2009/10/11/lifestyle/japans-top-100-most-common-family-names/ - "jp": ["Sato","Suzuki","Takahashi","Tanaka","Watanabe","Ito","Yamamoto","Nakamura","Kobayashi","Kato","Yoshida","Yamada","Sasaki","Yamaguchi","Saito","Matsumoto","Inoue","Kimura","Hayashi","Shimizu","Yamazaki","Mori","Abe","Ikeda","Hashimoto","Yamashita","Ishikawa","Nakajima","Maeda","Fujita","Ogawa","Goto","Okada","Hasegawa","Murakami","Kondo","Ishii","Saito","Sakamoto","Endo","Aoki","Fujii","Nishimura","Fukuda","Ota","Miura","Fujiwara","Okamoto","Matsuda","Nakagawa","Nakano","Harada","Ono","Tamura","Takeuchi","Kaneko","Wada","Nakayama","Ishida","Ueda","Morita","Hara","Shibata","Sakai","Kudo","Yokoyama","Miyazaki","Miyamoto","Uchida","Takagi","Ando","Taniguchi","Ohno","Maruyama","Imai","Takada","Fujimoto","Takeda","Murata","Ueno","Sugiyama","Masuda","Sugawara","Hirano","Kojima","Otsuka","Chiba","Kubo","Matsui","Iwasaki","Sakurai","Kinoshita","Noguchi","Matsuo","Nomura","Kikuchi","Sano","Onishi","Sugimoto","Arai"], - // http://www.lowchensaustralia.com/names/popular-spanish-names.htm - "es": ["Garcia","Fernandez","Lopez","Martinez","Gonzalez","Rodriguez","Sanchez","Perez","Martin","Gomez","Ruiz","Diaz","Hernandez","Alvarez","Jimenez","Moreno","Munoz","Alonso","Romero","Navarro","Gutierrez","Torres","Dominguez","Gil","Vazquez","Blanco","Serrano","Ramos","Castro","Suarez","Sanz","Rubio","Ortega","Molina","Delgado","Ortiz","Morales","Ramirez","Marin","Iglesias","Santos","Castillo","Garrido","Calvo","Pena","Cruz","Cano","Nunez","Prieto","Diez","Lozano","Vidal","Pascual","Ferrer","Medina","Vega","Leon","Herrero","Vicente","Mendez","Guerrero","Fuentes","Campos","Nieto","Cortes","Caballero","Ibanez","Lorenzo","Pastor","Gimenez","Saez","Soler","Marquez","Carrasco","Herrera","Montero","Arias","Crespo","Flores","Andres","Aguilar","Hidalgo","Cabrera","Mora","Duran","Velasco","Rey","Pardo","Roman","Vila","Bravo","Merino","Moya","Soto","Izquierdo","Reyes","Redondo","Marcos","Carmona","Menendez"], - // Data taken from https://fr.wikipedia.org/wiki/Liste_des_noms_de_famille_les_plus_courants_en_France - "fr": ["Martin","Bernard","Thomas","Petit","Robert","Richard","Durand","Dubois","Moreau","Laurent","Simon","Michel","LefĆØvre","Leroy","Roux","David","Bertrand","Morel","Fournier","Girard","Bonnet","Dupont","Lambert","Fontaine","Rousseau","Vincent","Müller","LefĆØvre","Faure","AndrĆ©","Mercier","Blanc","GuĆ©rin","Boyer","Garnier","Chevalier","FranƧois","Legrand","Gauthier","Garcia","Perrin","Robin","ClĆ©ment","Morin","Nicolas","Henry","Roussel","Matthieu","Gautier","Masson","Marchand","Duval","Denis","Dumont","Marie","Lemaire","NoĆ«l","Meyer","Dufour","Meunier","Brun","Blanchard","Giraud","Joly","RiviĆØre","Lucas","Brunet","Gaillard","Barbier","Arnaud","MartĆ­nez","GĆ©rard","Roche","Renard","Schmitt","Roy","Leroux","Colin","Vidal","Caron","Picard","Roger","Fabre","Aubert","Lemoine","Renaud","Dumas","Lacroix","Olivier","Philippe","Bourgeois","Pierre","BenoĆ®t","Rey","Leclerc","Payet","Rolland","Leclercq","Guillaume","Lecomte","López","Jean","Dupuy","Guillot","Hubert","Berger","Carpentier","SĆ”nchez","Dupuis","Moulin","Louis","Deschamps","Huet","Vasseur","Perez","Boucher","Fleury","Royer","Klein","Jacquet","Adam","Paris","Poirier","Marty","Aubry","Guyot","CarrĆ©","Charles","Renault","Charpentier","MĆ©nard","Maillard","Baron","Bertin","Bailly","HervĆ©","Schneider","FernĆ”ndez","Le GallGall","Collet","LĆ©ger","Bouvier","Julien","PrĆ©vost","Millet","Perrot","Daniel","Le RouxRoux","Cousin","Germain","Breton","Besson","Langlois","RĆ©mi","Le GoffGoff","Pelletier","LĆ©vĆŖque","Perrier","Leblanc","BarrĆ©","Lebrun","Marchal","Weber","Mallet","Hamon","Boulanger","Jacob","Monnier","Michaud","RodrĆ­guez","Guichard","Gillet","Ɖtienne","Grondin","Poulain","Tessier","Chevallier","Collin","Chauvin","Da SilvaSilva","Bouchet","Gay","LemaĆ®tre","BĆ©nard","MarĆ©chal","Humbert","Reynaud","Antoine","Hoarau","Perret","BarthĆ©lemy","Cordier","Pichon","Lejeune","Gilbert","Lamy","Delaunay","Pasquier","Carlier","LaporteLaporte"] - }, - - // Data taken from http://geoportal.statistics.gov.uk/datasets/ons-postcode-directory-latest-centroids - postcodeAreas: [{code: 'AB'}, {code: 'AL'}, {code: 'B'}, {code: 'BA'}, {code: 'BB'}, {code: 'BD'}, {code: 'BH'}, {code: 'BL'}, {code: 'BN'}, {code: 'BR'}, {code: 'BS'}, {code: 'BT'}, {code: 'CA'}, {code: 'CB'}, {code: 'CF'}, {code: 'CH'}, {code: 'CM'}, {code: 'CO'}, {code: 'CR'}, {code: 'CT'}, {code: 'CV'}, {code: 'CW'}, {code: 'DA'}, {code: 'DD'}, {code: 'DE'}, {code: 'DG'}, {code: 'DH'}, {code: 'DL'}, {code: 'DN'}, {code: 'DT'}, {code: 'DY'}, {code: 'E'}, {code: 'EC'}, {code: 'EH'}, {code: 'EN'}, {code: 'EX'}, {code: 'FK'}, {code: 'FY'}, {code: 'G'}, {code: 'GL'}, {code: 'GU'}, {code: 'GY'}, {code: 'HA'}, {code: 'HD'}, {code: 'HG'}, {code: 'HP'}, {code: 'HR'}, {code: 'HS'}, {code: 'HU'}, {code: 'HX'}, {code: 'IG'}, {code: 'IM'}, {code: 'IP'}, {code: 'IV'}, {code: 'JE'}, {code: 'KA'}, {code: 'KT'}, {code: 'KW'}, {code: 'KY'}, {code: 'L'}, {code: 'LA'}, {code: 'LD'}, {code: 'LE'}, {code: 'LL'}, {code: 'LN'}, {code: 'LS'}, {code: 'LU'}, {code: 'M'}, {code: 'ME'}, {code: 'MK'}, {code: 'ML'}, {code: 'N'}, {code: 'NE'}, {code: 'NG'}, {code: 'NN'}, {code: 'NP'}, {code: 'NR'}, {code: 'NW'}, {code: 'OL'}, {code: 'OX'}, {code: 'PA'}, {code: 'PE'}, {code: 'PH'}, {code: 'PL'}, {code: 'PO'}, {code: 'PR'}, {code: 'RG'}, {code: 'RH'}, {code: 'RM'}, {code: 'S'}, {code: 'SA'}, {code: 'SE'}, {code: 'SG'}, {code: 'SK'}, {code: 'SL'}, {code: 'SM'}, {code: 'SN'}, {code: 'SO'}, {code: 'SP'}, {code: 'SR'}, {code: 'SS'}, {code: 'ST'}, {code: 'SW'}, {code: 'SY'}, {code: 'TA'}, {code: 'TD'}, {code: 'TF'}, {code: 'TN'}, {code: 'TQ'}, {code: 'TR'}, {code: 'TS'}, {code: 'TW'}, {code: 'UB'}, {code: 'W'}, {code: 'WA'}, {code: 'WC'}, {code: 'WD'}, {code: 'WF'}, {code: 'WN'}, {code: 'WR'}, {code: 'WS'}, {code: 'WV'}, {code: 'YO'}, {code: 'ZE'}], - - // Data taken from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 - countries: [{"name":"Afghanistan","abbreviation":"AF"},{"name":"ƅland Islands","abbreviation":"AX"},{"name":"Albania","abbreviation":"AL"},{"name":"Algeria","abbreviation":"DZ"},{"name":"American Samoa","abbreviation":"AS"},{"name":"Andorra","abbreviation":"AD"},{"name":"Angola","abbreviation":"AO"},{"name":"Anguilla","abbreviation":"AI"},{"name":"Antarctica","abbreviation":"AQ"},{"name":"Antigua and Barbuda","abbreviation":"AG"},{"name":"Argentina","abbreviation":"AR"},{"name":"Armenia","abbreviation":"AM"},{"name":"Aruba","abbreviation":"AW"},{"name":"Australia","abbreviation":"AU"},{"name":"Austria","abbreviation":"AT"},{"name":"Azerbaijan","abbreviation":"AZ"},{"name":"Bahamas","abbreviation":"BS"},{"name":"Bahrain","abbreviation":"BH"},{"name":"Bangladesh","abbreviation":"BD"},{"name":"Barbados","abbreviation":"BB"},{"name":"Belarus","abbreviation":"BY"},{"name":"Belgium","abbreviation":"BE"},{"name":"Belize","abbreviation":"BZ"},{"name":"Benin","abbreviation":"BJ"},{"name":"Bermuda","abbreviation":"BM"},{"name":"Bhutan","abbreviation":"BT"},{"name":"Plurinational State of Bolivia","abbreviation":"BO"},{"name":"Bonaire, Sint Eustatius and Saba","abbreviation":"BQ"},{"name":"Bosnia and Herzegovina","abbreviation":"BA"},{"name":"Botswana","abbreviation":"BW"},{"name":"Bouvet Island","abbreviation":"BV"},{"name":"Brazil","abbreviation":"BR"},{"name":"British Indian Ocean Territory","abbreviation":"IO"},{"name":"Brunei Darussalam","abbreviation":"BN"},{"name":"Bulgaria","abbreviation":"BG"},{"name":"Burkina Faso","abbreviation":"BF"},{"name":"Burundi","abbreviation":"BI"},{"name":"Cabo Verde","abbreviation":"CV"},{"name":"Cambodia","abbreviation":"KH"},{"name":"Cameroon","abbreviation":"CM"},{"name":"Canada","abbreviation":"CA"},{"name":"Cayman Islands","abbreviation":"KY"},{"name":"Central African Republic","abbreviation":"CF"},{"name":"Chad","abbreviation":"TD"},{"name":"Chile","abbreviation":"CL"},{"name":"China","abbreviation":"CN"},{"name":"Christmas Island","abbreviation":"CX"},{"name":"Cocos (Keeling) Islands","abbreviation":"CC"},{"name":"Colombia","abbreviation":"CO"},{"name":"Comoros","abbreviation":"KM"},{"name":"Congo","abbreviation":"CG"},{"name":"Democratic Republic of the Congo","abbreviation":"CD"},{"name":"Cook Islands","abbreviation":"CK"},{"name":"Costa Rica","abbreviation":"CR"},{"name":"CĆ“te d'Ivoire","abbreviation":"CI"},{"name":"Croatia","abbreviation":"HR"},{"name":"Cuba","abbreviation":"CU"},{"name":"CuraƧao","abbreviation":"CW"},{"name":"Cyprus","abbreviation":"CY"},{"name":"Czechia","abbreviation":"CZ"},{"name":"Denmark","abbreviation":"DK"},{"name":"Djibouti","abbreviation":"DJ"},{"name":"Dominica","abbreviation":"DM"},{"name":"Dominican Republic","abbreviation":"DO"},{"name":"Ecuador","abbreviation":"EC"},{"name":"Egypt","abbreviation":"EG"},{"name":"El Salvador","abbreviation":"SV"},{"name":"Equatorial Guinea","abbreviation":"GQ"},{"name":"Eritrea","abbreviation":"ER"},{"name":"Estonia","abbreviation":"EE"},{"name":"Eswatini","abbreviation":"SZ"},{"name":"Ethiopia","abbreviation":"ET"},{"name":"Falkland Islands (Malvinas)","abbreviation":"FK"},{"name":"Faroe Islands","abbreviation":"FO"},{"name":"Fiji","abbreviation":"FJ"},{"name":"Finland","abbreviation":"FI"},{"name":"France","abbreviation":"FR"},{"name":"French Guiana","abbreviation":"GF"},{"name":"French Polynesia","abbreviation":"PF"},{"name":"French Southern Territories","abbreviation":"TF"},{"name":"Gabon","abbreviation":"GA"},{"name":"Gambia","abbreviation":"GM"},{"name":"Georgia","abbreviation":"GE"},{"name":"Germany","abbreviation":"DE"},{"name":"Ghana","abbreviation":"GH"},{"name":"Gibraltar","abbreviation":"GI"},{"name":"Greece","abbreviation":"GR"},{"name":"Greenland","abbreviation":"GL"},{"name":"Grenada","abbreviation":"GD"},{"name":"Guadeloupe","abbreviation":"GP"},{"name":"Guam","abbreviation":"GU"},{"name":"Guatemala","abbreviation":"GT"},{"name":"Guernsey","abbreviation":"GG"},{"name":"Guinea","abbreviation":"GN"},{"name":"Guinea-Bissau","abbreviation":"GW"},{"name":"Guyana","abbreviation":"GY"},{"name":"Haiti","abbreviation":"HT"},{"name":"Heard Island and McDonald Islands","abbreviation":"HM"},{"name":"Holy See","abbreviation":"VA"},{"name":"Honduras","abbreviation":"HN"},{"name":"Hong Kong","abbreviation":"HK"},{"name":"Hungary","abbreviation":"HU"},{"name":"Iceland","abbreviation":"IS"},{"name":"India","abbreviation":"IN"},{"name":"Indonesia","abbreviation":"ID"},{"name":"Islamic Republic of Iran","abbreviation":"IR"},{"name":"Iraq","abbreviation":"IQ"},{"name":"Ireland","abbreviation":"IE"},{"name":"Isle of Man","abbreviation":"IM"},{"name":"Israel","abbreviation":"IL"},{"name":"Italy","abbreviation":"IT"},{"name":"Jamaica","abbreviation":"JM"},{"name":"Japan","abbreviation":"JP"},{"name":"Jersey","abbreviation":"JE"},{"name":"Jordan","abbreviation":"JO"},{"name":"Kazakhstan","abbreviation":"KZ"},{"name":"Kenya","abbreviation":"KE"},{"name":"Kiribati","abbreviation":"KI"},{"name":"Democratic People's Republic of Korea","abbreviation":"KP"},{"name":"Republic of Korea","abbreviation":"KR"},{"name":"Kuwait","abbreviation":"KW"},{"name":"Kyrgyzstan","abbreviation":"KG"},{"name":"Lao People's Democratic Republic","abbreviation":"LA"},{"name":"Latvia","abbreviation":"LV"},{"name":"Lebanon","abbreviation":"LB"},{"name":"Lesotho","abbreviation":"LS"},{"name":"Liberia","abbreviation":"LR"},{"name":"Libya","abbreviation":"LY"},{"name":"Liechtenstein","abbreviation":"LI"},{"name":"Lithuania","abbreviation":"LT"},{"name":"Luxembourg","abbreviation":"LU"},{"name":"Macao","abbreviation":"MO"},{"name":"Madagascar","abbreviation":"MG"},{"name":"Malawi","abbreviation":"MW"},{"name":"Malaysia","abbreviation":"MY"},{"name":"Maldives","abbreviation":"MV"},{"name":"Mali","abbreviation":"ML"},{"name":"Malta","abbreviation":"MT"},{"name":"Marshall Islands","abbreviation":"MH"},{"name":"Martinique","abbreviation":"MQ"},{"name":"Mauritania","abbreviation":"MR"},{"name":"Mauritius","abbreviation":"MU"},{"name":"Mayotte","abbreviation":"YT"},{"name":"Mexico","abbreviation":"MX"},{"name":"Federated States of Micronesia","abbreviation":"FM"},{"name":"Republic of Moldova","abbreviation":"MD"},{"name":"Monaco","abbreviation":"MC"},{"name":"Mongolia","abbreviation":"MN"},{"name":"Montenegro","abbreviation":"ME"},{"name":"Montserrat","abbreviation":"MS"},{"name":"Morocco","abbreviation":"MA"},{"name":"Mozambique","abbreviation":"MZ"},{"name":"Myanmar","abbreviation":"MM"},{"name":"Namibia","abbreviation":"NA"},{"name":"Nauru","abbreviation":"NR"},{"name":"Nepal","abbreviation":"NP"},{"name":"Kingdom of the Netherlands","abbreviation":"NL"},{"name":"New Caledonia","abbreviation":"NC"},{"name":"New Zealand","abbreviation":"NZ"},{"name":"Nicaragua","abbreviation":"NI"},{"name":"Niger","abbreviation":"NE"},{"name":"Nigeria","abbreviation":"NG"},{"name":"Niue","abbreviation":"NU"},{"name":"Norfolk Island","abbreviation":"NF"},{"name":"North Macedonia","abbreviation":"MK"},{"name":"Northern Mariana Islands","abbreviation":"MP"},{"name":"Norway","abbreviation":"NO"},{"name":"Oman","abbreviation":"OM"},{"name":"Pakistan","abbreviation":"PK"},{"name":"Palau","abbreviation":"PW"},{"name":"State of Palestine","abbreviation":"PS"},{"name":"Panama","abbreviation":"PA"},{"name":"Papua New Guinea","abbreviation":"PG"},{"name":"Paraguay","abbreviation":"PY"},{"name":"Peru","abbreviation":"PE"},{"name":"Philippines","abbreviation":"PH"},{"name":"Pitcairn","abbreviation":"PN"},{"name":"Poland","abbreviation":"PL"},{"name":"Portugal","abbreviation":"PT"},{"name":"Puerto Rico","abbreviation":"PR"},{"name":"Qatar","abbreviation":"QA"},{"name":"RĆ©union","abbreviation":"RE"},{"name":"Romania","abbreviation":"RO"},{"name":"Russian Federation","abbreviation":"RU"},{"name":"Rwanda","abbreviation":"RW"},{"name":"Saint BarthĆ©lemy","abbreviation":"BL"},{"name":"Saint Helena, Ascension and Tristan da Cunha","abbreviation":"SH"},{"name":"Saint Kitts and Nevis","abbreviation":"KN"},{"name":"Saint Lucia","abbreviation":"LC"},{"name":"Saint Martin (French part)","abbreviation":"MF"},{"name":"Saint Pierre and Miquelon","abbreviation":"PM"},{"name":"Saint Vincent and the Grenadines","abbreviation":"VC"},{"name":"Samoa","abbreviation":"WS"},{"name":"San Marino","abbreviation":"SM"},{"name":"Sao Tome and Principe","abbreviation":"ST"},{"name":"Saudi Arabia","abbreviation":"SA"},{"name":"Senegal","abbreviation":"SN"},{"name":"Serbia","abbreviation":"RS"},{"name":"Seychelles","abbreviation":"SC"},{"name":"Sierra Leone","abbreviation":"SL"},{"name":"Singapore","abbreviation":"SG"},{"name":"Sint Maarten (Dutch part)","abbreviation":"SX"},{"name":"Slovakia","abbreviation":"SK"},{"name":"Slovenia","abbreviation":"SI"},{"name":"Solomon Islands","abbreviation":"SB"},{"name":"Somalia","abbreviation":"SO"},{"name":"South Africa","abbreviation":"ZA"},{"name":"South Georgia and the South Sandwich Islands","abbreviation":"GS"},{"name":"South Sudan","abbreviation":"SS"},{"name":"Spain","abbreviation":"ES"},{"name":"Sri Lanka","abbreviation":"LK"},{"name":"Sudan","abbreviation":"SD"},{"name":"Suriname","abbreviation":"SR"},{"name":"Svalbard and Jan Mayen","abbreviation":"SJ"},{"name":"Sweden","abbreviation":"SE"},{"name":"Switzerland","abbreviation":"CH"},{"name":"Syrian Arab Republic","abbreviation":"SY"},{"name":"Taiwan, Province of China","abbreviation":"TW"},{"name":"Tajikistan","abbreviation":"TJ"},{"name":"United Republic of Tanzania","abbreviation":"TZ"},{"name":"Thailand","abbreviation":"TH"},{"name":"Timor-Leste","abbreviation":"TL"},{"name":"Togo","abbreviation":"TG"},{"name":"Tokelau","abbreviation":"TK"},{"name":"Tonga","abbreviation":"TO"},{"name":"Trinidad and Tobago","abbreviation":"TT"},{"name":"Tunisia","abbreviation":"TN"},{"name":"Türkiye","abbreviation":"TR"},{"name":"Turkmenistan","abbreviation":"TM"},{"name":"Turks and Caicos Islands","abbreviation":"TC"},{"name":"Tuvalu","abbreviation":"TV"},{"name":"Uganda","abbreviation":"UG"},{"name":"Ukraine","abbreviation":"UA"},{"name":"United Arab Emirates","abbreviation":"AE"},{"name":"United Kingdom of Great Britain and Northern Ireland","abbreviation":"GB"},{"name":"United States Minor Outlying Islands","abbreviation":"UM"},{"name":"United States of America","abbreviation":"US"},{"name":"Uruguay","abbreviation":"UY"},{"name":"Uzbekistan","abbreviation":"UZ"},{"name":"Vanuatu","abbreviation":"VU"},{"name":"Bolivarian Republic of Venezuela","abbreviation":"VE"},{"name":"Viet Nam","abbreviation":"VN"},{"name":"Virgin Islands (British)","abbreviation":"VG"},{"name":"Virgin Islands (U.S.)","abbreviation":"VI"},{"name":"Wallis and Futuna","abbreviation":"WF"},{"name":"Western Sahara","abbreviation":"EH"},{"name":"Yemen","abbreviation":"YE"},{"name":"Zambia","abbreviation":"ZM"},{"name":"Zimbabwe","abbreviation":"ZW"}], - - counties: { - // Data taken from http://www.downloadexcelfiles.com/gb_en/download-excel-file-list-counties-uk - "uk": [ - {name: 'Bath and North East Somerset'}, - {name: 'Aberdeenshire'}, - {name: 'Anglesey'}, - {name: 'Angus'}, - {name: 'Bedford'}, - {name: 'Blackburn with Darwen'}, - {name: 'Blackpool'}, - {name: 'Bournemouth'}, - {name: 'Bracknell Forest'}, - {name: 'Brighton & Hove'}, - {name: 'Bristol'}, - {name: 'Buckinghamshire'}, - {name: 'Cambridgeshire'}, - {name: 'Carmarthenshire'}, - {name: 'Central Bedfordshire'}, - {name: 'Ceredigion'}, - {name: 'Cheshire East'}, - {name: 'Cheshire West and Chester'}, - {name: 'Clackmannanshire'}, - {name: 'Conwy'}, - {name: 'Cornwall'}, - {name: 'County Antrim'}, - {name: 'County Armagh'}, - {name: 'County Down'}, - {name: 'County Durham'}, - {name: 'County Fermanagh'}, - {name: 'County Londonderry'}, - {name: 'County Tyrone'}, - {name: 'Cumbria'}, - {name: 'Darlington'}, - {name: 'Denbighshire'}, - {name: 'Derby'}, - {name: 'Derbyshire'}, - {name: 'Devon'}, - {name: 'Dorset'}, - {name: 'Dumfries and Galloway'}, - {name: 'Dundee'}, - {name: 'East Lothian'}, - {name: 'East Riding of Yorkshire'}, - {name: 'East Sussex'}, - {name: 'Edinburgh?'}, - {name: 'Essex'}, - {name: 'Falkirk'}, - {name: 'Fife'}, - {name: 'Flintshire'}, - {name: 'Gloucestershire'}, - {name: 'Greater London'}, - {name: 'Greater Manchester'}, - {name: 'Gwent'}, - {name: 'Gwynedd'}, - {name: 'Halton'}, - {name: 'Hampshire'}, - {name: 'Hartlepool'}, - {name: 'Herefordshire'}, - {name: 'Hertfordshire'}, - {name: 'Highlands'}, - {name: 'Hull'}, - {name: 'Isle of Wight'}, - {name: 'Isles of Scilly'}, - {name: 'Kent'}, - {name: 'Lancashire'}, - {name: 'Leicester'}, - {name: 'Leicestershire'}, - {name: 'Lincolnshire'}, - {name: 'Lothian'}, - {name: 'Luton'}, - {name: 'Medway'}, - {name: 'Merseyside'}, - {name: 'Mid Glamorgan'}, - {name: 'Middlesbrough'}, - {name: 'Milton Keynes'}, - {name: 'Monmouthshire'}, - {name: 'Moray'}, - {name: 'Norfolk'}, - {name: 'North East Lincolnshire'}, - {name: 'North Lincolnshire'}, - {name: 'North Somerset'}, - {name: 'North Yorkshire'}, - {name: 'Northamptonshire'}, - {name: 'Northumberland'}, - {name: 'Nottingham'}, - {name: 'Nottinghamshire'}, - {name: 'Oxfordshire'}, - {name: 'Pembrokeshire'}, - {name: 'Perth and Kinross'}, - {name: 'Peterborough'}, - {name: 'Plymouth'}, - {name: 'Poole'}, - {name: 'Portsmouth'}, - {name: 'Powys'}, - {name: 'Reading'}, - {name: 'Redcar and Cleveland'}, - {name: 'Rutland'}, - {name: 'Scottish Borders'}, - {name: 'Shropshire'}, - {name: 'Slough'}, - {name: 'Somerset'}, - {name: 'South Glamorgan'}, - {name: 'South Gloucestershire'}, - {name: 'South Yorkshire'}, - {name: 'Southampton'}, - {name: 'Southend-on-Sea'}, - {name: 'Staffordshire'}, - {name: 'Stirlingshire'}, - {name: 'Stockton-on-Tees'}, - {name: 'Stoke-on-Trent'}, - {name: 'Strathclyde'}, - {name: 'Suffolk'}, - {name: 'Surrey'}, - {name: 'Swindon'}, - {name: 'Telford and Wrekin'}, - {name: 'Thurrock'}, - {name: 'Torbay'}, - {name: 'Tyne and Wear'}, - {name: 'Warrington'}, - {name: 'Warwickshire'}, - {name: 'West Berkshire'}, - {name: 'West Glamorgan'}, - {name: 'West Lothian'}, - {name: 'West Midlands'}, - {name: 'West Sussex'}, - {name: 'West Yorkshire'}, - {name: 'Western Isles'}, - {name: 'Wiltshire'}, - {name: 'Windsor and Maidenhead'}, - {name: 'Wokingham'}, - {name: 'Worcestershire'}, - {name: 'Wrexham'}, - {name: 'York'}] - }, - provinces: { - "ca": [ - {name: 'Alberta', abbreviation: 'AB'}, - {name: 'British Columbia', abbreviation: 'BC'}, - {name: 'Manitoba', abbreviation: 'MB'}, - {name: 'New Brunswick', abbreviation: 'NB'}, - {name: 'Newfoundland and Labrador', abbreviation: 'NL'}, - {name: 'Nova Scotia', abbreviation: 'NS'}, - {name: 'Ontario', abbreviation: 'ON'}, - {name: 'Prince Edward Island', abbreviation: 'PE'}, - {name: 'Quebec', abbreviation: 'QC'}, - {name: 'Saskatchewan', abbreviation: 'SK'}, - - // The case could be made that the following are not actually provinces - // since they are technically considered "territories" however they all - // look the same on an envelope! - {name: 'Northwest Territories', abbreviation: 'NT'}, - {name: 'Nunavut', abbreviation: 'NU'}, - {name: 'Yukon', abbreviation: 'YT'} - ], - "it": [ - { name: "Agrigento", abbreviation: "AG", code: 84 }, - { name: "Alessandria", abbreviation: "AL", code: 6 }, - { name: "Ancona", abbreviation: "AN", code: 42 }, - { name: "Aosta", abbreviation: "AO", code: 7 }, - { name: "L'Aquila", abbreviation: "AQ", code: 66 }, - { name: "Arezzo", abbreviation: "AR", code: 51 }, - { name: "Ascoli-Piceno", abbreviation: "AP", code: 44 }, - { name: "Asti", abbreviation: "AT", code: 5 }, - { name: "Avellino", abbreviation: "AV", code: 64 }, - { name: "Bari", abbreviation: "BA", code: 72 }, - { name: "Barletta-Andria-Trani", abbreviation: "BT", code: 72 }, - { name: "Belluno", abbreviation: "BL", code: 25 }, - { name: "Benevento", abbreviation: "BN", code: 62 }, - { name: "Bergamo", abbreviation: "BG", code: 16 }, - { name: "Biella", abbreviation: "BI", code: 96 }, - { name: "Bologna", abbreviation: "BO", code: 37 }, - { name: "Bolzano", abbreviation: "BZ", code: 21 }, - { name: "Brescia", abbreviation: "BS", code: 17 }, - { name: "Brindisi", abbreviation: "BR", code: 74 }, - { name: "Cagliari", abbreviation: "CA", code: 92 }, - { name: "Caltanissetta", abbreviation: "CL", code: 85 }, - { name: "Campobasso", abbreviation: "CB", code: 70 }, - { name: "Carbonia Iglesias", abbreviation: "CI", code: 70 }, - { name: "Caserta", abbreviation: "CE", code: 61 }, - { name: "Catania", abbreviation: "CT", code: 87 }, - { name: "Catanzaro", abbreviation: "CZ", code: 79 }, - { name: "Chieti", abbreviation: "CH", code: 69 }, - { name: "Como", abbreviation: "CO", code: 13 }, - { name: "Cosenza", abbreviation: "CS", code: 78 }, - { name: "Cremona", abbreviation: "CR", code: 19 }, - { name: "Crotone", abbreviation: "KR", code: 101 }, - { name: "Cuneo", abbreviation: "CN", code: 4 }, - { name: "Enna", abbreviation: "EN", code: 86 }, - { name: "Fermo", abbreviation: "FM", code: 86 }, - { name: "Ferrara", abbreviation: "FE", code: 38 }, - { name: "Firenze", abbreviation: "FI", code: 48 }, - { name: "Foggia", abbreviation: "FG", code: 71 }, - { name: "Forli-Cesena", abbreviation: "FC", code: 71 }, - { name: "Frosinone", abbreviation: "FR", code: 60 }, - { name: "Genova", abbreviation: "GE", code: 10 }, - { name: "Gorizia", abbreviation: "GO", code: 31 }, - { name: "Grosseto", abbreviation: "GR", code: 53 }, - { name: "Imperia", abbreviation: "IM", code: 8 }, - { name: "Isernia", abbreviation: "IS", code: 94 }, - { name: "La-Spezia", abbreviation: "SP", code: 66 }, - { name: "Latina", abbreviation: "LT", code: 59 }, - { name: "Lecce", abbreviation: "LE", code: 75 }, - { name: "Lecco", abbreviation: "LC", code: 97 }, - { name: "Livorno", abbreviation: "LI", code: 49 }, - { name: "Lodi", abbreviation: "LO", code: 98 }, - { name: "Lucca", abbreviation: "LU", code: 46 }, - { name: "Macerata", abbreviation: "MC", code: 43 }, - { name: "Mantova", abbreviation: "MN", code: 20 }, - { name: "Massa-Carrara", abbreviation: "MS", code: 45 }, - { name: "Matera", abbreviation: "MT", code: 77 }, - { name: "Medio Campidano", abbreviation: "VS", code: 77 }, - { name: "Messina", abbreviation: "ME", code: 83 }, - { name: "Milano", abbreviation: "MI", code: 15 }, - { name: "Modena", abbreviation: "MO", code: 36 }, - { name: "Monza-Brianza", abbreviation: "MB", code: 36 }, - { name: "Napoli", abbreviation: "NA", code: 63 }, - { name: "Novara", abbreviation: "NO", code: 3 }, - { name: "Nuoro", abbreviation: "NU", code: 91 }, - { name: "Ogliastra", abbreviation: "OG", code: 91 }, - { name: "Olbia Tempio", abbreviation: "OT", code: 91 }, - { name: "Oristano", abbreviation: "OR", code: 95 }, - { name: "Padova", abbreviation: "PD", code: 28 }, - { name: "Palermo", abbreviation: "PA", code: 82 }, - { name: "Parma", abbreviation: "PR", code: 34 }, - { name: "Pavia", abbreviation: "PV", code: 18 }, - { name: "Perugia", abbreviation: "PG", code: 54 }, - { name: "Pesaro-Urbino", abbreviation: "PU", code: 41 }, - { name: "Pescara", abbreviation: "PE", code: 68 }, - { name: "Piacenza", abbreviation: "PC", code: 33 }, - { name: "Pisa", abbreviation: "PI", code: 50 }, - { name: "Pistoia", abbreviation: "PT", code: 47 }, - { name: "Pordenone", abbreviation: "PN", code: 93 }, - { name: "Potenza", abbreviation: "PZ", code: 76 }, - { name: "Prato", abbreviation: "PO", code: 100 }, - { name: "Ragusa", abbreviation: "RG", code: 88 }, - { name: "Ravenna", abbreviation: "RA", code: 39 }, - { name: "Reggio-Calabria", abbreviation: "RC", code: 35 }, - { name: "Reggio-Emilia", abbreviation: "RE", code: 35 }, - { name: "Rieti", abbreviation: "RI", code: 57 }, - { name: "Rimini", abbreviation: "RN", code: 99 }, - { name: "Roma", abbreviation: "Roma", code: 58 }, - { name: "Rovigo", abbreviation: "RO", code: 29 }, - { name: "Salerno", abbreviation: "SA", code: 65 }, - { name: "Sassari", abbreviation: "SS", code: 90 }, - { name: "Savona", abbreviation: "SV", code: 9 }, - { name: "Siena", abbreviation: "SI", code: 52 }, - { name: "Siracusa", abbreviation: "SR", code: 89 }, - { name: "Sondrio", abbreviation: "SO", code: 14 }, - { name: "Taranto", abbreviation: "TA", code: 73 }, - { name: "Teramo", abbreviation: "TE", code: 67 }, - { name: "Terni", abbreviation: "TR", code: 55 }, - { name: "Torino", abbreviation: "TO", code: 1 }, - { name: "Trapani", abbreviation: "TP", code: 81 }, - { name: "Trento", abbreviation: "TN", code: 22 }, - { name: "Treviso", abbreviation: "TV", code: 26 }, - { name: "Trieste", abbreviation: "TS", code: 32 }, - { name: "Udine", abbreviation: "UD", code: 30 }, - { name: "Varese", abbreviation: "VA", code: 12 }, - { name: "Venezia", abbreviation: "VE", code: 27 }, - { name: "Verbania", abbreviation: "VB", code: 27 }, - { name: "Vercelli", abbreviation: "VC", code: 2 }, - { name: "Verona", abbreviation: "VR", code: 23 }, - { name: "Vibo-Valentia", abbreviation: "VV", code: 102 }, - { name: "Vicenza", abbreviation: "VI", code: 24 }, - { name: "Viterbo", abbreviation: "VT", code: 56 } - ] - }, - - // from: https://github.com/samsargent/Useful-Autocomplete-Data/blob/master/data/nationalities.json - nationalities: [ - {name: 'Afghan'}, - {name: 'Albanian'}, - {name: 'Algerian'}, - {name: 'American'}, - {name: 'Andorran'}, - {name: 'Angolan'}, - {name: 'Antiguans'}, - {name: 'Argentinean'}, - {name: 'Armenian'}, - {name: 'Australian'}, - {name: 'Austrian'}, - {name: 'Azerbaijani'}, - {name: 'Bahami'}, - {name: 'Bahraini'}, - {name: 'Bangladeshi'}, - {name: 'Barbadian'}, - {name: 'Barbudans'}, - {name: 'Batswana'}, - {name: 'Belarusian'}, - {name: 'Belgian'}, - {name: 'Belizean'}, - {name: 'Beninese'}, - {name: 'Bhutanese'}, - {name: 'Bolivian'}, - {name: 'Bosnian'}, - {name: 'Brazilian'}, - {name: 'British'}, - {name: 'Bruneian'}, - {name: 'Bulgarian'}, - {name: 'Burkinabe'}, - {name: 'Burmese'}, - {name: 'Burundian'}, - {name: 'Cambodian'}, - {name: 'Cameroonian'}, - {name: 'Canadian'}, - {name: 'Cape Verdean'}, - {name: 'Central African'}, - {name: 'Chadian'}, - {name: 'Chilean'}, - {name: 'Chinese'}, - {name: 'Colombian'}, - {name: 'Comoran'}, - {name: 'Congolese'}, - {name: 'Costa Rican'}, - {name: 'Croatian'}, - {name: 'Cuban'}, - {name: 'Cypriot'}, - {name: 'Czech'}, - {name: 'Danish'}, - {name: 'Djibouti'}, - {name: 'Dominican'}, - {name: 'Dutch'}, - {name: 'East Timorese'}, - {name: 'Ecuadorean'}, - {name: 'Egyptian'}, - {name: 'Emirian'}, - {name: 'Equatorial Guinean'}, - {name: 'Eritrean'}, - {name: 'Estonian'}, - {name: 'Ethiopian'}, - {name: 'Fijian'}, - {name: 'Filipino'}, - {name: 'Finnish'}, - {name: 'French'}, - {name: 'Gabonese'}, - {name: 'Gambian'}, - {name: 'Georgian'}, - {name: 'German'}, - {name: 'Ghanaian'}, - {name: 'Greek'}, - {name: 'Grenadian'}, - {name: 'Guatemalan'}, - {name: 'Guinea-Bissauan'}, - {name: 'Guinean'}, - {name: 'Guyanese'}, - {name: 'Haitian'}, - {name: 'Herzegovinian'}, - {name: 'Honduran'}, - {name: 'Hungarian'}, - {name: 'I-Kiribati'}, - {name: 'Icelander'}, - {name: 'Indian'}, - {name: 'Indonesian'}, - {name: 'Iranian'}, - {name: 'Iraqi'}, - {name: 'Irish'}, - {name: 'Israeli'}, - {name: 'Italian'}, - {name: 'Ivorian'}, - {name: 'Jamaican'}, - {name: 'Japanese'}, - {name: 'Jordanian'}, - {name: 'Kazakhstani'}, - {name: 'Kenyan'}, - {name: 'Kittian and Nevisian'}, - {name: 'Kuwaiti'}, - {name: 'Kyrgyz'}, - {name: 'Laotian'}, - {name: 'Latvian'}, - {name: 'Lebanese'}, - {name: 'Liberian'}, - {name: 'Libyan'}, - {name: 'Liechtensteiner'}, - {name: 'Lithuanian'}, - {name: 'Luxembourger'}, - {name: 'Macedonian'}, - {name: 'Malagasy'}, - {name: 'Malawian'}, - {name: 'Malaysian'}, - {name: 'Maldivan'}, - {name: 'Malian'}, - {name: 'Maltese'}, - {name: 'Marshallese'}, - {name: 'Mauritanian'}, - {name: 'Mauritian'}, - {name: 'Mexican'}, - {name: 'Micronesian'}, - {name: 'Moldovan'}, - {name: 'Monacan'}, - {name: 'Mongolian'}, - {name: 'Moroccan'}, - {name: 'Mosotho'}, - {name: 'Motswana'}, - {name: 'Mozambican'}, - {name: 'Namibian'}, - {name: 'Nauruan'}, - {name: 'Nepalese'}, - {name: 'New Zealander'}, - {name: 'Nicaraguan'}, - {name: 'Nigerian'}, - {name: 'Nigerien'}, - {name: 'North Korean'}, - {name: 'Northern Irish'}, - {name: 'Norwegian'}, - {name: 'Omani'}, - {name: 'Pakistani'}, - {name: 'Palauan'}, - {name: 'Panamanian'}, - {name: 'Papua New Guinean'}, - {name: 'Paraguayan'}, - {name: 'Peruvian'}, - {name: 'Polish'}, - {name: 'Portuguese'}, - {name: 'Qatari'}, - {name: 'Romani'}, - {name: 'Russian'}, - {name: 'Rwandan'}, - {name: 'Saint Lucian'}, - {name: 'Salvadoran'}, - {name: 'Samoan'}, - {name: 'San Marinese'}, - {name: 'Sao Tomean'}, - {name: 'Saudi'}, - {name: 'Scottish'}, - {name: 'Senegalese'}, - {name: 'Serbian'}, - {name: 'Seychellois'}, - {name: 'Sierra Leonean'}, - {name: 'Singaporean'}, - {name: 'Slovakian'}, - {name: 'Slovenian'}, - {name: 'Solomon Islander'}, - {name: 'Somali'}, - {name: 'South African'}, - {name: 'South Korean'}, - {name: 'Spanish'}, - {name: 'Sri Lankan'}, - {name: 'Sudanese'}, - {name: 'Surinamer'}, - {name: 'Swazi'}, - {name: 'Swedish'}, - {name: 'Swiss'}, - {name: 'Syrian'}, - {name: 'Taiwanese'}, - {name: 'Tajik'}, - {name: 'Tanzanian'}, - {name: 'Thai'}, - {name: 'Togolese'}, - {name: 'Tongan'}, - {name: 'Trinidadian or Tobagonian'}, - {name: 'Tunisian'}, - {name: 'Turkish'}, - {name: 'Tuvaluan'}, - {name: 'Ugandan'}, - {name: 'Ukrainian'}, - {name: 'Uruguaya'}, - {name: 'Uzbekistani'}, - {name: 'Venezuela'}, - {name: 'Vietnamese'}, - {name: 'Wels'}, - {name: 'Yemenit'}, - {name: 'Zambia'}, - {name: 'Zimbabwe'}, - ], - // http://www.loc.gov/standards/iso639-2/php/code_list.php (ISO-639-1 codes) - locale_languages: [ - "aa", - "ab", - "ae", - "af", - "ak", - "am", - "an", - "ar", - "as", - "av", - "ay", - "az", - "ba", - "be", - "bg", - "bh", - "bi", - "bm", - "bn", - "bo", - "br", - "bs", - "ca", - "ce", - "ch", - "co", - "cr", - "cs", - "cu", - "cv", - "cy", - "da", - "de", - "dv", - "dz", - "ee", - "el", - "en", - "eo", - "es", - "et", - "eu", - "fa", - "ff", - "fi", - "fj", - "fo", - "fr", - "fy", - "ga", - "gd", - "gl", - "gn", - "gu", - "gv", - "ha", - "he", - "hi", - "ho", - "hr", - "ht", - "hu", - "hy", - "hz", - "ia", - "id", - "ie", - "ig", - "ii", - "ik", - "io", - "is", - "it", - "iu", - "ja", - "jv", - "ka", - "kg", - "ki", - "kj", - "kk", - "kl", - "km", - "kn", - "ko", - "kr", - "ks", - "ku", - "kv", - "kw", - "ky", - "la", - "lb", - "lg", - "li", - "ln", - "lo", - "lt", - "lu", - "lv", - "mg", - "mh", - "mi", - "mk", - "ml", - "mn", - "mr", - "ms", - "mt", - "my", - "na", - "nb", - "nd", - "ne", - "ng", - "nl", - "nn", - "no", - "nr", - "nv", - "ny", - "oc", - "oj", - "om", - "or", - "os", - "pa", - "pi", - "pl", - "ps", - "pt", - "qu", - "rm", - "rn", - "ro", - "ru", - "rw", - "sa", - "sc", - "sd", - "se", - "sg", - "si", - "sk", - "sl", - "sm", - "sn", - "so", - "sq", - "sr", - "ss", - "st", - "su", - "sv", - "sw", - "ta", - "te", - "tg", - "th", - "ti", - "tk", - "tl", - "tn", - "to", - "tr", - "ts", - "tt", - "tw", - "ty", - "ug", - "uk", - "ur", - "uz", - "ve", - "vi", - "vo", - "wa", - "wo", - "xh", - "yi", - "yo", - "za", - "zh", - "zu" - ], - - // From http://data.okfn.org/data/core/language-codes#resource-language-codes-full (IETF language tags) - locale_regions: [ - "agq-CM", - "asa-TZ", - "ast-ES", - "bas-CM", - "bem-ZM", - "bez-TZ", - "brx-IN", - "cgg-UG", - "chr-US", - "dav-KE", - "dje-NE", - "dsb-DE", - "dua-CM", - "dyo-SN", - "ebu-KE", - "ewo-CM", - "fil-PH", - "fur-IT", - "gsw-CH", - "gsw-FR", - "gsw-LI", - "guz-KE", - "haw-US", - "hsb-DE", - "jgo-CM", - "jmc-TZ", - "kab-DZ", - "kam-KE", - "kde-TZ", - "kea-CV", - "khq-ML", - "kkj-CM", - "kln-KE", - "kok-IN", - "ksb-TZ", - "ksf-CM", - "ksh-DE", - "lag-TZ", - "lkt-US", - "luo-KE", - "luy-KE", - "mas-KE", - "mas-TZ", - "mer-KE", - "mfe-MU", - "mgh-MZ", - "mgo-CM", - "mua-CM", - "naq-NA", - "nmg-CM", - "nnh-CM", - "nus-SD", - "nyn-UG", - "rof-TZ", - "rwk-TZ", - "sah-RU", - "saq-KE", - "sbp-TZ", - "seh-MZ", - "ses-ML", - "shi-Latn", - "shi-Latn-MA", - "shi-Tfng", - "shi-Tfng-MA", - "smn-FI", - "teo-KE", - "teo-UG", - "twq-NE", - "tzm-Latn", - "tzm-Latn-MA", - "vai-Latn", - "vai-Latn-LR", - "vai-Vaii", - "vai-Vaii-LR", - "vun-TZ", - "wae-CH", - "xog-UG", - "yav-CM", - "zgh-MA", - "af-NA", - "af-ZA", - "ak-GH", - "am-ET", - "ar-001", - "ar-AE", - "ar-BH", - "ar-DJ", - "ar-DZ", - "ar-EG", - "ar-EH", - "ar-ER", - "ar-IL", - "ar-IQ", - "ar-JO", - "ar-KM", - "ar-KW", - "ar-LB", - "ar-LY", - "ar-MA", - "ar-MR", - "ar-OM", - "ar-PS", - "ar-QA", - "ar-SA", - "ar-SD", - "ar-SO", - "ar-SS", - "ar-SY", - "ar-TD", - "ar-TN", - "ar-YE", - "as-IN", - "az-Cyrl", - "az-Cyrl-AZ", - "az-Latn", - "az-Latn-AZ", - "be-BY", - "bg-BG", - "bm-Latn", - "bm-Latn-ML", - "bn-BD", - "bn-IN", - "bo-CN", - "bo-IN", - "br-FR", - "bs-Cyrl", - "bs-Cyrl-BA", - "bs-Latn", - "bs-Latn-BA", - "ca-AD", - "ca-ES", - "ca-ES-VALENCIA", - "ca-FR", - "ca-IT", - "cs-CZ", - "cy-GB", - "da-DK", - "da-GL", - "de-AT", - "de-BE", - "de-CH", - "de-DE", - "de-LI", - "de-LU", - "dz-BT", - "ee-GH", - "ee-TG", - "el-CY", - "el-GR", - "en-001", - "en-150", - "en-AG", - "en-AI", - "en-AS", - "en-AU", - "en-BB", - "en-BE", - "en-BM", - "en-BS", - "en-BW", - "en-BZ", - "en-CA", - "en-CC", - "en-CK", - "en-CM", - "en-CX", - "en-DG", - "en-DM", - "en-ER", - "en-FJ", - "en-FK", - "en-FM", - "en-GB", - "en-GD", - "en-GG", - "en-GH", - "en-GI", - "en-GM", - "en-GU", - "en-GY", - "en-HK", - "en-IE", - "en-IM", - "en-IN", - "en-IO", - "en-JE", - "en-JM", - "en-KE", - "en-KI", - "en-KN", - "en-KY", - "en-LC", - "en-LR", - "en-LS", - "en-MG", - "en-MH", - "en-MO", - "en-MP", - "en-MS", - "en-MT", - "en-MU", - "en-MW", - "en-MY", - "en-NA", - "en-NF", - "en-NG", - "en-NR", - "en-NU", - "en-NZ", - "en-PG", - "en-PH", - "en-PK", - "en-PN", - "en-PR", - "en-PW", - "en-RW", - "en-SB", - "en-SC", - "en-SD", - "en-SG", - "en-SH", - "en-SL", - "en-SS", - "en-SX", - "en-SZ", - "en-TC", - "en-TK", - "en-TO", - "en-TT", - "en-TV", - "en-TZ", - "en-UG", - "en-UM", - "en-US", - "en-US-POSIX", - "en-VC", - "en-VG", - "en-VI", - "en-VU", - "en-WS", - "en-ZA", - "en-ZM", - "en-ZW", - "eo-001", - "es-419", - "es-AR", - "es-BO", - "es-CL", - "es-CO", - "es-CR", - "es-CU", - "es-DO", - "es-EA", - "es-EC", - "es-ES", - "es-GQ", - "es-GT", - "es-HN", - "es-IC", - "es-MX", - "es-NI", - "es-PA", - "es-PE", - "es-PH", - "es-PR", - "es-PY", - "es-SV", - "es-US", - "es-UY", - "es-VE", - "et-EE", - "eu-ES", - "fa-AF", - "fa-IR", - "ff-CM", - "ff-GN", - "ff-MR", - "ff-SN", - "fi-FI", - "fo-FO", - "fr-BE", - "fr-BF", - "fr-BI", - "fr-BJ", - "fr-BL", - "fr-CA", - "fr-CD", - "fr-CF", - "fr-CG", - "fr-CH", - "fr-CI", - "fr-CM", - "fr-DJ", - "fr-DZ", - "fr-FR", - "fr-GA", - "fr-GF", - "fr-GN", - "fr-GP", - "fr-GQ", - "fr-HT", - "fr-KM", - "fr-LU", - "fr-MA", - "fr-MC", - "fr-MF", - "fr-MG", - "fr-ML", - "fr-MQ", - "fr-MR", - "fr-MU", - "fr-NC", - "fr-NE", - "fr-PF", - "fr-PM", - "fr-RE", - "fr-RW", - "fr-SC", - "fr-SN", - "fr-SY", - "fr-TD", - "fr-TG", - "fr-TN", - "fr-VU", - "fr-WF", - "fr-YT", - "fy-NL", - "ga-IE", - "gd-GB", - "gl-ES", - "gu-IN", - "gv-IM", - "ha-Latn", - "ha-Latn-GH", - "ha-Latn-NE", - "ha-Latn-NG", - "he-IL", - "hi-IN", - "hr-BA", - "hr-HR", - "hu-HU", - "hy-AM", - "id-ID", - "ig-NG", - "ii-CN", - "is-IS", - "it-CH", - "it-IT", - "it-SM", - "ja-JP", - "ka-GE", - "ki-KE", - "kk-Cyrl", - "kk-Cyrl-KZ", - "kl-GL", - "km-KH", - "kn-IN", - "ko-KP", - "ko-KR", - "ks-Arab", - "ks-Arab-IN", - "kw-GB", - "ky-Cyrl", - "ky-Cyrl-KG", - "lb-LU", - "lg-UG", - "ln-AO", - "ln-CD", - "ln-CF", - "ln-CG", - "lo-LA", - "lt-LT", - "lu-CD", - "lv-LV", - "mg-MG", - "mk-MK", - "ml-IN", - "mn-Cyrl", - "mn-Cyrl-MN", - "mr-IN", - "ms-Latn", - "ms-Latn-BN", - "ms-Latn-MY", - "ms-Latn-SG", - "mt-MT", - "my-MM", - "nb-NO", - "nb-SJ", - "nd-ZW", - "ne-IN", - "ne-NP", - "nl-AW", - "nl-BE", - "nl-BQ", - "nl-CW", - "nl-NL", - "nl-SR", - "nl-SX", - "nn-NO", - "om-ET", - "om-KE", - "or-IN", - "os-GE", - "os-RU", - "pa-Arab", - "pa-Arab-PK", - "pa-Guru", - "pa-Guru-IN", - "pl-PL", - "ps-AF", - "pt-AO", - "pt-BR", - "pt-CV", - "pt-GW", - "pt-MO", - "pt-MZ", - "pt-PT", - "pt-ST", - "pt-TL", - "qu-BO", - "qu-EC", - "qu-PE", - "rm-CH", - "rn-BI", - "ro-MD", - "ro-RO", - "ru-BY", - "ru-KG", - "ru-KZ", - "ru-MD", - "ru-RU", - "ru-UA", - "rw-RW", - "se-FI", - "se-NO", - "se-SE", - "sg-CF", - "si-LK", - "sk-SK", - "sl-SI", - "sn-ZW", - "so-DJ", - "so-ET", - "so-KE", - "so-SO", - "sq-AL", - "sq-MK", - "sq-XK", - "sr-Cyrl", - "sr-Cyrl-BA", - "sr-Cyrl-ME", - "sr-Cyrl-RS", - "sr-Cyrl-XK", - "sr-Latn", - "sr-Latn-BA", - "sr-Latn-ME", - "sr-Latn-RS", - "sr-Latn-XK", - "sv-AX", - "sv-FI", - "sv-SE", - "sw-CD", - "sw-KE", - "sw-TZ", - "sw-UG", - "ta-IN", - "ta-LK", - "ta-MY", - "ta-SG", - "te-IN", - "th-TH", - "ti-ER", - "ti-ET", - "to-TO", - "tr-CY", - "tr-TR", - "ug-Arab", - "ug-Arab-CN", - "uk-UA", - "ur-IN", - "ur-PK", - "uz-Arab", - "uz-Arab-AF", - "uz-Cyrl", - "uz-Cyrl-UZ", - "uz-Latn", - "uz-Latn-UZ", - "vi-VN", - "yi-001", - "yo-BJ", - "yo-NG", - "zh-Hans", - "zh-Hans-CN", - "zh-Hans-HK", - "zh-Hans-MO", - "zh-Hans-SG", - "zh-Hant", - "zh-Hant-HK", - "zh-Hant-MO", - "zh-Hant-TW", - "zu-ZA" - ], - - us_states_and_dc: [ - {name: 'Alabama', abbreviation: 'AL'}, - {name: 'Alaska', abbreviation: 'AK'}, - {name: 'Arizona', abbreviation: 'AZ'}, - {name: 'Arkansas', abbreviation: 'AR'}, - {name: 'California', abbreviation: 'CA'}, - {name: 'Colorado', abbreviation: 'CO'}, - {name: 'Connecticut', abbreviation: 'CT'}, - {name: 'Delaware', abbreviation: 'DE'}, - {name: 'District of Columbia', abbreviation: 'DC'}, - {name: 'Florida', abbreviation: 'FL'}, - {name: 'Georgia', abbreviation: 'GA'}, - {name: 'Hawaii', abbreviation: 'HI'}, - {name: 'Idaho', abbreviation: 'ID'}, - {name: 'Illinois', abbreviation: 'IL'}, - {name: 'Indiana', abbreviation: 'IN'}, - {name: 'Iowa', abbreviation: 'IA'}, - {name: 'Kansas', abbreviation: 'KS'}, - {name: 'Kentucky', abbreviation: 'KY'}, - {name: 'Louisiana', abbreviation: 'LA'}, - {name: 'Maine', abbreviation: 'ME'}, - {name: 'Maryland', abbreviation: 'MD'}, - {name: 'Massachusetts', abbreviation: 'MA'}, - {name: 'Michigan', abbreviation: 'MI'}, - {name: 'Minnesota', abbreviation: 'MN'}, - {name: 'Mississippi', abbreviation: 'MS'}, - {name: 'Missouri', abbreviation: 'MO'}, - {name: 'Montana', abbreviation: 'MT'}, - {name: 'Nebraska', abbreviation: 'NE'}, - {name: 'Nevada', abbreviation: 'NV'}, - {name: 'New Hampshire', abbreviation: 'NH'}, - {name: 'New Jersey', abbreviation: 'NJ'}, - {name: 'New Mexico', abbreviation: 'NM'}, - {name: 'New York', abbreviation: 'NY'}, - {name: 'North Carolina', abbreviation: 'NC'}, - {name: 'North Dakota', abbreviation: 'ND'}, - {name: 'Ohio', abbreviation: 'OH'}, - {name: 'Oklahoma', abbreviation: 'OK'}, - {name: 'Oregon', abbreviation: 'OR'}, - {name: 'Pennsylvania', abbreviation: 'PA'}, - {name: 'Rhode Island', abbreviation: 'RI'}, - {name: 'South Carolina', abbreviation: 'SC'}, - {name: 'South Dakota', abbreviation: 'SD'}, - {name: 'Tennessee', abbreviation: 'TN'}, - {name: 'Texas', abbreviation: 'TX'}, - {name: 'Utah', abbreviation: 'UT'}, - {name: 'Vermont', abbreviation: 'VT'}, - {name: 'Virginia', abbreviation: 'VA'}, - {name: 'Washington', abbreviation: 'WA'}, - {name: 'West Virginia', abbreviation: 'WV'}, - {name: 'Wisconsin', abbreviation: 'WI'}, - {name: 'Wyoming', abbreviation: 'WY'} - ], - - territories: [ - {name: 'American Samoa', abbreviation: 'AS'}, - {name: 'Federated States of Micronesia', abbreviation: 'FM'}, - {name: 'Guam', abbreviation: 'GU'}, - {name: 'Marshall Islands', abbreviation: 'MH'}, - {name: 'Northern Mariana Islands', abbreviation: 'MP'}, - {name: 'Puerto Rico', abbreviation: 'PR'}, - {name: 'Virgin Islands, U.S.', abbreviation: 'VI'} - ], - - armed_forces: [ - {name: 'Armed Forces Europe', abbreviation: 'AE'}, - {name: 'Armed Forces Pacific', abbreviation: 'AP'}, - {name: 'Armed Forces the Americas', abbreviation: 'AA'} - ], - - country_regions: { - it: [ - { name: "Valle d'Aosta", abbreviation: "VDA" }, - { name: "Piemonte", abbreviation: "PIE" }, - { name: "Lombardia", abbreviation: "LOM" }, - { name: "Veneto", abbreviation: "VEN" }, - { name: "Trentino Alto Adige", abbreviation: "TAA" }, - { name: "Friuli Venezia Giulia", abbreviation: "FVG" }, - { name: "Liguria", abbreviation: "LIG" }, - { name: "Emilia Romagna", abbreviation: "EMR" }, - { name: "Toscana", abbreviation: "TOS" }, - { name: "Umbria", abbreviation: "UMB" }, - { name: "Marche", abbreviation: "MAR" }, - { name: "Abruzzo", abbreviation: "ABR" }, - { name: "Lazio", abbreviation: "LAZ" }, - { name: "Campania", abbreviation: "CAM" }, - { name: "Puglia", abbreviation: "PUG" }, - { name: "Basilicata", abbreviation: "BAS" }, - { name: "Molise", abbreviation: "MOL" }, - { name: "Calabria", abbreviation: "CAL" }, - { name: "Sicilia", abbreviation: "SIC" }, - { name: "Sardegna", abbreviation: "SAR" } - ], - mx: [ - { name: 'Aguascalientes', abbreviation: 'AGU' }, - { name: 'Baja California', abbreviation: 'BCN' }, - { name: 'Baja California Sur', abbreviation: 'BCS' }, - { name: 'Campeche', abbreviation: 'CAM' }, - { name: 'Chiapas', abbreviation: 'CHP' }, - { name: 'Chihuahua', abbreviation: 'CHH' }, - { name: 'Ciudad de MĆ©xico', abbreviation: 'DIF' }, - { name: 'Coahuila', abbreviation: 'COA' }, - { name: 'Colima', abbreviation: 'COL' }, - { name: 'Durango', abbreviation: 'DUR' }, - { name: 'Guanajuato', abbreviation: 'GUA' }, - { name: 'Guerrero', abbreviation: 'GRO' }, - { name: 'Hidalgo', abbreviation: 'HID' }, - { name: 'Jalisco', abbreviation: 'JAL' }, - { name: 'MĆ©xico', abbreviation: 'MEX' }, - { name: 'MichoacĆ”n', abbreviation: 'MIC' }, - { name: 'Morelos', abbreviation: 'MOR' }, - { name: 'Nayarit', abbreviation: 'NAY' }, - { name: 'Nuevo León', abbreviation: 'NLE' }, - { name: 'Oaxaca', abbreviation: 'OAX' }, - { name: 'Puebla', abbreviation: 'PUE' }, - { name: 'QuerĆ©taro', abbreviation: 'QUE' }, - { name: 'Quintana Roo', abbreviation: 'ROO' }, - { name: 'San Luis PotosĆ­', abbreviation: 'SLP' }, - { name: 'Sinaloa', abbreviation: 'SIN' }, - { name: 'Sonora', abbreviation: 'SON' }, - { name: 'Tabasco', abbreviation: 'TAB' }, - { name: 'Tamaulipas', abbreviation: 'TAM' }, - { name: 'Tlaxcala', abbreviation: 'TLA' }, - { name: 'Veracruz', abbreviation: 'VER' }, - { name: 'YucatĆ”n', abbreviation: 'YUC' }, - { name: 'Zacatecas', abbreviation: 'ZAC' } - ] - }, - - street_suffixes: { - 'us': [ - {name: 'Avenue', abbreviation: 'Ave'}, - {name: 'Boulevard', abbreviation: 'Blvd'}, - {name: 'Center', abbreviation: 'Ctr'}, - {name: 'Circle', abbreviation: 'Cir'}, - {name: 'Court', abbreviation: 'Ct'}, - {name: 'Drive', abbreviation: 'Dr'}, - {name: 'Extension', abbreviation: 'Ext'}, - {name: 'Glen', abbreviation: 'Gln'}, - {name: 'Grove', abbreviation: 'Grv'}, - {name: 'Heights', abbreviation: 'Hts'}, - {name: 'Highway', abbreviation: 'Hwy'}, - {name: 'Junction', abbreviation: 'Jct'}, - {name: 'Key', abbreviation: 'Key'}, - {name: 'Lane', abbreviation: 'Ln'}, - {name: 'Loop', abbreviation: 'Loop'}, - {name: 'Manor', abbreviation: 'Mnr'}, - {name: 'Mill', abbreviation: 'Mill'}, - {name: 'Park', abbreviation: 'Park'}, - {name: 'Parkway', abbreviation: 'Pkwy'}, - {name: 'Pass', abbreviation: 'Pass'}, - {name: 'Path', abbreviation: 'Path'}, - {name: 'Pike', abbreviation: 'Pike'}, - {name: 'Place', abbreviation: 'Pl'}, - {name: 'Plaza', abbreviation: 'Plz'}, - {name: 'Point', abbreviation: 'Pt'}, - {name: 'Ridge', abbreviation: 'Rdg'}, - {name: 'River', abbreviation: 'Riv'}, - {name: 'Road', abbreviation: 'Rd'}, - {name: 'Square', abbreviation: 'Sq'}, - {name: 'Street', abbreviation: 'St'}, - {name: 'Terrace', abbreviation: 'Ter'}, - {name: 'Trail', abbreviation: 'Trl'}, - {name: 'Turnpike', abbreviation: 'Tpke'}, - {name: 'View', abbreviation: 'Vw'}, - {name: 'Way', abbreviation: 'Way'} - ], - 'it': [ - { name: 'Accesso', abbreviation: 'Acc.' }, - { name: 'Alzaia', abbreviation: 'Alz.' }, - { name: 'Arco', abbreviation: 'Arco' }, - { name: 'Archivolto', abbreviation: 'Acv.' }, - { name: 'Arena', abbreviation: 'Arena' }, - { name: 'Argine', abbreviation: 'Argine' }, - { name: 'Bacino', abbreviation: 'Bacino' }, - { name: 'Banchi', abbreviation: 'Banchi' }, - { name: 'Banchina', abbreviation: 'Ban.' }, - { name: 'Bastioni', abbreviation: 'Bas.' }, - { name: 'Belvedere', abbreviation: 'Belv.' }, - { name: 'Borgata', abbreviation: 'B.ta' }, - { name: 'Borgo', abbreviation: 'B.go' }, - { name: 'Calata', abbreviation: 'Cal.' }, - { name: 'Calle', abbreviation: 'Calle' }, - { name: 'Campiello', abbreviation: 'Cam.' }, - { name: 'Campo', abbreviation: 'Cam.' }, - { name: 'Canale', abbreviation: 'Can.' }, - { name: 'Carraia', abbreviation: 'Carr.' }, - { name: 'Cascina', abbreviation: 'Cascina' }, - { name: 'Case sparse', abbreviation: 'c.s.' }, - { name: 'Cavalcavia', abbreviation: 'Cv.' }, - { name: 'Circonvallazione', abbreviation: 'Cv.' }, - { name: 'Complanare', abbreviation: 'C.re' }, - { name: 'Contrada', abbreviation: 'C.da' }, - { name: 'Corso', abbreviation: 'C.so' }, - { name: 'Corte', abbreviation: 'C.te' }, - { name: 'Cortile', abbreviation: 'C.le' }, - { name: 'Diramazione', abbreviation: 'Dir.' }, - { name: 'Fondaco', abbreviation: 'F.co' }, - { name: 'Fondamenta', abbreviation: 'F.ta' }, - { name: 'Fondo', abbreviation: 'F.do' }, - { name: 'Frazione', abbreviation: 'Fr.' }, - { name: 'Isola', abbreviation: 'Is.' }, - { name: 'Largo', abbreviation: 'L.go' }, - { name: 'Litoranea', abbreviation: 'Lit.' }, - { name: 'Lungolago', abbreviation: 'L.go lago' }, - { name: 'Lungo Po', abbreviation: 'l.go Po' }, - { name: 'Molo', abbreviation: 'Molo' }, - { name: 'Mura', abbreviation: 'Mura' }, - { name: 'Passaggio privato', abbreviation: 'pass. priv.' }, - { name: 'Passeggiata', abbreviation: 'Pass.' }, - { name: 'Piazza', abbreviation: 'P.zza' }, - { name: 'Piazzale', abbreviation: 'P.le' }, - { name: 'Ponte', abbreviation: 'P.te' }, - { name: 'Portico', abbreviation: 'P.co' }, - { name: 'Rampa', abbreviation: 'Rampa' }, - { name: 'Regione', abbreviation: 'Reg.' }, - { name: 'Rione', abbreviation: 'R.ne' }, - { name: 'Rio', abbreviation: 'Rio' }, - { name: 'Ripa', abbreviation: 'Ripa' }, - { name: 'Riva', abbreviation: 'Riva' }, - { name: 'Rondò', abbreviation: 'Rondò' }, - { name: 'Rotonda', abbreviation: 'Rot.' }, - { name: 'Sagrato', abbreviation: 'Sagr.' }, - { name: 'Salita', abbreviation: 'Sal.' }, - { name: 'Scalinata', abbreviation: 'Scal.' }, - { name: 'Scalone', abbreviation: 'Scal.' }, - { name: 'Slargo', abbreviation: 'Sl.' }, - { name: 'Sottoportico', abbreviation: 'Sott.' }, - { name: 'Strada', abbreviation: 'Str.' }, - { name: 'Stradale', abbreviation: 'Str.le' }, - { name: 'Strettoia', abbreviation: 'Strett.' }, - { name: 'Traversa', abbreviation: 'Trav.' }, - { name: 'Via', abbreviation: 'V.' }, - { name: 'Viale', abbreviation: 'V.le' }, - { name: 'Vicinale', abbreviation: 'Vic.le' }, - { name: 'Vicolo', abbreviation: 'Vic.' } - ], - 'uk' : [ - {name: 'Avenue', abbreviation: 'Ave'}, - {name: 'Close', abbreviation: 'Cl'}, - {name: 'Court', abbreviation: 'Ct'}, - {name: 'Crescent', abbreviation: 'Cr'}, - {name: 'Drive', abbreviation: 'Dr'}, - {name: 'Garden', abbreviation: 'Gdn'}, - {name: 'Gardens', abbreviation: 'Gdns'}, - {name: 'Green', abbreviation: 'Gn'}, - {name: 'Grove', abbreviation: 'Gr'}, - {name: 'Lane', abbreviation: 'Ln'}, - {name: 'Mount', abbreviation: 'Mt'}, - {name: 'Place', abbreviation: 'Pl'}, - {name: 'Park', abbreviation: 'Pk'}, - {name: 'Ridge', abbreviation: 'Rdg'}, - {name: 'Road', abbreviation: 'Rd'}, - {name: 'Square', abbreviation: 'Sq'}, - {name: 'Street', abbreviation: 'St'}, - {name: 'Terrace', abbreviation: 'Ter'}, - {name: 'Valley', abbreviation: 'Val'} - ] - }, - - months: [ - {name: 'January', short_name: 'Jan', numeric: '01', days: 31}, - // Not messing with leap years... - {name: 'February', short_name: 'Feb', numeric: '02', days: 28}, - {name: 'March', short_name: 'Mar', numeric: '03', days: 31}, - {name: 'April', short_name: 'Apr', numeric: '04', days: 30}, - {name: 'May', short_name: 'May', numeric: '05', days: 31}, - {name: 'June', short_name: 'Jun', numeric: '06', days: 30}, - {name: 'July', short_name: 'Jul', numeric: '07', days: 31}, - {name: 'August', short_name: 'Aug', numeric: '08', days: 31}, - {name: 'September', short_name: 'Sep', numeric: '09', days: 30}, - {name: 'October', short_name: 'Oct', numeric: '10', days: 31}, - {name: 'November', short_name: 'Nov', numeric: '11', days: 30}, - {name: 'December', short_name: 'Dec', numeric: '12', days: 31} - ], - - // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 - cc_types: [ - {name: "American Express", short_name: 'amex', prefix: '34', length: 15}, - {name: "Bankcard", short_name: 'bankcard', prefix: '5610', length: 16}, - {name: "China UnionPay", short_name: 'chinaunion', prefix: '62', length: 16}, - {name: "Diners Club Carte Blanche", short_name: 'dccarte', prefix: '300', length: 14}, - {name: "Diners Club enRoute", short_name: 'dcenroute', prefix: '2014', length: 15}, - {name: "Diners Club International", short_name: 'dcintl', prefix: '36', length: 14}, - {name: "Diners Club United States & Canada", short_name: 'dcusc', prefix: '54', length: 16}, - {name: "Discover Card", short_name: 'discover', prefix: '6011', length: 16}, - {name: "InstaPayment", short_name: 'instapay', prefix: '637', length: 16}, - {name: "JCB", short_name: 'jcb', prefix: '3528', length: 16}, - {name: "Laser", short_name: 'laser', prefix: '6304', length: 16}, - {name: "Maestro", short_name: 'maestro', prefix: '5018', length: 16}, - {name: "Mastercard", short_name: 'mc', prefix: '51', length: 16}, - {name: "Solo", short_name: 'solo', prefix: '6334', length: 16}, - {name: "Switch", short_name: 'switch', prefix: '4903', length: 16}, - {name: "Visa", short_name: 'visa', prefix: '4', length: 16}, - {name: "Visa Electron", short_name: 'electron', prefix: '4026', length: 16} - ], - - //return all world currency by ISO 4217 - currency_types: [ - {'code' : 'AED', 'name' : 'United Arab Emirates Dirham'}, - {'code' : 'AFN', 'name' : 'Afghanistan Afghani'}, - {'code' : 'ALL', 'name' : 'Albania Lek'}, - {'code' : 'AMD', 'name' : 'Armenia Dram'}, - {'code' : 'ANG', 'name' : 'Netherlands Antilles Guilder'}, - {'code' : 'AOA', 'name' : 'Angola Kwanza'}, - {'code' : 'ARS', 'name' : 'Argentina Peso'}, - {'code' : 'AUD', 'name' : 'Australia Dollar'}, - {'code' : 'AWG', 'name' : 'Aruba Guilder'}, - {'code' : 'AZN', 'name' : 'Azerbaijan New Manat'}, - {'code' : 'BAM', 'name' : 'Bosnia and Herzegovina Convertible Marka'}, - {'code' : 'BBD', 'name' : 'Barbados Dollar'}, - {'code' : 'BDT', 'name' : 'Bangladesh Taka'}, - {'code' : 'BGN', 'name' : 'Bulgaria Lev'}, - {'code' : 'BHD', 'name' : 'Bahrain Dinar'}, - {'code' : 'BIF', 'name' : 'Burundi Franc'}, - {'code' : 'BMD', 'name' : 'Bermuda Dollar'}, - {'code' : 'BND', 'name' : 'Brunei Darussalam Dollar'}, - {'code' : 'BOB', 'name' : 'Bolivia Boliviano'}, - {'code' : 'BRL', 'name' : 'Brazil Real'}, - {'code' : 'BSD', 'name' : 'Bahamas Dollar'}, - {'code' : 'BTN', 'name' : 'Bhutan Ngultrum'}, - {'code' : 'BWP', 'name' : 'Botswana Pula'}, - {'code' : 'BYR', 'name' : 'Belarus Ruble'}, - {'code' : 'BZD', 'name' : 'Belize Dollar'}, - {'code' : 'CAD', 'name' : 'Canada Dollar'}, - {'code' : 'CDF', 'name' : 'Congo/Kinshasa Franc'}, - {'code' : 'CHF', 'name' : 'Switzerland Franc'}, - {'code' : 'CLP', 'name' : 'Chile Peso'}, - {'code' : 'CNY', 'name' : 'China Yuan Renminbi'}, - {'code' : 'COP', 'name' : 'Colombia Peso'}, - {'code' : 'CRC', 'name' : 'Costa Rica Colon'}, - {'code' : 'CUC', 'name' : 'Cuba Convertible Peso'}, - {'code' : 'CUP', 'name' : 'Cuba Peso'}, - {'code' : 'CVE', 'name' : 'Cape Verde Escudo'}, - {'code' : 'CZK', 'name' : 'Czech Republic Koruna'}, - {'code' : 'DJF', 'name' : 'Djibouti Franc'}, - {'code' : 'DKK', 'name' : 'Denmark Krone'}, - {'code' : 'DOP', 'name' : 'Dominican Republic Peso'}, - {'code' : 'DZD', 'name' : 'Algeria Dinar'}, - {'code' : 'EGP', 'name' : 'Egypt Pound'}, - {'code' : 'ERN', 'name' : 'Eritrea Nakfa'}, - {'code' : 'ETB', 'name' : 'Ethiopia Birr'}, - {'code' : 'EUR', 'name' : 'Euro Member Countries'}, - {'code' : 'FJD', 'name' : 'Fiji Dollar'}, - {'code' : 'FKP', 'name' : 'Falkland Islands (Malvinas) Pound'}, - {'code' : 'GBP', 'name' : 'United Kingdom Pound'}, - {'code' : 'GEL', 'name' : 'Georgia Lari'}, - {'code' : 'GGP', 'name' : 'Guernsey Pound'}, - {'code' : 'GHS', 'name' : 'Ghana Cedi'}, - {'code' : 'GIP', 'name' : 'Gibraltar Pound'}, - {'code' : 'GMD', 'name' : 'Gambia Dalasi'}, - {'code' : 'GNF', 'name' : 'Guinea Franc'}, - {'code' : 'GTQ', 'name' : 'Guatemala Quetzal'}, - {'code' : 'GYD', 'name' : 'Guyana Dollar'}, - {'code' : 'HKD', 'name' : 'Hong Kong Dollar'}, - {'code' : 'HNL', 'name' : 'Honduras Lempira'}, - {'code' : 'HRK', 'name' : 'Croatia Kuna'}, - {'code' : 'HTG', 'name' : 'Haiti Gourde'}, - {'code' : 'HUF', 'name' : 'Hungary Forint'}, - {'code' : 'IDR', 'name' : 'Indonesia Rupiah'}, - {'code' : 'ILS', 'name' : 'Israel Shekel'}, - {'code' : 'IMP', 'name' : 'Isle of Man Pound'}, - {'code' : 'INR', 'name' : 'India Rupee'}, - {'code' : 'IQD', 'name' : 'Iraq Dinar'}, - {'code' : 'IRR', 'name' : 'Iran Rial'}, - {'code' : 'ISK', 'name' : 'Iceland Krona'}, - {'code' : 'JEP', 'name' : 'Jersey Pound'}, - {'code' : 'JMD', 'name' : 'Jamaica Dollar'}, - {'code' : 'JOD', 'name' : 'Jordan Dinar'}, - {'code' : 'JPY', 'name' : 'Japan Yen'}, - {'code' : 'KES', 'name' : 'Kenya Shilling'}, - {'code' : 'KGS', 'name' : 'Kyrgyzstan Som'}, - {'code' : 'KHR', 'name' : 'Cambodia Riel'}, - {'code' : 'KMF', 'name' : 'Comoros Franc'}, - {'code' : 'KPW', 'name' : 'Korea (North) Won'}, - {'code' : 'KRW', 'name' : 'Korea (South) Won'}, - {'code' : 'KWD', 'name' : 'Kuwait Dinar'}, - {'code' : 'KYD', 'name' : 'Cayman Islands Dollar'}, - {'code' : 'KZT', 'name' : 'Kazakhstan Tenge'}, - {'code' : 'LAK', 'name' : 'Laos Kip'}, - {'code' : 'LBP', 'name' : 'Lebanon Pound'}, - {'code' : 'LKR', 'name' : 'Sri Lanka Rupee'}, - {'code' : 'LRD', 'name' : 'Liberia Dollar'}, - {'code' : 'LSL', 'name' : 'Lesotho Loti'}, - {'code' : 'LTL', 'name' : 'Lithuania Litas'}, - {'code' : 'LYD', 'name' : 'Libya Dinar'}, - {'code' : 'MAD', 'name' : 'Morocco Dirham'}, - {'code' : 'MDL', 'name' : 'Moldova Leu'}, - {'code' : 'MGA', 'name' : 'Madagascar Ariary'}, - {'code' : 'MKD', 'name' : 'Macedonia Denar'}, - {'code' : 'MMK', 'name' : 'Myanmar (Burma) Kyat'}, - {'code' : 'MNT', 'name' : 'Mongolia Tughrik'}, - {'code' : 'MOP', 'name' : 'Macau Pataca'}, - {'code' : 'MRO', 'name' : 'Mauritania Ouguiya'}, - {'code' : 'MUR', 'name' : 'Mauritius Rupee'}, - {'code' : 'MVR', 'name' : 'Maldives (Maldive Islands) Rufiyaa'}, - {'code' : 'MWK', 'name' : 'Malawi Kwacha'}, - {'code' : 'MXN', 'name' : 'Mexico Peso'}, - {'code' : 'MYR', 'name' : 'Malaysia Ringgit'}, - {'code' : 'MZN', 'name' : 'Mozambique Metical'}, - {'code' : 'NAD', 'name' : 'Namibia Dollar'}, - {'code' : 'NGN', 'name' : 'Nigeria Naira'}, - {'code' : 'NIO', 'name' : 'Nicaragua Cordoba'}, - {'code' : 'NOK', 'name' : 'Norway Krone'}, - {'code' : 'NPR', 'name' : 'Nepal Rupee'}, - {'code' : 'NZD', 'name' : 'New Zealand Dollar'}, - {'code' : 'OMR', 'name' : 'Oman Rial'}, - {'code' : 'PAB', 'name' : 'Panama Balboa'}, - {'code' : 'PEN', 'name' : 'Peru Nuevo Sol'}, - {'code' : 'PGK', 'name' : 'Papua New Guinea Kina'}, - {'code' : 'PHP', 'name' : 'Philippines Peso'}, - {'code' : 'PKR', 'name' : 'Pakistan Rupee'}, - {'code' : 'PLN', 'name' : 'Poland Zloty'}, - {'code' : 'PYG', 'name' : 'Paraguay Guarani'}, - {'code' : 'QAR', 'name' : 'Qatar Riyal'}, - {'code' : 'RON', 'name' : 'Romania New Leu'}, - {'code' : 'RSD', 'name' : 'Serbia Dinar'}, - {'code' : 'RUB', 'name' : 'Russia Ruble'}, - {'code' : 'RWF', 'name' : 'Rwanda Franc'}, - {'code' : 'SAR', 'name' : 'Saudi Arabia Riyal'}, - {'code' : 'SBD', 'name' : 'Solomon Islands Dollar'}, - {'code' : 'SCR', 'name' : 'Seychelles Rupee'}, - {'code' : 'SDG', 'name' : 'Sudan Pound'}, - {'code' : 'SEK', 'name' : 'Sweden Krona'}, - {'code' : 'SGD', 'name' : 'Singapore Dollar'}, - {'code' : 'SHP', 'name' : 'Saint Helena Pound'}, - {'code' : 'SLL', 'name' : 'Sierra Leone Leone'}, - {'code' : 'SOS', 'name' : 'Somalia Shilling'}, - {'code' : 'SPL', 'name' : 'Seborga Luigino'}, - {'code' : 'SRD', 'name' : 'Suriname Dollar'}, - {'code' : 'STD', 'name' : 'SĆ£o TomĆ© and PrĆ­ncipe Dobra'}, - {'code' : 'SVC', 'name' : 'El Salvador Colon'}, - {'code' : 'SYP', 'name' : 'Syria Pound'}, - {'code' : 'SZL', 'name' : 'Swaziland Lilangeni'}, - {'code' : 'THB', 'name' : 'Thailand Baht'}, - {'code' : 'TJS', 'name' : 'Tajikistan Somoni'}, - {'code' : 'TMT', 'name' : 'Turkmenistan Manat'}, - {'code' : 'TND', 'name' : 'Tunisia Dinar'}, - {'code' : 'TOP', 'name' : 'Tonga Pa\'anga'}, - {'code' : 'TRY', 'name' : 'Turkey Lira'}, - {'code' : 'TTD', 'name' : 'Trinidad and Tobago Dollar'}, - {'code' : 'TVD', 'name' : 'Tuvalu Dollar'}, - {'code' : 'TWD', 'name' : 'Taiwan New Dollar'}, - {'code' : 'TZS', 'name' : 'Tanzania Shilling'}, - {'code' : 'UAH', 'name' : 'Ukraine Hryvnia'}, - {'code' : 'UGX', 'name' : 'Uganda Shilling'}, - {'code' : 'USD', 'name' : 'United States Dollar'}, - {'code' : 'UYU', 'name' : 'Uruguay Peso'}, - {'code' : 'UZS', 'name' : 'Uzbekistan Som'}, - {'code' : 'VEF', 'name' : 'Venezuela Bolivar'}, - {'code' : 'VND', 'name' : 'Viet Nam Dong'}, - {'code' : 'VUV', 'name' : 'Vanuatu Vatu'}, - {'code' : 'WST', 'name' : 'Samoa Tala'}, - {'code' : 'XAF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BEAC) CFA Franc BEAC'}, - {'code' : 'XCD', 'name' : 'East Caribbean Dollar'}, - {'code' : 'XDR', 'name' : 'International Monetary Fund (IMF) Special Drawing Rights'}, - {'code' : 'XOF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BCEAO) Franc'}, - {'code' : 'XPF', 'name' : 'Comptoirs FranƧais du Pacifique (CFP) Franc'}, - {'code' : 'YER', 'name' : 'Yemen Rial'}, - {'code' : 'ZAR', 'name' : 'South Africa Rand'}, - {'code' : 'ZMW', 'name' : 'Zambia Kwacha'}, - {'code' : 'ZWD', 'name' : 'Zimbabwe Dollar'} - ], - - // return the names of all valide colors - colorNames : [ "AliceBlue", "Black", "Navy", "DarkBlue", "MediumBlue", "Blue", "DarkGreen", "Green", "Teal", "DarkCyan", "DeepSkyBlue", "DarkTurquoise", "MediumSpringGreen", "Lime", "SpringGreen", - "Aqua", "Cyan", "MidnightBlue", "DodgerBlue", "LightSeaGreen", "ForestGreen", "SeaGreen", "DarkSlateGray", "LimeGreen", "MediumSeaGreen", "Turquoise", "RoyalBlue", "SteelBlue", "DarkSlateBlue", "MediumTurquoise", - "Indigo", "DarkOliveGreen", "CadetBlue", "CornflowerBlue", "RebeccaPurple", "MediumAquaMarine", "DimGray", "SlateBlue", "OliveDrab", "SlateGray", "LightSlateGray", "MediumSlateBlue", "LawnGreen", "Chartreuse", - "Aquamarine", "Maroon", "Purple", "Olive", "Gray", "SkyBlue", "LightSkyBlue", "BlueViolet", "DarkRed", "DarkMagenta", "SaddleBrown", "Ivory", "White", - "DarkSeaGreen", "LightGreen", "MediumPurple", "DarkViolet", "PaleGreen", "DarkOrchid", "YellowGreen", "Sienna", "Brown", "DarkGray", "LightBlue", "GreenYellow", "PaleTurquoise", "LightSteelBlue", "PowderBlue", - "FireBrick", "DarkGoldenRod", "MediumOrchid", "RosyBrown", "DarkKhaki", "Silver", "MediumVioletRed", "IndianRed", "Peru", "Chocolate", "Tan", "LightGray", "Thistle", "Orchid", "GoldenRod", "PaleVioletRed", - "Crimson", "Gainsboro", "Plum", "BurlyWood", "LightCyan", "Lavender", "DarkSalmon", "Violet", "PaleGoldenRod", "LightCoral", "Khaki", "AliceBlue", "HoneyDew", "Azure", "SandyBrown", "Wheat", "Beige", "WhiteSmoke", - "MintCream", "GhostWhite", "Salmon", "AntiqueWhite", "Linen", "LightGoldenRodYellow", "OldLace", "Red", "Fuchsia", "Magenta", "DeepPink", "OrangeRed", "Tomato", "HotPink", "Coral", "DarkOrange", "LightSalmon", "Orange", - "LightPink", "Pink", "Gold", "PeachPuff", "NavajoWhite", "Moccasin", "Bisque", "MistyRose", "BlanchedAlmond", "PapayaWhip", "LavenderBlush", "SeaShell", "Cornsilk", "LemonChiffon", "FloralWhite", "Snow", "Yellow", "LightYellow" - ], - - // Data taken from https://www.sec.gov/rules/other/4-460list.htm - company: [ "3Com Corp", - "3M Company", - "A.G. Edwards Inc.", - "Abbott Laboratories", - "Abercrombie & Fitch Co.", - "ABM Industries Incorporated", - "Ace Hardware Corporation", - "ACT Manufacturing Inc.", - "Acterna Corp.", - "Adams Resources & Energy, Inc.", - "ADC Telecommunications, Inc.", - "Adelphia Communications Corporation", - "Administaff, Inc.", - "Adobe Systems Incorporated", - "Adolph Coors Company", - "Advance Auto Parts, Inc.", - "Advanced Micro Devices, Inc.", - "AdvancePCS, Inc.", - "Advantica Restaurant Group, Inc.", - "The AES Corporation", - "Aetna Inc.", - "Affiliated Computer Services, Inc.", - "AFLAC Incorporated", - "AGCO Corporation", - "Agilent Technologies, Inc.", - "Agway Inc.", - "Apartment Investment and Management Company", - "Air Products and Chemicals, Inc.", - "Airborne, Inc.", - "Airgas, Inc.", - "AK Steel Holding Corporation", - "Alaska Air Group, Inc.", - "Alberto-Culver Company", - "Albertson's, Inc.", - "Alcoa Inc.", - "Alleghany Corporation", - "Allegheny Energy, Inc.", - "Allegheny Technologies Incorporated", - "Allergan, Inc.", - "ALLETE, Inc.", - "Alliant Energy Corporation", - "Allied Waste Industries, Inc.", - "Allmerica Financial Corporation", - "The Allstate Corporation", - "ALLTEL Corporation", - "The Alpine Group, Inc.", - "Amazon.com, Inc.", - "AMC Entertainment Inc.", - "American Power Conversion Corporation", - "Amerada Hess Corporation", - "AMERCO", - "Ameren Corporation", - "America West Holdings Corporation", - "American Axle & Manufacturing Holdings, Inc.", - "American Eagle Outfitters, Inc.", - "American Electric Power Company, Inc.", - "American Express Company", - "American Financial Group, Inc.", - "American Greetings Corporation", - "American International Group, Inc.", - "American Standard Companies Inc.", - "American Water Works Company, Inc.", - "AmerisourceBergen Corporation", - "Ames Department Stores, Inc.", - "Amgen Inc.", - "Amkor Technology, Inc.", - "AMR Corporation", - "AmSouth Bancorp.", - "Amtran, Inc.", - "Anadarko Petroleum Corporation", - "Analog Devices, Inc.", - "Anheuser-Busch Companies, Inc.", - "Anixter International Inc.", - "AnnTaylor Inc.", - "Anthem, Inc.", - "AOL Time Warner Inc.", - "Aon Corporation", - "Apache Corporation", - "Apple Computer, Inc.", - "Applera Corporation", - "Applied Industrial Technologies, Inc.", - "Applied Materials, Inc.", - "Aquila, Inc.", - "ARAMARK Corporation", - "Arch Coal, Inc.", - "Archer Daniels Midland Company", - "Arkansas Best Corporation", - "Armstrong Holdings, Inc.", - "Arrow Electronics, Inc.", - "ArvinMeritor, Inc.", - "Ashland Inc.", - "Astoria Financial Corporation", - "AT&T Corp.", - "Atmel Corporation", - "Atmos Energy Corporation", - "Audiovox Corporation", - "Autoliv, Inc.", - "Automatic Data Processing, Inc.", - "AutoNation, Inc.", - "AutoZone, Inc.", - "Avaya Inc.", - "Avery Dennison Corporation", - "Avista Corporation", - "Avnet, Inc.", - "Avon Products, Inc.", - "Baker Hughes Incorporated", - "Ball Corporation", - "Bank of America Corporation", - "The Bank of New York Company, Inc.", - "Bank One Corporation", - "Banknorth Group, Inc.", - "Banta Corporation", - "Barnes & Noble, Inc.", - "Bausch & Lomb Incorporated", - "Baxter International Inc.", - "BB&T Corporation", - "The Bear Stearns Companies Inc.", - "Beazer Homes USA, Inc.", - "Beckman Coulter, Inc.", - "Becton, Dickinson and Company", - "Bed Bath & Beyond Inc.", - "Belk, Inc.", - "Bell Microproducts Inc.", - "BellSouth Corporation", - "Belo Corp.", - "Bemis Company, Inc.", - "Benchmark Electronics, Inc.", - "Berkshire Hathaway Inc.", - "Best Buy Co., Inc.", - "Bethlehem Steel Corporation", - "Beverly Enterprises, Inc.", - "Big Lots, Inc.", - "BJ Services Company", - "BJ's Wholesale Club, Inc.", - "The Black & Decker Corporation", - "Black Hills Corporation", - "BMC Software, Inc.", - "The Boeing Company", - "Boise Cascade Corporation", - "Borders Group, Inc.", - "BorgWarner Inc.", - "Boston Scientific Corporation", - "Bowater Incorporated", - "Briggs & Stratton Corporation", - "Brightpoint, Inc.", - "Brinker International, Inc.", - "Bristol-Myers Squibb Company", - "Broadwing, Inc.", - "Brown Shoe Company, Inc.", - "Brown-Forman Corporation", - "Brunswick Corporation", - "Budget Group, Inc.", - "Burlington Coat Factory Warehouse Corporation", - "Burlington Industries, Inc.", - "Burlington Northern Santa Fe Corporation", - "Burlington Resources Inc.", - "C. H. Robinson Worldwide Inc.", - "Cablevision Systems Corp", - "Cabot Corp", - "Cadence Design Systems, Inc.", - "Calpine Corp.", - "Campbell Soup Co.", - "Capital One Financial Corp.", - "Cardinal Health Inc.", - "Caremark Rx Inc.", - "Carlisle Cos. Inc.", - "Carpenter Technology Corp.", - "Casey's General Stores Inc.", - "Caterpillar Inc.", - "CBRL Group Inc.", - "CDI Corp.", - "CDW Computer Centers Inc.", - "CellStar Corp.", - "Cendant Corp", - "Cenex Harvest States Cooperatives", - "Centex Corp.", - "CenturyTel Inc.", - "Ceridian Corp.", - "CH2M Hill Cos. Ltd.", - "Champion Enterprises Inc.", - "Charles Schwab Corp.", - "Charming Shoppes Inc.", - "Charter Communications Inc.", - "Charter One Financial Inc.", - "ChevronTexaco Corp.", - "Chiquita Brands International Inc.", - "Chubb Corp", - "Ciena Corp.", - "Cigna Corp", - "Cincinnati Financial Corp.", - "Cinergy Corp.", - "Cintas Corp.", - "Circuit City Stores Inc.", - "Cisco Systems Inc.", - "Citigroup, Inc", - "Citizens Communications Co.", - "CKE Restaurants Inc.", - "Clear Channel Communications Inc.", - "The Clorox Co.", - "CMGI Inc.", - "CMS Energy Corp.", - "CNF Inc.", - "Coca-Cola Co.", - "Coca-Cola Enterprises Inc.", - "Colgate-Palmolive Co.", - "Collins & Aikman Corp.", - "Comcast Corp.", - "Comdisco Inc.", - "Comerica Inc.", - "Comfort Systems USA Inc.", - "Commercial Metals Co.", - "Community Health Systems Inc.", - "Compass Bancshares Inc", - "Computer Associates International Inc.", - "Computer Sciences Corp.", - "Compuware Corp.", - "Comverse Technology Inc.", - "ConAgra Foods Inc.", - "Concord EFS Inc.", - "Conectiv, Inc", - "Conoco Inc", - "Conseco Inc.", - "Consolidated Freightways Corp.", - "Consolidated Edison Inc.", - "Constellation Brands Inc.", - "Constellation Emergy Group Inc.", - "Continental Airlines Inc.", - "Convergys Corp.", - "Cooper Cameron Corp.", - "Cooper Industries Ltd.", - "Cooper Tire & Rubber Co.", - "Corn Products International Inc.", - "Corning Inc.", - "Costco Wholesale Corp.", - "Countrywide Credit Industries Inc.", - "Coventry Health Care Inc.", - "Cox Communications Inc.", - "Crane Co.", - "Crompton Corp.", - "Crown Cork & Seal Co. Inc.", - "CSK Auto Corp.", - "CSX Corp.", - "Cummins Inc.", - "CVS Corp.", - "Cytec Industries Inc.", - "D&K Healthcare Resources, Inc.", - "D.R. Horton Inc.", - "Dana Corporation", - "Danaher Corporation", - "Darden Restaurants Inc.", - "DaVita Inc.", - "Dean Foods Company", - "Deere & Company", - "Del Monte Foods Co", - "Dell Computer Corporation", - "Delphi Corp.", - "Delta Air Lines Inc.", - "Deluxe Corporation", - "Devon Energy Corporation", - "Di Giorgio Corporation", - "Dial Corporation", - "Diebold Incorporated", - "Dillard's Inc.", - "DIMON Incorporated", - "Dole Food Company, Inc.", - "Dollar General Corporation", - "Dollar Tree Stores, Inc.", - "Dominion Resources, Inc.", - "Domino's Pizza LLC", - "Dover Corporation, Inc.", - "Dow Chemical Company", - "Dow Jones & Company, Inc.", - "DPL Inc.", - "DQE Inc.", - "Dreyer's Grand Ice Cream, Inc.", - "DST Systems, Inc.", - "DTE Energy Co.", - "E.I. Du Pont de Nemours and Company", - "Duke Energy Corp", - "Dun & Bradstreet Inc.", - "DURA Automotive Systems Inc.", - "DynCorp", - "Dynegy Inc.", - "E*Trade Group, Inc.", - "E.W. Scripps Company", - "Earthlink, Inc.", - "Eastman Chemical Company", - "Eastman Kodak Company", - "Eaton Corporation", - "Echostar Communications Corporation", - "Ecolab Inc.", - "Edison International", - "EGL Inc.", - "El Paso Corporation", - "Electronic Arts Inc.", - "Electronic Data Systems Corp.", - "Eli Lilly and Company", - "EMC Corporation", - "Emcor Group Inc.", - "Emerson Electric Co.", - "Encompass Services Corporation", - "Energizer Holdings Inc.", - "Energy East Corporation", - "Engelhard Corporation", - "Enron Corp.", - "Entergy Corporation", - "Enterprise Products Partners L.P.", - "EOG Resources, Inc.", - "Equifax Inc.", - "Equitable Resources Inc.", - "Equity Office Properties Trust", - "Equity Residential Properties Trust", - "Estee Lauder Companies Inc.", - "Exelon Corporation", - "Exide Technologies", - "Expeditors International of Washington Inc.", - "Express Scripts Inc.", - "ExxonMobil Corporation", - "Fairchild Semiconductor International Inc.", - "Family Dollar Stores Inc.", - "Farmland Industries Inc.", - "Federal Mogul Corp.", - "Federated Department Stores Inc.", - "Federal Express Corp.", - "Felcor Lodging Trust Inc.", - "Ferro Corp.", - "Fidelity National Financial Inc.", - "Fifth Third Bancorp", - "First American Financial Corp.", - "First Data Corp.", - "First National of Nebraska Inc.", - "First Tennessee National Corp.", - "FirstEnergy Corp.", - "Fiserv Inc.", - "Fisher Scientific International Inc.", - "FleetBoston Financial Co.", - "Fleetwood Enterprises Inc.", - "Fleming Companies Inc.", - "Flowers Foods Inc.", - "Flowserv Corp", - "Fluor Corp", - "FMC Corp", - "Foamex International Inc", - "Foot Locker Inc", - "Footstar Inc.", - "Ford Motor Co", - "Forest Laboratories Inc.", - "Fortune Brands Inc.", - "Foster Wheeler Ltd.", - "FPL Group Inc.", - "Franklin Resources Inc.", - "Freeport McMoran Copper & Gold Inc.", - "Frontier Oil Corp", - "Furniture Brands International Inc.", - "Gannett Co., Inc.", - "Gap Inc.", - "Gateway Inc.", - "GATX Corporation", - "Gemstar-TV Guide International Inc.", - "GenCorp Inc.", - "General Cable Corporation", - "General Dynamics Corporation", - "General Electric Company", - "General Mills Inc", - "General Motors Corporation", - "Genesis Health Ventures Inc.", - "Gentek Inc.", - "Gentiva Health Services Inc.", - "Genuine Parts Company", - "Genuity Inc.", - "Genzyme Corporation", - "Georgia Gulf Corporation", - "Georgia-Pacific Corporation", - "Gillette Company", - "Gold Kist Inc.", - "Golden State Bancorp Inc.", - "Golden West Financial Corporation", - "Goldman Sachs Group Inc.", - "Goodrich Corporation", - "The Goodyear Tire & Rubber Company", - "Granite Construction Incorporated", - "Graybar Electric Company Inc.", - "Great Lakes Chemical Corporation", - "Great Plains Energy Inc.", - "GreenPoint Financial Corp.", - "Greif Bros. Corporation", - "Grey Global Group Inc.", - "Group 1 Automotive Inc.", - "Guidant Corporation", - "H&R Block Inc.", - "H.B. Fuller Company", - "H.J. Heinz Company", - "Halliburton Co.", - "Harley-Davidson Inc.", - "Harman International Industries Inc.", - "Harrah's Entertainment Inc.", - "Harris Corp.", - "Harsco Corp.", - "Hartford Financial Services Group Inc.", - "Hasbro Inc.", - "Hawaiian Electric Industries Inc.", - "HCA Inc.", - "Health Management Associates Inc.", - "Health Net Inc.", - "Healthsouth Corp", - "Henry Schein Inc.", - "Hercules Inc.", - "Herman Miller Inc.", - "Hershey Foods Corp.", - "Hewlett-Packard Company", - "Hibernia Corp.", - "Hillenbrand Industries Inc.", - "Hilton Hotels Corp.", - "Hollywood Entertainment Corp.", - "Home Depot Inc.", - "Hon Industries Inc.", - "Honeywell International Inc.", - "Hormel Foods Corp.", - "Host Marriott Corp.", - "Household International Corp.", - "Hovnanian Enterprises Inc.", - "Hub Group Inc.", - "Hubbell Inc.", - "Hughes Supply Inc.", - "Humana Inc.", - "Huntington Bancshares Inc.", - "Idacorp Inc.", - "IDT Corporation", - "IKON Office Solutions Inc.", - "Illinois Tool Works Inc.", - "IMC Global Inc.", - "Imperial Sugar Company", - "IMS Health Inc.", - "Ingles Market Inc", - "Ingram Micro Inc.", - "Insight Enterprises Inc.", - "Integrated Electrical Services Inc.", - "Intel Corporation", - "International Paper Co.", - "Interpublic Group of Companies Inc.", - "Interstate Bakeries Corporation", - "International Business Machines Corp.", - "International Flavors & Fragrances Inc.", - "International Multifoods Corporation", - "Intuit Inc.", - "IT Group Inc.", - "ITT Industries Inc.", - "Ivax Corp.", - "J.B. Hunt Transport Services Inc.", - "J.C. Penny Co.", - "J.P. Morgan Chase & Co.", - "Jabil Circuit Inc.", - "Jack In The Box Inc.", - "Jacobs Engineering Group Inc.", - "JDS Uniphase Corp.", - "Jefferson-Pilot Co.", - "John Hancock Financial Services Inc.", - "Johnson & Johnson", - "Johnson Controls Inc.", - "Jones Apparel Group Inc.", - "KB Home", - "Kellogg Company", - "Kellwood Company", - "Kelly Services Inc.", - "Kemet Corp.", - "Kennametal Inc.", - "Kerr-McGee Corporation", - "KeyCorp", - "KeySpan Corp.", - "Kimball International Inc.", - "Kimberly-Clark Corporation", - "Kindred Healthcare Inc.", - "KLA-Tencor Corporation", - "K-Mart Corp.", - "Knight-Ridder Inc.", - "Kohl's Corp.", - "KPMG Consulting Inc.", - "Kroger Co.", - "L-3 Communications Holdings Inc.", - "Laboratory Corporation of America Holdings", - "Lam Research Corporation", - "LandAmerica Financial Group Inc.", - "Lands' End Inc.", - "Landstar System Inc.", - "La-Z-Boy Inc.", - "Lear Corporation", - "Legg Mason Inc.", - "Leggett & Platt Inc.", - "Lehman Brothers Holdings Inc.", - "Lennar Corporation", - "Lennox International Inc.", - "Level 3 Communications Inc.", - "Levi Strauss & Co.", - "Lexmark International Inc.", - "Limited Inc.", - "Lincoln National Corporation", - "Linens 'n Things Inc.", - "Lithia Motors Inc.", - "Liz Claiborne Inc.", - "Lockheed Martin Corporation", - "Loews Corporation", - "Longs Drug Stores Corporation", - "Louisiana-Pacific Corporation", - "Lowe's Companies Inc.", - "LSI Logic Corporation", - "The LTV Corporation", - "The Lubrizol Corporation", - "Lucent Technologies Inc.", - "Lyondell Chemical Company", - "M & T Bank Corporation", - "Magellan Health Services Inc.", - "Mail-Well Inc.", - "Mandalay Resort Group", - "Manor Care Inc.", - "Manpower Inc.", - "Marathon Oil Corporation", - "Mariner Health Care Inc.", - "Markel Corporation", - "Marriott International Inc.", - "Marsh & McLennan Companies Inc.", - "Marsh Supermarkets Inc.", - "Marshall & Ilsley Corporation", - "Martin Marietta Materials Inc.", - "Masco Corporation", - "Massey Energy Company", - "MasTec Inc.", - "Mattel Inc.", - "Maxim Integrated Products Inc.", - "Maxtor Corporation", - "Maxxam Inc.", - "The May Department Stores Company", - "Maytag Corporation", - "MBNA Corporation", - "McCormick & Company Incorporated", - "McDonald's Corporation", - "The McGraw-Hill Companies Inc.", - "McKesson Corporation", - "McLeodUSA Incorporated", - "M.D.C. Holdings Inc.", - "MDU Resources Group Inc.", - "MeadWestvaco Corporation", - "Medtronic Inc.", - "Mellon Financial Corporation", - "The Men's Wearhouse Inc.", - "Merck & Co., Inc.", - "Mercury General Corporation", - "Merrill Lynch & Co. Inc.", - "Metaldyne Corporation", - "Metals USA Inc.", - "MetLife Inc.", - "Metris Companies Inc", - "MGIC Investment Corporation", - "MGM Mirage", - "Michaels Stores Inc.", - "Micron Technology Inc.", - "Microsoft Corporation", - "Milacron Inc.", - "Millennium Chemicals Inc.", - "Mirant Corporation", - "Mohawk Industries Inc.", - "Molex Incorporated", - "The MONY Group Inc.", - "Morgan Stanley Dean Witter & Co.", - "Motorola Inc.", - "MPS Group Inc.", - "Murphy Oil Corporation", - "Nabors Industries Inc", - "Nacco Industries Inc", - "Nash Finch Company", - "National City Corp.", - "National Commerce Financial Corporation", - "National Fuel Gas Company", - "National Oilwell Inc", - "National Rural Utilities Cooperative Finance Corporation", - "National Semiconductor Corporation", - "National Service Industries Inc", - "Navistar International Corporation", - "NCR Corporation", - "The Neiman Marcus Group Inc.", - "New Jersey Resources Corporation", - "New York Times Company", - "Newell Rubbermaid Inc", - "Newmont Mining Corporation", - "Nextel Communications Inc", - "Nicor Inc", - "Nike Inc", - "NiSource Inc", - "Noble Energy Inc", - "Nordstrom Inc", - "Norfolk Southern Corporation", - "Nortek Inc", - "North Fork Bancorporation Inc", - "Northeast Utilities System", - "Northern Trust Corporation", - "Northrop Grumman Corporation", - "NorthWestern Corporation", - "Novellus Systems Inc", - "NSTAR", - "NTL Incorporated", - "Nucor Corp", - "Nvidia Corp", - "NVR Inc", - "Northwest Airlines Corp", - "Occidental Petroleum Corp", - "Ocean Energy Inc", - "Office Depot Inc.", - "OfficeMax Inc", - "OGE Energy Corp", - "Oglethorpe Power Corp.", - "Ohio Casualty Corp.", - "Old Republic International Corp.", - "Olin Corp.", - "OM Group Inc", - "Omnicare Inc", - "Omnicom Group", - "On Semiconductor Corp", - "ONEOK Inc", - "Oracle Corp", - "Oshkosh Truck Corp", - "Outback Steakhouse Inc.", - "Owens & Minor Inc.", - "Owens Corning", - "Owens-Illinois Inc", - "Oxford Health Plans Inc", - "Paccar Inc", - "PacifiCare Health Systems Inc", - "Packaging Corp. of America", - "Pactiv Corp", - "Pall Corp", - "Pantry Inc", - "Park Place Entertainment Corp", - "Parker Hannifin Corp.", - "Pathmark Stores Inc.", - "Paychex Inc", - "Payless Shoesource Inc", - "Penn Traffic Co.", - "Pennzoil-Quaker State Company", - "Pentair Inc", - "Peoples Energy Corp.", - "PeopleSoft Inc", - "Pep Boys Manny, Moe & Jack", - "Potomac Electric Power Co.", - "Pepsi Bottling Group Inc.", - "PepsiAmericas Inc.", - "PepsiCo Inc.", - "Performance Food Group Co.", - "Perini Corp", - "PerkinElmer Inc", - "Perot Systems Corp", - "Petco Animal Supplies Inc.", - "Peter Kiewit Sons', Inc.", - "PETsMART Inc", - "Pfizer Inc", - "Pacific Gas & Electric Corp.", - "Pharmacia Corp", - "Phar Mor Inc.", - "Phelps Dodge Corp.", - "Philip Morris Companies Inc.", - "Phillips Petroleum Co", - "Phillips Van Heusen Corp.", - "Phoenix Companies Inc", - "Pier 1 Imports Inc.", - "Pilgrim's Pride Corporation", - "Pinnacle West Capital Corp", - "Pioneer-Standard Electronics Inc.", - "Pitney Bowes Inc.", - "Pittston Brinks Group", - "Plains All American Pipeline LP", - "PNC Financial Services Group Inc.", - "PNM Resources Inc", - "Polaris Industries Inc.", - "Polo Ralph Lauren Corp", - "PolyOne Corp", - "Popular Inc", - "Potlatch Corp", - "PPG Industries Inc", - "PPL Corp", - "Praxair Inc", - "Precision Castparts Corp", - "Premcor Inc.", - "Pride International Inc", - "Primedia Inc", - "Principal Financial Group Inc.", - "Procter & Gamble Co.", - "Pro-Fac Cooperative Inc.", - "Progress Energy Inc", - "Progressive Corporation", - "Protective Life Corp", - "Provident Financial Group", - "Providian Financial Corp.", - "Prudential Financial Inc.", - "PSS World Medical Inc", - "Public Service Enterprise Group Inc.", - "Publix Super Markets Inc.", - "Puget Energy Inc.", - "Pulte Homes Inc", - "Qualcomm Inc", - "Quanta Services Inc.", - "Quantum Corp", - "Quest Diagnostics Inc.", - "Questar Corp", - "Quintiles Transnational", - "Qwest Communications Intl Inc", - "R.J. Reynolds Tobacco Company", - "R.R. Donnelley & Sons Company", - "Radio Shack Corporation", - "Raymond James Financial Inc.", - "Raytheon Company", - "Reader's Digest Association Inc.", - "Reebok International Ltd.", - "Regions Financial Corp.", - "Regis Corporation", - "Reliance Steel & Aluminum Co.", - "Reliant Energy Inc.", - "Rent A Center Inc", - "Republic Services Inc", - "Revlon Inc", - "RGS Energy Group Inc", - "Rite Aid Corp", - "Riverwood Holding Inc.", - "RoadwayCorp", - "Robert Half International Inc.", - "Rock-Tenn Co", - "Rockwell Automation Inc", - "Rockwell Collins Inc", - "Rohm & Haas Co.", - "Ross Stores Inc", - "RPM Inc.", - "Ruddick Corp", - "Ryder System Inc", - "Ryerson Tull Inc", - "Ryland Group Inc.", - "Sabre Holdings Corp", - "Safeco Corp", - "Safeguard Scientifics Inc.", - "Safeway Inc", - "Saks Inc", - "Sanmina-SCI Inc", - "Sara Lee Corp", - "SBC Communications Inc", - "Scana Corp.", - "Schering-Plough Corp", - "Scholastic Corp", - "SCI Systems Onc.", - "Science Applications Intl. Inc.", - "Scientific-Atlanta Inc", - "Scotts Company", - "Seaboard Corp", - "Sealed Air Corp", - "Sears Roebuck & Co", - "Sempra Energy", - "Sequa Corp", - "Service Corp. International", - "ServiceMaster Co", - "Shaw Group Inc", - "Sherwin-Williams Company", - "Shopko Stores Inc", - "Siebel Systems Inc", - "Sierra Health Services Inc", - "Sierra Pacific Resources", - "Silgan Holdings Inc.", - "Silicon Graphics Inc", - "Simon Property Group Inc", - "SLM Corporation", - "Smith International Inc", - "Smithfield Foods Inc", - "Smurfit-Stone Container Corp", - "Snap-On Inc", - "Solectron Corp", - "Solutia Inc", - "Sonic Automotive Inc.", - "Sonoco Products Co.", - "Southern Company", - "Southern Union Company", - "SouthTrust Corp.", - "Southwest Airlines Co", - "Southwest Gas Corp", - "Sovereign Bancorp Inc.", - "Spartan Stores Inc", - "Spherion Corp", - "Sports Authority Inc", - "Sprint Corp.", - "SPX Corp", - "St. Jude Medical Inc", - "St. Paul Cos.", - "Staff Leasing Inc.", - "StanCorp Financial Group Inc", - "Standard Pacific Corp.", - "Stanley Works", - "Staples Inc", - "Starbucks Corp", - "Starwood Hotels & Resorts Worldwide Inc", - "State Street Corp.", - "Stater Bros. Holdings Inc.", - "Steelcase Inc", - "Stein Mart Inc", - "Stewart & Stevenson Services Inc", - "Stewart Information Services Corp", - "Stilwell Financial Inc", - "Storage Technology Corporation", - "Stryker Corp", - "Sun Healthcare Group Inc.", - "Sun Microsystems Inc.", - "SunGard Data Systems Inc.", - "Sunoco Inc.", - "SunTrust Banks Inc", - "Supervalu Inc", - "Swift Transportation, Co., Inc", - "Symbol Technologies Inc", - "Synovus Financial Corp.", - "Sysco Corp", - "Systemax Inc.", - "Target Corp.", - "Tech Data Corporation", - "TECO Energy Inc", - "Tecumseh Products Company", - "Tektronix Inc", - "Teleflex Incorporated", - "Telephone & Data Systems Inc", - "Tellabs Inc.", - "Temple-Inland Inc", - "Tenet Healthcare Corporation", - "Tenneco Automotive Inc.", - "Teradyne Inc", - "Terex Corp", - "Tesoro Petroleum Corp.", - "Texas Industries Inc.", - "Texas Instruments Incorporated", - "Textron Inc", - "Thermo Electron Corporation", - "Thomas & Betts Corporation", - "Tiffany & Co", - "Timken Company", - "TJX Companies Inc", - "TMP Worldwide Inc", - "Toll Brothers Inc", - "Torchmark Corporation", - "Toro Company", - "Tower Automotive Inc.", - "Toys 'R' Us Inc", - "Trans World Entertainment Corp.", - "TransMontaigne Inc", - "Transocean Inc", - "TravelCenters of America Inc.", - "Triad Hospitals Inc", - "Tribune Company", - "Trigon Healthcare Inc.", - "Trinity Industries Inc", - "Trump Hotels & Casino Resorts Inc.", - "TruServ Corporation", - "TRW Inc", - "TXU Corp", - "Tyson Foods Inc", - "U.S. Bancorp", - "U.S. Industries Inc.", - "UAL Corporation", - "UGI Corporation", - "Unified Western Grocers Inc", - "Union Pacific Corporation", - "Union Planters Corp", - "Unisource Energy Corp", - "Unisys Corporation", - "United Auto Group Inc", - "United Defense Industries Inc.", - "United Parcel Service Inc", - "United Rentals Inc", - "United Stationers Inc", - "United Technologies Corporation", - "UnitedHealth Group Incorporated", - "Unitrin Inc", - "Universal Corporation", - "Universal Forest Products Inc", - "Universal Health Services Inc", - "Unocal Corporation", - "Unova Inc", - "UnumProvident Corporation", - "URS Corporation", - "US Airways Group Inc", - "US Oncology Inc", - "USA Interactive", - "USFreighways Corporation", - "USG Corporation", - "UST Inc", - "Valero Energy Corporation", - "Valspar Corporation", - "Value City Department Stores Inc", - "Varco International Inc", - "Vectren Corporation", - "Veritas Software Corporation", - "Verizon Communications Inc", - "VF Corporation", - "Viacom Inc", - "Viad Corp", - "Viasystems Group Inc", - "Vishay Intertechnology Inc", - "Visteon Corporation", - "Volt Information Sciences Inc", - "Vulcan Materials Company", - "W.R. Berkley Corporation", - "W.R. Grace & Co", - "W.W. Grainger Inc", - "Wachovia Corporation", - "Wakenhut Corporation", - "Walgreen Co", - "Wallace Computer Services Inc", - "Wal-Mart Stores Inc", - "Walt Disney Co", - "Walter Industries Inc", - "Washington Mutual Inc", - "Washington Post Co.", - "Waste Management Inc", - "Watsco Inc", - "Weatherford International Inc", - "Weis Markets Inc.", - "Wellpoint Health Networks Inc", - "Wells Fargo & Company", - "Wendy's International Inc", - "Werner Enterprises Inc", - "WESCO International Inc", - "Western Digital Inc", - "Western Gas Resources Inc", - "WestPoint Stevens Inc", - "Weyerhauser Company", - "WGL Holdings Inc", - "Whirlpool Corporation", - "Whole Foods Market Inc", - "Willamette Industries Inc.", - "Williams Companies Inc", - "Williams Sonoma Inc", - "Winn Dixie Stores Inc", - "Wisconsin Energy Corporation", - "Wm Wrigley Jr Company", - "World Fuel Services Corporation", - "WorldCom Inc", - "Worthington Industries Inc", - "WPS Resources Corporation", - "Wyeth", - "Wyndham International Inc", - "Xcel Energy Inc", - "Xerox Corp", - "Xilinx Inc", - "XO Communications Inc", - "Yellow Corporation", - "York International Corp", - "Yum Brands Inc.", - "Zale Corporation", - "Zions Bancorporation" - ], - - fileExtension : { - "raster" : ["bmp", "gif", "gpl", "ico", "jpeg", "psd", "png", "psp", "raw", "tiff"], - "vector" : ["3dv", "amf", "awg", "ai", "cgm", "cdr", "cmx", "dxf", "e2d", "egt", "eps", "fs", "odg", "svg", "xar"], - "3d" : ["3dmf", "3dm", "3mf", "3ds", "an8", "aoi", "blend", "cal3d", "cob", "ctm", "iob", "jas", "max", "mb", "mdx", "obj", "x", "x3d"], - "document" : ["doc", "docx", "dot", "html", "xml", "odt", "odm", "ott", "csv", "rtf", "tex", "xhtml", "xps"] - }, - - // Data taken from https://github.com/dmfilipenko/timezones.json/blob/master/timezones.json - timezones: [ - { - "name": "Dateline Standard Time", - "abbr": "DST", - "offset": -12, - "isdst": false, - "text": "(UTC-12:00) International Date Line West", - "utc": [ - "Etc/GMT+12" - ] - }, - { - "name": "UTC-11", - "abbr": "U", - "offset": -11, - "isdst": false, - "text": "(UTC-11:00) Coordinated Universal Time-11", - "utc": [ - "Etc/GMT+11", - "Pacific/Midway", - "Pacific/Niue", - "Pacific/Pago_Pago" - ] - }, - { - "name": "Hawaiian Standard Time", - "abbr": "HST", - "offset": -10, - "isdst": false, - "text": "(UTC-10:00) Hawaii", - "utc": [ - "Etc/GMT+10", - "Pacific/Honolulu", - "Pacific/Johnston", - "Pacific/Rarotonga", - "Pacific/Tahiti" - ] - }, - { - "name": "Alaskan Standard Time", - "abbr": "AKDT", - "offset": -8, - "isdst": true, - "text": "(UTC-09:00) Alaska", - "utc": [ - "America/Anchorage", - "America/Juneau", - "America/Nome", - "America/Sitka", - "America/Yakutat" - ] - }, - { - "name": "Pacific Standard Time (Mexico)", - "abbr": "PDT", - "offset": -7, - "isdst": true, - "text": "(UTC-08:00) Baja California", - "utc": [ - "America/Santa_Isabel" - ] - }, - { - "name": "Pacific Daylight Time", - "abbr": "PDT", - "offset": -7, - "isdst": true, - "text": "(UTC-07:00) Pacific Time (US & Canada)", - "utc": [ - "America/Dawson", - "America/Los_Angeles", - "America/Tijuana", - "America/Vancouver", - "America/Whitehorse" - ] - }, - { - "name": "Pacific Standard Time", - "abbr": "PST", - "offset": -8, - "isdst": false, - "text": "(UTC-08:00) Pacific Time (US & Canada)", - "utc": [ - "America/Dawson", - "America/Los_Angeles", - "America/Tijuana", - "America/Vancouver", - "America/Whitehorse", - "PST8PDT" - ] - }, - { - "name": "US Mountain Standard Time", - "abbr": "UMST", - "offset": -7, - "isdst": false, - "text": "(UTC-07:00) Arizona", - "utc": [ - "America/Creston", - "America/Dawson_Creek", - "America/Hermosillo", - "America/Phoenix", - "Etc/GMT+7" - ] - }, - { - "name": "Mountain Standard Time (Mexico)", - "abbr": "MDT", - "offset": -6, - "isdst": true, - "text": "(UTC-07:00) Chihuahua, La Paz, Mazatlan", - "utc": [ - "America/Chihuahua", - "America/Mazatlan" - ] - }, - { - "name": "Mountain Standard Time", - "abbr": "MDT", - "offset": -6, - "isdst": true, - "text": "(UTC-07:00) Mountain Time (US & Canada)", - "utc": [ - "America/Boise", - "America/Cambridge_Bay", - "America/Denver", - "America/Edmonton", - "America/Inuvik", - "America/Ojinaga", - "America/Yellowknife", - "MST7MDT" - ] - }, - { - "name": "Central America Standard Time", - "abbr": "CAST", - "offset": -6, - "isdst": false, - "text": "(UTC-06:00) Central America", - "utc": [ - "America/Belize", - "America/Costa_Rica", - "America/El_Salvador", - "America/Guatemala", - "America/Managua", - "America/Tegucigalpa", - "Etc/GMT+6", - "Pacific/Galapagos" - ] - }, - { - "name": "Central Standard Time", - "abbr": "CDT", - "offset": -5, - "isdst": true, - "text": "(UTC-06:00) Central Time (US & Canada)", - "utc": [ - "America/Chicago", - "America/Indiana/Knox", - "America/Indiana/Tell_City", - "America/Matamoros", - "America/Menominee", - "America/North_Dakota/Beulah", - "America/North_Dakota/Center", - "America/North_Dakota/New_Salem", - "America/Rainy_River", - "America/Rankin_Inlet", - "America/Resolute", - "America/Winnipeg", - "CST6CDT" - ] - }, - { - "name": "Central Standard Time (Mexico)", - "abbr": "CDT", - "offset": -5, - "isdst": true, - "text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey", - "utc": [ - "America/Bahia_Banderas", - "America/Cancun", - "America/Merida", - "America/Mexico_City", - "America/Monterrey" - ] - }, - { - "name": "Canada Central Standard Time", - "abbr": "CCST", - "offset": -6, - "isdst": false, - "text": "(UTC-06:00) Saskatchewan", - "utc": [ - "America/Regina", - "America/Swift_Current" - ] - }, - { - "name": "SA Pacific Standard Time", - "abbr": "SPST", - "offset": -5, - "isdst": false, - "text": "(UTC-05:00) Bogota, Lima, Quito", - "utc": [ - "America/Bogota", - "America/Cayman", - "America/Coral_Harbour", - "America/Eirunepe", - "America/Guayaquil", - "America/Jamaica", - "America/Lima", - "America/Panama", - "America/Rio_Branco", - "Etc/GMT+5" - ] - }, - { - "name": "Eastern Standard Time", - "abbr": "EDT", - "offset": -4, - "isdst": true, - "text": "(UTC-05:00) Eastern Time (US & Canada)", - "utc": [ - "America/Detroit", - "America/Havana", - "America/Indiana/Petersburg", - "America/Indiana/Vincennes", - "America/Indiana/Winamac", - "America/Iqaluit", - "America/Kentucky/Monticello", - "America/Louisville", - "America/Montreal", - "America/Nassau", - "America/New_York", - "America/Nipigon", - "America/Pangnirtung", - "America/Port-au-Prince", - "America/Thunder_Bay", - "America/Toronto", - "EST5EDT" - ] - }, - { - "name": "US Eastern Standard Time", - "abbr": "UEDT", - "offset": -4, - "isdst": true, - "text": "(UTC-05:00) Indiana (East)", - "utc": [ - "America/Indiana/Marengo", - "America/Indiana/Vevay", - "America/Indianapolis" - ] - }, - { - "name": "Venezuela Standard Time", - "abbr": "VST", - "offset": -4.5, - "isdst": false, - "text": "(UTC-04:30) Caracas", - "utc": [ - "America/Caracas" - ] - }, - { - "name": "Paraguay Standard Time", - "abbr": "PYT", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Asuncion", - "utc": [ - "America/Asuncion" - ] - }, - { - "name": "Atlantic Standard Time", - "abbr": "ADT", - "offset": -3, - "isdst": true, - "text": "(UTC-04:00) Atlantic Time (Canada)", - "utc": [ - "America/Glace_Bay", - "America/Goose_Bay", - "America/Halifax", - "America/Moncton", - "America/Thule", - "Atlantic/Bermuda" - ] - }, - { - "name": "Central Brazilian Standard Time", - "abbr": "CBST", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Cuiaba", - "utc": [ - "America/Campo_Grande", - "America/Cuiaba" - ] - }, - { - "name": "SA Western Standard Time", - "abbr": "SWST", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Georgetown, La Paz, Manaus, San Juan", - "utc": [ - "America/Anguilla", - "America/Antigua", - "America/Aruba", - "America/Barbados", - "America/Blanc-Sablon", - "America/Boa_Vista", - "America/Curacao", - "America/Dominica", - "America/Grand_Turk", - "America/Grenada", - "America/Guadeloupe", - "America/Guyana", - "America/Kralendijk", - "America/La_Paz", - "America/Lower_Princes", - "America/Manaus", - "America/Marigot", - "America/Martinique", - "America/Montserrat", - "America/Port_of_Spain", - "America/Porto_Velho", - "America/Puerto_Rico", - "America/Santo_Domingo", - "America/St_Barthelemy", - "America/St_Kitts", - "America/St_Lucia", - "America/St_Thomas", - "America/St_Vincent", - "America/Tortola", - "Etc/GMT+4" - ] - }, - { - "name": "Pacific SA Standard Time", - "abbr": "PSST", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Santiago", - "utc": [ - "America/Santiago", - "Antarctica/Palmer" - ] - }, - { - "name": "Newfoundland Standard Time", - "abbr": "NDT", - "offset": -2.5, - "isdst": true, - "text": "(UTC-03:30) Newfoundland", - "utc": [ - "America/St_Johns" - ] - }, - { - "name": "E. South America Standard Time", - "abbr": "ESAST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Brasilia", - "utc": [ - "America/Sao_Paulo" - ] - }, - { - "name": "Argentina Standard Time", - "abbr": "AST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Buenos Aires", - "utc": [ - "America/Argentina/La_Rioja", - "America/Argentina/Rio_Gallegos", - "America/Argentina/Salta", - "America/Argentina/San_Juan", - "America/Argentina/San_Luis", - "America/Argentina/Tucuman", - "America/Argentina/Ushuaia", - "America/Buenos_Aires", - "America/Catamarca", - "America/Cordoba", - "America/Jujuy", - "America/Mendoza" - ] - }, - { - "name": "SA Eastern Standard Time", - "abbr": "SEST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Cayenne, Fortaleza", - "utc": [ - "America/Araguaina", - "America/Belem", - "America/Cayenne", - "America/Fortaleza", - "America/Maceio", - "America/Paramaribo", - "America/Recife", - "America/Santarem", - "Antarctica/Rothera", - "Atlantic/Stanley", - "Etc/GMT+3" - ] - }, - { - "name": "Greenland Standard Time", - "abbr": "GDT", - "offset": -3, - "isdst": true, - "text": "(UTC-03:00) Greenland", - "utc": [ - "America/Godthab" - ] - }, - { - "name": "Montevideo Standard Time", - "abbr": "MST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Montevideo", - "utc": [ - "America/Montevideo" - ] - }, - { - "name": "Bahia Standard Time", - "abbr": "BST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Salvador", - "utc": [ - "America/Bahia" - ] - }, - { - "name": "UTC-02", - "abbr": "U", - "offset": -2, - "isdst": false, - "text": "(UTC-02:00) Coordinated Universal Time-02", - "utc": [ - "America/Noronha", - "Atlantic/South_Georgia", - "Etc/GMT+2" - ] - }, - { - "name": "Mid-Atlantic Standard Time", - "abbr": "MDT", - "offset": -1, - "isdst": true, - "text": "(UTC-02:00) Mid-Atlantic - Old", - "utc": [] - }, - { - "name": "Azores Standard Time", - "abbr": "ADT", - "offset": 0, - "isdst": true, - "text": "(UTC-01:00) Azores", - "utc": [ - "America/Scoresbysund", - "Atlantic/Azores" - ] - }, - { - "name": "Cape Verde Standard Time", - "abbr": "CVST", - "offset": -1, - "isdst": false, - "text": "(UTC-01:00) Cape Verde Is.", - "utc": [ - "Atlantic/Cape_Verde", - "Etc/GMT+1" - ] - }, - { - "name": "Morocco Standard Time", - "abbr": "MDT", - "offset": 1, - "isdst": true, - "text": "(UTC) Casablanca", - "utc": [ - "Africa/Casablanca", - "Africa/El_Aaiun" - ] - }, - { - "name": "UTC", - "abbr": "UTC", - "offset": 0, - "isdst": false, - "text": "(UTC) Coordinated Universal Time", - "utc": [ - "America/Danmarkshavn", - "Etc/GMT" - ] - }, - { - "name": "GMT Standard Time", - "abbr": "GMT", - "offset": 0, - "isdst": false, - "text": "(UTC) Edinburgh, London", - "utc": [ - "Europe/Isle_of_Man", - "Europe/Guernsey", - "Europe/Jersey", - "Europe/London" - ] - }, - { - "name": "British Summer Time", - "abbr": "BST", - "offset": 1, - "isdst": true, - "text": "(UTC+01:00) Edinburgh, London", - "utc": [ - "Europe/Isle_of_Man", - "Europe/Guernsey", - "Europe/Jersey", - "Europe/London" - ] - }, - { - "name": "GMT Standard Time", - "abbr": "GDT", - "offset": 1, - "isdst": true, - "text": "(UTC) Dublin, Lisbon", - "utc": [ - "Atlantic/Canary", - "Atlantic/Faeroe", - "Atlantic/Madeira", - "Europe/Dublin", - "Europe/Lisbon" - ] - }, - { - "name": "Greenwich Standard Time", - "abbr": "GST", - "offset": 0, - "isdst": false, - "text": "(UTC) Monrovia, Reykjavik", - "utc": [ - "Africa/Abidjan", - "Africa/Accra", - "Africa/Bamako", - "Africa/Banjul", - "Africa/Bissau", - "Africa/Conakry", - "Africa/Dakar", - "Africa/Freetown", - "Africa/Lome", - "Africa/Monrovia", - "Africa/Nouakchott", - "Africa/Ouagadougou", - "Africa/Sao_Tome", - "Atlantic/Reykjavik", - "Atlantic/St_Helena" - ] - }, - { - "name": "W. Europe Standard Time", - "abbr": "WEDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", - "utc": [ - "Arctic/Longyearbyen", - "Europe/Amsterdam", - "Europe/Andorra", - "Europe/Berlin", - "Europe/Busingen", - "Europe/Gibraltar", - "Europe/Luxembourg", - "Europe/Malta", - "Europe/Monaco", - "Europe/Oslo", - "Europe/Rome", - "Europe/San_Marino", - "Europe/Stockholm", - "Europe/Vaduz", - "Europe/Vatican", - "Europe/Vienna", - "Europe/Zurich" - ] - }, - { - "name": "Central Europe Standard Time", - "abbr": "CEDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", - "utc": [ - "Europe/Belgrade", - "Europe/Bratislava", - "Europe/Budapest", - "Europe/Ljubljana", - "Europe/Podgorica", - "Europe/Prague", - "Europe/Tirane" - ] - }, - { - "name": "Romance Standard Time", - "abbr": "RDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris", - "utc": [ - "Africa/Ceuta", - "Europe/Brussels", - "Europe/Copenhagen", - "Europe/Madrid", - "Europe/Paris" - ] - }, - { - "name": "Central European Standard Time", - "abbr": "CEDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb", - "utc": [ - "Europe/Sarajevo", - "Europe/Skopje", - "Europe/Warsaw", - "Europe/Zagreb" - ] - }, - { - "name": "W. Central Africa Standard Time", - "abbr": "WCAST", - "offset": 1, - "isdst": false, - "text": "(UTC+01:00) West Central Africa", - "utc": [ - "Africa/Algiers", - "Africa/Bangui", - "Africa/Brazzaville", - "Africa/Douala", - "Africa/Kinshasa", - "Africa/Lagos", - "Africa/Libreville", - "Africa/Luanda", - "Africa/Malabo", - "Africa/Ndjamena", - "Africa/Niamey", - "Africa/Porto-Novo", - "Africa/Tunis", - "Etc/GMT-1" - ] - }, - { - "name": "Namibia Standard Time", - "abbr": "NST", - "offset": 1, - "isdst": false, - "text": "(UTC+01:00) Windhoek", - "utc": [ - "Africa/Windhoek" - ] - }, - { - "name": "GTB Standard Time", - "abbr": "GDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Athens, Bucharest", - "utc": [ - "Asia/Nicosia", - "Europe/Athens", - "Europe/Bucharest", - "Europe/Chisinau" - ] - }, - { - "name": "Middle East Standard Time", - "abbr": "MEDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Beirut", - "utc": [ - "Asia/Beirut" - ] - }, - { - "name": "Egypt Standard Time", - "abbr": "EST", - "offset": 2, - "isdst": false, - "text": "(UTC+02:00) Cairo", - "utc": [ - "Africa/Cairo" - ] - }, - { - "name": "Syria Standard Time", - "abbr": "SDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Damascus", - "utc": [ - "Asia/Damascus" - ] - }, - { - "name": "E. Europe Standard Time", - "abbr": "EEDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) E. Europe", - "utc": [ - "Asia/Nicosia", - "Europe/Athens", - "Europe/Bucharest", - "Europe/Chisinau", - "Europe/Helsinki", - "Europe/Kiev", - "Europe/Mariehamn", - "Europe/Nicosia", - "Europe/Riga", - "Europe/Sofia", - "Europe/Tallinn", - "Europe/Uzhgorod", - "Europe/Vilnius", - "Europe/Zaporozhye" - ] - }, - { - "name": "South Africa Standard Time", - "abbr": "SAST", - "offset": 2, - "isdst": false, - "text": "(UTC+02:00) Harare, Pretoria", - "utc": [ - "Africa/Blantyre", - "Africa/Bujumbura", - "Africa/Gaborone", - "Africa/Harare", - "Africa/Johannesburg", - "Africa/Kigali", - "Africa/Lubumbashi", - "Africa/Lusaka", - "Africa/Maputo", - "Africa/Maseru", - "Africa/Mbabane", - "Etc/GMT-2" - ] - }, - { - "name": "FLE Standard Time", - "abbr": "FDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", - "utc": [ - "Europe/Helsinki", - "Europe/Kiev", - "Europe/Mariehamn", - "Europe/Riga", - "Europe/Sofia", - "Europe/Tallinn", - "Europe/Uzhgorod", - "Europe/Vilnius", - "Europe/Zaporozhye" - ] - }, - { - "name": "Turkey Standard Time", - "abbr": "TDT", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Istanbul", - "utc": [ - "Europe/Istanbul" - ] - }, - { - "name": "Israel Standard Time", - "abbr": "JDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Jerusalem", - "utc": [ - "Asia/Jerusalem" - ] - }, - { - "name": "Libya Standard Time", - "abbr": "LST", - "offset": 2, - "isdst": false, - "text": "(UTC+02:00) Tripoli", - "utc": [ - "Africa/Tripoli" - ] - }, - { - "name": "Jordan Standard Time", - "abbr": "JST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Amman", - "utc": [ - "Asia/Amman" - ] - }, - { - "name": "Arabic Standard Time", - "abbr": "AST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Baghdad", - "utc": [ - "Asia/Baghdad" - ] - }, - { - "name": "Kaliningrad Standard Time", - "abbr": "KST", - "offset": 3, - "isdst": false, - "text": "(UTC+02:00) Kaliningrad", - "utc": [ - "Europe/Kaliningrad" - ] - }, - { - "name": "Arab Standard Time", - "abbr": "AST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Kuwait, Riyadh", - "utc": [ - "Asia/Aden", - "Asia/Bahrain", - "Asia/Kuwait", - "Asia/Qatar", - "Asia/Riyadh" - ] - }, - { - "name": "E. Africa Standard Time", - "abbr": "EAST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Nairobi", - "utc": [ - "Africa/Addis_Ababa", - "Africa/Asmera", - "Africa/Dar_es_Salaam", - "Africa/Djibouti", - "Africa/Juba", - "Africa/Kampala", - "Africa/Khartoum", - "Africa/Mogadishu", - "Africa/Nairobi", - "Antarctica/Syowa", - "Etc/GMT-3", - "Indian/Antananarivo", - "Indian/Comoro", - "Indian/Mayotte" - ] - }, - { - "name": "Moscow Standard Time", - "abbr": "MSK", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Moscow, St. Petersburg, Volgograd, Minsk", - "utc": [ - "Europe/Kirov", - "Europe/Moscow", - "Europe/Simferopol", - "Europe/Volgograd", - "Europe/Minsk" - ] - }, - { - "name": "Samara Time", - "abbr": "SAMT", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Samara, Ulyanovsk, Saratov", - "utc": [ - "Europe/Astrakhan", - "Europe/Samara", - "Europe/Ulyanovsk" - ] - }, - { - "name": "Iran Standard Time", - "abbr": "IDT", - "offset": 4.5, - "isdst": true, - "text": "(UTC+03:30) Tehran", - "utc": [ - "Asia/Tehran" - ] - }, - { - "name": "Arabian Standard Time", - "abbr": "AST", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Abu Dhabi, Muscat", - "utc": [ - "Asia/Dubai", - "Asia/Muscat", - "Etc/GMT-4" - ] - }, - { - "name": "Azerbaijan Standard Time", - "abbr": "ADT", - "offset": 5, - "isdst": true, - "text": "(UTC+04:00) Baku", - "utc": [ - "Asia/Baku" - ] - }, - { - "name": "Mauritius Standard Time", - "abbr": "MST", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Port Louis", - "utc": [ - "Indian/Mahe", - "Indian/Mauritius", - "Indian/Reunion" - ] - }, - { - "name": "Georgian Standard Time", - "abbr": "GET", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Tbilisi", - "utc": [ - "Asia/Tbilisi" - ] - }, - { - "name": "Caucasus Standard Time", - "abbr": "CST", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Yerevan", - "utc": [ - "Asia/Yerevan" - ] - }, - { - "name": "Afghanistan Standard Time", - "abbr": "AST", - "offset": 4.5, - "isdst": false, - "text": "(UTC+04:30) Kabul", - "utc": [ - "Asia/Kabul" - ] - }, - { - "name": "West Asia Standard Time", - "abbr": "WAST", - "offset": 5, - "isdst": false, - "text": "(UTC+05:00) Ashgabat, Tashkent", - "utc": [ - "Antarctica/Mawson", - "Asia/Aqtau", - "Asia/Aqtobe", - "Asia/Ashgabat", - "Asia/Dushanbe", - "Asia/Oral", - "Asia/Samarkand", - "Asia/Tashkent", - "Etc/GMT-5", - "Indian/Kerguelen", - "Indian/Maldives" - ] - }, - { - "name": "Yekaterinburg Time", - "abbr": "YEKT", - "offset": 5, - "isdst": false, - "text": "(UTC+05:00) Yekaterinburg", - "utc": [ - "Asia/Yekaterinburg" - ] - }, - { - "name": "Pakistan Standard Time", - "abbr": "PKT", - "offset": 5, - "isdst": false, - "text": "(UTC+05:00) Islamabad, Karachi", - "utc": [ - "Asia/Karachi" - ] - }, - { - "name": "India Standard Time", - "abbr": "IST", - "offset": 5.5, - "isdst": false, - "text": "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi", - "utc": [ - "Asia/Kolkata" - ] - }, - { - "name": "Sri Lanka Standard Time", - "abbr": "SLST", - "offset": 5.5, - "isdst": false, - "text": "(UTC+05:30) Sri Jayawardenepura", - "utc": [ - "Asia/Colombo" - ] - }, - { - "name": "Nepal Standard Time", - "abbr": "NST", - "offset": 5.75, - "isdst": false, - "text": "(UTC+05:45) Kathmandu", - "utc": [ - "Asia/Kathmandu" - ] - }, - { - "name": "Central Asia Standard Time", - "abbr": "CAST", - "offset": 6, - "isdst": false, - "text": "(UTC+06:00) Nur-Sultan (Astana)", - "utc": [ - "Antarctica/Vostok", - "Asia/Almaty", - "Asia/Bishkek", - "Asia/Qyzylorda", - "Asia/Urumqi", - "Etc/GMT-6", - "Indian/Chagos" - ] - }, - { - "name": "Bangladesh Standard Time", - "abbr": "BST", - "offset": 6, - "isdst": false, - "text": "(UTC+06:00) Dhaka", - "utc": [ - "Asia/Dhaka", - "Asia/Thimphu" - ] - }, - { - "name": "Myanmar Standard Time", - "abbr": "MST", - "offset": 6.5, - "isdst": false, - "text": "(UTC+06:30) Yangon (Rangoon)", - "utc": [ - "Asia/Rangoon", - "Indian/Cocos" - ] - }, - { - "name": "SE Asia Standard Time", - "abbr": "SAST", - "offset": 7, - "isdst": false, - "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta", - "utc": [ - "Antarctica/Davis", - "Asia/Bangkok", - "Asia/Hovd", - "Asia/Jakarta", - "Asia/Phnom_Penh", - "Asia/Pontianak", - "Asia/Saigon", - "Asia/Vientiane", - "Etc/GMT-7", - "Indian/Christmas" - ] - }, - { - "name": "N. Central Asia Standard Time", - "abbr": "NCAST", - "offset": 7, - "isdst": false, - "text": "(UTC+07:00) Novosibirsk", - "utc": [ - "Asia/Novokuznetsk", - "Asia/Novosibirsk", - "Asia/Omsk" - ] - }, - { - "name": "China Standard Time", - "abbr": "CST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi", - "utc": [ - "Asia/Hong_Kong", - "Asia/Macau", - "Asia/Shanghai" - ] - }, - { - "name": "North Asia Standard Time", - "abbr": "NAST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Krasnoyarsk", - "utc": [ - "Asia/Krasnoyarsk" - ] - }, - { - "name": "Singapore Standard Time", - "abbr": "MPST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Kuala Lumpur, Singapore", - "utc": [ - "Asia/Brunei", - "Asia/Kuala_Lumpur", - "Asia/Kuching", - "Asia/Makassar", - "Asia/Manila", - "Asia/Singapore", - "Etc/GMT-8" - ] - }, - { - "name": "W. Australia Standard Time", - "abbr": "WAST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Perth", - "utc": [ - "Antarctica/Casey", - "Australia/Perth" - ] - }, - { - "name": "Taipei Standard Time", - "abbr": "TST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Taipei", - "utc": [ - "Asia/Taipei" - ] - }, - { - "name": "Ulaanbaatar Standard Time", - "abbr": "UST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Ulaanbaatar", - "utc": [ - "Asia/Choibalsan", - "Asia/Ulaanbaatar" - ] - }, - { - "name": "North Asia East Standard Time", - "abbr": "NAEST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Irkutsk", - "utc": [ - "Asia/Irkutsk" - ] - }, - { - "name": "Japan Standard Time", - "abbr": "JST", - "offset": 9, - "isdst": false, - "text": "(UTC+09:00) Osaka, Sapporo, Tokyo", - "utc": [ - "Asia/Dili", - "Asia/Jayapura", - "Asia/Tokyo", - "Etc/GMT-9", - "Pacific/Palau" - ] - }, - { - "name": "Korea Standard Time", - "abbr": "KST", - "offset": 9, - "isdst": false, - "text": "(UTC+09:00) Seoul", - "utc": [ - "Asia/Pyongyang", - "Asia/Seoul" - ] - }, - { - "name": "Cen. Australia Standard Time", - "abbr": "CAST", - "offset": 9.5, - "isdst": false, - "text": "(UTC+09:30) Adelaide", - "utc": [ - "Australia/Adelaide", - "Australia/Broken_Hill" - ] - }, - { - "name": "AUS Central Standard Time", - "abbr": "ACST", - "offset": 9.5, - "isdst": false, - "text": "(UTC+09:30) Darwin", - "utc": [ - "Australia/Darwin" - ] - }, - { - "name": "E. Australia Standard Time", - "abbr": "EAST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Brisbane", - "utc": [ - "Australia/Brisbane", - "Australia/Lindeman" - ] - }, - { - "name": "AUS Eastern Standard Time", - "abbr": "AEST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Canberra, Melbourne, Sydney", - "utc": [ - "Australia/Melbourne", - "Australia/Sydney" - ] - }, - { - "name": "West Pacific Standard Time", - "abbr": "WPST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Guam, Port Moresby", - "utc": [ - "Antarctica/DumontDUrville", - "Etc/GMT-10", - "Pacific/Guam", - "Pacific/Port_Moresby", - "Pacific/Saipan", - "Pacific/Truk" - ] - }, - { - "name": "Tasmania Standard Time", - "abbr": "TST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Hobart", - "utc": [ - "Australia/Currie", - "Australia/Hobart" - ] - }, - { - "name": "Yakutsk Standard Time", - "abbr": "YST", - "offset": 9, - "isdst": false, - "text": "(UTC+09:00) Yakutsk", - "utc": [ - "Asia/Chita", - "Asia/Khandyga", - "Asia/Yakutsk" - ] - }, - { - "name": "Central Pacific Standard Time", - "abbr": "CPST", - "offset": 11, - "isdst": false, - "text": "(UTC+11:00) Solomon Is., New Caledonia", - "utc": [ - "Antarctica/Macquarie", - "Etc/GMT-11", - "Pacific/Efate", - "Pacific/Guadalcanal", - "Pacific/Kosrae", - "Pacific/Noumea", - "Pacific/Ponape" - ] - }, - { - "name": "Vladivostok Standard Time", - "abbr": "VST", - "offset": 11, - "isdst": false, - "text": "(UTC+11:00) Vladivostok", - "utc": [ - "Asia/Sakhalin", - "Asia/Ust-Nera", - "Asia/Vladivostok" - ] - }, - { - "name": "New Zealand Standard Time", - "abbr": "NZST", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Auckland, Wellington", - "utc": [ - "Antarctica/McMurdo", - "Pacific/Auckland" - ] - }, - { - "name": "UTC+12", - "abbr": "U", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Coordinated Universal Time+12", - "utc": [ - "Etc/GMT-12", - "Pacific/Funafuti", - "Pacific/Kwajalein", - "Pacific/Majuro", - "Pacific/Nauru", - "Pacific/Tarawa", - "Pacific/Wake", - "Pacific/Wallis" - ] - }, - { - "name": "Fiji Standard Time", - "abbr": "FST", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Fiji", - "utc": [ - "Pacific/Fiji" - ] - }, - { - "name": "Magadan Standard Time", - "abbr": "MST", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Magadan", - "utc": [ - "Asia/Anadyr", - "Asia/Kamchatka", - "Asia/Magadan", - "Asia/Srednekolymsk" - ] - }, - { - "name": "Kamchatka Standard Time", - "abbr": "KDT", - "offset": 13, - "isdst": true, - "text": "(UTC+12:00) Petropavlovsk-Kamchatsky - Old", - "utc": [ - "Asia/Kamchatka" - ] - }, - { - "name": "Tonga Standard Time", - "abbr": "TST", - "offset": 13, - "isdst": false, - "text": "(UTC+13:00) Nuku'alofa", - "utc": [ - "Etc/GMT-13", - "Pacific/Enderbury", - "Pacific/Fakaofo", - "Pacific/Tongatapu" - ] - }, - { - "name": "Samoa Standard Time", - "abbr": "SST", - "offset": 13, - "isdst": false, - "text": "(UTC+13:00) Samoa", - "utc": [ - "Pacific/Apia" - ] - } - ], - //List source: http://answers.google.com/answers/threadview/id/589312.html - profession: [ - "Airline Pilot", - "Academic Team", - "Accountant", - "Account Executive", - "Actor", - "Actuary", - "Acquisition Analyst", - "Administrative Asst.", - "Administrative Analyst", - "Administrator", - "Advertising Director", - "Aerospace Engineer", - "Agent", - "Agricultural Inspector", - "Agricultural Scientist", - "Air Traffic Controller", - "Animal Trainer", - "Anthropologist", - "Appraiser", - "Architect", - "Art Director", - "Artist", - "Astronomer", - "Athletic Coach", - "Auditor", - "Author", - "Baker", - "Banker", - "Bankruptcy Attorney", - "Benefits Manager", - "Biologist", - "Bio-feedback Specialist", - "Biomedical Engineer", - "Biotechnical Researcher", - "Broadcaster", - "Broker", - "Building Manager", - "Building Contractor", - "Building Inspector", - "Business Analyst", - "Business Planner", - "Business Manager", - "Buyer", - "Call Center Manager", - "Career Counselor", - "Cash Manager", - "Ceramic Engineer", - "Chief Executive Officer", - "Chief Operation Officer", - "Chef", - "Chemical Engineer", - "Chemist", - "Child Care Manager", - "Chief Medical Officer", - "Chiropractor", - "Cinematographer", - "City Housing Manager", - "City Manager", - "Civil Engineer", - "Claims Manager", - "Clinical Research Assistant", - "Collections Manager", - "Compliance Manager", - "Comptroller", - "Computer Manager", - "Commercial Artist", - "Communications Affairs Director", - "Communications Director", - "Communications Engineer", - "Compensation Analyst", - "Computer Programmer", - "Computer Ops. Manager", - "Computer Engineer", - "Computer Operator", - "Computer Graphics Specialist", - "Construction Engineer", - "Construction Manager", - "Consultant", - "Consumer Relations Manager", - "Contract Administrator", - "Copyright Attorney", - "Copywriter", - "Corporate Planner", - "Corrections Officer", - "Cosmetologist", - "Credit Analyst", - "Cruise Director", - "Chief Information Officer", - "Chief Technology Officer", - "Customer Service Manager", - "Cryptologist", - "Dancer", - "Data Security Manager", - "Database Manager", - "Day Care Instructor", - "Dentist", - "Designer", - "Design Engineer", - "Desktop Publisher", - "Developer", - "Development Officer", - "Diamond Merchant", - "Dietitian", - "Direct Marketer", - "Director", - "Distribution Manager", - "Diversity Manager", - "Economist", - "EEO Compliance Manager", - "Editor", - "Education Adminator", - "Electrical Engineer", - "Electro Optical Engineer", - "Electronics Engineer", - "Embassy Management", - "Employment Agent", - "Engineer Technician", - "Entrepreneur", - "Environmental Analyst", - "Environmental Attorney", - "Environmental Engineer", - "Environmental Specialist", - "Escrow Officer", - "Estimator", - "Executive Assistant", - "Executive Director", - "Executive Recruiter", - "Facilities Manager", - "Family Counselor", - "Fashion Events Manager", - "Fashion Merchandiser", - "Fast Food Manager", - "Film Producer", - "Film Production Assistant", - "Financial Analyst", - "Financial Planner", - "Financier", - "Fine Artist", - "Wildlife Specialist", - "Fitness Consultant", - "Flight Attendant", - "Flight Engineer", - "Floral Designer", - "Food & Beverage Director", - "Food Service Manager", - "Forestry Technician", - "Franchise Management", - "Franchise Sales", - "Fraud Investigator", - "Freelance Writer", - "Fund Raiser", - "General Manager", - "Geologist", - "General Counsel", - "Geriatric Specialist", - "Gerontologist", - "Glamour Photographer", - "Golf Club Manager", - "Gourmet Chef", - "Graphic Designer", - "Grounds Keeper", - "Hazardous Waste Manager", - "Health Care Manager", - "Health Therapist", - "Health Service Administrator", - "Hearing Officer", - "Home Economist", - "Horticulturist", - "Hospital Administrator", - "Hotel Manager", - "Human Resources Manager", - "Importer", - "Industrial Designer", - "Industrial Engineer", - "Information Director", - "Inside Sales", - "Insurance Adjuster", - "Interior Decorator", - "Internal Controls Director", - "International Acct.", - "International Courier", - "International Lawyer", - "Interpreter", - "Investigator", - "Investment Banker", - "Investment Manager", - "IT Architect", - "IT Project Manager", - "IT Systems Analyst", - "Jeweler", - "Joint Venture Manager", - "Journalist", - "Labor Negotiator", - "Labor Organizer", - "Labor Relations Manager", - "Lab Services Director", - "Lab Technician", - "Land Developer", - "Landscape Architect", - "Law Enforcement Officer", - "Lawyer", - "Lead Software Engineer", - "Lead Software Test Engineer", - "Leasing Manager", - "Legal Secretary", - "Library Manager", - "Litigation Attorney", - "Loan Officer", - "Lobbyist", - "Logistics Manager", - "Maintenance Manager", - "Management Consultant", - "Managed Care Director", - "Managing Partner", - "Manufacturing Director", - "Manpower Planner", - "Marine Biologist", - "Market Res. Analyst", - "Marketing Director", - "Materials Manager", - "Mathematician", - "Membership Chairman", - "Mechanic", - "Mechanical Engineer", - "Media Buyer", - "Medical Investor", - "Medical Secretary", - "Medical Technician", - "Mental Health Counselor", - "Merchandiser", - "Metallurgical Engineering", - "Meteorologist", - "Microbiologist", - "MIS Manager", - "Motion Picture Director", - "Multimedia Director", - "Musician", - "Network Administrator", - "Network Specialist", - "Network Operator", - "New Product Manager", - "Novelist", - "Nuclear Engineer", - "Nuclear Specialist", - "Nutritionist", - "Nursing Administrator", - "Occupational Therapist", - "Oceanographer", - "Office Manager", - "Operations Manager", - "Operations Research Director", - "Optical Technician", - "Optometrist", - "Organizational Development Manager", - "Outplacement Specialist", - "Paralegal", - "Park Ranger", - "Patent Attorney", - "Payroll Specialist", - "Personnel Specialist", - "Petroleum Engineer", - "Pharmacist", - "Photographer", - "Physical Therapist", - "Physician", - "Physician Assistant", - "Physicist", - "Planning Director", - "Podiatrist", - "Political Analyst", - "Political Scientist", - "Politician", - "Portfolio Manager", - "Preschool Management", - "Preschool Teacher", - "Principal", - "Private Banker", - "Private Investigator", - "Probation Officer", - "Process Engineer", - "Producer", - "Product Manager", - "Product Engineer", - "Production Engineer", - "Production Planner", - "Professional Athlete", - "Professional Coach", - "Professor", - "Project Engineer", - "Project Manager", - "Program Manager", - "Property Manager", - "Public Administrator", - "Public Safety Director", - "PR Specialist", - "Publisher", - "Purchasing Agent", - "Publishing Director", - "Quality Assurance Specialist", - "Quality Control Engineer", - "Quality Control Inspector", - "Radiology Manager", - "Railroad Engineer", - "Real Estate Broker", - "Recreational Director", - "Recruiter", - "Redevelopment Specialist", - "Regulatory Affairs Manager", - "Registered Nurse", - "Rehabilitation Counselor", - "Relocation Manager", - "Reporter", - "Research Specialist", - "Restaurant Manager", - "Retail Store Manager", - "Risk Analyst", - "Safety Engineer", - "Sales Engineer", - "Sales Trainer", - "Sales Promotion Manager", - "Sales Representative", - "Sales Manager", - "Service Manager", - "Sanitation Engineer", - "Scientific Programmer", - "Scientific Writer", - "Securities Analyst", - "Security Consultant", - "Security Director", - "Seminar Presenter", - "Ship's Officer", - "Singer", - "Social Director", - "Social Program Planner", - "Social Research", - "Social Scientist", - "Social Worker", - "Sociologist", - "Software Developer", - "Software Engineer", - "Software Test Engineer", - "Soil Scientist", - "Special Events Manager", - "Special Education Teacher", - "Special Projects Director", - "Speech Pathologist", - "Speech Writer", - "Sports Event Manager", - "Statistician", - "Store Manager", - "Strategic Alliance Director", - "Strategic Planning Director", - "Stress Reduction Specialist", - "Stockbroker", - "Surveyor", - "Structural Engineer", - "Superintendent", - "Supply Chain Director", - "System Engineer", - "Systems Analyst", - "Systems Programmer", - "System Administrator", - "Tax Specialist", - "Teacher", - "Technical Support Specialist", - "Technical Illustrator", - "Technical Writer", - "Technology Director", - "Telecom Analyst", - "Telemarketer", - "Theatrical Director", - "Title Examiner", - "Tour Escort", - "Tour Guide Director", - "Traffic Manager", - "Trainer Translator", - "Transportation Manager", - "Travel Agent", - "Treasurer", - "TV Programmer", - "Underwriter", - "Union Representative", - "University Administrator", - "University Dean", - "Urban Planner", - "Veterinarian", - "Vendor Relations Director", - "Viticulturist", - "Warehouse Manager" - ], - animals : { - //list of ocean animals comes from https://owlcation.com/stem/list-of-ocean-animals - "ocean" : ["Acantharea","Anemone","Angelfish King","Ahi Tuna","Albacore","American Oyster","Anchovy","Armored Snail","Arctic Char","Atlantic Bluefin Tuna","Atlantic Cod","Atlantic Goliath Grouper","Atlantic Trumpetfish","Atlantic Wolffish","Baleen Whale","Banded Butterflyfish","Banded Coral Shrimp","Banded Sea Krait","Barnacle","Barndoor Skate","Barracuda","Basking Shark","Bass","Beluga Whale","Bluebanded Goby","Bluehead Wrasse","Bluefish","Bluestreak Cleaner-Wrasse","Blue Marlin","Blue Shark","Blue Spiny Lobster","Blue Tang","Blue Whale","Broadclub Cuttlefish","Bull Shark","Chambered Nautilus","Chilean Basket Star","Chilean Jack Mackerel","Chinook Salmon","Christmas Tree Worm","Clam","Clown Anemonefish","Clown Triggerfish","Cod","Coelacanth","Cockscomb Cup Coral","Common Fangtooth","Conch","Cookiecutter Shark","Copepod","Coral","Corydoras","Cownose Ray","Crab","Crown-of-Thorns Starfish","Cushion Star","Cuttlefish","California Sea Otters","Dolphin","Dolphinfish","Dory","Devil Fish","Dugong","Dumbo Octopus","Dungeness Crab","Eccentric Sand Dollar","Edible Sea Cucumber","Eel","Elephant Seal","Elkhorn Coral","Emperor Shrimp","Estuarine Crocodile","Fathead Sculpin","Fiddler Crab","Fin Whale","Flameback","Flamingo Tongue Snail","Flashlight Fish","Flatback Turtle","Flatfish","Flying Fish","Flounder","Fluke","French Angelfish","Frilled Shark","Fugu (also called Pufferfish)","Gar","Geoduck","Giant Barrel Sponge","Giant Caribbean Sea Anemone","Giant Clam","Giant Isopod","Giant Kingfish","Giant Oarfish","Giant Pacific Octopus","Giant Pyrosome","Giant Sea Star","Giant Squid","Glowing Sucker Octopus","Giant Tube Worm","Goblin Shark","Goosefish","Great White Shark","Greenland Shark","Grey Atlantic Seal","Grouper","Grunion","Guineafowl Puffer","Haddock","Hake","Halibut","Hammerhead Shark","Hapuka","Harbor Porpoise","Harbor Seal","Hatchetfish","Hawaiian Monk Seal","Hawksbill Turtle","Hector's Dolphin","Hermit Crab","Herring","Hoki","Horn Shark","Horseshoe Crab","Humpback Anglerfish","Humpback Whale","Icefish","Imperator Angelfish","Irukandji Jellyfish","Isopod","Ivory Bush Coral","Japanese Spider Crab","Jellyfish","John Dory","Juan Fernandez Fur Seal","Killer Whale","Kiwa Hirsuta","Krill","Lagoon Triggerfish","Lamprey","Leafy Seadragon","Leopard Seal","Limpet","Ling","Lionfish","Lions Mane Jellyfish","Lobe Coral","Lobster","Loggerhead Turtle","Longnose Sawshark","Longsnout Seahorse","Lophelia Coral","Marrus Orthocanna","Manatee","Manta Ray","Marlin","Megamouth Shark","Mexican Lookdown","Mimic Octopus","Moon Jelly","Mollusk","Monkfish","Moray Eel","Mullet","Mussel","Megaladon","Napoleon Wrasse","Nassau Grouper","Narwhal","Nautilus","Needlefish","Northern Seahorse","North Atlantic Right Whale","Northern Red Snapper","Norway Lobster","Nudibranch","Nurse Shark","Oarfish","Ocean Sunfish","Oceanic Whitetip Shark","Octopus","Olive Sea Snake","Orange Roughy","Ostracod","Otter","Oyster","Pacific Angelshark","Pacific Blackdragon","Pacific Halibut","Pacific Sardine","Pacific Sea Nettle Jellyfish","Pacific White Sided Dolphin","Pantropical Spotted Dolphin","Patagonian Toothfish","Peacock Mantis Shrimp","Pelagic Thresher Shark","Penguin","Peruvian Anchoveta","Pilchard","Pink Salmon","Pinniped","Plankton","Porpoise","Polar Bear","Portuguese Man o' War","Pycnogonid Sea Spider","Quahog","Queen Angelfish","Queen Conch","Queen Parrotfish","Queensland Grouper","Ragfish","Ratfish","Rattail Fish","Ray","Red Drum","Red King Crab","Ringed Seal","Risso's Dolphin","Ross Seals","Sablefish","Salmon","Sand Dollar","Sandbar Shark","Sawfish","Sarcastic Fringehead","Scalloped Hammerhead Shark","Seahorse","Sea Cucumber","Sea Lion","Sea Urchin","Seal","Shark","Shortfin Mako Shark","Shovelnose Guitarfish","Shrimp","Silverside Fish","Skipjack Tuna","Slender Snipe Eel","Smalltooth Sawfish","Smelts","Sockeye Salmon","Southern Stingray","Sponge","Spotted Porcupinefish","Spotted Dolphin","Spotted Eagle Ray","Spotted Moray","Squid","Squidworm","Starfish","Stickleback","Stonefish","Stoplight Loosejaw","Sturgeon","Swordfish","Tan Bristlemouth","Tasseled Wobbegong","Terrible Claw Lobster","Threespot Damselfish","Tiger Prawn","Tiger Shark","Tilefish","Toadfish","Tropical Two-Wing Flyfish","Tuna","Umbrella Squid","Velvet Crab","Venus Flytrap Sea Anemone","Vigtorniella Worm","Viperfish","Vampire Squid","Vaquita","Wahoo","Walrus","West Indian Manatee","Whale","Whale Shark","Whiptail Gulper","White-Beaked Dolphin","White-Ring Garden Eel","White Shrimp","Wobbegong","Wrasse","Wreckfish","Xiphosura","Yellowtail Damselfish","Yelloweye Rockfish","Yellow Cup Black Coral","Yellow Tube Sponge","Yellowfin Tuna","Zebrashark","Zooplankton"], - //list of desert, grassland, and forest animals comes from http://www.skyenimals.com/ - "desert" : ["Aardwolf","Addax","African Wild Ass","Ant","Antelope","Armadillo","Baboon","Badger","Bat","Bearded Dragon","Beetle","Bird","Black-footed Cat","Boa","Brown Bear","Bustard","Butterfly","Camel","Caracal","Caracara","Caterpillar","Centipede","Cheetah","Chipmunk","Chuckwalla","Climbing Mouse","Coati","Cobra","Cotton Rat","Cougar","Courser","Crane Fly","Crow","Dassie Rat","Dove","Dunnart","Eagle","Echidna","Elephant","Emu","Falcon","Fly","Fox","Frogmouth","Gecko","Geoffroy's Cat","Gerbil","Grasshopper","Guanaco","Gundi","Hamster","Hawk","Hedgehog","Hyena","Hyrax","Jackal","Kangaroo","Kangaroo Rat","Kestrel","Kowari","Kultarr","Leopard","Lion","Macaw","Meerkat","Mouse","Oryx","Ostrich","Owl","Pronghorn","Python","Rabbit","Raccoon","Rattlesnake","Rhinoceros","Sand Cat","Spectacled Bear","Spiny Mouse","Starling","Stick Bug","Tarantula","Tit","Toad","Tortoise","Tyrant Flycatcher","Viper","Vulture","Waxwing","Xerus","Zebra"], - "grassland" : ["Aardvark","Aardwolf","Accentor","African Buffalo","African Wild Dog","Alpaca","Anaconda","Ant","Anteater","Antelope","Armadillo","Baboon","Badger","Bandicoot","Barbet","Bat","Bee","Bee-eater","Beetle","Bird","Bison","Black-footed Cat","Black-footed Ferret","Bluebird","Boa","Bowerbird","Brown Bear","Bush Dog","Bushshrike","Bustard","Butterfly","Buzzard","Caracal","Caracara","Cardinal","Caterpillar","Cheetah","Chipmunk","Civet","Climbing Mouse","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Common Genet","Cotton Rat","Cougar","Courser","Coyote","Crane","Crane Fly","Cricket","Crow","Culpeo","Death Adder","Deer","Deer Mouse","Dingo","Dinosaur","Dove","Drongo","Duck","Duiker","Dunnart","Eagle","Echidna","Elephant","Elk","Emu","Falcon","Finch","Flea","Fly","Flying Frog","Fox","Frog","Frogmouth","Garter Snake","Gazelle","Gecko","Geoffroy's Cat","Gerbil","Giant Tortoise","Giraffe","Grasshopper","Grison","Groundhog","Grouse","Guanaco","Guinea Pig","Hamster","Harrier","Hartebeest","Hawk","Hedgehog","Helmetshrike","Hippopotamus","Hornbill","Hyena","Hyrax","Impala","Jackal","Jaguar","Jaguarundi","Kangaroo","Kangaroo Rat","Kestrel","Kultarr","Ladybug","Leopard","Lion","Macaw","Meerkat","Mouse","Newt","Oryx","Ostrich","Owl","Pangolin","Pheasant","Prairie Dog","Pronghorn","Przewalski's Horse","Python","Quoll","Rabbit","Raven","Rhinoceros","Shelduck","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Tamandua","Tasmanian Devil","Thornbill","Thrush","Toad","Tortoise"], - "forest" : ["Agouti","Anaconda","Anoa","Ant","Anteater","Antelope","Armadillo","Asian Black Bear","Aye-aye","Babirusa","Baboon","Badger","Bandicoot","Banteng","Barbet","Basilisk","Bat","Bearded Dragon","Bee","Bee-eater","Beetle","Bettong","Binturong","Bird-of-paradise","Bongo","Bowerbird","Bulbul","Bush Dog","Bushbaby","Bushshrike","Butterfly","Buzzard","Caecilian","Cardinal","Cassowary","Caterpillar","Centipede","Chameleon","Chimpanzee","Cicada","Civet","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Colugo","Cotinga","Cotton Rat","Cougar","Crane Fly","Cricket","Crocodile","Crow","Cuckoo","Cuscus","Death Adder","Deer","Dhole","Dingo","Dinosaur","Drongo","Duck","Duiker","Eagle","Echidna","Elephant","Finch","Flat-headed Cat","Flea","Flowerpecker","Fly","Flying Frog","Fossa","Frog","Frogmouth","Gaur","Gecko","Gorilla","Grison","Hawaiian Honeycreeper","Hawk","Hedgehog","Helmetshrike","Hornbill","Hyrax","Iguana","Jackal","Jaguar","Jaguarundi","Kestrel","Ladybug","Lemur","Leopard","Lion","Macaw","Mandrill","Margay","Monkey","Mouse","Mouse Deer","Newt","Okapi","Old World Flycatcher","Orangutan","Owl","Pangolin","Peafowl","Pheasant","Possum","Python","Quokka","Rabbit","Raccoon","Red Panda","Red River Hog","Rhinoceros","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Sun Bear","Tamandua","Tamarin","Tapir","Tarantula","Thrush","Tiger","Tit","Toad","Tortoise","Toucan","Trogon","Trumpeter","Turaco","Turtle","Tyrant Flycatcher","Viper","Vulture","Wallaby","Warbler","Wasp","Waxwing","Weaver","Weaver-finch","Whistler","White-eye","Whydah","Woodswallow","Worm","Wren","Xenops","Yellowjacket","Accentor","African Buffalo","American Black Bear","Anole","Bird","Bison","Boa","Brown Bear","Chipmunk","Common Genet","Copperhead","Coyote","Deer Mouse","Dormouse","Elk","Emu","Fisher","Fox","Garter Snake","Giant Panda","Giant Tortoise","Groundhog","Grouse","Guanaco","Himalayan Tahr","Kangaroo","Koala","Numbat","Quoll","Raccoon dog","Tasmanian Devil","Thornbill","Turkey","Vole","Weasel","Wildcat","Wolf","Wombat","Woodchuck","Woodpecker"], - //list of farm animals comes from https://www.buzzle.com/articles/farm-animals-list.html - "farm" : ["Alpaca","Buffalo","Banteng","Cow","Cat","Chicken","Carp","Camel","Donkey","Dog","Duck","Emu","Goat","Gayal","Guinea","Goose","Horse","Honey","Llama","Pig","Pigeon","Rhea","Rabbit","Sheep","Silkworm","Turkey","Yak","Zebu"], - //list of pet animals comes from https://www.dogbreedinfo.com/pets/pet.htm - "pet" : ["Bearded Dragon","Birds","Burro","Cats","Chameleons","Chickens","Chinchillas","Chinese Water Dragon","Cows","Dogs","Donkey","Ducks","Ferrets","Fish","Geckos","Geese","Gerbils","Goats","Guinea Fowl","Guinea Pigs","Hamsters","Hedgehogs","Horses","Iguanas","Llamas","Lizards","Mice","Mule","Peafowl","Pigs and Hogs","Pigeons","Ponies","Pot Bellied Pig","Rabbits","Rats","Sheep","Skinks","Snakes","Stick Insects","Sugar Gliders","Tarantula","Turkeys","Turtles"], - //list of zoo animals comes from https://bronxzoo.com/animals - "zoo" : ["Aardvark","African Wild Dog","Aldabra Tortoise","American Alligator","American Bison","Amur Tiger","Anaconda","Andean Condor","Asian Elephant","Baby Doll Sheep","Bald Eagle","Barred Owl","Blue Iguana","Boer Goat","California Sea Lion","Caribbean Flamingo","Chinchilla","Collared Lemur","Coquerel's Sifaka","Cuban Amazon Parrot","Ebony Langur","Fennec Fox","Fossa","Gelada","Giant Anteater","Giraffe","Gorilla","Grizzly Bear","Henkel's Leaf-tailed Gecko","Indian Gharial","Indian Rhinoceros","King Cobra","King Vulture","Komodo Dragon","Linne's Two-toed Sloth","Lion","Little Penguin","Madagascar Tree Boa","Magellanic Penguin","Malayan Tapir","Malayan Tiger","Matschies Tree Kangaroo","Mini Donkey","Monarch Butterfly","Nile crocodile","North American Porcupine","Nubian Ibex","Okapi","Poison Dart Frog","Polar Bear","Pygmy Marmoset","Radiated Tortoise","Red Panda","Red Ruffed Lemur","Ring-tailed Lemur","Ring-tailed Mongoose","Rock Hyrax","Small Clawed Asian Otter","Snow Leopard","Snowy Owl","Southern White-faced Owl","Southern White Rhinocerous","Squirrel Monkey","Tufted Puffin","White Cheeked Gibbon","White-throated Bee Eater","Zebra"] - }, - primes: [ - // 1230 first primes, i.e. all primes up to the first one greater than 10000, inclusive. - 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,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007 - ], - emotions: [ - "love", - "joy", - "surprise", - "anger", - "sadness", - "fear" - ], - music_genres: { - 'general': [ - 'Rock', - 'Pop', - 'Hip-Hop', - 'Jazz', - 'Classical', - 'Electronic', - 'Country', - 'R&B', - 'Reggae', - 'Blues', - 'Metal', - 'Folk', - 'Alternative', - 'Punk', - 'Disco', - 'Funk', - 'Techno', - 'Indie', - 'Gospel', - 'Dance', - 'Children\'s', - 'World' - ], - 'alternative': [ - 'Art Punk', - 'Alternative Rock', - 'Britpunk', - 'College Rock', - 'Crossover Thrash', - 'Crust Punk', - 'Emo / Emocore', - 'Experimental Rock', - 'Folk Punk', - 'Goth / Gothic Rock', - 'Grunge', - 'Hardcore Punk', - 'Hard Rock', - 'Indie Rock', - 'Lo-fi', - 'Musique ConcrĆØte', - 'New Wave', - 'Progressive Rock', - 'Punk', - 'Shoegaze', - 'Steampunk', - ], 'blues': [ - 'Acoustic Blues', - 'African Blues', - 'Blues Rock', - 'Blues Shouter', - 'British Blues', - 'Canadian Blues', - 'Chicago Blues', - 'Classic Blues', - 'Classic Female Blues', - 'Contemporary Blues', - 'Country Blues', - 'Dark Blues', - 'Delta Blues', - 'Detroit Blues', - 'Doom Blues', - 'Electric Blues', - 'Folk Blues', - 'Gospel Blues', - 'Harmonica Blues', - 'Hill Country Blues', - 'Hokum Blues', - 'Jazz Blues', - 'Jump Blues', - 'Kansas City Blues', - 'Louisiana Blues', - 'Memphis Blues', - 'Modern Blues', - 'New Orlean Blues', - 'NY Blues', - 'Piano Blues', - 'Piedmont Blues', - 'Punk Blues', - 'Ragtime Blues', - 'Rhythm Blues', - 'Soul Blues', - 'St.Louis Blues', - 'Soul Blues', - 'Swamp Blues', - 'Texas Blues', - 'Urban Blues', - 'Vandeville', - 'West Coast Blues', - ], 'children\'s': [ - 'Lullabies', - 'Sing - Along', - 'Stories' - ], 'classical': [ - 'Avant-Garde', - 'Ballet', - 'Baroque', - 'Cantata', - 'Chamber Music', - 'String Quartet', - 'Chant', - 'Choral', - 'Classical Crossover', - 'Concerto', - 'Concerto Grosso', - 'Contemporary Classical', - 'Early Music', - 'Expressionist', - 'High Classical', - 'Impressionist', - 'Mass Requiem', - 'Medieval', - 'Minimalism', - 'Modern Composition', - 'Modern Classical', - 'Opera', - 'Oratorio', - 'Orchestral', - 'Organum', - 'Renaissance', - 'Romantic (early period)', - 'Romantic (later period)', - 'Sonata', - 'Symphonic', - 'Symphony', - 'Twelve-tone', - 'Wedding Music' - ], 'country': [ - 'Alternative Country', - 'Americana', - 'Australian Country', - 'Bakersfield Sound', - 'Bluegrass', - 'Blues Country', - 'Cajun Fiddle Tunes', - 'Christian Country', - 'Classic Country', - 'Close Harmony', - 'Contemporary Bluegrass', - 'Contemporary Country', - 'Country Gospel', - 'Country Pop', - 'Country Rap', - 'Country Rock', - 'Country Soul', - 'Cowboy / Western', - 'Cowpunk', - 'Dansband', - 'Honky Tonk', - 'Franco-Country', - 'Gulf and Western', - 'Hellbilly Music', - 'Honky Tonk', - 'Instrumental Country', - 'Lubbock Sound', - 'Nashville Sound', - 'Neotraditional Country', - 'Outlaw Country', - 'Progressive', - 'Psychobilly / Punkabilly', - 'Red Dirt', - 'Sertanejo', - 'Texas County', - 'Traditional Bluegrass', - 'Traditional Country', - 'Truck-Driving Country', - 'Urban Cowboy', - 'Western Swing' - ], 'dance': [ - 'Club / Club Dance', - 'Breakcore', - 'Breakbeat / Breakstep', - 'Chillstep', - 'Deep House', - 'Dubstep', - 'Dancehall', - 'Electro House', - 'Electroswing', - 'Exercise', - 'Future Garage', - 'Garage', - 'Glitch Hop', - 'Glitch Pop', - 'Grime', - 'Hardcore', - 'Hard Dance', - 'Hi-NRG / Eurodance', - 'Horrorcore', - 'House', - 'Jackin House', - 'Jungle / Drum n bass', - 'Liquid Dub', - 'Regstep', - 'Speedcore', - 'Techno', - 'Trance', - 'Trap' - ], electronic: [ - '2-Step', - '8bit', - 'Ambient', - 'Asian Underground', - 'Bassline', - 'Chillwave', - 'Chiptune', - 'Crunk', - 'Downtempo', - 'Drum & Bass', - 'Hard Step', - 'Electro', - 'Electro-swing', - 'Electroacoustic', - 'Electronica', - 'Electronic Rock', - 'Eurodance', - 'Hardstyle', - 'Hi-Nrg', - 'IDM/Experimental', - 'Industrial', - 'Trip Hop', - 'Vaporwave', - 'UK Garage', - 'House', - 'Dubstep', - 'Deep House', - 'EDM', - 'Future Bass', - 'Psychedelic trance' - ], 'jazz' : [ - 'Acid Jazz', - 'Afro-Cuban Jazz', - 'Avant-Garde Jazz', - 'Bebop', - 'Big Band', - 'Blue Note', - 'British Dance Band (Jazz)', - 'Cape Jazz', - 'Chamber Jazz', - 'Contemporary Jazz', - 'Continental Jazz', - 'Cool Jazz', - 'Crossover Jazz', - 'Dark Jazz', - 'Dixieland', - 'Early Jazz', - 'Electro Swing (Jazz)', - 'Ethio-jazz', - 'Ethno-Jazz', - 'European Free Jazz', - 'Free Funk (Avant-Garde / Funk Jazz)', - 'Free Jazz', - 'Fusion', - 'Gypsy Jazz', - 'Hard Bop', - 'Indo Jazz', - 'Jazz Blues', - 'Jazz-Funk (see Free Funk)', - 'Jazz-Fusion', - 'Jazz Rap', - 'Jazz Rock', - 'Kansas City Jazz', - 'Latin Jazz', - 'M-Base Jazz', - 'Mainstream Jazz', - 'Modal Jazz', - 'Neo-Bop', - 'Neo-Swing', - 'Nu Jazz', - 'Orchestral Jazz', - 'Post-Bop', - 'Punk Jazz', - 'Ragtime', - 'Ska Jazz', - 'Skiffle (also Folk)', - 'Smooth Jazz', - 'Soul Jazz', - 'Swing Jazz', - 'Straight-Ahead Jazz', - 'Trad Jazz', - 'Third Stream', - 'Jazz-Funk', - 'Free Jazz', - 'West Coast Jazz' - ], 'metal': [ - 'Heavy Metal', - 'Speed Metal', - 'Thrash Metal', - 'Power Metal', - 'Death Metal', - 'Black Metal', - 'Pagan Metal', - 'Viking Metal', - 'Folk Metal', - 'Symphonic Metal', - 'Gothic Metal', - 'Glam Metal', - 'Hair Metal', - 'Doom Metal', - 'Groove Metal', - 'Industrial Metal', - 'Modern Metal', - 'Neoclassical Metal', - 'New Wave Of British Heavy Metal', - 'Post Metal', - 'Progressive Metal', - 'Avantgarde Metal', - 'Sludge', - 'Djent', - 'Drone', - 'Kawaii Metal', - 'Pirate Metal', - 'Nu Metal', - 'Neue Deutsche HƤrte', - 'Math Metal', - 'Crossover', - 'Grindcore', - 'Hardcore', - 'Metalcore', - 'Deathcore', - 'Post Hardcore', - 'Mathcore' - ], 'folk': [ - 'American Folk Revival', - 'Anti - Folk', - 'British Folk Revival', - 'Contemporary Folk', - 'Filk Music', - 'Freak Folk', - 'Indie Folk', - 'Industrial Folk', - 'Neofolk', - 'Progressive Folk', - 'Psychedelic Folk', - 'Sung Poetry', - 'Techno - Folk', - 'Folk Rock', - 'Old-time Music', - 'Bluegrass', - 'Appalachian', - 'Roots Revival', - 'Celtic', - 'Indie Folk' - ], 'pop': [ - 'Adult Contemporary', - 'Arab Pop', - 'Baroque', - 'Britpop', - 'Bubblegum Pop', - 'Chamber Pop', - 'Chanson', - 'Christian Pop', - 'Classical Crossover', - 'Europop', - 'Austropop', - 'Balkan Pop', - 'French Pop', - 'Korean Pop', - 'Japanese Pop', - 'Chinese Pop', - 'Latin Pop', - 'LaĆÆkó', - 'Nederpop', - 'Russian Pop', - 'Dance Pop', - 'Dream Pop', - 'Electro Pop', - 'Iranian Pop', - 'Jangle Pop', - 'Latin Ballad', - 'Levenslied', - 'Louisiana Swamp Pop', - 'Mexican Pop', - 'Motorpop', - 'New Romanticism', - 'Orchestral Pop', - 'Pop Rap', - 'Popera', - 'Pop / Rock', - 'Pop Punk', - 'Power Pop', - 'Psychedelic Pop', - 'Russian Pop', - 'Schlager', - 'Soft Rock', - 'Sophisti - Pop', - 'Space Age Pop', - 'Sunshine Pop', - 'Surf Pop', - 'Synthpop', - 'Teen Pop', - 'Traditional Pop Music', - 'Turkish Pop', - 'Vispop', - 'Wonky Pop' - ], 'r&b': [ - '(Carolina) Beach Music', - 'Contemporary R & B', - 'Disco', - 'Doo Wop', - 'Funk', - 'Modern Soul', - 'Motown', - 'Neo - Soul', - 'Northern Soul', - 'Psychedelic Soul', - 'Quiet Storm', - 'Soul', - 'Soul Blues', - 'Southern Soul' - ], 'reggae': [ - '2 - Tone', - 'Dub', - 'Roots Reggae', - 'Reggae Fusion', - 'Reggae en EspaƱol', - 'Spanish Reggae', - 'Reggae 110', - 'Reggae Bultrón', - 'Romantic Flow', - 'Lovers Rock', - 'Raggamuffin', - 'Ragga', - 'Dancehall', - 'Ska', - ], 'rock': [ - 'Acid Rock', - 'Adult - Oriented Rock', - 'Afro Punk', - 'Adult Alternative', - 'Alternative Rock', - 'American Traditional Rock', - 'Anatolian Rock', - 'Arena Rock', - 'Art Rock', - 'Blues - Rock', - 'British Invasion', - 'Cock Rock', - 'Death Metal / Black Metal', - 'Doom Metal', - 'Glam Rock', - 'Gothic Metal', - 'Grind Core', - 'Hair Metal', - 'Hard Rock', - 'Math Metal', - 'Math Rock', - 'Metal', - 'Metal Core', - 'Noise Rock', - 'Jam Bands', - 'Post Punk', - 'Post Rock', - 'Prog - Rock / Art Rock', - 'Progressive Metal', - 'Psychedelic', - 'Rock & Roll', - 'Rockabilly', - 'Roots Rock', - 'Singer / Songwriter', - 'Southern Rock', - 'Spazzcore', - 'Stoner Metal', - 'Surf', - 'Technical Death Metal', - 'Tex - Mex', - 'Thrash Metal', - 'Time Lord Rock(Trock)', - 'Trip - hop', - 'Yacht Rock', - 'School House Rock' - ], 'hip-hop': [ - 'Alternative Rap', - 'Avant - Garde', - 'Bounce', - 'Chap Hop', - 'Christian Hip Hop', - 'Conscious Hip Hop', - 'Country - Rap', - 'Grunk', - 'Crunkcore', - 'Cumbia Rap', - 'Dirty South', - 'East Coast', - 'Brick City Club', - 'Hardcore Hip Hop', - 'Mafioso Rap', - 'New Jersey Hip Hop', - 'Freestyle Rap', - 'G - Funk', - 'Gangsta Rap', - 'Golden Age', - 'Grime', - 'Hardcore Rap', - 'Hip - Hop', - 'Hip Pop', - 'Horrorcore', - 'Hyphy', - 'Industrial Hip Hop', - 'Instrumental Hip Hop', - 'Jazz Rap', - 'Latin Rap', - 'Low Bap', - 'Lyrical Hip Hop', - 'Merenrap', - 'Midwest Hip Hop', - 'Chicago Hip Hop', - 'Detroit Hip Hop', - 'Horrorcore', - 'St.Louis Hip Hop', - 'Twin Cities Hip Hop', - 'Motswako', - 'Nerdcore', - 'New Jack Swing', - 'New School Hip Hop', - 'Old School Rap', - 'Rap', - 'Trap', - 'Turntablism', - 'Underground Rap', - 'West Coast Rap', - 'East Coast Rap', - 'Trap', - 'UK Grime', - 'Hyphy', - 'Emo-rap', - 'Cloud rap', - 'G-funk', - 'Boom Bap', - 'Mumble', - 'Drill', - 'UK Drill', - 'Soundcloud Rap', - 'Lo-fi' - ], 'punk': [ - 'Afro-punk', - 'Anarcho punk', - 'Art punk', - 'Christian punk', - 'Crust punk', - 'Deathrock', - 'Egg punk', - 'Garage punk', - 'Glam punk', - 'Hardcore punk', - 'Horror punk', - 'Incelcore/e-punk', - 'Oi!', - 'Peace punk', - 'Punk pathetique', - 'Queercore', - 'Riot Grrrl', - 'Skate punk', - 'Street punk', - 'Taqwacore', - 'Trallpunk' - ], 'disco': [ - 'Nu-disco', - 'Disco-funk', - 'Hi-NRG', - 'Italo Disco', - 'Eurodisco', - 'Boogie', - 'Space Disco', - 'Post-disco', - 'Electro Disco', - 'Disco House', - 'Disco Pop', - 'Soulful House' - ], 'funk': [ - 'Funk Rock', - 'P-Funk (Parliament-Funkadelic)', - 'Psychedelic Funk', - 'Funk Metal', - 'Electro-Funk', - 'Go-go', - 'Boogie-Funk', - 'Jazz-Funk', - 'Soul-Funk', - 'Funky Disco', - 'Nu-Funk', - 'Afrobeat', - 'Latin Funk', - 'G-Funk', - 'Acid Jazz', - 'Funktronica', - 'Folk-Funk', - 'Space Funk', - 'Ambient Funk', - 'Hard Funk', - 'Fusion Funk' - ], 'techno': [ - 'Acid Techno', - 'Ambient Techno', - 'Detroit Techno', - 'Dub Techno', - 'Minimal Techno', - 'Industrial Techno', - 'Hard Techno', - 'Trance', - 'Progressive Techno', - 'Tech House', - 'Electronica', - 'Breakbeat Techno', - 'Electro Techno', - 'Melodic Techno', - 'Experimental Techno', - 'Dark Techno', - 'Ebm', - 'Hypnotic Techno', - 'Psychedelic Techno', - 'Rave Techno', - 'Techno-Pop' - ], 'indie': [ - 'Indie Rock', - 'Indie Pop', - 'Indie Folk', - 'Indie Electronic', - 'Indie Punk', - 'Indie Hip-Hop', - 'Dream Pop', - 'Shoegaze', - 'Lo-fi', - 'Chillwave', - 'Freak Folk', - 'Noise Pop', - 'Math Rock', - 'Post-Punk', - 'Garage Rock', - 'Experimental Indie', - 'Surf Rock', - 'Alternative Country', - 'Indie Soul', - 'Art Rock', - 'Indie R&B', - 'Indietronica', - 'Emo', - 'Post-Rock', - 'Indie Pop-Rock', - 'Indie Synthpop', - 'Noise Rock', - 'Psych Folk', - 'Indie Blues' - ], 'gospel': [ - 'Traditional Gospel', - 'Contemporary Gospel', - 'Southern Gospel', - 'Black Gospel', - 'Urban Contemporary Gospel', - 'Gospel Blues', - 'Bluegrass Gospel', - 'Country Gospel', - 'Praise and Worship', - 'Christian Hip-Hop', - 'Gospel Jazz', - 'Reggae Gospel', - 'African Gospel', - 'Latin Gospel', - 'R&B Gospel', - 'Gospel Choir', - 'Acappella Gospel', - 'Instrumental Gospel', - 'Gospel Rap' - ], 'world': [ - 'African', - 'Arabic', - 'Asian', - 'Caribbean', - 'Celtic', - 'European', - 'Latin American', - 'Middle Eastern', - 'Native American', - 'Polynesian', - 'Reggae', - 'Ska', - 'Salsa', - 'Flamenco', - 'Bossa Nova', - 'Tango', - 'Fado', - 'Klezmer', - 'Balkan', - 'Afrobeat', - 'Mongolian Throat Singing', - 'Indian Classical', - 'Gamelan', - 'Sufi Music', - 'Zydeco', - 'Kora Music', - 'Andean Music', - 'Irish Traditional', - 'Gypsy Jazz', - 'Bollywood', - 'Bhangra', - 'Jawaiian', - 'Hawaiian Slack Key Guitar', - 'Calypso', - 'Cuban Son', - 'Taiko Drumming', - 'African Highlife', - 'Merengue', - 'Tuvan Throat Singing' - ] - }, - - // Data sourced from https://unicode.org/emoji/charts/full-emoji-list.html - emojis: { - "smileys_and_emotion": [ - "0x1f600", - "0x1f603", - "0x1f604", - "0x1f601", - "0x1f606", - "0x1f605", - "0x1f923", - "0x1f602", - "0x1f642", - "0x1f643", - "0x1fae0", - "0x1f609", - "0x1f60a", - "0x1f607", - "0x1f970", - "0x1f60d", - "0x1f929", - "0x1f618", - "0x1f617", - "0x263a", - "0x1f61a", - "0x1f619", - "0x1f972", - "0x1f60b", - "0x1f61b", - "0x1f61c", - "0x1f92a", - "0x1f61d", - "0x1f911", - "0x1f917", - "0x1f92d", - "0x1fae2", - "0x1fae3", - "0x1f92b", - "0x1f914", - "0x1fae1", - "0x1f910", - "0x1f928", - "0x1f610", - "0x1f611", - "0x1f636", - "0x1fae5", - "0x1f636", - "0x200d", - "0x1f32b", - "0xfe0f", - "0x1f60f", - "0x1f612", - "0x1f644", - "0x1f62c", - "0x1f62e", - "0x200d", - "0x1f4a8", - "0x1f925", - "0x1fae8", - "0x1f642", - "0x200d", - "0x2194", - "0xfe0f", - "0x1f642", - "0x200d", - "0x2195", - "0xfe0f", - "0x1f60c", - "0x1f614", - "0x1f62a", - "0x1f924", - "0x1f634", - "0x1f637", - "0x1f912", - "0x1f915", - "0x1f922", - "0x1f92e", - "0x1f927", - "0x1f975", - "0x1f976", - "0x1f974", - "0x1f635", - "0x1f635", - "0x200d", - "0x1f4ab", - "0x1f92f", - "0x1f920", - "0x1f973", - "0x1f978", - "0x1f60e", - "0x1f913", - "0x1f9d0", - "0x1f615", - "0x1fae4", - "0x1f61f", - "0x1f641", - "0x2639", - "0x1f62e", - "0x1f62f", - "0x1f632", - "0x1f633", - "0x1f97a", - "0x1f979", - "0x1f626", - "0x1f627", - "0x1f628", - "0x1f630", - "0x1f625", - "0x1f622", - "0x1f62d", - "0x1f631", - "0x1f616", - "0x1f623", - "0x1f61e", - "0x1f613", - "0x1f629", - "0x1f62b", - "0x1f971", - "0x1f624", - "0x1f621", - "0x1f620", - "0x1f92c", - "0x1f608", - "0x1f47f", - "0x1f480", - "0x2620", - "0x1f4a9", - "0x1f921", - "0x1f479", - "0x1f47a", - "0x1f47b", - "0x1f47d", - "0x1f47e", - "0x1f916", - "0x1f63a", - "0x1f638", - "0x1f639", - "0x1f63b", - "0x1f63c", - "0x1f63d", - "0x1f640", - "0x1f63f", - "0x1f63e", - "0x1f648", - "0x1f649", - "0x1f64a", - "0x1f48c", - "0x1f498", - "0x1f49d", - "0x1f496", - "0x1f497", - "0x1f493", - "0x1f49e", - "0x1f495", - "0x1f49f", - "0x2763", - "0x1f494", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f525", - "0x2764", - "0xfe0f", - "0x200d", - "0x1fa79", - "0x2764", - "0x1fa77", - "0x1f9e1", - "0x1f49b", - "0x1f49a", - "0x1f499", - "0x1fa75", - "0x1f49c", - "0x1f90e", - "0x1f5a4", - "0x1fa76", - "0x1f90d", - "0x1f48b", - "0x1f4af", - "0x1f4a2", - "0x1f4a5", - "0x1f4ab", - "0x1f4a6", - "0x1f4a8", - "0x1f573", - "0x1f4ac", - "0x1f441", - "0xfe0f", - "0x200d", - "0x1f5e8", - "0xfe0f", - "0x1f5e8", - "0x1f5ef", - "0x1f4ad", - "0x1f4a4" - ], - "people_and_body": [ - "0x1f44b", - "0x1f91a", - "0x1f590", - "0x270b", - "0x1f596", - "0x1faf1", - "0x1faf2", - "0x1faf3", - "0x1faf4", - "0x1faf7", - "0x1faf8", - "0x1f44c", - "0x1f90c", - "0x1f90f", - "0x270c", - "0x1f91e", - "0x1faf0", - "0x1f91f", - "0x1f918", - "0x1f919", - "0x1f448", - "0x1f449", - "0x1f446", - "0x1f595", - "0x1f447", - "0x261d", - "0x1faf5", - "0x1f44d", - "0x1f44e", - "0x270a", - "0x1f44a", - "0x1f91b", - "0x1f91c", - "0x1f44f", - "0x1f64c", - "0x1faf6", - "0x1f450", - "0x1f932", - "0x1f91d", - "0x1f64f", - "0x270d", - "0x1f485", - "0x1f933", - "0x1f4aa", - "0x1f9be", - "0x1f9bf", - "0x1f9b5", - "0x1f9b6", - "0x1f442", - "0x1f9bb", - "0x1f443", - "0x1f9e0", - "0x1fac0", - "0x1fac1", - "0x1f9b7", - "0x1f9b4", - "0x1f440", - "0x1f441", - "0x1f445", - "0x1f444", - "0x1fae6", - "0x1f476", - "0x1f9d2", - "0x1f466", - "0x1f467", - "0x1f9d1", - "0x1f471", - "0x1f468", - "0x1f9d4", - "0x1f9d4", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d4", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9b0", - "0x1f468", - "0x200d", - "0x1f9b1", - "0x1f468", - "0x200d", - "0x1f9b3", - "0x1f468", - "0x200d", - "0x1f9b2", - "0x1f469", - "0x1f469", - "0x200d", - "0x1f9b0", - "0x1f9d1", - "0x200d", - "0x1f9b0", - "0x1f469", - "0x200d", - "0x1f9b1", - "0x1f9d1", - "0x200d", - "0x1f9b1", - "0x1f469", - "0x200d", - "0x1f9b3", - "0x1f9d1", - "0x200d", - "0x1f9b3", - "0x1f469", - "0x200d", - "0x1f9b2", - "0x1f9d1", - "0x200d", - "0x1f9b2", - "0x1f471", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f471", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d3", - "0x1f474", - "0x1f475", - "0x1f64d", - "0x1f64d", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f64d", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f64e", - "0x1f64e", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f64e", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f645", - "0x1f645", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f645", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f646", - "0x1f646", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f646", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f481", - "0x1f481", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f481", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f64b", - "0x1f64b", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f64b", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9cf", - "0x1f9cf", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9cf", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f647", - "0x1f647", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f647", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f926", - "0x1f926", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f926", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f937", - "0x1f937", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f937", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x2695", - "0xfe0f", - "0x1f468", - "0x200d", - "0x2695", - "0xfe0f", - "0x1f469", - "0x200d", - "0x2695", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f393", - "0x1f468", - "0x200d", - "0x1f393", - "0x1f469", - "0x200d", - "0x1f393", - "0x1f9d1", - "0x200d", - "0x1f3eb", - "0x1f468", - "0x200d", - "0x1f3eb", - "0x1f469", - "0x200d", - "0x1f3eb", - "0x1f9d1", - "0x200d", - "0x2696", - "0xfe0f", - "0x1f468", - "0x200d", - "0x2696", - "0xfe0f", - "0x1f469", - "0x200d", - "0x2696", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f33e", - "0x1f468", - "0x200d", - "0x1f33e", - "0x1f469", - "0x200d", - "0x1f33e", - "0x1f9d1", - "0x200d", - "0x1f373", - "0x1f468", - "0x200d", - "0x1f373", - "0x1f469", - "0x200d", - "0x1f373", - "0x1f9d1", - "0x200d", - "0x1f527", - "0x1f468", - "0x200d", - "0x1f527", - "0x1f469", - "0x200d", - "0x1f527", - "0x1f9d1", - "0x200d", - "0x1f3ed", - "0x1f468", - "0x200d", - "0x1f3ed", - "0x1f469", - "0x200d", - "0x1f3ed", - "0x1f9d1", - "0x200d", - "0x1f4bc", - "0x1f468", - "0x200d", - "0x1f4bc", - "0x1f469", - "0x200d", - "0x1f4bc", - "0x1f9d1", - "0x200d", - "0x1f52c", - "0x1f468", - "0x200d", - "0x1f52c", - "0x1f469", - "0x200d", - "0x1f52c", - "0x1f9d1", - "0x200d", - "0x1f4bb", - "0x1f468", - "0x200d", - "0x1f4bb", - "0x1f469", - "0x200d", - "0x1f4bb", - "0x1f9d1", - "0x200d", - "0x1f3a4", - "0x1f468", - "0x200d", - "0x1f3a4", - "0x1f469", - "0x200d", - "0x1f3a4", - "0x1f9d1", - "0x200d", - "0x1f3a8", - "0x1f468", - "0x200d", - "0x1f3a8", - "0x1f469", - "0x200d", - "0x1f3a8", - "0x1f9d1", - "0x200d", - "0x2708", - "0xfe0f", - "0x1f468", - "0x200d", - "0x2708", - "0xfe0f", - "0x1f469", - "0x200d", - "0x2708", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f680", - "0x1f468", - "0x200d", - "0x1f680", - "0x1f469", - "0x200d", - "0x1f680", - "0x1f9d1", - "0x200d", - "0x1f692", - "0x1f468", - "0x200d", - "0x1f692", - "0x1f469", - "0x200d", - "0x1f692", - "0x1f46e", - "0x1f46e", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f46e", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f575", - "0x1f575", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f575", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f482", - "0x1f482", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f482", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f977", - "0x1f477", - "0x1f477", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f477", - "0x200d", - "0x2640", - "0xfe0f", - "0x1fac5", - "0x1f934", - "0x1f478", - "0x1f473", - "0x1f473", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f473", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f472", - "0x1f9d5", - "0x1f935", - "0x1f935", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f935", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f470", - "0x1f470", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f470", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f930", - "0x1fac3", - "0x1fac4", - "0x1f931", - "0x1f469", - "0x200d", - "0x1f37c", - "0x1f468", - "0x200d", - "0x1f37c", - "0x1f9d1", - "0x200d", - "0x1f37c", - "0x1f47c", - "0x1f385", - "0x1f936", - "0x1f9d1", - "0x200d", - "0x1f384", - "0x1f9b8", - "0x1f9b8", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9b8", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9b9", - "0x1f9b9", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9b9", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d9", - "0x1f9d9", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d9", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9da", - "0x1f9da", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9da", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9db", - "0x1f9db", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9db", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9dc", - "0x1f9dc", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9dc", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9dd", - "0x1f9dd", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9dd", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9de", - "0x1f9de", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9de", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9df", - "0x1f9df", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9df", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9cc", - "0x1f486", - "0x1f486", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f486", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f487", - "0x1f487", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f487", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b6", - "0x1f6b6", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x2640", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x2642", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9cd", - "0x1f9cd", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9cd", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9ce", - "0x1f9ce", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x2640", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x2642", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f9af", - "0x1f9d1", - "0x200d", - "0x1f9af", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9af", - "0x1f468", - "0x200d", - "0x1f9af", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f469", - "0x200d", - "0x1f9af", - "0x1f469", - "0x200d", - "0x1f9af", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f9bc", - "0x1f9d1", - "0x200d", - "0x1f9bc", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9bc", - "0x1f468", - "0x200d", - "0x1f9bc", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f469", - "0x200d", - "0x1f9bc", - "0x1f469", - "0x200d", - "0x1f9bc", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f9bd", - "0x1f9d1", - "0x200d", - "0x1f9bd", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9bd", - "0x1f468", - "0x200d", - "0x1f9bd", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f469", - "0x200d", - "0x1f9bd", - "0x1f469", - "0x200d", - "0x1f9bd", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f3c3", - "0x1f3c3", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x2640", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x2642", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f483", - "0x1f57a", - "0x1f574", - "0x1f46f", - "0x1f46f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f46f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d6", - "0x1f9d6", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d6", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d7", - "0x1f9d7", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d7", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93a", - "0x1f3c7", - "0x26f7", - "0x1f3c2", - "0x1f3cc", - "0x1f3cc", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3cc", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3c4", - "0x1f3c4", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3c4", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6a3", - "0x1f6a3", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6a3", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3ca", - "0x1f3ca", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3ca", - "0x200d", - "0x2640", - "0xfe0f", - "0x26f9", - "0x26f9", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x26f9", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3cb", - "0x1f3cb", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3cb", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b4", - "0x1f6b4", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6b4", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b5", - "0x1f6b5", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6b5", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f938", - "0x1f938", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f938", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93c", - "0x1f93c", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f93c", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93d", - "0x1f93d", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f93d", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93e", - "0x1f93e", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f93e", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f939", - "0x1f939", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f939", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d8", - "0x1f9d8", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d8", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6c0", - "0x1f6cc", - "0x1f9d1", - "0x200d", - "0x1f91d", - "0x200d", - "0x1f9d1", - "0x1f46d", - "0x1f46b", - "0x1f46c", - "0x1f48f", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f48b", - "0x200d", - "0x1f468", - "0x1f468", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f48b", - "0x200d", - "0x1f468", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f48b", - "0x200d", - "0x1f469", - "0x1f491", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f468", - "0x1f468", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f468", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f469", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f5e3", - "0x1f464", - "0x1f465", - "0x1fac2", - "0x1f46a", - "0x1f9d1", - "0x200d", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x1f9d1", - "0x200d", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x200d", - "0x1f9d2", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x200d", - "0x1f9d2", - "0x1f463" - ], - "animals_and_nature": [ - "0x1f435", - "0x1f412", - "0x1f98d", - "0x1f9a7", - "0x1f436", - "0x1f415", - "0x1f9ae", - "0x1f415", - "0x200d", - "0x1f9ba", - "0x1f429", - "0x1f43a", - "0x1f98a", - "0x1f99d", - "0x1f431", - "0x1f408", - "0x1f408", - "0x200d", - "0x2b1b", - "0x1f981", - "0x1f42f", - "0x1f405", - "0x1f406", - "0x1f434", - "0x1face", - "0x1facf", - "0x1f40e", - "0x1f984", - "0x1f993", - "0x1f98c", - "0x1f9ac", - "0x1f42e", - "0x1f402", - "0x1f403", - "0x1f404", - "0x1f437", - "0x1f416", - "0x1f417", - "0x1f43d", - "0x1f40f", - "0x1f411", - "0x1f410", - "0x1f42a", - "0x1f42b", - "0x1f999", - "0x1f992", - "0x1f418", - "0x1f9a3", - "0x1f98f", - "0x1f99b", - "0x1f42d", - "0x1f401", - "0x1f400", - "0x1f439", - "0x1f430", - "0x1f407", - "0x1f43f", - "0x1f9ab", - "0x1f994", - "0x1f987", - "0x1f43b", - "0x1f43b", - "0x200d", - "0x2744", - "0xfe0f", - "0x1f428", - "0x1f43c", - "0x1f9a5", - "0x1f9a6", - "0x1f9a8", - "0x1f998", - "0x1f9a1", - "0x1f43e", - "0x1f983", - "0x1f414", - "0x1f413", - "0x1f423", - "0x1f424", - "0x1f425", - "0x1f426", - "0x1f427", - "0x1f54a", - "0x1f985", - "0x1f986", - "0x1f9a2", - "0x1f989", - "0x1f9a4", - "0x1fab6", - "0x1f9a9", - "0x1f99a", - "0x1f99c", - "0x1fabd", - "0x1f426", - "0x200d", - "0x2b1b", - "0x1fabf", - "0x1f426", - "0x200d", - "0x1f525", - "0x1f438", - "0x1f40a", - "0x1f422", - "0x1f98e", - "0x1f40d", - "0x1f432", - "0x1f409", - "0x1f995", - "0x1f996", - "0x1f433", - "0x1f40b", - "0x1f42c", - "0x1f9ad", - "0x1f41f", - "0x1f420", - "0x1f421", - "0x1f988", - "0x1f419", - "0x1f41a", - "0x1fab8", - "0x1fabc", - "0x1f40c", - "0x1f98b", - "0x1f41b", - "0x1f41c", - "0x1f41d", - "0x1fab2", - "0x1f41e", - "0x1f997", - "0x1fab3", - "0x1f577", - "0x1f578", - "0x1f982", - "0x1f99f", - "0x1fab0", - "0x1fab1", - "0x1f9a0", - "0x1f490", - "0x1f338", - "0x1f4ae", - "0x1fab7", - "0x1f3f5", - "0x1f339", - "0x1f940", - "0x1f33a", - "0x1f33b", - "0x1f33c", - "0x1f337", - "0x1fabb", - "0x1f331", - "0x1fab4", - "0x1f332", - "0x1f333", - "0x1f334", - "0x1f335", - "0x1f33e", - "0x1f33f", - "0x2618", - "0x1f340", - "0x1f341", - "0x1f342", - "0x1f343", - "0x1fab9", - "0x1faba", - "0x1f344" - ], - "food_and_drink": [ - "0x1f347", - "0x1f348", - "0x1f349", - "0x1f34a", - "0x1f34b", - "0x1f34b", - "0x200d", - "0x1f7e9", - "0x1f34c", - "0x1f34d", - "0x1f96d", - "0x1f34e", - "0x1f34f", - "0x1f350", - "0x1f351", - "0x1f352", - "0x1f353", - "0x1fad0", - "0x1f95d", - "0x1f345", - "0x1fad2", - "0x1f965", - "0x1f951", - "0x1f346", - "0x1f954", - "0x1f955", - "0x1f33d", - "0x1f336", - "0x1fad1", - "0x1f952", - "0x1f96c", - "0x1f966", - "0x1f9c4", - "0x1f9c5", - "0x1f95c", - "0x1fad8", - "0x1f330", - "0x1fada", - "0x1fadb", - "0x1f344", - "0x200d", - "0x1f7eb", - "0x1f35e", - "0x1f950", - "0x1f956", - "0x1fad3", - "0x1f968", - "0x1f96f", - "0x1f95e", - "0x1f9c7", - "0x1f9c0", - "0x1f356", - "0x1f357", - "0x1f969", - "0x1f953", - "0x1f354", - "0x1f35f", - "0x1f355", - "0x1f32d", - "0x1f96a", - "0x1f32e", - "0x1f32f", - "0x1fad4", - "0x1f959", - "0x1f9c6", - "0x1f95a", - "0x1f373", - "0x1f958", - "0x1f372", - "0x1fad5", - "0x1f963", - "0x1f957", - "0x1f37f", - "0x1f9c8", - "0x1f9c2", - "0x1f96b", - "0x1f371", - "0x1f358", - "0x1f359", - "0x1f35a", - "0x1f35b", - "0x1f35c", - "0x1f35d", - "0x1f360", - "0x1f362", - "0x1f363", - "0x1f364", - "0x1f365", - "0x1f96e", - "0x1f361", - "0x1f95f", - "0x1f960", - "0x1f961", - "0x1f980", - "0x1f99e", - "0x1f990", - "0x1f991", - "0x1f9aa", - "0x1f366", - "0x1f367", - "0x1f368", - "0x1f369", - "0x1f36a", - "0x1f382", - "0x1f370", - "0x1f9c1", - "0x1f967", - "0x1f36b", - "0x1f36c", - "0x1f36d", - "0x1f36e", - "0x1f36f", - "0x1f37c", - "0x1f95b", - "0x2615", - "0x1fad6", - "0x1f375", - "0x1f376", - "0x1f37e", - "0x1f377", - "0x1f378", - "0x1f379", - "0x1f37a", - "0x1f37b", - "0x1f942", - "0x1f943", - "0x1fad7", - "0x1f964", - "0x1f9cb", - "0x1f9c3", - "0x1f9c9", - "0x1f9ca", - "0x1f962", - "0x1f37d", - "0x1f374", - "0x1f944", - "0x1f52a", - "0x1fad9", - "0x1f3fa" - ], - "travel_and_places": [ - "0x1f30d", - "0x1f30e", - "0x1f30f", - "0x1f310", - "0x1f5fa", - "0x1f5fe", - "0x1f9ed", - "0x1f3d4", - "0x26f0", - "0x1f30b", - "0x1f5fb", - "0x1f3d5", - "0x1f3d6", - "0x1f3dc", - "0x1f3dd", - "0x1f3de", - "0x1f3df", - "0x1f3db", - "0x1f3d7", - "0x1f9f1", - "0x1faa8", - "0x1fab5", - "0x1f6d6", - "0x1f3d8", - "0x1f3da", - "0x1f3e0", - "0x1f3e1", - "0x1f3e2", - "0x1f3e3", - "0x1f3e4", - "0x1f3e5", - "0x1f3e6", - "0x1f3e8", - "0x1f3e9", - "0x1f3ea", - "0x1f3eb", - "0x1f3ec", - "0x1f3ed", - "0x1f3ef", - "0x1f3f0", - "0x1f492", - "0x1f5fc", - "0x1f5fd", - "0x26ea", - "0x1f54c", - "0x1f6d5", - "0x1f54d", - "0x26e9", - "0x1f54b", - "0x26f2", - "0x26fa", - "0x1f301", - "0x1f303", - "0x1f3d9", - "0x1f304", - "0x1f305", - "0x1f306", - "0x1f307", - "0x1f309", - "0x2668", - "0x1f3a0", - "0x1f6dd", - "0x1f3a1", - "0x1f3a2", - "0x1f488", - "0x1f3aa", - "0x1f682", - "0x1f683", - "0x1f684", - "0x1f685", - "0x1f686", - "0x1f687", - "0x1f688", - "0x1f689", - "0x1f68a", - "0x1f69d", - "0x1f69e", - "0x1f68b", - "0x1f68c", - "0x1f68d", - "0x1f68e", - "0x1f690", - "0x1f691", - "0x1f692", - "0x1f693", - "0x1f694", - "0x1f695", - "0x1f696", - "0x1f697", - "0x1f698", - "0x1f699", - "0x1f6fb", - "0x1f69a", - "0x1f69b", - "0x1f69c", - "0x1f3ce", - "0x1f3cd", - "0x1f6f5", - "0x1f9bd", - "0x1f9bc", - "0x1f6fa", - "0x1f6b2", - "0x1f6f4", - "0x1f6f9", - "0x1f6fc", - "0x1f68f", - "0x1f6e3", - "0x1f6e4", - "0x1f6e2", - "0x26fd", - "0x1f6de", - "0x1f6a8", - "0x1f6a5", - "0x1f6a6", - "0x1f6d1", - "0x1f6a7", - "0x2693", - "0x1f6df", - "0x26f5", - "0x1f6f6", - "0x1f6a4", - "0x1f6f3", - "0x26f4", - "0x1f6e5", - "0x1f6a2", - "0x2708", - "0x1f6e9", - "0x1f6eb", - "0x1f6ec", - "0x1fa82", - "0x1f4ba", - "0x1f681", - "0x1f69f", - "0x1f6a0", - "0x1f6a1", - "0x1f6f0", - "0x1f680", - "0x1f6f8", - "0x1f6ce", - "0x1f9f3", - "0x231b", - "0x23f3", - "0x231a", - "0x23f0", - "0x23f1", - "0x23f2", - "0x1f570", - "0x1f55b", - "0x1f567", - "0x1f550", - "0x1f55c", - "0x1f551", - "0x1f55d", - "0x1f552", - "0x1f55e", - "0x1f553", - "0x1f55f", - "0x1f554", - "0x1f560", - "0x1f555", - "0x1f561", - "0x1f556", - "0x1f562", - "0x1f557", - "0x1f563", - "0x1f558", - "0x1f564", - "0x1f559", - "0x1f565", - "0x1f55a", - "0x1f566", - "0x1f311", - "0x1f312", - "0x1f313", - "0x1f314", - "0x1f315", - "0x1f316", - "0x1f317", - "0x1f318", - "0x1f319", - "0x1f31a", - "0x1f31b", - "0x1f31c", - "0x1f321", - "0x2600", - "0x1f31d", - "0x1f31e", - "0x1fa90", - "0x2b50", - "0x1f31f", - "0x1f320", - "0x1f30c", - "0x2601", - "0x26c5", - "0x26c8", - "0x1f324", - "0x1f325", - "0x1f326", - "0x1f327", - "0x1f328", - "0x1f329", - "0x1f32a", - "0x1f32b", - "0x1f32c", - "0x1f300", - "0x1f308", - "0x1f302", - "0x2602", - "0x2614", - "0x26f1", - "0x26a1", - "0x2744", - "0x2603", - "0x26c4", - "0x2604", - "0x1f525", - "0x1f4a7", - "0x1f30a" - ], - "activities": [ - "0x1f383", - "0x1f384", - "0x1f386", - "0x1f387", - "0x1f9e8", - "0x2728", - "0x1f388", - "0x1f389", - "0x1f38a", - "0x1f38b", - "0x1f38d", - "0x1f38e", - "0x1f38f", - "0x1f390", - "0x1f391", - "0x1f9e7", - "0x1f380", - "0x1f381", - "0x1f397", - "0x1f39f", - "0x1f3ab", - "0x1f396", - "0x1f3c6", - "0x1f3c5", - "0x1f947", - "0x1f948", - "0x1f949", - "0x26bd", - "0x26be", - "0x1f94e", - "0x1f3c0", - "0x1f3d0", - "0x1f3c8", - "0x1f3c9", - "0x1f3be", - "0x1f94f", - "0x1f3b3", - "0x1f3cf", - "0x1f3d1", - "0x1f3d2", - "0x1f94d", - "0x1f3d3", - "0x1f3f8", - "0x1f94a", - "0x1f94b", - "0x1f945", - "0x26f3", - "0x26f8", - "0x1f3a3", - "0x1f93f", - "0x1f3bd", - "0x1f3bf", - "0x1f6f7", - "0x1f94c", - "0x1f3af", - "0x1fa80", - "0x1fa81", - "0x1f52b", - "0x1f3b1", - "0x1f52e", - "0x1fa84", - "0x1f3ae", - "0x1f579", - "0x1f3b0", - "0x1f3b2", - "0x1f9e9", - "0x1f9f8", - "0x1fa85", - "0x1faa9", - "0x1fa86", - "0x2660", - "0x2665", - "0x2666", - "0x2663", - "0x265f", - "0x1f0cf", - "0x1f004", - "0x1f3b4", - "0x1f3ad", - "0x1f5bc", - "0x1f3a8", - "0x1f9f5", - "0x1faa1", - "0x1f9f6", - "0x1faa2" - ], - "objects": [ - "0x1f453", - "0x1f576", - "0x1f97d", - "0x1f97c", - "0x1f9ba", - "0x1f454", - "0x1f455", - "0x1f456", - "0x1f9e3", - "0x1f9e4", - "0x1f9e5", - "0x1f9e6", - "0x1f457", - "0x1f458", - "0x1f97b", - "0x1fa71", - "0x1fa72", - "0x1fa73", - "0x1f459", - "0x1f45a", - "0x1faad", - "0x1f45b", - "0x1f45c", - "0x1f45d", - "0x1f6cd", - "0x1f392", - "0x1fa74", - "0x1f45e", - "0x1f45f", - "0x1f97e", - "0x1f97f", - "0x1f460", - "0x1f461", - "0x1fa70", - "0x1f462", - "0x1faae", - "0x1f451", - "0x1f452", - "0x1f3a9", - "0x1f393", - "0x1f9e2", - "0x1fa96", - "0x26d1", - "0x1f4ff", - "0x1f484", - "0x1f48d", - "0x1f48e", - "0x1f507", - "0x1f508", - "0x1f509", - "0x1f50a", - "0x1f4e2", - "0x1f4e3", - "0x1f4ef", - "0x1f514", - "0x1f515", - "0x1f3bc", - "0x1f3b5", - "0x1f3b6", - "0x1f399", - "0x1f39a", - "0x1f39b", - "0x1f3a4", - "0x1f3a7", - "0x1f4fb", - "0x1f3b7", - "0x1fa97", - "0x1f3b8", - "0x1f3b9", - "0x1f3ba", - "0x1f3bb", - "0x1fa95", - "0x1f941", - "0x1fa98", - "0x1fa87", - "0x1fa88", - "0x1f4f1", - "0x1f4f2", - "0x260e", - "0x1f4de", - "0x1f4df", - "0x1f4e0", - "0x1f50b", - "0x1faab", - "0x1f50c", - "0x1f4bb", - "0x1f5a5", - "0x1f5a8", - "0x2328", - "0x1f5b1", - "0x1f5b2", - "0x1f4bd", - "0x1f4be", - "0x1f4bf", - "0x1f4c0", - "0x1f9ee", - "0x1f3a5", - "0x1f39e", - "0x1f4fd", - "0x1f3ac", - "0x1f4fa", - "0x1f4f7", - "0x1f4f8", - "0x1f4f9", - "0x1f4fc", - "0x1f50d", - "0x1f50e", - "0x1f56f", - "0x1f4a1", - "0x1f526", - "0x1f3ee", - "0x1fa94", - "0x1f4d4", - "0x1f4d5", - "0x1f4d6", - "0x1f4d7", - "0x1f4d8", - "0x1f4d9", - "0x1f4da", - "0x1f4d3", - "0x1f4d2", - "0x1f4c3", - "0x1f4dc", - "0x1f4c4", - "0x1f4f0", - "0x1f5de", - "0x1f4d1", - "0x1f516", - "0x1f3f7", - "0x1f4b0", - "0x1fa99", - "0x1f4b4", - "0x1f4b5", - "0x1f4b6", - "0x1f4b7", - "0x1f4b8", - "0x1f4b3", - "0x1f9fe", - "0x1f4b9", - "0x2709", - "0x1f4e7", - "0x1f4e8", - "0x1f4e9", - "0x1f4e4", - "0x1f4e5", - "0x1f4e6", - "0x1f4eb", - "0x1f4ea", - "0x1f4ec", - "0x1f4ed", - "0x1f4ee", - "0x1f5f3", - "0x270f", - "0x2712", - "0x1f58b", - "0x1f58a", - "0x1f58c", - "0x1f58d", - "0x1f4dd", - "0x1f4bc", - "0x1f4c1", - "0x1f4c2", - "0x1f5c2", - "0x1f4c5", - "0x1f4c6", - "0x1f5d2", - "0x1f5d3", - "0x1f4c7", - "0x1f4c8", - "0x1f4c9", - "0x1f4ca", - "0x1f4cb", - "0x1f4cc", - "0x1f4cd", - "0x1f4ce", - "0x1f587", - "0x1f4cf", - "0x1f4d0", - "0x2702", - "0x1f5c3", - "0x1f5c4", - "0x1f5d1", - "0x1f512", - "0x1f513", - "0x1f50f", - "0x1f510", - "0x1f511", - "0x1f5dd", - "0x1f528", - "0x1fa93", - "0x26cf", - "0x2692", - "0x1f6e0", - "0x1f5e1", - "0x2694", - "0x1f4a3", - "0x1fa83", - "0x1f3f9", - "0x1f6e1", - "0x1fa9a", - "0x1f527", - "0x1fa9b", - "0x1f529", - "0x2699", - "0x1f5dc", - "0x2696", - "0x1f9af", - "0x1f517", - "0x26d3", - "0xfe0f", - "0x200d", - "0x1f4a5", - "0x26d3", - "0x1fa9d", - "0x1f9f0", - "0x1f9f2", - "0x1fa9c", - "0x2697", - "0x1f9ea", - "0x1f9eb", - "0x1f9ec", - "0x1f52c", - "0x1f52d", - "0x1f4e1", - "0x1f489", - "0x1fa78", - "0x1f48a", - "0x1fa79", - "0x1fa7c", - "0x1fa7a", - "0x1fa7b", - "0x1f6aa", - "0x1f6d7", - "0x1fa9e", - "0x1fa9f", - "0x1f6cf", - "0x1f6cb", - "0x1fa91", - "0x1f6bd", - "0x1faa0", - "0x1f6bf", - "0x1f6c1", - "0x1faa4", - "0x1fa92", - "0x1f9f4", - "0x1f9f7", - "0x1f9f9", - "0x1f9fa", - "0x1f9fb", - "0x1faa3", - "0x1f9fc", - "0x1fae7", - "0x1faa5", - "0x1f9fd", - "0x1f9ef", - "0x1f6d2", - "0x1f6ac", - "0x26b0", - "0x1faa6", - "0x26b1", - "0x1f9ff", - "0x1faac", - "0x1f5ff", - "0x1faa7", - "0x1faaa" - ], - "symbols": [ - "0x1f3e7", - "0x1f6ae", - "0x1f6b0", - "0x267f", - "0x1f6b9", - "0x1f6ba", - "0x1f6bb", - "0x1f6bc", - "0x1f6be", - "0x1f6c2", - "0x1f6c3", - "0x1f6c4", - "0x1f6c5", - "0x26a0", - "0x1f6b8", - "0x26d4", - "0x1f6ab", - "0x1f6b3", - "0x1f6ad", - "0x1f6af", - "0x1f6b1", - "0x1f6b7", - "0x1f4f5", - "0x1f51e", - "0x2622", - "0x2623", - "0x2b06", - "0x2197", - "0x27a1", - "0x2198", - "0x2b07", - "0x2199", - "0x2b05", - "0x2196", - "0x2195", - "0x2194", - "0x21a9", - "0x21aa", - "0x2934", - "0x2935", - "0x1f503", - "0x1f504", - "0x1f519", - "0x1f51a", - "0x1f51b", - "0x1f51c", - "0x1f51d", - "0x1f6d0", - "0x269b", - "0x1f549", - "0x2721", - "0x2638", - "0x262f", - "0x271d", - "0x2626", - "0x262a", - "0x262e", - "0x1f54e", - "0x1f52f", - "0x1faaf", - "0x2648", - "0x2649", - "0x264a", - "0x264b", - "0x264c", - "0x264d", - "0x264e", - "0x264f", - "0x2650", - "0x2651", - "0x2652", - "0x2653", - "0x26ce", - "0x1f500", - "0x1f501", - "0x1f502", - "0x25b6", - "0x23e9", - "0x23ed", - "0x23ef", - "0x25c0", - "0x23ea", - "0x23ee", - "0x1f53c", - "0x23eb", - "0x1f53d", - "0x23ec", - "0x23f8", - "0x23f9", - "0x23fa", - "0x23cf", - "0x1f3a6", - "0x1f505", - "0x1f506", - "0x1f4f6", - "0x1f6dc", - "0x1f4f3", - "0x1f4f4", - "0x2640", - "0x2642", - "0x26a7", - "0x2716", - "0x2795", - "0x2796", - "0x2797", - "0x1f7f0", - "0x267e", - "0x203c", - "0x2049", - "0x2753", - "0x2754", - "0x2755", - "0x2757", - "0x3030", - "0x1f4b1", - "0x1f4b2", - "0x2695", - "0x267b", - "0x269c", - "0x1f531", - "0x1f4db", - "0x1f530", - "0x2b55", - "0x2705", - "0x2611", - "0x2714", - "0x274c", - "0x274e", - "0x27b0", - "0x27bf", - "0x303d", - "0x2733", - "0x2734", - "0x2747", - "0x00a9", - "0x00ae", - "0x2122", - "0x0023", - "0xfe0f", - "0x20e3", - "0x002a", - "0xfe0f", - "0x20e3", - "0x0030", - "0xfe0f", - "0x20e3", - "0x0031", - "0xfe0f", - "0x20e3", - "0x0032", - "0xfe0f", - "0x20e3", - "0x0033", - "0xfe0f", - "0x20e3", - "0x0034", - "0xfe0f", - "0x20e3", - "0x0035", - "0xfe0f", - "0x20e3", - "0x0036", - "0xfe0f", - "0x20e3", - "0x0037", - "0xfe0f", - "0x20e3", - "0x0038", - "0xfe0f", - "0x20e3", - "0x0039", - "0xfe0f", - "0x20e3", - "0x1f51f", - "0x1f520", - "0x1f521", - "0x1f522", - "0x1f523", - "0x1f524", - "0x1f170", - "0x1f18e", - "0x1f171", - "0x1f191", - "0x1f192", - "0x1f193", - "0x2139", - "0x1f194", - "0x24c2", - "0x1f195", - "0x1f196", - "0x1f17e", - "0x1f197", - "0x1f17f", - "0x1f198", - "0x1f199", - "0x1f19a", - "0x1f201", - "0x1f202", - "0x1f237", - "0x1f236", - "0x1f22f", - "0x1f250", - "0x1f239", - "0x1f21a", - "0x1f232", - "0x1f251", - "0x1f238", - "0x1f234", - "0x1f233", - "0x3297", - "0x3299", - "0x1f23a", - "0x1f235", - "0x1f534", - "0x1f7e0", - "0x1f7e1", - "0x1f7e2", - "0x1f535", - "0x1f7e3", - "0x1f7e4", - "0x26ab", - "0x26aa", - "0x1f7e5", - "0x1f7e7", - "0x1f7e8", - "0x1f7e9", - "0x1f7e6", - "0x1f7ea", - "0x1f7eb", - "0x2b1b", - "0x2b1c", - "0x25fc", - "0x25fb", - "0x25fe", - "0x25fd", - "0x25aa", - "0x25ab", - "0x1f536", - "0x1f537", - "0x1f538", - "0x1f539", - "0x1f53a", - "0x1f53b", - "0x1f4a0", - "0x1f518", - "0x1f533", - "0x1f532" - ], - "flags": [ - "0x1f3c1", - "0x1f6a9", - "0x1f38c", - "0x1f3f4", - "0x1f3f3", - "0x1f3f3", - "0xfe0f", - "0x200d", - "0x1f308", - "0x1f3f3", - "0xfe0f", - "0x200d", - "0x26a7", - "0xfe0f", - "0x1f3f4", - "0x200d", - "0x2620", - "0xfe0f", - "0x1f1e6", - "0x1f1e8", - "0x1f1e6", - "0x1f1e9", - "0x1f1e6", - "0x1f1ea", - "0x1f1e6", - "0x1f1eb", - "0x1f1e6", - "0x1f1ec", - "0x1f1e6", - "0x1f1ee", - "0x1f1e6", - "0x1f1f1", - "0x1f1e6", - "0x1f1f2", - "0x1f1e6", - "0x1f1f4", - "0x1f1e6", - "0x1f1f6", - "0x1f1e6", - "0x1f1f7", - "0x1f1e6", - "0x1f1f8", - "0x1f1e6", - "0x1f1f9", - "0x1f1e6", - "0x1f1fa", - "0x1f1e6", - "0x1f1fc", - "0x1f1e6", - "0x1f1fd", - "0x1f1e6", - "0x1f1ff", - "0x1f1e7", - "0x1f1e6", - "0x1f1e7", - "0x1f1e7", - "0x1f1e7", - "0x1f1e9", - "0x1f1e7", - "0x1f1ea", - "0x1f1e7", - "0x1f1eb", - "0x1f1e7", - "0x1f1ec", - "0x1f1e7", - "0x1f1ed", - "0x1f1e7", - "0x1f1ee", - "0x1f1e7", - "0x1f1ef", - "0x1f1e7", - "0x1f1f1", - "0x1f1e7", - "0x1f1f2", - "0x1f1e7", - "0x1f1f3", - "0x1f1e7", - "0x1f1f4", - "0x1f1e7", - "0x1f1f6", - "0x1f1e7", - "0x1f1f7", - "0x1f1e7", - "0x1f1f8", - "0x1f1e7", - "0x1f1f9", - "0x1f1e7", - "0x1f1fb", - "0x1f1e7", - "0x1f1fc", - "0x1f1e7", - "0x1f1fe", - "0x1f1e7", - "0x1f1ff", - "0x1f1e8", - "0x1f1e6", - "0x1f1e8", - "0x1f1e8", - "0x1f1e8", - "0x1f1e9", - "0x1f1e8", - "0x1f1eb", - "0x1f1e8", - "0x1f1ec", - "0x1f1e8", - "0x1f1ed", - "0x1f1e8", - "0x1f1ee", - "0x1f1e8", - "0x1f1f0", - "0x1f1e8", - "0x1f1f1", - "0x1f1e8", - "0x1f1f2", - "0x1f1e8", - "0x1f1f3", - "0x1f1e8", - "0x1f1f4", - "0x1f1e8", - "0x1f1f5", - "0x1f1e8", - "0x1f1f7", - "0x1f1e8", - "0x1f1fa", - "0x1f1e8", - "0x1f1fb", - "0x1f1e8", - "0x1f1fc", - "0x1f1e8", - "0x1f1fd", - "0x1f1e8", - "0x1f1fe", - "0x1f1e8", - "0x1f1ff", - "0x1f1e9", - "0x1f1ea", - "0x1f1e9", - "0x1f1ec", - "0x1f1e9", - "0x1f1ef", - "0x1f1e9", - "0x1f1f0", - "0x1f1e9", - "0x1f1f2", - "0x1f1e9", - "0x1f1f4", - "0x1f1e9", - "0x1f1ff", - "0x1f1ea", - "0x1f1e6", - "0x1f1ea", - "0x1f1e8", - "0x1f1ea", - "0x1f1ea", - "0x1f1ea", - "0x1f1ec", - "0x1f1ea", - "0x1f1ed", - "0x1f1ea", - "0x1f1f7", - "0x1f1ea", - "0x1f1f8", - "0x1f1ea", - "0x1f1f9", - "0x1f1ea", - "0x1f1fa", - "0x1f1eb", - "0x1f1ee", - "0x1f1eb", - "0x1f1ef", - "0x1f1eb", - "0x1f1f0", - "0x1f1eb", - "0x1f1f2", - "0x1f1eb", - "0x1f1f4", - "0x1f1eb", - "0x1f1f7", - "0x1f1ec", - "0x1f1e6", - "0x1f1ec", - "0x1f1e7", - "0x1f1ec", - "0x1f1e9", - "0x1f1ec", - "0x1f1ea", - "0x1f1ec", - "0x1f1eb", - "0x1f1ec", - "0x1f1ec", - "0x1f1ec", - "0x1f1ed", - "0x1f1ec", - "0x1f1ee", - "0x1f1ec", - "0x1f1f1", - "0x1f1ec", - "0x1f1f2", - "0x1f1ec", - "0x1f1f3", - "0x1f1ec", - "0x1f1f5", - "0x1f1ec", - "0x1f1f6", - "0x1f1ec", - "0x1f1f7", - "0x1f1ec", - "0x1f1f8", - "0x1f1ec", - "0x1f1f9", - "0x1f1ec", - "0x1f1fa", - "0x1f1ec", - "0x1f1fc", - "0x1f1ec", - "0x1f1fe", - "0x1f1ed", - "0x1f1f0", - "0x1f1ed", - "0x1f1f2", - "0x1f1ed", - "0x1f1f3", - "0x1f1ed", - "0x1f1f7", - "0x1f1ed", - "0x1f1f9", - "0x1f1ed", - "0x1f1fa", - "0x1f1ee", - "0x1f1e8", - "0x1f1ee", - "0x1f1e9", - "0x1f1ee", - "0x1f1ea", - "0x1f1ee", - "0x1f1f1", - "0x1f1ee", - "0x1f1f2", - "0x1f1ee", - "0x1f1f3", - "0x1f1ee", - "0x1f1f4", - "0x1f1ee", - "0x1f1f6", - "0x1f1ee", - "0x1f1f7", - "0x1f1ee", - "0x1f1f8", - "0x1f1ee", - "0x1f1f9", - "0x1f1ef", - "0x1f1ea", - "0x1f1ef", - "0x1f1f2", - "0x1f1ef", - "0x1f1f4", - "0x1f1ef", - "0x1f1f5", - "0x1f1f0", - "0x1f1ea", - "0x1f1f0", - "0x1f1ec", - "0x1f1f0", - "0x1f1ed", - "0x1f1f0", - "0x1f1ee", - "0x1f1f0", - "0x1f1f2", - "0x1f1f0", - "0x1f1f3", - "0x1f1f0", - "0x1f1f5", - "0x1f1f0", - "0x1f1f7", - "0x1f1f0", - "0x1f1fc", - "0x1f1f0", - "0x1f1fe", - "0x1f1f0", - "0x1f1ff", - "0x1f1f1", - "0x1f1e6", - "0x1f1f1", - "0x1f1e7", - "0x1f1f1", - "0x1f1e8", - "0x1f1f1", - "0x1f1ee", - "0x1f1f1", - "0x1f1f0", - "0x1f1f1", - "0x1f1f7", - "0x1f1f1", - "0x1f1f8", - "0x1f1f1", - "0x1f1f9", - "0x1f1f1", - "0x1f1fa", - "0x1f1f1", - "0x1f1fb", - "0x1f1f1", - "0x1f1fe", - "0x1f1f2", - "0x1f1e6", - "0x1f1f2", - "0x1f1e8", - "0x1f1f2", - "0x1f1e9", - "0x1f1f2", - "0x1f1ea", - "0x1f1f2", - "0x1f1eb", - "0x1f1f2", - "0x1f1ec", - "0x1f1f2", - "0x1f1ed", - "0x1f1f2", - "0x1f1f0", - "0x1f1f2", - "0x1f1f1", - "0x1f1f2", - "0x1f1f2", - "0x1f1f2", - "0x1f1f3", - "0x1f1f2", - "0x1f1f4", - "0x1f1f2", - "0x1f1f5", - "0x1f1f2", - "0x1f1f6", - "0x1f1f2", - "0x1f1f7", - "0x1f1f2", - "0x1f1f8", - "0x1f1f2", - "0x1f1f9", - "0x1f1f2", - "0x1f1fa", - "0x1f1f2", - "0x1f1fb", - "0x1f1f2", - "0x1f1fc", - "0x1f1f2", - "0x1f1fd", - "0x1f1f2", - "0x1f1fe", - "0x1f1f2", - "0x1f1ff", - "0x1f1f3", - "0x1f1e6", - "0x1f1f3", - "0x1f1e8", - "0x1f1f3", - "0x1f1ea", - "0x1f1f3", - "0x1f1eb", - "0x1f1f3", - "0x1f1ec", - "0x1f1f3", - "0x1f1ee", - "0x1f1f3", - "0x1f1f1", - "0x1f1f3", - "0x1f1f4", - "0x1f1f3", - "0x1f1f5", - "0x1f1f3", - "0x1f1f7", - "0x1f1f3", - "0x1f1fa", - "0x1f1f3", - "0x1f1ff", - "0x1f1f4", - "0x1f1f2", - "0x1f1f5", - "0x1f1e6", - "0x1f1f5", - "0x1f1ea", - "0x1f1f5", - "0x1f1eb", - "0x1f1f5", - "0x1f1ec", - "0x1f1f5", - "0x1f1ed", - "0x1f1f5", - "0x1f1f0", - "0x1f1f5", - "0x1f1f1", - "0x1f1f5", - "0x1f1f2", - "0x1f1f5", - "0x1f1f3", - "0x1f1f5", - "0x1f1f7", - "0x1f1f5", - "0x1f1f8", - "0x1f1f5", - "0x1f1f9", - "0x1f1f5", - "0x1f1fc", - "0x1f1f5", - "0x1f1fe", - "0x1f1f6", - "0x1f1e6", - "0x1f1f7", - "0x1f1ea", - "0x1f1f7", - "0x1f1f4", - "0x1f1f7", - "0x1f1f8", - "0x1f1f7", - "0x1f1fa", - "0x1f1f7", - "0x1f1fc", - "0x1f1f8", - "0x1f1e6", - "0x1f1f8", - "0x1f1e7", - "0x1f1f8", - "0x1f1e8", - "0x1f1f8", - "0x1f1e9", - "0x1f1f8", - "0x1f1ea", - "0x1f1f8", - "0x1f1ec", - "0x1f1f8", - "0x1f1ed", - "0x1f1f8", - "0x1f1ee", - "0x1f1f8", - "0x1f1ef", - "0x1f1f8", - "0x1f1f0", - "0x1f1f8", - "0x1f1f1", - "0x1f1f8", - "0x1f1f2", - "0x1f1f8", - "0x1f1f3", - "0x1f1f8", - "0x1f1f4", - "0x1f1f8", - "0x1f1f7", - "0x1f1f8", - "0x1f1f8", - "0x1f1f8", - "0x1f1f9", - "0x1f1f8", - "0x1f1fb", - "0x1f1f8", - "0x1f1fd", - "0x1f1f8", - "0x1f1fe", - "0x1f1f8", - "0x1f1ff", - "0x1f1f9", - "0x1f1e6", - "0x1f1f9", - "0x1f1e8", - "0x1f1f9", - "0x1f1e9", - "0x1f1f9", - "0x1f1eb", - "0x1f1f9", - "0x1f1ec", - "0x1f1f9", - "0x1f1ed", - "0x1f1f9", - "0x1f1ef", - "0x1f1f9", - "0x1f1f0", - "0x1f1f9", - "0x1f1f1", - "0x1f1f9", - "0x1f1f2", - "0x1f1f9", - "0x1f1f3", - "0x1f1f9", - "0x1f1f4", - "0x1f1f9", - "0x1f1f7", - "0x1f1f9", - "0x1f1f9", - "0x1f1f9", - "0x1f1fb", - "0x1f1f9", - "0x1f1fc", - "0x1f1f9", - "0x1f1ff", - "0x1f1fa", - "0x1f1e6", - "0x1f1fa", - "0x1f1ec", - "0x1f1fa", - "0x1f1f2", - "0x1f1fa", - "0x1f1f3", - "0x1f1fa", - "0x1f1f8", - "0x1f1fa", - "0x1f1fe", - "0x1f1fa", - "0x1f1ff", - "0x1f1fb", - "0x1f1e6", - "0x1f1fb", - "0x1f1e8", - "0x1f1fb", - "0x1f1ea", - "0x1f1fb", - "0x1f1ec", - "0x1f1fb", - "0x1f1ee", - "0x1f1fb", - "0x1f1f3", - "0x1f1fb", - "0x1f1fa", - "0x1f1fc", - "0x1f1eb", - "0x1f1fc", - "0x1f1f8", - "0x1f1fd", - "0x1f1f0", - "0x1f1fe", - "0x1f1ea", - "0x1f1fe", - "0x1f1f9", - "0x1f1ff", - "0x1f1e6", - "0x1f1ff", - "0x1f1f2", - "0x1f1ff", - "0x1f1fc", - "0x1f3f4", - "0xe0067", - "0xe0062", - "0xe0065", - "0xe006e", - "0xe0067", - "0xe007f", - "0x1f3f4", - "0xe0067", - "0xe0062", - "0xe0073", - "0xe0063", - "0xe0074", - "0xe007f", - "0x1f3f4", - "0xe0067", - "0xe0062", - "0xe0077", - "0xe006c", - "0xe0073", - "0xe007f" - ] - } - }; - - var o_hasOwnProperty = Object.prototype.hasOwnProperty; - var o_keys = (Object.keys || function(obj) { - var result = []; - for (var key in obj) { - if (o_hasOwnProperty.call(obj, key)) { - result.push(key); - } - } - - return result; - }); - - - function _copyObject(source, target) { - var keys = o_keys(source); - var key; - - for (var i = 0, l = keys.length; i < l; i++) { - key = keys[i]; - target[key] = source[key] || target[key]; - } - } - - function _copyArray(source, target) { - for (var i = 0, l = source.length; i < l; i++) { - target[i] = source[i]; - } - } - - function copyObject(source, _target) { - var isArray = Array.isArray(source); - var target = _target || (isArray ? new Array(source.length) : {}); - - if (isArray) { - _copyArray(source, target); - } else { - _copyObject(source, target); - } - - return target; - } - - /** Get the data based on key**/ - Chance.prototype.get = function (name) { - return copyObject(data[name]); - }; - - // Mac Address - Chance.prototype.mac_address = function(options){ - // typically mac addresses are separated by ":" - // however they can also be separated by "-" - // the network variant uses a dot every fourth byte - - options = initOptions(options); - if(!options.separator) { - options.separator = options.networkVersion ? "." : ":"; - } - - var mac_pool="ABCDEF1234567890", - mac = ""; - if(!options.networkVersion) { - mac = this.n(this.string, 6, { pool: mac_pool, length:2 }).join(options.separator); - } else { - mac = this.n(this.string, 3, { pool: mac_pool, length:4 }).join(options.separator); - } - - return mac; - }; - - Chance.prototype.normal = function (options) { - options = initOptions(options, {mean : 0, dev : 1, pool : []}); - - testRange( - options.pool.constructor !== Array, - "Chance: The pool option must be a valid array." - ); - testRange( - typeof options.mean !== 'number', - "Chance: Mean (mean) must be a number" - ); - testRange( - typeof options.dev !== 'number', - "Chance: Standard deviation (dev) must be a number" - ); - - // If a pool has been passed, then we are returning an item from that pool, - // using the normal distribution settings that were passed in - if (options.pool.length > 0) { - return this.normal_pool(options); - } - - // The Marsaglia Polar method - var s, u, v, norm, - mean = options.mean, - dev = options.dev; - - do { - // U and V are from the uniform distribution on (-1, 1) - u = this.random() * 2 - 1; - v = this.random() * 2 - 1; - - s = u * u + v * v; - } while (s >= 1); - - // Compute the standard normal variate - norm = u * Math.sqrt(-2 * Math.log(s) / s); - - // Shape and scale - return dev * norm + mean; - }; - - Chance.prototype.normal_pool = function(options) { - var performanceCounter = 0; - do { - var idx = Math.round(this.normal({ mean: options.mean, dev: options.dev })); - if (idx < options.pool.length && idx >= 0) { - return options.pool[idx]; - } else { - performanceCounter++; - } - } while(performanceCounter < 100); - - throw new RangeError("Chance: Your pool is too small for the given mean and standard deviation. Please adjust."); - }; - - Chance.prototype.radio = function (options) { - // Initial Letter (Typically Designated by Side of Mississippi River) - options = initOptions(options, {side : "?"}); - var fl = ""; - switch (options.side.toLowerCase()) { - case "east": - case "e": - fl = "W"; - break; - case "west": - case "w": - fl = "K"; - break; - default: - fl = this.character({pool: "KW"}); - break; - } - - return fl + this.character({alpha: true, casing: "upper"}) + - this.character({alpha: true, casing: "upper"}) + - this.character({alpha: true, casing: "upper"}); - }; - - // Set the data as key and data or the data map - Chance.prototype.set = function (name, values) { - if (typeof name === "string") { - data[name] = values; - } else { - data = copyObject(name, data); - } - }; - - Chance.prototype.tv = function (options) { - return this.radio(options); - }; - - // ID number for Brazil companies - Chance.prototype.cnpj = function () { - var n = this.n(this.natural, 8, { max: 9 }); - var d1 = 2+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; - d1 = 11 - (d1 % 11); - if (d1>=10){ - d1 = 0; - } - var d2 = d1*2+3+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; - d2 = 11 - (d2 % 11); - if (d2>=10){ - d2 = 0; - } - return ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/0001-'+d1+d2; - }; - - Chance.prototype.emotion = function () { - return this.pick(this.get("emotions")); - }; - - // -- End Miscellaneous -- - - Chance.prototype.mersenne_twister = function (seed) { - return new MersenneTwister(seed); - }; - - Chance.prototype.blueimp_md5 = function () { - return new BlueImpMD5(); - }; - - // Mersenne Twister from https://gist.github.com/banksean/300494 - /* - A C-program for MT19937, with initialization improved 2002/1/26. - Coded by Takuji Nishimura and Makoto Matsumoto. - - Before using, initialize the state by using init_genrand(seed) - or init_by_array(init_key, key_length). - - Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, - 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. The names of its contributors may not 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. - - - Any feedback is very welcome. - http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html - email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) - */ - var MersenneTwister = function (seed) { - if (seed === undefined) { - // kept random number same size as time used previously to ensure no unexpected results downstream - seed = Math.floor(Math.random()*Math.pow(10,13)); - } - /* Period parameters */ - this.N = 624; - this.M = 397; - this.MATRIX_A = 0x9908b0df; /* constant vector a */ - this.UPPER_MASK = 0x80000000; /* most significant w-r bits */ - this.LOWER_MASK = 0x7fffffff; /* least significant r bits */ - - this.mt = new Array(this.N); /* the array for the state vector */ - this.mti = this.N + 1; /* mti==N + 1 means mt[N] is not initialized */ - - this.init_genrand(seed); - }; - - /* initializes mt[N] with a seed */ - MersenneTwister.prototype.init_genrand = function (s) { - this.mt[0] = s >>> 0; - for (this.mti = 1; this.mti < this.N; this.mti++) { - s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30); - this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti; - /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ - /* In the previous versions, MSBs of the seed affect */ - /* only MSBs of the array mt[]. */ - /* 2002/01/09 modified by Makoto Matsumoto */ - this.mt[this.mti] >>>= 0; - /* for >32 bit machines */ - } - }; - - /* initialize by an array with array-length */ - /* init_key is the array for initializing keys */ - /* key_length is its length */ - /* slight change for C++, 2004/2/26 */ - MersenneTwister.prototype.init_by_array = function (init_key, key_length) { - var i = 1, j = 0, k, s; - this.init_genrand(19650218); - k = (this.N > key_length ? this.N : key_length); - for (; k; k--) { - s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); - this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525))) + init_key[j] + j; /* non linear */ - this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ - i++; - j++; - if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } - if (j >= key_length) { j = 0; } - } - for (k = this.N - 1; k; k--) { - s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); - this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i; /* non linear */ - this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ - i++; - if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } - } - - this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ - }; - - /* generates a random number on [0,0xffffffff]-interval */ - MersenneTwister.prototype.genrand_int32 = function () { - var y; - var mag01 = new Array(0x0, this.MATRIX_A); - /* mag01[x] = x * MATRIX_A for x=0,1 */ - - if (this.mti >= this.N) { /* generate N words at one time */ - var kk; - - if (this.mti === this.N + 1) { /* if init_genrand() has not been called, */ - this.init_genrand(5489); /* a default initial seed is used */ - } - for (kk = 0; kk < this.N - this.M; kk++) { - y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); - this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 0x1]; - } - for (;kk < this.N - 1; kk++) { - y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); - this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 0x1]; - } - y = (this.mt[this.N - 1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK); - this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; - - this.mti = 0; - } - - y = this.mt[this.mti++]; - - /* Tempering */ - y ^= (y >>> 11); - y ^= (y << 7) & 0x9d2c5680; - y ^= (y << 15) & 0xefc60000; - y ^= (y >>> 18); - - return y >>> 0; - }; - - /* generates a random number on [0,0x7fffffff]-interval */ - MersenneTwister.prototype.genrand_int31 = function () { - return (this.genrand_int32() >>> 1); - }; - - /* generates a random number on [0,1]-real-interval */ - MersenneTwister.prototype.genrand_real1 = function () { - return this.genrand_int32() * (1.0 / 4294967295.0); - /* divided by 2^32-1 */ - }; - - /* generates a random number on [0,1)-real-interval */ - MersenneTwister.prototype.random = function () { - return this.genrand_int32() * (1.0 / 4294967296.0); - /* divided by 2^32 */ - }; - - /* generates a random number on (0,1)-real-interval */ - MersenneTwister.prototype.genrand_real3 = function () { - return (this.genrand_int32() + 0.5) * (1.0 / 4294967296.0); - /* divided by 2^32 */ - }; - - /* generates a random number on [0,1) with 53-bit resolution*/ - MersenneTwister.prototype.genrand_res53 = function () { - var a = this.genrand_int32()>>>5, b = this.genrand_int32()>>>6; - return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); - }; - - // BlueImp MD5 hashing algorithm from https://github.com/blueimp/JavaScript-MD5 - var BlueImpMD5 = function () {}; - - BlueImpMD5.prototype.VERSION = '1.0.1'; - - /* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ - BlueImpMD5.prototype.safe_add = function safe_add(x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF), - msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); - }; - - /* - * Bitwise rotate a 32-bit number to the left. - */ - BlueImpMD5.prototype.bit_roll = function (num, cnt) { - return (num << cnt) | (num >>> (32 - cnt)); - }; - - /* - * These functions implement the five basic operations the algorithm uses. - */ - BlueImpMD5.prototype.md5_cmn = function (q, a, b, x, s, t) { - return this.safe_add(this.bit_roll(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s), b); - }; - BlueImpMD5.prototype.md5_ff = function (a, b, c, d, x, s, t) { - return this.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); - }; - BlueImpMD5.prototype.md5_gg = function (a, b, c, d, x, s, t) { - return this.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); - }; - BlueImpMD5.prototype.md5_hh = function (a, b, c, d, x, s, t) { - return this.md5_cmn(b ^ c ^ d, a, b, x, s, t); - }; - BlueImpMD5.prototype.md5_ii = function (a, b, c, d, x, s, t) { - return this.md5_cmn(c ^ (b | (~d)), a, b, x, s, t); - }; - - /* - * Calculate the MD5 of an array of little-endian words, and a bit length. - */ - BlueImpMD5.prototype.binl_md5 = function (x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << (len % 32); - x[(((len + 64) >>> 9) << 4) + 14] = len; - - var i, olda, oldb, oldc, oldd, - a = 1732584193, - b = -271733879, - c = -1732584194, - d = 271733878; - - for (i = 0; i < x.length; i += 16) { - olda = a; - oldb = b; - oldc = c; - oldd = d; - - a = this.md5_ff(a, b, c, d, x[i], 7, -680876936); - d = this.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); - c = this.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); - b = this.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = this.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); - d = this.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = this.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = this.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); - a = this.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = this.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = this.md5_ff(c, d, a, b, x[i + 10], 17, -42063); - b = this.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = this.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = this.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); - c = this.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = this.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); - - a = this.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); - d = this.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = this.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); - b = this.md5_gg(b, c, d, a, x[i], 20, -373897302); - a = this.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); - d = this.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); - c = this.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); - b = this.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); - a = this.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); - d = this.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = this.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); - b = this.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = this.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = this.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); - c = this.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = this.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); - - a = this.md5_hh(a, b, c, d, x[i + 5], 4, -378558); - d = this.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = this.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = this.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); - a = this.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = this.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = this.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); - b = this.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = this.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); - d = this.md5_hh(d, a, b, c, x[i], 11, -358537222); - c = this.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); - b = this.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); - a = this.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); - d = this.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); - c = this.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); - b = this.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); - - a = this.md5_ii(a, b, c, d, x[i], 6, -198630844); - d = this.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = this.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = this.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); - a = this.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = this.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = this.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); - b = this.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = this.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = this.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); - c = this.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = this.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = this.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); - d = this.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = this.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); - b = this.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); - - a = this.safe_add(a, olda); - b = this.safe_add(b, oldb); - c = this.safe_add(c, oldc); - d = this.safe_add(d, oldd); - } - return [a, b, c, d]; - }; - - /* - * Convert an array of little-endian words to a string - */ - BlueImpMD5.prototype.binl2rstr = function (input) { - var i, - output = ''; - for (i = 0; i < input.length * 32; i += 8) { - output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); - } - return output; - }; - - /* - * Convert a raw string to an array of little-endian words - * Characters >255 have their high-byte silently ignored. - */ - BlueImpMD5.prototype.rstr2binl = function (input) { - var i, - output = []; - output[(input.length >> 2) - 1] = undefined; - for (i = 0; i < output.length; i += 1) { - output[i] = 0; - } - for (i = 0; i < input.length * 8; i += 8) { - output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); - } - return output; - }; - - /* - * Calculate the MD5 of a raw string - */ - BlueImpMD5.prototype.rstr_md5 = function (s) { - return this.binl2rstr(this.binl_md5(this.rstr2binl(s), s.length * 8)); - }; - - /* - * Calculate the HMAC-MD5, of a key and some data (raw strings) - */ - BlueImpMD5.prototype.rstr_hmac_md5 = function (key, data) { - var i, - bkey = this.rstr2binl(key), - ipad = [], - opad = [], - hash; - ipad[15] = opad[15] = undefined; - if (bkey.length > 16) { - bkey = this.binl_md5(bkey, key.length * 8); - } - for (i = 0; i < 16; i += 1) { - ipad[i] = bkey[i] ^ 0x36363636; - opad[i] = bkey[i] ^ 0x5C5C5C5C; - } - hash = this.binl_md5(ipad.concat(this.rstr2binl(data)), 512 + data.length * 8); - return this.binl2rstr(this.binl_md5(opad.concat(hash), 512 + 128)); - }; - - /* - * Convert a raw string to a hex string - */ - BlueImpMD5.prototype.rstr2hex = function (input) { - var hex_tab = '0123456789abcdef', - output = '', - x, - i; - for (i = 0; i < input.length; i += 1) { - x = input.charCodeAt(i); - output += hex_tab.charAt((x >>> 4) & 0x0F) + - hex_tab.charAt(x & 0x0F); - } - return output; - }; - - /* - * Encode a string as utf-8 - */ - BlueImpMD5.prototype.str2rstr_utf8 = function (input) { - return unescape(encodeURIComponent(input)); - }; - - /* - * Take string arguments and return either raw or hex encoded strings - */ - BlueImpMD5.prototype.raw_md5 = function (s) { - return this.rstr_md5(this.str2rstr_utf8(s)); - }; - BlueImpMD5.prototype.hex_md5 = function (s) { - return this.rstr2hex(this.raw_md5(s)); - }; - BlueImpMD5.prototype.raw_hmac_md5 = function (k, d) { - return this.rstr_hmac_md5(this.str2rstr_utf8(k), this.str2rstr_utf8(d)); - }; - BlueImpMD5.prototype.hex_hmac_md5 = function (k, d) { - return this.rstr2hex(this.raw_hmac_md5(k, d)); - }; - - BlueImpMD5.prototype.md5 = function (string, key, raw) { - if (!key) { - if (!raw) { - return this.hex_md5(string); - } - - return this.raw_md5(string); - } - - if (!raw) { - return this.hex_hmac_md5(key, string); - } - - return this.raw_hmac_md5(key, string); - }; - - // CommonJS module - if (true) { - if ( true && module.exports) { - exports = module.exports = Chance; - } - exports.Chance = Chance; - } - - // Register as an anonymous AMD module - if (typeof define === 'function' && define.amd) { - define([], function () { - return Chance; - }); - } - - // if there is a importsScrips object define chance for worker - // allows worker to use full Chance functionality with seed - if (typeof importScripts !== 'undefined') { - chance = new Chance(); - self.Chance = Chance; - } - - // If there is a window object, that at least has a document property, - // instantiate and define chance on the window - if (typeof window === "object" && typeof window.document === "object") { - window.Chance = Chance; - window.chance = new Chance(); - } -})(); - - -/***/ }), - -/***/ 59051: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"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 - - -/***/ }), - -/***/ 83733: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const cliBoxes = __nccwpck_require__(70094); - -module.exports = cliBoxes; -// TODO: Remove this for the next major release -module.exports["default"] = cliBoxes; - - -/***/ }), - -/***/ 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); -}; - - -/***/ }), - -/***/ 24137: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const binding = __nccwpck_require__(24240); - -module.exports = binding.getCPUInfo; - - -/***/ }), - -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - let m; - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - // eslint-disable-next-line no-return-assign - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), - -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(80900); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - const split = (typeof namespaces === 'string' ? namespaces : '') - .trim() - .replace(/\s+/g, ',') - .split(',') - .filter(Boolean); - - for (const ns of split) { - if (ns[0] === '-') { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } - - /** - * Checks if the given string matches a namespace template, honoring - * asterisks as wildcards. - * - * @param {String} search - * @param {String} template - * @return {Boolean} - */ - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { - // Match character or proceed with wildcard - if (template[templateIndex] === '*') { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; // Skip the '*' - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition - // Backtrack to the last '*' and try to match more characters - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; // No match - } - } - - // Handle trailing '*' in template - while (templateIndex < template.length && template[templateIndex] === '*') { - templateIndex++; - } - - return templateIndex === template.length; - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - - return false; - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), - -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); -} - - -/***/ }), - -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * Module dependencies. - */ - -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(30132); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), - -/***/ 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; - - -/***/ }), - -/***/ 84305: -/***/ ((module, exports, __nccwpck_require__) => { - -//Based on follow-redirects v0.0.x - -var nativeHttps = __nccwpck_require__(95687), - nativeHttp = __nccwpck_require__(13685), - url = __nccwpck_require__(57310), - utils = __nccwpck_require__(74967); - -var maxRedirects = module.exports.maxRedirects = 5; - -var protocols = { - https: nativeHttps, - http: nativeHttp -}; - -for (var protocol in protocols) { - var h = function() {}; - h.prototype = protocols[protocol]; - h = new h(); - - h.request = function(h) { - return function(options, callback, redirectOptions) { - - redirectOptions = redirectOptions || {}; - - var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects; - - var redirect = utils.extend({ - count: 0, - max: max, - clientRequest: null, - userCallback: callback - }, redirectOptions); - - if (redirect.count > redirect.max) { - var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.'); - redirect.clientRequest.emit('error', err); - return redirect.clientRequest; - } - - redirect.count++; - - var reqUrl; - if (typeof options === 'string') { - reqUrl = options; - } else { - reqUrl = url.format(utils.extend({ - protocol: protocol - }, options)); - } - - var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect)); - - if (!redirect.clientRequest) redirect.clientRequest = clientRequest; - - function redirectCallback(reqUrl, redirect) { - return function(res) { - if (res.statusCode < 300 || res.statusCode > 399) { - return redirect.userCallback(res); - } - - if (!('location' in res.headers)) { - return redirect.userCallback(res); - } - - var redirectUrl = url.resolve(reqUrl, res.headers.location); - - var proto = url.parse(redirectUrl).protocol; - proto = proto.substr(0, proto.length - 1); - return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect); - }; - } - - return clientRequest; - }; - }(h); - - // see https://github.com/joyent/node/blob/master/lib/http.js#L1623 - h.get = function(h) { - return function(options, cb, redirectOptions) { - var req = h.request(options, cb, redirectOptions); - req.end(); - return req; - }; - }(h); - - module.exports[protocol] = h; -} - - -/***/ }), - -/***/ 13855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = HttpDuplex; - -var util = __nccwpck_require__(73837), - stream = __nccwpck_require__(51642); - -util.inherits(HttpDuplex, stream.Duplex); - -function HttpDuplex(req, res, options) { - var self = this; - - if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options); - - stream.Duplex.call(self, options); - self._output = null; - - self.connect(req, res); -} - -HttpDuplex.prototype.connect = function(req, res) { - var self = this; - self.req = req; - self._output = res; - self.emit('response', res); - - res.on('data', function(c) { - if (!self.push(c)) self._output.pause(); - }); - res.on('end', function() { - self.push(null); - }); -}; - -HttpDuplex.prototype._read = function(n) { - if (this._output) this._output.resume(); -}; - -HttpDuplex.prototype._write = function(chunk, encoding, cb) { - this.req.write(chunk, encoding); - cb(); -}; - -HttpDuplex.prototype.end = function(chunk, encoding, cb) { - this._output.socket.destroySoon(); - return this.req.end(chunk, encoding, cb); -}; - -HttpDuplex.prototype.destroy = function() { - this.req.destroy(); - this._output.socket.destroy(); -}; - -HttpDuplex.prototype.destroySoon = function() { - this.req.destroy(); - this._output.socket.destroy(); -}; - - -/***/ }), - -/***/ 26042: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var querystring = __nccwpck_require__(63477), - http = __nccwpck_require__(84305), - fs = __nccwpck_require__(57147), - path = __nccwpck_require__(71017), - url = __nccwpck_require__(57310), - ssh = __nccwpck_require__(7964), - HttpDuplex = __nccwpck_require__(13855), - debug = __nccwpck_require__(38237)('modem'), - utils = __nccwpck_require__(74967), - util = __nccwpck_require__(73837), - splitca = __nccwpck_require__(39798), - os = __nccwpck_require__(22037), - isWin = os.type() === 'Windows_NT', - stream = __nccwpck_require__(12781); - -var defaultOpts = function () { - var host; - var opts = {}; - - if (!process.env.DOCKER_HOST) { - // Windows socket path: //./pipe/docker_engine ( Windows 10 ) - // Linux & Darwin socket path is /var/run/docker.sock when running system-wide, - // or $HOME/.docker/run/docker.sock in new Docker Desktop installs. - opts.socketPath = isWin ? '//./pipe/docker_engine' : findDefaultUnixSocket; - } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) { - // Strip off unix://, fall back to default if unix:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket; - } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) { - // Strip off npipe://, fall back to default of //./pipe/docker_engine if - // npipe:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine'; - } else { - var hostStr = process.env.DOCKER_HOST; - if (hostStr.indexOf('\/\/') < 0) { - hostStr = 'tcp://' + hostStr; - } - try { - host = new url.URL(hostStr); - } catch (err) { - throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234'); - } - - opts.port = host.port; - - if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') { - opts.protocol = 'https'; - } else if (host.protocol === 'ssh:') { - opts.protocol = 'ssh'; - opts.username = host.username; - opts.sshOptions = { - agent: process.env.SSH_AUTH_SOCK, - } - } else { - opts.protocol = 'http'; - } - - if (process.env.DOCKER_PATH_PREFIX) { - opts.pathPrefix = process.env.DOCKER_PATH_PREFIX; - } - else { - opts.pathPrefix = '/'; - } - - opts.host = host.hostname; - - if (process.env.DOCKER_CERT_PATH) { - opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem')); - opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem')); - opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem')); - } - - if (process.env.DOCKER_CLIENT_TIMEOUT) { - opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); - } - } - - return opts; -}; - -var findDefaultUnixSocket = function () { - return new Promise(function (resolve) { - var userDockerSocket = path.join(os.homedir(), '.docker', 'run', 'docker.sock'); - fs.access(userDockerSocket, function (err) { - if (err) resolve('/var/run/docker.sock'); - else resolve(userDockerSocket); - }) - }); -} - - -var Modem = function (options) { - var optDefaults = defaultOpts(); - var opts = Object.assign({}, optDefaults, options); - - this.host = opts.host; - - if (!this.host) { - this.socketPath = opts.socketPath; - } - - this.port = opts.port; - this.pathPrefix = opts.pathPrefix; - this.username = opts.username; - this.password = opts.password; - this.version = opts.version; - this.key = opts.key; - this.cert = opts.cert; - this.ca = opts.ca; - this.timeout = opts.timeout; - this.connectionTimeout = opts.connectionTimeout; - this.checkServerIdentity = opts.checkServerIdentity; - this.agent = opts.agent; - this.headers = opts.headers || {}; - this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); - //retrocompabitlity - if (this.sshOptions.agentForward === undefined) { - this.sshOptions.agentForward = opts.agentForward; - } - - if (this.key && this.cert && this.ca) { - this.protocol = 'https'; - } - this.protocol = opts.protocol || this.protocol || 'http'; -}; - -Modem.prototype.dial = function (options, callback) { - var opts, address, data; - - if (options.options) { - opts = options.options; - } - - // Prevent credentials from showing up in URL - if (opts && opts.authconfig) { - delete opts.authconfig; - } - - // Prevent abortsignal from showing up in the URL - if (opts && opts.abortSignal) { - delete opts.abortSignal; - } - - if (this.version) { - options.path = '/' + this.version + options.path; - } - - if (this.host) { - var parsed = url.parse(this.host); - address = url.format({ - protocol: parsed.protocol || this.protocol, - hostname: parsed.hostname || this.host, - port: this.port, - pathname: parsed.pathname || this.pathPrefix, - }); - address = url.resolve(address, options.path); - } else { - address = options.path; - } - - if (options.path.indexOf('?') !== -1) { - if (opts && Object.keys(opts).length > 0) { - address += this.buildQuerystring(opts._query || opts); - } else { - address = address.substring(0, address.length - 1); - } - } - - var optionsf = { - path: address, - method: options.method, - headers: options.headers || Object.assign({}, this.headers), - key: this.key, - cert: this.cert, - ca: this.ca - }; - - - if (this.checkServerIdentity) { - optionsf.checkServerIdentity = this.checkServerIdentity; - } - - if (this.agent) { - optionsf.agent = this.agent; - } - - if (options.authconfig) { - optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 || - Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\+/g, "-").replace(/\//g, "_"); - } - - if (options.registryconfig) { - optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 || - Buffer.from(JSON.stringify(options.registryconfig)).toString('base64'); - } - - if (options.abortSignal) { - optionsf.signal = options.abortSignal; - } - - if (options.file) { - if (typeof options.file === 'string') { - data = fs.createReadStream(path.resolve(options.file)); - } else { - data = options.file; - } - optionsf.headers['Content-Type'] = 'application/tar'; - } else if (opts && options.method === 'POST') { - data = JSON.stringify(opts._body || opts); - if (options.allowEmpty) { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - if (data !== '{}' && data !== '""') { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - data = undefined; - } - } - } - - if (typeof data === 'string') { - optionsf.headers['Content-Length'] = Buffer.byteLength(data); - } else if (Buffer.isBuffer(data) === true) { - optionsf.headers['Content-Length'] = data.length; - } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) { - optionsf.headers['Transfer-Encoding'] = 'chunked'; - } - - if (options.hijack) { - optionsf.headers.Connection = 'Upgrade'; - optionsf.headers.Upgrade = optionsf.headers.Upgrade ?? 'tcp'; - } - - if (this.socketPath) { - // SocketPath may be a function that can return a promise: - this.getSocketPath().then((socketPath) => { - optionsf.socketPath = socketPath; - this.buildRequest(optionsf, options, data, callback); - }); - } else { - var urlp = url.parse(address); - optionsf.hostname = urlp.hostname; - optionsf.port = urlp.port; - optionsf.path = urlp.path; - - this.buildRequest(optionsf, options, data, callback); - } -}; - -Modem.prototype.getSocketPath = function () { - if (!this.socketPath) return; - if (this.socketPathCache) return Promise.resolve(this.socketPathCache); - - var socketPathValue = typeof this.socketPath === 'function' - ? this.socketPath() : this.socketPath; - - this.socketPathCache = socketPathValue; - - return Promise.resolve(socketPathValue); -} - -Modem.prototype.buildRequest = function (options, context, data, callback) { - var self = this; - var connectionTimeoutTimer; - var finished = false; - - var opts = self.protocol === 'ssh' ? Object.assign(options, { - agent: ssh(Object.assign({}, self.sshOptions, { - 'host': self.host, - 'port': self.port, - 'username': self.username, - 'password': self.password, - })), - protocol: 'http:', - }) : options; - - var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { }); - - debug('Sending: %s', util.inspect(options, { - showHidden: true, - depth: null - })); - - if (self.connectionTimeout) { - connectionTimeoutTimer = setTimeout(function () { - debug('Connection Timeout of %s ms exceeded', self.connectionTimeout); - req.destroy(); - }, self.connectionTimeout); - } - - if (self.timeout) { - req.setTimeout(self.timeout); - req.on('timeout', function () { - debug('Timeout of %s ms exceeded', self.timeout); - req.destroy(); - }); - } - - if (context.hijack === true) { - clearTimeout(connectionTimeoutTimer); - req.on('upgrade', function (res, sock, head) { - if (finished === false) { - finished = true; - if (head.length > 0) { - sock.unshift(head); - } - return callback(null, sock); - } - }); - } - - req.on('connect', function () { - clearTimeout(connectionTimeoutTimer); - }); - - req.on('disconnect', function () { - clearTimeout(connectionTimeoutTimer); - }); - - req.on('response', function (res) { - clearTimeout(connectionTimeoutTimer); - if (context.isStream === true) { - if (finished === false) { - finished = true; - self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback); - } - } else { - // The native 'request' method only handles aborting during the request lifecycle not the response lifecycle. - // We need to make the response stream abortable so that it's destroyed with an error on abort and then - // it triggers the request 'error' event - if (options.signal != null) { - stream.addAbortSignal(options.signal, res) - } - var chunks = []; - res.on('data', function (chunk) { - chunks.push(chunk); - }); - - res.on('end', function () { - var buffer = Buffer.concat(chunks); - var result = buffer.toString(); - - debug('Received: %s', result); - - var json = utils.parseJSON(result) || buffer; - if (finished === false) { - finished = true; - self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback); - } - }); - } - }); - - req.on('error', function (error) { - clearTimeout(connectionTimeoutTimer); - if (finished === false) { - finished = true; - self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback); - } - }); - - if (typeof data === 'string' || Buffer.isBuffer(data)) { - req.write(data); - } else if (data) { - data.on('error', function (error) { - req.destroy(error); - }); - data.pipe(req); - } - - if (!context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) { - req.end(); - } -}; - -Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) { - if (err) return cb(err, null); - - if (statusCodes[res.statusCode] !== true) { - getCause(isStream, res, json, function (err, cause) { - if (err) { - return cb(err, null); - } - var msg = new Error( - '(HTTP code ' + res.statusCode + ') ' + - (statusCodes[res.statusCode] || 'unexpected') + ' - ' + - (cause.message || cause.error || cause) + ' ' - ); - msg.reason = statusCodes[res.statusCode]; - msg.statusCode = res.statusCode; - msg.json = json; - cb(msg, null); - }); - } else { - if (openStdin) { - cb(null, new HttpDuplex(req, res)); - } else if (isStream) { - cb(null, res); - } else { - cb(null, json); - } - } - - function getCause(isStream, res, json, callback) { - var chunks = ''; - var done = false; - - if (isStream) { - res.on('data', function (chunk) { - chunks += chunk; - }); - res.on('error', function (err) { - handler(err, null); - }); - res.on('end', function () { - handler(null, utils.parseJSON(chunks) || chunks) - }); - } else { - callback(null, json); - } - - function handler(err, data) { - if (done === false) { - if (err) { - callback(err); - } else { - callback(null, data); - } - } - done = true; - } - } -}; - -Modem.prototype.demuxStream = function (streama, stdout, stderr) { - var nextDataType = null; - var nextDataLength = null; - var buffer = Buffer.from(''); - function processData(data) { - if (data) { - buffer = Buffer.concat([buffer, data]); - } - if (!nextDataType) { - if (buffer.length >= 8) { - var header = bufferSlice(8); - nextDataType = header.readUInt8(0); - nextDataLength = header.readUInt32BE(4); - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } else { - if (buffer.length >= nextDataLength) { - var content = bufferSlice(nextDataLength); - if (nextDataType === 1) { - stdout.write(content); - } else { - stderr.write(content); - } - nextDataType = null; - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } - } - - function bufferSlice(end) { - var out = buffer.subarray(0, end); - buffer = Buffer.from(buffer.subarray(end, buffer.length)); - return out; - } - - streama.on('data', processData); -}; - -Modem.prototype.followProgress = function (streama, onFinished, onProgress) { - var buf = ''; - var output = []; - var finished = false; - - streama.on('data', onStreamEvent); - streama.on('error', onStreamError); - streama.on('end', onStreamEnd); - streama.on('close', onStreamEnd); - - function onStreamEvent(data) { - buf += data.toString(); - pump(); - - function pump() { - var pos; - while ((pos = buf.indexOf('\n')) >= 0) { - if (pos == 0) { - buf = buf.slice(1); - continue; - } - processLine(buf.slice(0, pos)); - buf = buf.slice(pos + 1); - } - } - - function processLine(line) { - if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1); - if (line.length > 0) { - var obj = JSON.parse(line); - output.push(obj); - if (onProgress) { - onProgress(obj); - } - } - } - }; - - function onStreamError(err) { - finished = true; - streama.removeListener('data', onStreamEvent); - streama.removeListener('error', onStreamError); - streama.removeListener('end', onStreamEnd); - streama.removeListener('close', onStreamEnd); - onFinished(err, output); - } - - function onStreamEnd() { - if (!finished) onFinished(null, output); - finished = true; - } -}; - -Modem.prototype.buildQuerystring = function (opts) { - var clone = {}; - - Object.keys(opts).map(function (key, i) { - if ( - opts[key] && - typeof opts[key] === 'object' && - !Array.isArray(opts[key]) - ) { - clone[key] = JSON.stringify(opts[key]); - } else { - clone[key] = opts[key]; - } - }); - - return querystring.stringify(clone); -}; - -module.exports = Modem; - - -/***/ }), - -/***/ 7964: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Client = (__nccwpck_require__(95869).Client), - http = __nccwpck_require__(13685); - -module.exports = function (opt) { - var conn = new Client(); - var agent = new http.Agent(); - - agent.createConnection = function (options, fn) { - try { - conn.once('ready', function () { - conn.exec('docker system dial-stdio', function (err, stream) { - if (err) { - handleError(err , fn); - } - - fn(null, stream); - - stream.addListener('error', (err) => { - handleError(err, fn); - }); - stream.once('close', () => { - conn.end(); - agent.destroy(); - }); - }); - }).on('error', (err) => { - handleError(err, fn); - }) - .connect(opt); - conn.once('end', () => agent.destroy()); - - } catch (err) { - handleError(err); - } - }; - - function handleError(err, cb) { - conn.end(); - agent.destroy(); - if (cb) { - cb(err); - } else { - throw err; - } - } - - return agent; -}; - - -/***/ }), - -/***/ 74967: -/***/ ((module) => { - -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js - -var arr = []; -var each = arr.forEach; -var slice = arr.slice; - -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; -}; - -module.exports.parseJSON = function(s) { - try { - return JSON.parse(s); - } catch (e) { - return null; - } -}; - - -/***/ }), - -/***/ 5004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a config - * @param {Object} modem docker-modem - * @param {String} id Config's id - */ -var Config = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Config.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Config.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update a config. - * - * @param {object} opts - * @param {function} callback - */ -Config.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs/' + this.id + '/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Removes the config - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Config.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - -module.exports = Config; - - -/***/ }), - -/***/ 35815: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var extend = (__nccwpck_require__(41604).extend), - Exec = __nccwpck_require__(73149), - util = __nccwpck_require__(41604); - -/** - * Represents a Container - * @param {Object} modem docker-modem - * @param {String} id Container's ID - */ -var Container = function(modem, id) { - this.modem = modem; - this.id = id; - - this.defaultOptions = { - top: {}, - start: {}, - commit: {}, - stop: {}, - pause: {}, - unpause: {}, - restart: {}, - resize: {}, - attach: {}, - remove: {}, - copy: {}, - kill: {}, - exec: {}, - rename: {}, - log: {}, - stats: {}, - getArchive: {}, - infoArchive: {}, - putArchive: {}, - update: {}, - wait: {} - }; -}; - -Container.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if supplied will query Docker. - * @return {Object} ID only and only if callback isn't supplied. - */ -Container.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Rename - * @param {Object} opts Rename options - * @param {Function} callback Callback - */ -Container.prototype.rename = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.rename); - - var optsf = { - path: '/containers/' + this.id + '/rename?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update - * @param {Object} opts Update options - * @param {Function} callback Callback - */ -Container.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.update); - - var optsf = { - path: '/containers/' + this.id + '/update', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Top - * @param {Object} opts like 'ps_args' (optional) - * @param {Function} callback Callback - */ -Container.prototype.top = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.top); - - var optsf = { - path: '/containers/' + this.id + '/top?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Containers changes - * @param {Object} Options - * @param {Function} callback Callback - */ -Container.prototype.changes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/changes', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Checkpoints list - * @param {Object} opts List checkpoints options (optional) - * @param {Function} callback Callback - */ -Container.prototype.listCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/checkpoints?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Delete checkpoint - * @param {Object} opts Delete checkpoint options (optional) - * @param {Function} callback Callback - */ -Container.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Create checkpoint - * @param {Object} opts Create checkpoint options (optional) - * @param {Function} callback Callback - */ -Container.prototype.createCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/checkpoints', - method: 'POST', - abortSignal: args.opts.abortSignal, - allowEmpty: true, - statusCodes: { - 200: true, //unofficial, but proxies may return it - 201: true, - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Export - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with the octet-stream. - */ -Container.prototype.export = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/export', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Start - * @param {Object} opts Container start options (optional) - * @param {Function} callback Callback - */ -Container.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.start); - - var optsf = { - path: '/containers/' + this.id + '/start?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already started', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Pause - * @param {Object} opts Pause options (optional) - * @param {Function} callback Callback - */ -Container.prototype.pause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.pause); - - var optsf = { - path: '/containers/' + this.id + '/pause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Unpause - * @param {Object} opts Unpause options (optional) - * @param {Function} callback Callback - */ -Container.prototype.unpause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.unpause); - - var optsf = { - path: '/containers/' + this.id + '/unpause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Setup an exec call to a running container - * - * @param {object} opts - * @param {function} callback - */ -Container.prototype.exec = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.exec); - - var optsf = { - path: '/containers/' + this.id + '/exec', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 409: 'container stopped/paused', - 500: 'server error' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(new Exec(self.modem, data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, new Exec(self.modem, data.Id)); - }); - } -}; - -/** - * Commit - * @param {Object} opts Commit options like 'Hostname' (optional) - * @param {Function} callback Callback - */ -Container.prototype.commit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.commit); - - args.opts.container = this.id; - - var optsf = { - path: '/commit?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Stop - * @param {Object} opts Container stop options, like 't' (optional) - * @param {Function} callback Callback - */ -Container.prototype.stop = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stop); - - var optsf = { - path: '/containers/' + this.id + '/stop?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already stopped', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Restart - * @param {Object} opts Container restart options, like 't' (optional) - * @param {Function} callback Callback - */ -Container.prototype.restart = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.restart); - - var optsf = { - path: '/containers/' + this.id + '/restart?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Kill - * @param {Object} opts Container kill options, like 'signal' (optional) - * @param {Function} callback Callback - */ -Container.prototype.kill = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.kill); - - var optsf = { - path: '/containers/' + this.id + '/kill?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Container resize - * @param {[type]} opts Resize options. (optional) - * @param {Function} callback Callback - */ -Container.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.resize); - - var optsf = { - path: '/containers/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Attach - * @param {Object} opts Attach options, like 'logs' (optional) - * @param {Function} callback Callback with stream. - */ -Container.prototype.attach = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.attach); - - var optsf = { - path: '/containers/' + this.id + '/attach?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, stream) { - if (err) { - return reject(err); - } - resolve(stream); - }); - }); - } else { - this.modem.dial(optsf, function(err, stream) { - args.callback(err, stream); - }); - } -}; - -/** - * Waits for a container to end. - * @param {[type]} opts Container wait options, like condition. (optional) - * @param {Function} callback Callback - */ -Container.prototype.wait = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.wait); - - var optsf = { - path: '/containers/' + this.id + '/wait?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes a container - * @param {Object} opts Remove options, like 'force' (optional) - * @param {Function} callback Callback - */ -Container.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.remove); - - var optsf = { - path: '/containers/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Copy (WARNING: DEPRECATED since RAPI v1.20) - * @param {Object} opts Copy options, like 'Resource' (optional) - * @param {Function} callback Callback with stream. - */ -Container.prototype.copy = function(opts, callback) { - var self = this; - console.log('container.copy is deprecated since Docker v1.8.x'); - var args = util.processArgs(opts, callback, this.defaultOptions.copy); - - var optsf = { - path: '/containers/' + this.id + '/copy', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * getArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.getArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); - - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * infoArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.infoArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); - - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'HEAD', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * putArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.putArchive = function(file, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); - - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'PUT', - file: file, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 403: 'client error, permission denied', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Container logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Container.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); - - var optsf = { - path: '/containers/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Container stats - * @param {Object} opts Stats options. (optional) - * @param {Function} callback Callback with data - */ -Container.prototype.stats = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stats); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/containers/' + this.id + '/stats?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -module.exports = Container; - - -/***/ }), - -/***/ 14571: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var EventEmitter = (__nccwpck_require__(82361).EventEmitter), - Modem = __nccwpck_require__(26042), - Container = __nccwpck_require__(35815), - Image = __nccwpck_require__(96689), - Volume = __nccwpck_require__(94877), - Network = __nccwpck_require__(39780), - Service = __nccwpck_require__(28866), - Plugin = __nccwpck_require__(16606), - Secret = __nccwpck_require__(79934), - Config = __nccwpck_require__(5004), - Task = __nccwpck_require__(61385), - Node = __nccwpck_require__(52297), - Exec = __nccwpck_require__(73149), - util = __nccwpck_require__(41604), - withSession = __nccwpck_require__(68304), - extend = util.extend; - -var Docker = function(opts) { - if (!(this instanceof Docker)) return new Docker(opts); - - var plibrary = global.Promise; - - if (opts && opts.Promise) { - plibrary = opts.Promise; - - if (Object.keys(opts).length === 1) { - opts = undefined; - } - } - - if (opts && opts.modem) { - this.modem = opts.modem; - } else { - this.modem = new Modem(opts); - } - this.modem.Promise = plibrary; -}; - -/** - * Creates a new container - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createContainer = function(opts, callback) { - var self = this; - var optsf = { - path: '/containers/create?', - method: 'POST', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 400: 'bad parameter', - 404: 'no such container', - 406: 'impossible to attach', - 500: 'server error' - } - }; - - delete opts.authconfig; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getContainer(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getContainer(data.Id)); - }); - } -}; - -/** - * Creates a new image - * @param {Object} auth Authentication (optional) - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createImage = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!callback && !opts) { - opts = auth; - auth = opts.authconfig; - } - - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Load image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.loadImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } - - var optsf = { - path: '/images/load?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Import image from a tar archive - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.importImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = undefined; - } - - if (!opts) - opts = {}; - - opts.fromSrc = '-'; - - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Verifies auth - * @param {Object} opts Options - * @param {Function} callback Callback - */ -Docker.prototype.checkAuth = function(opts, callback) { - var self = this; - var optsf = { - path: '/auth', - method: 'POST', - options: opts, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Builds an image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.buildImage = function(file, opts, callback) { - var self = this; - - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } - - var optsf = { - path: '/build?', - method: 'POST', - file: undefined, - options: opts, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (opts) { - if (opts.registryconfig) { - optsf.registryconfig = optsf.options.registryconfig; - delete optsf.options.registryconfig; - } - - //undocumented? - if (opts.authconfig) { - optsf.authconfig = optsf.options.authconfig; - delete optsf.options.authconfig; - } - - if (opts.cachefrom && Array.isArray(opts.cachefrom)) { - optsf.options.cachefrom = JSON.stringify(opts.cachefrom); - } - } - - function dial(callback) { - util.prepareBuildContext(file, (ctx) => { - optsf.file = ctx; - self.modem.dial(optsf, callback); - }); - } - - function dialWithSession(callback) { - if (opts?.version === "2") { - withSession(self, optsf.authconfig,(err, sessionId, done) => { - if (err) { - return callback(err); - } - - optsf.options.session = sessionId; - - dial((err, data) => { - callback(err, data); - - if (data) { - data.on("end", done); - } - }); - }); - } else { - dial(callback); - } - } - - if (callback === undefined) { - return new self.modem.Promise(function (resolve, reject) { - dialWithSession(function (err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - dialWithSession(callback); - } -}; - -/** - * Fetches a Container by ID - * @param {String} id Container's ID - */ -Docker.prototype.getContainer = function(id) { - return new Container(this.modem, id); -}; - -/** - * Fetches an Image by name - * @param {String} name Image's name - */ -Docker.prototype.getImage = function(name) { - return new Image(this.modem, name); -}; - -/** - * Fetches a Volume by name - * @param {String} name Volume's name - */ -Docker.prototype.getVolume = function(name) { - return new Volume(this.modem, name); -}; - -/** - * Fetches a Plugin by name - * @param {String} name Volume's name - */ -Docker.prototype.getPlugin = function(name, remote) { - return new Plugin(this.modem, name, remote); -}; - -/** - * Fetches a Service by id - * @param {String} id Services's id - */ -Docker.prototype.getService = function(id) { - return new Service(this.modem, id); -}; - -/** - * Fetches a Task by id - * @param {String} id Task's id - */ -Docker.prototype.getTask = function(id) { - return new Task(this.modem, id); -}; - -/** - * Fetches Node by id - * @param {String} id Node's id - */ -Docker.prototype.getNode = function(id) { - return new Node(this.modem, id); -}; - -/** - * Fetches a Network by id - * @param {String} id network's id - */ -Docker.prototype.getNetwork = function(id) { - return new Network(this.modem, id); -}; - -/** - * Fetches a Secret by id - * @param {String} id network's id - */ -Docker.prototype.getSecret = function(id) { - return new Secret(this.modem, id); -}; - -/** - * Fetches a Config by id - * @param {String} id network's id - */ -Docker.prototype.getConfig = function(id) { - return new Config(this.modem, id); -}; - -/** - * Fetches an Exec instance by ID - * @param {String} id Exec instance's ID - */ -Docker.prototype.getExec = function(id) { - return new Exec(this.modem, id); -}; - -/** - * Lists containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Get images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.getImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/get?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists Services - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listServices = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists Nodes - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listNodes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such node', - 500: 'server error', - 503: 'node is not part of a swarm', - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists Tasks - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listTasks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/tasks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Creates a new secret - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createSecret = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/secrets/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getSecret(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getSecret(data.ID)); - }); - } -}; - - -/** - * Creates a new config - * @param {Object} opts Config options - * @param {Function} callback Callback - */ -Docker.prototype.createConfig = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/configs/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getConfig(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getConfig(data.ID)); - }); - } -}; - - -/** - * Lists secrets - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listSecrets = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/secrets?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists configs - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listConfigs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Creates a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createPlugin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/plugins/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getPlugin(args.opts.name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getPlugin(args.opts.name)); - }); - } -}; - - -/** - * Lists plugins - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listPlugins = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune builder - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneBuilder = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/build/prune', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Creates a new volume - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createVolume = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/volumes/create?', - method: 'POST', - allowEmpty: true, - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getVolume(data.Name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getVolume(data.Name)); - }); - } -}; - -/** - * Creates a new service - * @param {Object} auth - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createService = function(auth, opts, callback) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!opts && !callback) { - opts = auth; - } - - - var self = this; - var optsf = { - path: '/services/create', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 500: 'server error' - } - }; - - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getService(data.ID || data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getService(data.ID || data.Id)); - }); - } -}; - -/** - * Lists volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Creates a new network - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createNetwork = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/networks/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'driver not found', - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getNetwork(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getNetwork(data.Id)); - }); - } -}; - -/** - * Lists networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Search images - * @param {Object} opts Options - * @param {Function} callback Callback - */ -Docker.prototype.searchImages = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/search?', - method: 'GET', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Info - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with info - */ -Docker.prototype.info = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/info', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Version - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.version = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/version', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Ping - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.ping = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/_ping', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * SystemDf equivalent to system/df API Engine - * get usage data information - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.df = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/system/df', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Events - * @param {Object} opts Events options, like 'since' (optional) - * @param {Function} callback Callback - */ -Docker.prototype.getEvents = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/events?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Pull is a wrapper around createImage, parsing image's tags. - * @param {String} repoTag Repository tag - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @param {Object} auth Authentication (optional) - * @return {Object} Image - */ -Docker.prototype.pull = function(repoTag, opts, callback, auth) { - var args = util.processArgs(opts, callback); - - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - args.opts.tag = imageSrc.tag || 'latest'; - - var argsf = [args.opts, args.callback]; - if (auth) { - argsf = [auth, args.opts, args.callback]; - } - return this.createImage.apply(this, argsf); -}; - -/** - * PullAll is a wrapper around createImage, to pull all image tags of an image. - * @param {String} repoTag Repository tag - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @param {Object} auth Authentication (optional) - * @return {Object} Image - */ -Docker.prototype.pullAll = function(repoTag, opts, callback, auth) { - var args = util.processArgs(opts, callback); - - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - - var argsf = [args.opts, args.callback]; - if (auth) { - argsf = [auth, args.opts, args.callback]; - } - return this.createImage.apply(this, argsf); -}; - -/** - * Like run command from Docker's CLI - * @param {String} image Image name to be used. - * @param {Array} cmd Command to run in array format. - * @param {Object} streamo Output stream - * @param {Object} createOptions Container create options (optional) - * @param {Object} startOptions Container start options (optional) - * @param {Function} callback Callback - * @return {Object} EventEmitter - */ -Docker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (typeof arguments[arguments.length - 1] === 'function') { - return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); - } else { - return this.runPromise(image, cmd, streamo, createOptions, startOptions); - } -}; - - -Docker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (!callback && typeof createOptions === 'function') { - callback = createOptions; - createOptions = {}; - startOptions = {}; - } else if (!callback && typeof startOptions === 'function') { - callback = startOptions; - startOptions = {}; - } - - var hub = new EventEmitter(); - - function handler(err, container) { - if (err) return callback(err, null, container); - - hub.emit('container', container); - - container.attach({ - stream: true, - stdout: true, - stderr: true - }, function handler(err, stream) { - if (err) return callback(err, null, container); - - hub.emit('stream', stream); - - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - container.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } - } - - container.start(startOptions, function(err, data) { - if (err) return callback(err, data, container); - hub.emit('start', container); - - container.wait(function(err, data) { - hub.emit('data', data); - callback(err, data, container); - }); - }); - }); - } - - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] - }; - - extend(optsc, createOptions); - - this.createContainer(optsc, handler); - - return hub; -}; - -Docker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { - var self = this; - - createOptions = createOptions || {}; - startOptions = startOptions || {}; - - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] - }; - - extend(optsc, createOptions); - - var containero; - - return new this.modem.Promise(function(resolve, reject) { - self.createContainer(optsc).then(function(container) { - containero = container; - return container.attach({ - stream: true, - stdout: true, - stderr: true - }); - }).then(function(stream) { - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - containero.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } - } - return containero.start(startOptions); - }).then(function(data) { - return containero.wait(); - }).then(function(data) { - resolve([data, containero]); - }).catch(function(err) { - reject(err); - }); - }); -}; - -/** - * Init swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmInit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/init', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Join swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmJoin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/join', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Leave swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmLeave = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/leave?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'node is not part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmUpdate = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Inspect a Swarm. - * Warning: This method is not documented in the API - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.swarmInspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'This node is not a swarm manager', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -Docker.Container = Container; -Docker.Image = Image; -Docker.Volume = Volume; -Docker.Network = Network; -Docker.Service = Service; -Docker.Plugin = Plugin; -Docker.Secret = Secret; -Docker.Task = Task; -Docker.Node = Node; -Docker.Exec = Exec; - -module.exports = Docker; - - -/***/ }), - -/***/ 73149: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Exec - * @param {Object} modem docker-modem - * @param {String} id Exec's ID - */ -var Exec = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Exec.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Start the exec call that was setup. - * - * @param {object} opts - * @param {function} callback - */ -Exec.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/exec/' + this.id + '/start', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - allowEmpty: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 204: true, - 404: 'no such exec', - 409: 'container stopped/paused', - 500: 'container not running' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * Resize the exec call that was setup. - * - * @param {object} opts - * @param {function} callback - */ -Exec.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/exec/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'container not running' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * Get low-level information about the exec call. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Exec.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/exec/' + this.id + '/json', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - - -module.exports = Exec; - - -/***/ }), - -/***/ 96689: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an image - * @param {Object} modem docker-modem - * @param {String} name Image's name - */ -var Image = function(modem, name) { - this.modem = modem; - this.name = name; -}; - -Image.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Inspect options, only 'manifests' (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.inspect = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - - var opts = { - path: '/images/' + this.name + '/json', - method: 'GET', - options: args.opts, - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * Distribution - * @param {Object} opts - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.distribution = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - - var fopts = { - path: '/distribution/' + this.name + '/json', - method: 'GET', - statusCodes: { - 200: true, - 401: 'no such image', - 500: 'server error' - }, - authconfig: (args.opts) ? args.opts.authconfig : undefined - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(fopts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(fopts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * History - * @param {Function} callback Callback - */ -Image.prototype.history = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/history', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; - -/** - * Get - * @param {Function} callback Callback with data stream. - */ -Image.prototype.get = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/get', - method: 'GET', - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; - -/** - * Push - * @param {Object} opts Push options, like 'registry' (optional) - * @param {Function} callback Callback with stream. - * @param {Object} auth Registry authentication - */ -Image.prototype.push = function(opts, callback, auth) { - var self = this; - var args = util.processArgs(opts, callback); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/images/' + this.name + '/push?', - method: 'POST', - options: args.opts, - authconfig: args.opts.authconfig || auth, - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - delete optsf.options.authconfig; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Tag - * @param {Object} opts Tag options, like 'repo' (optional) - * @param {Function} callback Callback - */ -Image.prototype.tag = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/' + this.name + '/tag?', - method: 'POST', - options: opts, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 400: 'bad parameter', - 404: 'no such image', - 409: 'conflict', - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Removes the image - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Image.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such image', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -module.exports = Image; - - -/***/ }), - -/***/ 39780: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an network - * @param {Object} modem docker-modem - * @param {String} id Network's id - */ -var Network = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Network.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Id only if callback isn't specified. - */ -Network.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/networks/' + this.id + '?', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such network', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes the network - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Network.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such network', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Connects a container to a network - * @param {[Object]} opts Connect options (optional) - * @param {Function} callback Callback - */ -Network.prototype.connect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/' + this.id + '/connect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Disconnects a container from a network - * @param {[Object]} opts Disconnect options (optional) - * @param {Function} callback Callback - */ -Network.prototype.disconnect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/' + this.id + '/disconnect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - - -module.exports = Network; - - -/***/ }), - -/***/ 52297: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Node - * @param {Object} modem docker-modem - * @param {String} id Node's ID - */ -var Node = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Node.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Query Docker for Node details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Node.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Update a node. - * - * @param {object} opts - * @param {function} callback - */ -Node.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - } - - var optsf = { - path: '/nodes/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 406: 'node is not part of a swarm', - 500: 'server error' - }, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - -/** - * Remove a Node. - * Warning: This method is not documented in the API. - * - * @param {object} opts - * @param {function} callback - */ -Node.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -module.exports = Node; - - -/***/ }), - -/***/ 16606: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a plugin - * @param {Object} modem docker-modem - * @param {String} name Plugin's name - */ -var Plugin = function(modem, name, remote) { - this.modem = modem; - this.name = name; - this.remote = remote || name; -}; - -Plugin.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Plugin.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/json', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes the plugin - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * get privileges - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @return {Object} Name only if callback isn't specified. - */ -Plugin.prototype.privileges = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/privileges?', - method: 'GET', - options: { - 'remote': this.remote - }, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Installs a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Plugin.prototype.pull = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - if(args.opts._query && !args.opts._query.name) { - args.opts._query.name = this.name; - } - if(args.opts._query && !args.opts._query.remote) { - args.opts._query.remote = this.remote; - } - - var optsf = { - path: '/plugins/pull?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - options: args.opts, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Enable - * @param {Object} opts Plugin enable options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.enable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/enable?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Disable - * @param {Object} opts Plugin disable options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.disable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/disable', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Push - * @param {Object} opts Plugin push options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.push = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/push', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * COnfigure - * @param {Object} opts Plugin configure options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.configure = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/set', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Upgrade plugin - * - * @param {object} auth - * @param {object} opts - * @param {function} callback - */ -Plugin.prototype.upgrade = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } - - var optsf = { - path: '/plugins/' + this.name + '/upgrade?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'plugin not installed', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - -module.exports = Plugin; - - -/***/ }), - -/***/ 79934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a secret - * @param {Object} modem docker-modem - * @param {String} id Secret's id - */ -var Secret = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Secret.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Secret.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/secrets/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 406: 'node is not part of a swarm', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update a secret. - * - * @param {object} opts - * @param {function} callback - */ -Secret.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - } - - var optsf = { - path: '/secrets/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 500: 'server error' - }, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - -/** - * Removes the secret - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Secret.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/secrets/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'secret not found', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - -module.exports = Secret; - - -/***/ }), - -/***/ 28866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Service - * @param {Object} modem docker-modem - * @param {String} id Service's ID - */ -var Service = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Service.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Query Docker for service details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Service.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Delete Service - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Service.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such service', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update service - * - * @param {object} auth - * @param {object} opts - * @param {function} callback - */ -Service.prototype.update = function(auth, opts, callback) { - var self = this; - if (!callback) { - var t = typeof opts; - if(t === 'function'){ - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (t === 'undefined'){ - opts = auth; - auth = opts.authconfig || undefined; - } - } - - var optsf = { - path: '/services/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - - -/** - * Service logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Service.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, {}); - - var optsf = { - path: '/services/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - -module.exports = Service; - - -/***/ }), - -/***/ 68304: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var grpc = __nccwpck_require__(7025), - protoLoader = __nccwpck_require__(98171), - path = __nccwpck_require__(71017), - uuid = (__nccwpck_require__(93704).v4); - -function withSession(docker, auth, handler) { - const sessionId = uuid(); - - const opts = { - method: "POST", - path: "/session", - hijack: true, - headers: { - Upgrade: "h2c", - "X-Docker-Expose-Session-Uuid": sessionId, - "X-Docker-Expose-Session-Name": "testcontainers", - }, - statusCodes: { - 200: true, - 500: "server error", - }, - }; - - docker.modem.dial(opts, function (err, socket) { - if (err) { - return handler(err, null, () => undefined); - } - - const server = new grpc.Server(); - const creds = grpc.ServerCredentials.createInsecure(); - const injector = server.createConnectionInjector(creds); - injector.injectConnection(socket); - - const pkg = protoLoader.loadSync( - __nccwpck_require__.ab + "auth.proto" - ); - const service = grpc.loadPackageDefinition(pkg); - - server.addService(service.moby.filesync.v1.Auth.service, { - Credentials({ request }, callback) { - // We probably want to have the possibility to pass credentials per - // hots. The correct one could be returned based on `request.Host` - if (auth) { - callback(null, { - Username: auth.username, - Secret: auth.password, - }); - } else { - callback(null, {}); - } - }, - }); - - function done() { - server.forceShutdown(); - socket.end(); - } - - handler(null, sessionId, done); - }); -} - -module.exports = withSession; - - -/***/ }), - -/***/ 61385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Task - * @param {Object} modem docker-modem - * @param {String} id Task's ID - */ -var Task = function(modem, id) { - this.modem = modem; - this.id = id; - - this.defaultOptions = { - log: {} - }; -}; - -Task.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Query Docker for Task details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Task.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/tasks/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'unknown task', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Task logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Task.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); - - var optsf = { - path: '/tasks/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 101: true, - 200: true, - 404: 'no such container', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -module.exports = Task; - - -/***/ }), - -/***/ 41604: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var DockerIgnore = __nccwpck_require__(3358); -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -var tar = __nccwpck_require__(366); -var zlib = __nccwpck_require__(59796); - -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js - -var arr = []; -var each = arr.forEach; -var slice = arr.slice; - -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; -}; - -module.exports.processArgs = function(opts, callback, defaultOpts) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } - return { - callback: callback, - opts: module.exports.extend({}, defaultOpts, opts) - }; -}; - - -/** - * Parse the given repo tag name (as a string) and break it out into repo/tag pair. - * // if given the input http://localhost:8080/woot:latest - * { - * repository: 'http://localhost:8080/woot', - * tag: 'latest' - * } - * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest' - * @return {Object} input parsed into the repo and tag. - */ -module.exports.parseRepositoryTag = function(input) { - var separatorPos; - var digestPos = input.indexOf('@'); - var colonPos = input.lastIndexOf(':'); - // @ symbol is more important - if (digestPos >= 0) { - separatorPos = digestPos; - } else if (colonPos >= 0) { - separatorPos = colonPos; - } else { - // no colon nor @ - return { - repository: input - }; - } - - // last colon is either the tag (or part of a port designation) - var tag = input.slice(separatorPos + 1); - - // if it contains a / its not a tag and is part of the url - if (tag.indexOf('/') === -1) { - return { - repository: input.slice(0, separatorPos), - tag: tag - }; - } - - return { - repository: input - }; -}; - - -module.exports.prepareBuildContext = function(file, next) { - if (file && file.context) { - fs.readFile(path.join(file.context, '.dockerignore'), (err, data) => { - let ignoreFn; - let filterFn; - - if (!err) { - const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString()); - - filterFn = dockerIgnore.createFilter(); - ignoreFn = (path) => { - return !filterFn(path); - } - } - - const entries = file.src.slice() || [] - - const pack = tar.pack(file.context, { - entries: filterFn ? entries.filter(filterFn) : entries, - ignore: ignoreFn // Only works on directories - }); - - next(pack.pipe(zlib.createGzip())); - }) - } else { - next(file); - } -} - - -/***/ }), - -/***/ 94877: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a volume - * @param {Object} modem docker-modem - * @param {String} name Volume's name - */ -var Volume = function(modem, name) { - this.modem = modem; - this.name = name; -}; - -Volume.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Volume.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/' + this.name, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such volume', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes the volume - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Volume.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/' + this.name, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 204: true, - 404: 'no such volume', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -module.exports = Volume; - - -/***/ }), - -/***/ 93704: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ - value: true -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _max.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _nil.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _parse.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _stringify.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v1ToV.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v2.default; - } -}); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v4.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v5.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v6ToV.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v6.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _validate.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _version.default; - } -}); -var _max = _interopRequireDefault(__nccwpck_require__(70789)); -var _nil = _interopRequireDefault(__nccwpck_require__(57358)); -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -var _stringify = _interopRequireDefault(__nccwpck_require__(91908)); -var _v = _interopRequireDefault(__nccwpck_require__(20631)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(96802)); -var _v2 = _interopRequireDefault(__nccwpck_require__(7980)); -var _v3 = _interopRequireDefault(__nccwpck_require__(26316)); -var _v4 = _interopRequireDefault(__nccwpck_require__(1858)); -var _v5 = _interopRequireDefault(__nccwpck_require__(33887)); -var _v6ToV = _interopRequireDefault(__nccwpck_require__(60553)); -var _v6 = _interopRequireDefault(__nccwpck_require__(43398)); -var _validate = _interopRequireDefault(__nccwpck_require__(45685)); -var _version = _interopRequireDefault(__nccwpck_require__(74354)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } - -/***/ }), - -/***/ 70789: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - -/***/ }), - -/***/ 12698: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('md5').update(bytes).digest(); -} -var _default = exports["default"] = md5; - -/***/ }), - -/***/ 18355: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -var _default = exports["default"] = { - randomUUID: _nodeCrypto.default.randomUUID -}; - -/***/ }), - -/***/ 57358: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; - -/***/ }), - -/***/ 70807: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(45685)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -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 = exports["default"] = parse; - -/***/ }), - -/***/ 95604: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - -/***/ }), - -/***/ 81359: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 66265: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = exports["default"] = sha1; - -/***/ }), - -/***/ 91908: -/***/ ((__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__(45685)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * 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 - // - // Note to future-self: No, you can't remove the `toLowerCase()` call. - // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 - 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]]).toLowerCase(); -} -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 = exports["default"] = stringify; - -/***/ }), - -/***/ 20631: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(81359)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -// **`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; - let clockseq = options.clockseq; - - // v1 only: Use cached `node` and `clockseq` values - if (!options._v6) { - if (!node) { - node = _nodeId; - } - if (clockseq == null) { - clockseq = _clockseq; - } - } - - // Handle cases where we need entropy. 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)(); - - // Randomize node - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - - // v1 only: cache node value for reuse - if (!_nodeId && !options._v6) { - // per RFC4122 4.5: Set MAC multicast bit (v1 only) - node[0] |= 0x01; // Set multicast bit - - _nodeId = node; - } - } - - // Randomize clockseq - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; - } - } - } - - // v1 & v6 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 = exports["default"] = v1; - -/***/ }), - -/***/ 96802: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v1ToV6; -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v1 UUID to a v6 UUID - * - * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 - * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v1ToV6(uuid) { - const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v6Bytes = _v1ToV6(v1Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; -} - -// Do the field transformation needed for v1 -> v6 -function _v1ToV6(v1Bytes, randomize = false) { - return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); -} - -/***/ }), - -/***/ 7980: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(72149)); -var _md = _interopRequireDefault(__nccwpck_require__(12698)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = exports["default"] = v3; - -/***/ }), - -/***/ 72149: -/***/ ((__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__(91908); -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -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 = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -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; - } catch (err) {} - - // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 26316: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _native = _interopRequireDefault(__nccwpck_require__(18355)); -var _rng = _interopRequireDefault(__nccwpck_require__(81359)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -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 = exports["default"] = v4; - -/***/ }), - -/***/ 1858: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(72149)); -var _sha = _interopRequireDefault(__nccwpck_require__(66265)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = exports["default"] = v5; - -/***/ }), - -/***/ 33887: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6; -var _stringify = __nccwpck_require__(91908); -var _v = _interopRequireDefault(__nccwpck_require__(20631)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(96802)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * - * @param {object} options - * @param {Uint8Array=} buf - * @param {number=} offset - * @returns - */ -function v6(options = {}, buf, offset = 0) { - // v6 is v1 with different field layout, so we start with a v1 UUID, albeit - // with slightly different behavior around how the clock_seq and node fields - // are randomized, which is why we call v1 with _v6: true. - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - - // Reorder the fields to v6 layout. - bytes = (0, _v1ToV.default)(bytes); - - // Return as a byte array if requested - if (buf) { - for (let i = 0; i < 16; i++) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); -} - -/***/ }), - -/***/ 60553: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6ToV1; -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v6 UUID to a v1 UUID - * - * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 - * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v6ToV1(uuid) { - const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v1Bytes = _v6ToV1(v6Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; -} - -// Do the field transformation needed for v6 -> v1 -function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); -} - -/***/ }), - -/***/ 43398: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(81359)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * UUID V7 - Unix Epoch time-based UUID - * - * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This - * implementation of V7 is based on the accepted, though not yet approved, - * revisions. - * - * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique - * IDentifiers (UUIDs) - - * - * Sample V7 value: - * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value - * - * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: - * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 - * - * 0 1 2 3 0 1 2 3 4 5 6 - * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | ver | seq_hi | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |var| seq_low | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit - * seq_low, and randomly initialized upon timestamp change. 31 bit counter size - * was selected as any bitwise operations in node are done as _signed_ 32 bit - * ints. we exclude the sign bit. - */ - -let _seqLow = null; -let _seqHigh = null; -let _msecs = 0; -function v7(options, buf, offset) { - options = options || {}; - - // initialize buffer and pointer - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - - // rnds is Uint8Array(16) filled with random bytes - const rnds = options.random || (options.rng || _rng.default)(); - - // milliseconds since unix epoch, 1970-01-01 00:00 - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // seq is user provided 31 bit counter - let seq = options.seq !== undefined ? options.seq : null; - - // initialize local seq high/low parts - let seqHigh = _seqHigh; - let seqLow = _seqLow; - - // check if clock has advanced and user has not provided msecs - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - - // unless user provided seq, reset seq parts - if (seq !== null) { - seqHigh = null; - seqLow = null; - } - } - - // if we have a user provided seq - if (seq !== null) { - // trim provided seq to 31 bits of value, avoiding overflow - if (seq > 0x7fffffff) { - seq = 0x7fffffff; - } - - // split provided seq into high/low parts - seqHigh = seq >>> 19 & 0xfff; - seqLow = seq & 0x7ffff; - } - - // randomly initialize seq - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 0x7f; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 0x3f; // pad for var - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; - } - - // increment seq if within msecs window - if (msecs + 10000 > _msecs && seq === null) { - if (++seqLow > 0x7ffff) { - seqLow = 0; - if (++seqHigh > 0xfff) { - seqHigh = 0; - - // increment internal _msecs. this allows us to continue incrementing - // while staying monotonic. Note, once we hit 10k milliseconds beyond system - // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) - _msecs++; - } - } - } else { - // resetting; we have advanced more than - // 10k milliseconds beyond system clock - _msecs = msecs; - } - _seqHigh = seqHigh; - _seqLow = seqLow; - - // [bytes 0-5] 48 bits of local timestamp - b[i++] = _msecs / 0x10000000000 & 0xff; - b[i++] = _msecs / 0x100000000 & 0xff; - b[i++] = _msecs / 0x1000000 & 0xff; - b[i++] = _msecs / 0x10000 & 0xff; - b[i++] = _msecs / 0x100 & 0xff; - b[i++] = _msecs & 0xff; - - // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi - b[i++] = seqHigh >>> 4 & 0x0f | 0x70; - - // [byte 7] remaining 8 bits of seq_hi - b[i++] = seqHigh & 0xff; - - // [byte 8] - variant (2 bits), first 6 bits seq_low - b[i++] = seqLow >>> 13 & 0x3f | 0x80; - - // [byte 9] 8 bits seq_low - b[i++] = seqLow >>> 5 & 0xff; - - // [byte 10] remaining 5 bits seq_low, 3 bits random - b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; - - // [bytes 11-15] always random - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v7; - -/***/ }), - -/***/ 45685: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(95604)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} -var _default = exports["default"] = validate; - -/***/ }), - -/***/ 74354: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(45685)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - return parseInt(uuid.slice(14, 15), 16); -} -var _default = exports["default"] = version; - -/***/ }), - -/***/ 12437: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const fs = __nccwpck_require__(57147) -const path = __nccwpck_require__(71017) -const os = __nccwpck_require__(22037) -const crypto = __nccwpck_require__(6113) -const packageJson = __nccwpck_require__(49968) - -const version = packageJson.version - -const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg - -// Parse src into an Object -function parse (src) { - const obj = {} - - // Convert buffer to string - let lines = src.toString() - - // Convert line breaks to same format - lines = lines.replace(/\r\n?/mg, '\n') - - let match - while ((match = LINE.exec(lines)) != null) { - const key = match[1] - - // Default undefined or null to empty string - let value = (match[2] || '') - - // Remove whitespace - value = value.trim() - - // Check if double quoted - const maybeQuote = value[0] - - // Remove surrounding quotes - value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2') - - // Expand newlines if double quoted - if (maybeQuote === '"') { - value = value.replace(/\\n/g, '\n') - value = value.replace(/\\r/g, '\r') - } - - // Add to object - obj[key] = value - } - - return obj -} - -function _parseVault (options) { - options = options || {} - - const vaultPath = _vaultPath(options) - options.path = vaultPath // parse .env.vault - const result = DotenvModule.configDotenv(options) - if (!result.parsed) { - const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`) - err.code = 'MISSING_DATA' - throw err - } - - // handle scenario for comma separated keys - for use with key rotation - // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod" - const keys = _dotenvKey(options).split(',') - const length = keys.length - - let decrypted - for (let i = 0; i < length; i++) { - try { - // Get full key - const key = keys[i].trim() - - // Get instructions for decrypt - const attrs = _instructions(result, key) - - // Decrypt - decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key) - - break - } catch (error) { - // last key - if (i + 1 >= length) { - throw error - } - // try next key - } - } - - // Parse decrypted .env string - return DotenvModule.parse(decrypted) -} - -function _warn (message) { - console.log(`[dotenv@${version}][WARN] ${message}`) -} - -function _debug (message) { - console.log(`[dotenv@${version}][DEBUG] ${message}`) -} - -function _log (message) { - console.log(`[dotenv@${version}] ${message}`) -} - -function _dotenvKey (options) { - // prioritize developer directly setting options.DOTENV_KEY - if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { - return options.DOTENV_KEY - } - - // secondary infra already contains a DOTENV_KEY environment variable - if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { - return process.env.DOTENV_KEY - } - - // fallback to empty string - return '' -} - -function _instructions (result, dotenvKey) { - // Parse DOTENV_KEY. Format is a URI - let uri - try { - uri = new URL(dotenvKey) - } catch (error) { - if (error.code === 'ERR_INVALID_URL') { - const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development') - err.code = 'INVALID_DOTENV_KEY' - throw err - } - - throw error - } - - // Get decrypt key - const key = uri.password - if (!key) { - const err = new Error('INVALID_DOTENV_KEY: Missing key part') - err.code = 'INVALID_DOTENV_KEY' - throw err - } - - // Get environment - const environment = uri.searchParams.get('environment') - if (!environment) { - const err = new Error('INVALID_DOTENV_KEY: Missing environment part') - err.code = 'INVALID_DOTENV_KEY' - throw err - } - - // Get ciphertext payload - const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}` - const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION - if (!ciphertext) { - const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`) - err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT' - throw err - } - - return { ciphertext, key } -} - -function _vaultPath (options) { - let possibleVaultPath = null - - if (options && options.path && options.path.length > 0) { - if (Array.isArray(options.path)) { - for (const filepath of options.path) { - if (fs.existsSync(filepath)) { - possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault` - } - } - } else { - possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault` - } - } else { - possibleVaultPath = path.resolve(process.cwd(), '.env.vault') - } - - if (fs.existsSync(possibleVaultPath)) { - return possibleVaultPath - } - - return null -} - -function _resolveHome (envPath) { - return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath -} - -function _configVault (options) { - const debug = Boolean(options && options.debug) - const quiet = options && 'quiet' in options ? options.quiet : true - - if (debug || !quiet) { - _log('Loading env from encrypted .env.vault') - } - - const parsed = DotenvModule._parseVault(options) - - let processEnv = process.env - if (options && options.processEnv != null) { - processEnv = options.processEnv - } - - DotenvModule.populate(processEnv, parsed, options) - - return { parsed } -} - -function configDotenv (options) { - const dotenvPath = path.resolve(process.cwd(), '.env') - let encoding = 'utf8' - const debug = Boolean(options && options.debug) - const quiet = options && 'quiet' in options ? options.quiet : true - - if (options && options.encoding) { - encoding = options.encoding - } else { - if (debug) { - _debug('No encoding is specified. UTF-8 is used by default') - } - } - - let optionPaths = [dotenvPath] // default, look for .env - if (options && options.path) { - if (!Array.isArray(options.path)) { - optionPaths = [_resolveHome(options.path)] - } else { - optionPaths = [] // reset default - for (const filepath of options.path) { - optionPaths.push(_resolveHome(filepath)) - } - } - } - - // Build the parsed data in a temporary object (because we need to return it). Once we have the final - // parsed data, we will combine it with process.env (or options.processEnv if provided). - let lastError - const parsedAll = {} - for (const path of optionPaths) { - try { - // Specifying an encoding returns a string instead of a buffer - const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding })) - - DotenvModule.populate(parsedAll, parsed, options) - } catch (e) { - if (debug) { - _debug(`Failed to load ${path} ${e.message}`) - } - lastError = e - } - } - - let processEnv = process.env - if (options && options.processEnv != null) { - processEnv = options.processEnv - } - - DotenvModule.populate(processEnv, parsedAll, options) - - if (debug || !quiet) { - const keysCount = Object.keys(parsedAll).length - const shortPaths = [] - for (const filePath of optionPaths) { - try { - const relative = path.relative(process.cwd(), filePath) - shortPaths.push(relative) - } catch (e) { - if (debug) { - _debug(`Failed to load ${filePath} ${e.message}`) - } - lastError = e - } - } - - _log(`injecting env (${keysCount}) from ${shortPaths.join(',')}`) - } - - if (lastError) { - return { parsed: parsedAll, error: lastError } - } else { - return { parsed: parsedAll } - } -} - -// Populates process.env from .env file -function config (options) { - // fallback to original dotenv if DOTENV_KEY is not set - if (_dotenvKey(options).length === 0) { - return DotenvModule.configDotenv(options) - } - - const vaultPath = _vaultPath(options) - - // dotenvKey exists but .env.vault file does not exist - if (!vaultPath) { - _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`) - - return DotenvModule.configDotenv(options) - } - - return DotenvModule._configVault(options) -} - -function decrypt (encrypted, keyStr) { - const key = Buffer.from(keyStr.slice(-64), 'hex') - let ciphertext = Buffer.from(encrypted, 'base64') - - const nonce = ciphertext.subarray(0, 12) - const authTag = ciphertext.subarray(-16) - ciphertext = ciphertext.subarray(12, -16) - - try { - const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce) - aesgcm.setAuthTag(authTag) - return `${aesgcm.update(ciphertext)}${aesgcm.final()}` - } catch (error) { - const isRange = error instanceof RangeError - const invalidKeyLength = error.message === 'Invalid key length' - const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data' - - if (isRange || invalidKeyLength) { - const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)') - err.code = 'INVALID_DOTENV_KEY' - throw err - } else if (decryptionFailed) { - const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY') - err.code = 'DECRYPTION_FAILED' - throw err - } else { - throw error - } - } -} - -// Populate process.env with parsed values -function populate (processEnv, parsed, options = {}) { - const debug = Boolean(options && options.debug) - const override = Boolean(options && options.override) - - if (typeof parsed !== 'object') { - const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate') - err.code = 'OBJECT_REQUIRED' - throw err - } - - // Set process.env - for (const key of Object.keys(parsed)) { - if (Object.prototype.hasOwnProperty.call(processEnv, key)) { - if (override === true) { - processEnv[key] = parsed[key] - } - - if (debug) { - if (override === true) { - _debug(`"${key}" is already defined and WAS overwritten`) - } else { - _debug(`"${key}" is already defined and was NOT overwritten`) - } - } - } else { - processEnv[key] = parsed[key] - } - } -} - -const DotenvModule = { - configDotenv, - _configVault, - _parseVault, - config, - decrypt, - parse, - populate -} - -module.exports.configDotenv = DotenvModule.configDotenv -module.exports._configVault = DotenvModule._configVault -module.exports._parseVault = DotenvModule._parseVault -module.exports.config = DotenvModule.config -module.exports.decrypt = DotenvModule.decrypt -module.exports.parse = DotenvModule.parse -module.exports.populate = DotenvModule.populate - -module.exports = DotenvModule - - -/***/ }), - -/***/ 62693: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var callBind = __nccwpck_require__(86815); -var gOPD = __nccwpck_require__(18501); - -var hasProtoAccessor; -try { - // eslint-disable-next-line no-extra-parens, no-proto - hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; -} catch (e) { - if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { - throw e; - } -} - -// eslint-disable-next-line no-extra-parens -var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); - -var $Object = Object; -var $getPrototypeOf = $Object.getPrototypeOf; - -/** @type {import('./get')} */ -module.exports = desc && typeof desc.get === 'function' - ? callBind([desc.get]) - : typeof $getPrototypeOf === 'function' - ? /** @type {import('./get')} */ function getDunder(value) { - // eslint-disable-next-line eqeqeq - return $getPrototypeOf(value == null ? value : $Object(value)); - } - : false; - - -/***/ }), - -/***/ 18212: -/***/ ((module) => { - -module.exports = () => { - // https://mths.be/emoji - return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; -}; - - -/***/ }), - -/***/ 81205: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223); - -var noop = function() {}; - -var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process); - -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() { - qnt(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; - - -/***/ }), - -/***/ 6123: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('.')} */ -var $defineProperty = Object.defineProperty || false; -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = false; - } -} - -module.exports = $defineProperty; - - -/***/ }), - -/***/ 91933: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./eval')} */ -module.exports = EvalError; - - -/***/ }), - -/***/ 28015: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('.')} */ -module.exports = Error; - - -/***/ }), - -/***/ 54415: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./range')} */ -module.exports = RangeError; - - -/***/ }), - -/***/ 46279: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./ref')} */ -module.exports = ReferenceError; - - -/***/ }), - -/***/ 75474: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./syntax')} */ -module.exports = SyntaxError; - - -/***/ }), - -/***/ 6361: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./type')} */ -module.exports = TypeError; - - -/***/ }), - -/***/ 5065: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./uri')} */ -module.exports = URIError; - - -/***/ }), - -/***/ 78308: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('.')} */ -module.exports = Object; - - -/***/ }), - -/***/ 11770: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var GetIntrinsic = __nccwpck_require__(74538); - -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); - -var hasToStringTag = __nccwpck_require__(99038)(); -var hasOwn = __nccwpck_require__(62157); -var $TypeError = __nccwpck_require__(6361); - -var toStringTag = hasToStringTag ? Symbol.toStringTag : null; - -/** @type {import('.')} */ -module.exports = function setToStringTag(object, value) { - var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; - var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; - if ( - (typeof overrideIfSet !== 'undefined' && typeof overrideIfSet !== 'boolean') - || (typeof nonConfigurable !== 'undefined' && typeof nonConfigurable !== 'boolean') - ) { - throw new $TypeError('if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans'); - } - if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) { - if ($defineProperty) { - $defineProperty(object, toStringTag, { - configurable: !nonConfigurable, - enumerable: false, - value: value, - writable: false - }); - } else { - object[toStringTag] = value; // eslint-disable-line no-param-reassign - } - } -}; - - -/***/ }), - -/***/ 31133: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var debug; - -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __nccwpck_require__(38237)("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; - } - } - debug.apply(null, arguments); -}; - - -/***/ }), - -/***/ 67707: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var url = __nccwpck_require__(57310); -var URL = url.URL; -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var Writable = (__nccwpck_require__(12781).Writable); -var assert = __nccwpck_require__(39491); -var debug = __nccwpck_require__(31133); - -// Preventive platform detection -// istanbul ignore next -(function detectUnsupportedEnvironment() { - var looksLikeNode = typeof process !== "undefined"; - var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; - var looksLikeV8 = isFunction(Error.captureStackTrace); - if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { - console.warn("The follow-redirects package should be excluded from browser builds."); - } -}()); - -// Whether to use the native URL object or the legacy url module -var useNativeURL = false; -try { - assert(new URL("")); -} -catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; -} - -// URL fields to preserve in copy operations -var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash", -]; - -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); - -// Error types with codes -var InvalidUrlError = createErrorType( - "ERR_INVALID_URL", - "Invalid URL", - TypeError -); -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// istanbul ignore next -var destroy = Writable.prototype.destroy || noop; - -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } - - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - try { - self._processResponse(response); - } - catch (cause) { - self.emit("error", cause instanceof RedirectionError ? - cause : new RedirectionError({ cause: cause })); - } - }; - - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); - -RedirectableRequest.prototype.abort = function () { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); -}; - -RedirectableRequest.prototype.destroy = function (error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; -}; - -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - - // Validate input and shift parameters if necessary - if (!isString(data) && !isBuffer(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; - -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (isFunction(data)) { - callback = data; - data = encoding = null; - } - else if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; - -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; - -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; - -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } - - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } - - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - self.removeListener("close", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } - - // Attach callback if passed - if (callback) { - this.on("timeout", callback); - } - - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } - - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); - - return this; -}; - -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); - -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); - -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } - - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; - - -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } - - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } - - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } - - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._options.path; - - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - // istanbul ignore else - if (request === self._currentRequest) { - // Report any write errors - // istanbul ignore if - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - // istanbul ignore else - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; - -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - - // Clean up - this._requestBodyBuffers = []; - return; - } - - // The response is a redirect, so abort the current request - destroyRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); - } - - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } - - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = parseUrl(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); - - // Create the redirected request - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); - - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrl.protocol !== currentUrlParts.protocol && - redirectUrl.protocol !== "https:" || - redirectUrl.host !== currentHost && - !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); - } - - // Evaluate the beforeRedirect callback - if (isFunction(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); - } - - // Perform the redirected request - this._performRequest(); -}; - -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters, ensuring that input is an object - if (isURL(input)) { - input = spreadUrlObject(input); - } - else if (isString(input)) { - input = spreadUrlObject(parseUrl(input)); - } - else { - callback = options; - options = validateUrl(input); - input = { protocol: protocol }; - } - if (isFunction(options)) { - callback = options; - options = null; - } - - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString(options.host) && !isString(options.hostname)) { - options.hostname = "::1"; - } - - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } - - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} - -function noop() { /* empty */ } - -function parseUrl(input) { - var parsed; - // istanbul ignore else - if (useNativeURL) { - parsed = new URL(input); - } - else { - // Ensure the URL is valid and absolute - parsed = validateUrl(url.parse(input)); - if (!isString(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; -} - -function resolveUrl(relative, base) { - // istanbul ignore next - return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); -} - -function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; -} - -function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } - - // Fix IPv6 hostname - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - // Ensure port is a number - if (spread.port !== "") { - spread.port = Number(spread.port); - } - // Concatenate path - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; - - return spread; -} - -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} - -function createErrorType(code, message, baseClass) { - // Create constructor - function CustomError(properties) { - // istanbul ignore else - if (isFunction(Error.captureStackTrace)) { - Error.captureStackTrace(this, this.constructor); - } - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } - - // Attach constructor and set default properties - CustomError.prototype = new (baseClass || Error)(); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false, - }, - name: { - value: "Error [" + code + "]", - enumerable: false, - }, - }); - return CustomError; -} - -function destroyRequest(request, error) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); - } - request.on("error", noop); - request.destroy(error); -} - -function isSubdomain(subdomain, domain) { - assert(isString(subdomain) && isString(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} - -function isString(value) { - return typeof value === "string" || value instanceof String; -} - -function isFunction(value) { - return typeof value === "function"; -} - -function isBuffer(value) { - return typeof value === "object" && ("length" in value); -} - -function isURL(value) { - return URL && value instanceof URL; -} - -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; - - -/***/ }), - -/***/ 73186: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = (__nccwpck_require__(57147).constants) || __nccwpck_require__(22057) - - -/***/ }), - -/***/ 19320: -/***/ ((module) => { - -"use strict"; - - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var toStr = Object.prototype.toString; -var max = Math.max; -var funcType = '[object Function]'; - -var concatty = function concatty(a, b) { - var arr = []; - - for (var i = 0; i < a.length; i += 1) { - arr[i] = a[i]; - } - for (var j = 0; j < b.length; j += 1) { - arr[j + a.length] = b[j]; - } - - return arr; -}; - -var slicy = function slicy(arrLike, offset) { - var arr = []; - for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { - arr[j] = arrLike[i]; - } - return arr; -}; - -var joiny = function (arr, joiner) { - var str = ''; - for (var i = 0; i < arr.length; i += 1) { - str += arr[i]; - if (i + 1 < arr.length) { - str += joiner; - } - } - return str; -}; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - - }; - - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs[i] = '$' + i; - } - - bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - - -/***/ }), - -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var implementation = __nccwpck_require__(19320); - -module.exports = Function.prototype.bind || implementation; - - -/***/ }), - -/***/ 74538: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var undefined; - -var $Object = __nccwpck_require__(78308); - -var $Error = __nccwpck_require__(28015); -var $EvalError = __nccwpck_require__(91933); -var $RangeError = __nccwpck_require__(54415); -var $ReferenceError = __nccwpck_require__(46279); -var $SyntaxError = __nccwpck_require__(75474); -var $TypeError = __nccwpck_require__(6361); -var $URIError = __nccwpck_require__(5065); - -var abs = __nccwpck_require__(19775); -var floor = __nccwpck_require__(60924); -var max = __nccwpck_require__(52419); -var min = __nccwpck_require__(73373); -var pow = __nccwpck_require__(78029); -var round = __nccwpck_require__(59396); -var sign = __nccwpck_require__(39091); - -var $Function = Function; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = __nccwpck_require__(18501); -var $defineProperty = __nccwpck_require__(6123); - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = __nccwpck_require__(40587)(); - -var getProto = __nccwpck_require__(13592); -var $ObjectGPO = __nccwpck_require__(5045); -var $ReflectGPO = __nccwpck_require__(78859); - -var $apply = __nccwpck_require__(54177); -var $call = __nccwpck_require__(2808); - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - __proto__: null, - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, - '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': $Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': $EvalError, - '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': $Object, - '%Object.getOwnPropertyDescriptor%': $gOPD, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': $RangeError, - '%ReferenceError%': $ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': $URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, - - '%Function.prototype.call%': $call, - '%Function.prototype.apply%': $apply, - '%Object.defineProperty%': $defineProperty, - '%Object.getPrototypeOf%': $ObjectGPO, - '%Math.abs%': abs, - '%Math.floor%': floor, - '%Math.max%': max, - '%Math.min%': min, - '%Math.pow%': pow, - '%Math.round%': round, - '%Math.sign%': sign, - '%Reflect.getPrototypeOf%': $ReflectGPO -}; - -if (getProto) { - try { - null.error; // eslint-disable-line no-unused-expressions - } catch (e) { - // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 - var errorProto = getProto(getProto(e)); - INTRINSICS['%Error.prototype%'] = errorProto; - } -} - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen && getProto) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - __proto__: null, - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = __nccwpck_require__(88334); -var hasOwn = __nccwpck_require__(62157); -var $concat = bind.call($call, Array.prototype.concat); -var $spliceApply = bind.call($apply, Array.prototype.splice); -var $replace = bind.call($call, String.prototype.replace); -var $strSlice = bind.call($call, String.prototype.slice); -var $exec = bind.call($call, RegExp.prototype.exec); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - if ($exec(/^%?[^%]*%?$/, name) === null) { - throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); - } - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - - -/***/ }), - -/***/ 5045: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var $Object = __nccwpck_require__(78308); - -/** @type {import('./Object.getPrototypeOf')} */ -module.exports = $Object.getPrototypeOf || null; - - -/***/ }), - -/***/ 78859: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./Reflect.getPrototypeOf')} */ -module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; - - -/***/ }), - -/***/ 13592: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var reflectGetProto = __nccwpck_require__(78859); -var originalGetProto = __nccwpck_require__(5045); - -var getDunderProto = __nccwpck_require__(62693); - -/** @type {import('.')} */ -module.exports = reflectGetProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return reflectGetProto(O); - } - : originalGetProto - ? function getProto(O) { - if (!O || (typeof O !== 'object' && typeof O !== 'function')) { - throw new TypeError('getProto: not an object'); - } - // @ts-expect-error TS can't narrow inside a closure, for some reason - return originalGetProto(O); - } - : getDunderProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return getDunderProto(O); - } - : null; - - -/***/ }), - -/***/ 57087: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./gOPD')} */ -module.exports = Object.getOwnPropertyDescriptor; - - -/***/ }), - -/***/ 18501: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/** @type {import('.')} */ -var $gOPD = __nccwpck_require__(57087); - -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - - -/***/ }), - -/***/ 40587: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = __nccwpck_require__(57747); - -/** @type {import('.')} */ -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - - -/***/ }), - -/***/ 57747: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./shams')} */ -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - /** @type {{ [k in symbol]?: unknown }} */ - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - // eslint-disable-next-line no-extra-parens - var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - - -/***/ }), - -/***/ 99038: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var hasSymbols = __nccwpck_require__(57747); - -/** @type {import('.')} */ -module.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; -}; - - -/***/ }), - -/***/ 62157: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var call = Function.prototype.call; -var $hasOwn = Object.prototype.hasOwnProperty; -var bind = __nccwpck_require__(88334); - -/** @type {import('.')} */ -module.exports = bind.call(call, $hasOwn); - - -/***/ }), - -/***/ 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 - } - } -} - - -/***/ }), - -/***/ 64882: -/***/ ((module) => { - -"use strict"; -/* eslint-disable yoda */ - - -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } - - return false; -}; - -module.exports = isFullwidthCodePoint; -module.exports["default"] = isFullwidthCodePoint; - - -/***/ }), - -/***/ 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 -}); - - -/***/ }), - -/***/ 7994: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** Used to match words composed of alphanumeric characters. */ -var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - -/** Used to match Latin Unicode letters (excluding mathematical operators). */ -var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', - rsComboSymbolsRange = '\\u20d0-\\u20f0', - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - -/** Used to compose unicode capture groups. */ -var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - -/** Used to compose unicode regexes. */ -var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', - rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match apostrophes. */ -var reApos = RegExp(rsApos, 'g'); - -/** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ -var reComboMark = RegExp(rsCombo, 'g'); - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** Used to match complex or compound words. */ -var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', - rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, - rsUpper + '+' + rsOptUpperContr, - rsDigits, - rsEmoji -].join('|'), 'g'); - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); - -/** Used to detect strings that need a more robust regexp to match words. */ -var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - -/** Used to map Latin Unicode letters to basic Latin letters. */ -var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 'ss' -}; - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ -function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; -} - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -/** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function asciiWords(string) { - return string.match(reAsciiWord) || []; -} - -/** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; -} - -/** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ -var deburrLetter = basePropertyOf(deburredLetters); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ -function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function unicodeWords(string) { - return string.match(reUnicodeWord) || []; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var Symbol = root.Symbol; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} - -/** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ -function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; -} - -/** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ -function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {string} Returns the string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ -var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); -}); - -/** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ -function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); -} - -/** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('dĆ©jĆ  vu'); - * // => 'deja vu' - */ -function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); -} - -/** - * Converts the first character of `string` to upper case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.upperFirst('fred'); - * // => 'Fred' - * - * _.upperFirst('FRED'); - * // => 'FRED' - */ -var upperFirst = createCaseFirst('toUpperCase'); - -/** - * Splits `string` into an array of its words. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {RegExp|string} [pattern] The pattern to match words. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the words of `string`. - * @example - * - * _.words('fred, barney, & pebbles'); - * // => ['fred', 'barney', 'pebbles'] - * - * _.words('fred, barney, & pebbles', /[^, ]+/g); - * // => ['fred', 'barney', '&', 'pebbles'] - */ -function words(string, pattern, guard) { - string = toString(string); - pattern = guard ? undefined : pattern; - - if (pattern === undefined) { - return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); - } - return string.match(pattern) || []; -} - -module.exports = camelCase; - - -/***/ }), - -/***/ 19775: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./abs')} */ -module.exports = Math.abs; - - -/***/ }), - -/***/ 60924: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./floor')} */ -module.exports = Math.floor; - - -/***/ }), - -/***/ 57661: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./isNaN')} */ -module.exports = Number.isNaN || function isNaN(a) { - return a !== a; -}; - - -/***/ }), - -/***/ 52419: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./max')} */ -module.exports = Math.max; - - -/***/ }), - -/***/ 73373: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./min')} */ -module.exports = Math.min; - - -/***/ }), - -/***/ 78029: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./pow')} */ -module.exports = Math.pow; - - -/***/ }), - -/***/ 59396: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./round')} */ -module.exports = Math.round; - - -/***/ }), - -/***/ 39091: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var $isNaN = __nccwpck_require__(57661); - -/** @type {import('./sign')} */ -module.exports = function sign(number) { - if ($isNaN(number) || number === 0) { - return number; - } - return number < 0 ? -1 : +1; -}; - - -/***/ }), - -/***/ 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 - } - }) -} - - -/***/ }), - -/***/ 97614: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; - - -/***/ }), - -/***/ 80900: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - -/***/ }), - -/***/ 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 -} - - -/***/ }), - -/***/ 21629: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - -var $protobuf = __nccwpck_require__(85881); -module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(__nccwpck_require__(43571)).lookup(".google.protobuf"); - -var Namespace = $protobuf.Namespace, - Root = $protobuf.Root, - Enum = $protobuf.Enum, - Type = $protobuf.Type, - Field = $protobuf.Field, - MapField = $protobuf.MapField, - OneOf = $protobuf.OneOf, - Service = $protobuf.Service, - Method = $protobuf.Method; - -// --- Root --- - -/** - * Properties of a FileDescriptorSet message. - * @interface IFileDescriptorSet - * @property {IFileDescriptorProto[]} file Files - */ - -/** - * Properties of a FileDescriptorProto message. - * @interface IFileDescriptorProto - * @property {string} [name] File name - * @property {string} [package] Package - * @property {*} [dependency] Not supported - * @property {*} [publicDependency] Not supported - * @property {*} [weakDependency] Not supported - * @property {IDescriptorProto[]} [messageType] Nested message types - * @property {IEnumDescriptorProto[]} [enumType] Nested enums - * @property {IServiceDescriptorProto[]} [service] Nested services - * @property {IFieldDescriptorProto[]} [extension] Nested extension fields - * @property {IFileOptions} [options] Options - * @property {*} [sourceCodeInfo] Not supported - * @property {string} [syntax="proto2"] Syntax - * @property {IEdition} [edition] Edition - */ - -/** - * Values of the Edition enum. - * @typedef IEdition - * @type {number} - * @property {number} EDITION_UNKNOWN=0 - * @property {number} EDITION_LEGACY=900 - * @property {number} EDITION_PROTO2=998 - * @property {number} EDITION_PROTO3=999 - * @property {number} EDITION_2023=1000 - * @property {number} EDITION_2024=1001 - * @property {number} EDITION_1_TEST_ONLY=1 - * @property {number} EDITION_2_TEST_ONLY=2 - * @property {number} EDITION_99997_TEST_ONLY=99997 - * @property {number} EDITION_99998_TEST_ONLY=99998 - * @property {number} EDITION_99998_TEST_ONLY=99999 - * @property {number} EDITION_MAX=2147483647 - */ - -/** - * Properties of a FileOptions message. - * @interface IFileOptions - * @property {string} [javaPackage] - * @property {string} [javaOuterClassname] - * @property {boolean} [javaMultipleFiles] - * @property {boolean} [javaGenerateEqualsAndHash] - * @property {boolean} [javaStringCheckUtf8] - * @property {IFileOptionsOptimizeMode} [optimizeFor=1] - * @property {string} [goPackage] - * @property {boolean} [ccGenericServices] - * @property {boolean} [javaGenericServices] - * @property {boolean} [pyGenericServices] - * @property {boolean} [deprecated] - * @property {boolean} [ccEnableArenas] - * @property {string} [objcClassPrefix] - * @property {string} [csharpNamespace] - */ - -/** - * Values of he FileOptions.OptimizeMode enum. - * @typedef IFileOptionsOptimizeMode - * @type {number} - * @property {number} SPEED=1 - * @property {number} CODE_SIZE=2 - * @property {number} LITE_RUNTIME=3 - */ - -/** - * Creates a root from a descriptor set. - * @param {IFileDescriptorSet|Reader|Uint8Array} descriptor Descriptor - * @returns {Root} Root instance - */ -Root.fromDescriptor = function fromDescriptor(descriptor) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.FileDescriptorSet.decode(descriptor); - - var root = new Root(); - - if (descriptor.file) { - var fileDescriptor, - filePackage; - for (var j = 0, i; j < descriptor.file.length; ++j) { - filePackage = root; - if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) - filePackage = root.define(fileDescriptor["package"]); - var edition = editionFromDescriptor(fileDescriptor); - if (fileDescriptor.name && fileDescriptor.name.length) - root.files.push(filePackage.filename = fileDescriptor.name); - if (fileDescriptor.messageType) - for (i = 0; i < fileDescriptor.messageType.length; ++i) - filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], edition)); - if (fileDescriptor.enumType) - for (i = 0; i < fileDescriptor.enumType.length; ++i) - filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition)); - if (fileDescriptor.extension) - for (i = 0; i < fileDescriptor.extension.length; ++i) - filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition)); - if (fileDescriptor.service) - for (i = 0; i < fileDescriptor.service.length; ++i) - filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition)); - var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions); - if (opts) { - var ks = Object.keys(opts); - for (i = 0; i < ks.length; ++i) - filePackage.setOption(ks[i], opts[ks[i]]); - } - } - } - - return root.resolveAll(); -}; - -/** - * Converts a root to a descriptor set. - * @returns {Message} Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - */ -Root.prototype.toDescriptor = function toDescriptor(edition) { - var set = exports.FileDescriptorSet.create(); - Root_toDescriptorRecursive(this, set.file, edition); - return set; -}; - -// Traverses a namespace and assembles the descriptor set -function Root_toDescriptorRecursive(ns, files, edition) { - - // Create a new file - var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); - editionToDescriptor(edition, file); - if (!(ns instanceof Root)) - file["package"] = ns.fullName.substring(1); - - // Add nested types - for (var i = 0, nested; i < ns.nestedArray.length; ++i) - if ((nested = ns._nestedArray[i]) instanceof Type) - file.messageType.push(nested.toDescriptor(edition)); - else if (nested instanceof Enum) - file.enumType.push(nested.toDescriptor()); - else if (nested instanceof Field) - file.extension.push(nested.toDescriptor(edition)); - else if (nested instanceof Service) - file.service.push(nested.toDescriptor()); - else if (nested instanceof /* plain */ Namespace) - Root_toDescriptorRecursive(nested, files, edition); // requires new file - - // Keep package-level options - file.options = toDescriptorOptions(ns.options, exports.FileOptions); - - // And keep the file only if there is at least one nested object - if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) - files.push(file); -} - -// --- Type --- - -/** - * Properties of a DescriptorProto message. - * @interface IDescriptorProto - * @property {string} [name] Message type name - * @property {IFieldDescriptorProto[]} [field] Fields - * @property {IFieldDescriptorProto[]} [extension] Extension fields - * @property {IDescriptorProto[]} [nestedType] Nested message types - * @property {IEnumDescriptorProto[]} [enumType] Nested enums - * @property {IDescriptorProtoExtensionRange[]} [extensionRange] Extension ranges - * @property {IOneofDescriptorProto[]} [oneofDecl] Oneofs - * @property {IMessageOptions} [options] Not supported - * @property {IDescriptorProtoReservedRange[]} [reservedRange] Reserved ranges - * @property {string[]} [reservedName] Reserved names - */ - -/** - * Properties of a MessageOptions message. - * @interface IMessageOptions - * @property {boolean} [mapEntry=false] Whether this message is a map entry - */ - -/** - * Properties of an ExtensionRange message. - * @interface IDescriptorProtoExtensionRange - * @property {number} [start] Start field id - * @property {number} [end] End field id - */ - -/** - * Properties of a ReservedRange message. - * @interface IDescriptorProtoReservedRange - * @property {number} [start] Start field id - * @property {number} [end] End field id - */ - -var unnamedMessageIndex = 0; - -/** - * Creates a type from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a nested object - * @returns {Type} Type instance - */ -Type.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.DescriptorProto.decode(descriptor); - - // Create the message type - var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)), - i; - - if (!nested) - type._edition = edition; - - /* Oneofs */ if (descriptor.oneofDecl) - for (i = 0; i < descriptor.oneofDecl.length; ++i) - type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); - /* Fields */ if (descriptor.field) - for (i = 0; i < descriptor.field.length; ++i) { - var field = Field.fromDescriptor(descriptor.field[i], edition, true); - type.add(field); - if (descriptor.field[i].hasOwnProperty("oneofIndex")) // eslint-disable-line no-prototype-builtins - type.oneofsArray[descriptor.field[i].oneofIndex].add(field); - } - /* Extension fields */ if (descriptor.extension) - for (i = 0; i < descriptor.extension.length; ++i) - type.add(Field.fromDescriptor(descriptor.extension[i], edition, true)); - /* Nested types */ if (descriptor.nestedType) - for (i = 0; i < descriptor.nestedType.length; ++i) { - type.add(Type.fromDescriptor(descriptor.nestedType[i], edition, true)); - if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) - type.setOption("map_entry", true); - } - /* Nested enums */ if (descriptor.enumType) - for (i = 0; i < descriptor.enumType.length; ++i) - type.add(Enum.fromDescriptor(descriptor.enumType[i], edition, true)); - /* Extension ranges */ if (descriptor.extensionRange && descriptor.extensionRange.length) { - type.extensions = []; - for (i = 0; i < descriptor.extensionRange.length; ++i) - type.extensions.push([ descriptor.extensionRange[i].start, descriptor.extensionRange[i].end ]); - } - /* Reserved... */ if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { - type.reserved = []; - /* Ranges */ if (descriptor.reservedRange) - for (i = 0; i < descriptor.reservedRange.length; ++i) - type.reserved.push([ descriptor.reservedRange[i].start, descriptor.reservedRange[i].end ]); - /* Names */ if (descriptor.reservedName) - for (i = 0; i < descriptor.reservedName.length; ++i) - type.reserved.push(descriptor.reservedName[i]); - } - - return type; -}; - -/** - * Converts a type to a descriptor. - * @returns {Message} Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - */ -Type.prototype.toDescriptor = function toDescriptor(edition) { - var descriptor = exports.DescriptorProto.create({ name: this.name }), - i; - - /* Fields */ for (i = 0; i < this.fieldsArray.length; ++i) { - var fieldDescriptor; - descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition)); - if (this._fieldsArray[i] instanceof MapField) { // map fields are repeated FieldNameEntry - var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), - valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), - valueTypeName = valueType === /* type */ 11 || valueType === /* enum */ 14 - ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type - : undefined; - descriptor.nestedType.push(exports.DescriptorProto.create({ - name: fieldDescriptor.typeName, - field: [ - exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), // can't reference a type or enum - exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) - ], - options: exports.MessageOptions.create({ mapEntry: true }) - })); - } - } - /* Oneofs */ for (i = 0; i < this.oneofsArray.length; ++i) - descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); - /* Nested... */ for (i = 0; i < this.nestedArray.length; ++i) { - /* Extension fields */ if (this._nestedArray[i] instanceof Field) - descriptor.field.push(this._nestedArray[i].toDescriptor(edition)); - /* Types */ else if (this._nestedArray[i] instanceof Type) - descriptor.nestedType.push(this._nestedArray[i].toDescriptor(edition)); - /* Enums */ else if (this._nestedArray[i] instanceof Enum) - descriptor.enumType.push(this._nestedArray[i].toDescriptor()); - // plain nested namespaces become packages instead in Root#toDescriptor - } - /* Extension ranges */ if (this.extensions) - for (i = 0; i < this.extensions.length; ++i) - descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); - /* Reserved... */ if (this.reserved) - for (i = 0; i < this.reserved.length; ++i) - /* Names */ if (typeof this.reserved[i] === "string") - descriptor.reservedName.push(this.reserved[i]); - /* Ranges */ else - descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); - - descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions); - - return descriptor; -}; - -// --- Field --- - -/** - * Properties of a FieldDescriptorProto message. - * @interface IFieldDescriptorProto - * @property {string} [name] Field name - * @property {number} [number] Field id - * @property {IFieldDescriptorProtoLabel} [label] Field rule - * @property {IFieldDescriptorProtoType} [type] Field basic type - * @property {string} [typeName] Field type name - * @property {string} [extendee] Extended type name - * @property {string} [defaultValue] Literal default value - * @property {number} [oneofIndex] Oneof index if part of a oneof - * @property {*} [jsonName] Not supported - * @property {IFieldOptions} [options] Field options - */ - -/** - * Values of the FieldDescriptorProto.Label enum. - * @typedef IFieldDescriptorProtoLabel - * @type {number} - * @property {number} LABEL_OPTIONAL=1 - * @property {number} LABEL_REQUIRED=2 - * @property {number} LABEL_REPEATED=3 - */ - -/** - * Values of the FieldDescriptorProto.Type enum. - * @typedef IFieldDescriptorProtoType - * @type {number} - * @property {number} TYPE_DOUBLE=1 - * @property {number} TYPE_FLOAT=2 - * @property {number} TYPE_INT64=3 - * @property {number} TYPE_UINT64=4 - * @property {number} TYPE_INT32=5 - * @property {number} TYPE_FIXED64=6 - * @property {number} TYPE_FIXED32=7 - * @property {number} TYPE_BOOL=8 - * @property {number} TYPE_STRING=9 - * @property {number} TYPE_GROUP=10 - * @property {number} TYPE_MESSAGE=11 - * @property {number} TYPE_BYTES=12 - * @property {number} TYPE_UINT32=13 - * @property {number} TYPE_ENUM=14 - * @property {number} TYPE_SFIXED32=15 - * @property {number} TYPE_SFIXED64=16 - * @property {number} TYPE_SINT32=17 - * @property {number} TYPE_SINT64=18 - */ - -/** - * Properties of a FieldOptions message. - * @interface IFieldOptions - * @property {boolean} [packed] Whether packed or not (defaults to `false` for proto2 and `true` for proto3) - * @property {IFieldOptionsJSType} [jstype] JavaScript value type (not used by protobuf.js) - */ - -/** - * Values of the FieldOptions.JSType enum. - * @typedef IFieldOptionsJSType - * @type {number} - * @property {number} JS_NORMAL=0 - * @property {number} JS_STRING=1 - * @property {number} JS_NUMBER=2 - */ - -// copied here from parse.js -var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; - -/** - * Creates a field from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IFieldDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a top-level object - * @returns {Field} Field instance - */ -Field.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.DescriptorProto.decode(descriptor); - - if (typeof descriptor.number !== "number") - throw Error("missing field id"); - - // Rewire field type - var fieldType; - if (descriptor.typeName && descriptor.typeName.length) - fieldType = descriptor.typeName; - else - fieldType = fromDescriptorType(descriptor.type); - - // Rewire field rule - var fieldRule; - switch (descriptor.label) { - // 0 is reserved for errors - case 1: fieldRule = undefined; break; - case 2: fieldRule = "required"; break; - case 3: fieldRule = "repeated"; break; - default: throw Error("illegal label: " + descriptor.label); - } - - var extendee = descriptor.extendee; - if (descriptor.extendee !== undefined) { - extendee = extendee.length ? extendee : undefined; - } - var field = new Field( - descriptor.name.length ? descriptor.name : "field" + descriptor.number, - descriptor.number, - fieldType, - fieldRule, - extendee - ); - - if (!nested) - field._edition = edition; - - field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions); - if (descriptor.proto3_optional) - field.options.proto3_optional = true; - - if (descriptor.defaultValue && descriptor.defaultValue.length) { - var defaultValue = descriptor.defaultValue; - switch (defaultValue) { - case "true": case "TRUE": - defaultValue = true; - break; - case "false": case "FALSE": - defaultValue = false; - break; - default: - var match = numberRe.exec(defaultValue); - if (match) - defaultValue = parseInt(defaultValue); // eslint-disable-line radix - break; - } - field.setOption("default", defaultValue); - } - - if (packableDescriptorType(descriptor.type)) { - if (edition === "proto3") { // defaults to packed=true (internal preset is packed=true) - if (descriptor.options && !descriptor.options.packed) - field.setOption("packed", false); - } else if ((!edition || edition === "proto2") && descriptor.options && descriptor.options.packed) // defaults to packed=false - field.setOption("packed", true); - } - - return field; -}; - -/** - * Converts a field to a descriptor. - * @returns {Message} Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - */ -Field.prototype.toDescriptor = function toDescriptor(edition) { - var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id }); - - if (this.map) { - - descriptor.type = 11; // message - descriptor.typeName = $protobuf.util.ucFirst(this.name); // fieldName -> FieldNameEntry (built in Type#toDescriptor) - descriptor.label = 3; // repeated - - } else { - - // Rewire field type - switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) { - case 10: // group - case 11: // type - case 14: // enum - descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; - break; - } - - // Rewire field rule - if (this.rule === "repeated") { - descriptor.label = 3; - } else if (this.required && edition === "proto2") { - descriptor.label = 2; - } else { - descriptor.label = 1; - } - } - - // Handle extension field - descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; - - // Handle part of oneof - if (this.partOf) - if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) - throw Error("missing oneof"); - - if (this.options) { - descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions); - if (this.options["default"] != null) - descriptor.defaultValue = String(this.options["default"]); - if (this.options.proto3_optional) - descriptor.proto3_optional = true; - } - - if (edition === "proto3") { // defaults to packed=true - if (!this.packed) - (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false; - } else if ((!edition || edition === "proto2") && this.packed) // defaults to packed=false - (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true; - - return descriptor; -}; - -// --- Enum --- - -/** - * Properties of an EnumDescriptorProto message. - * @interface IEnumDescriptorProto - * @property {string} [name] Enum name - * @property {IEnumValueDescriptorProto[]} [value] Enum values - * @property {IEnumOptions} [options] Enum options - */ - -/** - * Properties of an EnumValueDescriptorProto message. - * @interface IEnumValueDescriptorProto - * @property {string} [name] Name - * @property {number} [number] Value - * @property {*} [options] Not supported - */ - -/** - * Properties of an EnumOptions message. - * @interface IEnumOptions - * @property {boolean} [allowAlias] Whether aliases are allowed - * @property {boolean} [deprecated] - */ - -var unnamedEnumIndex = 0; - -/** - * Creates an enum from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IEnumDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a top-level object - * @returns {Enum} Enum instance - */ -Enum.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.EnumDescriptorProto.decode(descriptor); - - // Construct values object - var values = {}; - if (descriptor.value) - for (var i = 0; i < descriptor.value.length; ++i) { - var name = descriptor.value[i].name, - value = descriptor.value[i].number || 0; - values[name && name.length ? name : "NAME" + value] = value; - } - - var enm = new Enum( - descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, - values, - fromDescriptorOptions(descriptor.options, exports.EnumOptions) - ); - - if (!nested) - enm._edition = edition; - - return enm; -}; - -/** - * Converts an enum to a descriptor. - * @returns {Message} Descriptor - */ -Enum.prototype.toDescriptor = function toDescriptor() { - - // Values - var values = []; - for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i) - values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); - - return exports.EnumDescriptorProto.create({ - name: this.name, - value: values, - options: toDescriptorOptions(this.options, exports.EnumOptions) - }); -}; - -// --- OneOf --- - -/** - * Properties of a OneofDescriptorProto message. - * @interface IOneofDescriptorProto - * @property {string} [name] Oneof name - * @property {*} [options] Not supported - */ - -var unnamedOneofIndex = 0; - -/** - * Creates a oneof from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IOneofDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @returns {OneOf} OneOf instance - */ -OneOf.fromDescriptor = function fromDescriptor(descriptor) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.OneofDescriptorProto.decode(descriptor); - - return new OneOf( - // unnamedOneOfIndex is global, not per type, because we have no ref to a type here - descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++ - // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option - ); -}; - -/** - * Converts a oneof to a descriptor. - * @returns {Message} Descriptor - */ -OneOf.prototype.toDescriptor = function toDescriptor() { - return exports.OneofDescriptorProto.create({ - name: this.name - // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option - }); -}; - -// --- Service --- - -/** - * Properties of a ServiceDescriptorProto message. - * @interface IServiceDescriptorProto - * @property {string} [name] Service name - * @property {IMethodDescriptorProto[]} [method] Methods - * @property {IServiceOptions} [options] Options - */ - -/** - * Properties of a ServiceOptions message. - * @interface IServiceOptions - * @property {boolean} [deprecated] - */ - -var unnamedServiceIndex = 0; - -/** - * Creates a service from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IServiceDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a top-level object - * @returns {Service} Service instance - */ -Service.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.ServiceDescriptorProto.decode(descriptor); - - var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions)); - if (!nested) - service._edition = edition; - if (descriptor.method) - for (var i = 0; i < descriptor.method.length; ++i) - service.add(Method.fromDescriptor(descriptor.method[i])); - - return service; -}; - -/** - * Converts a service to a descriptor. - * @returns {Message} Descriptor - */ -Service.prototype.toDescriptor = function toDescriptor() { - - // Methods - var methods = []; - for (var i = 0; i < this.methodsArray.length; ++i) - methods.push(this._methodsArray[i].toDescriptor()); - - return exports.ServiceDescriptorProto.create({ - name: this.name, - method: methods, - options: toDescriptorOptions(this.options, exports.ServiceOptions) - }); -}; - -// --- Method --- - -/** - * Properties of a MethodDescriptorProto message. - * @interface IMethodDescriptorProto - * @property {string} [name] Method name - * @property {string} [inputType] Request type name - * @property {string} [outputType] Response type name - * @property {IMethodOptions} [options] Not supported - * @property {boolean} [clientStreaming=false] Whether requests are streamed - * @property {boolean} [serverStreaming=false] Whether responses are streamed - */ - -/** - * Properties of a MethodOptions message. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @interface IMethodOptions - * @property {boolean} [deprecated] - */ - -var unnamedMethodIndex = 0; - -/** - * Creates a method from a descriptor. - * @param {IMethodDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @returns {Method} Reflected method instance - */ -Method.fromDescriptor = function fromDescriptor(descriptor) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.MethodDescriptorProto.decode(descriptor); - - return new Method( - // unnamedMethodIndex is global, not per service, because we have no ref to a service here - descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, - "rpc", - descriptor.inputType, - descriptor.outputType, - Boolean(descriptor.clientStreaming), - Boolean(descriptor.serverStreaming), - fromDescriptorOptions(descriptor.options, exports.MethodOptions) - ); -}; - -/** - * Converts a method to a descriptor. - * @returns {Message} Descriptor - */ -Method.prototype.toDescriptor = function toDescriptor() { - return exports.MethodDescriptorProto.create({ - name: this.name, - inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, - outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, - clientStreaming: this.requestStream, - serverStreaming: this.responseStream, - options: toDescriptorOptions(this.options, exports.MethodOptions) - }); -}; - -// --- utility --- - -// Converts a descriptor type to a protobuf.js basic type -function fromDescriptorType(type) { - switch (type) { - // 0 is reserved for errors - case 1: return "double"; - case 2: return "float"; - case 3: return "int64"; - case 4: return "uint64"; - case 5: return "int32"; - case 6: return "fixed64"; - case 7: return "fixed32"; - case 8: return "bool"; - case 9: return "string"; - case 12: return "bytes"; - case 13: return "uint32"; - case 15: return "sfixed32"; - case 16: return "sfixed64"; - case 17: return "sint32"; - case 18: return "sint64"; - } - throw Error("illegal type: " + type); -} - -// Tests if a descriptor type is packable -function packableDescriptorType(type) { - switch (type) { - case 1: // double - case 2: // float - case 3: // int64 - case 4: // uint64 - case 5: // int32 - case 6: // fixed64 - case 7: // fixed32 - case 8: // bool - case 13: // uint32 - case 14: // enum (!) - case 15: // sfixed32 - case 16: // sfixed64 - case 17: // sint32 - case 18: // sint64 - return true; - } - return false; -} - -// Converts a protobuf.js basic type to a descriptor type -function toDescriptorType(type, resolvedType, delimited) { - switch (type) { - // 0 is reserved for errors - case "double": return 1; - case "float": return 2; - case "int64": return 3; - case "uint64": return 4; - case "int32": return 5; - case "fixed64": return 6; - case "fixed32": return 7; - case "bool": return 8; - case "string": return 9; - case "bytes": return 12; - case "uint32": return 13; - case "sfixed32": return 15; - case "sfixed64": return 16; - case "sint32": return 17; - case "sint64": return 18; - } - if (resolvedType instanceof Enum) - return 14; - if (resolvedType instanceof Type) - return delimited ? 10 : 11; - throw Error("illegal type: " + type); -} - -function fromDescriptorOptionsRecursive(obj, type) { - var val = {}; - for (var i = 0, field, key; i < type.fieldsArray.length; ++i) { - if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") continue; - if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; - - var newKey = underScore(key); - if (field.resolvedType instanceof Type) { - val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType); - } else if(field.resolvedType instanceof Enum) { - val[newKey] = field.resolvedType.valuesById[obj[key]]; - } else { - val[newKey] = obj[key]; - } - } - return val; -} - -// Converts descriptor options to an options object -function fromDescriptorOptions(options, type) { - if (!options) - return undefined; - return fromDescriptorOptionsRecursive(type.toObject(options), type); -} - -function toDescriptorOptionsRecursive(obj, type) { - var val = {}; - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var newKey = $protobuf.util.camelCase(key); - if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue; - var field = type.fields[newKey]; - if (field.resolvedType instanceof Type) { - val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType); - } else { - val[newKey] = obj[key]; - } - if (field.repeated && !Array.isArray(val[newKey])) { - val[newKey] = [val[newKey]]; - } - } - return val; -} - -// Converts an options object to descriptor options -function toDescriptorOptions(options, type) { - if (!options) - return undefined; - return type.fromObject(toDescriptorOptionsRecursive(options, type)); -} - -// Calculates the shortest relative path from `from` to `to`. -function shortname(from, to) { - var fromPath = from.fullName.split("."), - toPath = to.fullName.split("."), - i = 0, - j = 0, - k = toPath.length - 1; - if (!(from instanceof Root) && to instanceof Namespace) - while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { - var other = to.lookup(fromPath[i++], true); - if (other !== null && other !== to) - break; - ++j; - } - else - for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j); - return toPath.slice(j).join("."); -} - -// copied here from cli/targets/proto.js -function underScore(str) { - return str.substring(0,1) - + str.substring(1) - .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); }); -} - -function editionFromDescriptor(fileDescriptor) { - if (fileDescriptor.syntax === "editions") { - switch(fileDescriptor.edition) { - case exports.Edition.EDITION_2023: - return "2023"; - default: - throw new Error("Unsupported edition " + fileDescriptor.edition); - } - } - if (fileDescriptor.syntax === "proto3") { - return "proto3"; - } - return "proto2"; -} - -function editionToDescriptor(edition, fileDescriptor) { - if (!edition) return; - if (edition === "proto2" || edition === "proto3") { - fileDescriptor.syntax = edition; - } else { - fileDescriptor.syntax = "editions"; - switch(edition) { - case "2023": - fileDescriptor.edition = exports.Edition.EDITION_2023; - break; - default: - throw new Error("Unsupported edition " + edition); - } - } -} - -// --- exports --- - -/** - * Reflected file descriptor set. - * @name FileDescriptorSet - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected file descriptor proto. - * @name FileDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected descriptor proto. - * @name DescriptorProto - * @type {Type} - * @property {Type} ExtensionRange - * @property {Type} ReservedRange - * @const - * @tstype $protobuf.Type & { - * ExtensionRange: $protobuf.Type, - * ReservedRange: $protobuf.Type - * } - */ - -/** - * Reflected field descriptor proto. - * @name FieldDescriptorProto - * @type {Type} - * @property {Enum} Label - * @property {Enum} Type - * @const - * @tstype $protobuf.Type & { - * Label: $protobuf.Enum, - * Type: $protobuf.Enum - * } - */ - -/** - * Reflected oneof descriptor proto. - * @name OneofDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum descriptor proto. - * @name EnumDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected service descriptor proto. - * @name ServiceDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum value descriptor proto. - * @name EnumValueDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected method descriptor proto. - * @name MethodDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected file options. - * @name FileOptions - * @type {Type} - * @property {Enum} OptimizeMode - * @const - * @tstype $protobuf.Type & { - * OptimizeMode: $protobuf.Enum - * } - */ - -/** - * Reflected message options. - * @name MessageOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected field options. - * @name FieldOptions - * @type {Type} - * @property {Enum} CType - * @property {Enum} JSType - * @const - * @tstype $protobuf.Type & { - * CType: $protobuf.Enum, - * JSType: $protobuf.Enum - * } - */ - -/** - * Reflected oneof options. - * @name OneofOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum options. - * @name EnumOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum value options. - * @name EnumValueOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected service options. - * @name ServiceOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected method options. - * @name MethodOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected uninterpretet option. - * @name UninterpretedOption - * @type {Type} - * @property {Type} NamePart - * @const - * @tstype $protobuf.Type & { - * NamePart: $protobuf.Type - * } - */ - -/** - * Reflected source code info. - * @name SourceCodeInfo - * @type {Type} - * @property {Type} Location - * @const - * @tstype $protobuf.Type & { - * Location: $protobuf.Type - * } - */ - -/** - * Reflected generated code info. - * @name GeneratedCodeInfo - * @type {Type} - * @property {Type} Annotation - * @const - * @tstype $protobuf.Type & { - * Annotation: $protobuf.Type - * } - */ - - -/***/ }), - -/***/ 85881: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// full library entry point. - - -module.exports = __nccwpck_require__(15360); - - -/***/ }), - -/***/ 12134: -/***/ ((module) => { - -"use strict"; - -module.exports = common; - -var commonRe = /\/|\./; - -/** - * Provides common type definitions. - * Can also be used to provide additional google types or your own custom types. - * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name - * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition - * @returns {undefined} - * @property {INamespace} google/protobuf/any.proto Any - * @property {INamespace} google/protobuf/duration.proto Duration - * @property {INamespace} google/protobuf/empty.proto Empty - * @property {INamespace} google/protobuf/field_mask.proto FieldMask - * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue - * @property {INamespace} google/protobuf/timestamp.proto Timestamp - * @property {INamespace} google/protobuf/wrappers.proto Wrappers - * @example - * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) - * protobuf.common("descriptor", descriptorJson); - * - * // manually provides a custom definition (uses my.foo namespace) - * protobuf.common("my/foo/bar.proto", myFooBarJson); - */ -function common(name, json) { - if (!commonRe.test(name)) { - name = "google/protobuf/" + name + ".proto"; - json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; - } - common[name] = json; -} - -// Not provided because of limited use (feel free to discuss or to provide yourself): -// -// google/protobuf/descriptor.proto -// google/protobuf/source_context.proto -// google/protobuf/type.proto -// -// Stripped and pre-parsed versions of these non-bundled files are instead available as part of -// the repository or package within the google/protobuf directory. - -common("any", { - - /** - * Properties of a google.protobuf.Any message. - * @interface IAny - * @type {Object} - * @property {string} [typeUrl] - * @property {Uint8Array} [bytes] - * @memberof common - */ - Any: { - fields: { - type_url: { - type: "string", - id: 1 - }, - value: { - type: "bytes", - id: 2 - } - } - } -}); - -var timeType; - -common("duration", { - - /** - * Properties of a google.protobuf.Duration message. - * @interface IDuration - * @type {Object} - * @property {number|Long} [seconds] - * @property {number} [nanos] - * @memberof common - */ - Duration: timeType = { - fields: { - seconds: { - type: "int64", - id: 1 - }, - nanos: { - type: "int32", - id: 2 - } - } - } -}); - -common("timestamp", { - - /** - * Properties of a google.protobuf.Timestamp message. - * @interface ITimestamp - * @type {Object} - * @property {number|Long} [seconds] - * @property {number} [nanos] - * @memberof common - */ - Timestamp: timeType -}); - -common("empty", { - - /** - * Properties of a google.protobuf.Empty message. - * @interface IEmpty - * @memberof common - */ - Empty: { - fields: {} - } -}); - -common("struct", { - - /** - * Properties of a google.protobuf.Struct message. - * @interface IStruct - * @type {Object} - * @property {Object.} [fields] - * @memberof common - */ - Struct: { - fields: { - fields: { - keyType: "string", - type: "Value", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.Value message. - * @interface IValue - * @type {Object} - * @property {string} [kind] - * @property {0} [nullValue] - * @property {number} [numberValue] - * @property {string} [stringValue] - * @property {boolean} [boolValue] - * @property {IStruct} [structValue] - * @property {IListValue} [listValue] - * @memberof common - */ - Value: { - oneofs: { - kind: { - oneof: [ - "nullValue", - "numberValue", - "stringValue", - "boolValue", - "structValue", - "listValue" - ] - } - }, - fields: { - nullValue: { - type: "NullValue", - id: 1 - }, - numberValue: { - type: "double", - id: 2 - }, - stringValue: { - type: "string", - id: 3 - }, - boolValue: { - type: "bool", - id: 4 - }, - structValue: { - type: "Struct", - id: 5 - }, - listValue: { - type: "ListValue", - id: 6 - } - } - }, - - NullValue: { - values: { - NULL_VALUE: 0 - } - }, - - /** - * Properties of a google.protobuf.ListValue message. - * @interface IListValue - * @type {Object} - * @property {Array.} [values] - * @memberof common - */ - ListValue: { - fields: { - values: { - rule: "repeated", - type: "Value", - id: 1 - } - } - } -}); - -common("wrappers", { - - /** - * Properties of a google.protobuf.DoubleValue message. - * @interface IDoubleValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - DoubleValue: { - fields: { - value: { - type: "double", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.FloatValue message. - * @interface IFloatValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - FloatValue: { - fields: { - value: { - type: "float", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.Int64Value message. - * @interface IInt64Value - * @type {Object} - * @property {number|Long} [value] - * @memberof common - */ - Int64Value: { - fields: { - value: { - type: "int64", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.UInt64Value message. - * @interface IUInt64Value - * @type {Object} - * @property {number|Long} [value] - * @memberof common - */ - UInt64Value: { - fields: { - value: { - type: "uint64", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.Int32Value message. - * @interface IInt32Value - * @type {Object} - * @property {number} [value] - * @memberof common - */ - Int32Value: { - fields: { - value: { - type: "int32", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.UInt32Value message. - * @interface IUInt32Value - * @type {Object} - * @property {number} [value] - * @memberof common - */ - UInt32Value: { - fields: { - value: { - type: "uint32", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.BoolValue message. - * @interface IBoolValue - * @type {Object} - * @property {boolean} [value] - * @memberof common - */ - BoolValue: { - fields: { - value: { - type: "bool", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.StringValue message. - * @interface IStringValue - * @type {Object} - * @property {string} [value] - * @memberof common - */ - StringValue: { - fields: { - value: { - type: "string", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.BytesValue message. - * @interface IBytesValue - * @type {Object} - * @property {Uint8Array} [value] - * @memberof common - */ - BytesValue: { - fields: { - value: { - type: "bytes", - id: 1 - } - } - } -}); - -common("field_mask", { - - /** - * Properties of a google.protobuf.FieldMask message. - * @interface IDoubleValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - FieldMask: { - fields: { - paths: { - rule: "repeated", - type: "string", - id: 1 - } - } - } -}); - -/** - * Gets the root definition of the specified common proto file. - * - * Bundled definitions are: - * - google/protobuf/any.proto - * - google/protobuf/duration.proto - * - google/protobuf/empty.proto - * - google/protobuf/field_mask.proto - * - google/protobuf/struct.proto - * - google/protobuf/timestamp.proto - * - google/protobuf/wrappers.proto - * - * @param {string} file Proto file name - * @returns {INamespace|null} Root definition or `null` if not defined - */ -common.get = function get(file) { - return common[file] || null; -}; - - -/***/ }), - -/***/ 13617: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * Runtime message from/to plain object converters. - * @namespace - */ -var converter = exports; - -var Enum = __nccwpck_require__(17732), - util = __nccwpck_require__(47174); - -/** - * Generates a partial value fromObject conveter. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {number} fieldIndex Field index - * @param {string} prop Property reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genValuePartial_fromObject(gen, field, fieldIndex, prop) { - var defaultAlreadyEmitted = false; - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - if (field.resolvedType) { - if (field.resolvedType instanceof Enum) { gen - ("switch(d%s){", prop); - for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { - // enum unknown values passthrough - if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen - ("default:") - ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); - if (!field.repeated) gen // fallback to default value only for - // arrays, to avoid leaving holes. - ("break"); // for non-repeated fields, just ignore - defaultAlreadyEmitted = true; - } - gen - ("case%j:", keys[i]) - ("case %i:", values[keys[i]]) - ("m%s=%j", prop, values[keys[i]]) - ("break"); - } gen - ("}"); - } else gen - ("if(typeof d%s!==\"object\")", prop) - ("throw TypeError(%j)", field.fullName + ": object expected") - ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); - } else { - var isUnsigned = false; - switch (field.type) { - case "double": - case "float": gen - ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" - break; - case "uint32": - case "fixed32": gen - ("m%s=d%s>>>0", prop, prop); - break; - case "int32": - case "sint32": - case "sfixed32": gen - ("m%s=d%s|0", prop, prop); - break; - case "uint64": - isUnsigned = true; - // eslint-disable-next-line no-fallthrough - case "int64": - case "sint64": - case "fixed64": - case "sfixed64": gen - ("if(util.Long)") - ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) - ("else if(typeof d%s===\"string\")", prop) - ("m%s=parseInt(d%s,10)", prop, prop) - ("else if(typeof d%s===\"number\")", prop) - ("m%s=d%s", prop, prop) - ("else if(typeof d%s===\"object\")", prop) - ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); - break; - case "bytes": gen - ("if(typeof d%s===\"string\")", prop) - ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) - ("else if(d%s.length >= 0)", prop) - ("m%s=d%s", prop, prop); - break; - case "string": gen - ("m%s=String(d%s)", prop, prop); - break; - case "bool": gen - ("m%s=Boolean(d%s)", prop, prop); - break; - /* default: gen - ("m%s=d%s", prop, prop); - break; */ - } - } - return gen; - /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ -} - -/** - * Generates a plain object to runtime message converter specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -converter.fromObject = function fromObject(mtype) { - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - var fields = mtype.fieldsArray; - var gen = util.codegen(["d"], mtype.name + "$fromObject") - ("if(d instanceof this.ctor)") - ("return d"); - if (!fields.length) return gen - ("return new this.ctor"); - gen - ("var m=new this.ctor"); - for (var i = 0; i < fields.length; ++i) { - var field = fields[i].resolve(), - prop = util.safeProp(field.name); - - // Map fields - if (field.map) { gen - ("if(d%s){", prop) - ("if(typeof d%s!==\"object\")", prop) - ("throw TypeError(%j)", field.fullName + ": object expected") - ("m%s={}", prop) - ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); - break; - case "bytes": gen - ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); - break; - default: gen - ("d%s=m%s", prop, prop); - break; - } - } - return gen; - /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ -} - -/** - * Generates a runtime message to plain object converter specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -converter.toObject = function toObject(mtype) { - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); - if (!fields.length) - return util.codegen()("return {}"); - var gen = util.codegen(["m", "o"], mtype.name + "$toObject") - ("if(!o)") - ("o={}") - ("var d={}"); - - var repeatedFields = [], - mapFields = [], - normalFields = [], - i = 0; - for (; i < fields.length; ++i) - if (!fields[i].partOf) - ( fields[i].resolve().repeated ? repeatedFields - : fields[i].map ? mapFields - : normalFields).push(fields[i]); - - if (repeatedFields.length) { gen - ("if(o.arrays||o.defaults){"); - for (i = 0; i < repeatedFields.length; ++i) gen - ("d%s=[]", util.safeProp(repeatedFields[i].name)); - gen - ("}"); - } - - if (mapFields.length) { gen - ("if(o.objects||o.defaults){"); - for (i = 0; i < mapFields.length; ++i) gen - ("d%s={}", util.safeProp(mapFields[i].name)); - gen - ("}"); - } - - if (normalFields.length) { gen - ("if(o.defaults){"); - for (i = 0; i < normalFields.length; ++i) { - var field = normalFields[i], - prop = util.safeProp(field.name); - if (field.resolvedType instanceof Enum) gen - ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); - else if (field.long) gen - ("if(util.Long){") - ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) - ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) - ("}else") - ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); - else if (field.bytes) { - var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; - gen - ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) - ("else{") - ("d%s=%s", prop, arrayDefault) - ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) - ("}"); - } else gen - ("d%s=%j", prop, field.typeDefault); // also messages (=null) - } gen - ("}"); - } - var hasKs2 = false; - for (i = 0; i < fields.length; ++i) { - var field = fields[i], - index = mtype._fieldsArray.indexOf(field), - prop = util.safeProp(field.name); - if (field.map) { - if (!hasKs2) { hasKs2 = true; gen - ("var ks2"); - } gen - ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) - ("d%s={}", prop) - ("for(var j=0;j { - -"use strict"; - -module.exports = decoder; - -var Enum = __nccwpck_require__(17732), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -function missing(field) { - return "missing required '" + field.name + "'"; -} - -/** - * Generates a decoder specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -function decoder(mtype) { - /* eslint-disable no-unexpected-multiline */ - var gen = util.codegen(["r", "l", "e"], mtype.name + "$decode") - ("if(!(r instanceof Reader))") - ("r=Reader.create(r)") - ("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field) { return field.map; }).length ? ",k,value" : "")) - ("while(r.pos>>3){"); - - var i = 0; - for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { - var field = mtype._fieldsArray[i].resolve(), - type = field.resolvedType instanceof Enum ? "int32" : field.type, - ref = "m" + util.safeProp(field.name); gen - ("case %i: {", field.id); - - // Map fields - if (field.map) { gen - ("if(%s===util.emptyObject)", ref) - ("%s={}", ref) - ("var c2 = r.uint32()+r.pos"); - - if (types.defaults[field.keyType] !== undefined) gen - ("k=%j", types.defaults[field.keyType]); - else gen - ("k=null"); - - if (types.defaults[type] !== undefined) gen - ("value=%j", types.defaults[type]); - else gen - ("value=null"); - - gen - ("while(r.pos>>3){") - ("case 1: k=r.%s(); break", field.keyType) - ("case 2:"); - - if (types.basic[type] === undefined) gen - ("value=types[%i].decode(r,r.uint32())", i); // can't be groups - else gen - ("value=r.%s()", type); - - gen - ("break") - ("default:") - ("r.skipType(tag2&7)") - ("break") - ("}") - ("}"); - - if (types.long[field.keyType] !== undefined) gen - ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); - else gen - ("%s[k]=value", ref); - - // Repeated fields - } else if (field.repeated) { gen - - ("if(!(%s&&%s.length))", ref, ref) - ("%s=[]", ref); - - // Packable (always check for forward and backward compatiblity) - if (types.packed[type] !== undefined) gen - ("if((t&7)===2){") - ("var c2=r.uint32()+r.pos") - ("while(r.pos { - -"use strict"; - -module.exports = encoder; - -var Enum = __nccwpck_require__(17732), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -/** - * Generates a partial message type encoder. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {number} fieldIndex Field index - * @param {string} ref Variable reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genTypePartial(gen, field, fieldIndex, ref) { - return field.delimited - ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) - : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); -} - -/** - * Generates an encoder specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -function encoder(mtype) { - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - var gen = util.codegen(["m", "w"], mtype.name + "$encode") - ("if(!w)") - ("w=Writer.create()"); - - var i, ref; - - // "when a message is serialized its known fields should be written sequentially by field number" - var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); - - for (var i = 0; i < fields.length; ++i) { - var field = fields[i].resolve(), - index = mtype._fieldsArray.indexOf(field), - type = field.resolvedType instanceof Enum ? "int32" : field.type, - wireType = types.basic[type]; - ref = "m" + util.safeProp(field.name); - - // Map fields - if (field.map) { - gen - ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null - ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); - if (wireType === undefined) gen - ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups - else gen - (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); - gen - ("}") - ("}"); - - // Repeated fields - } else if (field.repeated) { gen - ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null - - // Packed repeated - if (field.packed && types.packed[type] !== undefined) { gen - - ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) - ("for(var i=0;i<%s.length;++i)", ref) - ("w.%s(%s[i])", type, ref) - ("w.ldelim()"); - - // Non-packed - } else { gen - - ("for(var i=0;i<%s.length;++i)", ref); - if (wireType === undefined) - genTypePartial(gen, field, index, ref + "[i]"); - else gen - ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); - - } gen - ("}"); - - // Non-repeated - } else { - if (field.optional) gen - ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null - - if (wireType === undefined) - genTypePartial(gen, field, index, ref); - else gen - ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); - - } - } - - return gen - ("return w"); - /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ -} - - -/***/ }), - -/***/ 17732: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Enum; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; - -var Namespace = __nccwpck_require__(76189), - util = __nccwpck_require__(47174); - -/** - * Constructs a new enum instance. - * @classdesc Reflected enum. - * @extends ReflectionObject - * @constructor - * @param {string} name Unique name within its namespace - * @param {Object.} [values] Enum values as an object, by name - * @param {Object.} [options] Declared options - * @param {string} [comment] The comment for this enum - * @param {Object.} [comments] The value comments for this enum - * @param {Object.>|undefined} [valuesOptions] The value options for this enum - */ -function Enum(name, values, options, comment, comments, valuesOptions) { - ReflectionObject.call(this, name, options); - - if (values && typeof values !== "object") - throw TypeError("values must be an object"); - - /** - * Enum values by id. - * @type {Object.} - */ - this.valuesById = {}; - - /** - * Enum values by name. - * @type {Object.} - */ - this.values = Object.create(this.valuesById); // toJSON, marker - - /** - * Enum comment text. - * @type {string|null} - */ - this.comment = comment; - - /** - * Value comment texts, if any. - * @type {Object.} - */ - this.comments = comments || {}; - - /** - * Values options, if any - * @type {Object>|undefined} - */ - this.valuesOptions = valuesOptions; - - /** - * Resolved values features, if any - * @type {Object>|undefined} - */ - this._valuesFeatures = {}; - - /** - * Reserved ranges, if any. - * @type {Array.} - */ - this.reserved = undefined; // toJSON - - // Note that values inherit valuesById on their prototype which makes them a TypeScript- - // compatible enum. This is used by pbts to write actual enum definitions that work for - // static and reflection code alike instead of emitting generic object definitions. - - if (values) - for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) - if (typeof values[keys[i]] === "number") // use forward entries only - this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; -} - -/** - * @override - */ -Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { - edition = this._edition || edition; - ReflectionObject.prototype._resolveFeatures.call(this, edition); - - Object.keys(this.values).forEach(key => { - var parentFeaturesCopy = Object.assign({}, this._features); - this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features); - }); - - return this; -}; - -/** - * Enum descriptor. - * @interface IEnum - * @property {Object.} values Enum values - * @property {Object.} [options] Enum options - */ - -/** - * Constructs an enum from an enum descriptor. - * @param {string} name Enum name - * @param {IEnum} json Enum descriptor - * @returns {Enum} Created enum - * @throws {TypeError} If arguments are invalid - */ -Enum.fromJSON = function fromJSON(name, json) { - var enm = new Enum(name, json.values, json.options, json.comment, json.comments); - enm.reserved = json.reserved; - if (json.edition) - enm._edition = json.edition; - enm._defaultEdition = "proto3"; // For backwards-compatibility. - return enm; -}; - -/** - * Converts this enum to an enum descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IEnum} Enum descriptor - */ -Enum.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "options" , this.options, - "valuesOptions" , this.valuesOptions, - "values" , this.values, - "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, - "comment" , keepComments ? this.comment : undefined, - "comments" , keepComments ? this.comments : undefined - ]); -}; - -/** - * Adds a value to this enum. - * @param {string} name Value name - * @param {number} id Value id - * @param {string} [comment] Comment, if any - * @param {Object.|undefined} [options] Options, if any - * @returns {Enum} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If there is already a value with this name or id - */ -Enum.prototype.add = function add(name, id, comment, options) { - // utilized by the parser but not by .fromJSON - - if (!util.isString(name)) - throw TypeError("name must be a string"); - - if (!util.isInteger(id)) - throw TypeError("id must be an integer"); - - if (this.values[name] !== undefined) - throw Error("duplicate name '" + name + "' in " + this); - - if (this.isReservedId(id)) - throw Error("id " + id + " is reserved in " + this); - - if (this.isReservedName(name)) - throw Error("name '" + name + "' is reserved in " + this); - - if (this.valuesById[id] !== undefined) { - if (!(this.options && this.options.allow_alias)) - throw Error("duplicate id " + id + " in " + this); - this.values[name] = id; - } else - this.valuesById[this.values[name] = id] = name; - - if (options) { - if (this.valuesOptions === undefined) - this.valuesOptions = {}; - this.valuesOptions[name] = options || null; - } - - this.comments[name] = comment || null; - return this; -}; - -/** - * Removes a value from this enum - * @param {string} name Value name - * @returns {Enum} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If `name` is not a name of this enum - */ -Enum.prototype.remove = function remove(name) { - - if (!util.isString(name)) - throw TypeError("name must be a string"); - - var val = this.values[name]; - if (val == null) - throw Error("name '" + name + "' does not exist in " + this); - - delete this.valuesById[val]; - delete this.values[name]; - delete this.comments[name]; - if (this.valuesOptions) - delete this.valuesOptions[name]; - - return this; -}; - -/** - * Tests if the specified id is reserved. - * @param {number} id Id to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Enum.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); -}; - -/** - * Tests if the specified name is reserved. - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Enum.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); -}; - - -/***/ }), - -/***/ 48213: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Field; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; - -var Enum = __nccwpck_require__(17732), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -var Type; // cyclic - -var ruleRe = /^required|optional|repeated$/; - -/** - * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. - * @name Field - * @classdesc Reflected message field. - * @extends FieldBase - * @constructor - * @param {string} name Unique name within its namespace - * @param {number} id Unique id within its namespace - * @param {string} type Value type - * @param {string|Object.} [rule="optional"] Field rule - * @param {string|Object.} [extend] Extended type if different from parent - * @param {Object.} [options] Declared options - */ - -/** - * Constructs a field from a field descriptor. - * @param {string} name Field name - * @param {IField} json Field descriptor - * @returns {Field} Created field - * @throws {TypeError} If arguments are invalid - */ -Field.fromJSON = function fromJSON(name, json) { - var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); - if (json.edition) - field._edition = json.edition; - field._defaultEdition = "proto3"; // For backwards-compatibility. - return field; -}; - -/** - * Not an actual constructor. Use {@link Field} instead. - * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. - * @exports FieldBase - * @extends ReflectionObject - * @constructor - * @param {string} name Unique name within its namespace - * @param {number} id Unique id within its namespace - * @param {string} type Value type - * @param {string|Object.} [rule="optional"] Field rule - * @param {string|Object.} [extend] Extended type if different from parent - * @param {Object.} [options] Declared options - * @param {string} [comment] Comment associated with this field - */ -function Field(name, id, type, rule, extend, options, comment) { - - if (util.isObject(rule)) { - comment = extend; - options = rule; - rule = extend = undefined; - } else if (util.isObject(extend)) { - comment = options; - options = extend; - extend = undefined; - } - - ReflectionObject.call(this, name, options); - - if (!util.isInteger(id) || id < 0) - throw TypeError("id must be a non-negative integer"); - - if (!util.isString(type)) - throw TypeError("type must be a string"); - - if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) - throw TypeError("rule must be a string rule"); - - if (extend !== undefined && !util.isString(extend)) - throw TypeError("extend must be a string"); - - /** - * Field rule, if any. - * @type {string|undefined} - */ - if (rule === "proto3_optional") { - rule = "optional"; - } - this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON - - /** - * Field type. - * @type {string} - */ - this.type = type; // toJSON - - /** - * Unique field id. - * @type {number} - */ - this.id = id; // toJSON, marker - - /** - * Extended type if different from parent. - * @type {string|undefined} - */ - this.extend = extend || undefined; // toJSON - - /** - * Whether this field is repeated. - * @type {boolean} - */ - this.repeated = rule === "repeated"; - - /** - * Whether this field is a map or not. - * @type {boolean} - */ - this.map = false; - - /** - * Message this field belongs to. - * @type {Type|null} - */ - this.message = null; - - /** - * OneOf this field belongs to, if any, - * @type {OneOf|null} - */ - this.partOf = null; - - /** - * The field type's default value. - * @type {*} - */ - this.typeDefault = null; - - /** - * The field's default value on prototypes. - * @type {*} - */ - this.defaultValue = null; - - /** - * Whether this field's value should be treated as a long. - * @type {boolean} - */ - this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; - - /** - * Whether this field's value is a buffer. - * @type {boolean} - */ - this.bytes = type === "bytes"; - - /** - * Resolved type if not a basic type. - * @type {Type|Enum|null} - */ - this.resolvedType = null; - - /** - * Sister-field within the extended type if a declaring extension field. - * @type {Field|null} - */ - this.extensionField = null; - - /** - * Sister-field within the declaring namespace if an extended field. - * @type {Field|null} - */ - this.declaringField = null; - - /** - * Comment for this field. - * @type {string|null} - */ - this.comment = comment; -} - -/** - * Determines whether this field is required. - * @name Field#required - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "required", { - get: function() { - return this._features.field_presence === "LEGACY_REQUIRED"; - } -}); - -/** - * Determines whether this field is not required. - * @name Field#optional - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "optional", { - get: function() { - return !this.required; - } -}); - -/** - * Determines whether this field uses tag-delimited encoding. In proto2 this - * corresponded to group syntax. - * @name Field#delimited - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "delimited", { - get: function() { - return this.resolvedType instanceof Type && - this._features.message_encoding === "DELIMITED"; - } -}); - -/** - * Determines whether this field is packed. Only relevant when repeated. - * @name Field#packed - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "packed", { - get: function() { - return this._features.repeated_field_encoding === "PACKED"; - } -}); - -/** - * Determines whether this field tracks presence. - * @name Field#hasPresence - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "hasPresence", { - get: function() { - if (this.repeated || this.map) { - return false; - } - return this.partOf || // oneofs - this.declaringField || this.extensionField || // extensions - this._features.field_presence !== "IMPLICIT"; - } -}); - -/** - * @override - */ -Field.prototype.setOption = function setOption(name, value, ifNotSet) { - return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); -}; - -/** - * Field descriptor. - * @interface IField - * @property {string} [rule="optional"] Field rule - * @property {string} type Field type - * @property {number} id Field id - * @property {Object.} [options] Field options - */ - -/** - * Extension field descriptor. - * @interface IExtensionField - * @extends IField - * @property {string} extend Extended type - */ - -/** - * Converts this field to a field descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IField} Field descriptor - */ -Field.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "rule" , this.rule !== "optional" && this.rule || undefined, - "type" , this.type, - "id" , this.id, - "extend" , this.extend, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * Resolves this field's type references. - * @returns {Field} `this` - * @throws {Error} If any reference cannot be resolved - */ -Field.prototype.resolve = function resolve() { - - if (this.resolved) - return this; - - if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it - this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); - if (this.resolvedType instanceof Type) - this.typeDefault = null; - else // instanceof Enum - this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined - } else if (this.options && this.options.proto3_optional) { - // proto3 scalar value marked optional; should default to null - this.typeDefault = null; - } - - // use explicitly set default value if present - if (this.options && this.options["default"] != null) { - this.typeDefault = this.options["default"]; - if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") - this.typeDefault = this.resolvedType.values[this.typeDefault]; - } - - // remove unnecessary options - if (this.options) { - if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) - delete this.options.packed; - if (!Object.keys(this.options).length) - this.options = undefined; - } - - // convert to internal data type if necesssary - if (this.long) { - this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); - - /* istanbul ignore else */ - if (Object.freeze) - Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) - - } else if (this.bytes && typeof this.typeDefault === "string") { - var buf; - if (util.base64.test(this.typeDefault)) - util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); - else - util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); - this.typeDefault = buf; - } - - // take special care of maps and repeated fields - if (this.map) - this.defaultValue = util.emptyObject; - else if (this.repeated) - this.defaultValue = util.emptyArray; - else - this.defaultValue = this.typeDefault; - - // ensure proper value on prototype - if (this.parent instanceof Type) - this.parent.ctor.prototype[this.name] = this.defaultValue; - - return ReflectionObject.prototype.resolve.call(this); +// pkg/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repositories/{repository_id}/environments/{environment_name}/variables" + ], + createOrUpdateEnvironmentSecret: [ + "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables" + ], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" + } + ], + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" + } + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" + } + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" + } + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" + } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" + } + ], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ], + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" + } + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}" + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], + createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteCustomOrganizationRole: [ + "DELETE /orgs/{org}/organization-roles/{role_id}" + ], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + enableOrDisableSecurityProductOnAllOrgRepos: [ + "POST /orgs/{org}/{security_product}/{enablement}" + ], + get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + patchCustomOrganizationRole: [ + "PATCH /orgs/{org}/organization-roles/{role_id}" + ], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}" + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: [ + "GET /projects/{project_id}/collaborators/{username}/permission" + ], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: [ + "DELETE /projects/{project_id}/collaborators/{username}" + ], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteTagProtection: [ + "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" + ], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateProjectPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForProjectInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeProjectInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } }; +var endpoints_default = Endpoints; -/** - * Infers field features from legacy syntax that may have been specified differently. - * in older editions. - * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions - * @returns {object} The feature values to override - */ -Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { - if (edition !== "proto2" && edition !== "proto3") { - return {}; - } - - var features = {}; - - if (this.rule === "required") { - features.field_presence = "LEGACY_REQUIRED"; - } - if (this.parent && types.defaults[this.type] === undefined) { - // We can't use resolvedType because types may not have been resolved yet. However, - // legacy groups are always in the same scope as the field so we don't have to do a - // full scan of the tree. - var type = this.parent.get(this.type.split(".").pop()); - if (type && type instanceof Type && type.group) { - features.message_encoding = "DELIMITED"; - } - } - if (this.getOption("packed") === true) { - features.repeated_field_encoding = "PACKED"; - } else if (this.getOption("packed") === false) { - features.repeated_field_encoding = "EXPANDED"; +// pkg/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); } - return features; -}; - -/** - * @override - */ -Field.prototype._resolveFeatures = function _resolveFeatures(edition) { - return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); -}; - -/** - * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). - * @typedef FieldDecorator - * @type {function} - * @param {Object} prototype Target prototype - * @param {string} fieldName Field name - * @returns {undefined} - */ - -/** - * Field decorator (TypeScript). - * @name Field.d - * @function - * @param {number} fieldId Field id - * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type - * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule - * @param {T} [defaultValue] Default value - * @returns {FieldDecorator} Decorator function - * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] - */ -Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { - - // submessage: decorate the submessage and use its name as the type - if (typeof fieldType === "function") - fieldType = util.decorateType(fieldType).name; - - // enum reference: create a reflected copy of the enum and keep reuseing it - else if (fieldType && typeof fieldType === "object") - fieldType = util.decorateEnum(fieldType).name; - - return function fieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor) - .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); - }; -}; - -/** - * Field decorator (TypeScript). - * @name Field.d - * @function - * @param {number} fieldId Field id - * @param {Constructor|string} fieldType Field type - * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule - * @returns {FieldDecorator} Decorator function - * @template T extends Message - * @variation 2 - */ -// like Field.d but without a default value - -// Sets up cyclic dependencies (called in index-light) -Field._configure = function configure(Type_) { - Type = Type_; -}; - - -/***/ }), - -/***/ 26119: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var protobuf = module.exports = __nccwpck_require__(73242); - -protobuf.build = "light"; - -/** - * A node-style callback as used by {@link load} and {@link Root#load}. - * @typedef LoadCallback - * @type {function} - * @param {Error|null} error Error, if any, otherwise `null` - * @param {Root} [root] Root, if there hasn't been an error - * @returns {undefined} - */ - -/** - * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. - * @param {string|string[]} filename One or multiple files to load - * @param {Root} root Root namespace, defaults to create a new one if omitted. - * @param {LoadCallback} callback Callback function - * @returns {undefined} - * @see {@link Root#load} - */ -function load(filename, root, callback) { - if (typeof root === "function") { - callback = root; - root = new protobuf.Root(); - } else if (!root) - root = new protobuf.Root(); - return root.load(filename, callback); -} - -/** - * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. - * @name load - * @function - * @param {string|string[]} filename One or multiple files to load - * @param {LoadCallback} callback Callback function - * @returns {undefined} - * @see {@link Root#load} - * @variation 2 - */ -// function load(filename:string, callback:LoadCallback):undefined - -/** - * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. - * @name load - * @function - * @param {string|string[]} filename One or multiple files to load - * @param {Root} [root] Root namespace, defaults to create a new one if omitted. - * @returns {Promise} Promise - * @see {@link Root#load} - * @variation 3 - */ -// function load(filename:string, [root:Root]):Promise - -protobuf.load = load; - -/** - * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). - * @param {string|string[]} filename One or multiple files to load - * @param {Root} [root] Root namespace, defaults to create a new one if omitted. - * @returns {Root} Root namespace - * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid - * @see {@link Root#loadSync} - */ -function loadSync(filename, root) { - if (!root) - root = new protobuf.Root(); - return root.loadSync(filename); -} - -protobuf.loadSync = loadSync; - -// Serialization -protobuf.encoder = __nccwpck_require__(23072); -protobuf.decoder = __nccwpck_require__(65871); -protobuf.verifier = __nccwpck_require__(34334); -protobuf.converter = __nccwpck_require__(13617); - -// Reflection -protobuf.ReflectionObject = __nccwpck_require__(83575); -protobuf.Namespace = __nccwpck_require__(76189); -protobuf.Root = __nccwpck_require__(32614); -protobuf.Enum = __nccwpck_require__(17732); -protobuf.Type = __nccwpck_require__(38520); -protobuf.Field = __nccwpck_require__(48213); -protobuf.OneOf = __nccwpck_require__(44408); -protobuf.MapField = __nccwpck_require__(67777); -protobuf.Service = __nccwpck_require__(6178); -protobuf.Method = __nccwpck_require__(57771); - -// Runtime -protobuf.Message = __nccwpck_require__(68027); -protobuf.wrappers = __nccwpck_require__(63216); - -// Utility -protobuf.types = __nccwpck_require__(6581); -protobuf.util = __nccwpck_require__(47174); - -// Set up possibly cyclic reflection dependencies -protobuf.ReflectionObject._configure(protobuf.Root); -protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); -protobuf.Root._configure(protobuf.Type); -protobuf.Field._configure(protobuf.Type); - - -/***/ }), - -/***/ 73242: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var protobuf = exports; - -/** - * Build type, one of `"full"`, `"light"` or `"minimal"`. - * @name build - * @type {string} - * @const - */ -protobuf.build = "minimal"; - -// Serialization -protobuf.Writer = __nccwpck_require__(13098); -protobuf.BufferWriter = __nccwpck_require__(41863); -protobuf.Reader = __nccwpck_require__(41011); -protobuf.BufferReader = __nccwpck_require__(80339); - -// Utility -protobuf.util = __nccwpck_require__(71241); -protobuf.rpc = __nccwpck_require__(86444); -protobuf.roots = __nccwpck_require__(50073); -protobuf.configure = configure; - -/* istanbul ignore next */ -/** - * Reconfigures the library according to the environment. - * @returns {undefined} - */ -function configure() { - protobuf.util._configure(); - protobuf.Writer._configure(protobuf.BufferWriter); - protobuf.Reader._configure(protobuf.BufferReader); -} - -// Set up buffer utility according to the environment -configure(); - - -/***/ }), - -/***/ 15360: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var protobuf = module.exports = __nccwpck_require__(26119); - -protobuf.build = "full"; - -// Parser -protobuf.tokenize = __nccwpck_require__(61157); -protobuf.parse = __nccwpck_require__(32137); -protobuf.common = __nccwpck_require__(12134); - -// Configure parser -protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); - - -/***/ }), - -/***/ 67777: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = MapField; - -// extends Field -var Field = __nccwpck_require__(48213); -((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; - -var types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -/** - * Constructs a new map field instance. - * @classdesc Reflected map field. - * @extends FieldBase - * @constructor - * @param {string} name Unique name within its namespace - * @param {number} id Unique id within its namespace - * @param {string} keyType Key type - * @param {string} type Value type - * @param {Object.} [options] Declared options - * @param {string} [comment] Comment associated with this field - */ -function MapField(name, id, keyType, type, options, comment) { - Field.call(this, name, id, type, undefined, undefined, options, comment); - - /* istanbul ignore if */ - if (!util.isString(keyType)) - throw TypeError("keyType must be a string"); - - /** - * Key type. - * @type {string} - */ - this.keyType = keyType; // toJSON, marker - - /** - * Resolved key type if not a basic type. - * @type {ReflectionObject|null} - */ - this.resolvedKeyType = null; - - // Overrides Field#map - this.map = true; + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } } - -/** - * Map field descriptor. - * @interface IMapField - * @extends {IField} - * @property {string} keyType Key type - */ - -/** - * Extension map field descriptor. - * @interface IExtensionMapField - * @extends IMapField - * @property {string} extend Extended type - */ - -/** - * Constructs a map field from a map field descriptor. - * @param {string} name Field name - * @param {IMapField} json Map field descriptor - * @returns {MapField} Created map field - * @throws {TypeError} If arguments are invalid - */ -MapField.fromJSON = function fromJSON(name, json) { - return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); -}; - -/** - * Converts this map field to a map field descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IMapField} Map field descriptor - */ -MapField.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "keyType" , this.keyType, - "type" , this.type, - "id" , this.id, - "extend" , this.extend, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * @override - */ -MapField.prototype.resolve = function resolve() { - if (this.resolved) - return this; - - // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" - if (types.mapKey[this.keyType] === undefined) - throw Error("invalid key type: " + this.keyType); - - return Field.prototype.resolve.call(this); -}; - -/** - * Map field decorator (TypeScript). - * @name MapField.d - * @function - * @param {number} fieldId Field id - * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type - * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type - * @returns {FieldDecorator} Decorator function - * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } - */ -MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { - - // submessage value: decorate the submessage and use its name as the type - if (typeof fieldValueType === "function") - fieldValueType = util.decorateType(fieldValueType).name; - - // enum reference value: create a reflected copy of the enum and keep reuseing it - else if (fieldValueType && typeof fieldValueType === "object") - fieldValueType = util.decorateEnum(fieldValueType).name; - - return function mapFieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor) - .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true }; -}; - - -/***/ }), - -/***/ 68027: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Message; - -var util = __nccwpck_require__(71241); - -/** - * Constructs a new message instance. - * @classdesc Abstract runtime message. - * @constructor - * @param {Properties} [properties] Properties to set - * @template T extends object = object - */ -function Message(properties) { - // not used internally - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - this[keys[i]] = properties[keys[i]]; -} - -/** - * Reference to the reflected type. - * @name Message.$type - * @type {Type} - * @readonly - */ - -/** - * Reference to the reflected type. - * @name Message#$type - * @type {Type} - * @readonly - */ - -/*eslint-disable valid-jsdoc*/ - -/** - * Creates a new message of this type using the specified properties. - * @param {Object.} [properties] Properties to set - * @returns {Message} Message instance - * @template T extends Message - * @this Constructor - */ -Message.create = function create(properties) { - return this.$type.create(properties); -}; - -/** - * Encodes a message of this type. - * @param {T|Object.} message Message to encode - * @param {Writer} [writer] Writer to use - * @returns {Writer} Writer - * @template T extends Message - * @this Constructor - */ -Message.encode = function encode(message, writer) { - return this.$type.encode(message, writer); -}; - -/** - * Encodes a message of this type preceeded by its length as a varint. - * @param {T|Object.} message Message to encode - * @param {Writer} [writer] Writer to use - * @returns {Writer} Writer - * @template T extends Message - * @this Constructor - */ -Message.encodeDelimited = function encodeDelimited(message, writer) { - return this.$type.encodeDelimited(message, writer); -}; - -/** - * Decodes a message of this type. - * @name Message.decode - * @function - * @param {Reader|Uint8Array} reader Reader or buffer to decode - * @returns {T} Decoded message - * @template T extends Message - * @this Constructor - */ -Message.decode = function decode(reader) { - return this.$type.decode(reader); -}; - -/** - * Decodes a message of this type preceeded by its length as a varint. - * @name Message.decodeDelimited - * @function - * @param {Reader|Uint8Array} reader Reader or buffer to decode - * @returns {T} Decoded message - * @template T extends Message - * @this Constructor - */ -Message.decodeDelimited = function decodeDelimited(reader) { - return this.$type.decodeDelimited(reader); -}; - -/** - * Verifies a message of this type. - * @name Message.verify - * @function - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ -Message.verify = function verify(message) { - return this.$type.verify(message); -}; - -/** - * Creates a new message of this type from a plain object. Also converts values to their respective internal types. - * @param {Object.} object Plain object - * @returns {T} Message instance - * @template T extends Message - * @this Constructor - */ -Message.fromObject = function fromObject(object) { - return this.$type.fromObject(object); -}; - -/** - * Creates a plain object from a message of this type. Also converts values to other types if specified. - * @param {T} message Message instance - * @param {IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - * @template T extends Message - * @this Constructor - */ -Message.toObject = function toObject(message, options) { - return this.$type.toObject(message, options); -}; - -/** - * Converts this message to JSON. - * @returns {Object.} JSON object - */ -Message.prototype.toJSON = function toJSON() { - return this.$type.toObject(this, util.toJSONOptions); -}; - -/*eslint-enable valid-jsdoc*/ - -/***/ }), - -/***/ 57771: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Method; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; - -var util = __nccwpck_require__(47174); - -/** - * Constructs a new service method instance. - * @classdesc Reflected service method. - * @extends ReflectionObject - * @constructor - * @param {string} name Method name - * @param {string|undefined} type Method type, usually `"rpc"` - * @param {string} requestType Request message type - * @param {string} responseType Response message type - * @param {boolean|Object.} [requestStream] Whether the request is streamed - * @param {boolean|Object.} [responseStream] Whether the response is streamed - * @param {Object.} [options] Declared options - * @param {string} [comment] The comment for this method - * @param {Object.} [parsedOptions] Declared options, properly parsed into an object - */ -function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { - - /* istanbul ignore next */ - if (util.isObject(requestStream)) { - options = requestStream; - requestStream = responseStream = undefined; - } else if (util.isObject(responseStream)) { - options = responseStream; - responseStream = undefined; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; } - - /* istanbul ignore if */ - if (!(type === undefined || util.isString(type))) - throw TypeError("type must be a string"); - - /* istanbul ignore if */ - if (!util.isString(requestType)) - throw TypeError("requestType must be a string"); - - /* istanbul ignore if */ - if (!util.isString(responseType)) - throw TypeError("responseType must be a string"); - - ReflectionObject.call(this, name, options); - - /** - * Method type. - * @type {string} - */ - this.type = type || "rpc"; // toJSON - - /** - * Request type. - * @type {string} - */ - this.requestType = requestType; // toJSON, marker - - /** - * Whether requests are streamed or not. - * @type {boolean|undefined} - */ - this.requestStream = requestStream ? true : undefined; // toJSON - - /** - * Response type. - * @type {string} - */ - this.responseType = responseType; // toJSON - - /** - * Whether responses are streamed or not. - * @type {boolean|undefined} - */ - this.responseStream = responseStream ? true : undefined; // toJSON - - /** - * Resolved request type. - * @type {Type|null} - */ - this.resolvedRequestType = null; - - /** - * Resolved response type. - * @type {Type|null} - */ - this.resolvedResponseType = null; - - /** - * Comment for this method - * @type {string|null} - */ - this.comment = comment; - - /** - * Options properly parsed into an object - */ - this.parsedOptions = parsedOptions; -} - -/** - * Method descriptor. - * @interface IMethod - * @property {string} [type="rpc"] Method type - * @property {string} requestType Request type - * @property {string} responseType Response type - * @property {boolean} [requestStream=false] Whether requests are streamed - * @property {boolean} [responseStream=false] Whether responses are streamed - * @property {Object.} [options] Method options - * @property {string} comment Method comments - * @property {Object.} [parsedOptions] Method options properly parsed into an object - */ - -/** - * Constructs a method from a method descriptor. - * @param {string} name Method name - * @param {IMethod} json Method descriptor - * @returns {Method} Created method - * @throws {TypeError} If arguments are invalid - */ -Method.fromJSON = function fromJSON(name, json) { - return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); -}; - -/** - * Converts this method to a method descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IMethod} Method descriptor - */ -Method.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, - "requestType" , this.requestType, - "requestStream" , this.requestStream, - "responseType" , this.responseType, - "responseStream" , this.responseStream, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined, - "parsedOptions" , this.parsedOptions, - ]); -}; - -/** - * @override - */ -Method.prototype.resolve = function resolve() { - - /* istanbul ignore if */ - if (this.resolved) - return this; - - this.resolvedRequestType = this.parent.lookupType(this.requestType); - this.resolvedResponseType = this.parent.lookupType(this.responseType); - - return ReflectionObject.prototype.resolve.call(this); -}; - - -/***/ }), - -/***/ 76189: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Namespace; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; - -var Field = __nccwpck_require__(48213), - util = __nccwpck_require__(47174), - OneOf = __nccwpck_require__(44408); - -var Type, // cyclic - Service, - Enum; - -/** - * Constructs a new namespace instance. - * @name Namespace - * @classdesc Reflected namespace. - * @extends NamespaceBase - * @constructor - * @param {string} name Namespace name - * @param {Object.} [options] Declared options - */ - -/** - * Constructs a namespace from JSON. - * @memberof Namespace - * @function - * @param {string} name Namespace name - * @param {Object.} json JSON object - * @returns {Namespace} Created namespace - * @throws {TypeError} If arguments are invalid - */ -Namespace.fromJSON = function fromJSON(name, json) { - return new Namespace(name, json.options).addJSON(json.nested); -}; - -/** - * Converts an array of reflection objects to JSON. - * @memberof Namespace - * @param {ReflectionObject[]} array Object array - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {Object.|undefined} JSON object or `undefined` when array is empty - */ -function arrayToJSON(array, toJSONOptions) { - if (!(array && array.length)) - return undefined; - var obj = {}; - for (var i = 0; i < array.length; ++i) - obj[array[i].name] = array[i].toJSON(toJSONOptions); - return obj; -} - -Namespace.arrayToJSON = arrayToJSON; - -/** - * Tests if the specified id is reserved. - * @param {Array.|undefined} reserved Array of reserved ranges and names - * @param {number} id Id to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Namespace.isReservedId = function isReservedId(reserved, id) { - if (reserved) - for (var i = 0; i < reserved.length; ++i) - if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) - return true; - return false; -}; - -/** - * Tests if the specified name is reserved. - * @param {Array.|undefined} reserved Array of reserved ranges and names - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Namespace.isReservedName = function isReservedName(reserved, name) { - if (reserved) - for (var i = 0; i < reserved.length; ++i) - if (reserved[i] === name) - return true; - return false; -}; - -/** - * Not an actual constructor. Use {@link Namespace} instead. - * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. - * @exports NamespaceBase - * @extends ReflectionObject - * @abstract - * @constructor - * @param {string} name Namespace name - * @param {Object.} [options] Declared options - * @see {@link Namespace} - */ -function Namespace(name, options) { - ReflectionObject.call(this, name, options); - - /** - * Nested objects by name. - * @type {Object.|undefined} - */ - this.nested = undefined; // toJSON - - /** - * Cached nested objects as an array. - * @type {ReflectionObject[]|null} - * @private - */ - this._nestedArray = null; - - /** - * Cache lookup calls for any objects contains anywhere under this namespace. - * This drastically speeds up resolve for large cross-linked protos where the same - * types are looked up repeatedly. - * @type {Object.} - * @private - */ - this._lookupCache = {}; - - /** - * Whether or not objects contained in this namespace need feature resolution. - * @type {boolean} - * @protected - */ - this._needsRecursiveFeatureResolution = true; - - /** - * Whether or not objects contained in this namespace need a resolve. - * @type {boolean} - * @protected - */ - this._needsRecursiveResolve = true; -} - -function clearCache(namespace) { - namespace._nestedArray = null; - namespace._lookupCache = {}; - - // Also clear parent caches, since they include nested lookups. - var parent = namespace; - while(parent = parent.parent) { - parent._lookupCache = {}; + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; } - return namespace; -} - -/** - * Nested objects of this namespace as an array for iteration. - * @name NamespaceBase#nestedArray - * @type {ReflectionObject[]} - * @readonly - */ -Object.defineProperty(Namespace.prototype, "nestedArray", { - get: function() { - return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); } -}); - -/** - * Namespace descriptor. - * @interface INamespace - * @property {Object.} [options] Namespace options - * @property {Object.} [nested] Nested object descriptors - */ - -/** - * Any extension field descriptor. - * @typedef AnyExtensionField - * @type {IExtensionField|IExtensionMapField} - */ - -/** - * Any nested object descriptor. - * @typedef AnyNestedObject - * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} - */ - -/** - * Converts this namespace to a namespace descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {INamespace} Namespace descriptor - */ -Namespace.prototype.toJSON = function toJSON(toJSONOptions) { - return util.toObject([ - "options" , this.options, - "nested" , arrayToJSON(this.nestedArray, toJSONOptions) - ]); + return cache[methodName]; + } }; - -/** - * Adds nested objects to this namespace from nested object descriptors. - * @param {Object.} nestedJson Any nested object descriptors - * @returns {Namespace} `this` - */ -Namespace.prototype.addJSON = function addJSON(nestedJson) { - var ns = this; - /* istanbul ignore else */ - if (nestedJson) { - for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { - nested = nestedJson[names[i]]; - ns.add( // most to least likely - ( nested.fields !== undefined - ? Type.fromJSON - : nested.values !== undefined - ? Enum.fromJSON - : nested.methods !== undefined - ? Service.fromJSON - : nested.id !== undefined - ? Field.fromJSON - : Namespace.fromJSON )(names[i], nested) - ); - } +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); + } + return newMethods; +} +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); } - return this; -}; - -/** - * Gets the nested object of the specified name. - * @param {string} name Nested object name - * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist - */ -Namespace.prototype.get = function get(name) { - return this.nested && this.nested[name] - || null; -}; - -/** - * Gets the values of the nested {@link Enum|enum} of the specified name. - * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. - * @param {string} name Nested enum name - * @returns {Object.} Enum values - * @throws {Error} If there is no such enum - */ -Namespace.prototype.getEnum = function getEnum(name) { - if (this.nested && this.nested[name] instanceof Enum) - return this.nested[name].values; - throw Error("no such enum: " + name); -}; - -/** - * Adds a nested object to this namespace. - * @param {ReflectionObject} object Nested object to add - * @returns {Namespace} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If there is already a nested object with this name - */ -Namespace.prototype.add = function add(object) { - - if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) - throw TypeError("object must be a valid nested object"); - - if (!this.nested) - this.nested = {}; - else { - var prev = this.get(object.name); - if (prev) { - if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { - // replace plain namespace but keep existing nested elements and options - var nested = prev.nestedArray; - for (var i = 0; i < nested.length; ++i) - object.add(nested[i]); - this.remove(prev); - if (!this.nested) - this.nested = {}; - object.setOptions(prev.options, true); - - } else - throw Error("duplicate name '" + object.name + "' in " + this); - } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); } - this.nested[object.name] = object; - - if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { - // This is a package or a root namespace. - if (!object._edition) { - // Make sure that some edition is set if it hasn't already been specified. - object._edition = object._defaultEdition; - } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); } - - this._needsRecursiveFeatureResolution = true; - this._needsRecursiveResolve = true; - - // Also clear parent caches, since they need to recurse down. - var parent = this; - while(parent = parent.parent) { - parent._needsRecursiveFeatureResolution = true; - parent._needsRecursiveResolve = true; + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); } + return requestWithDefaults(...args); + } + return Object.assign(withDecorations, requestWithDefaults); +} - object.onAdd(this); - return clearCache(this); -}; - -/** - * Removes a nested object from this namespace. - * @param {ReflectionObject} object Nested object to remove - * @returns {Namespace} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If `object` is not a member of this namespace - */ -Namespace.prototype.remove = function remove(object) { +// pkg/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +legacyRestEndpointMethods.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - if (!(object instanceof ReflectionObject)) - throw TypeError("object must be a ReflectionObject"); - if (object.parent !== this) - throw Error(object + " is not a member of " + this); - delete this.nested[object.name]; - if (!Object.keys(this.nested).length) - this.nested = undefined; +/***/ }), - object.onRemove(this); - return clearCache(this); -}; +/***/ 537: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Defines additial namespaces within this one if not yet existing. - * @param {string|string[]} path Path to create - * @param {*} [json] Nested types to create from JSON - * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty - */ -Namespace.prototype.define = function define(path, json) { - - if (util.isString(path)) - path = path.split("."); - else if (!Array.isArray(path)) - throw TypeError("illegal path"); - if (path && path.length && path[0] === "") - throw Error("path must be relative"); - - var ptr = this; - while (path.length > 0) { - var part = path.shift(); - if (ptr.nested && ptr.nested[part]) { - ptr = ptr.nested[part]; - if (!(ptr instanceof Namespace)) - throw Error("path conflicts with non-namespace objects"); - } else - ptr.add(ptr = new Namespace(part)); - } - if (json) - ptr.addJSON(json); - return ptr; -}; +"use strict"; -/** - * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. - * @returns {Namespace} `this` - */ -Namespace.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - this._resolveFeaturesRecursive(this._edition); - - var nested = this.nestedArray, i = 0; - this.resolve(); - while (i < nested.length) - if (nested[i] instanceof Namespace) - nested[i++].resolveAll(); - else - nested[i++].resolve(); - this._needsRecursiveResolve = false; - return this; +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 }); }; - -/** - * @override - */ -Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - this._needsRecursiveFeatureResolution = false; - - edition = this._edition || edition; - - ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); - this.nestedArray.forEach(nested => { - nested._resolveFeaturesRecursive(edition); - }); - return this; +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); -/** - * Recursively looks up the reflection object matching the specified path in the scope of this namespace. - * @param {string|string[]} path Path to look up - * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. - * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked - * @returns {ReflectionObject|null} Looked up object or `null` if none could be found - */ -Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { - /* istanbul ignore next */ - if (typeof filterTypes === "boolean") { - parentAlreadyChecked = filterTypes; - filterTypes = undefined; - } else if (filterTypes && !Array.isArray(filterTypes)) - filterTypes = [ filterTypes ]; - - if (util.isString(path) && path.length) { - if (path === ".") - return this.root; - path = path.split("."); - } else if (!path.length) - return this; - - var flatPath = path.join("."); - - // Start at root if path is absolute - if (path[0] === "") - return this.root.lookup(path.slice(1), filterTypes); - - // Early bailout for objects with matching absolute paths - var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - - // Do a regular lookup at this namespace and below - found = this._lookupImpl(path, flatPath); - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; +// 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__(8932); +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); } - - if (parentAlreadyChecked) - return null; - - // If there hasn't been a match, walk up the tree and look more broadly - var current = this; - while (current.parent) { - found = current.parent._lookupImpl(path, flatPath); - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - current = current.parent; + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; } - return null; -}; - -/** - * Internal helper for lookup that handles searching just at this namespace and below along with caching. - * @param {string[]} path Path to look up - * @param {string} flatPath Flattened version of the path to use as a cache key - * @returns {ReflectionObject|null} Looked up object or `null` if none could be found - * @private - */ -Namespace.prototype._lookupImpl = function lookup(path, flatPath) { - if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { - return this._lookupCache[flatPath]; + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; } - - // Test if the first part matches any nested object, and if so, traverse if path contains more - var found = this.get(path[0]); - var exact = null; - if (found) { - if (path.length === 1) { - exact = found; - } else if (found instanceof Namespace) { - path = path.slice(1); - exact = found._lookupImpl(path, path.join(".")); - } - - // Otherwise try each nested namespace - } else { - for (var i = 0; i < this.nestedArray.length; ++i) - if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) - exact = found; + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { "use strict"; -module.exports = ReflectionObject; - -ReflectionObject.className = "ReflectionObject"; - -const OneOf = __nccwpck_require__(44408); -var util = __nccwpck_require__(47174); - -var Root; // cyclic - -/* eslint-disable no-warning-comments */ -// TODO: Replace with embedded proto. -var editions2023Defaults = {enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; -var proto2Defaults = {enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE"}; -var proto3Defaults = {enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; - -/** - * Constructs a new reflection object instance. - * @classdesc Base class of all reflection objects. - * @constructor - * @param {string} name Object name - * @param {Object.} [options] Declared options - * @abstract - */ -function ReflectionObject(name, options) { - - if (!util.isString(name)) - throw TypeError("name must be a string"); - - if (options && !util.isObject(options)) - throw TypeError("options must be an object"); - - /** - * Options. - * @type {Object.|undefined} - */ - this.options = options; // toJSON - - /** - * Parsed Options. - * @type {Array.>|undefined} - */ - this.parsedOptions = null; - - /** - * Unique name within its namespace. - * @type {string} - */ - this.name = name; - - /** - * The edition specified for this object. Only relevant for top-level objects. - * @type {string} - * @private - */ - this._edition = null; - - /** - * The default edition to use for this object if none is specified. For legacy reasons, - * this is proto2 except in the JSON parsing case where it was proto3. - * @type {string} - * @private - */ - this._defaultEdition = "proto2"; - - /** - * Resolved Features. - * @type {object} - * @private - */ - this._features = {}; - - /** - * Whether or not features have been resolved. - * @type {boolean} - * @private - */ - this._featuresResolved = false; - - /** - * Parent namespace. - * @type {Namespace|null} - */ - this.parent = null; - - /** - * Whether already resolved or not. - * @type {boolean} - */ - this.resolved = false; - - /** - * Comment text, if any. - * @type {string|null} - */ - this.comment = null; - - /** - * Defining file name. - * @type {string|null} - */ - this.filename = null; -} - -Object.defineProperties(ReflectionObject.prototype, { - - /** - * Reference to the root namespace. - * @name ReflectionObject#root - * @type {Root} - * @readonly - */ - root: { - get: function() { - var ptr = this; - while (ptr.parent !== null) - ptr = ptr.parent; - return ptr; - } - }, - - /** - * Full name including leading dot. - * @name ReflectionObject#fullName - * @type {string} - * @readonly - */ - fullName: { - get: function() { - var path = [ this.name ], - ptr = this.parent; - while (ptr) { - path.unshift(ptr.name); - ptr = ptr.parent; - } - return path.join("."); - } - } -}); - -/** - * Converts this reflection object to its descriptor representation. - * @returns {Object.} Descriptor - * @abstract - */ -ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { - throw Error(); // not implemented, shouldn't happen -}; - -/** - * Called when this object is added to a parent. - * @param {ReflectionObject} parent Parent added to - * @returns {undefined} - */ -ReflectionObject.prototype.onAdd = function onAdd(parent) { - if (this.parent && this.parent !== parent) - this.parent.remove(this); - this.parent = parent; - this.resolved = false; - var root = parent.root; - if (root instanceof Root) - root._handleAdd(this); -}; - -/** - * Called when this object is removed from a parent. - * @param {ReflectionObject} parent Parent removed from - * @returns {undefined} - */ -ReflectionObject.prototype.onRemove = function onRemove(parent) { - var root = parent.root; - if (root instanceof Root) - root._handleRemove(this); - this.parent = null; - this.resolved = false; +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 }); }; - -/** - * Resolves this objects type references. - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.resolve = function resolve() { - if (this.resolved) - return this; - if (this.root instanceof Root) - this.resolved = true; // only if part of a root - return this; +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); -/** - * Resolves this objects editions features. - * @param {string} edition The edition we're currently resolving for. - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - return this._resolveFeatures(this._edition || edition); -}; +// 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__(9440); +var import_universal_user_agent = __nccwpck_require__(5030); -/** - * Resolves child features from parent features - * @param {string} edition The edition we're currently resolving for. - * @returns {undefined} - */ -ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { - if (this._featuresResolved) { - return; - } +// pkg/dist-src/version.js +var VERSION = "8.4.1"; - var defaults = {}; +// 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); +} - /* istanbul ignore if */ - if (!edition) { - throw new Error("Unknown edition for " + this.fullName); - } +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(537); - var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {}, - this._inferLegacyProtoFeatures(edition)); +// pkg/dist-src/get-buffer-response.js +function getBufferResponse(response) { + return response.arrayBuffer(); +} - if (this._edition) { - // For a namespace marked with a specific edition, reset defaults. - /* istanbul ignore else */ - if (edition === "proto2") { - defaults = Object.assign({}, proto2Defaults); - } else if (edition === "proto3") { - defaults = Object.assign({}, proto3Defaults); - } else if (edition === "2023") { - defaults = Object.assign({}, editions2023Defaults); - } else { - throw new Error("Unknown edition: " + edition); - } - this._features = Object.assign(defaults, protoFeatures || {}); - this._featuresResolved = true; - return; +// pkg/dist-src/fetch-wrapper.js +function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + 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, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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]; } - - // fields in Oneofs aren't actually children of them, so we have to - // special-case it - /* istanbul ignore else */ - if (this.partOf instanceof OneOf) { - var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features); - this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {}); - } else if (this.declaringField) { - // Skip feature resolution of sister fields. - } else if (this.parent) { - var parentFeaturesCopy = Object.assign({}, this.parent._features); - this._features = Object.assign(parentFeaturesCopy, protoFeatures || {}); - } else { - throw new Error("Unable to find a parent for " + this.fullName); + 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 (this.extensionField) { - // Sister fields should have the same features as their extensions. - this.extensionField._features = this._features; + if (status === 204 || status === 205) { + return; } - this._featuresResolved = true; -}; - -/** - * Infers features from legacy syntax that may have been specified differently. - * in older editions. - * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions - * @returns {object} The feature values to override - */ -ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) { - return {}; -}; - -/** - * Gets an option value. - * @param {string} name Option name - * @returns {*} Option value or `undefined` if not set - */ -ReflectionObject.prototype.getOption = function getOption(name) { - if (this.options) - return this.options[name]; - return undefined; -}; - -/** - * Sets an option. - * @param {string} name Option name - * @param {*} value Option value - * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { - if (!this.options) - this.options = {}; - if (/^features\./.test(name)) { - util.setProperty(this.options, name, value, ifNotSet); - } else if (!ifNotSet || this.options[name] === undefined) { - if (this.getOption(name) !== value) this.resolved = false; - this.options[name] = value; + 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 + }); } - - return this; -}; - -/** - * Sets a parsed option. - * @param {string} name parsed Option name - * @param {*} value Option value - * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { - if (!this.parsedOptions) { - this.parsedOptions = []; - } - var parsedOptions = this.parsedOptions; - if (propName) { - // If setting a sub property of an option then try to merge it - // with an existing option - var opt = parsedOptions.find(function (opt) { - return Object.prototype.hasOwnProperty.call(opt, name); - }); - if (opt) { - // If we found an existing option - just merge the property value - // (If it's a feature, will just write over) - var newValue = opt[name]; - util.setProperty(newValue, propName, value); - } else { - // otherwise, create a new option, set its property and add it to the list - opt = {}; - opt[name] = util.setProperty({}, propName, value); - parsedOptions.push(opt); - } - } else { - // Always create a new option when setting the value of the option itself - var newOpt = {}; - newOpt[name] = value; - parsedOptions.push(newOpt); + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); } - - return this; -}; - -/** - * Sets multiple options. - * @param {Object.} options Options to set - * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { - if (options) - for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) - this.setOption(keys[i], options[keys[i]], ifNotSet); - return this; -}; - -/** - * Converts this instance to its string representation. - * @returns {string} Class name[, space, full name] - */ -ReflectionObject.prototype.toString = function toString() { - var className = this.constructor.className, - fullName = this.fullName; - if (fullName.length) - return className + " " + fullName; - return className; -}; - -/** - * Converts the edition this object is pinned to for JSON format. - * @returns {string|undefined} The edition string for JSON representation - */ -ReflectionObject.prototype._editionToJSON = function _editionToJSON() { - if (!this._edition || this._edition === "proto3") { - // Avoid emitting proto3 since we need to default to it for backwards - // compatibility anyway. - return undefined; + 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 this._edition; -}; - -// Sets up cyclic dependencies (called in index-light) -ReflectionObject._configure = function(Root_) { - Root = Root_; -}; - - -/***/ }), - -/***/ 44408: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = OneOf; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; - -var Field = __nccwpck_require__(48213), - util = __nccwpck_require__(47174); - -/** - * Constructs a new oneof instance. - * @classdesc Reflected oneof. - * @extends ReflectionObject - * @constructor - * @param {string} name Oneof name - * @param {string[]|Object.} [fieldNames] Field names - * @param {Object.} [options] Declared options - * @param {string} [comment] Comment associated with this field - */ -function OneOf(name, fieldNames, options, comment) { - if (!Array.isArray(fieldNames)) { - options = fieldNames; - fieldNames = undefined; + 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; + } } - ReflectionObject.call(this, name, options); - - /* istanbul ignore if */ - if (!(fieldNames === undefined || Array.isArray(fieldNames))) - throw TypeError("fieldNames must be an Array"); - - /** - * Field names that belong to this oneof. - * @type {string[]} - */ - this.oneof = fieldNames || []; // toJSON, marker - - /** - * Fields that belong to this oneof as an array for iteration. - * @type {Field[]} - * @readonly - */ - this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent - - /** - * Comment for this field. - * @type {string|null} - */ - this.comment = comment; + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); } - -/** - * Oneof descriptor. - * @interface IOneOf - * @property {Array.} oneof Oneof field names - * @property {Object.} [options] Oneof options - */ - -/** - * Constructs a oneof from a oneof descriptor. - * @param {string} name Oneof name - * @param {IOneOf} json Oneof descriptor - * @returns {OneOf} Created oneof - * @throws {TypeError} If arguments are invalid - */ -OneOf.fromJSON = function fromJSON(name, json) { - return new OneOf(name, json.oneof, json.options, json.comment); -}; - -/** - * Converts this oneof to a oneof descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IOneOf} Oneof descriptor - */ -OneOf.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "options" , this.options, - "oneof" , this.oneof, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * Adds the fields of the specified oneof to the parent if not already done so. - * @param {OneOf} oneof The oneof - * @returns {undefined} - * @inner - * @ignore - */ -function addFieldsToParent(oneof) { - if (oneof.parent) - for (var i = 0; i < oneof.fieldsArray.length; ++i) - if (!oneof.fieldsArray[i].parent) - oneof.parent.add(oneof.fieldsArray[i]); +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)}`; } -/** - * Adds a field to this oneof and removes it from its current parent, if any. - * @param {Field} field Field to add - * @returns {OneOf} `this` - */ -OneOf.prototype.add = function add(field) { - - /* istanbul ignore if */ - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); - - if (field.parent && field.parent !== this.parent) - field.parent.remove(field); - this.oneof.push(field.name); - this.fieldsArray.push(field); - field.partOf = this; // field.parent remains null - addFieldsToParent(this); - return this; -}; - -/** - * Removes a field from this oneof and puts it back to the oneof's parent. - * @param {Field} field Field to remove - * @returns {OneOf} `this` - */ -OneOf.prototype.remove = function remove(field) { - - /* istanbul ignore if */ - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); - - var index = this.fieldsArray.indexOf(field); - - /* istanbul ignore if */ - if (index < 0) - throw Error(field + " is not a member of " + this); - - this.fieldsArray.splice(index, 1); - index = this.oneof.indexOf(field.name); - - /* istanbul ignore else */ - if (index > -1) // theoretical - this.oneof.splice(index, 1); - - field.partOf = null; - return this; -}; - -/** - * @override - */ -OneOf.prototype.onAdd = function onAdd(parent) { - ReflectionObject.prototype.onAdd.call(this, parent); - var self = this; - // Collect present fields - for (var i = 0; i < this.oneof.length; ++i) { - var field = parent.get(this.oneof[i]); - if (field && !field.partOf) { - field.partOf = self; - self.fieldsArray.push(field); - } - } - // Add not yet present fields - addFieldsToParent(this); -}; +// 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) + }); +} -/** - * @override - */ -OneOf.prototype.onRemove = function onRemove(parent) { - for (var i = 0, field; i < this.fieldsArray.length; ++i) - if ((field = this.fieldsArray[i]).parent) - field.parent.remove(field); - ReflectionObject.prototype.onRemove.call(this, parent); -}; +// 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); -/** - * Determines whether this field corresponds to a synthetic oneof created for - * a proto3 optional field. No behavioral logic should depend on this, but it - * can be relevant for reflection. - * @name OneOf#isProto3Optional - * @type {boolean} - * @readonly - */ -Object.defineProperty(OneOf.prototype, "isProto3Optional", { - get: function() { - if (this.fieldsArray == null || this.fieldsArray.length !== 1) { - return false; - } - var field = this.fieldsArray[0]; - return field.options != null && field.options["proto3_optional"] === true; - } -}); +/***/ }), -/** - * Decorator function as returned by {@link OneOf.d} (TypeScript). - * @typedef OneOfDecorator - * @type {function} - * @param {Object} prototype Target prototype - * @param {string} oneofName OneOf name - * @returns {undefined} - */ +/***/ 9809: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * OneOf decorator (TypeScript). - * @function - * @param {...string} fieldNames Field names - * @returns {OneOfDecorator} Decorator function - * @template T extends string - */ -OneOf.d = function decorateOneOf() { - var fieldNames = new Array(arguments.length), - index = 0; - while (index < arguments.length) - fieldNames[index] = arguments[index++]; - return function oneOfDecorator(prototype, oneofName) { - util.decorateType(prototype.constructor) - .add(new OneOf(oneofName, fieldNames)); - Object.defineProperty(prototype, oneofName, { - get: util.oneOfGetter(fieldNames), - set: util.oneOfSetter(fieldNames) - }); - }; -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(6575)); +const AuthAdminApi = GoTrueAdminApi_1.default; +exports["default"] = AuthAdminApi; +//# sourceMappingURL=AuthAdminApi.js.map /***/ }), -/***/ 32137: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4525: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -module.exports = parse; - -parse.filename = null; -parse.defaults = { keepCase: false }; - -var tokenize = __nccwpck_require__(61157), - Root = __nccwpck_require__(32614), - Type = __nccwpck_require__(38520), - Field = __nccwpck_require__(48213), - MapField = __nccwpck_require__(67777), - OneOf = __nccwpck_require__(44408), - Enum = __nccwpck_require__(17732), - Service = __nccwpck_require__(6178), - Method = __nccwpck_require__(57771), - ReflectionObject = __nccwpck_require__(83575), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -var base10Re = /^[1-9][0-9]*$/, - base10NegRe = /^-?[1-9][0-9]*$/, - base16Re = /^0[x][0-9a-fA-F]+$/, - base16NegRe = /^-?0[x][0-9a-fA-F]+$/, - base8Re = /^0[0-7]+$/, - base8NegRe = /^-?0[0-7]+$/, - numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, - nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, - typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/; - -/** - * Result object returned from {@link parse}. - * @interface IParserResult - * @property {string|undefined} package Package name, if declared - * @property {string[]|undefined} imports Imports, if any - * @property {string[]|undefined} weakImports Weak imports, if any - * @property {Root} root Populated root instance - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(313)); +const AuthClient = GoTrueClient_1.default; +exports["default"] = AuthClient; +//# sourceMappingURL=AuthClient.js.map -/** - * Options modifying the behavior of {@link parse}. - * @interface IParseOptions - * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case - * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments. - * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist. - */ +/***/ }), -/** - * Options modifying the behavior of JSON serialization. - * @interface IToJSONOptions - * @property {boolean} [keepComments=false] Serializes comments. - */ +/***/ 6575: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Parses the given .proto source and returns an object with the parsed contents. - * @param {string} source Source contents - * @param {Root} root Root to populate - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {IParserResult} Parser result - * @property {string} filename=null Currently processing file name for error reporting, if known - * @property {IParseOptions} defaults Default {@link IParseOptions} - */ -function parse(source, root, options) { - /* eslint-disable callback-return */ - if (!(root instanceof Root)) { - options = root; - root = new Root(); - } - if (!options) - options = parse.defaults; - - var preferTrailingComment = options.preferTrailingComment || false; - var tn = tokenize(source, options.alternateCommentMode || false), - next = tn.next, - push = tn.push, - peek = tn.peek, - skip = tn.skip, - cmnt = tn.cmnt; - - var head = true, - pkg, - imports, - weakImports, - edition = "proto2"; - - var ptr = root; - - var topLevelObjects = []; - var topLevelOptions = {}; - - var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; - - function resolveFileFeatures() { - topLevelObjects.forEach(obj => { - obj._edition = edition; - Object.keys(topLevelOptions).forEach(opt => { - if (obj.getOption(opt) !== undefined) return; - obj.setOption(opt, topLevelOptions[opt], true); - }); - }); - } +"use strict"; - /* istanbul ignore next */ - function illegal(token, name, insideTryCatch) { - var filename = parse.filename; - if (!insideTryCatch) - parse.filename = null; - return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const fetch_1 = __nccwpck_require__(7072); +const helpers_1 = __nccwpck_require__(4044); +const types_1 = __nccwpck_require__(1852); +const errors_1 = __nccwpck_require__(9938); +class GoTrueAdminApi { + constructor({ url = '', headers = {}, fetch, }) { + this.url = url; + this.headers = headers; + this.fetch = (0, helpers_1.resolveFetch)(fetch); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + }; + this.oauth = { + listClients: this._listOAuthClients.bind(this), + createClient: this._createOAuthClient.bind(this), + getClient: this._getOAuthClient.bind(this), + updateClient: this._updateOAuthClient.bind(this), + deleteClient: this._deleteOAuthClient.bind(this), + regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this), + }; } - - function readString() { - var values = [], - token; - do { - /* istanbul ignore if */ - if ((token = next()) !== "\"" && token !== "'") - throw illegal(token); - - values.push(next()); - skip(token); - token = peek(); - } while (token === "\"" || token === "'"); - return values.join(""); - } - - function readValue(acceptTypeRef) { - var token = next(); - switch (token) { - case "'": - case "\"": - push(token); - return readString(); - case "true": case "TRUE": - return true; - case "false": case "FALSE": - return false; + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) { + if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) { + throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`); } try { - return parseNumber(token, /* insideTryCatch */ true); - } catch (e) { - /* istanbul ignore else */ - if (acceptTypeRef && typeRefRe.test(token)) - return token; - - /* istanbul ignore next */ - throw illegal(token, "value"); + await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }); + return { data: null, error: null }; } - } - - function readRanges(target, acceptStrings) { - var token, start; - do { - if (acceptStrings && ((token = peek()) === "\"" || token === "'")) { - var str = readString(); - target.push(str); - if (edition >= 2023) { - throw illegal(str, "id"); - } - } else { - try { - target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); - } catch (err) { - if (acceptStrings && typeRefRe.test(token) && edition >= 2023) { - target.push(token); - } else { - throw err; - } - } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; } - } while (skip(",", true)); - var dummy = {options: undefined}; - dummy.setOption = function(name, value) { - if (this.options === undefined) this.options = {}; - this.options[name] = value; - }; - ifBlock( - dummy, - function parseRange_block(token) { - /* istanbul ignore else */ - if (token === "option") { - parseOption(dummy, token); // skip - skip(";"); - } else - throw illegal(token); - }, - function parseRange_line() { - parseInlineOptions(dummy); // skip - }); + throw error; + } } - - function parseNumber(token, insideTryCatch) { - var sign = 1; - if (token.charAt(0) === "-") { - sign = -1; - token = token.substring(1); + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: fetch_1._userResponse, + }); } - switch (token) { - case "inf": case "INF": case "Inf": - return sign * Infinity; - case "nan": case "NAN": case "Nan": case "NaN": - return NaN; - case "0": - return 0; + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; } - if (base10Re.test(token)) - return sign * parseInt(token, 10); - if (base16Re.test(token)) - return sign * parseInt(token, 16); - if (base8Re.test(token)) - return sign * parseInt(token, 8); - - /* istanbul ignore else */ - if (numberRe.test(token)) - return sign * parseFloat(token); - - /* istanbul ignore next */ - throw illegal(token, "number", insideTryCatch); } - - function parseId(token, acceptNegative) { - switch (token) { - case "max": case "MAX": case "Max": - return 536870911; - case "0": - return 0; + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = tslib_1.__rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body['newEmail']; + } + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: fetch_1._generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, + }); } - - /* istanbul ignore if */ - if (!acceptNegative && token.charAt(0) === "-") - throw illegal(token, "id"); - - if (base10NegRe.test(token)) - return parseInt(token, 10); - if (base16NegRe.test(token)) - return parseInt(token, 16); - - /* istanbul ignore else */ - if (base8NegRe.test(token)) - return parseInt(token, 8); - - /* istanbul ignore next */ - throw illegal(token, "id"); - } - - function parsePackage() { - /* istanbul ignore if */ - if (pkg !== undefined) - throw illegal("package"); - - pkg = next(); - - /* istanbul ignore if */ - if (!typeRefRe.test(pkg)) - throw illegal(pkg, "name"); - - ptr = ptr.define(pkg); - - skip(";"); - } - - function parseImport() { - var token = peek(); - var whichImports; - switch (token) { - case "weak": - whichImports = weakImports || (weakImports = []); - next(); - break; - case "public": - next(); - // eslint-disable-next-line no-fallthrough - default: - whichImports = imports || (imports = []); - break; + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + }; + } + throw error; } - token = readString(); - skip(";"); - whichImports.push(token); - } - - function parseSyntax() { - skip("="); - edition = readString(); - - /* istanbul ignore if */ - if (edition < 2023) - throw illegal(edition, "syntax"); - - skip(";"); } - - function parseEdition() { - skip("="); - edition = readString(); - const supportedEditions = ["2023"]; - - /* istanbul ignore if */ - if (!supportedEditions.includes(edition)) - throw illegal(edition, "edition"); - - skip(";"); - } - - - function parseCommon(parent, token) { - switch (token) { - - case "option": - parseOption(parent, token); - skip(";"); - return true; - - case "message": - parseType(parent, token); - return true; - - case "enum": - parseEnum(parent, token); - return true; - - case "service": - parseService(parent, token); - return true; - - case "extend": - parseExtension(parent, token); - return true; + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; } - return false; } - - function ifBlock(obj, fnIf, fnElse) { - var trailingLine = tn.line; - if (obj) { - if(typeof obj.comment !== "string") { - obj.comment = cmnt(); // try block-type comment + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: fetch_1._noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); } - obj.filename = parse.filename; + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; } - if (skip("{", true)) { - var token; - while ((token = next()) !== "}") - fnIf(token); - skip(";", true); - } else { - if (fnElse) - fnElse(); - skip(";"); - if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) - obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { users: [] }, error }; + } + throw error; } } - - function parseType(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "type name"); - - var type = new Type(token); - ifBlock(type, function parseType_block(token) { - if (parseCommon(type, token)) - return; - - switch (token) { - - case "map": - parseMapField(type, token); - break; - - case "required": - if (edition !== "proto2") - throw illegal(token); - /* eslint-disable no-fallthrough */ - case "repeated": - parseField(type, token); - break; - - case "optional": - /* istanbul ignore if */ - if (edition === "proto3") { - parseField(type, "proto3_optional"); - } else if (edition !== "proto2") { - throw illegal(token); - } else { - parseField(type, "optional"); - } - break; - - case "oneof": - parseOneOf(type, token); - break; - - case "extensions": - readRanges(type.extensions || (type.extensions = [])); - break; - - case "reserved": - readRanges(type.reserved || (type.reserved = []), true); - break; - - default: - /* istanbul ignore if */ - if (edition === "proto2" || !typeRefRe.test(token)) { - throw illegal(token); - } - - push(token); - parseField(type, "optional"); - break; + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; } - }); - parent.add(type); - if (parent === ptr) { - topLevelObjects.push(type); + throw error; } } - - function parseField(parent, rule, extend) { - var type = next(); - if (type === "group") { - parseGroup(parent, rule); - return; + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); } - // Type names can consume multiple tokens, in multiple variants: - // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field" - // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field" - // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field" - // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field" - // Keep reading tokens until we get a type name with no period at the end, - // and the next token does not start with a period. - while (type.endsWith(".") || peek().startsWith(".")) { - type += next(); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; } - - /* istanbul ignore if */ - if (!typeRefRe.test(type)) - throw illegal(type, "type"); - - var name = next(); - - /* istanbul ignore if */ - - if (!nameRe.test(name)) - throw illegal(name, "name"); - - name = applyCase(name); - skip("="); - - var field = new Field(name, parseId(next()), type, rule, extend); - - ifBlock(field, function parseField_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(field, token); - skip(";"); - } else - throw illegal(token); - - }, function parseField_line() { - parseInlineOptions(field); - }); - - if (rule === "proto3_optional") { - // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior - var oneof = new OneOf("_" + name); - field.setOption("proto3_optional", true); - oneof.add(field); - parent.add(oneof); - } else { - parent.add(field); + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + (0, helpers_1.validateUUID)(id); + try { + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: fetch_1._userResponse, + }); } - if (parent === ptr) { - topLevelObjects.push(field); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; } } - - function parseGroup(parent, rule) { - if (edition >= 2023) { - throw illegal("group"); + async _listFactors(params) { + (0, helpers_1.validateUUID)(params.userId); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + }, + }); + return { data, error }; } - var name = next(); - - /* istanbul ignore if */ - if (!nameRe.test(name)) - throw illegal(name, "name"); - - var fieldName = util.lcFirst(name); - if (name === fieldName) - name = util.ucFirst(name); - skip("="); - var id = parseId(next()); - var type = new Type(name); - type.group = true; - var field = new Field(fieldName, id, name, rule); - field.filename = parse.filename; - ifBlock(type, function parseGroup_block(token) { - switch (token) { - - case "option": - parseOption(type, token); - skip(";"); - break; - case "required": - case "repeated": - parseField(type, token); - break; - - case "optional": - /* istanbul ignore if */ - if (edition === "proto3") { - parseField(type, "proto3_optional"); - } else { - parseField(type, "optional"); - } - break; - - case "message": - parseType(type, token); - break; - - case "enum": - parseEnum(type, token); - break; - - case "reserved": - readRanges(type.reserved || (type.reserved = []), true); - break; - - /* istanbul ignore next */ - default: - throw illegal(token); // there are no groups with proto3 semantics + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; } - }); - parent.add(type) - .add(field); - } - - function parseMapField(parent) { - skip("<"); - var keyType = next(); - - /* istanbul ignore if */ - if (types.mapKey[keyType] === undefined) - throw illegal(keyType, "type"); - - skip(","); - var valueType = next(); - - /* istanbul ignore if */ - if (!typeRefRe.test(valueType)) - throw illegal(valueType, "type"); - - skip(">"); - var name = next(); - - /* istanbul ignore if */ - if (!nameRe.test(name)) - throw illegal(name, "name"); - - skip("="); - var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); - ifBlock(field, function parseMapField_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(field, token); - skip(";"); - } else - throw illegal(token); - - }, function parseMapField_line() { - parseInlineOptions(field); - }); - parent.add(field); + throw error; + } } - - function parseOneOf(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var oneof = new OneOf(applyCase(token)); - ifBlock(oneof, function parseOneOf_block(token) { - if (token === "option") { - parseOption(oneof, token); - skip(";"); - } else { - push(token); - parseField(oneof, "optional"); + async _deleteFactor(params) { + (0, helpers_1.validateUUID)(params.userId); + (0, helpers_1.validateUUID)(params.id); + try { + const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; } - }); - parent.add(oneof); - } - - function parseEnum(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var enm = new Enum(token); - ifBlock(enm, function parseEnum_block(token) { - switch(token) { - case "option": - parseOption(enm, token); - skip(";"); - break; - - case "reserved": - readRanges(enm.reserved || (enm.reserved = []), true); - if(enm.reserved === undefined) enm.reserved = []; - break; - - default: - parseEnumValue(enm, token); - } - }); - parent.add(enm); - if (parent === ptr) { - topLevelObjects.push(enm); + throw error; } } - - function parseEnumValue(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token)) - throw illegal(token, "name"); - - skip("="); - var value = parseId(next(), true), - dummy = { - options: undefined - }; - dummy.getOption = function(name) { - return this.options[name]; - }; - dummy.setOption = function(name, value) { - ReflectionObject.prototype.setOption.call(dummy, name, value); - }; - dummy.setParsedOption = function() { - return undefined; - }; - ifBlock(dummy, function parseEnumValue_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(dummy, token); // skip - skip(";"); - } else - throw illegal(token); - - }, function parseEnumValue_line() { - parseInlineOptions(dummy); // skip - }); - parent.add(token, value, dummy.comment, dummy.parsedOptions || dummy.options); - } - - function parseOption(parent, token) { - var option; - var propName; - var isOption = true; - if (token === "option") { - token = next(); + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _listOAuthClients(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: fetch_1._noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const clients = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); } - - while (token !== "=") { - if (token === "(") { - var parensValue = next(); - skip(")"); - token = "(" + parensValue + ")"; - } - if (isOption) { - isOption = false; - if (token.includes(".") && !token.includes("(")) { - var tokens = token.split("."); - option = tokens[0] + "."; - token = tokens[1]; - continue; - } - option = token; - } else { - propName = propName ? propName += token : token; - } - token = next(); + return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { clients: [] }, error }; } - var name = propName ? option.concat(propName) : option; - var optionValue = parseOptionValue(parent, name); - propName = propName && propName[0] === "." ? propName.slice(1) : propName; - option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option; - setParsedOption(parent, option, optionValue, propName); + throw error; + } } - - function parseOptionValue(parent, name) { - // { a: "foo" b { c: "bar" } } - if (skip("{", true)) { - var objectResult = {}; - - while (!skip("}", true)) { - /* istanbul ignore if */ - if (!nameRe.test(token = next())) { - throw illegal(token, "name"); - } - if (token === null) { - throw illegal(token, "end of input"); - } - - var value; - var propName = token; - - skip(":", true); - - if (peek() === "{") { - // option (my_option) = { - // repeated_value: [ "foo", "bar" ] - // }; - value = parseOptionValue(parent, name + "." + token); - } else if (peek() === "[") { - value = []; - var lastValue; - if (skip("[", true)) { - do { - lastValue = readValue(true); - value.push(lastValue); - } while (skip(",", true)); - skip("]"); - if (typeof lastValue !== "undefined") { - setOption(parent, name + "." + token, lastValue); - } - } - } else { - value = readValue(true); - setOption(parent, name + "." + token, value); - } - - var prevValue = objectResult[propName]; - - if (prevValue) - value = [].concat(prevValue).concat(value); - - objectResult[propName] = value; - - // Semicolons and commas can be optional - skip(",", true); - skip(";", true); + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _createOAuthClient(params) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; } - - return objectResult; + throw error; } - - var simpleValue = readValue(true); - setOption(parent, name, simpleValue); - return simpleValue; - // Does not enforce a delimiter to be universal } - - function setOption(parent, name, value) { - if (ptr === parent && /^features\./.test(name)) { - topLevelOptions[name] = value; - return; + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _getOAuthClient(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); } - if (parent.setOption) - parent.setOption(name, value); - } - - function setParsedOption(parent, name, value, propName) { - if (parent.setParsedOption) - parent.setParsedOption(name, value, propName); - } - - function parseInlineOptions(parent) { - if (skip("[", true)) { - do { - parseOption(parent, "option"); - } while (skip(",", true)); - skip("]"); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; } - return parent; } - - function parseService(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "service name"); - - var service = new Service(token); - ifBlock(service, function parseService_block(token) { - if (parseCommon(service, token)) { - return; + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _updateOAuthClient(clientId, params) { + try { + return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; } - - /* istanbul ignore else */ - if (token === "rpc") - parseMethod(service, token); - else - throw illegal(token); - }); - parent.add(service); - if (parent === ptr) { - topLevelObjects.push(service); + throw error; } } - - function parseMethod(parent, token) { - // Get the comment of the preceding line now (if one exists) in case the - // method is defined across multiple lines. - var commentText = cmnt(); - - var type = token; - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var name = token, - requestType, requestStream, - responseType, responseStream; - - skip("("); - if (skip("stream", true)) - requestStream = true; - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token); - - requestType = token; - skip(")"); skip("returns"); skip("("); - if (skip("stream", true)) - responseStream = true; - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token); - - responseType = token; - skip(")"); - - var method = new Method(name, type, requestType, responseType, requestStream, responseStream); - method.comment = commentText; - ifBlock(method, function parseMethod_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(method, token); - skip(";"); - } else - throw illegal(token); - - }); - parent.add(method); - } - - function parseExtension(parent, token) { - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token, "reference"); - - var reference = token; - ifBlock(null, function parseExtension_block(token) { - switch (token) { - - case "required": - case "repeated": - parseField(parent, token, reference); - break; - - case "optional": - /* istanbul ignore if */ - if (edition === "proto3") { - parseField(parent, "proto3_optional", reference); - } else { - parseField(parent, "optional", reference); - } - break; - - default: - /* istanbul ignore if */ - if (edition === "proto2" || !typeRefRe.test(token)) - throw illegal(token); - push(token); - parseField(parent, "optional", reference); - break; + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _deleteOAuthClient(clientId) { + try { + await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; } - }); + throw error; + } } - - var token; - while ((token = next()) !== null) { - switch (token) { - - case "package": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parsePackage(); - break; - - case "import": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parseImport(); - break; - - case "syntax": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parseSyntax(); - break; - - case "edition": - /* istanbul ignore if */ - if (!head) - throw illegal(token); - parseEdition(); - break; - - case "option": - parseOption(ptr, token); - skip(";", true); - break; - - default: - - /* istanbul ignore else */ - if (parseCommon(ptr, token)) { - head = false; - continue; - } - - /* istanbul ignore next */ - throw illegal(token); + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _regenerateOAuthClientSecret(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; } } - - resolveFileFeatures(); - - parse.filename = null; - return { - "package" : pkg, - "imports" : imports, - weakImports : weakImports, - root : root - }; } - -/** - * Parses the given .proto source and returns an object with the parsed contents. - * @name parse - * @function - * @param {string} source Source contents - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {IParserResult} Parser result - * @property {string} filename=null Currently processing file name for error reporting, if known - * @property {IParseOptions} defaults Default {@link IParseOptions} - * @variation 2 - */ - +exports["default"] = GoTrueAdminApi; +//# sourceMappingURL=GoTrueAdminApi.js.map /***/ }), -/***/ 41011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 313: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -module.exports = Reader; - -var util = __nccwpck_require__(71241); - -var BufferReader; // cyclic - -var LongBits = util.LongBits, - utf8 = util.utf8; - -/* istanbul ignore next */ -function indexOutOfRange(reader, writeLength) { - return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(6575)); +const constants_1 = __nccwpck_require__(518); +const errors_1 = __nccwpck_require__(9938); +const fetch_1 = __nccwpck_require__(7072); +const helpers_1 = __nccwpck_require__(4044); +const local_storage_1 = __nccwpck_require__(5804); +const locks_1 = __nccwpck_require__(163); +const polyfills_1 = __nccwpck_require__(1897); +const version_1 = __nccwpck_require__(6677); +const base64url_1 = __nccwpck_require__(3649); +const ethereum_1 = __nccwpck_require__(9031); +const webauthn_1 = __nccwpck_require__(9451); +(0, polyfills_1.polyfillGlobalThis)(); // Make "globalThis" available +const DEFAULT_OPTIONS = { + url: constants_1.GOTRUE_URL, + storageKey: constants_1.STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: constants_1.DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, + hasCustomAuthorizationHeader: false, + throwOnError: false, +}; +async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); } - /** - * Constructs a new reader instance using the specified buffer. - * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. - * @constructor - * @param {Uint8Array} buffer Buffer to read from + * Caches JWKS values for all clients created in the same environment. This is + * especially useful for shared-memory execution environments such as Vercel's + * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how + * many clients are created, if they share the same storage key they will use + * the same JWKS cache, significantly speeding up getClaims() with asymmetric + * JWTs. */ -function Reader(buffer) { - +const GLOBAL_JWKS = {}; +class GoTrueClient { /** - * Read buffer. - * @type {Uint8Array} + * The JWKS used for verifying asymmetric JWTs */ - this.buf = buffer; - + get jwks() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; + } + set jwks(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); + } + get jwks_cached_at() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; + } + set jwks_cached_at(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); + } /** - * Read buffer position. - * @type {number} + * Create a new client for use in the browser. */ - this.pos = 0; - + constructor(options) { + var _a, _b, _c; + /** + * @experimental + */ + this.userStorage = null; + this.memoryStorage = null; + this.stateChangeEmitters = new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the auth state is known and it's safe to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + this.initializePromise = null; + this.detectSessionInUrl = true; + this.hasCustomAuthorizationHeader = false; + this.suppressGetSessionWarning = false; + this.lockAcquired = false; + this.pendingInLock = []; + /** + * Used to broadcast state change events to other tabs listening. + */ + this.broadcastChannel = null; + this.logger = console.log; + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.storageKey = settings.storageKey; + this.instanceID = (_a = GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 0; + GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1; + this.logDebugMessages = !!settings.debug; + if (typeof settings.debug === 'function') { + this.logger = settings.debug; + } + if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { + const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`; + console.warn(message); + if (this.logDebugMessages) { + console.trace(message); + } + } + this.persistSession = settings.persistSession; + this.autoRefreshToken = settings.autoRefreshToken; + this.admin = new GoTrueAdminApi_1.default({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; + this.throwOnError = settings.throwOnError; + if (settings.lock) { + this.lock = settings.lock; + } + else if ((0, helpers_1.isBrowser)() && ((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.locks)) { + this.lock = locks_1.navigatorLock; + } + else { + this.lock = lockNoOp; + } + if (!this.jwks) { + this.jwks = { keys: [] }; + this.jwks_cached_at = Number.MIN_SAFE_INTEGER; + } + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + webauthn: new webauthn_1.WebAuthnApi(this), + }; + this.oauth = { + getAuthorizationDetails: this._getAuthorizationDetails.bind(this), + approveAuthorization: this._approveAuthorization.bind(this), + denyAuthorization: this._denyAuthorization.bind(this), + }; + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage; + } + else { + if ((0, helpers_1.supportsLocalStorage)()) { + this.storage = globalThis.localStorage; + } + else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + } + if (settings.userStorage) { + this.userStorage = settings.userStorage; + } + } + else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } + catch (e) { + console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); + } + (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages + }); + } + this.initialize(); + } /** - * Read buffer length. - * @type {number} + * Returns whether error throwing mode is enabled for this client. */ - this.len = buffer.length; -} - -var create_array = typeof Uint8Array !== "undefined" - ? function create_typed_array(buffer) { - if (buffer instanceof Uint8Array || Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); + isThrowOnErrorEnabled() { + return this.throwOnError; } - /* istanbul ignore next */ - : function create_array(buffer) { - if (Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - }; - -var create = function create() { - return util.Buffer - ? function create_buffer_setup(buffer) { - return (Reader.create = function create_buffer(buffer) { - return util.Buffer.isBuffer(buffer) - ? new BufferReader(buffer) - /* istanbul ignore next */ - : create_array(buffer); - })(buffer); - } - /* istanbul ignore next */ - : create_array; -}; - -/** - * Creates a new reader using the specified buffer. - * @function - * @param {Uint8Array|Buffer} buffer Buffer to read from - * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} - * @throws {Error} If `buffer` is not a valid buffer - */ -Reader.create = create(); - -Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; - -/** - * Reads a varint as an unsigned 32 bit value. - * @function - * @returns {number} Value read - */ -Reader.prototype.uint32 = (function read_uint32_setup() { - var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) - return function read_uint32() { - value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; - - /* istanbul ignore if */ - if ((this.pos += 5) > this.len) { - this.pos = this.len; - throw indexOutOfRange(this, 10); - } - return value; - }; -})(); - -/** - * Reads a varint as a signed 32 bit value. - * @returns {number} Value read - */ -Reader.prototype.int32 = function read_int32() { - return this.uint32() | 0; -}; - -/** - * Reads a zig-zag encoded varint as a signed 32 bit value. - * @returns {number} Value read - */ -Reader.prototype.sint32 = function read_sint32() { - var value = this.uint32(); - return value >>> 1 ^ -(value & 1) | 0; -}; - -/* eslint-disable no-invalid-this */ - -function readLongVarint() { - // tends to deopt with local vars for octet etc. - var bits = new LongBits(0, 0); - var i = 0; - if (this.len - this.pos > 4) { // fast route (lo) - for (; i < 4; ++i) { - // 1st..4th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 5th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; - bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - i = 0; - } else { - for (; i < 3; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 1st..3th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 4th - bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; - return bits; - } - if (this.len - this.pos > 4) { // fast route (hi) - for (; i < 5; ++i) { - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + _returnResult(result) { + if (this.throwOnError && result && result.error) { + throw result.error; } - } else { - for (; i < 5; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; + return result; + } + _logPrefix() { + return ('GoTrueClient@' + + `${this.storageKey}:${this.instanceID} (${version_1.version}) ${new Date().toISOString()}`); + } + _debug(...args) { + if (this.logDebugMessages) { + this.logger(this._logPrefix(), ...args); } + return this; } - /* istanbul ignore next */ - throw Error("invalid varint encoding"); -} - -/* eslint-enable no-invalid-this */ - -/** - * Reads a varint as a signed 64 bit value. - * @name Reader#int64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a varint as an unsigned 64 bit value. - * @name Reader#uint64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a zig-zag encoded varint as a signed 64 bit value. - * @name Reader#sint64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a varint as a boolean. - * @returns {boolean} Value read - */ -Reader.prototype.bool = function read_bool() { - return this.uint32() !== 0; -}; - -function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` - return (buf[end - 4] - | buf[end - 3] << 8 - | buf[end - 2] << 16 - | buf[end - 1] << 24) >>> 0; -} - -/** - * Reads fixed 32 bits as an unsigned 32 bit integer. - * @returns {number} Value read - */ -Reader.prototype.fixed32 = function read_fixed32() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4); -}; - -/** - * Reads fixed 32 bits as a signed 32 bit integer. - * @returns {number} Value read - */ -Reader.prototype.sfixed32 = function read_sfixed32() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4) | 0; -}; - -/* eslint-disable no-invalid-this */ - -function readFixed64(/* this: Reader */) { - - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 8); - - return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); -} - -/* eslint-enable no-invalid-this */ - -/** - * Reads fixed 64 bits. - * @name Reader#fixed64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads zig-zag encoded fixed 64 bits. - * @name Reader#sfixed64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a float (32 bit) as a number. - * @function - * @returns {number} Value read - */ -Reader.prototype.float = function read_float() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readFloatLE(this.buf, this.pos); - this.pos += 4; - return value; -}; - -/** - * Reads a double (64 bit float) as a number. - * @function - * @returns {number} Value read - */ -Reader.prototype.double = function read_double() { - - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readDoubleLE(this.buf, this.pos); - this.pos += 8; - return value; -}; - -/** - * Reads a sequence of bytes preceeded by its length as a varint. - * @returns {Uint8Array} Value read - */ -Reader.prototype.bytes = function read_bytes() { - var length = this.uint32(), - start = this.pos, - end = this.pos + length; - - /* istanbul ignore if */ - if (end > this.len) - throw indexOutOfRange(this, length); - - this.pos += length; - if (Array.isArray(this.buf)) // plain array - return this.buf.slice(start, end); - - if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 - var nativeBuffer = util.Buffer; - return nativeBuffer - ? nativeBuffer.alloc(0) - : new this.buf.constructor(0); - } - return this._slice.call(this.buf, start, end); -}; - -/** - * Reads a string preceeded by its byte length as a varint. - * @returns {string} Value read - */ -Reader.prototype.string = function read_string() { - var bytes = this.bytes(); - return utf8.read(bytes, 0, bytes.length); -}; - -/** - * Skips the specified number of bytes if specified, otherwise skips a varint. - * @param {number} [length] Length if known, otherwise a varint is assumed - * @returns {Reader} `this` - */ -Reader.prototype.skip = function skip(length) { - if (typeof length === "number") { - /* istanbul ignore if */ - if (this.pos + length > this.len) - throw indexOutOfRange(this, length); - this.pos += length; - } else { - do { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - } while (this.buf[this.pos++] & 128); + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize() { + if (this.initializePromise) { + return await this.initializePromise; + } + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize(); + }); + })(); + return await this.initializePromise; } - return this; -}; - -/** - * Skips the next element of the specified wire type. - * @param {number} wireType Wire type received - * @returns {Reader} `this` - */ -Reader.prototype.skipType = function(wireType) { - switch (wireType) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - while ((wireType = this.uint32() & 7) !== 4) { - this.skipType(wireType); + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + var _a; + try { + let params = {}; + let callbackUrlType = 'none'; + if ((0, helpers_1.isBrowser)()) { + params = (0, helpers_1.parseParametersFromURL)(window.location.href); + if (this._isImplicitGrantCallback(params)) { + callbackUrlType = 'implicit'; + } + else if (await this._isPKCECallback(params)) { + callbackUrlType = 'pkce'; + } + } + /** + * Attempt to get the session from the URL only if these conditions are fulfilled + * + * Note: If the URL isn't one of the callback url types (implicit or pkce), + * then there could be an existing session so we don't want to prematurely remove it + */ + if ((0, helpers_1.isBrowser)() && this.detectSessionInUrl && callbackUrlType !== 'none') { + const { data, error } = await this._getSessionFromURL(params, callbackUrlType); + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error); + if ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) { + const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; + if (errorCode === 'identity_already_exists' || + errorCode === 'identity_not_found' || + errorCode === 'single_identity_not_deletable') { + return { error }; + } + } + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); + } + else { + await this._notifyAllSubscribers('SIGNED_IN', session); + } + }, 0); + return { error: null }; } - break; - case 5: - this.skip(4); - break; - - /* istanbul ignore next */ - default: - throw Error("invalid wire type " + wireType + " at offset " + this.pos); - } - return this; -}; - -Reader._configure = function(BufferReader_) { - BufferReader = BufferReader_; - Reader.create = create(); - BufferReader._configure(); - - var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; - util.merge(Reader.prototype, { - - int64: function read_int64() { - return readLongVarint.call(this)[fn](false); - }, - - uint64: function read_uint64() { - return readLongVarint.call(this)[fn](true); - }, - - sint64: function read_sint64() { - return readLongVarint.call(this).zzDecode()[fn](false); - }, - - fixed64: function read_fixed64() { - return readFixed64.call(this)[fn](true); - }, - - sfixed64: function read_sfixed64() { - return readFixed64.call(this)[fn](false); + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh(); + return { error: null }; } - - }); -}; - - -/***/ }), - -/***/ 80339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = BufferReader; - -// extends Reader -var Reader = __nccwpck_require__(41011); -(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; - -var util = __nccwpck_require__(71241); - -/** - * Constructs a new buffer reader instance. - * @classdesc Wire format reader using node buffers. - * @extends Reader - * @constructor - * @param {Buffer} buffer Buffer to read from - */ -function BufferReader(buffer) { - Reader.call(this, buffer); - + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ error }); + } + return this._returnResult({ + error: new errors_1.AuthUnknownError('Unexpected error during initialization', error), + }); + } + finally { + await this._handleVisibilityChange(); + this._debug('#_initialize()', 'end'); + } + } /** - * Read buffer. - * @name BufferReader#buf - * @type {Buffer} + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true */ -} - -BufferReader._configure = function () { - /* istanbul ignore else */ - if (util.Buffer) - BufferReader.prototype._slice = util.Buffer.prototype.slice; -}; - - -/** - * @override - */ -BufferReader.prototype.string = function read_string_buffer() { - var len = this.uint32(); // modifies pos - return this.buf.utf8Slice - ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) - : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); -}; - -/** - * Reads a sequence of bytes preceeded by its length as a varint. - * @name BufferReader#bytes - * @function - * @returns {Buffer} Value read - */ - -BufferReader._configure(); - - -/***/ }), - -/***/ 32614: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Root; - -// extends Namespace -var Namespace = __nccwpck_require__(76189); -((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; - -var Field = __nccwpck_require__(48213), - Enum = __nccwpck_require__(17732), - OneOf = __nccwpck_require__(44408), - util = __nccwpck_require__(47174); - -var Type, // cyclic - parse, // might be excluded - common; // " - -/** - * Constructs a new root namespace instance. - * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. - * @extends NamespaceBase - * @constructor - * @param {Object.} [options] Top level options - */ -function Root(options) { - Namespace.call(this, "", options); - + async signInAnonymously(credentials) { + var _a, _b, _c; + try { + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, + gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } /** - * Deferred extension fields. - * @type {Field[]} + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF */ - this.deferred = []; - + async signUp(credentials) { + var _a, _b, _c; + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: fetch_1._sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } /** - * Resolved file names of loaded files. - * @type {string[]} + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. */ - this.files = []; - + async signInWithPassword(credentials) { + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponsePassword, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponsePassword, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ + data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), + error, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } /** - * Edition, defaults to proto2 if unspecified. - * @type {string} - * @private + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. */ - this._edition = "proto2"; - + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, + }); + } /** - * Global lookup cache of fully qualified names. - * @type {Object.} - * @private + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. */ - this._fullyQualifiedObjects = {}; -} - -/** - * Loads a namespace descriptor into a root namespace. - * @param {INamespace} json Namespace descriptor - * @param {Root} [root] Root namespace, defaults to create a new one if omitted - * @returns {Root} Root namespace - */ -Root.fromJSON = function fromJSON(json, root) { - if (!root) - root = new Root(); - if (json.options) - root.setOptions(json.options); - return root.addJSON(json.nested).resolveAll(); -}; - -/** - * Resolves the path of an imported file, relative to the importing origin. - * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. - * @function - * @param {string} origin The file name of the importing file - * @param {string} target The file name being imported - * @returns {string|null} Resolved path to `target` or `null` to skip the file - */ -Root.prototype.resolvePath = util.path.resolve; - -/** - * Fetch content from file path or url - * This method exists so you can override it with your own logic. - * @function - * @param {string} path File path or url - * @param {FetchCallback} callback Callback function - * @returns {undefined} - */ -Root.prototype.fetch = util.fetch; - -// A symbol-like function to safely signal synchronous loading -/* istanbul ignore next */ -function SYNC() {} // eslint-disable-line no-empty-function - -/** - * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. - * @param {string|string[]} filename Names of one or multiple files to load - * @param {IParseOptions} options Parse options - * @param {LoadCallback} callback Callback function - * @returns {undefined} - */ -Root.prototype.load = function load(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = undefined; + async exchangeCodeForSession(authCode) { + await this.initializePromise; + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode); + }); } - var self = this; - if (!callback) { - return util.asPromise(load, self, filename, options); + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + async signInWithWeb3(credentials) { + const { chain } = credentials; + switch (chain) { + case 'ethereum': + return await this.signInWithEthereum(credentials); + case 'solana': + return await this.signInWithSolana(credentials); + default: + throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); + } } - - var sync = callback === SYNC; // undocumented - - // Finishes loading by calling the callback (exactly once) - function finish(err, root) { - /* istanbul ignore if */ - if (!callback) { - return; + async signInWithEthereum(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + // TODO: flatten type + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; } - if (sync) { - throw err; + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('ethereum' in windowAny && + typeof windowAny.ethereum === 'object' && + 'request' in windowAny.ethereum && + typeof windowAny.ethereum.request === 'function') { + resolvedWallet = windowAny.ethereum; + } + else { + throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + const accounts = await resolvedWallet + .request({ + method: 'eth_requestAccounts', + }) + .then((accs) => accs) + .catch(() => { + throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); + }); + if (!accounts || accounts.length === 0) { + throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); + } + const address = (0, ethereum_1.getAddress)(accounts[0]); + let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; + if (!chainId) { + const chainIdHex = await resolvedWallet.request({ + method: 'eth_chainId', + }); + chainId = (0, ethereum_1.fromHex)(chainIdHex); + } + const siweMessage = { + domain: url.host, + address: address, + statement: statement, + uri: url.href, + version: '1', + chainId: chainId, + nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, + issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : new Date(), + expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, + notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, + requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, + resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources, + }; + message = (0, ethereum_1.createSiweMessage)(siweMessage); + // Sign message + signature = (await resolvedWallet.request({ + method: 'personal_sign', + params: [(0, ethereum_1.toHex)(message), address], + })); + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'ethereum', message, + signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } + : null)), + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); } - if (root) { - root.resolveAll(); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } - var cb = callback; - callback = null; - cb(err, root); } - - // Bundled definition existence checking - function getBundledFileName(filename) { - var idx = filename.lastIndexOf("google/protobuf/"); - if (idx > -1) { - var altname = filename.substring(idx); - if (altname in common) return altname; + async signInWithSolana(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; + } + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('solana' in windowAny && + typeof windowAny.solana === 'object' && + (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || + ('signMessage' in windowAny.solana && + typeof windowAny.solana.signMessage === 'function'))) { + resolvedWallet = windowAny.solana; + } + else { + throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + if ('signIn' in resolvedWallet && resolvedWallet.signIn) { + const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { + // non-overridable properties + version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null))); + let outputToProcess; + if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { + outputToProcess = output[0]; + } + else if (output && + typeof output === 'object' && + 'signedMessage' in output && + 'signature' in output) { + outputToProcess = output; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value'); + } + if ('signedMessage' in outputToProcess && + 'signature' in outputToProcess && + (typeof outputToProcess.signedMessage === 'string' || + outputToProcess.signedMessage instanceof Uint8Array) && + outputToProcess.signature instanceof Uint8Array) { + message = + typeof outputToProcess.signedMessage === 'string' + ? outputToProcess.signedMessage + : new TextDecoder().decode(outputToProcess.signedMessage); + signature = outputToProcess.signature; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'); + } + } + else { + if (!('signMessage' in resolvedWallet) || + typeof resolvedWallet.signMessage !== 'function' || + !('publicKey' in resolvedWallet) || + typeof resolvedWallet !== 'object' || + !resolvedWallet.publicKey || + !('toBase58' in resolvedWallet.publicKey) || + typeof resolvedWallet.publicKey.toBase58 !== 'function') { + throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'); + } + message = [ + `${url.host} wants you to sign in with your Solana account:`, + resolvedWallet.publicKey.toBase58(), + ...(statement ? ['', statement, ''] : ['']), + 'Version: 1', + `URI: ${url.href}`, + `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`, + ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) + ? [`Not Before: ${options.signInWithSolana.notBefore}`] + : []), + ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) + ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] + : []), + ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) + ? [`Chain ID: ${options.signInWithSolana.chainId}`] + : []), + ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), + ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) + ? [`Request ID: ${options.signInWithSolana.requestId}`] + : []), + ...(((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) + ? [ + 'Resources', + ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), + ] + : []), + ].join('\n'); + const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8'); + if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { + throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value'); + } + signature = maybeSignature; + } } - return null; - } - - // Processes a single file - function process(filename, source) { try { - if (util.isString(source) && source.charAt(0) === "{") - source = JSON.parse(source); - if (!util.isString(source)) - self.setOptions(source.options).addJSON(source.nested); - else { - parse.filename = filename; - var parsed = parse(source, self, options), - resolved, - i = 0; - if (parsed.imports) - for (; i < parsed.imports.length; ++i) - if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) - fetch(resolved); - if (parsed.weakImports) - for (i = 0; i < parsed.weakImports.length; ++i) - if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) - fetch(resolved, true); + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'solana', message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } + : null)), + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; } - } catch (err) { - finish(err); + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); } - if (!sync && !queued) { - finish(null, self); // only once anyway + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } } - - // Fetches a single file - function fetch(filename, weak) { - filename = getBundledFileName(filename) || filename; - - // Skip if already loaded / attempted - if (self.files.indexOf(filename) > -1) { - return; - } - self.files.push(filename); - - // Shortcut bundled definitions - if (filename in common) { - if (sync) { - process(filename, common[filename]); - } else { - ++queued; - setTimeout(function() { - --queued; - process(filename, common[filename]); + async _exchangeCodeForSession(authCode) { + const storageItem = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: fetch_1._sessionResponse, + }); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error: invalidTokenError, }); } - return; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }); } - - // Otherwise fetch from disk or network - if (sync) { - var source; - try { - source = util.fs.readFileSync(filename).toString("utf8"); - } catch (err) { - if (!weak) - finish(err); - return; + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error, + }); } - process(filename, source); - } else { - ++queued; - self.fetch(filename, function(err, source) { - --queued; - /* istanbul ignore if */ - if (!callback) { - return; // terminated meanwhile - } - if (err) { - /* istanbul ignore else */ - if (!weak) - finish(err); - else if (!queued) // can't be covered reliably - finish(null, self); - return; - } - process(filename, source); - }); + throw error; } } - var queued = 0; - - // Assembling the root namespace doesn't require working type - // references anymore, so we can load everything in parallel - if (util.isString(filename)) { - filename = [ filename ]; - } - for (var i = 0, resolved; i < filename.length; ++i) - if (resolved = self.resolvePath("", filename[i])) - fetch(resolved); - if (sync) { - self.resolveAll(); - return self; - } - if (!queued) { - finish(null, self); - } - - return self; -}; -// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined - -/** - * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. - * @function Root#load - * @param {string|string[]} filename Names of one or multiple files to load - * @param {LoadCallback} callback Callback function - * @returns {undefined} - * @variation 2 - */ -// function load(filename:string, callback:LoadCallback):undefined - -/** - * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. - * @function Root#load - * @param {string|string[]} filename Names of one or multiple files to load - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {Promise} Promise - * @variation 3 - */ -// function load(filename:string, [options:IParseOptions]):Promise - -/** - * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). - * @function Root#loadSync - * @param {string|string[]} filename Names of one or multiple files to load - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {Root} Root namespace - * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid - */ -Root.prototype.loadSync = function loadSync(filename, options) { - if (!util.isNode) - throw Error("not supported"); - return this.load(filename, options, SYNC); -}; - -/** - * @override - */ -Root.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - if (this.deferred.length) - throw Error("unresolvable extensions: " + this.deferred.map(function(field) { - return "'extend " + field.extend + "' in " + field.parent.fullName; - }).join(", ")); - return Namespace.prototype.resolveAll.call(this); -}; - -// only uppercased (and thus conflict-free) children are exposed, see below -var exposeRe = /^[A-Z]/; - -/** - * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. - * @param {Root} root Root instance - * @param {Field} field Declaring extension field witin the declaring type - * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise - * @inner - * @ignore - */ -function tryHandleExtension(root, field) { - var extendedType = field.parent.lookup(field.extend); - if (extendedType) { - var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); - //do not allow to extend same field twice to prevent the error - if (extendedType.get(sisterField.name)) { - return true; + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data, error }); } - sisterField.declaringField = field; - field.extensionField = sisterField; - extendedType.add(sisterField); - return true; - } - return false; -} - -/** - * Called when any object is added to this root or its sub-namespaces. - * @param {ReflectionObject} object Object added - * @returns {undefined} - * @private - */ -Root.prototype._handleAdd = function _handleAdd(object) { - if (object instanceof Field) { - - if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) - if (!tryHandleExtension(this, object)) - this.deferred.push(object); - - } else if (object instanceof Enum) { - - if (exposeRe.test(object.name)) - object.parent[object.name] = object.values; // expose enum values as property of its parent - - } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { - - if (object instanceof Type) // Try to handle any deferred extensions - for (var i = 0; i < this.deferred.length;) - if (tryHandleExtension(this, this.deferred[i])) - this.deferred.splice(i, 1); - else - ++i; - for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace - this._handleAdd(object._nestedArray[j]); - if (exposeRe.test(object.name)) - object.parent[object.name] = object; // expose namespace as property of its parent - } - - if (object instanceof Type || object instanceof Enum || object instanceof Field) { - // Only store types and enums for quick lookup during resolve. - this._fullyQualifiedObjects[object.fullName] = object; - } - - // The above also adds uppercased (and thus conflict-free) nested types, services and enums as - // properties of namespaces just like static code does. This allows using a .d.ts generated for - // a static module with reflection-based solutions where the condition is met. -}; - -/** - * Called when any object is removed from this root or its sub-namespaces. - * @param {ReflectionObject} object Object removed - * @returns {undefined} - * @private - */ -Root.prototype._handleRemove = function _handleRemove(object) { - if (object instanceof Field) { - - if (/* an extension field */ object.extend !== undefined) { - if (/* already handled */ object.extensionField) { // remove its sister field - object.extensionField.parent.remove(object.extensionField); - object.extensionField = null; - } else { // cancel the extension - var index = this.deferred.indexOf(object); - /* istanbul ignore else */ - if (index > -1) - this.deferred.splice(index, 1); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); } + throw error; } - - } else if (object instanceof Enum) { - - if (exposeRe.test(object.name)) - delete object.parent[object.name]; // unexpose enum values - - } else if (object instanceof Namespace) { - - for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace - this._handleRemove(object._nestedArray[i]); - - if (exposeRe.test(object.name)) - delete object.parent[object.name]; // unexpose namespaces - } - - delete this._fullyQualifiedObjects[object.fullName]; -}; - -// Sets up cyclic dependencies (called in index-light) -Root._configure = function(Type_, parse_, common_) { - Type = Type_; - parse = parse_; - common = common_; -}; - - -/***/ }), - -/***/ 50073: -/***/ ((module) => { - -"use strict"; - -module.exports = {}; - -/** - * Named roots. - * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). - * Can also be used manually to make roots available across modules. - * @name roots - * @type {Object.} - * @example - * // pbjs -r myroot -o compiled.js ... - * - * // in another module: - * require("./compiled.js"); - * - * // in any subsequent module: - * var root = protobuf.roots["myroot"]; - */ - - -/***/ }), - -/***/ 86444: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * Streaming RPC helpers. - * @namespace - */ -var rpc = exports; - -/** - * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. - * @typedef RPCImpl - * @type {function} - * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called - * @param {Uint8Array} requestData Request data - * @param {RPCImplCallback} callback Callback function - * @returns {undefined} - * @example - * function rpcImpl(method, requestData, callback) { - * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code - * throw Error("no such method"); - * asynchronouslyObtainAResponse(requestData, function(err, responseData) { - * callback(err, responseData); - * }); - * } - */ - -/** - * Node-style callback as used by {@link RPCImpl}. - * @typedef RPCImplCallback - * @type {function} - * @param {Error|null} error Error, if any, otherwise `null` - * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error - * @returns {undefined} - */ - -rpc.Service = __nccwpck_require__(12439); - - -/***/ }), - -/***/ 12439: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Service; - -var util = __nccwpck_require__(71241); - -// Extends EventEmitter -(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; - -/** - * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. - * - * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. - * @typedef rpc.ServiceMethodCallback - * @template TRes extends Message - * @type {function} - * @param {Error|null} error Error, if any - * @param {TRes} [response] Response message - * @returns {undefined} - */ - -/** - * A service method part of a {@link rpc.Service} as created by {@link Service.create}. - * @typedef rpc.ServiceMethod - * @template TReq extends Message - * @template TRes extends Message - * @type {function} - * @param {TReq|Properties} request Request message or plain object - * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message - * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` - */ - -/** - * Constructs a new RPC service instance. - * @classdesc An RPC service as returned by {@link Service#create}. - * @exports rpc.Service - * @extends util.EventEmitter - * @constructor - * @param {RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ -function Service(rpcImpl, requestDelimited, responseDelimited) { - - if (typeof rpcImpl !== "function") - throw TypeError("rpcImpl must be a function"); - - util.EventEmitter.call(this); - - /** - * RPC implementation. Becomes `null` once the service is ended. - * @type {RPCImpl|null} - */ - this.rpcImpl = rpcImpl; - - /** - * Whether requests are length-delimited. - * @type {boolean} - */ - this.requestDelimited = Boolean(requestDelimited); - /** - * Whether responses are length-delimited. - * @type {boolean} + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. */ - this.responseDelimited = Boolean(responseDelimited); -} - -/** - * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. - * @param {Method|rpc.ServiceMethod} method Reflected or static method - * @param {Constructor} requestCtor Request constructor - * @param {Constructor} responseCtor Response constructor - * @param {TReq|Properties} request Request message or plain object - * @param {rpc.ServiceMethodCallback} callback Service callback - * @returns {undefined} - * @template TReq extends Message - * @template TRes extends Message - */ -Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { - - if (!request) - throw TypeError("request must be specified"); - - var self = this; - if (!callback) - return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); - - if (!self.rpcImpl) { - setTimeout(function() { callback(Error("already ended")); }, 0); - return undefined; - } - - try { - return self.rpcImpl( - method, - requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), - function rpcCallback(err, response) { - - if (err) { - self.emit("error", err, method); - return callback(err); - } - - if (response === null) { - self.end(/* endedByRPC */ true); - return undefined; - } - - if (!(response instanceof responseCtor)) { - try { - response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); - } catch (err) { - self.emit("error", err, method); - return callback(err); - } + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e; + try { + if ('email' in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); } - - self.emit("data", response, method); - return callback(null, response); + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); } - ); - } catch (err) { - self.emit("error", err, method); - setTimeout(function() { callback(err); }, 0); - return undefined; - } -}; - -/** - * Ends this service and emits the `end` event. - * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. - * @returns {rpc.Service} `this` - */ -Service.prototype.end = function end(endedByRPC) { - if (this.rpcImpl) { - if (!endedByRPC) // signal end to rpcImpl - this.rpcImpl(null, null, null); - this.rpcImpl = null; - this.emit("end").off(); + if ('phone' in credentials) { + const { phone, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); + } + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number.'); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - return this; -}; - - -/***/ }), - -/***/ 6178: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Service; - -// extends Namespace -var Namespace = __nccwpck_require__(76189); -((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; - -var Method = __nccwpck_require__(57771), - util = __nccwpck_require__(47174), - rpc = __nccwpck_require__(86444); - -/** - * Constructs a new service instance. - * @classdesc Reflected service. - * @extends NamespaceBase - * @constructor - * @param {string} name Service name - * @param {Object.} [options] Service options - * @throws {TypeError} If arguments are invalid - */ -function Service(name, options) { - Namespace.call(this, name, options); - /** - * Service methods. - * @type {Object.} - */ - this.methods = {}; // toJSON, marker - - /** - * Cached methods as an array. - * @type {Method[]|null} - * @private + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. */ - this._methodsArray = null; -} - -/** - * Service descriptor. - * @interface IService - * @extends INamespace - * @property {Object.} methods Method descriptors - */ - -/** - * Constructs a service from a service descriptor. - * @param {string} name Service name - * @param {IService} json Service descriptor - * @returns {Service} Created service - * @throws {TypeError} If arguments are invalid - */ -Service.fromJSON = function fromJSON(name, json) { - var service = new Service(name, json.options); - /* istanbul ignore else */ - if (json.methods) - for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) - service.add(Method.fromJSON(names[i], json.methods[names[i]])); - if (json.nested) - service.addJSON(json.nested); - if (json.edition) - service._edition = json.edition; - service.comment = json.comment; - service._defaultEdition = "proto3"; // For backwards-compatibility. - return service; -}; - -/** - * Converts this service to a service descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IService} Service descriptor - */ -Service.prototype.toJSON = function toJSON(toJSONOptions) { - var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "options" , inherited && inherited.options || undefined, - "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, - "nested" , inherited && inherited.nested || undefined, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * Methods of this service as an array for iteration. - * @name Service#methodsArray - * @type {Method[]} - * @readonly - */ -Object.defineProperty(Service.prototype, "methodsArray", { - get: function() { - return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); - } -}); - -function clearCache(service) { - service._methodsArray = null; - return service; -} - -/** - * @override - */ -Service.prototype.get = function get(name) { - return this.methods[name] - || Namespace.prototype.get.call(this, name); -}; - -/** - * @override - */ -Service.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - Namespace.prototype.resolve.call(this); - var methods = this.methodsArray; - for (var i = 0; i < methods.length; ++i) - methods[i].resolve(); - return this; -}; - -/** - * @override - */ -Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - - edition = this._edition || edition; - - Namespace.prototype._resolveFeaturesRecursive.call(this, edition); - this.methodsArray.forEach(method => { - method._resolveFeaturesRecursive(edition); - }); - return this; -}; - -/** - * @override - */ -Service.prototype.add = function add(object) { - - /* istanbul ignore if */ - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - - if (object instanceof Method) { - this.methods[object.name] = object; - object.parent = this; - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); -}; - -/** - * @override - */ -Service.prototype.remove = function remove(object) { - if (object instanceof Method) { - - /* istanbul ignore if */ - if (this.methods[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.methods[object.name]; - object.parent = null; - return clearCache(this); - } - return Namespace.prototype.remove.call(this, object); -}; - -/** - * Creates a runtime service using the specified rpc implementation. - * @param {RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. - */ -Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { - var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); - for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { - var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); - rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ - m: method, - q: method.resolvedRequestType.ctor, - s: method.resolvedResponseType.ctor - }); - } - return rpcService; -}; - - -/***/ }), - -/***/ 61157: -/***/ ((module) => { - -"use strict"; - -module.exports = tokenize; - -var delimRe = /[\s{}=;:[\],'"()<>]/g, - stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, - stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; - -var setCommentRe = /^ *[*/]+ */, - setCommentAltRe = /^\s*\*?\/*/, - setCommentSplitRe = /\n/g, - whitespaceRe = /\s/, - unescapeRe = /\\(.?)/g; - -var unescapeMap = { - "0": "\0", - "r": "\r", - "n": "\n", - "t": "\t" -}; - -/** - * Unescapes a string. - * @param {string} str String to unescape - * @returns {string} Unescaped string - * @property {Object.} map Special characters map - * @memberof tokenize - */ -function unescape(str) { - return str.replace(unescapeRe, function($0, $1) { - switch ($1) { - case "\\": - case "": - return $1; - default: - return unescapeMap[$1] || ""; + async verifyOtp(params) { + var _a, _b; + try { + let redirectTo = undefined; + let captchaToken = undefined; + if ('options' in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data) { + const tokenVerificationError = new Error('An error occurred on token verification.'); + throw tokenVerificationError; + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } - }); -} - -tokenize.unescape = unescape; - -/** - * Gets the next token and advances. - * @typedef TokenizerHandleNext - * @type {function} - * @returns {string|null} Next token or `null` on eof - */ - -/** - * Peeks for the next token. - * @typedef TokenizerHandlePeek - * @type {function} - * @returns {string|null} Next token or `null` on eof - */ - -/** - * Pushes a token back to the stack. - * @typedef TokenizerHandlePush - * @type {function} - * @param {string} token Token - * @returns {undefined} - */ - -/** - * Skips the next token. - * @typedef TokenizerHandleSkip - * @type {function} - * @param {string} expected Expected token - * @param {boolean} [optional=false] If optional - * @returns {boolean} Whether the token matched - * @throws {Error} If the token didn't match and is not optional - */ - -/** - * Gets the comment on the previous line or, alternatively, the line comment on the specified line. - * @typedef TokenizerHandleCmnt - * @type {function} - * @param {number} [line] Line number - * @returns {string|null} Comment text or `null` if none - */ - -/** - * Handle object returned from {@link tokenize}. - * @interface ITokenizerHandle - * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof) - * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof) - * @property {TokenizerHandlePush} push Pushes a token back to the stack - * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws - * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any - * @property {number} line Current line number - */ - -/** - * Tokenizes the given .proto source and returns an object with useful utility functions. - * @param {string} source Source contents - * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode. - * @returns {ITokenizerHandle} Tokenizer handle - */ -function tokenize(source, alternateCommentMode) { - /* eslint-disable callback-return */ - source = source.toString(); - - var offset = 0, - length = source.length, - line = 1, - lastCommentLine = 0, - comments = {}; - - var stack = []; - - var stringDelim = null; - - /* istanbul ignore next */ - /** - * Creates an error for illegal syntax. - * @param {string} subject Subject - * @returns {Error} Error created - * @inner - */ - function illegal(subject) { - return Error("illegal " + subject + " (line " + line + ")"); } - /** - * Reads a string till its end. - * @returns {string} String read - * @inner + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. */ - function readString() { - var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; - re.lastIndex = offset - 1; - var match = re.exec(source); - if (!match) - throw illegal("string"); - offset = re.lastIndex; - push(stringDelim); - stringDelim = null; - return unescape(match[1]); + async signInWithSSO(params) { + var _a, _b, _c; + try { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const result = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + headers: this.headers, + xform: fetch_1._ssoResponse, + }); + return this._returnResult(result); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - /** - * Gets the character at `pos` within the source. - * @param {number} pos Position - * @returns {string} Character - * @inner + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. */ - function charAt(pos) { - return source.charAt(pos); + async reauthenticate() { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._reauthenticate(); + }); } - - /** - * Sets the current comment text. - * @param {number} start Start offset - * @param {number} end End offset - * @param {boolean} isLeading set if a leading comment - * @returns {undefined} - * @inner - */ - function setComment(start, end, isLeading) { - var comment = { - type: source.charAt(start++), - lineEmpty: false, - leading: isLeading, - }; - var lookback; - if (alternateCommentMode) { - lookback = 2; // alternate comment parsing: "//" or "/*" - } else { - lookback = 3; // "///" or "/**" + async _reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new errors_1.AuthSessionMissingError(); + const { error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + }); } - var commentOffset = start - lookback, - c; - do { - if (--commentOffset < 0 || - (c = source.charAt(commentOffset)) === "\n") { - comment.lineEmpty = true; - break; + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); } - } while (c === " " || c === "\t"); - var lines = source - .substring(start, end) - .split(setCommentSplitRe); - for (var i = 0; i < lines.length; ++i) - lines[i] = lines[i] - .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "") - .trim(); - comment.text = lines - .join("\n") - .trim(); - - comments[line] = comment; - lastCommentLine = line; - } - - function isDoubleSlashCommentLine(startOffset) { - var endOffset = findEndOfLine(startOffset); - - // see if remaining line matches comment pattern - var lineText = source.substring(startOffset, endOffset); - var isComment = /^\s*\/\//.test(lineText); - return isComment; - } - - function findEndOfLine(cursor) { - // find end of cursor's line - var endOffset = cursor; - while (endOffset < length && charAt(endOffset) !== "\n") { - endOffset++; + throw error; } - return endOffset; } - /** - * Obtains the next token. - * @returns {string|null} Next token or `null` on eof - * @inner + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. */ - function next() { - if (stack.length > 0) - return stack.shift(); - if (stringDelim) - return readString(); - var repeat, - prev, - curr, - start, - isDoc, - isLeadingComment = offset === 0; - do { - if (offset === length) - return null; - repeat = false; - while (whitespaceRe.test(curr = charAt(offset))) { - if (curr === "\n") { - isLeadingComment = true; - ++line; - } - if (++offset === length) - return null; + async resend(credentials) { + try { + const endpoint = `${this.url}/resend`; + if ('email' in credentials) { + const { email, type, options } = credentials; + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); } - - if (charAt(offset) === "/") { - if (++offset === length) { - throw illegal("comment"); - } - if (charAt(offset) === "/") { // Line - if (!alternateCommentMode) { - // check for triple-slash comment - isDoc = charAt(start = offset + 1) === "/"; - - while (charAt(++offset) !== "\n") { - if (offset === length) { - return null; - } - } - ++offset; - if (isDoc) { - setComment(start, offset - 1, isLeadingComment); - // Trailing comment cannot not be multi-line, - // so leading comment state should be reset to handle potential next comments - isLeadingComment = true; - } - ++line; - repeat = true; - } else { - // check for double-slash comments, consolidating consecutive lines - start = offset; - isDoc = false; - if (isDoubleSlashCommentLine(offset - 1)) { - isDoc = true; - do { - offset = findEndOfLine(offset); - if (offset === length) { - break; - } - offset++; - if (!isLeadingComment) { - // Trailing comment cannot not be multi-line - break; - } - } while (isDoubleSlashCommentLine(offset)); - } else { - offset = Math.min(length, findEndOfLine(offset) + 1); - } - if (isDoc) { - setComment(start, offset, isLeadingComment); - isLeadingComment = true; - } - line++; - repeat = true; - } - } else if ((curr = charAt(offset)) === "*") { /* Block */ - // check for /** (regular comment mode) or /* (alternate comment mode) - start = offset + 1; - isDoc = alternateCommentMode || charAt(start) === "*"; - do { - if (curr === "\n") { - ++line; - } - if (++offset === length) { - throw illegal("comment"); - } - prev = curr; - curr = charAt(offset); - } while (prev !== "*" || curr !== "/"); - ++offset; - if (isDoc) { - setComment(start, offset - 2, isLeadingComment); - isLeadingComment = true; - } - repeat = true; - } else { - return "/"; - } + else if ('phone' in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); } - } while (repeat); - - // offset !== length if we got here - - var end = offset; - delimRe.lastIndex = 0; - var delim = delimRe.test(charAt(end++)); - if (!delim) - while (end < length && !delimRe.test(charAt(end))) - ++end; - var token = source.substring(offset, offset = end); - if (token === "\"" || token === "'") - stringDelim = token; - return token; + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - /** - * Pushes a token back to the stack. - * @param {string} token Token - * @returns {undefined} - * @inner + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. */ - function push(token) { - stack.push(token); + async getSession() { + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result) => { + return result; + }); + }); + return result; } - /** - * Peeks for the next token. - * @returns {string|null} Token or `null` on eof - * @inner + * Acquires a global lock based on the storage key. */ - function peek() { - if (!stack.length) { - var token = next(); - if (token === null) - return null; - push(token); + async _acquireLock(acquireTimeout, fn) { + this._debug('#_acquireLock', 'begin', acquireTimeout); + try { + if (this.lockAcquired) { + const last = this.pendingInLock.length + ? this.pendingInLock[this.pendingInLock.length - 1] + : Promise.resolve(); + const result = (async () => { + await last; + return await fn(); + })(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + return result; + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); + try { + this.lockAcquired = true; + const result = fn(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + await result; + // keep draining the queue until there's nothing to wait on + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock]; + await Promise.all(waitOn); + this.pendingInLock.splice(0, waitOn.length); + } + return await result; + } + finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); + this.lockAcquired = false; + } + }); + } + finally { + this._debug('#_acquireLock', 'end'); } - return stack[0]; } - /** - * Skips a token. - * @param {string} expected Expected token - * @param {boolean} [optional=false] Whether the token is optional - * @returns {boolean} `true` when skipped, `false` if not - * @throws {Error} When a required token is not present - * @inner + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. */ - function skip(expected, optional) { - var actual = peek(), - equals = actual === expected; - if (equals) { - next(); - return true; + async _useSession(fn) { + this._debug('#_useSession', 'begin'); + try { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + } + finally { + this._debug('#_useSession', 'end'); } - if (!optional) - throw illegal("token '" + actual + "', '" + expected + "' expected"); - return false; } - /** - * Gets a comment. - * @param {number} [trailingLine] Line number if looking for a trailing comment - * @returns {string|null} Comment text - * @inner + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. */ - function cmnt(trailingLine) { - var ret = null; - var comment; - if (trailingLine === undefined) { - comment = comments[line - 1]; - delete comments[line - 1]; - if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { - ret = comment.leading ? comment.text : null; + async __loadSession() { + this._debug('#__loadSession()', 'begin'); + if (!this.lockAcquired) { + this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); + } + try { + let currentSession = null; + const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + this._debug('#getSession()', 'session from storage', maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } + else { + this._debug('#getSession()', 'session from storage is not valid'); + await this._removeSession(); + } } - } else { - /* istanbul ignore else */ - if (lastCommentLine < trailingLine) { - peek(); + if (!currentSession) { + return { data: { session: null }, error: null }; + } + // A session is considered expired before the access token _actually_ + // expires. When the autoRefreshToken option is off (or when the tab is + // in the background), very eager users of getSession() -- like + // realtime-js -- might send a valid JWT which will expire by the time it + // reaches the server. + const hasExpired = currentSession.expires_at + ? currentSession.expires_at * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS + : false; + this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); + if (!hasExpired) { + if (this.userStorage) { + const maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); + if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { + currentSession.user = maybeUser.user; + } + else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + // Wrap the user object with a warning proxy on the server + // This warns when properties of the user are accessed, not when session.user itself is accessed + if (this.storage.isServer && + currentSession.user && + !currentSession.user.__isUserNotAvailableProxy) { + const suppressWarningRef = { value: this.suppressGetSessionWarning }; + currentSession.user = (0, helpers_1.insecureUserWarningProxy)(currentSession.user, suppressWarningRef); + // Update the client-level suppression flag when the proxy suppresses the warning + if (suppressWarningRef.value) { + this.suppressGetSessionWarning = true; + } + } + return { data: { session: currentSession }, error: null }; } - comment = comments[trailingLine]; - delete comments[trailingLine]; - if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { - ret = comment.leading ? null : comment.text; + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { session: null }, error }); } + return this._returnResult({ data: { session }, error: null }); + } + finally { + this._debug('#__loadSession()', 'end'); } - return ret; } - - return Object.defineProperty({ - next: next, - peek: peek, - push: push, - skip: skip, - cmnt: cmnt - }, "line", { - get: function() { return line; } - }); - /* eslint-enable callback-return */ -} - - -/***/ }), - -/***/ 38520: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Type; - -// extends Namespace -var Namespace = __nccwpck_require__(76189); -((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; - -var Enum = __nccwpck_require__(17732), - OneOf = __nccwpck_require__(44408), - Field = __nccwpck_require__(48213), - MapField = __nccwpck_require__(67777), - Service = __nccwpck_require__(6178), - Message = __nccwpck_require__(68027), - Reader = __nccwpck_require__(41011), - Writer = __nccwpck_require__(13098), - util = __nccwpck_require__(47174), - encoder = __nccwpck_require__(23072), - decoder = __nccwpck_require__(65871), - verifier = __nccwpck_require__(34334), - converter = __nccwpck_require__(13617), - wrappers = __nccwpck_require__(63216); - -/** - * Constructs a new reflected message type instance. - * @classdesc Reflected message type. - * @extends NamespaceBase - * @constructor - * @param {string} name Message name - * @param {Object.} [options] Declared options - */ -function Type(name, options) { - Namespace.call(this, name, options); - - /** - * Message fields. - * @type {Object.} - */ - this.fields = {}; // toJSON, marker - - /** - * Oneofs declared within this namespace, if any. - * @type {Object.} - */ - this.oneofs = undefined; // toJSON - - /** - * Extension ranges, if any. - * @type {number[][]} - */ - this.extensions = undefined; // toJSON - - /** - * Reserved ranges, if any. - * @type {Array.} - */ - this.reserved = undefined; // toJSON - - /*? - * Whether this type is a legacy group. - * @type {boolean|undefined} - */ - this.group = undefined; // toJSON - /** - * Cached fields by id. - * @type {Object.|null} - * @private - */ - this._fieldsById = null; - - /** - * Cached fields as an array. - * @type {Field[]|null} - * @private - */ - this._fieldsArray = null; - - /** - * Cached oneofs as an array. - * @type {OneOf[]|null} - * @private - */ - this._oneofsArray = null; - - /** - * Cached constructor. - * @type {Constructor<{}>} - * @private - */ - this._ctor = null; -} - -Object.defineProperties(Type.prototype, { - - /** - * Message fields by id. - * @name Type#fieldsById - * @type {Object.} - * @readonly + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. */ - fieldsById: { - get: function() { - - /* istanbul ignore if */ - if (this._fieldsById) - return this._fieldsById; - - this._fieldsById = {}; - for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { - var field = this.fields[names[i]], - id = field.id; - - /* istanbul ignore if */ - if (this._fieldsById[id]) - throw Error("duplicate id " + id + " in " + this); - - this._fieldsById[id] = field; + async getUser(jwt) { + if (jwt) { + return await this._getUser(jwt); + } + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return await this._getUser(); + }); + return result; + } + async _getUser(jwt) { + try { + if (jwt) { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: fetch_1._userResponse, + }); } - return this._fieldsById; + return await this._useSession(async (result) => { + var _a, _b, _c; + const { data, error } = result; + if (error) { + throw error; + } + // returns an error if there is no access_token or custom authorization header + if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new errors_1.AuthSessionMissingError() }; + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, + xform: fetch_1._userResponse, + }); + }); } - }, - - /** - * Fields of this message as an array for iteration. - * @name Type#fieldsArray - * @type {Field[]} - * @readonly - */ - fieldsArray: { - get: function() { - return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + if ((0, errors_1.isAuthSessionMissingError)(error)) { + // JWT contains a `session_id` which does not correspond to an active + // session in the database, indicating the user is signed out. + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ data: { user: null }, error }); + } + throw error; } - }, - + } /** - * Oneofs of this message as an array for iteration. - * @name Type#oneofsArray - * @type {OneOf[]} - * @readonly + * Updates user data for a logged in user. */ - oneofsArray: { - get: function() { - return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + async updateUser(attributes, options = {}) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options); + }); + } + async _updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new errors_1.AuthSessionMissingError(); + } + const session = sessionData.session; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce' && attributes.email != null) { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { data, error: userError } = await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + jwt: session.access_token, + xform: fetch_1._userResponse, + }); + if (userError) { + throw userError; + } + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers('USER_UPDATED', session); + return this._returnResult({ data: { user: session.user }, error: null }); + }); } - }, - - /** - * The registered constructor, if any registered, otherwise a generic constructor. - * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. - * @name Type#ctor - * @type {Constructor<{}>} - */ - ctor: { - get: function() { - return this._ctor || (this.ctor = Type.generateConstructor(this)()); - }, - set: function(ctor) { - - // Ensure proper prototype - var prototype = ctor.prototype; - if (!(prototype instanceof Message)) { - (ctor.prototype = new Message()).constructor = ctor; - util.merge(ctor.prototype, prototype); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null }, error }); } - - // Classes and messages reference their reflected type - ctor.$type = ctor.prototype.$type = this; - - // Mix in static methods - util.merge(ctor, Message, true); - - this._ctor = ctor; - - // Messages have non-enumerable default values on their prototype - var i = 0; - for (; i < /* initializes */ this.fieldsArray.length; ++i) - this._fieldsArray[i].resolve(); // ensures a proper value - - // Messages have non-enumerable getters and setters for each virtual oneof field - var ctorProperties = {}; - for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) - ctorProperties[this._oneofsArray[i].resolve().name] = { - get: util.oneOfGetter(this._oneofsArray[i].oneof), - set: util.oneOfSetter(this._oneofsArray[i].oneof) - }; - if (i) - Object.defineProperties(ctor.prototype, ctorProperties); - } - } -}); - -/** - * Generates a constructor function for the specified type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -Type.generateConstructor = function generateConstructor(mtype) { - /* eslint-disable no-unexpected-multiline */ - var gen = util.codegen(["p"], mtype.name); - // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype - for (var i = 0, field; i < mtype.fieldsArray.length; ++i) - if ((field = mtype._fieldsArray[i]).map) gen - ("this%s={}", util.safeProp(field.name)); - else if (field.repeated) gen - ("this%s=[]", util.safeProp(field.name)); - return gen - ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors - * @property {Object.} fields Field descriptors - * @property {number[][]} [extensions] Extension ranges - * @property {Array.} [reserved] Reserved ranges - * @property {boolean} [group=false] Whether a legacy group or not - */ - -/** - * Creates a message type from a message type descriptor. - * @param {string} name Message name - * @param {IType} json Message type descriptor - * @returns {Type} Created message type - */ -Type.fromJSON = function fromJSON(name, json) { - var type = new Type(name, json.options); - type.extensions = json.extensions; - type.reserved = json.reserved; - var names = Object.keys(json.fields), - i = 0; - for (; i < names.length; ++i) - type.add( - ( typeof json.fields[names[i]].keyType !== "undefined" - ? MapField.fromJSON - : Field.fromJSON )(names[i], json.fields[names[i]]) - ); - if (json.oneofs) - for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) - type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); - if (json.nested) - for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { - var nested = json.nested[names[i]]; - type.add( // most to least likely - ( nested.id !== undefined - ? Field.fromJSON - : nested.fields !== undefined - ? Type.fromJSON - : nested.values !== undefined - ? Enum.fromJSON - : nested.methods !== undefined - ? Service.fromJSON - : Namespace.fromJSON )(names[i], nested) - ); + throw error; } - if (json.extensions && json.extensions.length) - type.extensions = json.extensions; - if (json.reserved && json.reserved.length) - type.reserved = json.reserved; - if (json.group) - type.group = true; - if (json.comment) - type.comment = json.comment; - if (json.edition) - type._edition = json.edition; - type._defaultEdition = "proto3"; // For backwards-compatibility. - return type; -}; - -/** - * Converts this message type to a message type descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IType} Message type descriptor - */ -Type.prototype.toJSON = function toJSON(toJSONOptions) { - var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "options" , inherited && inherited.options || undefined, - "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), - "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, - "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, - "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, - "group" , this.group || undefined, - "nested" , inherited && inherited.nested || undefined, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * @override - */ -Type.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - Namespace.prototype.resolveAll.call(this); - var oneofs = this.oneofsArray; i = 0; - while (i < oneofs.length) - oneofs[i++].resolve(); - var fields = this.fieldsArray, i = 0; - while (i < fields.length) - fields[i++].resolve(); - return this; -}; - -/** - * @override - */ -Type.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - - edition = this._edition || edition; - - Namespace.prototype._resolveFeaturesRecursive.call(this, edition); - this.oneofsArray.forEach(oneof => { - oneof._resolveFeatures(edition); - }); - this.fieldsArray.forEach(field => { - field._resolveFeatures(edition); - }); - return this; -}; - -/** - * @override - */ -Type.prototype.get = function get(name) { - return this.fields[name] - || this.oneofs && this.oneofs[name] - || this.nested && this.nested[name] - || null; -}; - -/** - * Adds a nested object to this type. - * @param {ReflectionObject} object Nested object to add - * @returns {Type} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id - */ -Type.prototype.add = function add(object) { - - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - - if (object instanceof Field && object.extend === undefined) { - // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. - // The root object takes care of adding distinct sister-fields to the respective extended - // type instead. - - // avoids calling the getter if not absolutely necessary because it's called quite frequently - if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) - throw Error("duplicate id " + object.id + " in " + this); - if (this.isReservedId(object.id)) - throw Error("id " + object.id + " is reserved in " + this); - if (this.isReservedName(object.name)) - throw Error("name '" + object.name + "' is reserved in " + this); - - if (object.parent) - object.parent.remove(object); - this.fields[object.name] = object; - object.message = this; - object.onAdd(this); - return clearCache(this); - } - if (object instanceof OneOf) { - if (!this.oneofs) - this.oneofs = {}; - this.oneofs[object.name] = object; - object.onAdd(this); - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); -}; - -/** - * Removes a nested object from this type. - * @param {ReflectionObject} object Nested object to remove - * @returns {Type} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If `object` is not a member of this type - */ -Type.prototype.remove = function remove(object) { - if (object instanceof Field && object.extend === undefined) { - // See Type#add for the reason why extension fields are excluded here. - - /* istanbul ignore if */ - if (!this.fields || this.fields[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.fields[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); } - if (object instanceof OneOf) { - - /* istanbul ignore if */ - if (!this.oneofs || this.oneofs[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.oneofs[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession); + }); } - return Namespace.prototype.remove.call(this, object); -}; - -/** - * Tests if the specified id is reserved. - * @param {number} id Id to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Type.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); -}; - -/** - * Tests if the specified name is reserved. - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Type.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); -}; - -/** - * Creates a new message of this type using the specified properties. - * @param {Object.} [properties] Properties to set - * @returns {Message<{}>} Message instance - */ -Type.prototype.create = function create(properties) { - return new this.ctor(properties); -}; - -/** - * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. - * @returns {Type} `this` - */ -Type.prototype.setup = function setup() { - // Sets up everything at once so that the prototype chain does not have to be re-evaluated - // multiple times (V8, soft-deopt prototype-check). - - var fullName = this.fullName, - types = []; - for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) - types.push(this._fieldsArray[i].resolve().resolvedType); - - // Replace setup methods with type-specific generated functions - this.encode = encoder(this)({ - Writer : Writer, - types : types, - util : util - }); - this.decode = decoder(this)({ - Reader : Reader, - types : types, - util : util - }); - this.verify = verifier(this)({ - types : types, - util : util - }); - this.fromObject = converter.fromObject(this)({ - types : types, - util : util - }); - this.toObject = converter.toObject(this)({ - types : types, - util : util - }); - - // Inject custom wrappers for common types - var wrapper = wrappers[fullName]; - if (wrapper) { - var originalThis = Object.create(this); - // if (wrapper.fromObject) { - originalThis.fromObject = this.fromObject; - this.fromObject = wrapper.fromObject.bind(originalThis); - // } - // if (wrapper.toObject) { - originalThis.toObject = this.toObject; - this.toObject = wrapper.toObject.bind(originalThis); - // } + async _setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new errors_1.AuthSessionMissingError(); + } + const timeNow = Date.now() / 1000; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const { payload } = (0, helpers_1.decodeJWT)(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } + else { + const { data, error } = await this._getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + }; + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } } - - return this; -}; - -/** - * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. - * @param {Message<{}>|Object.} message Message instance or plain object - * @param {Writer} [writer] Writer to encode to - * @returns {Writer} writer - */ -Type.prototype.encode = function encode_setup(message, writer) { - return this.setup().encode(message, writer); // overrides this method -}; - -/** - * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. - * @param {Message<{}>|Object.} message Message instance or plain object - * @param {Writer} [writer] Writer to encode to - * @returns {Writer} writer - */ -Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); -}; - -/** - * Decodes a message of this type. - * @param {Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Length of the message, if known beforehand - * @returns {Message<{}>} Decoded message - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {util.ProtocolError<{}>} If required fields are missing - */ -Type.prototype.decode = function decode_setup(reader, length) { - return this.setup().decode(reader, length); // overrides this method -}; - -/** - * Decodes a message of this type preceeded by its byte length as a varint. - * @param {Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {Message<{}>} Decoded message - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {util.ProtocolError} If required fields are missing - */ -Type.prototype.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof Reader)) - reader = Reader.create(reader); - return this.decode(reader, reader.uint32()); -}; - -/** - * Verifies that field values are valid and that required fields are present. - * @param {Object.} message Plain object to verify - * @returns {null|string} `null` if valid, otherwise the reason why it is not - */ -Type.prototype.verify = function verify_setup(message) { - return this.setup().verify(message); // overrides this method -}; - -/** - * Creates a new message of this type from a plain object. Also converts values to their respective internal types. - * @param {Object.} object Plain object to convert - * @returns {Message<{}>} Message instance - */ -Type.prototype.fromObject = function fromObject(object) { - return this.setup().fromObject(object); -}; - -/** - * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. - * @interface IConversionOptions - * @property {Function} [longs] Long conversion type. - * Valid values are `String` and `Number` (the global types). - * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. - * @property {Function} [enums] Enum value conversion type. - * Only valid value is `String` (the global type). - * Defaults to copy the present value, which is the numeric id. - * @property {Function} [bytes] Bytes value conversion type. - * Valid values are `Array` and (a base64 encoded) `String` (the global types). - * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. - * @property {boolean} [defaults=false] Also sets default values on the resulting object - * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` - * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` - * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any - * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings - */ - -/** - * Creates a plain object from a message of this type. Also converts values to other types if specified. - * @param {Message<{}>} message Message instance - * @param {IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ -Type.prototype.toObject = function toObject(message, options) { - return this.setup().toObject(message, options); -}; - -/** - * Decorator function as returned by {@link Type.d} (TypeScript). - * @typedef TypeDecorator - * @type {function} - * @param {Constructor} target Target constructor - * @returns {undefined} - * @template T extends Message - */ - -/** - * Type decorator (TypeScript). - * @param {string} [typeName] Type name, defaults to the constructor's name - * @returns {TypeDecorator} Decorator function - * @template T extends Message - */ -Type.d = function decorateType(typeName) { - return function typeDecorator(target) { - util.decorateType(target, typeName); - }; -}; - - -/***/ }), - -/***/ 6581: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * Common type constants. - * @namespace - */ -var types = exports; - -var util = __nccwpck_require__(47174); - -var s = [ - "double", // 0 - "float", // 1 - "int32", // 2 - "uint32", // 3 - "sint32", // 4 - "fixed32", // 5 - "sfixed32", // 6 - "int64", // 7 - "uint64", // 8 - "sint64", // 9 - "fixed64", // 10 - "sfixed64", // 11 - "bool", // 12 - "string", // 13 - "bytes" // 14 -]; - -function bake(values, offset) { - var i = 0, o = {}; - offset |= 0; - while (i < values.length) o[s[i + offset]] = values[i++]; - return o; -} - -/** - * Basic type wire types. - * @type {Object.} - * @const - * @property {number} double=1 Fixed64 wire type - * @property {number} float=5 Fixed32 wire type - * @property {number} int32=0 Varint wire type - * @property {number} uint32=0 Varint wire type - * @property {number} sint32=0 Varint wire type - * @property {number} fixed32=5 Fixed32 wire type - * @property {number} sfixed32=5 Fixed32 wire type - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - * @property {number} bool=0 Varint wire type - * @property {number} string=2 Ldelim wire type - * @property {number} bytes=2 Ldelim wire type - */ -types.basic = bake([ - /* double */ 1, - /* float */ 5, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0, - /* string */ 2, - /* bytes */ 2 -]); - -/** - * Basic type defaults. - * @type {Object.} - * @const - * @property {number} double=0 Double default - * @property {number} float=0 Float default - * @property {number} int32=0 Int32 default - * @property {number} uint32=0 Uint32 default - * @property {number} sint32=0 Sint32 default - * @property {number} fixed32=0 Fixed32 default - * @property {number} sfixed32=0 Sfixed32 default - * @property {number} int64=0 Int64 default - * @property {number} uint64=0 Uint64 default - * @property {number} sint64=0 Sint32 default - * @property {number} fixed64=0 Fixed64 default - * @property {number} sfixed64=0 Sfixed64 default - * @property {boolean} bool=false Bool default - * @property {string} string="" String default - * @property {Array.} bytes=Array(0) Bytes default - * @property {null} message=null Message default - */ -types.defaults = bake([ - /* double */ 0, - /* float */ 0, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 0, - /* sfixed32 */ 0, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 0, - /* sfixed64 */ 0, - /* bool */ false, - /* string */ "", - /* bytes */ util.emptyArray, - /* message */ null -]); - -/** - * Basic long type wire types. - * @type {Object.} - * @const - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - */ -types.long = bake([ - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1 -], 7); - -/** - * Allowed types for map keys with their associated wire type. - * @type {Object.} - * @const - * @property {number} int32=0 Varint wire type - * @property {number} uint32=0 Varint wire type - * @property {number} sint32=0 Varint wire type - * @property {number} fixed32=5 Fixed32 wire type - * @property {number} sfixed32=5 Fixed32 wire type - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - * @property {number} bool=0 Varint wire type - * @property {number} string=2 Ldelim wire type - */ -types.mapKey = bake([ - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0, - /* string */ 2 -], 2); - -/** - * Allowed types for packed repeated fields with their associated wire type. - * @type {Object.} - * @const - * @property {number} double=1 Fixed64 wire type - * @property {number} float=5 Fixed32 wire type - * @property {number} int32=0 Varint wire type - * @property {number} uint32=0 Varint wire type - * @property {number} sint32=0 Varint wire type - * @property {number} fixed32=5 Fixed32 wire type - * @property {number} sfixed32=5 Fixed32 wire type - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - * @property {number} bool=0 Varint wire type - */ -types.packed = bake([ - /* double */ 1, - /* float */ 5, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0 -]); - - -/***/ }), - -/***/ 47174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * Various utility functions. - * @namespace - */ -var util = module.exports = __nccwpck_require__(71241); - -var roots = __nccwpck_require__(50073); - -var Type, // cyclic - Enum; - -util.codegen = __nccwpck_require__(58882); -util.fetch = __nccwpck_require__(50663); -util.path = __nccwpck_require__(24761); - -/** - * Node's fs module if available. - * @type {Object.} - */ -util.fs = util.inquire("fs"); - -/** - * Converts an object's values to an array. - * @param {Object.} object Object to convert - * @returns {Array.<*>} Converted array - */ -util.toArray = function toArray(object) { - if (object) { - var keys = Object.keys(object), - array = new Array(keys.length), - index = 0; - while (index < keys.length) - array[index] = object[keys[index++]]; - return array; + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession); + }); } - return []; -}; - -/** - * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. - * @param {Array.<*>} array Array to convert - * @returns {Object.} Converted object - */ -util.toObject = function toObject(array) { - var object = {}, - index = 0; - while (index < array.length) { - var key = array[index++], - val = array[index++]; - if (val !== undefined) - object[key] = val; - } - return object; -}; - -var safePropBackslashRe = /\\/g, - safePropQuoteRe = /"/g; - -/** - * Tests whether the specified name is a reserved word in JS. - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -util.isReserved = function isReserved(name) { - return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); -}; - -/** - * Returns a safe property accessor for the specified property name. - * @param {string} prop Property name - * @returns {string} Safe accessor - */ -util.safeProp = function safeProp(prop) { - if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) - return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; - return "." + prop; -}; - -/** - * Converts the first character of a string to upper case. - * @param {string} str String to convert - * @returns {string} Converted string - */ -util.ucFirst = function ucFirst(str) { - return str.charAt(0).toUpperCase() + str.substring(1); -}; - -var camelCaseRe = /_([a-z])/g; - -/** - * Converts a string to camel case. - * @param {string} str String to convert - * @returns {string} Converted string - */ -util.camelCase = function camelCase(str) { - return str.substring(0, 1) - + str.substring(1) - .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); -}; - -/** - * Compares reflected fields by id. - * @param {Field} a First field - * @param {Field} b Second field - * @returns {number} Comparison value - */ -util.compareFieldsById = function compareFieldsById(a, b) { - return a.id - b.id; -}; - -/** - * Decorator helper for types (TypeScript). - * @param {Constructor} ctor Constructor function - * @param {string} [typeName] Type name, defaults to the constructor's name - * @returns {Type} Reflected type - * @template T extends Message - * @property {Root} root Decorators root - */ -util.decorateType = function decorateType(ctor, typeName) { - - /* istanbul ignore if */ - if (ctor.$type) { - if (typeName && ctor.$type.name !== typeName) { - util.decorateRoot.remove(ctor.$type); - ctor.$type.name = typeName; - util.decorateRoot.add(ctor.$type); + async _refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error } = result; + if (error) { + throw error; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new errors_1.AuthSessionMissingError(); + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!session) { + return this._returnResult({ data: { user: null, session: null }, error: null }); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } - return ctor.$type; } - - /* istanbul ignore next */ - if (!Type) - Type = __nccwpck_require__(38520); - - var type = new Type(typeName || ctor.name); - util.decorateRoot.add(type); - type.ctor = ctor; // sets up .encode, .decode etc. - Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); - Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); - return type; -}; - -var decorateEnumIndex = 0; - -/** - * Decorator helper for enums (TypeScript). - * @param {Object} object Enum object - * @returns {Enum} Reflected enum - */ -util.decorateEnum = function decorateEnum(object) { - - /* istanbul ignore if */ - if (object.$type) - return object.$type; - - /* istanbul ignore next */ - if (!Enum) - Enum = __nccwpck_require__(17732); - - var enm = new Enum("Enum" + decorateEnumIndex++, object); - util.decorateRoot.add(enm); - Object.defineProperty(object, "$type", { value: enm, enumerable: false }); - return enm; -}; - - -/** - * Sets the value of a property by property path. If a value already exists, it is turned to an array - * @param {Object.} dst Destination object - * @param {string} path dot '.' delimited path of the property to set - * @param {Object} value the value to set - * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set - * @returns {Object.} Destination object - */ -util.setProperty = function setProperty(dst, path, value, ifNotSet) { - function setProp(dst, path, value) { - var part = path.shift(); - if (part === "__proto__" || part === "prototype") { - return dst; - } - if (path.length > 0) { - dst[part] = setProp(dst[part] || {}, path, value); - } else { - var prevValue = dst[part]; - if (prevValue && ifNotSet) - return dst; - if (prevValue) - value = [].concat(prevValue).concat(value); - dst[part] = value; + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(params, callbackUrlType) { + try { + if (!(0, helpers_1.isBrowser)()) + throw new errors_1.AuthImplicitGrantRedirectError('No browser detected.'); + // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. + if (params.error || params.error_description || params.error_code) { + // The error class returned implies that the redirect is from an implicit grant flow + // but it could also be from a redirect error from a PKCE flow. + throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + }); + } + // Checks for mismatches between the flowType initialised in the client and the URL parameters + switch (callbackUrlType) { + case 'implicit': + if (this.flowType === 'pkce') { + throw new errors_1.AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); + } + break; + case 'pkce': + if (this.flowType === 'implicit') { + throw new errors_1.AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); + } + break; + default: + // there's no mismatch so we continue + } + // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange + if (callbackUrlType === 'pkce') { + this._debug('#_initialize()', 'begin', 'is PKCE flow', true); + if (!params.code) + throw new errors_1.AuthPKCEGrantCodeExchangeError('No code detected.'); + const { data, error } = await this._exchangeCodeForSession(params.code); + if (error) + throw error; + const url = new URL(window.location.href); + url.searchParams.delete('code'); + window.history.replaceState(window.history.state, '', url.toString()); + return { data: { session: data.session, redirectType: null }, error: null }; + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new errors_1.AuthImplicitGrantRedirectError('No session defined in URL'); + } + const timeNow = Math.round(Date.now() / 1000); + const expiresIn = parseInt(expires_in); + let expiresAt = timeNow + expiresIn; + if (expires_at) { + expiresAt = parseInt(expires_at); + } + const actuallyExpiresIn = expiresAt - timeNow; + if (actuallyExpiresIn * 1000 <= constants_1.AUTO_REFRESH_TICK_DURATION_MS) { + console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); + } + const issuedAt = expiresAt - expiresIn; + if (timeNow - issuedAt >= 120) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); + } + else if (timeNow - issuedAt < 0) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); + } + const { data, error } = await this._getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type: token_type, + user: data.user, + }; + // Remove tokens from URL + window.location.hash = ''; + this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); + return this._returnResult({ data: { session, redirectType: params.type }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, redirectType: null }, error }); + } + throw error; } - return dst; } - - if (typeof dst !== "object") - throw TypeError("dst must be an object"); - if (!path) - throw TypeError("path must be specified"); - - path = path.split("."); - return setProp(dst, path, value); -}; - -/** - * Decorator root (TypeScript). - * @name util.decorateRoot - * @type {Root} - * @readonly - */ -Object.defineProperty(util, "decorateRoot", { - get: function() { - return roots["decorated"] || (roots["decorated"] = new (__nccwpck_require__(32614))()); + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantCallback(params) { + return Boolean(params.access_token || params.error_description); } -}); - - -/***/ }), - -/***/ 8374: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = LongBits; - -var util = __nccwpck_require__(71241); - -/** - * Constructs new long bits. - * @classdesc Helper class for working with the low and high bits of a 64 bit value. - * @memberof util - * @constructor - * @param {number} lo Low 32 bits, unsigned - * @param {number} hi High 32 bits, unsigned - */ -function LongBits(lo, hi) { - - // note that the casts below are theoretically unnecessary as of today, but older statically - // generated converter code might still call the ctor with signed 32bits. kept for compat. - /** - * Low bits. - * @type {number} + * Checks if the current URL and backing storage contain parameters given by a PKCE flow */ - this.lo = lo >>> 0; - + async _isPKCECallback(params) { + const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } /** - * High bits. - * @type {number} + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! */ - this.hi = hi >>> 0; -} - -/** - * Zero bits. - * @memberof util.LongBits - * @type {util.LongBits} - */ -var zero = LongBits.zero = new LongBits(0, 0); - -zero.toNumber = function() { return 0; }; -zero.zzEncode = zero.zzDecode = function() { return this; }; -zero.length = function() { return 1; }; - -/** - * Zero hash. - * @memberof util.LongBits - * @type {string} - */ -var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; - -/** - * Constructs new long bits from the specified number. - * @param {number} value Value - * @returns {util.LongBits} Instance - */ -LongBits.fromNumber = function fromNumber(value) { - if (value === 0) - return zero; - var sign = value < 0; - if (sign) - value = -value; - var lo = value >>> 0, - hi = (value - lo) / 4294967296 >>> 0; - if (sign) { - hi = ~hi >>> 0; - lo = ~lo >>> 0; - if (++lo > 4294967295) { - lo = 0; - if (++hi > 4294967295) - hi = 0; - } - } - return new LongBits(lo, hi); -}; - -/** - * Constructs new long bits from a number, long or string. - * @param {Long|number|string} value Value - * @returns {util.LongBits} Instance - */ -LongBits.from = function from(value) { - if (typeof value === "number") - return LongBits.fromNumber(value); - if (util.isString(value)) { - /* istanbul ignore else */ - if (util.Long) - value = util.Long.fromString(value); - else - return LongBits.fromNumber(parseInt(value, 10)); - } - return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; -}; - -/** - * Converts this long bits to a possibly unsafe JavaScript number. - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {number} Possibly unsafe number - */ -LongBits.prototype.toNumber = function toNumber(unsigned) { - if (!unsigned && this.hi >>> 31) { - var lo = ~this.lo + 1 >>> 0, - hi = ~this.hi >>> 0; - if (!lo) - hi = hi + 1 >>> 0; - return -(lo + hi * 4294967296); - } - return this.lo + this.hi * 4294967296; -}; - -/** - * Converts this long bits to a long. - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {Long} Long - */ -LongBits.prototype.toLong = function toLong(unsigned) { - return util.Long - ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) - /* istanbul ignore next */ - : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; -}; - -var charCodeAt = String.prototype.charCodeAt; - -/** - * Constructs new long bits from the specified 8 characters long hash. - * @param {string} hash Hash - * @returns {util.LongBits} Bits - */ -LongBits.fromHash = function fromHash(hash) { - if (hash === zeroHash) - return zero; - return new LongBits( - ( charCodeAt.call(hash, 0) - | charCodeAt.call(hash, 1) << 8 - | charCodeAt.call(hash, 2) << 16 - | charCodeAt.call(hash, 3) << 24) >>> 0 - , - ( charCodeAt.call(hash, 4) - | charCodeAt.call(hash, 5) << 8 - | charCodeAt.call(hash, 6) << 16 - | charCodeAt.call(hash, 7) << 24) >>> 0 - ); -}; - -/** - * Converts this long bits to a 8 characters long hash. - * @returns {string} Hash - */ -LongBits.prototype.toHash = function toHash() { - return String.fromCharCode( - this.lo & 255, - this.lo >>> 8 & 255, - this.lo >>> 16 & 255, - this.lo >>> 24 , - this.hi & 255, - this.hi >>> 8 & 255, - this.hi >>> 16 & 255, - this.hi >>> 24 - ); -}; - -/** - * Zig-zag encodes this long bits. - * @returns {util.LongBits} `this` - */ -LongBits.prototype.zzEncode = function zzEncode() { - var mask = this.hi >> 31; - this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; - this.lo = ( this.lo << 1 ^ mask) >>> 0; - return this; -}; - -/** - * Zig-zag decodes this long bits. - * @returns {util.LongBits} `this` - */ -LongBits.prototype.zzDecode = function zzDecode() { - var mask = -(this.lo & 1); - this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; - this.hi = ( this.hi >>> 1 ^ mask) >>> 0; - return this; -}; - -/** - * Calculates the length of this longbits when encoded as a varint. - * @returns {number} Length - */ -LongBits.prototype.length = function length() { - var part0 = this.lo, - part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, - part2 = this.hi >>> 24; - return part2 === 0 - ? part1 === 0 - ? part0 < 16384 - ? part0 < 128 ? 1 : 2 - : part0 < 2097152 ? 3 : 4 - : part1 < 16384 - ? part1 < 128 ? 5 : 6 - : part1 < 2097152 ? 7 : 8 - : part2 < 128 ? 9 : 10; -}; - - -/***/ }), - -/***/ 71241: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var util = exports; - -// used to return a Promise where callback is omitted -util.asPromise = __nccwpck_require__(252); - -// converts to / from base64 encoded strings -util.base64 = __nccwpck_require__(26718); - -// base class of rpc.Service -util.EventEmitter = __nccwpck_require__(86850); - -// float handling accross browsers -util.float = __nccwpck_require__(21843); - -// requires modules optionally and hides the call from bundlers -util.inquire = __nccwpck_require__(60094); - -// converts to / from utf8 encoded strings -util.utf8 = __nccwpck_require__(99049); - -// provides a node-like buffer pool in the browser -util.pool = __nccwpck_require__(47743); - -// utility to work with the low and high bits of a 64 bit value -util.LongBits = __nccwpck_require__(8374); - -/** - * Whether running within node or not. - * @memberof util - * @type {boolean} - */ -util.isNode = Boolean(typeof global !== "undefined" - && global - && global.process - && global.process.versions - && global.process.versions.node); - -/** - * Global object reference. - * @memberof util - * @type {Object} - */ -util.global = util.isNode && global - || typeof window !== "undefined" && window - || typeof self !== "undefined" && self - || this; // eslint-disable-line no-invalid-this - -/** - * An immuable empty array. - * @memberof util - * @type {Array.<*>} - * @const - */ -util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes - -/** - * An immutable empty object. - * @type {Object} - * @const - */ -util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes - -/** - * Tests if the specified value is an integer. - * @function - * @param {*} value Value to test - * @returns {boolean} `true` if the value is an integer - */ -util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; -}; - -/** - * Tests if the specified value is a string. - * @param {*} value Value to test - * @returns {boolean} `true` if the value is a string - */ -util.isString = function isString(value) { - return typeof value === "string" || value instanceof String; -}; - -/** - * Tests if the specified value is a non-null object. - * @param {*} value Value to test - * @returns {boolean} `true` if the value is a non-null object - */ -util.isObject = function isObject(value) { - return value && typeof value === "object"; -}; - -/** - * Checks if a property on a message is considered to be present. - * This is an alias of {@link util.isSet}. - * @function - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ -util.isset = - -/** - * Checks if a property on a message is considered to be present. - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ -util.isSet = function isSet(obj, prop) { - var value = obj[prop]; - if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins - return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; - return false; -}; - -/** - * Any compatible Buffer instance. - * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. - * @interface Buffer - * @extends Uint8Array - */ - -/** - * Node's Buffer class if available. - * @type {Constructor} - */ -util.Buffer = (function() { - try { - var Buffer = util.inquire("buffer").Buffer; - // refuse to use non-node buffers if not explicitly assigned (perf reasons): - return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; - } catch (e) { - /* istanbul ignore next */ - return null; + async signOut(options = { scope: 'global' }) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._signOut(options); + }); } -})(); - -// Internal alias of or polyfull for Buffer.from. -util._Buffer_from = null; - -// Internal alias of or polyfill for Buffer.allocUnsafe. -util._Buffer_allocUnsafe = null; - -/** - * Creates a new buffer of whatever type supported by the environment. - * @param {number|number[]} [sizeOrArray=0] Buffer size or number array - * @returns {Uint8Array|Buffer} Buffer - */ -util.newBuffer = function newBuffer(sizeOrArray) { - /* istanbul ignore next */ - return typeof sizeOrArray === "number" - ? util.Buffer - ? util._Buffer_allocUnsafe(sizeOrArray) - : new util.Array(sizeOrArray) - : util.Buffer - ? util._Buffer_from(sizeOrArray) - : typeof Uint8Array === "undefined" - ? sizeOrArray - : new Uint8Array(sizeOrArray); -}; - -/** - * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. - * @type {Constructor} - */ -util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; - -/** - * Any compatible Long instance. - * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. - * @interface Long - * @property {number} low Low bits - * @property {number} high High bits - * @property {boolean} unsigned Whether unsigned or not - */ - -/** - * Long.js's Long class if available. - * @type {Constructor} - */ -util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long - || /* istanbul ignore next */ util.global.Long - || util.inquire("long"); - -/** - * Regular expression used to verify 2 bit (`bool`) map keys. - * @type {RegExp} - * @const - */ -util.key2Re = /^true|false|0|1$/; - -/** - * Regular expression used to verify 32 bit (`int32` etc.) map keys. - * @type {RegExp} - * @const - */ -util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; - -/** - * Regular expression used to verify 64 bit (`int64` etc.) map keys. - * @type {RegExp} - * @const - */ -util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; - -/** - * Converts a number or long to an 8 characters long hash string. - * @param {Long|number} value Value to convert - * @returns {string} Hash - */ -util.longToHash = function longToHash(value) { - return value - ? util.LongBits.from(value).toHash() - : util.LongBits.zeroHash; -}; - -/** - * Converts an 8 characters long hash string to a long or number. - * @param {string} hash Hash - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {Long|number} Original value - */ -util.longFromHash = function longFromHash(hash, unsigned) { - var bits = util.LongBits.fromHash(hash); - if (util.Long) - return util.Long.fromBits(bits.lo, bits.hi, unsigned); - return bits.toNumber(Boolean(unsigned)); -}; - -/** - * Merges the properties of the source object into the destination object. - * @memberof util - * @param {Object.} dst Destination object - * @param {Object.} src Source object - * @param {boolean} [ifNotSet=false] Merges only if the key is not already set - * @returns {Object.} Destination object - */ -function merge(dst, src, ifNotSet) { // used by converters - for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) - if (dst[keys[i]] === undefined || !ifNotSet) - dst[keys[i]] = src[keys[i]]; - return dst; -} - -util.merge = merge; - -/** - * Converts the first character of a string to lower case. - * @param {string} str String to convert - * @returns {string} Converted string - */ -util.lcFirst = function lcFirst(str) { - return str.charAt(0).toLowerCase() + str.substring(1); -}; - -/** - * Creates a custom error constructor. - * @memberof util - * @param {string} name Error name - * @returns {Constructor} Custom error constructor - */ -function newError(name) { - - function CustomError(message, properties) { - - if (!(this instanceof CustomError)) - return new CustomError(message, properties); - - // Error.call(this, message); - // ^ just returns a new error instance because the ctor can be called as a function - - Object.defineProperty(this, "message", { get: function() { return message; } }); - - /* istanbul ignore next */ - if (Error.captureStackTrace) // node - Error.captureStackTrace(this, CustomError); - else - Object.defineProperty(this, "stack", { value: new Error().stack || "" }); - - if (properties) - merge(this, properties); + async _signOut({ scope } = { scope: 'global' }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ error: sessionError }); + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!((0, errors_1.isAuthApiError)(error) && + (error.status === 404 || error.status === 401 || error.status === 403))) { + return this._returnResult({ error }); + } + } + } + if (scope !== 'others') { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ error: null }); + }); + } + onAuthStateChange(callback) { + const id = (0, helpers_1.uuid)(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id); + this.stateChangeEmitters.delete(id); + }, + }; + this._debug('#onAuthStateChange()', 'registered callback with id', id); + this.stateChangeEmitters.set(id, subscription); + (async () => { + await this.initializePromise; + await this._acquireLock(-1, async () => { + this._emitInitialSession(id); + }); + })(); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error, } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); + } + catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); + console.error(err); + } + }); } - - CustomError.prototype = Object.create(Error.prototype, { - constructor: { - value: CustomError, - writable: true, - enumerable: false, - configurable: true, - }, - name: { - get: function get() { return name; }, - set: undefined, - enumerable: false, - // configurable: false would accurately preserve the behavior of - // the original, but I'm guessing that was not intentional. - // For an actual error subclass, this property would - // be configurable. - configurable: true, - }, - toString: { - value: function value() { return this.name + ": " + this.message; }, - writable: true, - enumerable: false, - configurable: true, - }, - }); - - return CustomError; -} - -util.newError = newError; - -/** - * Constructs a new protocol error. - * @classdesc Error subclass indicating a protocol specifc error. - * @memberof util - * @extends Error - * @template T extends Message - * @constructor - * @param {string} message Error message - * @param {Object.} [properties] Additional properties - * @example - * try { - * MyMessage.decode(someBuffer); // throws if required fields are missing - * } catch (e) { - * if (e instanceof ProtocolError && e.instance) - * console.log("decoded so far: " + JSON.stringify(e.instance)); - * } - */ -util.ProtocolError = newError("ProtocolError"); - -/** - * So far decoded message instance. - * @name util.ProtocolError#instance - * @type {Message} - */ - -/** - * A OneOf getter as returned by {@link util.oneOfGetter}. - * @typedef OneOfGetter - * @type {function} - * @returns {string|undefined} Set field name, if any - */ - -/** - * Builds a getter for a oneof's present field name. - * @param {string[]} fieldNames Field names - * @returns {OneOfGetter} Unbound getter - */ -util.oneOfGetter = function getOneOf(fieldNames) { - var fieldMap = {}; - for (var i = 0; i < fieldNames.length; ++i) - fieldMap[fieldNames[i]] = 1; - /** - * @returns {string|undefined} Set field name, if any - * @this Object - * @ignore + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. */ - return function() { // eslint-disable-line consistent-return - for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) - if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) - return keys[i]; - }; -}; - -/** - * A OneOf setter as returned by {@link util.oneOfSetter}. - * @typedef OneOfSetter - * @type {function} - * @param {string|undefined} value Field name - * @returns {undefined} - */ - -/** - * Builds a setter for a oneof's present field name. - * @param {string[]} fieldNames Field names - * @returns {OneOfSetter} Unbound setter - */ -util.oneOfSetter = function setOneOf(fieldNames) { - + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey, true // isPasswordRecovery + ); + } + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } /** - * @param {string} name Field name - * @returns {undefined} - * @this Object - * @ignore + * Gets all the identities linked to a user. */ - return function(name) { - for (var i = 0; i < fieldNames.length; ++i) - if (fieldNames[i] !== name) - delete this[fieldNames[i]]; - }; -}; - -/** - * Default conversion options used for {@link Message#toJSON} implementations. - * - * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: - * - * - Longs become strings - * - Enums become string keys - * - Bytes become base64 encoded strings - * - (Sub-)Messages become plain objects - * - Maps become plain objects with all string keys - * - Repeated fields become arrays - * - NaN and Infinity for float and double fields become strings - * - * @type {IConversionOptions} - * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json - */ -util.toJSONOptions = { - longs: String, - enums: String, - bytes: String, - json: true -}; - -// Sets up buffer utility according to the environment (called in index-minimal) -util._configure = function() { - var Buffer = util.Buffer; - /* istanbul ignore if */ - if (!Buffer) { - util._Buffer_from = util._Buffer_allocUnsafe = null; - return; + async getUserIdentities() { + var _a; + try { + const { data, error } = await this.getUser(); + if (error) + throw error; + return this._returnResult({ data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - // because node 4.x buffers are incompatible & immutable - // see: https://github.com/dcodeIO/protobuf.js/pull/665 - util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || - /* istanbul ignore next */ - function Buffer_from(value, encoding) { - return new Buffer(value, encoding); - }; - util._Buffer_allocUnsafe = Buffer.allocUnsafe || - /* istanbul ignore next */ - function Buffer_allocUnsafe(size) { - return new Buffer(size); - }; -}; - - -/***/ }), - -/***/ 34334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = verifier; - -var Enum = __nccwpck_require__(17732), - util = __nccwpck_require__(47174); - -function invalid(field, expected) { - return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; -} - -/** - * Generates a partial value verifier. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {number} fieldIndex Field index - * @param {string} ref Variable reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genVerifyValue(gen, field, fieldIndex, ref) { - /* eslint-disable no-unexpected-multiline */ - if (field.resolvedType) { - if (field.resolvedType instanceof Enum) { gen - ("switch(%s){", ref) - ("default:") - ("return%j", invalid(field, "enum value")); - for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen - ("case %i:", field.resolvedType.values[keys[j]]); - gen - ("break") - ("}"); - } else { - gen - ("{") - ("var e=types[%i].verify(%s);", fieldIndex, ref) - ("if(e)") - ("return%j+e", field.name + ".") - ("}"); + async linkIdentity(credentials) { + if ('token' in credentials) { + return this.linkIdentityIdToken(credentials); } - } else { - switch (field.type) { - case "int32": - case "uint32": - case "sint32": - case "fixed32": - case "sfixed32": gen - ("if(!util.isInteger(%s))", ref) - ("return%j", invalid(field, "integer")); - break; - case "int64": - case "uint64": - case "sint64": - case "fixed64": - case "sfixed64": gen - ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) - ("return%j", invalid(field, "integer|Long")); - break; - case "float": - case "double": gen - ("if(typeof %s!==\"number\")", ref) - ("return%j", invalid(field, "number")); - break; - case "bool": gen - ("if(typeof %s!==\"boolean\")", ref) - ("return%j", invalid(field, "boolean")); - break; - case "string": gen - ("if(!util.isString(%s))", ref) - ("return%j", invalid(field, "string")); - break; - case "bytes": gen - ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) - ("return%j", invalid(field, "buffer")); - break; + return this.linkIdentityOAuth(credentials); + } + async linkIdentityOAuth(credentials) { + var _a; + try { + const { data, error } = await this._useSession(async (result) => { + var _a, _b, _c, _d, _e; + const { data, error } = result; + if (error) + throw error; + const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: true, + }); + return await (0, fetch_1._request)(this.fetch, 'GET', url, { + headers: this.headers, + jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, + }); + }); + if (error) + throw error; + if ((0, helpers_1.isBrowser)() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { + window.location.assign(data === null || data === void 0 ? void 0 : data.url); + } + return this._returnResult({ + data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, + error: null, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { provider: credentials.provider, url: null }, error }); + } + throw error; } } - return gen; - /* eslint-enable no-unexpected-multiline */ -} - -/** - * Generates a partial key verifier. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {string} ref Variable reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genVerifyKey(gen, field, ref) { - /* eslint-disable no-unexpected-multiline */ - switch (field.keyType) { - case "int32": - case "uint32": - case "sint32": - case "fixed32": - case "sfixed32": gen - ("if(!util.key32Re.test(%s))", ref) - ("return%j", invalid(field, "integer key")); - break; - case "int64": - case "uint64": - case "sint64": - case "fixed64": - case "sfixed64": gen - ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not - ("return%j", invalid(field, "integer|Long key")); - break; - case "bool": gen - ("if(!util.key2Re.test(%s))", ref) - ("return%j", invalid(field, "boolean key")); - break; + async linkIdentityIdToken(credentials) { + return await this._useSession(async (result) => { + var _a; + try { + const { error: sessionError, data: { session }, } = result; + if (sessionError) + throw sessionError; + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined, + body: { + provider, + id_token: token, + access_token, + nonce, + link_identity: true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + return this._returnResult({ + data: { user: null, session: null }, + error: new errors_1.AuthInvalidTokenResponseError(), + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('USER_UPDATED', data.session); + } + return this._returnResult({ data, error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + }); } - return gen; - /* eslint-enable no-unexpected-multiline */ -} - -/** - * Generates a verifier specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -function verifier(mtype) { - /* eslint-disable no-unexpected-multiline */ - - var gen = util.codegen(["m"], mtype.name + "$verify") - ("if(typeof m!==\"object\"||m===null)") - ("return%j", "object expected"); - var oneofs = mtype.oneofsArray, - seenFirstField = {}; - if (oneofs.length) gen - ("var p={}"); - - for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { - var field = mtype._fieldsArray[i].resolve(), - ref = "m" + util.safeProp(field.name); - - if (field.optional) gen - ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null - - // map fields - if (field.map) { gen - ("if(!util.isObject(%s))", ref) - ("return%j", invalid(field, "object")) - ("var k=Object.keys(%s)", ref) - ("for(var i=0;i { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); } - genVerifyValue(gen, field, i, ref); + throw error; } - if (field.optional) gen - ("}"); } - return gen - ("return null"); - /* eslint-enable no-unexpected-multiline */ -} - -/***/ }), - -/***/ 63216: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * Wrappers for common types. - * @type {Object.} - * @const - */ -var wrappers = exports; - -var Message = __nccwpck_require__(68027); - -/** - * From object converter part of an {@link IWrapper}. - * @typedef WrapperFromObjectConverter - * @type {function} - * @param {Object.} object Plain object - * @returns {Message<{}>} Message instance - * @this Type - */ - -/** - * To object converter part of an {@link IWrapper}. - * @typedef WrapperToObjectConverter - * @type {function} - * @param {Message<{}>} message Message instance - * @param {IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - * @this Type - */ - -/** - * Common type wrapper part of {@link wrappers}. - * @interface IWrapper - * @property {WrapperFromObjectConverter} [fromObject] From object converter - * @property {WrapperToObjectConverter} [toObject] To object converter - */ - -// Custom wrapper for Any -wrappers[".google.protobuf.Any"] = { - - fromObject: function(object) { - - // unwrap value type if mapped - if (object && object["@type"]) { - // Only use fully qualified type name after the last '/' - var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); - var type = this.lookup(name); - /* istanbul ignore else */ - if (type) { - // type_url does not accept leading "." - var type_url = object["@type"].charAt(0) === "." ? - object["@type"].slice(1) : object["@type"]; - // type_url prefix is optional, but path seperator is required - if (type_url.indexOf("/") === -1) { - type_url = "/" + type_url; + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + const startedAt = Date.now(); + // will attempt to refresh the token with exponential backoff + return await (0, helpers_1.retryable)(async (attempt) => { + if (attempt > 0) { + await (0, helpers_1.sleep)(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... + } + this._debug(debugName, 'refreshing attempt', attempt); + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: fetch_1._sessionResponse, + }); + }, (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt); + return (error && + (0, errors_1.isAuthRetryableFetchError)(error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < constants_1.AUTO_REFRESH_TICK_DURATION_MS); + }); + } + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } + finally { + this._debug(debugName, 'end'); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }); + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); + // try to open on the browser + if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a, _b; + const debugName = '#_recoverAndRefresh()'; + this._debug(debugName, 'begin'); + try { + const currentSession = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey)); + if (currentSession && this.userStorage) { + let maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); + if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { + // storage and userStorage are the same storage medium, for example + // window.localStorage if userStorage does not have the user from + // storage stored, store it first thereby migrating the user object + // from storage -> userStorage + maybeUser = { user: currentSession.user }; + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', maybeUser); + } + currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : (0, helpers_1.userNotAvailableProxy)(); + } + else if (currentSession && !currentSession.user) { + // user storage is not set, let's check if it was previously enabled so + // we bring back the storage as it should be + if (!currentSession.user) { + // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key + const separateUser = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey + '-user')); + if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { + currentSession.user = separateUser.user; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); + } + else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + } + this._debug(debugName, 'session from storage', currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid'); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS; + this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${constants_1.EXPIRY_MARGIN_MS}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); + await this._removeSession(); + } + } + } + } + else if (currentSession.user && + currentSession.user.__isUserNotAvailableProxy === true) { + // If we have a proxy user, try to get the real user data + try { + const { data, error: userError } = await this._getUser(currentSession.access_token); + if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { + currentSession.user = data.user; + await this._saveSession(currentSession); + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + else { + this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification'); + } + } + catch (getUserError) { + console.error('Error getting user data:', getUserError); + this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError); + } + } + else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + } + catch (err) { + this._debug(debugName, 'error', err); + console.error(err); + return; + } + finally { + this._debug(debugName, 'end'); + } + } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new errors_1.AuthSessionMissingError(); + } + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + this.refreshingDeferred = new helpers_1.Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new errors_1.AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); + const result = { data: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + const result = { data: null, error }; + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + await this._removeSession(); + } + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } + finally { + this.refreshingDeferred = null; + this._debug(debugName, 'end'); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } + catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); } - return this.create({ - type_url: type_url, - value: type.encode(type.fromObject(object)).finish() + throw errors[0]; + } + } + finally { + this._debug(debugName, 'end'); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug('#_saveSession()', session); + // _saveSession is always called whenever a new session has been acquired + // so we can safely suppress the warning returned by future getSession calls + this.suppressGetSessionWarning = true; + // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere + const sessionToProcess = Object.assign({}, session); + const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; + if (this.userStorage) { + if (!userIsProxy && sessionToProcess.user) { + // If it's a real user object, save it to userStorage. + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', { + user: sessionToProcess.user, }); } + else if (userIsProxy) { + // If it's the proxy, it means user was not found in userStorage. + // We should ensure no stale user data for this key exists in userStorage if we were to save null, + // or simply not save the proxy. For now, we don't save the proxy here. + // If there's a need to clear userStorage if user becomes proxy, that logic would go here. + } + // Prepare the main session data for primary storage: remove the user property before cloning + // This is important because the original session.user might be the proxy + const mainSessionData = Object.assign({}, sessionToProcess); + delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage + const clonedMainSessionData = (0, helpers_1.deepClone)(mainSessionData); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedMainSessionData); } - - return this.fromObject(object); - }, - - toObject: function(message, options) { - - // Default prefix - var googleApi = "type.googleapis.com/"; - var prefix = ""; - var name = ""; - - // decode value if requested and unmapped - if (options && options.json && message.type_url && message.value) { - // Only use fully qualified type name after the last '/' - name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); - // Separate the prefix used - prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); - var type = this.lookup(name); - /* istanbul ignore else */ - if (type) - message = type.decode(message.value); + else { + // No userStorage is configured. + // In this case, session.user should ideally not be a proxy. + // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here + const clonedSession = (0, helpers_1.deepClone)(sessionToProcess); // sessionToProcess still has its original user property + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedSession); } - - // wrap value if unmapped - if (!(message instanceof this.ctor) && message instanceof Message) { - var object = message.$type.toObject(message, options); - var messageName = message.$type.fullName[0] === "." ? - message.$type.fullName.slice(1) : message.$type.fullName; - // Default to type.googleapis.com prefix if no prefix is used - if (prefix === "") { - prefix = googleApi; - } - name = prefix + messageName; - object["@type"] = name; - return object; + } + async _removeSession() { + this._debug('#_removeSession()'); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-code-verifier'); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); + if (this.userStorage) { + await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + '-user'); } - - return this.toObject(message, options); + await this._notifyAllSubscribers('SIGNED_OUT', null); } -}; - - -/***/ }), - -/***/ 13098: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Writer; - -var util = __nccwpck_require__(71241); - -var BufferWriter; // cyclic - -var LongBits = util.LongBits, - base64 = util.base64, - utf8 = util.utf8; - -/** - * Constructs a new writer operation instance. - * @classdesc Scheduled writer operation. - * @constructor - * @param {function(*, Uint8Array, number)} fn Function to call - * @param {number} len Value byte length - * @param {*} val Value to write - * @ignore - */ -function Op(fn, len, val) { - - /** - * Function to call. - * @type {function(Uint8Array, number, *)} - */ - this.fn = fn; - - /** - * Value byte length. - * @type {number} - */ - this.len = len; - - /** - * Next operation. - * @type {Writer.Op|undefined} - */ - this.next = undefined; - - /** - * Value to write. - * @type {*} - */ - this.val = val; // type varies -} - -/* istanbul ignore next */ -function noop() {} // eslint-disable-line no-empty-function - -/** - * Constructs a new writer state instance. - * @classdesc Copied writer state. - * @memberof Writer - * @constructor - * @param {Writer} writer Writer to copy state from - * @ignore - */ -function State(writer) { - - /** - * Current head. - * @type {Writer.Op} - */ - this.head = writer.head; - - /** - * Current tail. - * @type {Writer.Op} - */ - this.tail = writer.tail; - - /** - * Current buffer length. - * @type {number} - */ - this.len = writer.len; - - /** - * Next state. - * @type {State|null} - */ - this.next = writer.states; -} - -/** - * Constructs a new writer instance. - * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. - * @constructor - */ -function Writer() { - - /** - * Current length. - * @type {number} - */ - this.len = 0; - - /** - * Operations head. - * @type {Object} - */ - this.head = new Op(noop, 0, 0); - - /** - * Operations tail - * @type {Object} - */ - this.tail = this.head; - /** - * Linked forked states. - * @type {Object|null} + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} */ - this.states = null; - - // When a value is written, the writer calculates its byte length and puts it into a linked - // list of operations to perform when finish() is called. This both allows us to allocate - // buffers of the exact required size and reduces the amount of work we have to do compared - // to first calculating over objects and then encoding over objects. In our case, the encoding - // part is just a linked list walk calling operations with already prepared values. -} - -var create = function create() { - return util.Buffer - ? function create_buffer_setup() { - return (Writer.create = function create_buffer() { - return new BufferWriter(); - })(); + _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()'); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener('visibilitychange', callback); + } + } + catch (e) { + console.error('removing visibilitychange callback failed', e); } - /* istanbul ignore next */ - : function create_array() { - return new Writer(); - }; -}; - -/** - * Creates a new writer. - * @function - * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} - */ -Writer.create = create(); - -/** - * Allocates a buffer of the specified size. - * @param {number} size Buffer size - * @returns {Uint8Array} Buffer - */ -Writer.alloc = function alloc(size) { - return new util.Array(size); -}; - -// Use Uint8Array buffer pool in the browser, just like node does with buffers -/* istanbul ignore else */ -if (util.Array !== Array) - Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); - -/** - * Pushes a new operation to the queue. - * @param {function(Uint8Array, number, *)} fn Function to call - * @param {number} len Value byte length - * @param {number} val Value to write - * @returns {Writer} `this` - * @private - */ -Writer.prototype._push = function push(fn, len, val) { - this.tail = this.tail.next = new Op(fn, len, val); - this.len += len; - return this; -}; - -function writeByte(val, buf, pos) { - buf[pos] = val & 255; -} - -function writeVarint32(val, buf, pos) { - while (val > 127) { - buf[pos++] = val & 127 | 128; - val >>>= 7; - } - buf[pos] = val; -} - -/** - * Constructs a new varint writer operation instance. - * @classdesc Scheduled varint writer operation. - * @extends Op - * @constructor - * @param {number} len Value byte length - * @param {number} val Value to write - * @ignore - */ -function VarintOp(len, val) { - this.len = len; - this.next = undefined; - this.val = val; -} - -VarintOp.prototype = Object.create(Op.prototype); -VarintOp.prototype.fn = writeVarint32; - -/** - * Writes an unsigned 32 bit value as a varint. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.uint32 = function write_uint32(value) { - // here, the call to this.push has been inlined and a varint specific Op subclass is used. - // uint32 is by far the most frequently used operation and benefits significantly from this. - this.len += (this.tail = this.tail.next = new VarintOp( - (value = value >>> 0) - < 128 ? 1 - : value < 16384 ? 2 - : value < 2097152 ? 3 - : value < 268435456 ? 4 - : 5, - value)).len; - return this; -}; - -/** - * Writes a signed 32 bit value as a varint. - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.int32 = function write_int32(value) { - return value < 0 - ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec - : this.uint32(value); -}; - -/** - * Writes a 32 bit value as a varint, zig-zag encoded. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.sint32 = function write_sint32(value) { - return this.uint32((value << 1 ^ value >> 31) >>> 0); -}; - -function writeVarint64(val, buf, pos) { - while (val.hi) { - buf[pos++] = val.lo & 127 | 128; - val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; - val.hi >>>= 7; - } - while (val.lo > 127) { - buf[pos++] = val.lo & 127 | 128; - val.lo = val.lo >>> 7; - } - buf[pos++] = val.lo; -} - -/** - * Writes an unsigned 64 bit value as a varint. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.uint64 = function write_uint64(value) { - var bits = LongBits.from(value); - return this._push(writeVarint64, bits.length(), bits); -}; - -/** - * Writes a signed 64 bit value as a varint. - * @function - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.int64 = Writer.prototype.uint64; - -/** - * Writes a signed 64 bit value as a varint, zig-zag encoded. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.sint64 = function write_sint64(value) { - var bits = LongBits.from(value).zzEncode(); - return this._push(writeVarint64, bits.length(), bits); -}; - -/** - * Writes a boolish value as a varint. - * @param {boolean} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.bool = function write_bool(value) { - return this._push(writeByte, 1, value ? 1 : 0); -}; - -function writeFixed32(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; -} - -/** - * Writes an unsigned 32 bit value as fixed 32 bits. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.fixed32 = function write_fixed32(value) { - return this._push(writeFixed32, 4, value >>> 0); -}; - -/** - * Writes a signed 32 bit value as fixed 32 bits. - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.sfixed32 = Writer.prototype.fixed32; - -/** - * Writes an unsigned 64 bit value as fixed 64 bits. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.fixed64 = function write_fixed64(value) { - var bits = LongBits.from(value); - return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); -}; - -/** - * Writes a signed 64 bit value as fixed 64 bits. - * @function - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.sfixed64 = Writer.prototype.fixed64; - -/** - * Writes a float (32 bit). - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.float = function write_float(value) { - return this._push(util.float.writeFloatLE, 4, value); -}; - -/** - * Writes a double (64 bit float). - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.double = function write_double(value) { - return this._push(util.float.writeDoubleLE, 8, value); -}; - -var writeBytes = util.Array.prototype.set - ? function writeBytes_set(val, buf, pos) { - buf.set(val, pos); // also works for plain array values - } - /* istanbul ignore next */ - : function writeBytes_for(val, buf, pos) { - for (var i = 0; i < val.length; ++i) - buf[pos + i] = val[i]; - }; - -/** - * Writes a sequence of bytes. - * @param {Uint8Array|string} value Buffer or base64 encoded string to write - * @returns {Writer} `this` - */ -Writer.prototype.bytes = function write_bytes(value) { - var len = value.length >>> 0; - if (!len) - return this._push(writeByte, 1, 0); - if (util.isString(value)) { - var buf = Writer.alloc(len = base64.length(value)); - base64.decode(value, buf, 0); - value = buf; - } - return this.uint32(len)._push(writeBytes, len, value); -}; - -/** - * Writes a string. - * @param {string} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.string = function write_string(value) { - var len = utf8.length(value); - return len - ? this.uint32(len)._push(utf8.write, len, value) - : this._push(writeByte, 1, 0); -}; - -/** - * Forks this writer's state by pushing it to a stack. - * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. - * @returns {Writer} `this` - */ -Writer.prototype.fork = function fork() { - this.states = new State(this); - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - return this; -}; - -/** - * Resets this instance to the last state. - * @returns {Writer} `this` - */ -Writer.prototype.reset = function reset() { - if (this.states) { - this.head = this.states.head; - this.tail = this.states.tail; - this.len = this.states.len; - this.states = this.states.next; - } else { - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - } - return this; -}; - -/** - * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. - * @returns {Writer} `this` - */ -Writer.prototype.ldelim = function ldelim() { - var head = this.head, - tail = this.tail, - len = this.len; - this.reset().uint32(len); - if (len) { - this.tail.next = head.next; // skip noop - this.tail = tail; - this.len += len; } - return this; -}; - -/** - * Finishes the write operation. - * @returns {Uint8Array} Finished buffer - */ -Writer.prototype.finish = function finish() { - var head = this.head.next, // skip noop - buf = this.constructor.alloc(this.len), - pos = 0; - while (head) { - head.fn(head.val, buf, pos); - pos += head.len; - head = head.next; - } - // this.head = this.tail = null; - return buf; -}; - -Writer._configure = function(BufferWriter_) { - BufferWriter = BufferWriter_; - Writer.create = create(); - BufferWriter._configure(); -}; - - -/***/ }), - -/***/ 41863: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = BufferWriter; - -// extends Writer -var Writer = __nccwpck_require__(13098); -(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; - -var util = __nccwpck_require__(71241); - -/** - * Constructs a new buffer writer instance. - * @classdesc Wire format writer using node buffers. - * @extends Writer - * @constructor - */ -function BufferWriter() { - Writer.call(this); -} - -BufferWriter._configure = function () { /** - * Allocates a buffer of the specified size. - * @function - * @param {number} size Buffer size - * @returns {Buffer} Buffer + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. */ - BufferWriter.alloc = util._Buffer_allocUnsafe; - - BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" - ? function writeBytesBuffer_set(val, buf, pos) { - buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) - // also works for plain array values + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug('#_startAutoRefresh()'); + const ticker = setInterval(() => this._autoRefreshTokenTick(), constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref(); + // @ts-expect-error TS has no context of Deno } - /* istanbul ignore next */ - : function writeBytesBuffer_copy(val, buf, pos) { - if (val.copy) // Buffer values - val.copy(buf, pos, 0, val.length); - else for (var i = 0; i < val.length;) // plain array values - buf[pos++] = val[i++]; - }; -}; - - -/** - * @override - */ -BufferWriter.prototype.bytes = function write_bytes_buffer(value) { - if (util.isString(value)) - value = util._Buffer_from(value, "base64"); - var len = value.length >>> 0; - this.uint32(len); - if (len) - this._push(BufferWriter.writeBytesBuffer, len, value); - return this; -}; - -function writeStringBuffer(val, buf, pos) { - if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) - util.utf8.write(val, buf, pos); - else if (buf.utf8Write) - buf.utf8Write(val, pos); - else - buf.write(val, pos); -} - -/** - * @override - */ -BufferWriter.prototype.string = function write_string_buffer(value) { - var len = util.Buffer.byteLength(value); - this.uint32(len); - if (len) - this._push(writeStringBuffer, len, value); - return this; -}; - - -/** - * Finishes the write operation. - * @name BufferWriter#finish - * @function - * @returns {Buffer} Finished buffer - */ - -BufferWriter._configure(); - - -/***/ }), - -/***/ 63329: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var parseUrl = (__nccwpck_require__(57310).parse); - -var DEFAULT_PORTS = { - ftp: 21, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443, -}; - -var stringEndsWith = String.prototype.endsWith || function(s) { - return s.length <= this.length && - this.indexOf(s, this.length - s.length) !== -1; -}; - -/** - * @param {string|object} url - The URL, or the result from url.parse. - * @return {string} The URL of the proxy that should handle the request to the - * given URL. If no proxy is set, this will be an empty string. - */ -function getProxyForUrl(url) { - var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; - var proto = parsedUrl.protocol; - var hostname = parsedUrl.host; - var port = parsedUrl.port; - if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { - return ''; // Don't proxy URLs without a valid scheme or host. - } - - proto = proto.split(':', 1)[0]; - // Stripping ports in this way instead of using parsedUrl.hostname to make - // sure that the brackets around IPv6 addresses are kept. - hostname = hostname.replace(/:\d*$/, ''); - port = parseInt(port) || DEFAULT_PORTS[proto] || 0; - if (!shouldProxy(hostname, port)) { - return ''; // Don't proxy URLs that match NO_PROXY. - } - - var proxy = - getEnv('npm_config_' + proto + '_proxy') || - getEnv(proto + '_proxy') || - getEnv('npm_config_proxy') || - getEnv('all_proxy'); - if (proxy && proxy.indexOf('://') === -1) { - // Missing scheme in proxy, default to the requested URL's scheme. - proxy = proto + '://' + proxy; - } - return proxy; -} - -/** - * Determines whether a given URL should be proxied. - * - * @param {string} hostname - The host name of the URL. - * @param {number} port - The effective port of the URL. - * @returns {boolean} Whether the given URL should be proxied. - * @private - */ -function shouldProxy(hostname, port) { - var NO_PROXY = - (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); - if (!NO_PROXY) { - return true; // Always proxy if NO_PROXY is not set. - } - if (NO_PROXY === '*') { - return false; // Never proxy if wildcard is set. - } - - return NO_PROXY.split(/[,\s]/).every(function(proxy) { - if (!proxy) { - return true; // Skip zero-length hosts. - } - var parsedProxy = proxy.match(/^(.+):(\d+)$/); - var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; - var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; - if (parsedProxyPort && parsedProxyPort !== port) { - return true; // Skip if ports don't match. - } - - if (!/^[.*]/.test(parsedProxyHostname)) { - // No wildcards, so stop proxying if there is an exact match. - return hostname !== parsedProxyHostname; - } - - if (parsedProxyHostname.charAt(0) === '*') { - // Remove leading wildcard. - parsedProxyHostname = parsedProxyHostname.slice(1); - } - // Stop proxying if the hostname ends with the no_proxy host. - return !stringEndsWith.call(hostname, parsedProxyHostname); - }); -} - -/** - * Get the value for an environment variable. - * - * @param {string} key - The name of the environment variable. - * @return {string} The value of the environment variable. - * @private - */ -function getEnv(key) { - return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; -} - -exports.getProxyForUrl = getProxyForUrl; - - -/***/ }), - -/***/ 18341: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223) -var eos = __nccwpck_require__(81205) -var fs - -try { - fs = __nccwpck_require__(57147) // we only need fs to get the ReadStream and WriteStream prototypes -} catch (e) {} - -var noop = function () {} -var ancient = typeof process === 'undefined' ? false : /^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 - - -/***/ }), - -/***/ 67214: -/***/ ((module) => { - -"use strict"; - - -const codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error - } - - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } - } - - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; -} - -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - -module.exports.q = codes; - - -/***/ }), - -/***/ 41359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - - - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -}; -/**/ - -module.exports = Duplex; -var Readable = __nccwpck_require__(51433); -var Writable = __nccwpck_require__(26993); -__nccwpck_require__(44124)(Duplex, Readable); -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -// the no-half-open enforcer -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(onEndNT, this); -} -function onEndNT(self) { - self.end(); -} -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; + else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-expect-error TS has no context of Deno + Deno.unrefTimer(ticker); + } + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); - -/***/ }), - -/***/ 81542: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - - - -module.exports = PassThrough; -var Transform = __nccwpck_require__(34415); -__nccwpck_require__(44124)(PassThrough, Transform); -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; - -/***/ }), - -/***/ 51433: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - - - -module.exports = Readable; - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = (__nccwpck_require__(82361).EventEmitter); -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = __nccwpck_require__(62387); -/**/ - -var Buffer = (__nccwpck_require__(14300).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ -var debugUtil = __nccwpck_require__(73837); -var debug; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - -var BufferList = __nccwpck_require__(52746); -var destroyImpl = __nccwpck_require__(97049); -var _require = __nccwpck_require__(39948), - getHighWaterMark = _require.getHighWaterMark; -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - -// Lazy loaded to improve the startup performance. -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; -__nccwpck_require__(44124)(Readable, Stream); -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); - - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(41359); - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; - - // Should close be emitted on destroy. Defaults to true. - this.emitClose = options.emitClose !== false; - - // Should .destroy() be called after 'end' (and potentially 'finish') - this.autoDestroy = !!options.autoDestroy; - - // has it been destroyed - this.destroyed = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(94841)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(41359); - if (!(this instanceof Readable)) return new Readable(options); - - // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); - - // legacy - this.readable = true; - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - Stream.call(this); -} -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()'); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } } - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin'); + try { + await this._acquireLock(0, async () => { + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session }, } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session'); + return; + } + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } + catch (e) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e); + } + } + finally { + this._debug('#_autoRefreshTokenTick()', 'end'); + } + }); + } + catch (e) { + if (e.isAcquireTimeout || e instanceof locks_1.LockAcquireTimeoutError) { + this._debug('auto refresh token tick lock not available'); + } + else { + throw e; + } } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); } - } - - // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - return er; -} -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(94841)/* .StringDecoder */ .s); - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; - // If setEncoding(null), decoder.encoding equals utf8 - this._readableState.encoding = this._readableState.decoder.encoding; - - // Iterate over current buffer to convert already stored Buffers: - var p = this._readableState.buffer.head; - var content = ''; - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - this._readableState.buffer.clear(); - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; - -// Don't raise the hwm > 1GB -var MAX_HWM = 0x40000000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - if (ret !== null) this.emit('data', ret); - return ret; -}; -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } - - // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()'); + if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true); // initial call + } + catch (error) { + console.error('_handleVisibilityChange', error); + } } - } - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - src.pause(); + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(calledFromInitialize) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; + this._debug(methodName, 'visibilityState', document.visibilityState); + if (document.visibilityState === 'visible') { + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh(); + } + if (!calledFromInitialize) { + // called when the visibility has changed, i.e. the browser + // transitioned from hidden -> visible so we need to see if the session + // should be recovered immediately... but to do that we need to acquire + // the lock first asynchronously + await this.initializePromise; + await this._acquireLock(-1, async () => { + if (document.visibilityState !== 'visible') { + this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); + // visibility has changed while waiting for the lock, abort + return; + } + // recover the session + await this._recoverAndRefresh(); + }); + } + } + else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - return dest; -}; -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(url, provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === 'pkce') { + const [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); + } + return `${url}?${urlParams.join('&')}`; } - }; -} -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; - - // Try start flowing on next tick if stream isn't explicitly paused - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - } - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - return res; -}; -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - return res; -}; -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; - - // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - state.flowing = !state.readableListening; - resume(this, state); - } - state.paused = false; - return this; -}; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} -function resume_(stream, state) { - debug('resume', state.reading); - if (!state.reading) { - stream.read(0); - } - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - this._readableState.paused = true; - return this; -}; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null); -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' + ? { phone: params.phone } + : params.factorType === 'totp' + ? { issuer: params.issuer } + : {})); + const { data, error } = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (error) { + return this._returnResult({ data: null, error }); + } + if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return this._returnResult({ data, error: null }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); + async _verify(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params + ? { + webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create' + ? (0, webauthn_1.serializeCredentialCreationResponse)(params.webauthn.credential_response) + : (0, webauthn_1.serializeCredentialRequestResponse)(params.webauthn.credential_response) }), + } + : { code: params.code })); + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return this._returnResult({ data: null, error }); + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); + return this._returnResult({ data, error }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + async _challenge(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const response = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { + body: params, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (response.error) { + return response; + } + const { data } = response; + if (data.type !== 'webauthn') { + return { data, error: null }; + } + switch (data.webauthn.type) { + case 'create': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialCreationOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + case 'request': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialRequestOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + } + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + // both _challenge and _verify independently acquire the lock, so no need + // to acquire it here + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }); + if (challengeError) { + return this._returnResult({ data: null, error: challengeError }); + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + var _a; + // use #getUser instead of #_getUser as the former acquires a lock + const { data: { user }, error: userError, } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const data = { + all: [], + phone: [], + totp: [], + webauthn: [], + }; + // loop over the factors ONCE + for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) { + data.all.push(factor); + if (factor.status === 'verified') { + ; + data[factor.factor_type].push(factor); + } + } + return { + data, + error: null, }; - }(i); } - } - - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + var _a, _b; + const { data: { session }, error: sessionError, } = await this.getSession(); + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + }; + } + const { payload } = (0, helpers_1.decodeJWT)(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = 'aal2'; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; } - }; - return this; -}; -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = __nccwpck_require__(43306); + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + async _getAuthorizationDetails(authorizationId) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }), + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _approveAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'approve' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - return createReadableStreamAsyncIterator(this); - }; -} -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _denyAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'deny' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - } -}); - -// exposed for testing purposes only. -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); - - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } + async fetchJwk(kid, jwks = { keys: [] }) { + // try fetching from the supplied jwks + let jwk = jwks.keys.find((key) => key.kid === kid); + if (jwk) { + return jwk; + } + const now = Date.now(); + // try fetching from cache + jwk = this.jwks.keys.find((key) => key.kid === kid); + // jwk exists and jwks isn't stale + if (jwk && this.jwks_cached_at + constants_1.JWKS_TTL > now) { + return jwk; + } + // jwk isn't cached in memory so we need to fetch it from the well-known endpoint + const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, { + headers: this.headers, + }); + if (error) { + throw error; + } + if (!data.keys || data.keys.length === 0) { + return null; + } + this.jwks = data; + this.jwks_cached_at = now; + // Find the signing key + jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) { + return null; + } + return jwk; } - } -} -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = __nccwpck_require__(39082); + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + async getClaims(jwt, options = {}) { + try { + let token = jwt; + if (!token) { + const { data, error } = await this.getSession(); + if (error || !data.session) { + return this._returnResult({ data: null, error }); + } + token = data.session.access_token; + } + const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = (0, helpers_1.decodeJWT)(token); + if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { + // Reject expired JWTs should only happen if jwt argument was passed + (0, helpers_1.validateExp)(payload.exp); + } + const signingKey = !header.alg || + header.alg.startsWith('HS') || + !header.kid || + !('crypto' in globalThis && 'subtle' in globalThis.crypto) + ? null + : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); + // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser() + if (!signingKey) { + const { error } = await this.getUser(token); + if (error) { + throw error; + } + // getUser succeeds so the claims in the JWT can be trusted + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + const algorithm = (0, helpers_1.getAlgorithm)(header.alg); + // Convert JWK to CryptoKey + const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [ + 'verify', + ]); + // Verify the signature + const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, (0, base64url_1.stringToUint8Array)(`${rawHeader}.${rawPayload}`)); + if (!isValid) { + throw new errors_1.AuthInvalidJwtError('Invalid JWT signature'); + } + // If verification succeeds, decode and return claims + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - return from(Readable, iterable, opts); - }; -} -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; } +GoTrueClient.nextInstanceID = {}; +exports["default"] = GoTrueClient; +//# sourceMappingURL=GoTrueClient.js.map /***/ }), -/***/ 34415: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 6748: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// 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. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - - -module.exports = Transform; -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; -var Duplex = __nccwpck_require__(41359); -__nccwpck_require__(44124)(Transform, Duplex); -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - ts.writechunk = null; - ts.writecb = null; - if (data != null) - // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } - - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); -} -function prefinish() { - var _this = this; - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) - // single equals check for both `null` and `undefined` - stream.push(data); - - // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; +const tslib_1 = __nccwpck_require__(4351); +const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(6575)); +exports.GoTrueAdminApi = GoTrueAdminApi_1.default; +const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(313)); +exports.GoTrueClient = GoTrueClient_1.default; +const AuthAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(9809)); +exports.AuthAdminApi = AuthAdminApi_1.default; +const AuthClient_1 = tslib_1.__importDefault(__nccwpck_require__(4525)); +exports.AuthClient = AuthClient_1.default; +tslib_1.__exportStar(__nccwpck_require__(1852), exports); +tslib_1.__exportStar(__nccwpck_require__(9938), exports); +var locks_1 = __nccwpck_require__(163); +Object.defineProperty(exports, "navigatorLock", ({ enumerable: true, get: function () { return locks_1.navigatorLock; } })); +Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", ({ enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } })); +Object.defineProperty(exports, "lockInternals", ({ enumerable: true, get: function () { return locks_1.internals; } })); +Object.defineProperty(exports, "processLock", ({ enumerable: true, get: function () { return locks_1.processLock; } })); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 26993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 3649: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// 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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - - - -module.exports = Writable; - -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var internalUtil = { - deprecate: __nccwpck_require__(65278) -}; -/**/ - -/**/ -var Stream = __nccwpck_require__(62387); -/**/ - -var Buffer = (__nccwpck_require__(14300).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -var destroyImpl = __nccwpck_require__(97049); -var _require = __nccwpck_require__(39948), - getHighWaterMark = _require.getHighWaterMark; -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; -var errorOrDestroy = destroyImpl.errorOrDestroy; -__nccwpck_require__(44124)(Writable, Stream); -function nop() {} -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(41359); - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); - - // if _final has been called - this.finalCalled = false; - - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // has it been destroyed - this.destroyed = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // Should close be emitted on destroy. Defaults to true. - this.emitClose = options.emitClose !== false; - - // Should .destroy() be called after 'finish' (and potentially 'end') - this.autoDestroy = !!options.autoDestroy; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); - -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(41359); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); - - // legacy. - this.writable = true; - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); - // TODO: defer error events consistently everywhere, not just the cb - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} - -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var er; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - return true; -} -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; -Writable.prototype.cork = function () { - this._writableState.corked++; -}; -Writable.prototype.uncork = function () { - var state = this._writableState; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - return ret; -} -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); +/** + * Avoid modifying this file. It's part of + * https://github.com/supabase-community/base64url-js. Submit all fixes on + * that repo! + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.byteToBase64URL = byteToBase64URL; +exports.byteFromBase64URL = byteFromBase64URL; +exports.stringToBase64URL = stringToBase64URL; +exports.stringFromBase64URL = stringFromBase64URL; +exports.codepointToUTF8 = codepointToUTF8; +exports.stringToUTF8 = stringToUTF8; +exports.stringFromUTF8 = stringFromUTF8; +exports.base64UrlToUint8Array = base64UrlToUint8Array; +exports.stringToUint8Array = stringToUint8Array; +exports.bytesToBase64URL = bytesToBase64URL; +/** + * An array of characters that encode 6 bits into a Base64-URL alphabet + * character. + */ +const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split(''); +/** + * An array of characters that can appear in a Base64-URL encoded string but + * should be ignored. + */ +const IGNORE_BASE64URL = ' \t\n\r='.split(''); +/** + * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2 + * used to skip the character, or if -1 used to error out. + */ +const FROM_BASE64URL = (() => { + const charMap = new Array(128); + for (let i = 0; i < charMap.length; i += 1) { + charMap[i] = -1; } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } + for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { + charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2; } - if (entry === null) state.lastBufferedRequest = null; - } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; -Writable.prototype._writev = null; -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending) endWritable(this, state, cb); - return this; -}; -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream, err); + for (let i = 0; i < TO_BASE64URL.length; i += 1) { + charMap[TO_BASE64URL[i].charCodeAt(0)] = i; } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); + return charMap; +})(); +/** + * Converts a byte to a Base64-URL string. + * + * @param byte The byte to convert, or null to flush at the end of the byte sequence. + * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next Base64 character when ready. + */ +function byteToBase64URL(byte, state, emit) { + if (byte !== null) { + state.queue = (state.queue << 8) | byte; + state.queuedBits += 8; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } } - } -} -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); + else if (state.queuedBits > 0) { + state.queue = state.queue << (6 - state.queuedBits); + state.queuedBits = 6; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; } - } } - } - return need; -} -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - - // reuse the free corkReq. - state.corkedRequestsFree.next = corkReq; } -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; +/** + * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. + * + * @param charCode The char code of the JavaScript string. + * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next byte. + */ +function byteFromBase64URL(charCode, state, emit) { + const bits = FROM_BASE64URL[charCode]; + if (bits > -1) { + // valid Base64-URL character + state.queue = (state.queue << 6) | bits; + state.queuedBits += 6; + while (state.queuedBits >= 8) { + emit((state.queue >> (state.queuedBits - 8)) & 0xff); + state.queuedBits -= 8; + } } - - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; - -/***/ }), - -/***/ 43306: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var _Object$setPrototypeO; -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -var finished = __nccwpck_require__(76080); -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - if (resolve !== null) { - var data = iter[kStream].read(); - // we defer if data is null - // we can be expecting either 'end' or - // 'error' - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); + else if (bits === -2) { + // ignore spaces, tabs, newlines, = return; - } - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - next: function next() { - var _this = this; - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - if (error !== null) { - return Promise.reject(error); - } - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); } - - // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - var lastPromise = this[kLastPromise]; - var promise; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - promise = new Promise(this[kHandlePromise]); + else { + throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); } - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - resolve(createIterResult(undefined, true)); +} +/** + * Converts a JavaScript string (which may include any valid character) into a + * Base64-URL encoded string. The string is first encoded in UTF-8 which is + * then encoded as Base64-URL. + * + * @param str The string to convert. + */ +function stringToBase64URL(str) { + const base64 = []; + const emitter = (char) => { + base64.push(char); + }; + const state = { queue: 0, queuedBits: 0 }; + stringToUTF8(str, (byte) => { + byteToBase64URL(byte, state, emitter); }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; - // reject if we are waiting for data in the Promise - // returned by next() and store the error - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - iterator[kError] = err; - return; - } - var resolve = iterator[kLastResolve]; - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); + byteToBase64URL(null, state, emitter); + return base64.join(''); +} +/** + * Converts a Base64-URL encoded string into a JavaScript string. It is assumed + * that the underlying string has been encoded as UTF-8. + * + * @param str The Base64-URL encoded string. + */ +function stringFromBase64URL(str) { + const conv = []; + const utf8Emit = (codepoint) => { + conv.push(String.fromCodePoint(codepoint)); + }; + const utf8State = { + utf8seq: 0, + codepoint: 0, + }; + const b64State = { queue: 0, queuedBits: 0 }; + const byteEmit = (byte) => { + stringFromUTF8(byte, utf8State, utf8Emit); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit); } - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; -module.exports = createReadableStreamAsyncIterator; - -/***/ }), - -/***/ 52746: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -var _require = __nccwpck_require__(14300), - Buffer = _require.Buffer; -var _require2 = __nccwpck_require__(73837), - inspect = _require2.inspect; -var custom = inspect && inspect.custom || 'inspect'; -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} -module.exports = /*#__PURE__*/function () { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) ret += s + p.data; - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - } - - // Consumes a specified amount of bytes or characters from the buffered data. - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } - - // Consumes a specified amount of characters from the buffered data. - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - this.length -= c; - return ret; - } - - // Consumes a specified amount of bytes from the buffered data. - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - this.length -= c; - return ret; + return conv.join(''); +} +/** + * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. + * + * @param codepoint The Unicode codepoint. + * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. + */ +function codepointToUTF8(codepoint, emit) { + if (codepoint <= 0x7f) { + emit(codepoint); + return; } - - // Make sure the linked list only shows the minimal necessary information. - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread(_objectSpread({}, options), {}, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); + else if (codepoint <= 0x7ff) { + emit(0xc0 | (codepoint >> 6)); + emit(0x80 | (codepoint & 0x3f)); + return; } - }]); - return BufferList; -}(); - -/***/ }), - -/***/ 97049: -/***/ ((module) => { - -"use strict"; - - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } + else if (codepoint <= 0xffff) { + emit(0xe0 | (codepoint >> 12)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; } - return this; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } - - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); + else if (codepoint <= 0x10ffff) { + emit(0xf0 | (codepoint >> 18)); + emit(0x80 | ((codepoint >> 12) & 0x3f)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; } - }); - return this; -} -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} -function emitErrorNT(self, err) { - self.emit('error', err); -} -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); + throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); } -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; - -/***/ }), - -/***/ 76080: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). - - - -var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(67214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; +/** + * Converts a JavaScript string to a sequence of UTF-8 bytes. + * + * @param str The string to convert to UTF-8. + * @param emit Function which will be called for each UTF-8 byte of the string. + */ +function stringToUTF8(str, emit) { + for (let i = 0; i < str.length; i += 1) { + let codepoint = str.charCodeAt(i); + if (codepoint > 0xd7ff && codepoint <= 0xdbff) { + // most UTF-16 codepoints are Unicode codepoints, except values in this + // range where the next UTF-16 codepoint needs to be combined with the + // current one to get the Unicode codepoint + const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff; + const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff; + codepoint = (lowSurrogate | highSurrogate) + 0x10000; + i += 1; + } + codepointToUTF8(codepoint, emit); } - callback.apply(this, args); - }; } -function noop() {} -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - var writableEnded = stream._writableState && stream._writableState.finished; - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - var onerror = function onerror(err) { - callback.call(stream, err); - }; - var onclose = function onclose() { - var err; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); +/** + * Converts a UTF-8 byte to a Unicode codepoint. + * + * @param byte The UTF-8 byte next in the sequence. + * @param state The shared state between consecutive UTF-8 bytes in the + * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. + * @param emit Function which will be called for each codepoint. + */ +function stringFromUTF8(byte, state, emit) { + if (state.utf8seq === 0) { + if (byte <= 0x7f) { + emit(byte); + return; + } + // count the number of 1 leading bits until you reach 0 + for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { + if (((byte >> (7 - leadingBit)) & 1) === 0) { + state.utf8seq = leadingBit; + break; + } + } + if (state.utf8seq === 2) { + state.codepoint = byte & 31; + } + else if (state.utf8seq === 3) { + state.codepoint = byte & 15; + } + else if (state.utf8seq === 4) { + state.codepoint = byte & 7; + } + else { + throw new Error('Invalid UTF-8 sequence'); + } + state.utf8seq -= 1; } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); + else if (state.utf8seq > 0) { + if (byte <= 0x7f) { + throw new Error('Invalid UTF-8 sequence'); + } + state.codepoint = (state.codepoint << 6) | (byte & 63); + state.utf8seq -= 1; + if (state.utf8seq === 0) { + emit(state.codepoint); + } } - }; - var onrequest = function onrequest() { - 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 && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - 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('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; } -module.exports = eos; - -/***/ }), - -/***/ 39082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(67214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); -function from(Readable, iterable, opts) { - var iterator; - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); - // Reading boolean to protect against _read - // being called before last iteration completion. - var reading = false; - readable._read = function () { - if (!reading) { - reading = true; - next(); +/** + * Helper functions to convert different types of strings to Uint8Array + */ +function base64UrlToUint8Array(str) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onByte = (byte) => { + result.push(byte); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), state, onByte); } - }; - function next() { - return _next2.apply(this, arguments); - } - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _yield$iterator$next = yield iterator.next(), - value = _yield$iterator$next.value, - done = _yield$iterator$next.done; - if (done) { - readable.push(null); - } else if (readable.push(yield value)) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - return readable; -} -module.exports = from; - - -/***/ }), - -/***/ 76989: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). - - - -var eos; -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; + return new Uint8Array(result); } -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = __nccwpck_require__(76080); - 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; - - // request.destroy just do .end - .abort is what we want - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; +function stringToUint8Array(str) { + const result = []; + stringToUTF8(str, (byte) => result.push(byte)); + return new Uint8Array(result); } -function call(fn) { - fn(); -} -function pipe(from, to) { - return from.pipe(to); -} -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - 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); +function bytesToBase64URL(bytes) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onChar = (char) => { + result.push(char); + }; + bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); + // always call with `null` after processing all bytes + byteToBase64URL(null, state, onChar); + return result.join(''); } -module.exports = pipeline; +//# sourceMappingURL=base64url.js.map /***/ }), -/***/ 39948: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 518: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(67214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - return Math.floor(hwm); - } - - // Default value - return state.objectMode ? 16 : 16 * 1024; -} -module.exports = { - getHighWaterMark: getHighWaterMark +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0; +const version_1 = __nccwpck_require__(6677); +/** Current session will be checked for refresh at this interval. */ +exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +exports.AUTO_REFRESH_TICK_THRESHOLD = 3; +/* + * Earliest time before an access token expires that the session should be refreshed. + */ +exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS; +exports.GOTRUE_URL = 'http://localhost:9999'; +exports.STORAGE_KEY = 'supabase.auth.token'; +exports.AUDIENCE = ''; +exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` }; +exports.NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds }; +exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; +exports.API_VERSIONS = { + '2024-01-01': { + timestamp: Date.parse('2024-01-01T00:00:00.0Z'), + name: '2024-01-01', + }, +}; +exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; +exports.JWKS_TTL = 10 * 60 * 1000; // 10 minutes +//# sourceMappingURL=constants.js.map /***/ }), -/***/ 62387: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(12781); - - -/***/ }), - -/***/ 51642: -/***/ ((module, exports, __nccwpck_require__) => { - -var Stream = __nccwpck_require__(12781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(51433); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(26993); - exports.Duplex = __nccwpck_require__(41359); - exports.Transform = __nccwpck_require__(34415); - exports.PassThrough = __nccwpck_require__(81542); - exports.finished = __nccwpck_require__(76080); - exports.pipeline = __nccwpck_require__(76989); -} - - -/***/ }), - -/***/ 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) +/***/ 9938: +/***/ ((__unused_webpack_module, exports) => { -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +"use strict"; -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) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0; +exports.isAuthError = isAuthError; +exports.isAuthApiError = isAuthApiError; +exports.isAuthSessionMissingError = isAuthSessionMissingError; +exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError; +exports.isAuthRetryableFetchError = isAuthRetryableFetchError; +exports.isAuthWeakPasswordError = isAuthWeakPasswordError; +class AuthError extends Error { + constructor(message, status, code) { + super(message); + this.__isAuthError = true; + this.name = 'AuthError'; + this.status = status; + this.code = code; } - } 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) +exports.AuthError = AuthError; +function isAuthError(error) { + return typeof error === 'object' && error !== null && '__isAuthError' in error; } - - -/***/ }), - -/***/ 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] +class AuthApiError extends AuthError { + constructor(message, status, code) { + super(message, status, code); + this.name = 'AuthApiError'; + this.status = status; + this.code = code; + } } - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] +exports.AuthApiError = AuthApiError; +function isAuthApiError(error) { + return isAuthError(error) && error.name === 'AuthApiError'; } - -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) +class AuthUnknownError extends AuthError { + constructor(message, originalError) { + super(message); + this.name = 'AuthUnknownError'; + this.originalError = originalError; } - 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) +exports.AuthUnknownError = AuthUnknownError; +class CustomAuthError extends AuthError { + constructor(message, name, status, code) { + super(message, status, code); + this.name = name; + this.status = status; } - 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 - } +exports.CustomAuthError = CustomAuthError; +class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); + } } - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } +exports.AuthSessionMissingError = AuthSessionMissingError; +function isAuthSessionMissingError(error) { + return isAuthError(error) && error.name === 'AuthSessionMissingError'; } - -module.exports = safer - - -/***/ }), - -/***/ 39798: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var fs = __nccwpck_require__(57147); - -module.exports = function (filepath, split, encoding) { - split = typeof split !== 'undefined' ? split : "\n"; - encoding = typeof encoding !== 'undefined' ? encoding : "utf8"; - - var ca = []; - var chain = fs.readFileSync(filepath, encoding); - if(chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0){ - throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); - } - chain = chain.split(split); - var cert = []; - var _i, _len; - for (_i = 0, _len = chain.length; _i < _len; _i++) { - var line = chain[_i]; - if (!(line.length !== 0)) { - continue; - } - cert.push(line); - if (line.match(/-END CERTIFICATE-/)) { - ca.push(cert.join(split)); - cert = []; +class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); } - } - return ca; } - - -/***/ }), - -/***/ 83204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - Duplex: DuplexStream, - Readable: ReadableStream, - Writable: WritableStream, -} = __nccwpck_require__(12781); - -const { - CHANNEL_EXTENDED_DATATYPE: { STDERR }, -} = __nccwpck_require__(36832); -const { bufferSlice } = __nccwpck_require__(49475); - -const PACKET_SIZE = 32 * 1024; -const MAX_WINDOW = 2 * 1024 * 1024; -const WINDOW_THRESHOLD = MAX_WINDOW / 2; - -class ClientStderr extends ReadableStream { - constructor(channel, streamOpts) { - super(streamOpts); - - this._channel = channel; - } - _read(n) { - if (this._channel._waitChanDrain) { - this._channel._waitChanDrain = false; - if (this._channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this._channel); +exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; +class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidCredentialsError', 400, undefined); } - } } - -class ServerStderr extends WritableStream { - constructor(channel) { - super({ highWaterMark: MAX_WINDOW }); - - this._channel = channel; - } - - _write(data, encoding, cb) { - const channel = this._channel; - const protocol = channel._client._protocol; - const outgoing = channel.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelExtData(id, data, STDERR); - else - protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); - - p += sliceLen; - window -= sliceLen; +exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; +class AuthImplicitGrantRedirectError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthImplicitGrantRedirectError', 500, undefined); + this.details = null; + this.details = details; } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - channel._waitWindow = true; - if (p > 0) - channel._chunkErr = bufferSlice(data, p, len); - else - channel._chunkErr = data; - channel._chunkcbErr = cb; - return; + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; } - - cb(); - } } - -class Channel extends DuplexStream { - constructor(client, info, opts) { - const streamOpts = { - highWaterMark: MAX_WINDOW, - allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), - emitClose: false, - }; - super(streamOpts); - this.allowHalfOpen = streamOpts.allowHalfOpen; - - const server = !!(opts && opts.server); - - this.server = server; - this.type = info.type; - this.subtype = undefined; - - /* - incoming and outgoing contain these properties: - { - id: undefined, - window: undefined, - packetSize: undefined, - state: 'closed' - } - */ - this.incoming = info.incoming; - this.outgoing = info.outgoing; - this._callbacks = []; - - this._client = client; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - - this.stdin = this.stdout = this; - - if (server) - this.stderr = new ServerStderr(this); - else - this.stderr = new ClientStderr(this, streamOpts); - - // Outgoing data - this._waitWindow = false; // SSH-level backpressure - - // Incoming data - this._waitChanDrain = false; // Channel Readable side backpressure - - this._chunk = undefined; - this._chunkcb = undefined; - this._chunkErr = undefined; - this._chunkcbErr = undefined; - - this.on('finish', onFinish) - .on('prefinish', onFinish); // For node v0.11+ - - this.on('end', onEnd).on('close', onEnd); - } - - _read(n) { - if (this._waitChanDrain) { - this._waitChanDrain = false; - if (this.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this); - } - } - - _write(data, encoding, cb) { - const protocol = this._client._protocol; - const outgoing = this.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelData(id, data); - else - protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); - - p += sliceLen; - window -= sliceLen; - } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - this._waitWindow = true; - if (p > 0) - this._chunk = bufferSlice(data, p, len); - else - this._chunk = data; - this._chunkcb = cb; - return; - } - - cb(); - } - - eof() { - if (this.outgoing.state === 'open') { - this.outgoing.state = 'eof'; - this._client._protocol.channelEOF(this.outgoing.id); - } - } - - close() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._client._protocol.channelClose(this.outgoing.id); - } - } - - destroy() { - this.end(); - this.close(); - return this; - } - - // Session type-specific methods ============================================= - setWindow(rows, cols, height, width) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && (this.subtype === 'shell' || this.subtype === 'exec') - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.windowChange(this.outgoing.id, - rows, - cols, - height, - width); - } - } - - signal(signalName) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.signal(this.outgoing.id, signalName); +exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; +function isAuthImplicitGrantRedirectError(error) { + return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError'; +} +class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); + this.details = null; + this.details = details; } - } - - exit(statusOrSignal, coreDumped, msg) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - if (typeof statusOrSignal === 'number') { - this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); - } else { - this._client._protocol.exitSignal(this.outgoing.id, - statusOrSignal, - coreDumped, - msg); - } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; } - } - -} - -function onFinish() { - this.eof(); - if (this.server || !this.allowHalfOpen) - this.close(); - this.writable = false; -} - -function onEnd() { - this.readable = false; } - -function windowAdjust(self) { - if (self.outgoing.state === 'closed') - return; - const amt = MAX_WINDOW - self.incoming.window; - if (amt <= 0) - return; - self.incoming.window += amt; - self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); -} - -module.exports = { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -}; - - -/***/ }), - -/***/ 49054: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Socket } = __nccwpck_require__(41808); -const { Duplex } = __nccwpck_require__(12781); -const { resolve } = __nccwpck_require__(71017); -const { readFile } = __nccwpck_require__(57147); -const { execFile, spawn } = __nccwpck_require__(32081); - -const { isParsedKey, parseKey } = __nccwpck_require__(22218); - -const { - makeBufferParser, - readUInt32BE, - writeUInt32BE, - writeUInt32LE, -} = __nccwpck_require__(49475); - -function once(cb) { - let called = false; - return (...args) => { - if (called) - return; - called = true; - cb(...args); - }; +exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; +class AuthRetryableFetchError extends CustomAuthError { + constructor(message, status) { + super(message, 'AuthRetryableFetchError', status, undefined); + } } - -function concat(buf1, buf2) { - const combined = Buffer.allocUnsafe(buf1.length + buf2.length); - buf1.copy(combined, 0); - buf2.copy(combined, buf1.length); - return combined; +exports.AuthRetryableFetchError = AuthRetryableFetchError; +function isAuthRetryableFetchError(error) { + return isAuthError(error) && error.name === 'AuthRetryableFetchError'; } - -function noop() {} - -const EMPTY_BUF = Buffer.alloc(0); - -const binaryParser = makeBufferParser(); - -class BaseAgent { - getIdentities(cb) { - cb(new Error('Missing getIdentities() implementation')); - } - sign(pubKey, data, options, cb) { - if (typeof options === 'function') - cb = options; - cb(new Error('Missing sign() implementation')); - } +/** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ +class AuthWeakPasswordError extends CustomAuthError { + constructor(message, status, reasons) { + super(message, 'AuthWeakPasswordError', status, 'weak_password'); + this.reasons = reasons; + } } - -class OpenSSHAgent extends BaseAgent { - constructor(socketPath) { - super(); - this.socketPath = socketPath; - } - - getStream(cb) { - cb = once(cb); - const sock = new Socket(); - sock.on('connect', () => { - cb(null, sock); - }); - sock.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - sock.connect(this.socketPath); - - function onFail() { - try { - sock.destroy(); - } catch {} - - cb(new Error('Failed to connect to agent')); +exports.AuthWeakPasswordError = AuthWeakPasswordError; +function isAuthWeakPasswordError(error) { + return isAuthError(error) && error.name === 'AuthWeakPasswordError'; +} +class AuthInvalidJwtError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt'); } - } - - getIdentities(cb) { - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to retrieve identities from agent'); - cb(err); - } - - if (err) - return onFail(err); +} +exports.AuthInvalidJwtError = AuthInvalidJwtError; +//# sourceMappingURL=errors.js.map - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); +/***/ }), - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); +/***/ 7072: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - protocol.getIdentities((err, keys) => { - if (err) - return onFail(err); - try { - stream.destroy(); - } catch {} - cb(null, keys); - }); - }); - } +"use strict"; - sign(pubKey, data, options, cb) { - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.handleError = handleError; +exports._request = _request; +exports._sessionResponse = _sessionResponse; +exports._sessionResponsePassword = _sessionResponsePassword; +exports._userResponse = _userResponse; +exports._ssoResponse = _ssoResponse; +exports._generateLinkResponse = _generateLinkResponse; +exports._noResolveJsonResponse = _noResolveJsonResponse; +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(518); +const helpers_1 = __nccwpck_require__(4044); +const errors_1 = __nccwpck_require__(9938); +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const NETWORK_ERROR_CODES = [502, 503, 504]; +async function handleError(error) { + var _a; + if (!(0, helpers_1.looksLikeFetchResponse)(error)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); } - - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to sign data with agent'); - cb(err); - } - - if (err) - return onFail(err); - - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - - protocol.sign(pubKey, data, options, (err, sig) => { - if (err) - return onFail(err); - - try { - stream.destroy(); - } catch {} - - cb(null, sig); - }); - }); - } -} - -const PageantAgent = (() => { - const RET_ERR_BADARGS = 10; - const RET_ERR_UNAVAILABLE = 11; - const RET_ERR_NOMAP = 12; - const RET_ERR_BINSTDIN = 13; - const RET_ERR_BINSTDOUT = 14; - const RET_ERR_BADLEN = 15; - - const EXEPATH = __nccwpck_require__.ab + "pagent.exe"; - const ERROR = { - [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), - [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), - [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), - [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), - [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), - [RET_ERR_BADLEN]: - new Error('pagent.exe did not get expected input payload'), - }; - - function destroy(stream) { - stream.buffer = null; - if (stream.proc) { - stream.proc.kill(); - stream.proc = undefined; + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); } - } - - class PageantSocket extends Duplex { - constructor() { - super(); - this.proc = undefined; - this.buffer = null; - } - _read(n) {} - _write(data, encoding, cb) { - if (this.buffer === null) { - this.buffer = data; - } else { - const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); - this.buffer.copy(newBuffer, 0); - data.copy(newBuffer, this.buffer.length); - this.buffer = newBuffer; - } - // Wait for at least all length bytes - if (this.buffer.length < 4) - return cb(); - - const len = readUInt32BE(this.buffer, 0); - // Make sure we have a full message before querying pageant - if ((this.buffer.length - 4) < len) - return cb(); - - data = this.buffer.slice(0, 4 + len); - if (this.buffer.length > (4 + len)) - return cb(new Error('Unexpected multiple agent requests')); - this.buffer = null; - - let error; - const proc = this.proc = spawn(__nccwpck_require__.ab + "pagent.exe", [ data.length ]); - proc.stdout.on('data', (data) => { - this.push(data); - }); - proc.on('error', (err) => { - error = err; - cb(error); - }); - proc.on('close', (code) => { - this.proc = undefined; - if (!error) { - if (error = ERROR[code]) - return cb(error); - cb(); - } - }); - proc.stdin.end(data); + let data; + try { + data = await error.json(); } - _final(cb) { - destroy(this); - cb(); + catch (e) { + throw new errors_1.AuthUnknownError(_getErrorMessage(e), e); } - _destroy(err, cb) { - destroy(this); - cb(); + let errorCode = undefined; + const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error); + if (responseAPIVersion && + responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp && + typeof data === 'object' && + data && + typeof data.code === 'string') { + errorCode = data.code; } - } - - return class PageantAgent extends OpenSSHAgent { - getStream(cb) { - cb(null, new PageantSocket()); + else if (typeof data === 'object' && data && typeof data.error_code === 'string') { + errorCode = data.error_code; } - }; -})(); - -const CygwinAgent = (() => { - const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; - - return class CygwinAgent extends OpenSSHAgent { - getStream(cb) { - cb = once(cb); - - // The cygwin ssh-agent connection process looks like this: - // 1. Read the "socket" as a file to get the underlying TCP port and a - // special "secret" that must be sent to the TCP server. - // 2. Connect to the server listening on localhost at the TCP port. - // 3. Send the "secret" to the server. - // 4. The server sends back the same "secret". - // 5. Send three 32-bit integer values of zero. This is ordinarily the - // pid, uid, and gid of this process, but cygwin will actually - // send us the correct values as a response. - // 6. The server sends back the pid, uid, gid. - // 7. Disconnect. - // 8. Repeat steps 2-6, except send the received pid, uid, and gid in - // step 5 instead of zeroes. - // 9. Connection is ready to be used. - - let socketPath = this.socketPath; - let triedCygpath = false; - readFile(socketPath, function readCygsocket(err, data) { - if (err) { - if (triedCygpath) - return cb(new Error('Invalid cygwin unix socket path')); - - // Try using `cygpath` to convert a possible *nix-style path to the - // real Windows path before giving up ... - execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { - if (err || stdout.length === 0) - return cb(new Error('Invalid cygwin unix socket path')); - - triedCygpath = true; - socketPath = stdout.toString().replace(/[\r\n]/g, ''); - readFile(socketPath, readCygsocket); - }); - return; - } - - const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); - if (!m) - return cb(new Error('Malformed cygwin unix socket file')); - - let state; - let bc = 0; - let isRetrying = false; - const inBuf = []; - let sock; - - // Use 0 for pid, uid, and gid to ensure we get an error and also - // a valid uid and gid from cygwin so that we don't have to figure it - // out ourselves - let credsBuf = Buffer.alloc(12); - - // Parse cygwin unix socket file contents - const port = parseInt(m[1], 10); - const secret = m[2].replace(/-/g, ''); - const secretBuf = Buffer.allocUnsafe(16); - for (let i = 0, j = 0; j < 32; ++i, j += 2) - secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); - - // Convert to host order (always LE for Windows) - for (let i = 0; i < 16; i += 4) - writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); - - tryConnect(); - - function _onconnect() { - bc = 0; - state = 'secret'; - sock.write(secretBuf); - } - - function _ondata(data) { - bc += data.length; - - if (state === 'secret') { - // The secret we sent is echoed back to us by cygwin, not sure of - // the reason for that, but we ignore it nonetheless ... - if (bc === 16) { - bc = 0; - state = 'creds'; - sock.write(credsBuf); - } - return; - } - - if (state === 'creds') { - // If this is the first attempt, make sure to gather the valid - // uid and gid for our next attempt - if (!isRetrying) - inBuf.push(data); - - if (bc === 12) { - sock.removeListener('connect', _onconnect); - sock.removeListener('data', _ondata); - sock.removeListener('error', onFail); - sock.removeListener('end', onFail); - sock.removeListener('close', onFail); - - if (isRetrying) - return cb(null, sock); - - isRetrying = true; - credsBuf = Buffer.concat(inBuf); - writeUInt32LE(credsBuf, process.pid, 0); - sock.on('error', () => {}); - sock.destroy(); - - tryConnect(); - } - } - } - - function onFail() { - cb(new Error('Problem negotiating cygwin unix socket security')); - } - - function tryConnect() { - sock = new Socket(); - sock.on('connect', _onconnect); - sock.on('data', _ondata); - sock.on('error', onFail); - sock.on('end', onFail); - sock.on('close', onFail); - sock.connect(port); + if (!errorCode) { + // Legacy support for weak password errors, when there were no error codes + if (typeof data === 'object' && + data && + typeof data.weak_password === 'object' && + data.weak_password && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); } - }); } - }; -})(); - -// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes -// being interchangeable -const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; -function createAgent(path) { - if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { - return (path === 'pageant' - ? new PageantAgent() - : new CygwinAgent(path)); - } - return new OpenSSHAgent(path); -} - -const AgentProtocol = (() => { - // Client->Server messages - const SSH_AGENTC_REQUEST_IDENTITIES = 11; - const SSH_AGENTC_SIGN_REQUEST = 13; - // const SSH_AGENTC_ADD_IDENTITY = 17; - // const SSH_AGENTC_REMOVE_IDENTITY = 18; - // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; - // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; - // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; - // const SSH_AGENTC_LOCK = 22; - // const SSH_AGENTC_UNLOCK = 23; - // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; - // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; - // const SSH_AGENTC_EXTENSION = 27; - // Server->Client messages - const SSH_AGENT_FAILURE = 5; - // const SSH_AGENT_SUCCESS = 6; - const SSH_AGENT_IDENTITIES_ANSWER = 12; - const SSH_AGENT_SIGN_RESPONSE = 14; - // const SSH_AGENT_EXTENSION_FAILURE = 28; - - // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; - // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; - // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; - - const SSH_AGENT_RSA_SHA2_256 = (1 << 1); - const SSH_AGENT_RSA_SHA2_512 = (1 << 2); - - const ROLE_CLIENT = 0; - const ROLE_SERVER = 1; - - // Ensures that responses get sent back in the same order the requests were - // received - function processResponses(protocol) { - let ret; - while (protocol[SYM_REQS].length) { - const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; - if (nextResponse === undefined) - break; - - protocol[SYM_REQS].shift(); - ret = protocol.push(nextResponse); + else if (errorCode === 'weak_password') { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); } - return ret; - } - - const SYM_TYPE = Symbol('Inbound Request Type'); - const SYM_RESP = Symbol('Inbound Request Response'); - const SYM_CTX = Symbol('Inbound Request Context'); - class AgentInboundRequest { - constructor(type, ctx) { - this[SYM_TYPE] = type; - this[SYM_RESP] = undefined; - this[SYM_CTX] = ctx; + else if (errorCode === 'session_not_found') { + // The `session_id` inside the JWT does not correspond to a row in the + // `sessions` table. This usually means the user has signed out, has been + // deleted, or their session has somehow been terminated. + throw new errors_1.AuthSessionMissingError(); } - hasResponded() { - return (this[SYM_RESP] !== undefined); + throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); +} +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; } - getType() { - return this[SYM_TYPE]; + params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (!headers[constants_1.API_VERSION_HEADER_NAME]) { + headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name; } - getContext() { - return this[SYM_CTX]; + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}`; } - } - function respond(protocol, req, data) { - req[SYM_RESP] = data; - return processResponses(protocol); - } - - function cleanup(protocol) { - protocol[SYM_BUFFER] = null; - if (protocol[SYM_MODE] === ROLE_CLIENT) { - const reqs = protocol[SYM_REQS]; - if (reqs && reqs.length) { - protocol[SYM_REQS] = []; - for (const req of reqs) - req.cb(new Error('No reply from server')); - } + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs['redirect_to'] = options.redirectTo; } - - // Node streams hackery to make streams do the "right thing" + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; + const data = await _handleRequest(fetcher, method, url + queryString, { + headers, + noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, + }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; +} +async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; try { - protocol.end(); - } catch {} - setImmediate(() => { - if (!protocol[SYM_ENDED]) - protocol.emit('end'); - if (!protocol[SYM_CLOSED]) - protocol.emit('close'); - }); - } - - function onClose() { - this[SYM_CLOSED] = true; - } - - function onEnd() { - this[SYM_ENDED] = true; - } - - const SYM_REQS = Symbol('Requests'); - const SYM_MODE = Symbol('Agent Protocol Role'); - const SYM_BUFFER = Symbol('Agent Protocol Buffer'); - const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); - const SYM_CLOSED = Symbol('Agent Protocol Closed'); - const SYM_ENDED = Symbol('Agent Protocol Ended'); - // Implementation based on: - // https://tools.ietf.org/html/draft-miller-ssh-agent-04 - return class AgentProtocol extends Duplex { - /* - Notes: - - `constraint` type consists of: - byte constraint_type - byte[] constraint_data - where `constraint_type` is one of: - * SSH_AGENT_CONSTRAIN_LIFETIME - - `constraint_data` consists of: - uint32 seconds - * SSH_AGENT_CONSTRAIN_CONFIRM - - `constraint_data` N/A - * SSH_AGENT_CONSTRAIN_EXTENSION - - `constraint_data` consists of: - string extension name - byte[] extension-specific details - */ - - constructor(isClient) { - super({ autoDestroy: true, emitClose: false }); - this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); - this[SYM_REQS] = []; - this[SYM_BUFFER] = null; - this[SYM_MSGLEN] = -1; - this.once('end', onEnd); - this.once('close', onClose); + result = await fetcher(url, Object.assign({}, requestParams)); } - - _read(n) {} - - _write(data, encoding, cb) { - /* - Messages are of the format: - uint32 message length - byte message type - byte[message length - 1] message contents - */ - if (this[SYM_BUFFER] === null) - this[SYM_BUFFER] = data; - else - this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); - - let buffer = this[SYM_BUFFER]; - let bufferLen = buffer.length; - - let p = 0; - while (p < bufferLen) { - // Wait for length + type - if (bufferLen < 5) - break; - - if (this[SYM_MSGLEN] === -1) - this[SYM_MSGLEN] = readUInt32BE(buffer, p); - - // Check if we have the entire message - if (bufferLen < (4 + this[SYM_MSGLEN])) - break; - - const msgType = buffer[p += 4]; - ++p; - - if (this[SYM_MODE] === ROLE_CLIENT) { - if (this[SYM_REQS].length === 0) - return cb(new Error('Received unexpected message from server')); - - const req = this[SYM_REQS].shift(); - - switch (msgType) { - case SSH_AGENT_FAILURE: - req.cb(new Error('Agent responded with failure')); - break; - case SSH_AGENT_IDENTITIES_ANSWER: { - if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - binaryParser.init(buffer, p); - - const numKeys = binaryParser.readUInt32BE(); - - if (numKeys === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const keys = []; - for (let i = 0; i < numKeys; ++i) { - let pubKey = binaryParser.readString(); - if (pubKey === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const comment = binaryParser.readString(true); - if (comment === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - pubKey = parseKey(pubKey); - // We continue parsing the packet if we encounter an error - // in case the error is due to the key being an unsupported - // type - if (pubKey instanceof Error) - continue; - - pubKey.comment = pubKey.comment || comment; - - keys.push(pubKey); - } - p = binaryParser.pos(); - binaryParser.clear(); - - req.cb(null, keys); - break; - } - case SSH_AGENT_SIGN_RESPONSE: { - if (req.type !== SSH_AGENTC_SIGN_REQUEST) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - binaryParser.init(buffer, p); - let signature = binaryParser.readString(); - p = binaryParser.pos(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed agent response')); - - // We strip the algorithm from OpenSSH's output and assume it's - // using the algorithm we specified. This makes it easier on - // custom Agent implementations so they don't have to construct - // the correct binary format for a (OpenSSH-style) signature. - - // TODO: verify signature type based on key and options used - // during initial sign request - binaryParser.init(signature, 0); - binaryParser.readString(true); - signature = binaryParser.readString(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed OpenSSH signature format')); - - req.cb(null, signature); - break; - } - default: - return cb( - new Error('Agent responded with unsupported message type') - ); - } - } else { - switch (msgType) { - case SSH_AGENTC_REQUEST_IDENTITIES: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - this.emit('identities', req); - break; - } - case SSH_AGENTC_SIGN_REQUEST: { - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - binaryParser.init(buffer, p); - let pubKey = binaryParser.readString(); - const data = binaryParser.readString(); - const flagsVal = binaryParser.readUInt32BE(); - p = binaryParser.pos(); - binaryParser.clear(); - if (flagsVal === undefined) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - const flags = { - hash: undefined, - }; - let ctx; - if (pubKey.type === 'ssh-rsa') { - if (flagsVal & SSH_AGENT_RSA_SHA2_256) { - ctx = 'rsa-sha2-256'; - flags.hash = 'sha256'; - } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { - ctx = 'rsa-sha2-512'; - flags.hash = 'sha512'; - } - } - if (ctx === undefined) - ctx = pubKey.type; - - const req = new AgentInboundRequest(msgType, ctx); - this[SYM_REQS].push(req); - - this.emit('sign', req, pubKey, data, flags); - break; - } - default: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.failureReply(req); - } - } - } - - // Get ready for next message - this[SYM_MSGLEN] = -1; - if (p === bufferLen) { - // Nothing left to process for now - this[SYM_BUFFER] = null; - break; - } else { - this[SYM_BUFFER] = buffer = buffer.slice(p); - bufferLen = buffer.length; - p = 0; - } - } - - cb(); + catch (e) { + console.error(e); + // fetch failed, likely due to a network or CORS error + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0); } - - _destroy(err, cb) { - cleanup(this); - cb(); + if (!result.ok) { + await handleError(result); } - - _final(cb) { - cleanup(this); - cb(); + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; } - - // Client->Server messages ================================================= - sign(pubKey, data, options, cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } - - let flags = 0; - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid public key argument'); - - if (pubKey.type === 'ssh-rsa' && options) { - switch (options.hash) { - case 'sha256': - flags = SSH_AGENT_RSA_SHA2_256; - break; - case 'sha512': - flags = SSH_AGENT_RSA_SHA2_512; - break; + try { + return await result.json(); + } + catch (e) { + await handleError(e); + } +} +function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + if (!data.expires_at) { + session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); } - } - pubKey = pubKey.getPublicSSH(); - - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - const type = SSH_AGENTC_SIGN_REQUEST; - const keyLen = pubKey.length; - const dataLen = data.length; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - writeUInt32BE(buf, keyLen, ++p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, dataLen, p += keyLen); - data.copy(buf, p += 4); - - writeUInt32BE(buf, flags, p += dataLen); - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); } - getIdentities(cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - const type = SSH_AGENTC_REQUEST_IDENTITIES; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; +} +function _sessionResponsePassword(data) { + const response = _sessionResponse(data); + if (!response.error && + data.weak_password && + typeof data.weak_password === 'object' && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.message && + typeof data.weak_password.message === 'string' && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + response.data.weak_password = data.weak_password; } + return response; +} +function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; +} +function _ssoResponse(data) { + return { data, error: null }; +} +function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user, + }, + error: null, + }; +} +function _noResolveJsonResponse(data) { + return data; +} +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; +} +//# sourceMappingURL=fetch.js.map - // Server->Client messages ================================================= - failureReply(req) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); +/***/ }), - writeUInt32BE(buf, buf.length - 4, p); +/***/ 4044: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - buf[p += 4] = SSH_AGENT_FAILURE; +"use strict"; - return respond(this, req, buf); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0; +exports.expiresAt = expiresAt; +exports.uuid = uuid; +exports.parseParametersFromURL = parseParametersFromURL; +exports.decodeJWT = decodeJWT; +exports.sleep = sleep; +exports.retryable = retryable; +exports.generatePKCEVerifier = generatePKCEVerifier; +exports.generatePKCEChallenge = generatePKCEChallenge; +exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod; +exports.parseResponseAPIVersion = parseResponseAPIVersion; +exports.validateExp = validateExp; +exports.getAlgorithm = getAlgorithm; +exports.validateUUID = validateUUID; +exports.userNotAvailableProxy = userNotAvailableProxy; +exports.insecureUserWarningProxy = insecureUserWarningProxy; +exports.deepClone = deepClone; +const constants_1 = __nccwpck_require__(518); +const errors_1 = __nccwpck_require__(9938); +const base64url_1 = __nccwpck_require__(3649); +function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1000); + return timeNow + expiresIn; +} +function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'; +exports.isBrowser = isBrowser; +const localStorageWriteTests = { + tested: false, + writable: false, +}; +/** + * Checks whether localStorage is supported on this browser. + */ +const supportsLocalStorage = () => { + if (!(0, exports.isBrowser)()) { + return false; } - getIdentitiesReply(req, keys) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) - throw new Error('Invalid response to request'); - - if (!Array.isArray(keys)) - throw new Error('Keys argument must be an array'); - - let totalKeysLen = 4; // Include `nkeys` size - - const newKeys = []; - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - if (typeof entry !== 'object' || entry === null) - throw new Error(`Invalid key entry: ${entry}`); - - let pubKey; - let comment; - if (isParsedKey(entry)) { - pubKey = entry; - } else if (isParsedKey(entry.pubKey)) { - pubKey = entry.pubKey; - } else { - if (typeof entry.pubKey !== 'object' || entry.pubKey === null) - continue; - ({ pubKey, comment } = entry.pubKey); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; // TODO: add debug output - } - comment = pubKey.comment || comment; - pubKey = pubKey.getPublicSSH(); - - totalKeysLen += 4 + pubKey.length; - - if (comment && typeof comment === 'string') - comment = Buffer.from(comment); - else if (!Buffer.isBuffer(comment)) - comment = EMPTY_BUF; - - totalKeysLen += 4 + comment.length; - - newKeys.push({ pubKey, comment }); - } - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; - - writeUInt32BE(buf, newKeys.length, ++p); - p += 4; - for (let i = 0; i < newKeys.length; ++i) { - const { pubKey, comment } = newKeys[i]; - - writeUInt32BE(buf, pubKey.length, p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, comment.length, p += pubKey.length); - p += 4; - if (comment.length) { - comment.copy(buf, p); - p += comment.length; + try { + if (typeof globalThis.localStorage !== 'object') { + return false; } - } - - return respond(this, req, buf); } - signReply(req, signature) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) - throw new Error('Invalid response to request'); - - if (!Buffer.isBuffer(signature)) - throw new Error('Signature argument must be a Buffer'); - - if (signature.length === 0) - throw new Error('Signature argument must be non-empty'); - - /* - OpenSSH agent signatures are encoded as: - - string signature format identifier (as specified by the - public key/certificate format) - byte[n] signature blob in format specific encoding. - - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 - types - */ - - let p = 0; - const sigFormat = req.getContext(); - const sigFormatLen = Buffer.byteLength(sigFormat); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length - ); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; - - writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); - writeUInt32BE(buf, sigFormatLen, p += 4); - buf.utf8Write(sigFormat, p += 4, sigFormatLen); - writeUInt32BE(buf, signature.length, p += sigFormatLen); - signature.copy(buf, p += 4); - - return respond(this, req, buf); + catch (e) { + // DOM exception when accessing `localStorage` + return false; } - }; -})(); - -const SYM_AGENT = Symbol('Agent'); -const SYM_AGENT_KEYS = Symbol('Agent Keys'); -const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); -const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); -class AgentContext { - constructor(agent) { - if (typeof agent === 'string') - agent = createAgent(agent); - else if (!isAgent(agent)) - throw new Error('Invalid agent argument'); - this[SYM_AGENT] = agent; - this[SYM_AGENT_KEYS] = null; - this[SYM_AGENT_KEYS_IDX] = -1; - this[SYM_AGENT_CBS] = null; - } - init(cb) { - if (typeof cb !== 'function') - cb = noop; - - if (this[SYM_AGENT_KEYS] === null) { - if (this[SYM_AGENT_CBS] === null) { - this[SYM_AGENT_CBS] = [cb]; - - const doCbs = (...args) => { - process.nextTick(() => { - const cbs = this[SYM_AGENT_CBS]; - this[SYM_AGENT_CBS] = null; - for (const cb of cbs) - cb(...args); - }); - }; - - this[SYM_AGENT].getIdentities(once((err, keys) => { - if (err) - return doCbs(err); - - if (!Array.isArray(keys)) { - return doCbs(new Error( - 'Agent implementation failed to provide keys' - )); - } - - const newKeys = []; - for (let key of keys) { - key = parseKey(key); - if (key instanceof Error) { - // TODO: add debug output - continue; - } - newKeys.push(key); - } - - this[SYM_AGENT_KEYS] = newKeys; - this[SYM_AGENT_KEYS_IDX] = -1; - doCbs(); - })); - } else { - this[SYM_AGENT_CBS].push(cb); - } - } else { - process.nextTick(cb); + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; } - } - nextKey() { - if (this[SYM_AGENT_KEYS] === null - || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return false; + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - currentKey() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return null; + catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - pos() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return -1; + return localStorageWriteTests.writable; +}; +exports.supportsLocalStorage = supportsLocalStorage; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } + catch (e) { + // hash is not a query string + } } - - return this[SYM_AGENT_KEYS_IDX]; - } - reset() { - this[SYM_AGENT_KEYS_IDX] = -1; - } - - sign(...args) { - this[SYM_AGENT].sign(...args); - } -} - -function isAgent(val) { - return (val instanceof BaseAgent); + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; } - -module.exports = { - AgentContext, - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - isAgent, - OpenSSHAgent, - PageantAgent, +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); }; - - -/***/ }), - -/***/ 36063: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// TODO: -// * add `.connected` or similar property to allow immediate connection -// status checking -// * add/improve debug output during user authentication phase - - -const { - createHash, - getHashes, - randomFillSync, -} = __nccwpck_require__(6113); -const { Socket } = __nccwpck_require__(41808); -const { lookup: dnsLookup } = __nccwpck_require__(9523); -const EventEmitter = __nccwpck_require__(82361); -const HASHES = getHashes(); - -const { - COMPAT, - CHANNEL_EXTENDED_DATATYPE: { STDERR }, - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(36832); -const { init: cryptoInit } = __nccwpck_require__(45708); -const Protocol = __nccwpck_require__(59031); -const { parseKey } = __nccwpck_require__(22218); -const { SFTP } = __nccwpck_require__(52026); -const { - bufferCopy, - makeBufferParser, - makeError, - readUInt32BE, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const { AgentContext, createAgent, isAgent } = __nccwpck_require__(49054); -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(83204); -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(40834); - -const bufferParser = makeBufferParser(); -const sigParser = makeBufferParser(); -const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; -const noop = (err) => {}; - -class Client extends EventEmitter { - constructor() { - super(); - - this.config = { - host: undefined, - port: undefined, - localAddress: undefined, - localPort: undefined, - forceIPv4: undefined, - forceIPv6: undefined, - keepaliveCountMax: undefined, - keepaliveInterval: undefined, - readyTimeout: undefined, - ident: undefined, - - username: undefined, - password: undefined, - privateKey: undefined, - tryKeyboard: undefined, - agent: undefined, - allowAgentFwd: undefined, - authHandler: undefined, - - hostHashAlgo: undefined, - hostHashCb: undefined, - strictVendor: undefined, - debug: undefined - }; - - this._agent = undefined; - this._readyTimeout = undefined; - this._chanMgr = undefined; - this._callbacks = undefined; - this._forwarding = undefined; - this._forwardingUnix = undefined; - this._acceptX11 = undefined; - this._agentFwdEnabled = undefined; - this._remoteVer = undefined; - - this._protocol = undefined; - this._sock = undefined; - this._resetKA = undefined; - } - - connect(cfg) { - if (this._sock && isWritable(this._sock)) { - this.once('close', () => { - this.connect(cfg); - }); - this.end(); - return this; +exports.resolveFetch = resolveFetch; +const looksLikeFetchResponse = (maybeResponse) => { + return (typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof maybeResponse.json === 'function'); +}; +exports.looksLikeFetchResponse = looksLikeFetchResponse; +// Storage helpers +const setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); +}; +exports.setItemAsync = setItemAsync; +const getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; } - - this.config.host = cfg.hostname || cfg.host || 'localhost'; - this.config.port = cfg.port || 22; - this.config.localAddress = (typeof cfg.localAddress === 'string' - ? cfg.localAddress - : undefined); - this.config.localPort = (typeof cfg.localPort === 'string' - || typeof cfg.localPort === 'number' - ? cfg.localPort - : undefined); - this.config.forceIPv4 = cfg.forceIPv4 || false; - this.config.forceIPv6 = cfg.forceIPv6 || false; - this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' - && cfg.keepaliveCountMax >= 0 - ? cfg.keepaliveCountMax - : 3); - this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' - && cfg.keepaliveInterval > 0 - ? cfg.keepaliveInterval - : 0); - this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' - && cfg.readyTimeout >= 0 - ? cfg.readyTimeout - : 20000); - this.config.ident = (typeof cfg.ident === 'string' - || Buffer.isBuffer(cfg.ident) - ? cfg.ident - : undefined); - - const algorithms = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: [], - }, - sc: undefined, - }; - let allOfferDefaults = true; - if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { - algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, - DEFAULT_KEX, - SUPPORTED_KEX); - if (algorithms.kex !== DEFAULT_KEX) - allOfferDefaults = false; - - algorithms.serverHostKey = - generateAlgorithmList(cfg.algorithms.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY); - if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) - allOfferDefaults = false; - - algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER); - if (algorithms.cs.cipher !== DEFAULT_CIPHER) - allOfferDefaults = false; - - algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, - DEFAULT_MAC, - SUPPORTED_MAC); - if (algorithms.cs.mac !== DEFAULT_MAC) - allOfferDefaults = false; - - algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION); - if (algorithms.cs.compress !== DEFAULT_COMPRESSION) - allOfferDefaults = false; - - if (!allOfferDefaults) - algorithms.sc = algorithms.cs; - } - - if (typeof cfg.username === 'string') - this.config.username = cfg.username; - else if (typeof cfg.user === 'string') - this.config.username = cfg.user; - else - throw new Error('Invalid username'); - - this.config.password = (typeof cfg.password === 'string' - ? cfg.password - : undefined); - this.config.privateKey = (typeof cfg.privateKey === 'string' - || Buffer.isBuffer(cfg.privateKey) - ? cfg.privateKey - : undefined); - this.config.localHostname = (typeof cfg.localHostname === 'string' - ? cfg.localHostname - : undefined); - this.config.localUsername = (typeof cfg.localUsername === 'string' - ? cfg.localUsername - : undefined); - this.config.tryKeyboard = (cfg.tryKeyboard === true); - if (typeof cfg.agent === 'string' && cfg.agent.length) - this.config.agent = createAgent(cfg.agent); - else if (isAgent(cfg.agent)) - this.config.agent = cfg.agent; - else - this.config.agent = undefined; - this.config.allowAgentFwd = (cfg.agentForward === true - && this.config.agent !== undefined); - let authHandler = this.config.authHandler = ( - typeof cfg.authHandler === 'function' - || Array.isArray(cfg.authHandler) - ? cfg.authHandler - : undefined - ); - - this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' - ? cfg.strictVendor - : true); - - const debug = this.config.debug = (typeof cfg.debug === 'function' - ? cfg.debug - : undefined); - - if (cfg.agentForward === true && !this.config.allowAgentFwd) { - throw new Error( - 'You must set a valid agent path to allow agent forwarding' - ); + try { + return JSON.parse(value); } - - let callbacks = this._callbacks = []; - this._chanMgr = new ChannelManager(this); - this._forwarding = {}; - this._forwardingUnix = {}; - this._acceptX11 = 0; - this._agentFwdEnabled = false; - this._agent = (this.config.agent ? this.config.agent : undefined); - this._remoteVer = undefined; - let privateKey; - - if (this.config.privateKey) { - privateKey = parseKey(this.config.privateKey, cfg.passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) { - throw new Error( - 'privateKey value does not contain a (valid) private key' - ); - } + catch (_a) { + return value; } - - let hostVerifier; - if (typeof cfg.hostVerifier === 'function') { - const hashCb = cfg.hostVerifier; - let hashAlgo; - if (HASHES.indexOf(cfg.hostHash) !== -1) { - // Default to old behavior of hashing on user's behalf - hashAlgo = cfg.hostHash; - } - hostVerifier = (key, verify) => { - if (hashAlgo) - key = createHash(hashAlgo).update(key).digest('hex'); - const ret = hashCb(key, verify); - if (ret !== undefined) - verify(ret); - }; +}; +exports.getItemAsync = getItemAsync; +const removeItemAsync = async (storage, key) => { + await storage.removeItem(key); +}; +exports.removeItemAsync = removeItemAsync; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +class Deferred { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.resolve = res; + this.reject = rej; + }); } - - const sock = this._sock = (cfg.sock || new Socket()); - let ready = false; - let sawHeader = false; - if (this._protocol) - this._protocol.cleanup(); - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from server: ${JSON.stringify(msg)}`); - }); - let serverSigAlgs; - const proto = this._protocol = new Protocol({ - ident: this.config.ident, - offer: (allOfferDefaults ? undefined : algorithms), - onWrite: (data) => { - if (isWritable(sock)) - sock.write(data); - }, - onError: (err) => { - if (err.level === 'handshake') - clearTimeout(this._readyTimeout); - if (!proto._destruct) - sock.removeAllListeners('data'); - this.emit('error', err); - try { - sock.end(); - } catch {} - }, - onHeader: (header) => { - sawHeader = true; - this._remoteVer = header.versions.software; - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - this.emit('handshake', negotiated); - if (!ready) { - ready = true; - proto.service('ssh-userauth'); +} +exports.Deferred = Deferred; +Deferred.promiseConstructor = Promise; +function decodeJWT(token) { + const parts = token.split('.'); + if (parts.length !== 3) { + throw new errors_1.AuthInvalidJwtError('Invalid JWT structure'); + } + // Regex checks for base64url format + for (let i = 0; i < parts.length; i++) { + if (!constants_1.BASE64URL_REGEX.test(parts[i])) { + throw new errors_1.AuthInvalidJwtError('JWT not in base64url format'); } - }, - debug, - hostVerifier, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - sock.end(); - }, - SERVICE_ACCEPT: (p, name) => { - if (name === 'ssh-userauth') - tryNextAuth(); - }, - EXT_INFO: (p, exts) => { - if (serverSigAlgs === undefined) { - for (const ext of exts) { - if (ext.name === 'server-sig-algs') { - serverSigAlgs = ext.algs; - return; - } - } - serverSigAlgs = null; - } - }, - USERAUTH_BANNER: (p, msg) => { - this.emit('banner', msg); - }, - USERAUTH_SUCCESS: (p) => { - // Start keepalive mechanism - resetKA(); - - clearTimeout(this._readyTimeout); - - this.emit('ready'); + } + const data = { + // using base64url lib + header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])), + payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])), + signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]), + raw: { + header: parts[0], + payload: parts[1], }, - USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { - // For key-based authentication, check if we should retry the current - // key with a different algorithm first - if (curAuth.keyAlgos) { - const oldKeyAlgo = curAuth.keyAlgos[0][0]; - if (debug) - debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); - curAuth.keyAlgos.shift(); - if (curAuth.keyAlgos.length) { - const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - switch (curAuth.type) { - case 'agent': - proto.authPK( - curAuth.username, - curAuth.agentCtx.currentKey(), - keyAlgo - ); - return; - case 'publickey': - proto.authPK(curAuth.username, curAuth.key, keyAlgo); - return; - case 'hostbased': - proto.authHostbased(curAuth.username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - keyAlgo, - (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); + }; + return data; +} +/** + * Creates a promise that resolves to null after some time. + */ +async function sleep(time) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time); + }); +} +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } + catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; } - - cb(signature); - }); - return; - } - } else { - curAuth.keyAlgos = undefined; - } - } - - if (curAuth.type === 'agent') { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Client: Agent key #${pos + 1} failed`); - return tryNextAgentKey(); - } - - debug && debug(`Client: ${curAuth.type} auth failed`); - - curPartial = partialSuccess; - curAuthsLeft = authMethods; - tryNextAuth(); - }, - USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { - if (curAuth.type === 'password') { - // TODO: support a `changePrompt()` on `curAuth` that defaults to - // emitting 'change password' as before - this.emit('change password', prompt, (newPassword) => { - proto.authPassword( - this.config.username, - this.config.password, - newPassword - ); - }); - } - }, - USERAUTH_PK_OK: (p) => { - let keyAlgo; - let hashAlgo; - if (curAuth.keyAlgos) - [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.currentKey(); - proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { - const opts = { hash: hashAlgo }; - curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - } else { - return cb(signed); } - - tryNextAgentKey(); - }); - }); - } else if (curAuth.type === 'publickey') { - proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = - `Error signing data with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - cb(signature); - }); - } - }, - USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { - if (curAuth.type === 'keyboard-interactive') { - const nprompts = (Array.isArray(prompts) ? prompts.length : 0); - if (nprompts === 0) { - debug && debug( - 'Client: Sending automatic USERAUTH_INFO_RESPONSE' - ); - proto.authInfoRes(); - return; - } - // We sent a keyboard-interactive user authentication request and - // now the server is sending us the prompts we need to present to - // the user - curAuth.prompt( - name, - instructions, - '', - prompts, - (answers) => { - proto.authInfoRes(answers); - } - ); - } - }, - REQUEST_SUCCESS: (p, data) => { - if (callbacks.length) - callbacks.shift()(false, data); - }, - REQUEST_FAILURE: (p) => { - if (callbacks.length) - callbacks.shift()(true); - }, - GLOBAL_REQUEST: (p, name, wantReply, data) => { - switch (name) { - case 'hostkeys-00@openssh.com': - // Automatically verify keys before passing to end user - hostKeysProve(this, data, (err, keys) => { - if (err) - return; - this.emit('hostkeys', keys); - }); - if (wantReply) - proto.requestSuccess(); - break; - default: - // Auto-reject all other global requests, this can be especially - // useful if the server is sending us dummy keepalive global - // requests - if (wantReply) - proto.requestFailure(); - } - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from server, typically a forwarded TCP or - // X11 connection - onCHANNEL_OPEN(this, info); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const isSFTP = (channel.type === 'sftp'); - const type = (isSFTP ? 'session' : channel.type); - const chanInfo = { - type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const instance = ( - isSFTP - ? new SFTP(this, chanInfo, { debug }) - : new Channel(this, chanInfo) - ); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - if (type !== STDERR) - return; - - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (!channel.stderr.push(data)) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - const exit = channel._exit; - if (exit.code !== undefined) - return; - switch (type) { - case 'exit-status': - channel.emit('exit', exit.code = data); - return; - case 'exit-signal': - channel.emit('exit', - exit.code = null, - exit.signal = `SIG${data.signal}`, - exit.dump = data.coreDumped, - exit.desc = data.errorMessage); - return; - } - - // Keepalive request? OpenSSH will send one as a channel request if - // there is a channel open - - if (wantReply) - p.channelFailure(channel.outgoing.id); - }, - CHANNEL_EOF: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - if (channel.stderr.readable) - channel.stderr.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); - }, - }, + })(); }); - - sock.pause(); - - // TODO: check keepalive implementation - // Keepalive-related - const kainterval = this.config.keepaliveInterval; - const kacountmax = this.config.keepaliveCountMax; - let kacount = 0; - let katimer; - const sendKA = () => { - if (++kacount > kacountmax) { - clearInterval(katimer); - if (sock.readable) { - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); + return promise; +} +function dec2hex(dec) { + return ('0' + dec.toString(16)).substr(-2); +} +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; + const charSetLen = charSet.length; + let verifier = ''; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); } - return; - } - if (isWritable(sock)) { - // Append dummy callback to keep correct callback order - callbacks.push(resetKA); - proto.ping(); - } else { - clearInterval(katimer); - } - }; - function resetKA() { - if (kainterval > 0) { - kacount = 0; - clearInterval(katimer); - if (isWritable(sock)) - katimer = setInterval(sendKA, kainterval); - } + return verifier; } - this._resetKA = resetKA; - - const onDone = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (wasConnected && !sawHeader) { - const err = - makeError('Connection lost before handshake', 'protocol', true); - this.emit('error', err); - } - }; - })(); - const onConnect = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - - wasConnected = true; - debug && debug('Socket connected'); - this.emit('connect'); - - cryptoInit.then(() => { - proto.start(); - sock.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - } - }); - - // Drain stderr if we are connection hopping using an exec stream - if (sock.stderr && typeof sock.stderr.resume === 'function') - sock.stderr.resume(); - - sock.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - }); - }; - })(); - let wasConnected = false; - sock.on('connect', onConnect) - .on('timeout', () => { - this.emit('timeout'); - }).on('error', (err) => { - debug && debug(`Socket error: ${err.message}`); - clearTimeout(this._readyTimeout); - err.level = 'client-socket'; - this.emit('error', err); - }).on('end', () => { - debug && debug('Socket ended'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('end'); - }).on('close', () => { - debug && debug('Socket closed'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('close'); - - // Notify outstanding channel requests of disconnection ... - const callbacks_ = callbacks; - callbacks = this._callbacks = []; - const err = new Error('No response from server'); - for (let i = 0; i < callbacks_.length; ++i) - callbacks_[i](err); - - // Simulate error for any channels waiting to be opened - this._chanMgr.cleanup(err); - }); - - // Begin authentication handling =========================================== - let curAuth; - let curPartial = null; - let curAuthsLeft = null; - const authsAllowed = ['none']; - if (this.config.password !== undefined) - authsAllowed.push('password'); - if (privateKey !== undefined) - authsAllowed.push('publickey'); - if (this._agent !== undefined) - authsAllowed.push('agent'); - if (this.config.tryKeyboard) - authsAllowed.push('keyboard-interactive'); - if (privateKey !== undefined - && this.config.localHostname !== undefined - && this.config.localUsername !== undefined) { - authsAllowed.push('hostbased'); - } - - if (Array.isArray(authHandler)) - authHandler = makeSimpleAuthHandler(authHandler); - else if (typeof authHandler !== 'function') - authHandler = makeSimpleAuthHandler(authsAllowed); - - let hasSentAuth = false; - const doNextAuth = (nextAuth) => { - if (hasSentAuth) - return; - hasSentAuth = true; - - if (nextAuth === false) { - const err = new Error('All configured authentication methods failed'); - err.level = 'client-authentication'; - this.emit('error', err); - this.end(); - return; - } - - if (typeof nextAuth === 'string') { - // Remain backwards compatible with original `authHandler()` usage, - // which only supported passing names of next method to try using data - // from the `connect()` config object - - const type = nextAuth; - if (authsAllowed.indexOf(type) === -1) - return skipAuth(`Authentication method not allowed: ${type}`); - - const username = this.config.username; - switch (type) { - case 'password': - nextAuth = { type, username, password: this.config.password }; - break; - case 'publickey': - nextAuth = { type, username, key: privateKey }; - break; - case 'hostbased': - nextAuth = { - type, - username, - key: privateKey, - localHostname: this.config.localHostname, - localUsername: this.config.localUsername, - }; - break; - case 'agent': - nextAuth = { - type, - username, - agentCtx: new AgentContext(this._agent), - }; - break; - case 'keyboard-interactive': - nextAuth = { - type, - username, - prompt: (...args) => this.emit('keyboard-interactive', ...args), - }; - break; - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } else if (typeof nextAuth !== 'object' || nextAuth === null) { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } else { - const username = nextAuth.username; - if (typeof username !== 'string') { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } - const type = nextAuth.type; - switch (type) { - case 'password': { - const { password } = nextAuth; - if (typeof password !== 'string' && !Buffer.isBuffer(password)) - return skipAuth('Skipping invalid password auth attempt'); - nextAuth = { type, username, password }; - break; - } - case 'publickey': { - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error) - return skipAuth('Skipping invalid key auth attempt'); - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key }; - break; - } - case 'hostbased': { - const { localHostname, localUsername } = nextAuth; - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error - || typeof localHostname !== 'string' - || typeof localUsername !== 'string') { - return skipAuth('Skipping invalid hostbased auth attempt'); - } - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key, localHostname, localUsername }; - break; - } - case 'agent': { - let agent = nextAuth.agent; - if (typeof agent === 'string' && agent.length) { - agent = createAgent(agent); - } else if (!isAgent(agent)) { - return skipAuth( - `Skipping invalid agent: ${nextAuth.agent}` - ); - } - nextAuth = { type, username, agentCtx: new AgentContext(agent) }; - break; - } - case 'keyboard-interactive': { - const { prompt } = nextAuth; - if (typeof prompt !== 'function') { - return skipAuth( - 'Skipping invalid keyboard-interactive auth attempt' - ); - } - nextAuth = { type, username, prompt }; - break; - } - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } - curAuth = nextAuth; - - // Begin authentication method's process - try { - const username = curAuth.username; - switch (curAuth.type) { - case 'password': - proto.authPassword(username, curAuth.password); - break; - case 'publickey': { - let keyAlgo; - curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - keyAlgo = curAuth.keyAlgos[0][0]; - } else { - return skipAuth( - 'Skipping key authentication (no mutual hash algorithm)' - ); - } - } - proto.authPK(username, curAuth.key, keyAlgo); - break; - } - case 'hostbased': { - let keyAlgo; - let hashAlgo; - curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - } else { - return skipAuth( - 'Skipping hostbased authentication (no mutual hash algorithm)' - ); - } - } - - proto.authHostbased(username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - keyAlgo, - (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - - cb(signature); - }); - break; - } - case 'agent': - curAuth.agentCtx.init((err) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - return tryNextAuth(); - } - tryNextAgentKey(); - }); - break; - case 'keyboard-interactive': - proto.authKeyboard(username); - break; - case 'none': - proto.authNone(username); - break; - } - } finally { - hasSentAuth = false; - } - }; - - function skipAuth(msg) { - debug && debug(msg); - process.nextTick(tryNextAuth); + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(''); +} +async function sha256(randomString) { + const encoder = new TextEncoder(); + const encodedData = encoder.encode(randomString); + const hash = await crypto.subtle.digest('SHA-256', encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join(''); +} +async function generatePKCEChallenge(verifier) { + const hasCryptoSupport = typeof crypto !== 'undefined' && + typeof crypto.subtle !== 'undefined' && + typeof TextEncoder !== 'undefined'; + if (!hasCryptoSupport) { + console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); + return verifier; } - - function tryNextAuth() { - hasSentAuth = false; - const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); - if (hasSentAuth || auth === undefined) - return; - doNextAuth(auth); + const hashed = await sha256(verifier); + return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { + const codeVerifier = generatePKCEVerifier(); + let storedCodeVerifier = codeVerifier; + if (isPasswordRecovery) { + storedCodeVerifier += '/PASSWORD_RECOVERY'; } - - const tryNextAgentKey = () => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.nextKey(); - if (key === false) { - debug && debug('Agent: No more keys left to try'); - debug && debug('Client: agent auth failed'); - tryNextAuth(); - } else { - const pos = curAuth.agentCtx.pos(); - let keyAlgo; - curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - keyAlgo = curAuth.keyAlgos[0][0]; - } else { - debug && debug( - `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` - ); - tryNextAgentKey(); - return; - } - } - debug && debug(`Agent: Trying key #${pos + 1}`); - proto.authPK(curAuth.username, key, keyAlgo); - } - } - }; - - const startTimeout = () => { - if (this.config.readyTimeout > 0) { - this._readyTimeout = setTimeout(() => { - const err = new Error('Timed out while waiting for handshake'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - }, this.config.readyTimeout); - } - }; - - if (!cfg.sock) { - let host = this.config.host; - const forceIPv4 = this.config.forceIPv4; - const forceIPv6 = this.config.forceIPv6; - - debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); - - const doConnect = () => { - startTimeout(); - sock.connect({ - host, - port: this.config.port, - localAddress: this.config.localAddress, - localPort: this.config.localPort - }); - sock.setMaxListeners(0); - sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); - }; - - if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { - doConnect(); - } else { - dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { - if (err) { - const type = (forceIPv4 ? 'IPv4' : 'IPv6'); - const error = new Error( - `Error while looking up ${type} address for '${host}': ${err}` - ); - clearTimeout(this._readyTimeout); - error.level = 'client-dns'; - this.emit('error', error); - this.emit('close'); - return; - } - host = address; - doConnect(); - }); - } - } else { - // Custom socket passed in - startTimeout(); - if (typeof sock.connecting === 'boolean') { - // net.Socket - - if (!sock.connecting) { - // Already connected - onConnect(); - } - } else { - // Assume socket/stream is already "connected" - onConnect(); - } + await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + return [codeChallenge, codeChallengeMethod]; +} +/** Parses the API version which is 2YYY-MM-DD. */ +const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; +function parseResponseAPIVersion(response) { + const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME); + if (!apiVersion) { + return null; } - - return this; - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); + if (!apiVersion.match(API_VERSION_REGEX)) { + return null; } - return this; - } - - destroy() { - this._sock && isWritable(this._sock) && this._sock.destroy(); - return this; - } - - exec(cmd, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; + try { + const date = new Date(`${apiVersion}T00:00:00.0Z`); + return date; } - - const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; - - openChannel(this, 'session', extraOpts, (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.pty === 'object' && opts.pty !== null) - || opts.pty === true) { - todo.push(() => reqPty(chan, opts.pty, reqCb)); - } - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqExec(chan, cmd, opts, cb)); - todo.shift()(); - }); - - return this; - } - - shell(wndopts, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof wndopts === 'function') { - cb = wndopts; - wndopts = opts = undefined; - } else if (typeof opts === 'function') { - cb = opts; - opts = undefined; + catch (e) { + return null; + } +} +function validateExp(exp) { + if (!exp) { + throw new Error('Missing exp claim'); } - if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { - opts = wndopts; - wndopts = undefined; + const timeNow = Math.floor(Date.now() / 1000); + if (exp <= timeNow) { + throw new Error('JWT has expired'); } - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (wndopts !== false) - todo.push(() => reqPty(chan, wndopts, reqCb)); - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqShell(chan, cb)); - todo.shift()(); - }); - - return this; - } - - subsys(name, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(chan, name, (err, stream) => { - if (err) { - cb(err); - return; - } - - cb(undefined, stream); - }); - }); - - return this; - } - - forwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request for the server to start forwarding TCP connections to us - // on a particular address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); - return; - } - - let realPort = bindPort; - if (bindPort === 0 && data && data.length >= 4) { - realPort = readUInt32BE(data, 0); - if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) - bindPort = realPort; - } - - this._forwarding[`${bindAddr}:${bindPort}`] = realPort; - - cb(undefined, realPort); - }); +} +function getAlgorithm(alg) { + switch (alg) { + case 'RS256': + return { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + case 'ES256': + return { + name: 'ECDSA', + namedCurve: 'P-256', + hash: { name: 'SHA-256' }, + }; + default: + throw new Error('Invalid alg claim'); } - - this._protocol.tcpipForward(bindAddr, bindPort, wantReply); - - return this; - } - - unforwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request to stop forwarding us new connections for a particular - // address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); - return; - } - - delete this._forwarding[`${bindAddr}:${bindPort}`]; - - cb(); - }); +} +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +function validateUUID(str) { + if (!UUID_REGEX.test(str)) { + throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not'); } +} +function userNotAvailableProxy() { + const proxyTarget = {}; + return new Proxy(proxyTarget, { + get: (target, prop) => { + if (prop === '__isUserNotAvailableProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms. + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)') { + // Node.js util.inspect + return undefined; + } + } + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); + }, + set: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + deleteProperty: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + }); +} +/** + * Creates a proxy around a user object that warns when properties are accessed on the server. + * This is used to alert developers that using user data from getSession() on the server is insecure. + * + * @param user The actual user object to wrap + * @param suppressWarningRef An object with a 'value' property that controls warning suppression + * @returns A proxied user object that warns on property access + */ +function insecureUserWarningProxy(user, suppressWarningRef) { + return new Proxy(user, { + get: (target, prop, receiver) => { + // Allow internal checks without warning + if (prop === '__isInsecureUserWarningProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)' || + sProp === 'Symbol(nodejs.util.inspect.custom)') { + // Return the actual value for these symbols to allow proper inspection + return Reflect.get(target, prop, receiver); + } + } + // Emit warning on first property access + if (!suppressWarningRef.value && typeof prop === 'string') { + console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); + suppressWarningRef.value = true; + } + return Reflect.get(target, prop, receiver); + }, + }); +} +/** + * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). + * Note: Only works for JSON-safe data. + */ +function deepClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} +//# sourceMappingURL=helpers.js.map - this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); - - return this; - } +/***/ }), - forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +/***/ 5804: +/***/ ((__unused_webpack_module, exports) => { - // Send a request to forward a TCP connection to the server +"use strict"; - const cfg = { - srcIP: srcIP, - srcPort: srcPort, - dstIP: dstIP, - dstPort: dstPort +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter; +/** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ +function memoryLocalStorageAdapter(store = {}) { + return { + getItem: (key) => { + return store[key] || null; + }, + setItem: (key, value) => { + store[key] = value; + }, + removeItem: (key) => { + delete store[key]; + }, }; +} +//# sourceMappingURL=local-storage.js.map - if (typeof cb !== 'function') - cb = noop; - - openChannel(this, 'direct-tcpip', cfg, cb); - - return this; - } - - openssh_noMoreSessions(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to disable future sessions')); - return; - } - - cb(); - }); - } - - this._protocol.openssh_noMoreSessions(wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${socketPath}`)); - return; - } - this._forwardingUnix[socketPath] = true; - cb(); - }); - } - - this._protocol.openssh_streamLocalForward(socketPath, wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_unforwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); +/***/ }), - const wantReply = (typeof cb === 'function'); +/***/ 163: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${socketPath}`)); - return; - } - delete this._forwardingUnix[socketPath]; - cb(); - }); - } +"use strict"; - this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); - return this; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0; +exports.navigatorLock = navigatorLock; +exports.processLock = processLock; +const helpers_1 = __nccwpck_require__(4044); +/** + * @experimental + */ +exports.internals = { + /** + * @experimental + */ + debug: !!(globalThis && + (0, helpers_1.supportsLocalStorage)() && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), +}; +/** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + */ +class LockAcquireTimeoutError extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof cb !== 'function') - cb = noop; - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); - return this; +} +exports.LockAcquireTimeoutError = LockAcquireTimeoutError; +class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; +class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError; +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +async function navigatorLock(name, acquireTimeout, fn) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); } - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - sftp(env, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof env === 'function') { - cb = env; - env = undefined; + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort(); + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); + } + }, acquireTimeout); } - - openChannel(this, 'sftp', (err, sftp) => { - if (err) { - cb(err); - return; - } - - const reqSubsystemCb = (err, sftp_) => { - if (err) { - cb(err); - return; + // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request + // Wrapping navigator.locks.request() with a plain Promise is done as some + // libraries like zone.js patch the Promise object to track the execution + // context. However, it appears that most browsers use an internal promise + // implementation when using the navigator.locks.request() API causing them + // to lose context and emit confusing log messages or break certain features. + // This wrapping is believed to help zone.js track the execution context + // better. + return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 + ? { + mode: 'exclusive', + ifAvailable: true, } - - function removeListeners() { - sftp.removeListener('ready', onReady); - sftp.removeListener('error', onError); - sftp.removeListener('exit', onExit); - sftp.removeListener('close', onExit); + : { + mode: 'exclusive', + signal: abortController.signal, + }, async (lock) => { + if (lock) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); + } + try { + return await fn(); + } + finally { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); + } + } } - - function onReady() { - // TODO: do not remove exit/close in case remote end closes the - // channel abruptly and we need to notify outstanding callbacks - removeListeners(); - cb(undefined, sftp); + else { + if (acquireTimeout === 0) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); + } + throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + } + else { + if (exports.internals.debug) { + try { + const result = await globalThis.navigator.locks.query(); + console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); + } + catch (e) { + console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); + } + } + // Browser is not following the Navigator LockManager spec, it + // returned a null lock when we didn't use ifAvailable. So we can + // pretend the lock is acquired in the name of backward compatibility + // and user experience and just run the function. + console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); + return await fn(); + } } - - function onError(err) { - removeListeners(); - cb(err); + })); +} +const PROCESS_LOCKS = {}; +/** + * Implements a global exclusive lock that works only in the current process. + * Useful for environments like React Native or other non-browser + * single-process (i.e. no concept of "tabs") environments. + * + * Use {@link #navigatorLock} in browser environments. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +async function processLock(name, acquireTimeout, fn) { + var _a; + const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve(); + const currentOperation = Promise.race([ + previousOperation.catch(() => { + // ignore error of previous operation that we're waiting to finish + return null; + }), + acquireTimeout >= 0 + ? new Promise((_, reject) => { + setTimeout(() => { + reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); + }, acquireTimeout); + }) + : null, + ].filter((x) => x)) + .catch((e) => { + if (e && e.isAcquireTimeout) { + throw e; } - - function onExit(code, signal) { - removeListeners(); - let msg; - if (typeof code === 'number') - msg = `Received exit code ${code} while establishing SFTP session`; - else if (signal !== undefined) - msg = `Received signal ${signal} while establishing SFTP session`; - else - msg = 'Received unexpected SFTP session termination'; - const err = new Error(msg); - err.code = code; - err.signal = signal; - cb(err); + return null; + }) + .then(async () => { + // previous operations finished and we didn't get a race on the acquire + // timeout, so the current operation can finally start + return await fn(); + }); + PROCESS_LOCKS[name] = currentOperation.catch(async (e) => { + if (e && e.isAcquireTimeout) { + // if the current operation timed out, it doesn't mean that the previous + // operation finished, so we need contnue waiting for it to finish + await previousOperation; + return null; } - - sftp.on('ready', onReady) - .on('error', onError) - .on('exit', onExit) - .on('close', onExit); - - sftp._init(); - }; - - if (typeof env === 'object' && env !== null) { - reqEnv(sftp, env, (err) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(sftp, 'sftp', reqSubsystemCb); - }); - } else { - reqSubsystem(sftp, 'sftp', reqSubsystemCb); - } + throw e; }); - - return this; - } - - setNoDelay(noDelay) { - if (this._sock && typeof this._sock.setNoDelay === 'function') - this._sock.setNoDelay(noDelay); - - return this; - } + // finally wait for the current operation to finish successfully, with an + // error or with an acquire timeout error + return await currentOperation; } +//# sourceMappingURL=locks.js.map -function openChannel(self, type, opts, cb) { - // Ask the server to open a channel for some purpose - // (e.g. session (sftp, exec, shell), or forwarding a TCP connection - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'session': - case 'sftp': - self._protocol.session(localChan, initWindow, maxPacket); - break; - case 'direct-tcpip': - self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'direct-streamlocal@openssh.com': - self._protocol.openssh_directStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} +/***/ }), -function reqX11(chan, screen, cb) { - // Asks server to start sending us X11 connections - const cfg = { - single: false, - protocol: 'MIT-MAGIC-COOKIE-1', - cookie: undefined, - screen: 0 - }; +/***/ 1897: +/***/ ((__unused_webpack_module, exports) => { - if (typeof screen === 'function') { - cb = screen; - } else if (typeof screen === 'object' && screen !== null) { - if (typeof screen.single === 'boolean') - cfg.single = screen.single; - if (typeof screen.screen === 'number') - cfg.screen = screen.screen; - if (typeof screen.protocol === 'string') - cfg.protocol = screen.protocol; - if (typeof screen.cookie === 'string') - cfg.cookie = screen.cookie; - else if (Buffer.isBuffer(screen.cookie)) - cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); - } - if (cfg.cookie === undefined) - cfg.cookie = randomCookie(); - - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } +"use strict"; - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to request X11')); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.polyfillGlobalThis = polyfillGlobalThis; +/** + * https://mathiasbynens.be/notes/globalthis + */ +function polyfillGlobalThis() { + if (typeof globalThis === 'object') return; - } - - chan._hasX11 = true; - ++chan._client._acceptX11; - chan.once('close', () => { - if (chan._client._acceptX11) - --chan._client._acceptX11; - }); - - cb(); - }); - } - - chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this; + }, + configurable: true, + }); + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__; + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__; + } + catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self; + } + } } +//# sourceMappingURL=polyfills.js.map -function reqPty(chan, opts, cb) { - let rows = 24; - let cols = 80; - let width = 640; - let height = 480; - let term = 'vt100'; - let modes = null; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.rows === 'number') - rows = opts.rows; - if (typeof opts.cols === 'number') - cols = opts.cols; - if (typeof opts.width === 'number') - width = opts.width; - if (typeof opts.height === 'number') - height = opts.height; - if (typeof opts.term === 'string') - term = opts.term; - if (typeof opts.modes === 'object') - modes = opts.modes; - } - - const wantReply = (typeof cb === 'function'); +/***/ }), - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } +/***/ 1852: +/***/ ((__unused_webpack_module, exports) => { - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to request a pseudo-terminal')); - return; - } - cb(); - }); - } +"use strict"; - chan._client._protocol.pty(chan.outgoing.id, - rows, - cols, - height, - width, - term, - modes, - wantReply); -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SIGN_OUT_SCOPES = void 0; +const WeakPasswordReasons = (/* unused pure expression or super */ null && (['length', 'characters', 'pwned'])); +const AMRMethods = (/* unused pure expression or super */ null && ([ + 'password', + 'otp', + 'oauth', + 'totp', + 'mfa/totp', + 'mfa/phone', + 'mfa/webauthn', + 'anonymous', + 'sso/saml', + 'magiclink', + 'web3', +])); +const FactorTypes = (/* unused pure expression or super */ null && (['totp', 'phone', 'webauthn'])); +const FactorVerificationStatuses = (/* unused pure expression or super */ null && (['verified', 'unverified'])); +const MFATOTPChannels = (/* unused pure expression or super */ null && (['sms', 'whatsapp'])); +exports.SIGN_OUT_SCOPES = ['global', 'local', 'others']; +//# sourceMappingURL=types.js.map -function reqAgentFwd(chan, cb) { - const wantReply = (typeof cb === 'function'); +/***/ }), - if (chan.outgoing.state !== 'open') { - wantReply && cb(new Error('Channel is not open')); - return; - } - if (chan._client._agentFwdEnabled) { - wantReply && cb(false); - return; - } +/***/ 6677: +/***/ ((__unused_webpack_module, exports) => { - chan._client._agentFwdEnabled = true; +"use strict"; - chan._callbacks.push((had_err) => { - if (had_err) { - chan._client._agentFwdEnabled = false; - if (wantReply) { - cb(had_err !== true - ? had_err - : new Error('Unable to request agent forwarding')); - } - return; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map - if (wantReply) - cb(); - }); +/***/ }), - chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); -} +/***/ 9031: +/***/ ((__unused_webpack_module, exports) => { -function reqShell(chan, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } +"use strict"; - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to open shell')); - return; +// types and functions copied over from viem so this library doesn't depend on it +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAddress = getAddress; +exports.fromHex = fromHex; +exports.toHex = toHex; +exports.createSiweMessage = createSiweMessage; +function getAddress(address) { + if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { + throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); } - chan.subtype = 'shell'; - cb(undefined, chan); - }); - - chan._client._protocol.shell(chan.outgoing.id, true); + return address.toLowerCase(); } - -function reqExec(chan, cmd, opts, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to exec')); - return; +function fromHex(hex) { + return parseInt(hex, 16); +} +function toHex(value) { + const bytes = new TextEncoder().encode(value); + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + return ('0x' + hex); +} +/** + * Creates EIP-4361 formatted message. + */ +function createSiweMessage(parameters) { + var _a; + const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters; + // Validate fields + { + if (!Number.isInteger(chainId)) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); + if (!domain) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); + if (nonce && nonce.length < 8) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); + if (!uri) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); + if (version !== '1') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`); + if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n')) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); } - chan.subtype = 'exec'; - chan.allowHalfOpen = (opts.allowHalfOpen !== false); - cb(undefined, chan); - }); - - chan._client._protocol.exec(chan.outgoing.id, cmd, true); + // Construct message + const address = getAddress(parameters.address); + const origin = scheme ? `${scheme}://${domain}` : domain; + const statement = parameters.statement ? `${parameters.statement}\n` : ''; + const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`; + let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`; + if (expirationTime) + suffix += `\nExpiration Time: ${expirationTime.toISOString()}`; + if (notBefore) + suffix += `\nNot Before: ${notBefore.toISOString()}`; + if (requestId) + suffix += `\nRequest ID: ${requestId}`; + if (resources) { + let content = '\nResources:'; + for (const resource of resources) { + if (!resource || typeof resource !== 'string') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); + content += `\n- ${resource}`; + } + suffix += content; + } + return `${prefix}\n${suffix}`; } +//# sourceMappingURL=ethereum.js.map -function reqEnv(chan, env, cb) { - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } +/***/ }), - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to set environment')); - return; - } - cb(); - }); - } +/***/ 7906: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const keys = Object.keys(env || {}); +"use strict"; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const val = env[key]; - chan._client._protocol.env(chan.outgoing.id, key, val, wantReply); - } +/* eslint-disable @typescript-eslint/ban-ts-comment */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebAuthnUnknownError = exports.WebAuthnError = void 0; +exports.isWebAuthnError = isWebAuthnError; +exports.identifyRegistrationError = identifyRegistrationError; +exports.identifyAuthenticationError = identifyAuthenticationError; +const webauthn_1 = __nccwpck_require__(9451); +/** + * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented + * errors in the spec was raised after calling `navigator.credentials.create()` or + * `navigator.credentials.get()`: + * + * - `AbortError` + * - `ConstraintError` + * - `InvalidStateError` + * - `NotAllowedError` + * - `NotSupportedError` + * - `SecurityError` + * - `TypeError` + * - `UnknownError` + * + * Error messages were determined through investigation of the spec to determine under which + * scenarios a given error would be raised. + */ +class WebAuthnError extends Error { + constructor({ message, code, cause, name, }) { + var _a; + // @ts-ignore: help Rollup understand that `cause` is okay to set + super(message, { cause }); + this.__isWebAuthnError = true; + this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error'; + this.code = code; + } } - -function reqSubsystem(chan, name, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to start subsystem: ${name}`)); - return; +exports.WebAuthnError = WebAuthnError; +/** + * Error class for unknown WebAuthn errors. + * Wraps unexpected errors that don't match known WebAuthn error conditions. + */ +class WebAuthnUnknownError extends WebAuthnError { + constructor(message, originalError) { + super({ + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: originalError, + message, + }); + this.name = 'WebAuthnUnknownError'; + this.originalError = originalError; } - chan.subtype = 'subsystem'; - cb(undefined, chan); - }); - - chan._client._protocol.subsystem(chan.outgoing.id, name, true); } - -// TODO: inline implementation into single call site -function onCHANNEL_OPEN(self, info) { - // The server is trying to open a channel with us, this is usually when - // we asked the server to forward us connections on some port and now they - // are asking us to accept/deny an incoming connection on their side - - let localChan = -1; - let reason; - - const accept = () => { - const chanInfo = { - type: info.type, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const stream = new Channel(self, chanInfo); - self._chanMgr.update(localChan, stream); - - self._protocol.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - return stream; - }; - const reject = () => { - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; +exports.WebAuthnUnknownError = WebAuthnUnknownError; +/** + * Type guard to check if an error is a WebAuthnError. + * @param {unknown} error - The error to check + * @returns {boolean} True if the error is a WebAuthnError + */ +function isWebAuthnError(error) { + return typeof error === 'object' && error !== null && '__isWebAuthnError' in error; +} +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + */ +function identifyRegistrationError({ error, options, }) { + var _a, _b, _c; + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); } - - if (localChan !== -1) - self._chanMgr.remove(localChan); - - self._protocol.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = self._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of incoming channel open: ' - + 'no channels available' - ); - } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Registration ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); + } } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'forwarded-tcpip': { - const val = self._forwarding[`${data.destIP}:${data.destPort}`]; - if (val !== undefined && reserveChannel()) { - if (data.destPort === 0) - data.destPort = val; - self.emit('tcp connection', data, accept, reject); - return; - } - break; + else if (error.name === 'ConstraintError') { + if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) + return new WebAuthnError({ + message: 'Discoverable credentials were required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', + cause: error, + }); + } + else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === 'conditional' && + ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') { + // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4) + return new WebAuthnError({ + message: 'User verification was required during automatic registration but it could not be performed', + code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE', + cause: error, + }); + } + else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) + return new WebAuthnError({ + message: 'User verification was required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', + cause: error, + }); + } } - case 'forwarded-streamlocal@openssh.com': - if (self._forwardingUnix[data.socketPath] !== undefined - && reserveChannel()) { - self.emit('unix connection', data, accept, reject); - return; - } - break; - case 'auth-agent@openssh.com': - if (self._agentFwdEnabled - && typeof self._agent.getStream === 'function' - && reserveChannel()) { - self._agent.getStream((err, stream) => { - if (err) - return reject(); - - const upstream = accept(); - upstream.pipe(stream).pipe(upstream); + else if (error.name === 'InvalidStateError') { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) + return new WebAuthnError({ + message: 'The authenticator was previously registered', + code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', + cause: error, }); - return; - } - break; - case 'x11': - if (self._acceptX11 !== 0 && reserveChannel()) { - self.emit('x11', data, accept, reject); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unsupported incoming channel open ' - + `type: ${info.type}` - ); - } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unexpected incoming channel open for: ' - + info.type - ); } - } - - reject(); + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); + } + else if (error.name === 'NotSupportedError') { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key'); + if (validPubKeyCredParams.length === 0) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', + cause: error, + }); + } + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) + return new WebAuthnError({ + message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms', + code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', + cause: error, + }); + } + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rp.id !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } + } + else if (error.name === 'TypeError') { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) + return new WebAuthnError({ + message: 'User ID was not between 1 and 64 characters', + code: 'ERROR_INVALID_USER_ID_LENGTH', + cause: error, + }); + } + } + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new credential', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); + } + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); } - -const randomCookie = (() => { - const buffer = Buffer.allocUnsafe(16); - return () => { - randomFillSync(buffer, 0, 16); - return buffer.hexSlice(0, 16); - }; -})(); - -function makeSimpleAuthHandler(authList) { - if (!Array.isArray(authList)) - throw new Error('authList must be an array'); - - let a = 0; - return (authsLeft, partialSuccess, cb) => { - if (a === authList.length) - return false; - return authList[a++]; - }; +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + */ +function identifyAuthenticationError({ error, options, }) { + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); + } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Authentication ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); + } + } + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); + } + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rpId !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } + } + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); + } + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); } +//# sourceMappingURL=webauthn.errors.js.map -function hostKeysProve(client, keys_, cb) { - if (!client._sock || !isWritable(client._sock)) - return; - - if (typeof cb !== 'function') - cb = noop; - - if (!Array.isArray(keys_)) - throw new TypeError('Invalid keys argument type'); +/***/ }), - const keys = []; - for (const key of keys_) { - const parsed = parseKey(key); - if (parsed instanceof Error) - throw parsed; - keys.push(parsed); - } +/***/ 9451: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!client.config.strictVendor - || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { - client._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Server failed to prove supplied keys')); - return; - } +"use strict"; - // TODO: move all of this parsing/verifying logic out of the client? - const ret = []; - let keyIdx = 0; - bufferParser.init(data, 0); - while (bufferParser.avail()) { - if (keyIdx === keys.length) - break; - const key = keys[keyIdx++]; - const keyPublic = key.getPublicSSH(); - - const sigEntry = bufferParser.readString(); - sigParser.init(sigEntry, 0); - const type = sigParser.readString(true); - let value = sigParser.readString(); - - let algo; - if (type !== key.type) { - if (key.type === 'ssh-rsa') { - switch (type) { - case 'rsa-sha2-256': - algo = 'sha256'; - break; - case 'rsa-sha2-512': - algo = 'sha512'; - break; - default: - continue; - } - } else { - continue; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0; +exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions; +exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions; +exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse; +exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse; +exports.isValidDomain = isValidDomain; +exports.createCredential = createCredential; +exports.getCredential = getCredential; +exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions; +exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions; +const tslib_1 = __nccwpck_require__(4351); +const base64url_1 = __nccwpck_require__(3649); +const errors_1 = __nccwpck_require__(9938); +const helpers_1 = __nccwpck_require__(4044); +const webauthn_errors_1 = __nccwpck_require__(7906); +Object.defineProperty(exports, "identifyAuthenticationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } })); +Object.defineProperty(exports, "identifyRegistrationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } })); +Object.defineProperty(exports, "isWebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } })); +Object.defineProperty(exports, "WebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } })); +/** + * WebAuthn abort service to manage ceremony cancellation. + * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. + * + * @experimental This class is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} + */ +class WebAuthnAbortService { + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal() { + // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() + if (this.controller) { + const abortError = new Error('Cancelling existing WebAuthn API call for new one'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + } + const newController = new AbortController(); + this.controller = newController; + return newController.signal; + } + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony() { + if (this.controller) { + const abortError = new Error('Manually cancelling existing WebAuthn API call'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + this.controller = undefined; } - - const sessionID = client._protocol._kex.sessionID; - const verifyData = Buffer.allocUnsafe( - 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length - ); - let p = 0; - writeUInt32BE(verifyData, 29, p); - verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - writeUInt32BE(verifyData, sessionID.length, p += 29); - bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); - writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); - bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); - - if (!(value = sigSSHToASN1(value, type))) - continue; - if (key.verify(verifyData, value, algo) === true) - ret.push(key); - } - sigParser.clear(); - bufferParser.clear(); - - cb(null, ret); - }); - - client._protocol.openssh_hostKeysProve(keys); - return; - } - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); + } } - -function getKeyAlgos(client, key, serverSigAlgs) { - switch (key.type) { - case 'ssh-rsa': - if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { - if (!Array.isArray(serverSigAlgs)) - serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512']; - else - serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs]; - } - if (Array.isArray(serverSigAlgs)) { - if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1) - return [['rsa-sha2-256', 'sha256']]; - if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1) - return [['rsa-sha2-512', 'sha512']]; - if (serverSigAlgs.indexOf('ssh-rsa') === -1) - return []; - } - return [['ssh-rsa', 'sha1']]; - } +exports.WebAuthnAbortService = WebAuthnAbortService; +/** + * Singleton instance to ensure only one WebAuthn ceremony is active at a time. + * This prevents "operation already in progress" errors when retrying WebAuthn operations. + * + * @experimental This instance is experimental and may change in future releases + */ +exports.webAuthnAbortService = new WebAuthnAbortService(); +/** + * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} + */ +function deserializeCredentialCreationOptions(options) { + if (!options) { + throw new Error('Credential creation options are required'); + } + // Check if the native parseCreationOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseCreationOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseCreationOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseCreationOptionsFromJSON( + /** we assert the options here as typescript still doesn't know about future webauthn types */ + options); + } + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "user", "excludeCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + // Convert user.id from base64url to ArrayBuffer + const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer }); + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge, + user }); + // Only add excludeCredentials if it exists + if (excludeCredentials && excludeCredentials.length > 0) { + result.excludeCredentials = new Array(excludeCredentials.length); + for (let i = 0; i < excludeCredentials.length; i++) { + const cred = excludeCredentials[i]; + result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } + } + return result; } - -module.exports = Client; - - -/***/ }), - -/***/ 42994: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const { Agent: HttpAgent } = __nccwpck_require__(13685); -const { Agent: HttpsAgent } = __nccwpck_require__(95687); -const { connect: tlsConnect } = __nccwpck_require__(24404); - -let Client; - -for (const ctor of [HttpAgent, HttpsAgent]) { - class SSHAgent extends ctor { - constructor(connectCfg, agentOptions) { - super(agentOptions); - - this._connectCfg = connectCfg; - this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; +/** + * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} + */ +function deserializeCredentialRequestOptions(options) { + if (!options) { + throw new Error('Credential request options are required'); } - - createConnection(options, cb) { - const srcIP = (options && options.localAddress) || this._defaultSrcIP; - const srcPort = (options && options.localPort) || 0; - const dstIP = options.host; - const dstPort = options.port; - - if (Client === undefined) - Client = __nccwpck_require__(36063); - - const client = new Client(); - let triedForward = false; - client.on('ready', () => { - client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { - triedForward = true; - if (err) { - client.end(); - return cb(err); - } - stream.once('close', () => client.end()); - cb(null, decorateStream(stream, ctor, options)); - }); - }).on('error', cb).on('close', () => { - if (!triedForward) - cb(new Error('Unexpected connection close')); - }).connect(this._connectCfg); + // Check if the native parseRequestOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseRequestOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseRequestOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseRequestOptionsFromJSON(options); } - } - - exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "allowCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge }); + // Only add allowCredentials if it exists + if (allowCredentials && allowCredentials.length > 0) { + result.allowCredentials = new Array(allowCredentials.length); + for (let i = 0; i < allowCredentials.length; i++) { + const cred = allowCredentials[i]; + result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } + } + return result; } - -function noop() {} - -function decorateStream(stream, ctor, options) { - if (ctor === HttpAgent) { - // HTTP - stream.setKeepAlive = noop; - stream.setNoDelay = noop; - stream.setTimeout = noop; - stream.ref = noop; - stream.unref = noop; - stream.destroySoon = stream.destroy; - return stream; - } - - // HTTPS - options.socket = stream; - const wrapped = tlsConnect(options); - - // This is a workaround for a regression in node v12.16.3+ - // https://github.com/nodejs/node/issues/35904 - const onClose = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (stream.isPaused()) - stream.resume(); +/** + * Convert a registration/enrollment credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() + * @returns {RegistrationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +function serializeCredentialCreationResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); + } + const credentialWithAttachment = credential; + return { + id: credential.id, + rawId: credential.id, + response: { + attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)), + }, + type: 'public-key', + clientExtensionResults: credential.getClientExtensionResults(), + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), }; - })(); - // 'end' listener is needed because 'close' is not emitted in some scenarios - // in node v12.x for some unknown reason - wrapped.on('end', onClose).on('close', onClose); - - return wrapped; } - - -/***/ }), - -/***/ 95869: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - OpenSSHAgent, - PageantAgent, -} = __nccwpck_require__(49054); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = __nccwpck_require__(42994); -const { parseKey } = __nccwpck_require__(22218); -const { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, -} = __nccwpck_require__(52026); - -module.exports = { - AgentProtocol, - BaseAgent, - createAgent, - Client: __nccwpck_require__(36063), - CygwinAgent, - HTTPAgent, - HTTPSAgent, - OpenSSHAgent, - PageantAgent, - Server: __nccwpck_require__(12986), - utils: { - parseKey, - ...__nccwpck_require__(63823), - sftp: { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, - }, - }, -}; - - -/***/ }), - -/***/ 63823: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - createCipheriv, - generateKeyPair: generateKeyPair_, - generateKeyPairSync: generateKeyPairSync_, - getCurves, - randomBytes, -} = __nccwpck_require__(6113); - -const { Ber } = __nccwpck_require__(80970); -const bcrypt_pbkdf = (__nccwpck_require__(45447).pbkdf); - -const { CIPHER_INFO } = __nccwpck_require__(45708); - -const SALT_LEN = 16; -const DEFAULT_ROUNDS = 16; - -const curves = getCurves(); -const ciphers = new Map(Object.entries(CIPHER_INFO)); - -function makeArgs(type, opts) { - if (typeof type !== 'string') - throw new TypeError('Key type must be a string'); - - const publicKeyEncoding = { type: 'spki', format: 'der' }; - const privateKeyEncoding = { type: 'pkcs8', format: 'der' }; - - switch (type.toLowerCase()) { - case 'rsa': { - if (typeof opts !== 'object' || opts === null) - throw new TypeError('Missing options object for RSA key'); - const modulusLength = opts.bits; - if (!Number.isInteger(modulusLength)) - throw new TypeError('RSA bits must be an integer'); - if (modulusLength <= 0 || modulusLength > 16384) - throw new RangeError('RSA bits must be non-zero and <= 16384'); - return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }]; - } - case 'ecdsa': { - if (typeof opts !== 'object' || opts === null) - throw new TypeError('Missing options object for ECDSA key'); - if (!Number.isInteger(opts.bits)) - throw new TypeError('ECDSA bits must be an integer'); - let namedCurve; - switch (opts.bits) { - case 256: - namedCurve = 'prime256v1'; - break; - case 384: - namedCurve = 'secp384r1'; - break; - case 521: - namedCurve = 'secp521r1'; - break; - default: - throw new Error('ECDSA bits must be 256, 384, or 521'); - } - if (!curves.includes(namedCurve)) - throw new Error('Unsupported ECDSA bits value'); - return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }]; +/** + * Convert an authentication/verification credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() + * @returns {AuthenticationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +function serializeCredentialRequestResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); } - case 'ed25519': - return ['ed25519', { publicKeyEncoding, privateKeyEncoding }]; - default: - throw new Error(`Unsupported key type: ${type}`); - } + // Fallback to manual conversion for browsers that don't support toJSON + // Access authenticatorAttachment via type assertion to handle TypeScript version differences + // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't + const credentialWithAttachment = credential; + const clientExtensionResults = credential.getClientExtensionResults(); + const assertionResponse = credential.response; + return { + id: credential.id, + rawId: credential.id, // W3C spec expects rawId to match id for JSON format + response: { + authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)), + signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)), + userHandle: assertionResponse.userHandle + ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle)) + : undefined, + }, + type: 'public-key', + clientExtensionResults, + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), + }; } - -function parseDERs(keyType, pub, priv) { - switch (keyType) { - case 'rsa': { - // Note: we don't need to parse the public key since the PKCS8 private key - // already includes the public key parameters - - // Parse private key - let reader = new Ber.Reader(priv); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 0) - throw new Error('Unsupported version in RSA private key'); - - // - Algorithm - reader.readSequence(); - if (reader.readOID() !== '1.2.840.113549.1.1.1') - throw new Error('Bad RSA private OID'); - // - Algorithm parameters (RSA has none) - if (reader.readByte() !== Ber.Null) - throw new Error('Malformed RSA private key (expected null)'); - if (reader.readByte() !== 0x00) { - throw new Error( - 'Malformed RSA private key (expected zero-length null)' - ); - } - - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - reader.readSequence(); - if (reader.readInt() !== 0) - throw new Error('Unsupported version in RSA private key'); - const n = reader.readString(Ber.Integer, true); - const e = reader.readString(Ber.Integer, true); - const d = reader.readString(Ber.Integer, true); - const p = reader.readString(Ber.Integer, true); - const q = reader.readString(Ber.Integer, true); - reader.readString(Ber.Integer, true); // dmp1 - reader.readString(Ber.Integer, true); // dmq1 - const iqmp = reader.readString(Ber.Integer, true); - - /* - OpenSSH RSA private key: - string "ssh-rsa" - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const keyName = Buffer.from('ssh-rsa'); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + n.length - + 4 + e.length - + 4 + d.length - + 4 + iqmp.length - + 4 + p.length - + 4 + q.length - ); - let pos = 0; - - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(n.length, pos += keyName.length); - privBuf.set(n, pos += 4); - privBuf.writeUInt32BE(e.length, pos += n.length); - privBuf.set(e, pos += 4); - privBuf.writeUInt32BE(d.length, pos += e.length); - privBuf.set(d, pos += 4); - privBuf.writeUInt32BE(iqmp.length, pos += d.length); - privBuf.set(iqmp, pos += 4); - privBuf.writeUInt32BE(p.length, pos += iqmp.length); - privBuf.set(p, pos += 4); - privBuf.writeUInt32BE(q.length, pos += p.length); - privBuf.set(q, pos += 4); - - /* - OpenSSH RSA public key: - string "ssh-rsa" - string e -- public - string n -- public - */ - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + e.length - + 4 + n.length - ); - pos = 0; - - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(e.length, pos += keyName.length); - pubBuf.set(e, pos += 4); - pubBuf.writeUInt32BE(n.length, pos += e.length); - pubBuf.set(n, pos += 4); - - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; - } - case 'ec': { - // Parse public key - let reader = new Ber.Reader(pub); - reader.readSequence(); - - reader.readSequence(); - if (reader.readOID() !== '1.2.840.10045.2.1') - throw new Error('Bad ECDSA public OID'); - // Skip curve OID, we'll get it from the private key - reader.readOID(); - let pubBin = reader.readString(Ber.BitString, true); - { - // Remove leading zero bytes - let i = 0; - for (; i < pubBin.length && pubBin[i] === 0x00; ++i); - if (i > 0) - pubBin = pubBin.slice(i); - } - - // Parse private key - reader = new Ber.Reader(priv); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 0) - throw new Error('Unsupported version in ECDSA private key'); - - reader.readSequence(); - if (reader.readOID() !== '1.2.840.10045.2.1') - throw new Error('Bad ECDSA private OID'); - const curveOID = reader.readOID(); - let sshCurveName; - switch (curveOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - sshCurveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - sshCurveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - sshCurveName = 'nistp521'; - break; - default: - throw new Error('Unsupported curve in ECDSA private key'); - } - - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 1) - throw new Error('Unsupported version in ECDSA private key'); - - // Add leading zero byte to prevent negative bignum in private key - const privBin = Buffer.concat([ - Buffer.from([0x00]), - reader.readString(Ber.OctetString, true) - ]); - - /* - OpenSSH ECDSA private key: - string "ecdsa-sha2-" - string curve name - string Q -- public - string d -- private - */ - const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); - sshCurveName = Buffer.from(sshCurveName); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + sshCurveName.length - + 4 + pubBin.length - + 4 + privBin.length - ); - let pos = 0; - - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); - privBuf.set(sshCurveName, pos += 4); - privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); - privBuf.set(pubBin, pos += 4); - privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); - privBuf.set(privBin, pos += 4); - - /* - OpenSSH ECDSA public key: - string "ecdsa-sha2-" - string curve name - string Q -- public - */ - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + sshCurveName.length - + 4 + pubBin.length - ); - pos = 0; - - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); - pubBuf.set(sshCurveName, pos += 4); - pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); - pubBuf.set(pubBin, pos += 4); - - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; +/** + * A simple test to determine if a hostname is a properly-formatted domain name. + * Considers localhost valid for development environments. + * + * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain + * + * Regex sourced from here: + * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + * + * @param {string} hostname - The hostname to validate + * @returns {boolean} True if valid domain or localhost + * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} + */ +function isValidDomain(hostname) { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname)); +} +/** + * Determine if the browser is capable of WebAuthn. + * Checks for necessary Web APIs: PublicKeyCredential and Credential Management. + * + * @returns {boolean} True if browser supports WebAuthn + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility} + */ +function browserSupportsWebAuthn() { + var _a, _b; + return !!((0, helpers_1.isBrowser)() && + 'PublicKeyCredential' in window && + window.PublicKeyCredential && + 'credentials' in navigator && + typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' && + typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function'); +} +/** + * Create a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.create() with error handling. + * + * @param {CredentialCreationOptions} options - Options including publicKey parameters + * @returns {Promise>} Created credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} + */ +async function createCredential(options) { + try { + const response = await navigator.credentials.create( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; } - case 'ed25519': { - // Parse public key - let reader = new Ber.Reader(pub); - reader.readSequence(); - - // - Algorithm - reader.readSequence(); - if (reader.readOID() !== '1.3.101.112') - throw new Error('Bad ED25519 public OID'); - // - Attributes (absent for ED25519) - - let pubBin = reader.readString(Ber.BitString, true); - { - // Remove leading zero bytes - let i = 0; - for (; i < pubBin.length && pubBin[i] === 0x00; ++i); - if (i > 0) - pubBin = pubBin.slice(i); - } - - // Parse private key - reader = new Ber.Reader(priv); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 0) - throw new Error('Unsupported version in ED25519 private key'); - - // - Algorithm - reader.readSequence(); - if (reader.readOID() !== '1.3.101.112') - throw new Error('Bad ED25519 private OID'); - // - Attributes (absent) - - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - const privBin = reader.readString(Ber.OctetString, true); - - /* - OpenSSH ed25519 private key: - string "ssh-ed25519" - string public key - string private key + public key - */ - const keyName = Buffer.from('ssh-ed25519'); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + pubBin.length - + 4 + (privBin.length + pubBin.length) - ); - let pos = 0; - - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); - privBuf.set(pubBin, pos += 4); - privBuf.writeUInt32BE( - privBin.length + pubBin.length, - pos += pubBin.length - ); - privBuf.set(privBin, pos += 4); - privBuf.set(pubBin, pos += privBin.length); - - /* - OpenSSH ed25519 public key: - string "ssh-ed25519" - string public key - */ - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + pubBin.length - ); - pos = 0; - - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); - pubBuf.set(pubBin, pos += 4); - - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; + catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyRegistrationError)({ + error: err, + options, + }), + }; } - } } - -function convertKeys(keyType, pub, priv, opts) { - let format = 'new'; - let encrypted; - let comment = ''; - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.comment === 'string' && opts.comment) - comment = opts.comment; - if (typeof opts.format === 'string' && opts.format) - format = opts.format; - if (opts.passphrase) { - let passphrase; - if (typeof opts.passphrase === 'string') - passphrase = Buffer.from(opts.passphrase); - else if (Buffer.isBuffer(opts.passphrase)) - passphrase = opts.passphrase; - else - throw new Error('Invalid passphrase'); - - if (opts.cipher === undefined) - throw new Error('Missing cipher name'); - const cipher = ciphers.get(opts.cipher); - if (cipher === undefined) - throw new Error('Invalid cipher name'); - - if (format === 'new') { - let rounds = DEFAULT_ROUNDS; - if (opts.rounds !== undefined) { - if (!Number.isInteger(opts.rounds)) - throw new TypeError('rounds must be an integer'); - if (opts.rounds > 0) - rounds = opts.rounds; - } - - const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); - const salt = randomBytes(SALT_LEN); - const r = bcrypt_pbkdf( - passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds - ); - if (r !== 0) - return new Error('Failed to generate information to encrypt key'); - - /* - string salt - uint32 rounds - */ - const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); - { - let pos = 0; - kdfOptions.writeUInt32BE(salt.length, pos += 0); - kdfOptions.set(salt, pos += 4); - kdfOptions.writeUInt32BE(rounds, pos += salt.length); - } - - encrypted = { - cipher, - cipherName: opts.cipher, - kdfName: 'bcrypt', - kdfOptions, - key: gen.slice(0, cipher.keyLen), - iv: gen.slice(cipher.keyLen), - }; - } +/** + * Get a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.get() with error handling. + * + * @param {CredentialRequestOptions} options - Options including publicKey parameters + * @returns {Promise>} Retrieved credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} + */ +async function getCredential(options) { + try { + const response = await navigator.credentials.get( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; } - } - - switch (format) { - case 'new': { - let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\n'; - let publicB64; - /* - byte[] "openssh-key-v1\0" - string ciphername - string kdfname - string kdfoptions - uint32 number of keys N - string publickey1 - string encrypted, padded list of private keys - uint32 checkint - uint32 checkint - byte[] privatekey1 - string comment1 - byte 1 - byte 2 - byte 3 - ... - byte padlen % 255 - */ - const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none'); - const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none'); - const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0)); - const blockLen = (encrypted ? encrypted.cipher.blockLen : 8); - - const parsed = parseDERs(keyType, pub, priv); - - const checkInt = randomBytes(4); - const commentBin = Buffer.from(comment); - const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length); - let padding = []; - for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i) - padding.push(i & 0xFF); - padding = Buffer.from(padding); - - let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); - let extra; - { - let pos = 0; - privBlob.set(checkInt, pos += 0); - privBlob.set(checkInt, pos += 4); - privBlob.set(parsed.priv, pos += 4); - privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); - privBlob.set(commentBin, pos += 4); - privBlob.set(padding, pos += commentBin.length); - } - - if (encrypted) { - const options = { authTagLength: encrypted.cipher.authLen }; - const cipher = createCipheriv( - encrypted.cipher.sslName, - encrypted.key, - encrypted.iv, - options - ); - cipher.setAutoPadding(false); - privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]); - if (encrypted.cipher.authLen > 0) - extra = cipher.getAuthTag(); - else - extra = Buffer.alloc(0); - encrypted.key.fill(0); - encrypted.iv.fill(0); - } else { - extra = Buffer.alloc(0); - } - - const magicBytes = Buffer.from('openssh-key-v1\0'); - const privBin = Buffer.allocUnsafe( - magicBytes.length - + 4 + cipherName.length - + 4 + kdfName.length - + 4 + kdfOptions.length - + 4 - + 4 + parsed.pub.length - + 4 + privBlob.length - + extra.length - ); - { - let pos = 0; - privBin.set(magicBytes, pos += 0); - privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); - privBin.set(cipherName, pos += 4); - privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); - privBin.set(kdfName, pos += 4); - privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); - privBin.set(kdfOptions, pos += 4); - privBin.writeUInt32BE(1, pos += kdfOptions.length); - privBin.writeUInt32BE(parsed.pub.length, pos += 4); - privBin.set(parsed.pub, pos += 4); - privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); - privBin.set(privBlob, pos += 4); - privBin.set(extra, pos += privBlob.length); - } - - { - const b64 = privBin.base64Slice(0, privBin.length); - let formatted = b64.replace(/.{64}/g, '$&\n'); - if (b64.length & 63) - formatted += '\n'; - privateB64 += formatted; - } - - { - const b64 = parsed.pub.base64Slice(0, parsed.pub.length); - publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`; - } - - privateB64 += '-----END OPENSSH PRIVATE KEY-----\n'; - return { - private: privateB64, - public: publicB64, - }; + catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyAuthenticationError)({ + error: err, + options, + }), + }; } - default: - throw new Error('Invalid output key format'); - } } - -function noop() {} - -module.exports = { - generateKeyPair: (keyType, opts, cb) => { - if (typeof opts === 'function') { - cb = opts; - opts = undefined; - } - if (typeof cb !== 'function') - cb = noop; - const args = makeArgs(keyType, opts); - generateKeyPair_(...args, (err, pub, priv) => { - if (err) - return cb(err); - let ret; - try { - ret = convertKeys(args[0], pub, priv, opts); - } catch (ex) { - return cb(ex); - } - cb(null, ret); - }); - }, - generateKeyPairSync: (keyType, opts) => { - const args = makeArgs(keyType, opts); - const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); - return convertKeys(args[0], pub, priv, opts); - } +exports.DEFAULT_CREATION_OPTIONS = { + hints: ['security-key'], + authenticatorSelection: { + authenticatorAttachment: 'cross-platform', + requireResidentKey: false, + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + residentKey: 'discouraged', + }, + attestation: 'none', }; - - -/***/ }), - -/***/ 59031: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - TODO: - * Replace `buffer._pos` usage in keyParser.js and elsewhere - * Utilize optional "writev" support when writing packets from - cipher.encrypt() - * Built-in support for automatic re-keying, on by default - * Revisit receiving unexpected/unknown packets - * Error (fatal or otherwise) or ignore or pass on to user (in some or all - cases)? - * Including server/client check for single directional packet types? - * Check packets for validity or bail as early as possible? - * Automatic re-key every 2**31 packets after the last key exchange (sent or - received), as suggested by RFC4344. OpenSSH currently does this. - * Automatic re-key every so many blocks depending on cipher. RFC4344: - Because of a birthday property of block ciphers and some modes of - operation, implementations must be careful not to encrypt too many - blocks with the same encryption key. - - Let L be the block length (in bits) of an SSH encryption method's - block cipher (e.g., 128 for AES). If L is at least 128, then, after - rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) - blocks before rekeying again. If L is at least 128, then SSH - implementations should also attempt to force a rekey before receiving - more than 2**(L/4) blocks. If L is less than 128 (which is the case - for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, - although it may be too expensive to rekey every 2**(L/4) blocks, it - is still advisable for SSH implementations to follow the original - recommendation in [RFC4253]: rekey at least once for every gigabyte - of transmitted data. - - Note that if L is less than or equal to 128, then the recommendation - in this subsection supersedes the recommendation in Section 3.1. If - an SSH implementation uses a block cipher with a larger block size - (e.g., Rijndael with 256-bit blocks), then the recommendations in - Section 3.1 may supersede the recommendations in this subsection - (depending on the lengths of the packets). -*/ - - - -const { inspect } = __nccwpck_require__(73837); - -const { bindingAvailable, NullCipher, NullDecipher } = __nccwpck_require__(45708); -const { - COMPAT_CHECKS, - DISCONNECT_REASON, - eddsaSupported, - MESSAGE, - SIGNALS, - TERMINAL_MODE, -} = __nccwpck_require__(36832); -const { - DEFAULT_KEXINIT_CLIENT, - DEFAULT_KEXINIT_SERVER, - KexInit, - kexinit, - onKEXPayload, -} = __nccwpck_require__(64126); -const { - parseKey, -} = __nccwpck_require__(22218); -const MESSAGE_HANDLERS = __nccwpck_require__(10172); -const { - bufferCopy, - bufferFill, - bufferSlice, - convertSignature, - sendPacket, - writeUInt32BE, -} = __nccwpck_require__(49475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(26715); - -const MODULE_VER = (__nccwpck_require__(66674)/* .version */ .i8); - -const VALID_DISCONNECT_REASONS = new Map( - Object.values(DISCONNECT_REASON).map((n) => [n, 1]) -); -const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); -const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); -const MAX_LINE_LEN = 8192; -const MAX_LINES = 1024; -const PING_PAYLOAD = Buffer.from([ - MESSAGE.GLOBAL_REQUEST, - // "keepalive@openssh.com" - 0, 0, 0, 21, - 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, - 115, 104, 46, 99, 111, 109, - // Request a reply - 1, -]); -const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); - -function noop() {} - -/* - Inbound: - * kexinit payload (needed only until exchange hash is generated) - * raw ident - * rekey packet queue - * expected packet (implemented as separate _parse() function?) - Outbound: - * kexinit payload (needed only until exchange hash is generated) - * rekey packet queue - * kex secret (needed only until NEWKEYS) - * exchange hash (needed only until NEWKEYS) - * session ID (set to exchange hash from initial handshake) -*/ -class Protocol { - constructor(config) { - const onWrite = config.onWrite; - if (typeof onWrite !== 'function') - throw new Error('Missing onWrite function'); - this._onWrite = (data) => { onWrite(data); }; - - const onError = config.onError; - if (typeof onError !== 'function') - throw new Error('Missing onError function'); - this._onError = (err) => { onError(err); }; - - const debug = config.debug; - this._debug = (typeof debug === 'function' - ? (msg) => { debug(msg); } - : undefined); - - const onHeader = config.onHeader; - this._onHeader = (typeof onHeader === 'function' - ? (...args) => { onHeader(...args); } - : noop); - - const onPacket = config.onPacket; - this._onPacket = (typeof onPacket === 'function' - ? () => { onPacket(); } - : noop); - - let onHandshakeComplete = config.onHandshakeComplete; - if (typeof onHandshakeComplete !== 'function') - onHandshakeComplete = noop; - let firstHandshake; - this._onHandshakeComplete = (...args) => { - this._debug && this._debug('Handshake completed'); - if (firstHandshake === undefined) - firstHandshake = true; - else - firstHandshake = false; - - // Process packets queued during a rekey where necessary - const oldQueue = this._queue; - if (oldQueue) { - this._queue = undefined; - this._debug && this._debug( - `Draining outbound queue (${oldQueue.length}) ...` - ); - for (let i = 0; i < oldQueue.length; ++i) { - const data = oldQueue[i]; - // data === payload only - - // XXX: hacky - let finalized = this._packetRW.write.finalize(data); - if (finalized === data) { - const packet = this._cipher.allocPacket(data.length); - packet.set(data, 5); - finalized = packet; - } - - sendPacket(this, finalized); +exports.DEFAULT_REQUEST_OPTIONS = { + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + hints: ['security-key'], +}; +function deepMerge(...sources) { + const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val); + const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); + const result = {}; + for (const source of sources) { + if (!source) + continue; + for (const key in source) { + const value = source[key]; + if (value === undefined) + continue; + if (Array.isArray(value)) { + // preserve array reference, including unions like AuthenticatorTransport[] + result[key] = value; + } + else if (isArrayBufferLike(value)) { + result[key] = value; + } + else if (isObject(value)) { + const existing = result[key]; + if (isObject(existing)) { + result[key] = deepMerge(existing, value); + } + else { + result[key] = deepMerge(value); + } + } + else { + result[key] = value; + } } - this._debug && this._debug('... finished draining outbound queue'); - } - - if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) - sendExtInfo(this); - - onHandshakeComplete(...args); - }; - this._queue = undefined; - - const messageHandlers = config.messageHandlers; - if (typeof messageHandlers === 'object' && messageHandlers !== null) - this._handlers = messageHandlers; - else - this._handlers = {}; - - this._onPayload = onPayload.bind(this); - - this._server = !!config.server; - this._banner = undefined; - let greeting; - if (this._server) { - if (typeof config.hostKeys !== 'object' || config.hostKeys === null) - throw new Error('Missing server host key(s)'); - this._hostKeys = config.hostKeys; - - // Greeting displayed before the ssh identification string is sent, this - // is usually ignored by most clients - if (typeof config.greeting === 'string' && config.greeting.length) { - greeting = (config.greeting.slice(-2) === '\r\n' - ? config.greeting - : `${config.greeting}\r\n`); - } - - // Banner shown after the handshake completes, but before user - // authentication begins - if (typeof config.banner === 'string' && config.banner.length) { - this._banner = (config.banner.slice(-2) === '\r\n' - ? config.banner - : `${config.banner}\r\n`); - } - } else { - this._hostKeys = undefined; - } - - let offer = config.offer; - if (typeof offer !== 'object' || offer === null) { - offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT); - } else if (offer.constructor !== KexInit) { - if (this._server) { - offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']); - } else { - offer.kex = offer.kex.concat([ - 'ext-info-c', - 'kex-strict-c-v00@openssh.com', - ]); - } - offer = new KexInit(offer); - } - this._kex = undefined; - this._strictMode = undefined; - this._kexinit = undefined; - this._offer = offer; - this._cipher = new NullCipher(0, this._onWrite); - this._decipher = undefined; - this._skipNextInboundPacket = false; - this._packetRW = { - read: new PacketReader(), - write: new PacketWriter(this), - }; - this._hostVerifier = (!this._server - && typeof config.hostVerifier === 'function' - ? config.hostVerifier - : undefined); - - this._parse = parseHeader; - this._buffer = undefined; - this._authsQueue = []; - this._authenticated = false; - this._remoteIdentRaw = undefined; - let sentIdent; - if (typeof config.ident === 'string') { - this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); - - sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); - sentIdent.set(this._identRaw, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else if (Buffer.isBuffer(config.ident)) { - const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); - fullIdent.latin1Write('SSH-2.0-', 0, 8); - fullIdent.set(config.ident, 8); - this._identRaw = fullIdent; - - sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); - sentIdent.set(fullIdent, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else { - this._identRaw = IDENT_RAW; - sentIdent = IDENT; - } - this._compatFlags = 0; - - if (this._debug) { - if (bindingAvailable) - this._debug('Custom crypto binding available'); - else - this._debug('Custom crypto binding not available'); - } - - this._debug && this._debug( - `Local ident: ${inspect(this._identRaw.toString())}` - ); - this.start = () => { - this.start = undefined; - if (greeting) - this._onWrite(greeting); - this._onWrite(sentIdent); - }; - } - _destruct(reason) { - this._packetRW.read.cleanup(); - this._packetRW.write.cleanup(); - this._cipher && this._cipher.free(); - this._decipher && this._decipher.free(); - if (typeof reason !== 'string' || reason.length === 0) - reason = 'fatal error'; - this.parse = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._onWrite = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._destruct = undefined; - } - cleanup() { - this._destruct && this._destruct(); - } - parse(chunk, i, len) { - while (i < len) - i = this._parse(chunk, i, len); - } - - // Protocol message API - - // =========================================================================== - // Common/Shared ============================================================= - // =========================================================================== - - // Global - // ------ - disconnect(reason) { - const pktLen = 1 + 4 + 4 + 4; - // We don't use _packetRW.write.* here because we need to make sure that - // we always get a full packet allocated because this message can be sent - // at any time -- even during a key exchange - let p = this._packetRW.write.allocStartKEX; - const packet = this._packetRW.write.alloc(pktLen, true); - const end = p + pktLen; - - if (!VALID_DISCONNECT_REASONS.has(reason)) - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - - packet[p] = MESSAGE.DISCONNECT; - writeUInt32BE(packet, reason, ++p); - packet.fill(0, p += 4, end); - - this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); - sendPacket(this, this._packetRW.write.finalize(packet, true), true); - } - ping() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); - - packet.set(PING_PAYLOAD, p); - - this._debug && this._debug( - 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - rekey() { - if (this._kexinit === undefined) { - this._debug && this._debug('Outbound: Initiated explicit rekey'); - this._queue = []; - kexinit(this); - } else { - this._debug && this._debug('Outbound: Ignoring rekey during handshake'); - } - } - - // 'ssh-connection' service-specific - // --------------------------------- - requestSuccess(data) { - let p = this._packetRW.write.allocStart; - let packet; - if (Buffer.isBuffer(data)) { - packet = this._packetRW.write.alloc(1 + data.length); - - packet[p] = MESSAGE.REQUEST_SUCCESS; - - packet.set(data, ++p); - } else { - packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_SUCCESS; } - - this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - requestFailure() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_FAILURE; - - this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelSuccess(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_SUCCESS; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelFailure(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_FAILURE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelEOF(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_EOF; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelClose(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_CLOSE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelWindowAdjust(chan, amount) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, amount, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelData(chan, data) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelExtData(chan, data, type) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, type, p += 4); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenConfirm(remote, local, initWindow, maxPacket) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, local, p += 4); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenFail(remote, reason, desc) { - if (typeof desc !== 'string') - desc = ''; - - const descLen = Buffer.byteLength(desc); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, reason, p += 4); - - writeUInt32BE(packet, descLen, p += 4); - - p += 4; - if (descLen) { - packet.utf8Write(desc, p, descLen); - p += descLen; + return result; +} +/** + * Merges WebAuthn credential creation options with overrides. + * Sets sensible defaults for authenticator selection and extensions. + * + * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply + * @param {string} friendlyName - Optional friendly name for the credential + * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} + */ +function mergeCredentialCreationOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); +} +/** + * Merges WebAuthn credential request options with overrides. + * Sets sensible defaults for user verification and hints. + * + * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply + * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + */ +function mergeCredentialRequestOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); +} +/** + * WebAuthn API wrapper for Supabase Auth. + * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. + * + * @experimental This API is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} + */ +class WebAuthnApi { + constructor(client) { + this.client = client; + // Bind all methods so they can be destructured + this.enroll = this._enroll.bind(this); + this.challenge = this._challenge.bind(this); + this.verify = this._verify.bind(this); + this.authenticate = this._authenticate.bind(this); + this.register = this._register.bind(this); } - - writeUInt32BE(packet, 0, p); // Empty language tag - - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - - // Global - // ------ - service(name) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + nameLen); - - packet[p] = MESSAGE.SERVICE_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-userauth' service-specific - // ------------------------------- - authPassword(username, password, newPassword) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - const passLen = Buffer.byteLength(password); - const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen - + (newPassword ? 4 + newPassLen : 0) - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 8, p += 14); - packet.utf8Write('password', p += 4, 8); - - packet[p += 8] = (newPassword ? 1 : 0); - - writeUInt32BE(packet, passLen, ++p); - if (Buffer.isBuffer(password)) - bufferCopy(password, packet, 0, passLen, p += 4); - else - packet.utf8Write(password, p += 4, passLen); - - if (newPassword) { - writeUInt32BE(packet, newPassLen, p += passLen); - if (Buffer.isBuffer(newPassword)) - bufferCopy(newPassword, packet, 0, newPassLen, p += 4); - else - packet.utf8Write(newPassword, p += 4, newPassLen); - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (changed password)' - ); - } else { - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (password)' - ); + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + async _enroll(params) { + return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' })); } - - this._authsQueue.push('password'); - - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPK(username, pubKey, keyAlgo, cbSign) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - if (typeof keyAlgo === 'function') { - cbSign = keyAlgo; - keyAlgo = undefined; - } - if (!keyAlgo) - keyAlgo = keyType; - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyAlgo); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const payloadLen = - (cbSign ? 4 + sesLen : 0) - + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; - let packet; - let p; - if (cbSign) { - packet = Buffer.allocUnsafe(payloadLen); - p = 0; - writeUInt32BE(packet, sesLen, p); - packet.set(sessionID, p += 4); - p += sesLen; - } else { - packet = this._packetRW.write.alloc(payloadLen); - p = this._packetRW.write.allocStart; + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) { + try { + // Get challenge from server using the client's MFA methods + const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ + factorId, + webauthn, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal(); + /** webauthn will fail if either of the name/displayname are blank */ + if (challengeResponse.webauthn.type === 'create') { + const { user } = challengeResponse.webauthn.credential_options.publicKey; + if (!user.name) { + user.name = `${user.id}:${friendlyName}`; + } + if (!user.displayName) { + user.displayName = user.name; + } + } + switch (challengeResponse.webauthn.type) { + case 'create': { + const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); + const { data, error } = await createCredential({ + publicKey: options, + signal: abortSignal, + }); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + case 'request': { + const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); + const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + } + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in challenge', error), + }; + } } - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = (cbSign ? 1 : 0); - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - if (!cbSign) { - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - return; + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + async _verify({ challengeId, factorId, webauthn, }) { + return this.client.mfa.verify({ + factorId, + challengeId, + webauthn: webauthn, + }); } - - cbSign(packet, (signature) => { - signature = convertSignature(signature, keyType); - if (signature === false) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - p = this._packetRW.write.allocStart; - packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 - + 4 + algoLen + 4 + sigLen - ); - - // TODO: simply copy from original "packet" to new `packet` to avoid - // having to write each individual field a second time? - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = 1; - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); - - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - // Servers shouldn't send packet type 60 in response to signed publickey - // attempts, but if they do, interpret as type 60. - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { - // TODO: Make DRY by sharing similar code with authPK() - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - if (typeof keyAlgo === 'function') { - cbSign = keyAlgo; - keyAlgo = undefined; - } - if (!keyAlgo) - keyAlgo = keyType; - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyAlgo); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const hostnameLen = Buffer.byteLength(hostname); - const userlocalLen = Buffer.byteLength(userlocal); - const data = Buffer.allocUnsafe( - 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen - + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen - ); - let p = 0; - - writeUInt32BE(data, sesLen, p); - data.set(sessionID, p += 4); - - data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(data, userLen, ++p); - data.utf8Write(username, p += 4, userLen); - - writeUInt32BE(data, 14, p += userLen); - data.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(data, 9, p += 14); - data.utf8Write('hostbased', p += 4, 9); - - writeUInt32BE(data, algoLen, p += 9); - data.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(data, pubKeyLen, p += algoLen); - data.set(pubKey, p += 4); - - writeUInt32BE(data, hostnameLen, p += pubKeyLen); - data.utf8Write(hostname, p += 4, hostnameLen); - - writeUInt32BE(data, userlocalLen, p += hostnameLen); - data.utf8Write(userlocal, p += 4, userlocalLen); - - cbSign(data, (signature) => { - signature = convertSignature(signature, keyType); - if (!signature) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - const reqDataLen = (data.length - sesLen - 4); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - reqDataLen + 4 + 4 + algoLen + 4 + sigLen - ); - - bufferCopy(data, packet, 4 + sesLen, data.length, p); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyAlgo, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - this._authsQueue.push('hostbased'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (hostbased)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authKeyboard(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 20, p += 14); - packet.utf8Write('keyboard-interactive', p += 4, 20); - - writeUInt32BE(packet, 0, p += 20); - - writeUInt32BE(packet, 0, p += 4); - - this._authsQueue.push('keyboard-interactive'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authNone(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 4, p += 14); - packet.utf8Write('none', p += 4, 4); - - this._authsQueue.push('none'); - - this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoRes(responses) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let responsesTotalLen = 0; - let responseLens; - - if (responses) { - responseLens = new Array(responses.length); - for (let i = 0; i < responses.length; ++i) { - const len = Buffer.byteLength(responses[i]); - responseLens[i] = len; - responsesTotalLen += 4 + len; - } + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError('rpId is required for WebAuthn authentication'), + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), + }; + } + // Get challenge and credential + const { data: challengeResponse, error: challengeError } = await this.challenge({ + factorId, + webauthn: { rpId, rpOrigins }, + signal, + }, { request: overrides }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const { webauthn } = challengeResponse; + // Verify credential + return this._verify({ + factorId, + challengeId: challengeResponse.challengeId, + webauthn: { + type: webauthn.type, + rpId, + rpOrigins, + credential_response: webauthn.credential_response, + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in authenticate', error), + }; + } } - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); - - packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; - - if (responses) { - writeUInt32BE(packet, responses.length, ++p); - p += 4; - for (let i = 0; i < responses.length; ++i) { - const len = responseLens[i]; - writeUInt32BE(packet, len, p); - p += 4; - if (len) { - packet.utf8Write(responses[i], p, len); - p += len; + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + async _register({ friendlyName, rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError('rpId is required for WebAuthn registration'), + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), + }; + } + // Enroll factor + const { data: factor, error: enrollError } = await this._enroll({ + friendlyName, + }); + if (!factor) { + await this.client.mfa + .listFactors() + .then((factors) => { + var _a; + return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' && + v.friendly_name === friendlyName && + v.status !== 'unverified'); + }) + .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0)); + return { data: null, error: enrollError }; + } + // Get challenge and create credential + const { data: challengeResponse, error: challengeError } = await this._challenge({ + factorId: factor.id, + friendlyName: factor.friendly_name, + webauthn: { rpId, rpOrigins }, + signal, + }, { + create: overrides, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + return this._verify({ + factorId: factor.id, + challengeId: challengeResponse.challengeId, + webauthn: { + rpId, + rpOrigins, + type: challengeResponse.webauthn.type, + credential_response: challengeResponse.webauthn.credential_response, + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in register', error), + }; } - } - } else { - writeUInt32BE(packet, 0, ++p); } +} +exports.WebAuthnApi = WebAuthnApi; +//# sourceMappingURL=webauthn.js.map - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-connection' service-specific - // --------------------------------- - tcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 13, ++p); - packet.utf8Write('tcpip-forward', p += 4, 13); - - packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - cancelTcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 20, ++p); - packet.utf8Write('cancel-tcpip-forward', p += 4, 20); - - packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_streamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 31 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 31, ++p); - packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); - - packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_cancelStreamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 38 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 38, ++p); - packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); +/***/ }), - packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); +/***/ 9904: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); +"use strict"; - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST ' - + '(cancel-streamlocal-forward@openssh.com)' - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FunctionsClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +const helper_1 = __nccwpck_require__(618); +const types_1 = __nccwpck_require__(3136); +class FunctionsClient { + constructor(url, { headers = {}, customFetch, region = types_1.FunctionRegion.Any, } = {}) { + this.url = url; + this.headers = headers; + this.region = region; + this.fetch = (0, helper_1.resolveFetch)(customFetch); } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - directTcpip(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const srcLen = Buffer.byteLength(cfg.srcIP); - const dstLen = Buffer.byteLength(cfg.dstIP); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 12, ++p); - packet.utf8Write('direct-tcpip', p += 4, 12); - - writeUInt32BE(packet, chan, p += 12); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, dstLen, p += 4); - packet.utf8Write(cfg.dstIP, p += 4, dstLen); - - writeUInt32BE(packet, cfg.dstPort, p += dstLen); - - writeUInt32BE(packet, srcLen, p += 4); - packet.utf8Write(cfg.srcIP, p += 4, srcLen); - - writeUInt32BE(packet, cfg.srcPort, p += srcLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 30, ++p); - packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); - - writeUInt32BE(packet, chan, p += 30); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - // zero-fill reserved fields (string and uint32) - bufferFill(packet, 0, p += pathLen, p + 8); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, direct-streamlocal@openssh.com)` - ); + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_noMoreSessions(wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 28, ++p); - packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); - - packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - session(chan, initWindow, maxPacket) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 7, ++p); - packet.utf8Write('session', p += 4, 7); - - writeUInt32BE(packet, chan, p += 7); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - windowChange(chan, rows, cols, height, width) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 13, p += 4); - packet.utf8Write('window-change', p += 4, 13); - - packet[p += 13] = 0; - - writeUInt32BE(packet, cols, ++p); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - pty(chan, rows, cols, height, width, term, modes, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - if (!term || !term.length) - term = 'vt100'; - if (modes - && !Buffer.isBuffer(modes) - && !Array.isArray(modes) - && typeof modes === 'object' - && modes !== null) { - modes = modesToBytes(modes); - } - if (!modes || !modes.length) - modes = NO_TERMINAL_MODES_BUFFER; - - const termLen = term.length; - const modesLen = modes.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('pty-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, termLen, ++p); - packet.utf8Write(term, p += 4, termLen); - - writeUInt32BE(packet, cols, p += termLen); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); - - writeUInt32BE(packet, modesLen, p += 4); - p += 4; - if (Array.isArray(modes)) { - for (let i = 0; i < modesLen; ++i) - packet[p++] = modes[i]; - } else if (Buffer.isBuffer(modes)) { - packet.set(modes, p); + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + invoke(functionName_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) { + var _a; + try { + const { headers, method, body: functionArgs, signal } = options; + let _headers = {}; + let { region } = options; + if (!region) { + region = this.region; + } + // Add region as query parameter using URL API + const url = new URL(`${this.url}/${functionName}`); + if (region && region !== 'any') { + _headers['x-region'] = region; + url.searchParams.set('forceFunctionRegion', region); + } + let body; + if (functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { + if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream'; + body = functionArgs; + } + else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain'; + body = functionArgs; + } + else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs; + } + else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json'; + body = JSON.stringify(functionArgs); + } + } + else { + // if the Content-Type was supplied, simply set the body + body = functionArgs; + } + const response = yield this.fetch(url.toString(), { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + signal, + }).catch((fetchError) => { + if (fetchError.name === 'AbortError') { + throw fetchError; + } + throw new types_1.FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get('x-relay-error'); + if (isRelayError && isRelayError === 'true') { + throw new types_1.FunctionsRelayError(response); + } + if (!response.ok) { + throw new types_1.FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); + let data; + if (responseType === 'application/json') { + data = yield response.json(); + } + else if (responseType === 'application/octet-stream' || + responseType === 'application/pdf') { + data = yield response.blob(); + } + else if (responseType === 'text/event-stream') { + data = response; + } + else if (responseType === 'multipart/form-data') { + data = yield response.formData(); + } + else { + // default to text + data = yield response.text(); + } + return { data, error: null, response }; + } + catch (error) { + if (error instanceof Error && error.name === 'AbortError') { + return { data: null, error: new types_1.FunctionsFetchError(error) }; + } + return { + data: null, + error, + response: error instanceof types_1.FunctionsHttpError || error instanceof types_1.FunctionsRelayError + ? error.context + : undefined, + }; + } + }); } +} +exports.FunctionsClient = FunctionsClient; +//# sourceMappingURL=FunctionsClient.js.map - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - shell(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 5, p += 4); - packet.utf8Write('shell', p += 4, 5); - - packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exec(chan, cmd, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const isBuf = Buffer.isBuffer(cmd); - const cmdLen = (isBuf ? cmd.length : Buffer.byteLength(cmd)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + cmdLen); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 4, p += 4); - packet.utf8Write('exec', p += 4, 4); - - packet[p += 4] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, cmdLen, ++p); - if (isBuf) - packet.set(cmd, p += 4); - else - packet.utf8Write(cmd, p += 4, cmdLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - signal(chan, signal) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const origSignal = signal; - - signal = signal.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - - const signalLen = signal.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 6 + 1 + 4 + signalLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 6, p += 4); - packet.utf8Write('signal', p += 4, 6); - - packet[p += 6] = 0; - - writeUInt32BE(packet, signalLen, ++p); - packet.utf8Write(signal, p += 4, signalLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - env(chan, key, val, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const keyLen = Buffer.byteLength(key); - const isBuf = Buffer.isBuffer(val); - const valLen = (isBuf ? val.length : Buffer.byteLength(val)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 3, p += 4); - packet.utf8Write('env', p += 4, 3); - - packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, keyLen, ++p); - packet.utf8Write(key, p += 4, keyLen); - - writeUInt32BE(packet, valLen, p += keyLen); - if (isBuf) - packet.set(val, p += 4); - else - packet.utf8Write(val, p += 4, valLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11Forward(chan, cfg, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const protocol = cfg.protocol; - const cookie = cfg.cookie; - const isBufProto = Buffer.isBuffer(protocol); - const protoLen = (isBufProto - ? protocol.length - : Buffer.byteLength(protocol)); - const isBufCookie = Buffer.isBuffer(cookie); - const cookieLen = (isBufCookie - ? cookie.length - : Buffer.byteLength(cookie)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('x11-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - packet[++p] = (cfg.single ? 1 : 0); - - writeUInt32BE(packet, protoLen, ++p); - if (isBufProto) - packet.set(protocol, p += 4); - else - packet.utf8Write(protocol, p += 4, protoLen); - - writeUInt32BE(packet, cookieLen, p += protoLen); - if (isBufCookie) - packet.set(cookie, p += 4); - else - packet.latin1Write(cookie, p += 4, cookieLen); - - writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); +/***/ }), - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - subsystem(chan, name, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +/***/ 618: +/***/ ((__unused_webpack_module, exports) => { - // Does not consume window space - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); +"use strict"; - packet[p] = MESSAGE.CHANNEL_REQUEST; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +//# sourceMappingURL=helper.js.map - writeUInt32BE(packet, chan, ++p); +/***/ }), - writeUInt32BE(packet, 9, p += 4); - packet.utf8Write('subsystem', p += 4, 9); +/***/ 8519: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); +"use strict"; - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FunctionRegion = exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; +var FunctionsClient_1 = __nccwpck_require__(9904); +Object.defineProperty(exports, "FunctionsClient", ({ enumerable: true, get: function () { return FunctionsClient_1.FunctionsClient; } })); +var types_1 = __nccwpck_require__(3136); +Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return types_1.FunctionsError; } })); +Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return types_1.FunctionsFetchError; } })); +Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return types_1.FunctionsHttpError; } })); +Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return types_1.FunctionsRelayError; } })); +Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return types_1.FunctionRegion; } })); +//# sourceMappingURL=index.js.map - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_agentForward(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); +/***/ }), - // Does not consume window space +/***/ 3136: +/***/ ((__unused_webpack_module, exports) => { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); +"use strict"; - packet[p] = MESSAGE.CHANNEL_REQUEST; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; +class FunctionsError extends Error { + constructor(message, name = 'FunctionsError', context) { + super(message); + this.name = name; + this.context = context; + } +} +exports.FunctionsError = FunctionsError; +class FunctionsFetchError extends FunctionsError { + constructor(context) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); + } +} +exports.FunctionsFetchError = FunctionsFetchError; +class FunctionsRelayError extends FunctionsError { + constructor(context) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); + } +} +exports.FunctionsRelayError = FunctionsRelayError; +class FunctionsHttpError extends FunctionsError { + constructor(context) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); + } +} +exports.FunctionsHttpError = FunctionsHttpError; +// Define the enum for the 'region' property +var FunctionRegion; +(function (FunctionRegion) { + FunctionRegion["Any"] = "any"; + FunctionRegion["ApNortheast1"] = "ap-northeast-1"; + FunctionRegion["ApNortheast2"] = "ap-northeast-2"; + FunctionRegion["ApSouth1"] = "ap-south-1"; + FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; + FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; + FunctionRegion["CaCentral1"] = "ca-central-1"; + FunctionRegion["EuCentral1"] = "eu-central-1"; + FunctionRegion["EuWest1"] = "eu-west-1"; + FunctionRegion["EuWest2"] = "eu-west-2"; + FunctionRegion["EuWest3"] = "eu-west-3"; + FunctionRegion["SaEast1"] = "sa-east-1"; + FunctionRegion["UsEast1"] = "us-east-1"; + FunctionRegion["UsWest1"] = "us-west-1"; + FunctionRegion["UsWest2"] = "us-west-2"; +})(FunctionRegion || (exports.FunctionRegion = FunctionRegion = {})); +//# sourceMappingURL=types.js.map - writeUInt32BE(packet, chan, ++p); +/***/ }), - writeUInt32BE(packet, 26, p += 4); - packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); +/***/ 1049: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); +"use strict"; - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_REQUEST ' - + `(r:${chan}, auth-agent-req@openssh.com)` - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(7317)); +class PostgrestBuilder { + constructor(builder) { + var _a, _b; + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = new Headers(builder.headers); + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = (_a = builder.shouldThrowOnError) !== null && _a !== void 0 ? _a : false; + this.signal = builder.signal; + this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false; + if (builder.fetch) { + this.fetch = builder.fetch; + } + else { + this.fetch = fetch; + } + } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Set an HTTP header for the request. + */ + setHeader(name, value) { + this.headers = new Headers(this.headers); + this.headers.set(name, value); + return this; + } + then(onfulfilled, onrejected) { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) { + // skip + } + else if (['GET', 'HEAD'].includes(this.method)) { + this.headers.set('Accept-Profile', this.schema); + } + else { + this.headers.set('Content-Profile', this.schema); + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers.set('Content-Type', 'application/json'); + } + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + var _a, _b, _c, _d; + let error = null; + let data = null; + let count = null; + let status = res.status; + let statusText = res.statusText; + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text(); + if (body === '') { + // Prefer: return=minimal + } + else if (this.headers.get('Accept') === 'text/csv') { + data = body; + } + else if (this.headers.get('Accept') && + ((_a = this.headers.get('Accept')) === null || _a === void 0 ? void 0 : _a.includes('application/vnd.pgrst.plan+text'))) { + data = body; + } + else { + data = JSON.parse(body); + } + } + const countHeader = (_b = this.headers.get('Prefer')) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/); + const contentRange = (_c = res.headers.get('content-range')) === null || _c === void 0 ? void 0 : _c.split('/'); + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]); + } + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + }; + data = null; + count = null; + status = 406; + statusText = 'Not Acceptable'; + } + else if (data.length === 1) { + data = data[0]; + } + else { + data = null; + } + } + } + else { + const body = await res.text(); + try { + error = JSON.parse(body); + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = []; + error = null; + status = 200; + statusText = 'OK'; + } + } + catch (_e) { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204; + statusText = 'No Content'; + } + else { + error = { + message: body, + }; + } + } + if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes('0 rows'))) { + error = null; + status = 200; + statusText = 'OK'; + } + if (error && this.shouldThrowOnError) { + throw new PostgrestError_1.default(error); + } + } + const postgrestResponse = { + error, + data, + count, + status, + statusText, + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a, _b, _c; + return ({ + error: { + message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, + hint: '', + code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, + }, + data: null, + count: null, + status: 0, + statusText: '', + }); + }); + } + return res.then(onfulfilled, onrejected); } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_hostKeysProve(keys) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let keysTotal = 0; - const publicKeys = []; - for (const key of keys) { - const publicKey = key.getPublicSSH(); - keysTotal += 4 + publicKey.length; - publicKeys.push(publicKey); + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + /* istanbul ignore next */ + return this; } + /** + * Override the type of the returned `data` field in the response. + * + * @typeParam NewResult - The new type to cast the response data to + * @typeParam Options - Optional type configuration (defaults to { merge: true }) + * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) + * @example + * ```typescript + * // Merge with existing types (default behavior) + * const query = supabase + * .from('users') + * .select() + * .overrideTypes<{ custom_field: string }>() + * + * // Replace existing types completely + * const replaceQuery = supabase + * .from('users') + * .select() + * .overrideTypes<{ id: number; name: string }, { merge: false }>() + * ``` + * @returns A PostgrestBuilder instance with the new type + */ + overrideTypes() { + return this; + } +} +exports["default"] = PostgrestBuilder; +//# sourceMappingURL=PostgrestBuilder.js.map - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); - - packet[p] = MESSAGE.GLOBAL_REQUEST; +/***/ }), - writeUInt32BE(packet, 29, ++p); - packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); +/***/ 1526: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - packet[p += 29] = 1; // want reply +"use strict"; - ++p; - for (const buf of publicKeys) { - writeUInt32BE(packet, buf.length, p); - bufferCopy(buf, packet, 0, buf.length, p += 4); - p += buf.length; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50)); +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +class PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor(url, { headers = {}, schema, fetch, } = {}) { + this.url = url; + this.headers = new Headers(headers); + this.schemaName = schema; + this.fetch = fetch; } - - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' - ); + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder_1.default(url, { + headers: new Headers(this.headers), + schema: this.schemaName, + fetch: this.fetch, + }); } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - - // Global - // ------ - serviceAccept(svcName) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const svcNameLen = Buffer.byteLength(svcName); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); - - packet[p] = MESSAGE.SERVICE_ACCEPT; - - writeUInt32BE(packet, svcNameLen, ++p); - packet.utf8Write(svcName, p += 4, svcNameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._server && this._banner && svcName === 'ssh-userauth') { - const banner = this._banner; - this._banner = undefined; // Prevent banner from being displayed again - const bannerLen = Buffer.byteLength(banner); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); - - packet[p] = MESSAGE.USERAUTH_BANNER; - - writeUInt32BE(packet, bannerLen, ++p); - packet.utf8Write(banner, p += 4, bannerLen); - - writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); - sendPacket(this, this._packetRW.write.finalize(packet)); + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return new PostgrestClient(this.url, { + headers: this.headers, + schema, + fetch: this.fetch, + }); } - } - // 'ssh-connection' service-specific - forwardedTcpip(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const boundAddrLen = Buffer.byteLength(cfg.boundAddr); - const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 15, ++p); - packet.utf8Write('forwarded-tcpip', p += 4, 15); - - writeUInt32BE(packet, chan, p += 15); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, boundAddrLen, p += 4); - packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); - - writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); - - writeUInt32BE(packet, remoteAddrLen, p += 4); - packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); - - writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const addrLen = Buffer.byteLength(cfg.originAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 3, ++p); - packet.utf8Write('x11', p += 4, 3); - - writeUInt32BE(packet, chan, p += 3); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, addrLen, p += 4); - packet.utf8Write(cfg.originAddr, p += 4, addrLen); - - writeUInt32BE(packet, cfg.originPort, p += addrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_authAgent(chan, initWindow, maxPacket) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 22, ++p); - packet.utf8Write('auth-agent@openssh.com', p += 4, 22); - - writeUInt32BE(packet, chan, p += 22); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 33, ++p); - packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); - - writeUInt32BE(packet, chan, p += 33); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - writeUInt32BE(packet, 0, p += pathLen); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, forwarded-streamlocal@openssh.com)` - ); + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, { head = false, get = false, count, } = {}) { + var _a; + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head || get) { + method = head ? 'HEAD' : 'GET'; + Object.entries(args) + // params with undefined value needs to be filtered out, otherwise it'll + // show up as `?param=undefined` + .filter(([_, value]) => value !== undefined) + // array values need special syntax + .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) + .forEach(([name, value]) => { + url.searchParams.append(name, value); + }); + } + else { + method = 'POST'; + body = args; + } + const headers = new Headers(this.headers); + if (count) { + headers.set('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url, + headers, + schema: this.schemaName, + body, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitStatus(chan, status) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-status', p += 4, 11); - - packet[p += 11] = 0; - - writeUInt32BE(packet, status, ++p); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - exitSignal(chan, name, coreDumped, msg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - - const origSignal = name; - - if (typeof origSignal !== 'string' || !origSignal) - throw new Error(`Invalid signal: ${origSignal}`); - - let signal = name.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - - const nameLen = Buffer.byteLength(signal); - const msgLen = (msg ? Buffer.byteLength(msg) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-signal', p += 4, 11); - - packet[p += 11] = 0; +} +exports["default"] = PostgrestClient; +//# sourceMappingURL=PostgrestClient.js.map - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(signal, p += 4, nameLen); +/***/ }), - packet[p += nameLen] = (coreDumped ? 1 : 0); +/***/ 7317: +/***/ ((__unused_webpack_module, exports) => { - writeUInt32BE(packet, msgLen, ++p); +"use strict"; - p += 4; - if (msgLen) { - packet.utf8Write(msg, p, msgLen); - p += msgLen; +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Error format + * + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} + */ +class PostgrestError extends Error { + constructor(context) { + super(context.message); + this.name = 'PostgrestError'; + this.details = context.details; + this.hint = context.hint; + this.code = context.code; } +} +exports["default"] = PostgrestError; +//# sourceMappingURL=PostgrestError.js.map - writeUInt32BE(packet, 0, p); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // 'ssh-userauth' service-specific - authFailure(authMethods, isPartial) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +/***/ }), - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); +/***/ 6671: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let methods; +"use strict"; - if (typeof authMethods === 'boolean') { - isPartial = authMethods; - authMethods = undefined; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1566)); +const PostgrestReservedCharsRegexp = new RegExp('[,()]'); +class PostgrestFilterBuilder extends PostgrestTransformBuilder_1.default { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; } - - if (authMethods) { - methods = []; - for (let i = 0; i < authMethods.length; ++i) { - if (authMethods[i].toLowerCase() === 'none') - continue; - methods.push(authMethods[i]); - } - methods = methods.join(','); - } else { - methods = ''; + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; } - - const methodsLen = methods.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); - - packet[p] = MESSAGE.USERAUTH_FAILURE; - - writeUInt32BE(packet, methodsLen, ++p); - packet.utf8Write(methods, p += 4, methodsLen); - - packet[p += methodsLen] = (isPartial === true ? 1 : 0); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authSuccess() { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); - - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.USERAUTH_SUCCESS; - - this._authsQueue.shift(); - this._authenticated = true; - - this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - } - authPKOK(keyAlgo, key) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') - throw new Error('"publickey" auth not in progress'); - - // TODO: support parsed key for `key` - - const keyAlgoLen = Buffer.byteLength(keyAlgo); - const keyLen = key.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); - - packet[p] = MESSAGE.USERAUTH_PK_OK; - - writeUInt32BE(packet, keyAlgoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); - - writeUInt32BE(packet, keyLen, p += keyAlgoLen); - packet.set(key, p += 4); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPasswdChg(prompt) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const promptLen = Buffer.byteLength(prompt); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - - packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; - - writeUInt32BE(packet, promptLen, ++p); - packet.utf8Write(prompt, p += 4, promptLen); - - writeUInt32BE(packet, 0, p += promptLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoReq(name, instructions, prompts) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let promptsLen = 0; - const nameLen = name ? Buffer.byteLength(name) : 0; - const instrLen = instructions ? Buffer.byteLength(instructions) : 0; - - for (let i = 0; i < prompts.length; ++i) - promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen - ); - - packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - p += 4; - if (name) { - packet.utf8Write(name, p, nameLen); - p += nameLen; + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; } - - writeUInt32BE(packet, instrLen, p); - p += 4; - if (instructions) { - packet.utf8Write(instructions, p, instrLen); - p += instrLen; + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; + } + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; + } + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = Array.from(new Set(values)) + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) + return `"${s}"`; + else + return `${s}`; + }) + .join(','); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; } - - writeUInt32BE(packet, 0, p); - - writeUInt32BE(packet, prompts.length, p += 4); - p += 4; - for (let i = 0; i < prompts.length; ++i) { - const prompt = prompts[i]; - const promptLen = Buffer.byteLength(prompt.prompt); - - writeUInt32BE(packet, promptLen, p); - p += 4; - if (promptLen) { - packet.utf8Write(prompt.prompt, p, promptLen); - p += promptLen; - } - packet[p++] = (prompt.echo ? 1 : 0); + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; } - - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } -} - -// SSH-protoversion-softwareversion (SP comments) CR LF -const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; - -// TODO: optimize this by starting n bytes from the end of this._buffer instead -// of the beginning -function parseHeader(chunk, p, len) { - let data; - let chunkOffset; - if (this._buffer) { - data = Buffer.allocUnsafe(this._buffer.length + (len - p)); - data.set(this._buffer, 0); - if (p === 0) { - data.set(chunk, this._buffer.length); - } else { - data.set(new Uint8Array(chunk.buffer, - chunk.byteOffset + p, - (len - p)), - this._buffer.length); + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; } - chunkOffset = this._buffer.length; - p = 0; - } else { - data = chunk; - chunkOffset = 0; - } - const op = p; - let start = p; - let end = p; - let needNL = false; - let lineLen = 0; - let lines = 0; - for (; p < data.length; ++p) { - const ch = data[p]; - - if (ch === 13 /* '\r' */) { - needNL = true; - continue; + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; } - - if (ch === 10 /* '\n' */) { - if (end > start - && end - start > 4 - && data[start] === 83 /* 'S' */ - && data[start + 1] === 83 /* 'S' */ - && data[start + 2] === 72 /* 'H' */ - && data[start + 3] === 45 /* '-' */) { - - const full = data.latin1Slice(op, end + 1); - const identRaw = (start === op ? full : full.slice(start - op)); - const m = RE_IDENT.exec(identRaw); - if (!m) - throw new Error('Invalid identification string'); - - const header = { - greeting: (start === op ? '' : full.slice(0, start - op)), - identRaw, - versions: { - protocol: m[1], - software: m[2], - }, - comments: m[3] - }; - - // Needed during handshake - this._remoteIdentRaw = Buffer.from(identRaw); - - this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); - this._compatFlags = getCompatFlags(header); - - this._buffer = undefined; - this._decipher = - new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); - this._parse = parsePacket; - - this._onHeader(header); - if (!this._destruct) { - // We disconnected inside _onHeader - return len; - } - - kexinit(this); - - return p + 1 - chunkOffset; - } - - // Only allow pre-ident greetings when we're a client - if (this._server) - throw new Error('Greetings from clients not permitted'); - - if (++lines > MAX_LINES) - throw new Error('Max greeting lines exceeded'); - - needNL = false; - start = p + 1; - lineLen = 0; - } else if (needNL) { - throw new Error('Invalid header: expected newline'); - } else if (++lineLen >= MAX_LINE_LEN) { - throw new Error('Header line too long'); + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; } - - end = p; - } - if (!this._buffer) - this._buffer = bufferSlice(data, op); - - return p - chunkOffset; -} - -function parsePacket(chunk, p, len) { - return this._decipher.decrypt(chunk, p, len); -} - -function onPayload(payload) { - // XXX: move this to the Decipher implementations? - - this._onPacket(); - - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - payload = this._packetRW.read.read(payload); - - const type = payload[0]; - if (type === MESSAGE.USERAUTH_SUCCESS - && !this._server - && !this._authenticated) { - this._authenticated = true; - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - } - const handler = MESSAGE_HANDLERS[type]; - if (handler === undefined) { - this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); - return; - } - - return handler(this, payload); -} - -function getCompatFlags(header) { - const software = header.versions.software; - - let flags = 0; - - for (const rule of COMPAT_CHECKS) { - if (typeof rule[0] === 'string') { - if (software === rule[0]) - flags |= rule[1]; - } else if (rule[0].test(software)) { - flags |= rule[1]; + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; } - } - - return flags; -} - -function modesToBytes(modes) { - const keys = Object.keys(modes); - const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); - let b = 0; - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === 'TTY_OP_END') - continue; - - const opcode = TERMINAL_MODE[key]; - if (opcode === undefined) - continue; - - const val = modes[key]; - if (typeof val === 'number' && isFinite(val)) { - bytes[b++] = opcode; - bytes[b++] = val >>> 24; - bytes[b++] = val >>> 16; - bytes[b++] = val >>> 8; - bytes[b++] = val; + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; } - } - - bytes[b++] = TERMINAL_MODE.TTY_OP_END; - - if (b < bytes.length) - return bufferSlice(bytes, 0, b); - - return bytes; -} - -function sendExtInfo(proto) { - let serverSigAlgs = - 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521' - + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss'; - if (eddsaSupported) - serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; - const algsLen = Buffer.byteLength(serverSigAlgs); - - let p = proto._packetRW.write.allocStart; - const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); - - packet[p] = MESSAGE.EXT_INFO; - - writeUInt32BE(packet, 1, ++p); - - writeUInt32BE(packet, 15, p += 4); - packet.utf8Write('server-sig-algs', p += 4, 15); - - writeUInt32BE(packet, algsLen, p += 15); - packet.utf8Write(serverSigAlgs, p += 4, algsLen); - - proto._debug && proto._debug('Outbound: Sending EXT_INFO'); - sendPacket(proto, proto._packetRW.write.finalize(packet)); -} - -module.exports = Protocol; - - -/***/ }), - -/***/ 52026: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const EventEmitter = __nccwpck_require__(82361); -const fs = __nccwpck_require__(57147); -const { constants } = fs; -const { - Readable: ReadableStream, - Writable: WritableStream -} = __nccwpck_require__(12781); -const { inherits, types: { isDate } } = __nccwpck_require__(73837); - -const FastBuffer = Buffer[Symbol.species]; - -const { - bufferCopy, - bufferSlice, - makeBufferParser, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const ATTR = { - SIZE: 0x00000001, - UIDGID: 0x00000002, - PERMISSIONS: 0x00000004, - ACMODTIME: 0x00000008, - EXTENDED: 0x80000000, -}; - -// Large enough to store all possible attributes -const ATTRS_BUF = Buffer.alloc(28); - -const STATUS_CODE = { - OK: 0, - EOF: 1, - NO_SUCH_FILE: 2, - PERMISSION_DENIED: 3, - FAILURE: 4, - BAD_MESSAGE: 5, - NO_CONNECTION: 6, - CONNECTION_LOST: 7, - OP_UNSUPPORTED: 8 -}; - -const VALID_STATUS_CODES = new Map( - Object.values(STATUS_CODE).map((n) => [n, 1]) -); - -const STATUS_CODE_STR = { - [STATUS_CODE.OK]: 'No error', - [STATUS_CODE.EOF]: 'End of file', - [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', - [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', - [STATUS_CODE.FAILURE]: 'Failure', - [STATUS_CODE.BAD_MESSAGE]: 'Bad message', - [STATUS_CODE.NO_CONNECTION]: 'No connection', - [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', - [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', -}; - -const REQUEST = { - INIT: 1, - OPEN: 3, - CLOSE: 4, - READ: 5, - WRITE: 6, - LSTAT: 7, - FSTAT: 8, - SETSTAT: 9, - FSETSTAT: 10, - OPENDIR: 11, - READDIR: 12, - REMOVE: 13, - MKDIR: 14, - RMDIR: 15, - REALPATH: 16, - STAT: 17, - RENAME: 18, - READLINK: 19, - SYMLINK: 20, - EXTENDED: 200 -}; - -const RESPONSE = { - VERSION: 2, - STATUS: 101, - HANDLE: 102, - DATA: 103, - NAME: 104, - ATTRS: 105, - EXTENDED: 201 -}; - -const OPEN_MODE = { - READ: 0x00000001, - WRITE: 0x00000002, - APPEND: 0x00000004, - CREAT: 0x00000008, - TRUNC: 0x00000010, - EXCL: 0x00000020 -}; - -const PKT_RW_OVERHEAD = 2 * 1024; -const MAX_REQID = 2 ** 32 - 1; -const CLIENT_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - REQUEST.INIT, - 0, 0, 0, 3 /* version */ -]); -const SERVER_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - RESPONSE.VERSION, - 0, 0, 0, 3 /* version */ -]); - -const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; -const OPENSSH_MAX_PKT_LEN = 256 * 1024; - -const bufferParser = makeBufferParser(); - -const fakeStderr = { - readable: false, - writable: false, - push: (data) => {}, - once: () => {}, - on: () => {}, - emit: () => {}, - end: () => {}, -}; - -function noop() {} - -// Emulates enough of `Channel` to be able to be used as a drop-in replacement -// in order to process incoming data with as little overhead as possible -class SFTP extends EventEmitter { - constructor(client, chanInfo, cfg) { - super(); - - if (typeof cfg !== 'object' || !cfg) - cfg = {}; - - const remoteIdentRaw = client._protocol._remoteIdentRaw; - - this.server = !!cfg.server; - this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); - - this._version = -1; - this._extensions = {}; - this._biOpt = cfg.biOpt; - this._pktLenBytes = 0; - this._pktLen = 0; - this._pktPos = 0; - this._pktType = 0; - this._pktData = undefined; - this._writeReqid = -1; - this._requests = {}; - this._maxInPktLen = OPENSSH_MAX_PKT_LEN; - this._maxOutPktLen = 34000; - this._maxReadLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - this._maxWriteLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - - this.maxOpenHandles = undefined; - - // Channel compatibility - this._client = client; - this._protocol = client._protocol; - this._callbacks = []; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - this._waitWindow = false; // SSH-level backpressure - this._chunkcb = undefined; - this._buffer = []; - this.type = chanInfo.type; - this.subtype = undefined; - this.incoming = chanInfo.incoming; - this.outgoing = chanInfo.outgoing; - this.stderr = fakeStderr; - this.readable = true; - } - - // This handles incoming data to parse - push(data) { - if (data === null) { - cleanupRequests(this); - if (!this.readable) - return; - // No more incoming data from the remote side - this.readable = false; - this.emit('end'); - return; + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`); + } + else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`); + } + return this; } - /* - uint32 length - byte type - byte[length - 1] data payload - */ - let p = 0; - - while (p < data.length) { - if (this._pktLenBytes < 4) { - let nb = Math.min(4 - this._pktLenBytes, data.length - p); - this._pktLenBytes += nb; - - while (nb--) - this._pktLen = (this._pktLen << 8) + data[p++]; - - if (this._pktLenBytes < 4) - return; - if (this._pktLen === 0) - return doFatalSFTPError(this, 'Invalid packet length'); - if (this._pktLen > this._maxInPktLen) { - const max = this._maxInPktLen; - return doFatalSFTPError( - this, - `Packet length ${this._pktLen} exceeds max length of ${max}` - ); + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config, type } = {}) { + let typePart = ''; + if (type === 'plain') { + typePart = 'pl'; } - if (p >= data.length) - return; - } - if (this._pktPos < this._pktLen) { - const nb = Math.min(this._pktLen - this._pktPos, data.length - p); - if (p !== 0 || nb !== data.length) { - if (nb === this._pktLen) { - this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._pktPos - ); - } - } else if (nb === this._pktLen) { - this._pkt = data; - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set(data, this._pktPos); + else if (type === 'phrase') { + typePart = 'ph'; } - p += nb; - this._pktPos += nb; - if (this._pktPos < this._pktLen) - return; - } - - const type = this._pkt[0]; - const payload = this._pkt; - - // Prepare for next packet - this._pktLen = 0; - this._pktLenBytes = 0; - this._pkt = undefined; - this._pktPos = 0; - - const handler = (this.server - ? SERVER_HANDLERS[type] - : CLIENT_HANDLERS[type]); - if (!handler) - return doFatalSFTPError(this, `Unknown packet type ${type}`); - - if (this._version === -1) { - if (this.server) { - if (type !== REQUEST.INIT) - return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); - } else if (type !== RESPONSE.VERSION) { - return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); + else if (type === 'websearch') { + typePart = 'w'; } - } - - if (handler(this, payload) === false) - return; + const configPart = config === undefined ? '' : `(${config})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; } - } - - end() { - this.destroy(); - } - destroy() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._protocol.channelClose(this.outgoing.id); + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; } - } - _init() { - this._init = noop; - if (!this.server) - sendOrBuffer(this, CLIENT_VERSION_BUFFER); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - createReadStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new ReadStream(this, path, options); - } - createWriteStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new WriteStream(this, path, options); - } - open(path, flags_, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; } - - const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); - if (flags === null) - throw new Error(`Unknown flags string: ${flags_}`); - - let attrsFlags = 0; - let attrsLen = 0; - if (typeof attrs === 'string' || typeof attrs === 'number') - attrs = { mode: attrs }; - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - attrsFlags = attrs.flags; - attrsLen = attrs.nb; + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or(filters, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.or` : 'or'; + this.url.searchParams.append(key, `(${filters})`); + return this; } - - /* - uint32 id - string filename - uint32 pflags - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPEN; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - writeUInt32BE(buf, attrsFlags, p += 4); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; } - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` - ); - } - close(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.CLOSE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +} +exports["default"] = PostgrestFilterBuilder; +//# sourceMappingURL=PostgrestFilterBuilder.js.map - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); +/***/ }), - this._requests[reqid] = { cb }; +/***/ 50: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` - ); - } - read(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off >= buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - - read_(this, handle, buf, off, len, position, cb); - } - readData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.read(handle, buf, off, len, position, cb); - } - write(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off > buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); +"use strict"; - if (!len) { - cb && process.nextTick(cb, undefined, 0); - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); +class PostgrestQueryBuilder { + constructor(url, { headers = {}, schema, fetch, }) { + this.url = url; + this.headers = new Headers(headers); + this.schema = schema; + this.fetch = fetch; } - - const maxDataLen = this._maxWriteLen; - const overflow = Math.max(len - maxDataLen, 0); - const origPosition = position; - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - string data - */ - const handleLen = handle.length; - let p = 9; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.WRITE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = position & 0xFF; - position /= 256; - } - writeUInt32BE(out, len, p += 8); - bufferCopy(buf, out, off, off + len, p += 4); - - this._requests[reqid] = { - cb: (err) => { - if (err) { - if (typeof cb === 'function') - cb(err); - } else if (overflow) { - this.write(handle, - buf, - off + len, - overflow, - origPosition + len, - cb); - } else if (typeof cb === 'function') { - cb(undefined, off + len); + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, options) { + const { head = false, count } = options !== null && options !== void 0 ? options : {}; + const method = head ? 'HEAD' : 'GET'; + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (count) { + this.headers.append('Prefer', `count=${count}`); } - } - }; - - const isSent = sendOrBuffer(this, out); - if (this._debug) { - const how = (isSent ? 'Sent' : 'Buffered'); - this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + }); } - } - writeData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.write(handle, buf, off, len, position, cb); - } - fastGet(remotePath, localPath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(this, fs, remotePath, localPath, opts, cb); - } - fastPut(localPath, remotePath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(fs, this, localPath, remotePath, opts, cb); - } - readFile(path, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. Only applies for bulk + * inserts. + */ + insert(values, { count, defaultToNull = true, } = {}) { + var _a; + const method = 'POST'; + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + if (!defaultToNull) { + this.headers.append('Prefer', `missing=default`); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); } - - if (typeof options === 'string') - options = { encoding: options, flag: 'r' }; - else if (!options) - options = { encoding: null, flag: 'r' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - const encoding = options.encoding; - if (encoding && !Buffer.isEncoding(encoding)) - throw new Error(`Unknown encoding: ${encoding}`); - - // First stat the file, so we know the size. - let size; - let buffer; // Single buffer with file data - let buffers; // List for when size is unknown - let pos = 0; - let handle; - - // SFTPv3 does not support using -1 for read position, so we have to track - // read position manually - let bytesRead = 0; - - const flag = options.flag || 'r'; - - const read = () => { - if (size === 0) { - buffer = Buffer.allocUnsafe(8192); - this.read(handle, buffer, 0, 8192, bytesRead, afterRead); - } else { - this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); - } - }; - - const afterRead = (er, nbytes) => { - let eof; - if (er) { - eof = (er.code === STATUS_CODE.EOF); - if (!eof) { - return this.close(handle, () => { - return callback && callback(er); - }); + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. + */ + upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { + var _a; + const method = 'POST'; + this.headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`); + if (onConflict !== undefined) + this.url.searchParams.set('on_conflict', onConflict); + if (count) { + this.headers.append('Prefer', `count=${count}`); } - } else { - eof = false; - } - - if (eof || (size === 0 && nbytes === 0)) - return close(); - - bytesRead += nbytes; - pos += nbytes; - if (size !== 0) { - if (pos === size) - close(); - else - read(); - } else { - // Unknown size, just read until we don't get bytes. - buffers.push(bufferSlice(buffer, 0, nbytes)); - read(); - } - }; - afterRead._wantEOFError = true; - - const close = () => { - this.close(handle, (er) => { - if (size === 0) { - // Collect the data into the buffers list. - buffer = Buffer.concat(buffers, pos); - } else if (pos < size) { - buffer = bufferSlice(buffer, 0, pos); + if (!defaultToNull) { + this.headers.append('Prefer', 'missing=default'); } - - if (encoding) - buffer = buffer.toString(encoding); - return callback && callback(er, buffer); - }); - }; - - this.open(path, flag, 0o666, (er, handle_) => { - if (er) - return callback && callback(er); - handle = handle_; - - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } } - - size = st.size || 0; - if (size === 0) { - // The kernel lies about many files. - // Go ahead and try to read some bytes. - buffers = []; - return read(); + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count, } = {}) { + var _a; + const method = 'PATCH'; + if (count) { + this.headers.append('Prefer', `count=${count}`); } - - buffer = Buffer.allocUnsafe(size); - read(); - }; - this.fstat(handle, tryStat); - }); - } - writeFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); } - - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'w' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (options.encoding && !Buffer.isEncoding(options.encoding)) - throw new Error(`Unknown encoding: ${options.encoding}`); - - const flag = options.flag || 'w'; - this.open(path, flag, options.mode, (openErr, handle) => { - if (openErr) { - callback && callback(openErr); - } else { - const buffer = (Buffer.isBuffer(data) - ? data - : Buffer.from('' + data, options.encoding || 'utf8')); - const position = (/a/.test(flag) ? null : 0); - - // SFTPv3 does not support the notion of 'current position' - // (null position), so we just attempt to append to the end of the file - // instead - if (position === null) { - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); - }; - this.fstat(handle, tryStat); - return; + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, } = {}) { + var _a; + const method = 'DELETE'; + if (count) { + this.headers.append('Prefer', `count=${count}`); } - writeAll(this, handle, buffer, 0, buffer.length, position, callback); - } - }); - } - appendFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); } +} +exports["default"] = PostgrestQueryBuilder; +//# sourceMappingURL=PostgrestQueryBuilder.js.map - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'a' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (!options.flag) - options = Object.assign({ flag: 'a' }, options); - this.writeFile(path, data, options, callback); - } - exists(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - this.stat(path, (err) => { - cb && cb(err ? false : true); - }); - } - unlink(filename, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string filename - */ - const fnameLen = Buffer.byteLength(filename); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REMOVE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, fnameLen, p); - buf.utf8Write(filename, p += 4, fnameLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` - ); - } - rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +/***/ }), - /* - uint32 id - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RENAME; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, oldLen, p); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` - ); - } - mkdir(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); +/***/ 1566: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let flags = 0; - let attrsLen = 0; +"use strict"; - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1049)); +class PostgrestTransformBuilder extends PostgrestBuilder_1.default { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + this.headers.append('Prefer', 'return=representation'); + return this; } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order referenced tables, but it only affects the ordering of the + * parent table if you use `!inner` in the query. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.referencedTable - Set this to order a referenced table by + * its columns + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.order` : 'order'; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); + return this; } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.MKDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit(count, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(key, `${count}`); + return this; } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` - ); - } - rmdir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RMDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` - ); - } - readdir(where, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) { + const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`; + const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; } - if (typeof opts !== 'object' || opts === null) - opts = {}; - - const doFilter = (opts && opts.full ? false : true); - - if (!Buffer.isBuffer(where) && typeof where !== 'string') - throw new Error('missing directory handle or path'); - - if (typeof where === 'string') { - const entries = []; - let e = 0; - - const reread = (err, handle) => { - if (err) - return cb(err); - - this.readdir(handle, opts, (err, list) => { - const eof = (err && err.code === STATUS_CODE.EOF); - - if (err && !eof) - return this.close(handle, () => cb(err)); - - if (eof) { - return this.close(handle, (err) => { - if (err) - return cb(err); - cb(undefined, entries); - }); - } - - for (let i = 0; i < list.length; ++i, ++e) - entries[e] = list[i]; - - reread(undefined, handle); - }); - }; - return this.opendir(where, reread); + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; } - - /* - uint32 id - string handle - */ - const handleLen = where.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(where, p += 4); - - this._requests[reqid] = { - cb: (doFilter - ? (err, list) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - - for (let i = list.length - 1; i >= 0; --i) { - if (list[i].filename === '.' || list[i].filename === '..') - list.splice(i, 1); - } - - cb(undefined, list); - } - : cb) - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` - ); - } - fstat(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` - ); - } - stat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.STAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` - ); - } - lstat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.LSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` - ); - } - opendir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPENDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` - ); - } - setstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers.set('Accept', 'application/vnd.pgrst.object+json'); + return this; } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers.set('Accept', 'application/json'); + } + else { + this.headers.set('Accept', 'application/vnd.pgrst.object+json'); + } + this.isMaybeSingle = true; + return this; } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` - ); - } - fsetstat(handle, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers.set('Accept', 'text/csv'); + return this; } - - /* - uint32 id - string handle - ATTRS attrs - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - writeUInt32BE(buf, flags, p += handleLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers.set('Accept', 'application/geo+json'); + return this; } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` - ); - } - futimes(handle, atime, mtime, cb) { - return this.fsetstat(handle, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - utimes(path, atime, mtime, cb) { - return this.setstat(path, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - fchown(handle, uid, gid, cb) { - return this.fsetstat(handle, { - uid: uid, - gid: gid - }, cb); - } - chown(path, uid, gid, cb) { - return this.setstat(path, { - uid: uid, - gid: gid - }, cb); - } - fchmod(handle, mode, cb) { - return this.fsetstat(handle, { - mode: mode - }, cb); - } - chmod(path, mode, cb) { - return this.setstat(path, { - mode: mode - }, cb); - } - readlink(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing link info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` - ); - } - symlink(targetPath, linkPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string linkpath - string targetpath - */ - const linkLen = Buffer.byteLength(linkPath); - const targetLen = Buffer.byteLength(targetPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SYMLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - if (this._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - writeUInt32BE(buf, targetLen, p); - buf.utf8Write(targetPath, p += 4, targetLen); - writeUInt32BE(buf, linkLen, p += targetLen); - buf.utf8Write(linkPath, p += 4, linkLen); - } else { - writeUInt32BE(buf, linkLen, p); - buf.utf8Write(linkPath, p += 4, linkLen); - writeUInt32BE(buf, targetLen, p += linkLen); - buf.utf8Write(targetPath, p += 4, targetLen); + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { + var _a; + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|'); + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = (_a = this.headers.get('Accept')) !== null && _a !== void 0 ? _a : 'application/json'; + this.headers.set('Accept', `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`); + if (format === 'json') { + return this; + } + else { + return this; + } } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` - ); - } - realpath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REALPATH; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing path info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` - ); - } - // extended requests - ext_openssh_rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['posix-rename@openssh.com']; - if (!ext || ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "posix-rename@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 24, p); - buf.utf8Write('posix-rename@openssh.com', p += 4, 24); - writeUInt32BE(buf, oldLen, p += 24); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + this.headers.append('Prefer', 'tx=rollback'); + return this; } - } - ext_openssh_statvfs(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['statvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "statvfs@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 19, p); - buf.utf8Write('statvfs@openssh.com', p += 4, 19); - writeUInt32BE(buf, pathLen, p += 19); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + return this; } - } - ext_openssh_fstatvfs(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fstatvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fstatvfs@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); - writeUInt32BE(buf, handleLen, p += 20); - buf.set(handle, p += 4); - - this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); + /** + * Set the maximum number of rows that can be affected by the query. + * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. + * + * @param value - The maximum number of rows that can be affected + */ + maxAffected(value) { + this.headers.append('Prefer', 'handling=strict'); + this.headers.append('Prefer', `max-affected=${value}`); + return this; } - } - ext_openssh_hardlink(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['hardlink@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "hardlink@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('hardlink@openssh.com', p += 4, 20); - writeUInt32BE(buf, oldLen, p += 20); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); - } - } - ext_openssh_fsync(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fsync@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fsync@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 17, p); - buf.utf8Write('fsync@openssh.com', p += 4, 17); - writeUInt32BE(buf, handleLen, p += 17); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` - ); - } - ext_openssh_lsetstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['lsetstat@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - let flags = 0; - let attrsLen = 0; +} +exports["default"] = PostgrestTransformBuilder; +//# sourceMappingURL=PostgrestTransformBuilder.js.map - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } +/***/ }), - /* - uint32 id - string "lsetstat@openssh.com" - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); +/***/ 1178: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); +"use strict"; - writeUInt32BE(buf, 20, p); - buf.utf8Write('lsetstat@openssh.com', p += 4, 20); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +// Always update wrapper.mjs when updating this file. +const PostgrestClient_1 = tslib_1.__importDefault(__nccwpck_require__(1526)); +exports.PostgrestClient = PostgrestClient_1.default; +const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50)); +exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); +exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; +const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1566)); +exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; +const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1049)); +exports.PostgrestBuilder = PostgrestBuilder_1.default; +const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(7317)); +exports.PostgrestError = PostgrestError_1.default; +exports["default"] = { + PostgrestClient: PostgrestClient_1.default, + PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, + PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, + PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, + PostgrestBuilder: PostgrestBuilder_1.default, + PostgrestError: PostgrestError_1.default, +}; +//# sourceMappingURL=index.js.map - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); +/***/ }), - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; +/***/ 9911: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); +"use strict"; - p += attrsLen; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(88); +const push_1 = tslib_1.__importDefault(__nccwpck_require__(2292)); +const timer_1 = tslib_1.__importDefault(__nccwpck_require__(8960)); +const RealtimePresence_1 = tslib_1.__importDefault(__nccwpck_require__(5583)); +const Transformers = tslib_1.__importStar(__nccwpck_require__(1140)); +const transformers_1 = __nccwpck_require__(1140); +var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; +(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; +})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); +var REALTIME_LISTEN_TYPES; +(function (REALTIME_LISTEN_TYPES) { + REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; + REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; + REALTIME_LISTEN_TYPES["SYSTEM"] = "system"; +})(REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = REALTIME_LISTEN_TYPES = {})); +var REALTIME_SUBSCRIBE_STATES; +(function (REALTIME_SUBSCRIBE_STATES) { + REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; +})(REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = REALTIME_SUBSCRIBE_STATES = {})); +exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES; +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ +class RealtimeChannel { + constructor( + /** Topic name can be any string. */ + topic, params = { config: {} }, socket) { + var _a, _b; + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = constants_1.CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.subTopic = topic.replace(/^realtime:/i, ''); + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: '', enabled: false }, + private: false, + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive('ok', () => { + this.state = constants_1.CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); + this.state = constants_1.CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return; + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('error', (reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence_1.default(this); + this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint); + this.private = this.params.config.private || false; + if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { + throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; + } } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b, _c; + if (!this.socket.isConnected()) { + this.socket.connect(); + } + if (this.state == constants_1.CHANNEL_STATES.closed) { + const { config: { broadcast, presence, private: isPrivate }, } = this.params; + const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []; + const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && + this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) || + ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; + const accessTokenPayload = {}; + const config = { + broadcast, + presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), + postgres_changes, + private: isPrivate, + }; + if (this.socket.accessTokenValue) { + accessTokenPayload.access_token = this.socket.accessTokenValue; + } + this._onError((e) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, e)); + this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CLOSED)); + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush + .receive('ok', async ({ postgres_changes }) => { + var _a; + this.socket.setAuth(); + if (postgres_changes === undefined) { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter }, } = clientPostgresBinding; + const serverPostgresFilter = postgres_changes && postgres_changes[i]; + if (serverPostgresFilter && + serverPostgresFilter.event === event && + serverPostgresFilter.schema === schema && + serverPostgresFilter.table === table && + serverPostgresFilter.filter === filter) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } + else { + this.unsubscribe(); + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error('mismatch between server and client bindings for postgres changes')); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + }) + .receive('error', (error) => { + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); + return; + }) + .receive('timeout', () => { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.TIMED_OUT); + return; + }); + } + return this; } - } - ext_openssh_expandPath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['expand-path@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "expand-path@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 23, p); - buf.utf8Write('expand-path@openssh.com', p += 4, 23); - - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing expanded path')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); + presenceState() { + return this.presence.state; } - } - ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['copy-data']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - if (!Buffer.isBuffer(srcHandle)) - throw new Error('Source handle is not a Buffer'); - - if (!Buffer.isBuffer(dstHandle)) - throw new Error('Destination handle is not a Buffer'); - - /* - uint32 id - string "copy-data" - string read-from-handle - uint64 read-from-offset - uint64 read-data-length - string write-to-handle - uint64 write-to-offset - */ - let p = 0; - const buf = Buffer.allocUnsafe( - 4 + 1 - + 4 - + 4 + 9 - + 4 + srcHandle.length - + 8 - + 8 - + 4 + dstHandle.length - + 8 - ); - - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - - buf[p] = REQUEST.EXTENDED; - ++p; - - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - - writeUInt32BE(buf, 9, p); - p += 4; - buf.utf8Write('copy-data', p, 9); - p += 9; - - writeUInt32BE(buf, srcHandle.length, p); - p += 4; - buf.set(srcHandle, p); - p += srcHandle.length; - - for (let i = 7; i >= 0; --i) { - buf[p + i] = srcOffset & 0xFF; - srcOffset /= 256; + async track(payload, opts = {}) { + return await this.send({ + type: 'presence', + event: 'track', + payload, + }, opts.timeout || this.timeout); } - p += 8; - - for (let i = 7; i >= 0; --i) { - buf[p + i] = len & 0xFF; - len /= 256; + async untrack(opts = {}) { + return await this.send({ + type: 'presence', + event: 'untrack', + }, opts); } - p += 8; - - writeUInt32BE(buf, dstHandle.length, p); - p += 4; - buf.set(dstHandle, p); - p += dstHandle.length; - - for (let i = 7; i >= 0; --i) { - buf[p + i] = dstOffset & 0xFF; - dstOffset /= 256; + on(type, filter, callback) { + if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) { + this.socket.log('channel', `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); + this.unsubscribe().then(() => this.subscribe()); + } + return this._on(type, filter, callback); } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} copy-data`); + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + async httpSend(event, payload, opts = {}) { + var _a; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + if (payload === undefined || payload === null) { + return Promise.reject('Payload is required for httpSend()'); + } + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: payload, + private: this.private, + }, + ], + }), + }; + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + if (response.status === 202) { + return { success: true }; + } + let errorMessage = response.statusText; + try { + const errorBody = await response.json(); + errorMessage = errorBody.error || errorBody.message || errorMessage; + } + catch (_b) { } + return Promise.reject(new Error(errorMessage)); } - } - ext_home_dir(username, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['home-directory']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - if (typeof username !== 'string') - throw new TypeError('username is not a string'); - - /* - uint32 id - string "home-directory" - string username - */ - let p = 0; - const usernameLen = Buffer.byteLength(username); - const buf = Buffer.allocUnsafe( - 4 + 1 - + 4 - + 4 + 14 - + 4 + usernameLen - ); - - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - - buf[p] = REQUEST.EXTENDED; - ++p; - - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - - writeUInt32BE(buf, 14, p); - p += 4; - buf.utf8Write('home-directory', p, 14); - p += 14; - - writeUInt32BE(buf, usernameLen, p); - p += 4; - buf.utf8Write(username, p, usernameLen); - p += usernameLen; - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing home directory')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} home-directory`); + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send(args, opts = {}) { + var _a, _b; + if (!this._canPush() && args.type === 'broadcast') { + console.warn('Realtime send() is automatically falling back to REST API. ' + + 'This behavior will be deprecated in the future. ' + + 'Please use httpSend() explicitly for REST delivery.'); + const { event, payload: endpoint_payload } = args; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: endpoint_payload, + private: this.private, + }, + ], + }), + }; + try { + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); + return response.ok ? 'ok' : 'error'; + } + catch (error) { + if (error.name === 'AbortError') { + return 'timed out'; + } + else { + return 'error'; + } + } + } + else { + return new Promise((resolve) => { + var _a, _b, _c; + const push = this._push(args.type, args, opts.timeout || this.timeout); + if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve('ok'); + } + push.receive('ok', () => resolve('ok')); + push.receive('error', () => resolve('error')); + push.receive('timeout', () => resolve('timed out')); + }); + } } - } - ext_users_groups(uids, gids, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['users-groups-by-id@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - if (!Array.isArray(uids)) - throw new TypeError('uids is not an array'); - for (const val of uids) { - if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) - throw new Error('uid values must all be 32-bit unsigned integers'); + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); } - if (!Array.isArray(gids)) - throw new TypeError('gids is not an array'); - for (const val of gids) { - if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) - throw new Error('gid values must all be 32-bit unsigned integers'); + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = constants_1.CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`); + this._trigger(constants_1.CHANNEL_EVENTS.close, 'leave', this._joinRef()); + }; + this.joinPush.destroy(); + let leavePush = null; + return new Promise((resolve) => { + leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); + leavePush + .receive('ok', () => { + onClose(); + resolve('ok'); + }) + .receive('timeout', () => { + onClose(); + resolve('timed out'); + }) + .receive('error', () => { + resolve('error'); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger('ok', {}); + } + }).finally(() => { + leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); + }); } - - /* - uint32 id - string "users-groups-by-id@openssh.com" - string uids - uint32 uid1 - ... - string gids - uint32 gid1 - ... - */ - let p = 0; - const buf = Buffer.allocUnsafe( - 4 + 1 - + 4 - + 4 + 30 - + 4 + (4 * uids.length) - + 4 + (4 * gids.length) - ); - - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - - buf[p] = REQUEST.EXTENDED; - ++p; - - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - - writeUInt32BE(buf, 30, p); - p += 4; - buf.utf8Write('users-groups-by-id@openssh.com', p, 30); - p += 30; - - writeUInt32BE(buf, 4 * uids.length, p); - p += 4; - for (const val of uids) { - writeUInt32BE(buf, val, p); - p += 4; + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown() { + this.pushBuffer.forEach((push) => push.destroy()); + this.pushBuffer = []; + this.rejoinTimer.reset(); + this.joinPush.destroy(); + this.state = constants_1.CHANNEL_STATES.closed; + this.bindings = {}; } - - writeUInt32BE(buf, 4 * gids.length, p); - p += 4; - for (const val of gids) { - writeUInt32BE(buf, val, p); - p += 4; + /** @internal */ + async _fetchWithTimeout(url, options, timeout) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); + clearTimeout(id); + return response; } - - this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new push_1.default(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } + else { + this._addToPushBuffer(pushEvent); + } + return pushEvent; } - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - handle(reqid, handle) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - const handleLen = handle.length; - - if (handleLen > 256) - throw new Error('handle too large (> 256 bytes)'); - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.HANDLE; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - if (handleLen) - buf.set(handle, p += 4); - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` - ); - } - status(reqid, code, message) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!VALID_STATUS_CODES.has(code)) - throw new Error(`Bad status code: ${code}`); - - message || (message = ''); - - const msgLen = Buffer.byteLength(message); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.STATUS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, code, p); - - writeUInt32BE(buf, msgLen, p += 4); - p += 4; - if (msgLen) { - buf.utf8Write(message, p, msgLen); - p += msgLen; + /** @internal */ + _addToPushBuffer(pushEvent) { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + // Enforce buffer size limit + if (this.pushBuffer.length > constants_1.MAX_PUSH_BUFFER_SIZE) { + const removedPush = this.pushBuffer.shift(); + if (removedPush) { + removedPush.destroy(); + this.socket.log('channel', `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); + } + } } - - writeUInt32BE(buf, 0, p); // Empty language tag - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` - ); - } - data(reqid, data, encoding) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - const isBuffer = Buffer.isBuffer(data); - - if (!isBuffer && typeof data !== 'string') - throw new Error('data is not a Buffer or string'); - - let isUTF8; - if (!isBuffer && !encoding) { - encoding = undefined; - isUTF8 = true; + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; } - - const dataLen = ( - isBuffer - ? data.length - : Buffer.byteLength(data, encoding) - ); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.DATA; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, dataLen, p); - if (dataLen) { - if (isBuffer) - buf.set(data, p += 4); - else if (isUTF8) - buf.utf8Write(data, p += 4, dataLen); - else - buf.write(data, p += 4, dataLen, encoding); + /** @internal */ + _isMember(topic) { + return this.topic === topic; } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` - ); - } - name(reqid, names) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Array.isArray(names)) { - if (typeof names !== 'object' || names === null) - throw new Error('names is not an object or array'); - names = [ names ]; + /** @internal */ + _joinRef() { + return this.joinPush.ref; } - - const count = names.length; - let namesLen = 0; - let nameAttrs; - const attrs = []; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - namesLen += 4 + Buffer.byteLength(filename); - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - namesLen += 4 + Buffer.byteLength(longname); - - if (typeof name.attrs === 'object' && name.attrs !== null) { - nameAttrs = attrsToBytes(name.attrs); - namesLen += 4 + nameAttrs.nb; - - if (nameAttrs.nb) { - let bytes; - - if (nameAttrs.nb === ATTRS_BUF.length) { - bytes = new Uint8Array(ATTRS_BUF); - } else { - bytes = new Uint8Array(nameAttrs.nb); - bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); - } - - nameAttrs.bytes = bytes; + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = constants_1.CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; } - - attrs.push(nameAttrs); - } else { - namesLen += 4; - attrs.push(null); - } - } - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.NAME; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, count, p); - - p += 4; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - - { - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - const len = Buffer.byteLength(filename); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(filename, p, len); - p += len; + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified'; } - } - - { - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - const len = Buffer.byteLength(longname); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(longname, p, len); - p += len; + if (['insert', 'update', 'delete'].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { + var _a, _b, _c; + return ((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; + }).map((bind) => bind.callback(handledPayload, ref)); } - } - - const attr = attrs[i]; - if (attr) { - writeUInt32BE(buf, attr.flags, p); - p += 4; - if (attr.flags && attr.bytes) { - buf.set(attr.bytes, p); - p += attr.nb; + else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { + var _a, _b, _c, _d, _e, _f; + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id; + const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; + return (bindId && + ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && + (bindEvent === '*' || + (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); + } + else { + const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return bindEvent === '*' || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); + } + } + else { + return bind.type.toLocaleLowerCase() === typeLower; + } + }).map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type, errors } = postgresChanges; + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind.callback(handledPayload, ref); + }); } - } else { - writeUInt32BE(buf, 0, p); - p += 4; - } } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` - ); - } - attrs(reqid, attrs) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (typeof attrs !== 'object' || attrs === null) - throw new Error('attrs is not an object'); - - attrs = attrsToBytes(attrs); - const flags = attrs.flags; - const attrsLen = attrs.nb; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.ATTRS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, flags, p); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + /** @internal */ + _isClosed() { + return this.state === constants_1.CHANNEL_STATES.closed; } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` - ); - } -} - -function tryCreateBuffer(size) { - try { - return Buffer.allocUnsafe(size); - } catch (ex) { - return ex; - } -} - -function read_(self, handle, buf, off, len, position, cb, req_) { - const maxDataLen = self._maxReadLen; - const overflow = Math.max(len - maxDataLen, 0); - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - uint32 len - */ - const handleLen = handle.length; - let p = 9; - let pos = position; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.READ; - const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = pos & 0xFF; - pos /= 256; - } - writeUInt32BE(out, len, p += 8); - - if (typeof cb !== 'function') - cb = noop; - - const req = (req_ || { - nb: 0, - position, - off, - origOff: off, - len: undefined, - overflow: undefined, - cb: (err, data, nb) => { - const len = req.len; - const overflow = req.overflow; - - if (err) { - if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) - return cb(err); - } else if (nb > len) { - return cb(new Error('Received more data than requested')); - } else if (nb === len && overflow) { - req.nb += nb; - req.position += nb; - req.off += nb; - read_(self, handle, buf, req.off, overflow, req.position, cb, req); - return; - } - - nb = (nb || 0); - if (req.origOff === 0 && buf.length === req.nb) - data = buf; - else - data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); - cb(undefined, req.nb + nb, data, req.position); - }, - buffer: undefined, - }); - - req.len = len; - req.overflow = overflow; - - // TODO: avoid creating multiple buffer slices when we need to re-call read_() - // because of overflow - req.buffer = bufferSlice(buf, off, off + len); - - self._requests[reqid] = req; - - const isBuffered = sendOrBuffer(self, out); - self._debug && self._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` - ); -} - -function fastXfer(src, dst, srcPath, dstPath, opts, cb) { - let concurrency = 64; - let chunkSize = 32768; - let onstep; - let mode; - let fileSize; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.concurrency === 'number' - && opts.concurrency > 0 - && !isNaN(opts.concurrency)) { - concurrency = opts.concurrency; - } - if (typeof opts.chunkSize === 'number' - && opts.chunkSize > 0 - && !isNaN(opts.chunkSize)) { - chunkSize = opts.chunkSize; - } - if (typeof opts.fileSize === 'number' - && opts.fileSize > 0 - && !isNaN(opts.fileSize)) { - fileSize = opts.fileSize; - } - if (typeof opts.step === 'function') - onstep = opts.step; - - if (typeof opts.mode === 'string' || typeof opts.mode === 'number') - mode = modeNum(opts.mode); - } - - // Internal state variables - let fsize; - let pdst = 0; - let total = 0; - let hadError = false; - let srcHandle; - let dstHandle; - let readbuf; - let bufsize = chunkSize * concurrency; - - function onerror(err) { - if (hadError) - return; - - hadError = true; - - let left = 0; - let cbfinal; - - if (srcHandle || dstHandle) { - cbfinal = () => { - if (--left === 0) - cb(err); - }; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - ++left; - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - ++left; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - dst.close(dstHandle, cbfinal); - } else { - cb(err); + /** @internal */ + _isJoined() { + return this.state === constants_1.CHANNEL_STATES.joined; } - } - - src.open(srcPath, 'r', (err, sourceHandle) => { - if (err) - return onerror(err); - - srcHandle = sourceHandle; - - if (fileSize === undefined) - src.fstat(srcHandle, tryStat); - else - tryStat(null, { size: fileSize }); - - function tryStat(err, attrs) { - if (err) { - if (src !== fs) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - src.stat(srcPath, (err_, attrs_) => { - if (err_) - return onerror(err); - tryStat(null, attrs_); - }); - return; - } - return onerror(err); - } - fsize = attrs.size; - - dst.open(dstPath, 'w', (err, destHandle) => { - if (err) - return onerror(err); - - dstHandle = destHandle; - - if (fsize <= 0) - return onerror(); - - // Use less memory where possible - while (bufsize > fsize) { - if (concurrency === 1) { - bufsize = fsize; - break; - } - bufsize -= chunkSize; - --concurrency; + /** @internal */ + _isJoining() { + return this.state === constants_1.CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === constants_1.CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter: filter, + callback: callback, + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); } - - readbuf = tryCreateBuffer(bufsize); - if (readbuf instanceof Error) - return onerror(readbuf); - - if (mode !== undefined) { - dst.fchmod(dstHandle, mode, function tryAgain(err) { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() - // for whatever reason - dst.chmod(dstPath, mode, (err_) => tryAgain()); - return; - } - startReads(); - }); - } else { - startReads(); + else { + this.bindings[typeLower] = [binding]; } - - function onread(err, nb, data, dstpos, datapos, origChunkLen) { - if (err) - return onerror(err); - - datapos = datapos || 0; - - dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); - - function writeCb(err) { - if (err) - return onerror(err); - - total += nb; - onstep && onstep(total, nb, fsize); - - if (nb < origChunkLen) - return singleRead(datapos, dstpos + nb, origChunkLen - nb); - - if (total === fsize) { - dst.close(dstHandle, (err) => { - dstHandle = undefined; - if (err) - return onerror(err); - src.close(srcHandle, (err) => { - srcHandle = undefined; - if (err) - return onerror(err); - cb(); - }); - }); - return; - } - - if (pdst >= fsize) - return; - - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(datapos, pdst, chunk); - pdst += chunk; - } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + if (this.bindings[typeLower]) { + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + var _a; + return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && + RealtimeChannel.isEqual(bind.filter, filter)); + }); } - - function makeCb(psrc, pdst, chunk) { - return (err, nb, data) => { - onread(err, nb, data, pdst, psrc, chunk); - }; + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; } - - function singleRead(psrc, pdst, chunk) { - src.read(srcHandle, - readbuf, - psrc, - chunk, - pdst, - makeCb(psrc, pdst, chunk)); - } - - function startReads() { - let reads = 0; - let psrc = 0; - while (pdst < fsize && reads < concurrency) { - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(psrc, pdst, chunk); - psrc += chunk; - pdst += chunk; - ++reads; - } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } } - }); - } - }); -} - -function writeAll(sftp, handle, buffer, offset, length, position, callback_) { - const callback = (typeof callback_ === 'function' ? callback_ : undefined); - - sftp.write(handle, - buffer, - offset, - length, - position, - (writeErr, written) => { - if (writeErr) { - return sftp.close(handle, () => { - callback && callback(writeErr); - }); + return true; } - if (written === length) { - sftp.close(handle, callback); - } else { - offset += written; - length -= written; - position += written; - writeAll(sftp, handle, buffer, offset, length, position, callback); + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } } - }); -} - -class Stats { - constructor(initial) { - this.mode = (initial && initial.mode); - this.uid = (initial && initial.uid); - this.gid = (initial && initial.gid); - this.size = (initial && initial.size); - this.atime = (initial && initial.atime); - this.mtime = (initial && initial.mtime); - this.extended = (initial && initial.extended); - } - isDirectory() { - return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); - } - isFile() { - return ((this.mode & constants.S_IFMT) === constants.S_IFREG); - } - isBlockDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); - } - isCharacterDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); - } - isSymbolicLink() { - return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); - } - isFIFO() { - return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); - } - isSocket() { - return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); - } -} - -function attrsToBytes(attrs) { - let flags = 0; - let nb = 0; - - if (typeof attrs === 'object' && attrs !== null) { - if (typeof attrs.size === 'number') { - flags |= ATTR.SIZE; - const val = attrs.size; - // Big Endian - ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 - ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 - ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 - ATTRS_BUF[nb++] = val / 4294967296; // 2**32 - ATTRS_BUF[nb++] = val / 16777216; // 2**24 - ATTRS_BUF[nb++] = val / 65536; // 2**16 - ATTRS_BUF[nb++] = val / 256; // 2**8 - ATTRS_BUF[nb++] = val; - } - if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { - flags |= ATTR.UIDGID; - const uid = attrs.uid; - const gid = attrs.gid; - // Big Endian - ATTRS_BUF[nb++] = uid >>> 24; - ATTRS_BUF[nb++] = uid >>> 16; - ATTRS_BUF[nb++] = uid >>> 8; - ATTRS_BUF[nb++] = uid; - ATTRS_BUF[nb++] = gid >>> 24; - ATTRS_BUF[nb++] = gid >>> 16; - ATTRS_BUF[nb++] = gid >>> 8; - ATTRS_BUF[nb++] = gid; - } - if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { - const mode = modeNum(attrs.mode); - flags |= ATTR.PERMISSIONS; - // Big Endian - ATTRS_BUF[nb++] = mode >>> 24; - ATTRS_BUF[nb++] = mode >>> 16; - ATTRS_BUF[nb++] = mode >>> 8; - ATTRS_BUF[nb++] = mode; - } - if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) - && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { - const atime = toUnixTimestamp(attrs.atime); - const mtime = toUnixTimestamp(attrs.mtime); - - flags |= ATTR.ACMODTIME; - // Big Endian - ATTRS_BUF[nb++] = atime >>> 24; - ATTRS_BUF[nb++] = atime >>> 16; - ATTRS_BUF[nb++] = atime >>> 8; - ATTRS_BUF[nb++] = atime; - ATTRS_BUF[nb++] = mtime >>> 24; - ATTRS_BUF[nb++] = mtime >>> 16; - ATTRS_BUF[nb++] = mtime >>> 8; - ATTRS_BUF[nb++] = mtime; - } - // TODO: extended attributes - } - - return { flags, nb }; -} - -function toUnixTimestamp(time) { - // eslint-disable-next-line no-self-compare - if (typeof time === 'number' && time === time) // Valid, non-NaN number - return time; - if (isDate(time)) - return parseInt(time.getTime() / 1000, 10); - throw new Error(`Cannot parse time: ${time}`); -} - -function modeNum(mode) { - // eslint-disable-next-line no-self-compare - if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number - return mode; - if (typeof mode === 'string') - return modeNum(parseInt(mode, 8)); - throw new Error(`Cannot parse mode: ${mode}`); -} - -const stringFlagMap = { - 'r': OPEN_MODE.READ, - 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, - 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL -}; - -function stringToFlags(str) { - const flags = stringFlagMap[str]; - return (flags !== undefined ? flags : null); -} - -const flagsToString = (() => { - const stringFlagMapKeys = Object.keys(stringFlagMap); - return (flags) => { - for (let i = 0; i < stringFlagMapKeys.length; ++i) { - const key = stringFlagMapKeys[i]; - if (stringFlagMap[key] === flags) - return key; + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); } - return null; - }; -})(); - -function readAttrs(biOpt) { - /* - uint32 flags - uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - string extended_type - string extended_data - ... more extended data (extended_type - extended_data pairs), - so that number of pairs equals extended_count - */ - const flags = bufferParser.readUInt32BE(); - if (flags === undefined) - return; - - const attrs = new Stats(); - if (flags & ATTR.SIZE) { - const size = bufferParser.readUInt64BE(biOpt); - if (size === undefined) - return; - attrs.size = size; - } - - if (flags & ATTR.UIDGID) { - const uid = bufferParser.readUInt32BE(); - const gid = bufferParser.readUInt32BE(); - if (gid === undefined) - return; - attrs.uid = uid; - attrs.gid = gid; - } - - if (flags & ATTR.PERMISSIONS) { - const mode = bufferParser.readUInt32BE(); - if (mode === undefined) - return; - attrs.mode = mode; - } - - if (flags & ATTR.ACMODTIME) { - const atime = bufferParser.readUInt32BE(); - const mtime = bufferParser.readUInt32BE(); - if (mtime === undefined) - return; - attrs.atime = atime; - attrs.mtime = mtime; - } - - if (flags & ATTR.EXTENDED) { - const count = bufferParser.readUInt32BE(); - if (count === undefined) - return; - const extended = {}; - for (let i = 0; i < count; ++i) { - const type = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data === undefined) - return; - extended[type] = data; + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); } - attrs.extended = extended; - } - - return attrs; -} - -function sendOrBuffer(sftp, payload) { - const ret = tryWritePayload(sftp, payload); - if (ret !== undefined) { - sftp._buffer.push(ret); - return false; - } - return true; -} - -function tryWritePayload(sftp, payload) { - const outgoing = sftp.outgoing; - if (outgoing.state !== 'open') - return; - - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - return payload; - } - - let ret; - const len = payload.length; - let p = 0; - - while (len - p > 0 && outgoing.window > 0) { - const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); - outgoing.window -= actualLen; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); } - - if (p === 0 && actualLen === len) { - sftp._protocol.channelData(sftp.outgoing.id, payload); - } else { - sftp._protocol.channelData(sftp.outgoing.id, - bufferSlice(payload, p, p + actualLen)); + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = constants_1.CHANNEL_STATES.joining; + this.joinPush.resend(timeout); } - - p += actualLen; - } - - if (len - p > 0) { - if (p > 0) - ret = bufferSlice(payload, p, len); - else - ret = payload; // XXX: should never get here? - } - - return ret; -} - -function drainBuffer() { - this._chunkcb = undefined; - const buffer = this._buffer; - let i = 0; - while (i < buffer.length) { - const payload = buffer[i]; - const ret = tryWritePayload(this, payload); - if (ret !== undefined) { - if (ret !== payload) - buffer[i] = ret; - if (i > 0) - this._buffer = buffer.slice(i); - return; + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {}, + }; + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; } - ++i; - } - if (i > 0) - this._buffer = []; -} - -function doFatalSFTPError(sftp, msg, noDebug) { - const err = new Error(msg); - err.level = 'sftp-protocol'; - if (!noDebug && sftp._debug) - sftp._debug(`SFTP: Inbound: ${msg}`); - sftp.emit('error', err); - sftp.destroy(); - cleanupRequests(sftp); - return false; -} - -function cleanupRequests(sftp) { - const keys = Object.keys(sftp._requests); - if (keys.length === 0) - return; - - const reqs = sftp._requests; - sftp._requests = {}; - const err = new Error('No response from server'); - for (let i = 0; i < keys.length; ++i) { - const req = reqs[keys[i]]; - if (typeof req.cb === 'function') - req.cb(err); - } -} - -function requestLimits(sftp, cb) { - /* - uint32 id - string "limits@openssh.com" - */ - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 18, p); - buf.utf8Write('limits@openssh.com', p += 4, 18); - - sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; - - const isBuffered = sendOrBuffer(sftp, buf); - if (sftp._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); - } } +exports["default"] = RealtimeChannel; +//# sourceMappingURL=RealtimeChannel.js.map -const CLIENT_HANDLERS = { - [RESPONSE.VERSION]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); - - const extensions = {}; +/***/ }), - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); +/***/ 9103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed VERSION packet'); +"use strict"; - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(3478)); +const constants_1 = __nccwpck_require__(88); +const serializer_1 = tslib_1.__importDefault(__nccwpck_require__(5360)); +const timer_1 = tslib_1.__importDefault(__nccwpck_require__(8960)); +const transformers_1 = __nccwpck_require__(1140); +const RealtimeChannel_1 = tslib_1.__importDefault(__nccwpck_require__(9911)); +const noop = () => { }; +// Connection-related constants +const CONNECTION_TIMEOUTS = { + HEARTBEAT_INTERVAL: 25000, + RECONNECT_DELAY: 10, + HEARTBEAT_TIMEOUT_FALLBACK: 100, +}; +const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000]; +const DEFAULT_RECONNECT_FALLBACK = 10000; +const WORKER_SCRIPT = ` + addEventListener("message", (e) => { + if (e.data.event === "start") { + setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } - - sftp._version = version; - sftp._extensions = extensions; - - if (extensions['limits@openssh.com'] === '1') { - return requestLimits(sftp, (err, limits) => { - if (!err) { - if (limits.maxPktLen > 0) - sftp._maxOutPktLen = limits.maxPktLen; - if (limits.maxReadLen > 0) - sftp._maxReadLen = limits.maxReadLen; - if (limits.maxWriteLen > 0) - sftp._maxWriteLen = limits.maxWriteLen; - sftp.maxOpenHandles = ( - limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity - ); + });`; +class RealtimeClient { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + */ + constructor(endPoint, options) { + var _a; + this.accessTokenValue = null; + this.apiKey = null; + this.channels = new Array(); + this.endPoint = ''; + this.httpEndpoint = ''; + /** @deprecated headers cannot be set on websocket connections */ + this.headers = {}; + this.params = {}; + this.timeout = constants_1.DEFAULT_TIMEOUT; + this.transport = null; + this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.heartbeatTimer = undefined; + this.pendingHeartbeatRef = null; + this.heartbeatCallback = noop; + this.ref = 0; + this.reconnectTimer = null; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new serializer_1.default(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [], + }; + this.accessToken = null; + this._connectionState = 'disconnected'; + this._wasManualDisconnect = false; + this._authPromise = null; + /** + * Use either custom fetch, if provided, or default fetch to make HTTP requests + * + * @internal + */ + this._resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + // Validate required parameters + if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) { + throw new Error('API key is required to connect to Realtime'); } - sftp.emit('ready'); - }); - } - - sftp.emit('ready'); - }, - [RESPONSE.STATUS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - uint32 error/status code - string error message (ISO-10646 UTF-8) - string language tag - */ - const errorCode = bufferParser.readUInt32BE(); - const errorMsg = bufferParser.readString(true); - bufferParser.clear(); - - // Note: we avoid checking that the error message and language tag are in - // the packet because there are some broken implementations that incorrectly - // omit them. The language tag in general was never really used amongst ssh - // implementations, so in the case of a missing error message we just - // default to something sensible. - - if (sftp._debug) { - const jsonMsg = JSON.stringify(errorMsg); - sftp._debug( - `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` - ); - } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') { - if (errorCode === STATUS_CODE.OK) { - req.cb(); - return; - } - const err = new Error(errorMsg - || STATUS_CODE_STR[errorCode] - || 'Unknown status'); - err.code = errorCode; - req.cb(err); - } - }, - [RESPONSE.HANDLE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); - } - - sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); - - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') - req.cb(undefined, handle); - }, - [RESPONSE.DATA]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; + this.apiKey = options.params.apikey; + // Initialize endpoint URLs + this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; + this.httpEndpoint = (0, transformers_1.httpEndpointURL)(endPoint); + this._initializeOptions(options); + this._setupReconnectionTimer(); + this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); } - /* - string data - */ - if (req && typeof req.cb === 'function') { - if (req.buffer) { - // We have already pre-allocated space to store the data - - const nb = bufferParser.readString(req.buffer); - bufferParser.clear(); - - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - req.cb(undefined, req.buffer, nb); - return; + /** + * Connects the socket, unless already connected. + */ + connect() { + // Skip if already connecting, disconnecting, or connected + if (this.isConnecting() || + this.isDisconnecting() || + (this.conn !== null && this.isConnected())) { + return; } - } else { - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` - ); - req.cb(undefined, data); - return; + this._setConnectionState('connecting'); + this._setAuthSafely('connect'); + // Establish WebSocket connection + if (this.transport) { + // Use custom transport if provided + this.conn = new this.transport(this.endpointURL()); } - } - } else { - const nb = bufferParser.skipString(); - bufferParser.clear(); - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - return; - } - } - - return doFatalSFTPError(sftp, 'Malformed DATA packet'); - }, - [RESPONSE.NAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - uint32 count - repeats count times: - string filename - string longname - ATTRS attrs - */ - const count = bufferParser.readUInt32BE(); - if (count !== undefined) { - let names = []; - for (let i = 0; i < count; ++i) { - // We are going to assume UTF-8 for filenames despite the SFTPv3 - // spec not specifying an encoding because the specs for newer - // versions of the protocol all explicitly specify UTF-8 for - // filenames - const filename = bufferParser.readString(true); - - // `longname` only exists in SFTPv3 and since it typically will - // contain the filename, we assume it is also UTF-8 - const longname = bufferParser.readString(true); - - const attrs = readAttrs(sftp._biOpt); - if (attrs === undefined) { - names = undefined; - break; + else { + // Try to use native WebSocket + try { + this.conn = websocket_factory_1.default.createWebSocket(this.endpointURL()); + } + catch (error) { + this._setConnectionState('disconnected'); + const errorMessage = error.message; + // Provide helpful error message based on environment + if (errorMessage.includes('Node.js')) { + throw new Error(`${errorMessage}\n\n` + + 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' + + 'Option 1: Use Node.js 22+ which has native WebSocket support\n' + + 'Option 2: Install and provide the "ws" package:\n\n' + + ' npm install ws\n\n' + + ' import ws from "ws"\n' + + ' const client = new RealtimeClient(url, {\n' + + ' ...options,\n' + + ' transport: ws\n' + + ' })'); + } + throw new Error(`WebSocket not available: ${errorMessage}`); + } } - names.push({ filename, longname, attrs }); - } - if (names !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` - ); - bufferParser.clear(); - if (req && typeof req.cb === 'function') - req.cb(undefined, names); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed NAME packet'); - }, - [RESPONSE.ATTRS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; + this._setupConnectionHandlers(); } - /* - ATTRS attrs - */ - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs !== undefined) { - sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); - if (req && typeof req.cb === 'function') - req.cb(undefined, attrs); - return; + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: constants_1.VSN })); } - - return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); - }, - [RESPONSE.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - if (reqID !== undefined) { - const req = sftp._requests[reqID]; - if (req) { - delete sftp._requests[reqID]; - switch (req.extended) { - case 'statvfs@openssh.com': - case 'fstatvfs@openssh.com': { - /* - uint64 f_bsize // file system block size - uint64 f_frsize // fundamental fs block size - uint64 f_blocks // number of blocks (unit f_frsize) - uint64 f_bfree // free blocks in file system - uint64 f_bavail // free blocks for non-root - uint64 f_files // total file inodes - uint64 f_ffree // free file inodes - uint64 f_favail // free file inodes for to non-root - uint64 f_fsid // file system id - uint64 f_flag // bit mask of f_flag values - uint64 f_namemax // maximum filename length - */ - const biOpt = sftp._biOpt; - const stats = { - f_bsize: bufferParser.readUInt64BE(biOpt), - f_frsize: bufferParser.readUInt64BE(biOpt), - f_blocks: bufferParser.readUInt64BE(biOpt), - f_bfree: bufferParser.readUInt64BE(biOpt), - f_bavail: bufferParser.readUInt64BE(biOpt), - f_files: bufferParser.readUInt64BE(biOpt), - f_ffree: bufferParser.readUInt64BE(biOpt), - f_favail: bufferParser.readUInt64BE(biOpt), - f_sid: bufferParser.readUInt64BE(biOpt), - f_flag: bufferParser.readUInt64BE(biOpt), - f_namemax: bufferParser.readUInt64BE(biOpt), - }; - if (stats.f_namemax === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, stats); + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.isDisconnecting()) { return; - } - case 'limits@openssh.com': { - /* - uint64 max-packet-length - uint64 max-read-length - uint64 max-write-length - uint64 max-open-handles - */ - const limits = { - maxPktLen: bufferParser.readUInt64BE(), - maxReadLen: bufferParser.readUInt64BE(), - maxWriteLen: bufferParser.readUInt64BE(), - maxOpenHandles: bufferParser.readUInt64BE(), + } + this._setConnectionState('disconnecting', true); + if (this.conn) { + // Setup fallback timer to prevent hanging in disconnecting state + const fallbackTimer = setTimeout(() => { + this._setConnectionState('disconnected'); + }, 100); + this.conn.onclose = () => { + clearTimeout(fallbackTimer); + this._setConnectionState('disconnected'); }; - if (limits.maxOpenHandles === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, limits); - return; - } - case 'users-groups-by-id@openssh.com': { - /* - string usernames - string username1 - ... - string groupnames - string groupname1 - ... - */ - const usernameCount = bufferParser.readUInt32BE(); - if (usernameCount === undefined) - break; - const usernames = new Array(usernameCount); - for (let i = 0; i < usernames.length; ++i) - usernames[i] = bufferParser.readString(true); - - const groupnameCount = bufferParser.readUInt32BE(); - if (groupnameCount === undefined) - break; - const groupnames = new Array(groupnameCount); - for (let i = 0; i < groupnames.length; ++i) - groupnames[i] = bufferParser.readString(true); - if (groupnames.length > 0 - && groupnames[groupnames.length - 1] === undefined) { - break; - } - - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, usernames, groupnames); - return; - } - default: - // Unknown extended request - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(); - return; + // Close the WebSocket connection + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); + } + else { + this.conn.close(); + } + this._teardownConnection(); + } + else { + this._setConnectionState('disconnected'); } - } else { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); - }, -}; -const SERVER_HANDLERS = { - [REQUEST.INIT]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate INIT packet'); - - const extensions = {}; - - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed INIT packet'); - - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received INIT (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); - } - } - - sendOrBuffer(sftp, SERVER_VERSION_BUFFER); - - sftp._version = version; - sftp._extensions = extensions; - sftp.emit('ready'); - }, - [REQUEST.OPEN]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string filename - uint32 pflags - ATTRS attrs - */ - const filename = bufferParser.readString(true); - const pflags = bufferParser.readUInt32BE(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed OPEN packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); - - if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.CLOSE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); - - if (!sftp.emit('CLOSE', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READ]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - uint32 len - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const len = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (len === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READ packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); - - if (!sftp.emit('READ', reqID, handle, offset, len)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.WRITE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - string data - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed WRITE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); - - if (!sftp.emit('WRITE', reqID, handle, offset, data)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); } - }, - [REQUEST.LSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); - - if (!sftp.emit('LSTAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Returns all created channels + */ + getChannels() { + return this.channels; } - }, - [REQUEST.FSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); - - if (!sftp.emit('FSTAT', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel) { + const status = await channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; } - }, - [REQUEST.SETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); - - if (!sftp.emit('SETSTAT', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels() { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.channels = []; + this.disconnect(); + return values_1; } - }, - [REQUEST.FSETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - ATTRS attrs - */ - const handle = bufferParser.readString(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received FSETSTAT (id:${reqID})` - ); - - if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); } - }, - [REQUEST.OPENDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); - - if (!sftp.emit('OPENDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case constants_1.SOCKET_STATES.connecting: + return constants_1.CONNECTION_STATE.Connecting; + case constants_1.SOCKET_STATES.open: + return constants_1.CONNECTION_STATE.Open; + case constants_1.SOCKET_STATES.closing: + return constants_1.CONNECTION_STATE.Closing; + default: + return constants_1.CONNECTION_STATE.Closed; + } } - }, - [REQUEST.READDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); - - if (!sftp.emit('READDIR', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === constants_1.CONNECTION_STATE.Open; } - }, - [REQUEST.REMOVE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); - - if (!sftp.emit('REMOVE', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting() { + return this._connectionState === 'connecting'; } - }, - [REQUEST.MKDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); - - if (!sftp.emit('MKDIR', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting() { + return this._connectionState === 'disconnecting'; } - }, - [REQUEST.RMDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); - - if (!sftp.emit('RMDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + channel(topic, params = { config: {} }) { + const realtimeTopic = `realtime:${topic}`; + const exists = this.getChannels().find((c) => c.topic === realtimeTopic); + if (!exists) { + const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } + else { + return exists; + } } - }, - [REQUEST.REALPATH]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received REALPATH (id:${reqID})` - ); - - if (!sftp.emit('REALPATH', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + const callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log('push', `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + callback(); + } + else { + this.sendBuffer.push(callback); + } } - }, - [REQUEST.STAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed STAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); - - if (!sftp.emit('STAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * @param token A JWT string to override the token set on the client. + */ + async setAuth(token = null) { + this._authPromise = this._performAuth(token); + try { + await this._authPromise; + } + finally { + this._authPromise = null; + } } - }, - [REQUEST.RENAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string oldpath - string newpath - */ - const oldPath = bufferParser.readString(true); - const newPath = bufferParser.readString(true); - bufferParser.clear(); - - if (newPath === undefined) - return doFatalSFTPError(sftp, 'Malformed RENAME packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); - - if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Sends a heartbeat message if the socket is connected. + */ + async sendHeartbeat() { + var _a; + if (!this.isConnected()) { + try { + this.heartbeatCallback('disconnected'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + return; + } + // Handle heartbeat timeout and force reconnection if needed + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); + try { + this.heartbeatCallback('timeout'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + // Force reconnection after heartbeat timeout + this._wasManualDisconnect = false; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, 'heartbeat timeout'); + setTimeout(() => { + var _a; + if (!this.isConnected()) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); + return; + } + // Send heartbeat message to server + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }); + try { + this.heartbeatCallback('sent'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + this._setAuthSafely('heartbeat'); } - }, - [REQUEST.READLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed READLINK packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received READLINK (id:${reqID})` - ); - - if (!sftp.emit('READLINK', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + onHeartbeat(callback) { + this.heartbeatCallback = callback; } - }, - [REQUEST.SYMLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string linkpath - string targetpath - */ - const linkPath = bufferParser.readString(true); - const targetPath = bufferParser.readString(true); - bufferParser.clear(); - - if (targetPath === undefined) - return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); - - let handled; - if (sftp._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); - } else { - handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); + /** + * Flushes send buffer + */ + flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } } - if (!handled) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } + else { + this.ref = newRef; + } + return this.ref.toString(); } - }, - [REQUEST.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string extended-request - ... any request-specific data ... - */ - const extName = bufferParser.readString(true); - if (extName === undefined) { - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } } - - let extData; - if (bufferParser.avail()) - extData = bufferParser.readRaw(); - bufferParser.clear(); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED (id:${reqID})` - ); - - if (!sftp.emit('EXTENDED', reqID, extName, extData)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c.topic !== channel.topic); } - }, -}; - -// ============================================================================= -// ReadStream/WriteStream-related ============================================== -// ============================================================================= -const { - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - validateNumber -} = __nccwpck_require__(47609); - -const kMinPoolSpace = 128; - -let pool; -// It can happen that we expect to read a large chunk of data, and reserve -// a large chunk of the pool accordingly, but the read() call only filled -// a portion of it. If a concurrently executing read() then uses the same pool, -// the "reserved" portion cannot be used, so we allow it to be re-used as a -// new pool later. -const poolFragments = []; - -function allocNewPool(poolSize) { - if (poolFragments.length > 0) - pool = poolFragments.pop(); - else - pool = Buffer.allocUnsafe(poolSize); - pool.used = 0; -} - -// Check the `this.start` and `this.end` of stream. -function checkPosition(pos, name) { - if (!Number.isSafeInteger(pos)) { - validateNumber(pos, name); - if (!Number.isInteger(pos)) - throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); - } - if (pos < 0) - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); -} - -function roundUpToMultipleOf8(n) { - return (n + 7) & ~7; // Align to 8 byte boundary. -} - -function ReadStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // A little bit bigger buffer and water marks by default - if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - ReadableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'r' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.end = options.end; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesRead = 0; - this.isClosed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (this.end === undefined) { - this.end = Infinity; - } else if (this.end !== Infinity) { - checkPosition(this.end, 'end'); - - if (this.start !== undefined && this.start > this.end) { - throw new ERR_OUT_OF_RANGE( - 'start', - `<= "end" (here: ${this.end})`, - this.start - ); + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + // Handle heartbeat responses + if (msg.topic === 'phoenix' && msg.event === 'phx_reply') { + try { + this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + } + // Handle pending heartbeat reference cleanup + if (msg.ref && msg.ref === this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + } + // Log incoming message + const { topic, event, payload, ref } = msg; + const refString = ref ? `(${ref})` : ''; + const status = payload.status || ''; + this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload); + // Route message to appropriate channels + this.channels + .filter((channel) => channel._isMember(topic)) + .forEach((channel) => channel._trigger(event, payload, ref)); + this._triggerStateCallbacks('message', msg); + }); } - } - - this.on('end', function() { - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(ReadStream, ReadableStream); - -ReadStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + /** + * Clear specific timer + * @internal + */ + _clearTimer(timer) { + var _a; + if (timer === 'heartbeat' && this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = undefined; + } + else if (timer === 'reconnect') { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset(); + } } - - this.handle = handle; - this.emit('open', handle); - this.emit('ready'); - // Start the flow of data. - this.read(); - }); -}; - -ReadStream.prototype._read = function(n) { - if (!Buffer.isBuffer(this.handle)) - return this.once('open', () => this._read(n)); - - // XXX: safe to remove this? - if (this.destroyed) - return; - - if (!pool || pool.length - pool.used < kMinPoolSpace) { - // Discard the old pool. - allocNewPool(this.readableHighWaterMark - || this._readableState.highWaterMark); - } - - // Grab another reference to the pool in the case that while we're - // in the thread pool another read() finishes up the pool, and - // allocates a new one. - const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); - const start = pool.used; - - if (this.end !== undefined) - toRead = Math.min(this.end - this.pos + 1, toRead); - - // Already read everything we were supposed to read! - // treat as EOF. - if (toRead <= 0) - return this.push(null); - - // the actual read. - this.sftp.read(this.handle, - pool, - pool.used, - toRead, - this.pos, - (er, bytesRead) => { - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + /** + * Clear all timers + * @internal + */ + _clearAllTimers() { + this._clearTimer('heartbeat'); + this._clearTimer('reconnect'); } - let b = null; - - // Now that we know how much data we have actually read, re-wind the - // 'used' field if we can, and otherwise allow the remainder of our - // reservation to be used as a new pool later. - if (start + toRead === thisPool.used && thisPool === pool) { - thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); - } else { - // Round down to the next lowest multiple of 8 to ensure the new pool - // fragment start and end positions are aligned to an 8 byte boundary. - const alignedEnd = (start + toRead) & ~7; - const alignedStart = roundUpToMultipleOf8(start + bytesRead); - if (alignedEnd - alignedStart >= kMinPoolSpace) - poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); + /** + * Setup connection handlers for WebSocket events + * @internal + */ + _setupConnectionHandlers() { + if (!this.conn) + return; + // Set binary type if supported (browsers and most WebSocket implementations) + if ('binaryType' in this.conn) { + ; + this.conn.binaryType = 'arraybuffer'; + } + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); } - - if (bytesRead > 0) { - this.bytesRead += bytesRead; - b = thisPool.slice(start, start + bytesRead); + /** + * Teardown connection and cleanup resources + * @internal + */ + _teardownConnection() { + if (this.conn) { + this.conn.onopen = null; + this.conn.onerror = null; + this.conn.onmessage = null; + this.conn.onclose = null; + this.conn = null; + } + this._clearAllTimers(); + this.channels.forEach((channel) => channel.teardown()); } - - // Move the pool positions, and internal position for reading. - this.pos += bytesRead; - - this.push(b); - }); - - pool.used = roundUpToMultipleOf8(pool.used + toRead); -}; - -ReadStream.prototype._destroy = function(err, cb) { - if (this._opening && !Buffer.isBuffer(this.handle)) { - this.once('open', closeStream.bind(null, this, cb, err)); - return; - } - - closeStream(this, cb, err); - this.handle = null; - this._opening = false; -}; - -function closeStream(stream, cb, err) { - if (!stream.handle) - return onclose(); - - stream.sftp.close(stream.handle, onclose); - - function onclose(er) { - er = er || err; - cb(er); - stream.isClosed = true; - if (!er) - stream.emit('close'); - } -} - -ReadStream.prototype.close = function(cb) { - this.destroy(null, cb); -}; - -Object.defineProperty(ReadStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); - -// TODO: add `concurrency` setting to allow more than one in-flight WRITE -// request to server to improve throughput -function WriteStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - WritableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'w' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesWritten = 0; - this.isClosed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (options.encoding) - this.setDefaultEncoding(options.encoding); - - // Node v6.x only - this.on('finish', function() { - if (this._writableState.finalCalled) - return; - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(WriteStream, WritableStream); - -WriteStream.prototype._final = function(cb) { - if (this.autoClose) - this.destroy(); - cb(); -}; - -WriteStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + /** @internal */ + _onConnOpen() { + this._setConnectionState('connected'); + this.log('transport', `connected to ${this.endpointURL()}`); + this.flushSendBuffer(); + this._clearTimer('reconnect'); + if (!this.worker) { + this._startHeartbeat(); + } + else { + if (!this.workerRef) { + this._startWorkerHeartbeat(); + } + } + this._triggerStateCallbacks('open'); } - - this.handle = handle; - - const tryAgain = (err) => { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() for - // whatever reason - this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); - return; - } - - // SFTPv3 requires absolute offsets, no matter the open flag used - if (this.flags[0] === 'a') { - const tryStat = (err, st) => { - if (err) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.sftp.stat(this.path, (err_, st_) => { - if (err_) { - this.destroy(); - this.emit('error', err); - return; - } - tryStat(null, st_); - }); - return; - } - - this.pos = st.size; - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fstat(handle, tryStat); - return; - } - - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fchmod(handle, this.mode, tryAgain); - }); -}; - -WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) { - const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); - return this.emit('error', err); - } - - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._write(data, encoding, cb); - }); - } - - this.sftp.write(this.handle, - data, - 0, - data.length, - this.pos, - (er, bytes) => { - if (er) { - if (this.autoClose) - this.destroy(); - return cb(er); + /** @internal */ + _startHeartbeat() { + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); } - this.bytesWritten += bytes; - cb(); - }); - - this.pos += data.length; -}; - -WriteStream.prototype._writev = function(data, cb) { - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._writev(data, cb); - }); - } - - const sftp = this.sftp; - const handle = this.handle; - let writesLeft = data.length; - - const onwrite = (er, bytes) => { - if (er) { - this.destroy(); - return cb(er); + /** @internal */ + _startWorkerHeartbeat() { + if (this.workerUrl) { + this.log('worker', `starting worker for from ${this.workerUrl}`); + } + else { + this.log('worker', `starting default worker`); + } + const objectUrl = this._workerObjectUrl(this.workerUrl); + this.workerRef = new Worker(objectUrl); + this.workerRef.onerror = (error) => { + this.log('worker', 'worker error', error.message); + this.workerRef.terminate(); + }; + this.workerRef.onmessage = (event) => { + if (event.data.event === 'keepAlive') { + this.sendHeartbeat(); + } + }; + this.workerRef.postMessage({ + event: 'start', + interval: this.heartbeatIntervalMs, + }); } - this.bytesWritten += bytes; - if (--writesLeft === 0) - cb(); - }; - - // TODO: try to combine chunks to reduce number of requests to the server? - for (let i = 0; i < data.length; ++i) { - const chunk = data[i].chunk; - - sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); - this.pos += chunk.length; - } -}; - -if (typeof WritableStream.prototype.destroy !== 'function') - WriteStream.prototype.destroy = ReadStream.prototype.destroy; - -WriteStream.prototype._destroy = ReadStream.prototype._destroy; -WriteStream.prototype.close = function(cb) { - if (cb) { - if (this.isClosed) { - process.nextTick(cb); - return; + /** @internal */ + _onConnClose(event) { + var _a; + this._setConnectionState('disconnected'); + this.log('transport', 'close', event); + this._triggerChanError(); + this._clearTimer('heartbeat'); + // Only schedule reconnection if it wasn't a manual disconnect + if (!this._wasManualDisconnect) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + this._triggerStateCallbacks('close', event); } - this.on('close', cb); - } - - // If we are not autoClosing, we should call - // destroy on 'finish'. - if (!this.autoClose) - this.on('finish', this.destroy.bind(this)); - - this.end(); -}; - -// There is no shutdown() for files. -WriteStream.prototype.destroySoon = WriteStream.prototype.end; - -Object.defineProperty(WriteStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); -// ============================================================================= - -module.exports = { - flagsToString, - OPEN_MODE, - SFTP, - Stats, - STATUS_CODE, - stringToFlags, -}; - - -/***/ }), - -/***/ 36832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const crypto = __nccwpck_require__(6113); - -let cpuInfo; -try { - cpuInfo = __nccwpck_require__(24137)(); -} catch {} - -const { bindingAvailable, CIPHER_INFO, MAC_INFO } = __nccwpck_require__(45708); - -const eddsaSupported = (() => { - if (typeof crypto.sign === 'function' - && typeof crypto.verify === 'function') { - const key = - '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' - + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; - const data = Buffer.from('a'); - let sig; - let verified; - try { - sig = crypto.sign(null, data, key); - verified = crypto.verify(null, data, key, sig); - } catch {} - return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); - } - - return false; -})(); - -const curve25519Supported = (typeof crypto.diffieHellman === 'function' - && typeof crypto.generateKeyPairSync === 'function' - && typeof crypto.createPublicKey === 'function'); - -const DEFAULT_KEX = [ - // https://tools.ietf.org/html/rfc5656#section-10.1 - 'ecdh-sha2-nistp256', - 'ecdh-sha2-nistp384', - 'ecdh-sha2-nistp521', - - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha256', - - // https://tools.ietf.org/html/rfc8268 - 'diffie-hellman-group14-sha256', - 'diffie-hellman-group15-sha512', - 'diffie-hellman-group16-sha512', - 'diffie-hellman-group17-sha512', - 'diffie-hellman-group18-sha512', -]; -if (curve25519Supported) { - DEFAULT_KEX.unshift('curve25519-sha256'); - DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); -} -const SUPPORTED_KEX = DEFAULT_KEX.concat([ - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha1', - - 'diffie-hellman-group14-sha1', // REQUIRED - 'diffie-hellman-group1-sha1', // REQUIRED -]); - - -const DEFAULT_SERVER_HOST_KEY = [ - 'ecdsa-sha2-nistp256', - 'ecdsa-sha2-nistp384', - 'ecdsa-sha2-nistp521', - 'rsa-sha2-512', // RFC 8332 - 'rsa-sha2-256', // RFC 8332 - 'ssh-rsa', -]; -if (eddsaSupported) - DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); -const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ - 'ssh-dss', -]); - - -const canUseCipher = (() => { - const ciphers = crypto.getCiphers(); - return (name) => ciphers.includes(CIPHER_INFO[name].sslName); -})(); -let DEFAULT_CIPHER = [ - // http://tools.ietf.org/html/rfc5647 - 'aes128-gcm@openssh.com', - 'aes256-gcm@openssh.com', - - // http://tools.ietf.org/html/rfc4344#section-4 - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', -]; -if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { - // We know for sure the CPU does not support AES acceleration - if (bindingAvailable) - DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); - else - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { - // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers - // seem to outperform it on x86, but it seems to be faster than CTR ciphers - DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); -} else { - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} -DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); -const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ - 'aes256-cbc', - 'aes192-cbc', - 'aes128-cbc', - 'blowfish-cbc', - '3des-cbc', - 'aes128-gcm', - 'aes256-gcm', - - // http://tools.ietf.org/html/rfc4345#section-4: - 'arcfour256', - 'arcfour128', - - 'cast128-cbc', - 'arcfour', -].filter(canUseCipher)); - - -const canUseMAC = (() => { - const hashes = crypto.getHashes(); - return (name) => hashes.includes(MAC_INFO[name].sslName); -})(); -const DEFAULT_MAC = [ - 'hmac-sha2-256-etm@openssh.com', - 'hmac-sha2-512-etm@openssh.com', - 'hmac-sha1-etm@openssh.com', - 'hmac-sha2-256', - 'hmac-sha2-512', - 'hmac-sha1', -].filter(canUseMAC); -const SUPPORTED_MAC = DEFAULT_MAC.concat([ - 'hmac-md5', - 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 - 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 - 'hmac-ripemd160', - 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 - 'hmac-md5-96', // first 96 bits of HMAC-MD5 -].filter(canUseMAC)); - -const DEFAULT_COMPRESSION = [ - 'none', - 'zlib@openssh.com', // ZLIB (LZ77) compression, except - // compression/decompression does not start until after - // successful user authentication - 'zlib', // ZLIB (LZ77) compression -]; -const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ -]); - - -const COMPAT = { - BAD_DHGEX: 1 << 0, - OLD_EXIT: 1 << 1, - DYN_RPORT_BUG: 1 << 2, - BUG_DHGEX_LARGE: 1 << 3, - IMPLY_RSA_SHA2_SIGALGS: 1 << 4, -}; - -module.exports = { - MESSAGE: { - // Transport layer protocol -- generic (1-19) - DISCONNECT: 1, - IGNORE: 2, - UNIMPLEMENTED: 3, - DEBUG: 4, - SERVICE_REQUEST: 5, - SERVICE_ACCEPT: 6, - EXT_INFO: 7, // RFC 8308 - - // Transport layer protocol -- algorithm negotiation (20-29) - KEXINIT: 20, - NEWKEYS: 21, - - // Transport layer protocol -- key exchange method-specific (30-49) - KEXDH_INIT: 30, - KEXDH_REPLY: 31, - - KEXDH_GEX_GROUP: 31, - KEXDH_GEX_INIT: 32, - KEXDH_GEX_REPLY: 33, - KEXDH_GEX_REQUEST: 34, - - KEXECDH_INIT: 30, - KEXECDH_REPLY: 31, - - // User auth protocol -- generic (50-59) - USERAUTH_REQUEST: 50, - USERAUTH_FAILURE: 51, - USERAUTH_SUCCESS: 52, - USERAUTH_BANNER: 53, - - // User auth protocol -- user auth method-specific (60-79) - USERAUTH_PASSWD_CHANGEREQ: 60, - - USERAUTH_PK_OK: 60, - - USERAUTH_INFO_REQUEST: 60, - USERAUTH_INFO_RESPONSE: 61, - - // Connection protocol -- generic (80-89) - GLOBAL_REQUEST: 80, - REQUEST_SUCCESS: 81, - REQUEST_FAILURE: 82, - - // Connection protocol -- channel-related (90-127) - CHANNEL_OPEN: 90, - CHANNEL_OPEN_CONFIRMATION: 91, - CHANNEL_OPEN_FAILURE: 92, - CHANNEL_WINDOW_ADJUST: 93, - CHANNEL_DATA: 94, - CHANNEL_EXTENDED_DATA: 95, - CHANNEL_EOF: 96, - CHANNEL_CLOSE: 97, - CHANNEL_REQUEST: 98, - CHANNEL_SUCCESS: 99, - CHANNEL_FAILURE: 100 - - // Reserved for client protocols (128-191) - - // Local extensions (192-155) - }, - DISCONNECT_REASON: { - HOST_NOT_ALLOWED_TO_CONNECT: 1, - PROTOCOL_ERROR: 2, - KEY_EXCHANGE_FAILED: 3, - RESERVED: 4, - MAC_ERROR: 5, - COMPRESSION_ERROR: 6, - SERVICE_NOT_AVAILABLE: 7, - PROTOCOL_VERSION_NOT_SUPPORTED: 8, - HOST_KEY_NOT_VERIFIABLE: 9, - CONNECTION_LOST: 10, - BY_APPLICATION: 11, - TOO_MANY_CONNECTIONS: 12, - AUTH_CANCELED_BY_USER: 13, - NO_MORE_AUTH_METHODS_AVAILABLE: 14, - ILLEGAL_USER_NAME: 15, - }, - DISCONNECT_REASON_STR: undefined, - CHANNEL_OPEN_FAILURE: { - ADMINISTRATIVELY_PROHIBITED: 1, - CONNECT_FAILED: 2, - UNKNOWN_CHANNEL_TYPE: 3, - RESOURCE_SHORTAGE: 4 - }, - TERMINAL_MODE: { - TTY_OP_END: 0, // Indicates end of options. - VINTR: 1, // Interrupt character; 255 if none. Similarly for the - // other characters. Not all of these characters are - // supported on all systems. - VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX - // systems). - VERASE: 3, // Erase the character to left of the cursor. - VKILL: 4, // Kill the current input line. - VEOF: 5, // End-of-file character (sends EOF from the - // terminal). - VEOL: 6, // End-of-line character in addition to carriage - // return and/or linefeed. - VEOL2: 7, // Additional end-of-line character. - VSTART: 8, // Continues paused output (normally control-Q). - VSTOP: 9, // Pauses output (normally control-S). - VSUSP: 10, // Suspends the current program. - VDSUSP: 11, // Another suspend character. - VREPRINT: 12, // Reprints the current input line. - VWERASE: 13, // Erases a word left of cursor. - VLNEXT: 14, // Enter the next character typed literally, even if - // it is a special character - VFLUSH: 15, // Character to flush output. - VSWTCH: 16, // Switch to a different shell layer. - VSTATUS: 17, // Prints system status line (load, command, pid, - // etc). - VDISCARD: 18, // Toggles the flushing of terminal output. - IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 - // if this flag is FALSE, and 1 if it is TRUE. - PARMRK: 31, // Mark parity and framing errors. - INPCK: 32, // Enable checking of parity errors. - ISTRIP: 33, // Strip 8th bit off characters. - INLCR: 34, // Map NL into CR on input. - IGNCR: 35, // Ignore CR on input. - ICRNL: 36, // Map CR to NL on input. - IUCLC: 37, // Translate uppercase characters to lowercase. - IXON: 38, // Enable output flow control. - IXANY: 39, // Any char will restart after stop. - IXOFF: 40, // Enable input flow control. - IMAXBEL: 41, // Ring bell on input queue full. - ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. - ICANON: 51, // Canonicalize input lines. - XCASE: 52, // Enable input and output of uppercase characters by - // preceding their lowercase equivalents with "\". - ECHO: 53, // Enable echoing. - ECHOE: 54, // Visually erase chars. - ECHOK: 55, // Kill character discards current line. - ECHONL: 56, // Echo NL even if ECHO is off. - NOFLSH: 57, // Don't flush after interrupt. - TOSTOP: 58, // Stop background jobs from output. - IEXTEN: 59, // Enable extensions. - ECHOCTL: 60, // Echo control characters as ^(Char). - ECHOKE: 61, // Visual erase for line kill. - PENDIN: 62, // Retype pending input. - OPOST: 70, // Enable output processing. - OLCUC: 71, // Convert lowercase to uppercase. - ONLCR: 72, // Map NL to CR-NL. - OCRNL: 73, // Translate carriage return to newline (output). - ONOCR: 74, // Translate newline to carriage return-newline - // (output). - ONLRET: 75, // Newline performs a carriage return (output). - CS7: 90, // 7 bit mode. - CS8: 91, // 8 bit mode. - PARENB: 92, // Parity enable. - PARODD: 93, // Odd parity, else even. - TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. - TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. - }, - CHANNEL_EXTENDED_DATATYPE: { - STDERR: 1, - }, - - SIGNALS: [ - 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', - 'USR2', 'KILL', 'PIPE' - ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), - - COMPAT, - COMPAT_CHECKS: [ - [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], - [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ], - [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations - [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ], - [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ], - ], - - // KEX proposal-related - DEFAULT_KEX, - SUPPORTED_KEX, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY, - DEFAULT_CIPHER, - SUPPORTED_CIPHER, - DEFAULT_MAC, - SUPPORTED_MAC, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION, - - curve25519Supported, - eddsaSupported, -}; - -module.exports.DISCONNECT_REASON_BY_VALUE = - Array.from(Object.entries(module.exports.DISCONNECT_REASON)) - .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); - - -/***/ }), - -/***/ 45708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// TODO: -// * make max packet size configurable -// * if decompression is enabled, use `._packet` in decipher instances as -// input to (sync) zlib inflater with appropriate offset and length to -// avoid an additional copy of payload data before inflation -// * factor decompression status into packet length checks - - -const { - createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual -} = __nccwpck_require__(6113); - -const { readUInt32BE, writeUInt32BE } = __nccwpck_require__(49475); - -const FastBuffer = Buffer[Symbol.species]; -const MAX_SEQNO = 2 ** 32 - 1; -const EMPTY_BUFFER = Buffer.alloc(0); -const BUF_INT = Buffer.alloc(4); -const DISCARD_CACHE = new Map(); -const MAX_PACKET_SIZE = 35000; - -let binding; -let AESGCMCipher; -let ChaChaPolyCipher; -let GenericCipher; -let AESGCMDecipher; -let ChaChaPolyDecipher; -let GenericDecipher; -try { - binding = __nccwpck_require__(29041); - ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, - AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); -} catch {} - -const CIPHER_STREAM = 1 << 0; -const CIPHER_INFO = (() => { - function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { - return { - sslName, - blockLen, - keyLen, - ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) - ? ivLen - : blockLen), - authLen, - discardLen, - stream: !!(flags & CIPHER_STREAM), - }; - } - - return { - 'chacha20-poly1305@openssh.com': - info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), - - 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - 'aes128-gcm@openssh.com': - info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm@openssh.com': - info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - - 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), - 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), - 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), - 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), - 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), - 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), - - 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), - 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), - 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), - '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), - 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), - 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), - }; -})(); - -const MAC_INFO = (() => { - function info(sslName, len, actualLen, isETM) { - return { - sslName, - len, - actualLen, - isETM, - }; - } - - return { - 'hmac-md5': info('md5', 16, 16, false), - 'hmac-md5-96': info('md5', 16, 12, false), - 'hmac-ripemd160': info('ripemd160', 20, 20, false), - 'hmac-sha1': info('sha1', 20, 20, false), - 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), - 'hmac-sha1-96': info('sha1', 20, 12, false), - 'hmac-sha2-256': info('sha256', 32, 32, false), - 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), - 'hmac-sha2-256-96': info('sha256', 32, 12, false), - 'hmac-sha2-512': info('sha512', 64, 64, false), - 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), - 'hmac-sha2-512-96': info('sha512', 64, 12, false), - }; -})(); - - -// Should only_be used during the initial handshake -class NullCipher { - constructor(seqno, onWrite) { - this.outSeqno = seqno; - this._onWrite = onWrite; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -const POLY1305_ZEROS = Buffer.alloc(32); -const POLY1305_OUT_COMPUTE = Buffer.alloc(16); -let POLY1305_WASM_MODULE; -let POLY1305_RESULT_MALLOC; -let poly1305_auth; -class ChaChaPolyCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encKeyMain = enc.cipherKey.slice(0, 32); - this._encKeyPktLen = enc.cipherKey.slice(32); - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Encrypt packet length - const pktLenEnc = - createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) - .update(packet.slice(0, 4)); - this._onWrite(pktLenEnc); - - // Encrypt rest of packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const payloadEnc = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(packet.slice(4)); - this._onWrite(payloadEnc); - - // Calculate Poly1305 MAC - poly1305_auth(POLY1305_RESULT_MALLOC, - pktLenEnc, - pktLenEnc.length, - payloadEnc, - payloadEnc.length, - polyKey); - const mac = Buffer.allocUnsafe(16); - mac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - this._onWrite(mac); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class ChaChaPolyCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new ChaChaPolyCipher(enc.cipherKey); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class AESGCMCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encSSLName = enc.cipherInfo.sslName; - this._encKey = enc.cipherKey; - this._encIV = enc.cipherIV; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); - cipher.setAutoPadding(false); - - const lenData = packet.slice(0, 4); - cipher.setAAD(lenData); - this._onWrite(lenData); - - // Encrypt pad length, payload, and padding - const encrypted = cipher.update(packet.slice(4)); - this._onWrite(encrypted); - const final = cipher.final(); - // XXX: final.length === 0 always? - if (final.length) - this._onWrite(final); - - // Generate MAC - const tag = cipher.getAuthTag(); - this._onWrite(tag); - - // Increment counter in IV by 1 for next packet - ivIncrement(this._encIV); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class AESGCMCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new AESGCMCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class GenericCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._macSSLName = enc.macInfo.sslName; - this._macKey = enc.macKey; - this._macActualLen = enc.macInfo.actualLen; - this._macETM = enc.macInfo.isETM; - this._aadLen = (this._macETM ? 4 : 0); - this._dead = false; - - const discardLen = enc.cipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._cipherInstance.update(discard); + /** @internal */ + _onConnError(error) { + this._setConnectionState('disconnected'); + this.log('transport', `${error}`); + this._triggerChanError(); + this._triggerStateCallbacks('error', error); } - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - let mac; - if (this._macETM) { - // Encrypt pad length, payload, and padding - const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); - const encrypted = this._cipherInstance.update( - new Uint8Array(packet.buffer, - packet.byteOffset + 4, - packet.length - 4) - ); - - this._onWrite(lenBytes); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(lenBytes); - mac.update(encrypted); - } else { - // Encrypt length field, pad length, payload, and padding - const encrypted = this._cipherInstance.update(packet); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(packet); + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); } - - let digest = mac.digest(); - if (digest.length > this._macActualLen) - digest = digest.slice(0, this._macActualLen); - this._onWrite(digest); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class GenericCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._macLen = enc.macInfo.len; - this._macActualLen = enc.macInfo.actualLen; - this._aadLen = (enc.macInfo.isETM ? 4 : 0); - this._instance = new GenericCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV, - enc.macInfo.sslName, - enc.macKey, - enc.macInfo.isETM); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + this._macLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - if (this._macActualLen < this._macLen) { - packet = new FastBuffer(packet.buffer, - packet.byteOffset, - (packet.length - - (this._macLen - this._macActualLen))); + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? '&' : '?'; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; } - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class NullDecipher { - constructor(seqno, onPayload) { - this.inSeqno = seqno; - this._onPayload = onPayload; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - while (p < dataLen) { - // Read packet length - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - - if (this._lenBytes < 4) - return; - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (4 + this._len & 7) !== 0) { - throw new Error('Bad packet length'); + _workerObjectUrl(url) { + let result_url; + if (url) { + result_url = url; } - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._packetPos < this._len) { - const nb = Math.min(this._len - this._packetPos, dataLen - p); - let chunk; - if (p !== 0 || nb !== dataLen) - chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - chunk = data; - if (nb === this._len) { - this._packet = chunk; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(chunk, this._packetPos); + else { + const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' }); + result_url = URL.createObjectURL(blob); } - p += nb; - this._packetPos += nb; - if (this._packetPos < this._len) - return; - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + return result_url; } - } -} - -class ChaChaPolyDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decKeyMain = dec.decipherKey.slice(0, 32); - this._decKeyPktLen = dec.decipherKey.slice(32); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._calcMac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - - const decLenBytes = - createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) - .update(this._lenBuf); - this._len = readUInt32BE(decLenBytes, 0); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); + /** + * Set connection state with proper state management + * @internal + */ + _setConnectionState(state, manual = false) { + this._connectionState = state; + if (state === 'connecting') { + this._wasManualDisconnect = false; } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); + else if (state === 'disconnecting') { + this._wasManualDisconnect = manual; } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Calculate and compare Poly1305 MACs - poly1305_auth(POLY1305_RESULT_MALLOC, - this._lenBuf, - 4, - this._packet, - this._packet.length, - polyKey); - - this._calcMac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - if (!timingSafeEqual(this._calcMac, this._mac)) - throw new Error('Invalid MAC'); - - // Decrypt packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const packet = - createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(this._packet); - - const payload = new FastBuffer(packet.buffer, - packet.byteOffset + 1, - packet.length - packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } -} - -class ChaChaPolyDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new ChaChaPolyDecipher(dec.decipherKey); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); + /** + * Perform the actual auth operation + * @internal + */ + async _performAuth(token = null) { + let tokenToSend; + if (token) { + tokenToSend = token; } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); + else if (this.accessToken) { + // Always call the accessToken callback to get fresh token + tokenToSend = await this.accessToken(); } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); + else { + tokenToSend = this.accessTokenValue; + } + if (this.accessTokenValue != tokenToSend) { + this.accessTokenValue = tokenToSend; + this.channels.forEach((channel) => { + const payload = { + access_token: tokenToSend, + version: constants_1.DEFAULT_VERSION, + }; + tokenToSend && channel.updateJoinPayload(payload); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(constants_1.CHANNEL_EVENTS.access_token, { + access_token: tokenToSend, + }); + } + }); } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - this._instance.decrypt(this._packet, this._mac, this.inSeqno); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } -} - -class AESGCMDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = null; - this._decipherSSLName = dec.decipherInfo.sslName; - this._decipherKey = dec.decipherKey; - this._decipherIV = dec.decipherIV; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error('Bad packet length'); + /** + * Wait for any in-flight auth operations to complete + * @internal + */ + async _waitForAuthIfNeeded() { + if (this._authPromise) { + await this._authPromise; } - - this._decipherInstance = createDecipheriv( - this._decipherSSLName, - this._decipherKey, - this._decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._decipherInstance.setAAD(intToBytes(this._len)); - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let decrypted; - if (p !== 0 || nb !== dataLen) { - decrypted = this._decipherInstance.update( - new Uint8Array(data.buffer, data.byteOffset + p, nb) - ); - } else { - decrypted = this._decipherInstance.update(data); + } + /** + * Safely call setAuth with standardized error handling + * @internal + */ + _setAuthSafely(context = 'general') { + this.setAuth().catch((e) => { + this.log('error', `error setting auth in ${context}`, e); + }); + } + /** + * Trigger state change callbacks with proper error handling + * @internal + */ + _triggerStateCallbacks(event, data) { + try { + this.stateChangeCallbacks[event].forEach((callback) => { + try { + callback(data); + } + catch (e) { + this.log('error', `error in ${event} callback`, e); + } + }); } - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; + catch (e) { + this.log('error', `error triggering ${event} callbacks`, e); } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); + } + /** + * Setup reconnection timer with proper configuration + * @internal + */ + _setupReconnectionTimer() { + this.reconnectTimer = new timer_1.default(async () => { + setTimeout(async () => { + await this._waitForAuthIfNeeded(); + if (!this.isConnected()) { + this.connect(); + } + }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); + }, this.reconnectAfterMs); + } + /** + * Initialize client options with defaults + * @internal + */ + _initializeOptions(options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + // Set defaults + this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null; + this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT; + this.heartbeatIntervalMs = + (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; + this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null; + this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; + // Handle special cases + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { + this.logLevel = options.logLevel || options.log_level; + this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - - { - // Verify authentication tag - this._decipherInstance.setAuthTag(this._tag); - - const decrypted = this._decipherInstance.final(); - - // XXX: this should never output any data since stream ciphers always - // return data from .update() and block ciphers must end on a multiple - // of the block length, which would have caused an exception to be - // thrown if the total input was not... - if (decrypted.length) { - if (this._packet) - this._packet.set(decrypted, this._packetPos); - else - this._packet = decrypted; + // Set up functions with defaults + this.reconnectAfterMs = + (_g = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _g !== void 0 ? _g : ((tries) => { + return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; + }); + this.encode = + (_h = options === null || options === void 0 ? void 0 : options.encode) !== null && _h !== void 0 ? _h : ((payload, callback) => { + return callback(JSON.stringify(payload)); + }); + this.decode = (_j = options === null || options === void 0 ? void 0 : options.decode) !== null && _j !== void 0 ? _j : this.serializer.decode.bind(this.serializer); + // Handle worker setup + if (this.worker) { + if (typeof window !== 'undefined' && !window.Worker) { + throw new Error('Web Worker is not supported'); + } + this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; } - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - ivIncrement(this._decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tagPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } } +exports["default"] = RealtimeClient; +//# sourceMappingURL=RealtimeClient.js.map -class AESGCMDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; +/***/ }), - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error(`Bad packet length: ${this._len}`); - } - } +/***/ 5583: +/***/ ((__unused_webpack_module, exports) => { - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } +"use strict"; - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; +var REALTIME_PRESENCE_LISTEN_EVENTS; +(function (REALTIME_PRESENCE_LISTEN_EVENTS) { + REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; +})(REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS = {})); +class RealtimePresence { + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.enabled = false; + this.caller = { + onJoin: () => { }, + onLeave: () => { }, + onSync: () => { }, + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: 'presence_state', + diff: 'presence_diff', + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } + else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }); + }); + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } + else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + }; + if (!onJoin) { + onJoin = () => { }; } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - - this._instance.decrypt(this._packet, this._len, this._tag); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tagPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + if (!onLeave) { + onLeave = () => { }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref']; + delete presence['phx_ref']; + delete presence['phx_ref_prev']; + return presence; + }); + } + else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); } - } } +exports["default"] = RealtimePresence; +//# sourceMappingURL=RealtimePresence.js.map -// TODO: test incremental .update()s vs. copying to _packet and doing a single -// .update() after entire packet read -- a single .update() would allow -// verifying MAC before decrypting for ETM MACs -class GenericDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._decipherInstance.setAutoPadding(false); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen - ); - this._blockSize = dec.decipherInfo.blockLen; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macSSLName = dec.macInfo.sslName; - this._macKey = dec.macKey; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - this._macInstance = null; - - const discardLen = dec.decipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._decipherInstance.update(discard); - } - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data +/***/ }), - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); - } +/***/ 442: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; +"use strict"; - let decrypted; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - decrypted = this._decipherInstance.update(this._block); - this._len = readUInt32BE(decrypted, 0); - need = 4 + this._len - this._blockSize; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; +const tslib_1 = __nccwpck_require__(4351); +const RealtimeClient_1 = tslib_1.__importDefault(__nccwpck_require__(9103)); +exports.RealtimeClient = RealtimeClient_1.default; +const RealtimeChannel_1 = tslib_1.__importStar(__nccwpck_require__(9911)); +exports.RealtimeChannel = RealtimeChannel_1.default; +Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_LISTEN_TYPES; } })); +Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } })); +Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; } })); +Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_CHANNEL_STATES; } })); +const RealtimePresence_1 = tslib_1.__importStar(__nccwpck_require__(5583)); +exports.RealtimePresence = RealtimePresence_1.default; +Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", ({ enumerable: true, get: function () { return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; } })); +const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(3478)); +exports.WebSocketFactory = websocket_factory_1.default; +//# sourceMappingURL=index.js.map - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._blockSize - 1)) !== 0) { - throw new Error('Bad packet length'); - } +/***/ }), - // Create MAC up front to calculate in parallel with decryption - this._macInstance = createHmac(this._macSSLName, this._macKey); +/***/ 88: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - writeUInt32BE(BUF_INT, this.inSeqno, 0); - this._macInstance.update(BUF_INT); - if (this._macETM) { - this._macInstance.update(this._block); - } else { - this._macInstance.update(new Uint8Array(decrypted.buffer, - decrypted.byteOffset, - 4)); - this._pktLen = decrypted.length - 4; - this._packetPos = this._pktLen; - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(decrypted.buffer, - decrypted.byteOffset + 4, - this._packetPos), - 0 - ); - } +"use strict"; - if (p >= dataLen) - return; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.VSN = exports.DEFAULT_VERSION = void 0; +const version_1 = __nccwpck_require__(318); +exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`; +exports.VSN = '1.0.0'; +exports.VERSION = version_1.version; +exports.DEFAULT_TIMEOUT = 10000; +exports.WS_CLOSE_NORMAL = 1000; +exports.MAX_PUSH_BUFFER_SIZE = 100; +var SOCKET_STATES; +(function (SOCKET_STATES) { + SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; + SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; + SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; + SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; +})(SOCKET_STATES || (exports.SOCKET_STATES = SOCKET_STATES = {})); +var CHANNEL_STATES; +(function (CHANNEL_STATES) { + CHANNEL_STATES["closed"] = "closed"; + CHANNEL_STATES["errored"] = "errored"; + CHANNEL_STATES["joined"] = "joined"; + CHANNEL_STATES["joining"] = "joining"; + CHANNEL_STATES["leaving"] = "leaving"; +})(CHANNEL_STATES || (exports.CHANNEL_STATES = CHANNEL_STATES = {})); +var CHANNEL_EVENTS; +(function (CHANNEL_EVENTS) { + CHANNEL_EVENTS["close"] = "phx_close"; + CHANNEL_EVENTS["error"] = "phx_error"; + CHANNEL_EVENTS["join"] = "phx_join"; + CHANNEL_EVENTS["reply"] = "phx_reply"; + CHANNEL_EVENTS["leave"] = "phx_leave"; + CHANNEL_EVENTS["access_token"] = "access_token"; +})(CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = CHANNEL_EVENTS = {})); +var TRANSPORTS; +(function (TRANSPORTS) { + TRANSPORTS["websocket"] = "websocket"; +})(TRANSPORTS || (exports.TRANSPORTS = TRANSPORTS = {})); +var CONNECTION_STATE; +(function (CONNECTION_STATE) { + CONNECTION_STATE["Connecting"] = "connecting"; + CONNECTION_STATE["Open"] = "open"; + CONNECTION_STATE["Closing"] = "closing"; + CONNECTION_STATE["Closed"] = "closed"; +})(CONNECTION_STATE || (exports.CONNECTION_STATE = CONNECTION_STATE = {})); +//# sourceMappingURL=constants.js.map - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (this._macETM) - this._macInstance.update(encrypted); - const decrypted = this._decipherInstance.update(encrypted); - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } +/***/ }), - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); - } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } +/***/ 2292: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Verify MAC - if (!this._macETM) - this._macInstance.update(this._packet); - let calculated = this._macInstance.digest(); - if (this._macActualLen < calculated.length) { - calculated = new Uint8Array(calculated.buffer, - calculated.byteOffset, - this._macActualLen); - } - if (!timingSafeEquals(calculated, this._mac)) - throw new Error('Invalid MAC'); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; +"use strict"; - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const constants_1 = __nccwpck_require__(88); +class Push { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = undefined; + this.ref = ''; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ''; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); } - } -} - -class GenericDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new GenericDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV, - dec.macInfo.sslName, - dec.macKey, - dec.macInfo.isETM, - dec.macInfo.actualLen); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM || dec.decipherInfo.stream - ? 4 - : dec.decipherInfo.blockLen - ); - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); + send() { + if (this._hasReceived('timeout')) { + return; } - - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - this._instance.decryptBlock(this._block); - this._len = readUInt32BE(this._block, 0); - need = 4 + this._len - this._block.length; - } - - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._block.length - 1)) !== 0) { - throw new Error('Bad packet length'); - } - - if (!this._macETM) { - this._pktLen = (this._block.length - 4); - if (this._pktLen) { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(this._block.buffer, - this._block.byteOffset + 4, - this._pktLen), - 0 - ); - } + this.startTimeout(); + this.sent = true; + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }); + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - - // Decrypt and verify MAC - this._instance.decrypt(this._packet, - this.inSeqno, - this._block, - this._mac); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } + this.channel._off(this.refEvent, {}); } - } -} - -// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV -function ivIncrement(iv) { - // eslint-disable-next-line no-unused-expressions - ++iv[11] >>> 8 - && ++iv[10] >>> 8 - && ++iv[9] >>> 8 - && ++iv[8] >>> 8 - && ++iv[7] >>> 8 - && ++iv[6] >>> 8 - && ++iv[5] >>> 8 - && ++iv[4] >>> 8; -} - -const intToBytes = (() => { - const ret = Buffer.alloc(4); - return (n) => { - ret[0] = (n >>> 24); - ret[1] = (n >>> 16); - ret[2] = (n >>> 8); - ret[3] = n; - return ret; - }; -})(); - -function timingSafeEquals(a, b) { - if (a.length !== b.length) { - timingSafeEqual(a, a); - return false; - } - return timingSafeEqual(a, b); -} - -function createCipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.outbound !== 'object' || config.outbound === null) - throw new Error('Invalid outbound'); - - const outbound = config.outbound; - - if (typeof outbound.onWrite !== 'function') - throw new Error('Invalid outbound.onWrite'); - - if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) - throw new Error('Invalid outbound.cipherInfo'); - - if (!Buffer.isBuffer(outbound.cipherKey) - || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { - throw new Error('Invalid outbound.cipherKey'); - } - - if (outbound.cipherInfo.ivLen - && (!Buffer.isBuffer(outbound.cipherIV) - || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { - throw new Error('Invalid outbound.cipherIV'); - } - - if (typeof outbound.seqno !== 'number' - || outbound.seqno < 0 - || outbound.seqno > MAX_SEQNO) { - throw new Error('Invalid outbound.seqno'); - } - - const forceNative = !!outbound.forceNative; - - switch (outbound.cipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMCipher && !forceNative - ? new AESGCMCipherBinding(config) - : new AESGCMCipherNative(config)); - case 'chacha20': - return (ChaChaPolyCipher && !forceNative - ? new ChaChaPolyCipherBinding(config) - : new ChaChaPolyCipherNative(config)); - default: { - if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) - throw new Error('Invalid outbound.macInfo'); - if (!Buffer.isBuffer(outbound.macKey) - || outbound.macKey.length !== outbound.macInfo.len) { - throw new Error('Invalid outbound.macKey'); - } - return (GenericCipher && !forceNative - ? new GenericCipherBinding(config) - : new GenericCipherNative(config)); + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = undefined; } - } -} - -function createDecipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.inbound !== 'object' || config.inbound === null) - throw new Error('Invalid inbound'); - - const inbound = config.inbound; - - if (typeof inbound.onPayload !== 'function') - throw new Error('Invalid inbound.onPayload'); - - if (typeof inbound.decipherInfo !== 'object' - || inbound.decipherInfo === null) { - throw new Error('Invalid inbound.decipherInfo'); - } - - if (!Buffer.isBuffer(inbound.decipherKey) - || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { - throw new Error('Invalid inbound.decipherKey'); - } - - if (inbound.decipherInfo.ivLen - && (!Buffer.isBuffer(inbound.decipherIV) - || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { - throw new Error('Invalid inbound.decipherIV'); - } - - if (typeof inbound.seqno !== 'number' - || inbound.seqno < 0 - || inbound.seqno > MAX_SEQNO) { - throw new Error('Invalid inbound.seqno'); - } - - const forceNative = !!inbound.forceNative; - - switch (inbound.decipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMDecipher && !forceNative - ? new AESGCMDecipherBinding(config) - : new AESGCMDecipherNative(config)); - case 'chacha20': - return (ChaChaPolyDecipher && !forceNative - ? new ChaChaPolyDecipherBinding(config) - : new ChaChaPolyDecipherNative(config)); - default: { - if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) - throw new Error('Invalid inbound.macInfo'); - if (!Buffer.isBuffer(inbound.macKey) - || inbound.macKey.length !== inbound.macInfo.len) { - throw new Error('Invalid inbound.macKey'); - } - return (GenericDecipher && !forceNative - ? new GenericDecipherBinding(config) - : new GenericDecipherNative(config)); + _matchReceive({ status, response }) { + this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; } - } } - -module.exports = { - CIPHER_INFO, - MAC_INFO, - bindingAvailable: !!binding, - init: (() => { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - try { - POLY1305_WASM_MODULE = await __nccwpck_require__(64989)(); - POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); - poly1305_auth = POLY1305_WASM_MODULE.cwrap( - 'poly1305_auth', - null, - ['number', 'array', 'number', 'array', 'number', 'array'] - ); - } catch (ex) { - return reject(ex); - } - resolve(); - }); - })(), - - NullCipher, - createCipher, - NullDecipher, - createDecipher, -}; - +exports["default"] = Push; +//# sourceMappingURL=push.js.map /***/ }), -/***/ 64989: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5360: +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -var createPoly1305 = (function() { - var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; - if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; - return ( -function(createPoly1305) { - createPoly1305 = createPoly1305 || {}; - - -var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; -if(z)B=y?(__nccwpck_require__(71017).dirname)(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__nccwpck_require__(57147));G||(G=__nccwpck_require__(71017));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__nccwpck_require__(57147));G||(G=__nccwpck_require__(71017));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= -0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; -function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; -function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} -function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} -function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; -(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, -a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); -b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; -b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; -function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { +/***/ 8960: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -const MESSAGE_HANDLERS = new Array(256); -[ - (__nccwpck_require__(64126).HANDLERS), - __nccwpck_require__(6475), -].forEach((handlers) => { - // eslint-disable-next-line prefer-const - for (let [type, handler] of Object.entries(handlers)) { - type = +type; - if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) - MESSAGE_HANDLERS[type] = handler; - } -}); - -module.exports = MESSAGE_HANDLERS; - +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +class Timer { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = undefined; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + this.timer = undefined; + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } +} +exports["default"] = Timer; +//# sourceMappingURL=timer.js.map /***/ }), -/***/ 6475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1140: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -const { - bufferSlice, - bufferParser, - doFatalError, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const { - CHANNEL_OPEN_FAILURE, - COMPAT, - MESSAGE, - TERMINAL_MODE, -} = __nccwpck_require__(36832); - -const { - parseKey, -} = __nccwpck_require__(22218); - -const TERMINAL_MODE_BY_VALUE = - Array.from(Object.entries(TERMINAL_MODE)) - .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); - -module.exports = { - // Transport layer protocol ================================================== - [MESSAGE.DISCONNECT]: (self, payload) => { - /* - byte SSH_MSG_DISCONNECT - uint32 reason code - string description in ISO-10646 UTF-8 encoding - string language tag - */ - bufferParser.init(payload, 1); - const reason = bufferParser.readUInt32BE(); - const desc = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DISCONNECT packet' - ); +/** + * Helpers to convert the change Payload into native JS types. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.httpEndpointURL = exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE +var PostgresTypes; +(function (PostgresTypes) { + PostgresTypes["abstime"] = "abstime"; + PostgresTypes["bool"] = "bool"; + PostgresTypes["date"] = "date"; + PostgresTypes["daterange"] = "daterange"; + PostgresTypes["float4"] = "float4"; + PostgresTypes["float8"] = "float8"; + PostgresTypes["int2"] = "int2"; + PostgresTypes["int4"] = "int4"; + PostgresTypes["int4range"] = "int4range"; + PostgresTypes["int8"] = "int8"; + PostgresTypes["int8range"] = "int8range"; + PostgresTypes["json"] = "json"; + PostgresTypes["jsonb"] = "jsonb"; + PostgresTypes["money"] = "money"; + PostgresTypes["numeric"] = "numeric"; + PostgresTypes["oid"] = "oid"; + PostgresTypes["reltime"] = "reltime"; + PostgresTypes["text"] = "text"; + PostgresTypes["time"] = "time"; + PostgresTypes["timestamp"] = "timestamp"; + PostgresTypes["timestamptz"] = "timestamptz"; + PostgresTypes["timetz"] = "timetz"; + PostgresTypes["tsrange"] = "tsrange"; + PostgresTypes["tstzrange"] = "tstzrange"; +})(PostgresTypes || (exports.PostgresTypes = PostgresTypes = {})); +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +const convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + if (!record) { + return {}; } - - self._debug && self._debug( - `Inbound: Received DISCONNECT (${reason}, "${desc}")` - ); - - const handler = self._handlers.DISCONNECT; - handler && handler(self, reason, desc); - }, - [MESSAGE.IGNORE]: (self, payload) => { - /* - byte SSH_MSG_IGNORE - string data - */ - self._debug && self._debug('Inbound: Received IGNORE'); - }, - [MESSAGE.UNIMPLEMENTED]: (self, payload) => { - /* - byte SSH_MSG_UNIMPLEMENTED - uint32 packet sequence number of rejected message - */ - bufferParser.init(payload, 1); - const seqno = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (seqno === undefined) { - return doFatalError( - self, - 'Inbound: Malformed UNIMPLEMENTED packet' - ); + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); + return acc; + }, {}); +}; +exports.convertChangeData = convertChangeData; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +const convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return (0, exports.convertCell)(colType, value); } - - self._debug - && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); - }, - [MESSAGE.DEBUG]: (self, payload) => { - /* - byte SSH_MSG_DEBUG - boolean always_display - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const display = bufferParser.readBool(); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DEBUG packet' - ); + return noop(value); +}; +exports.convertColumn = convertColumn; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +const convertCell = (type, value) => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length); + return (0, exports.toArray)(value, dataType); } - - self._debug && self._debug('Inbound: Received DEBUG'); - - const handler = self._handlers.DEBUG; - handler && handler(self, display, msg); - }, - [MESSAGE.SERVICE_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_SERVICE_REQUEST - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_REQUEST packet' - ); + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return (0, exports.toBoolean)(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return (0, exports.toNumber)(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return (0, exports.toJson)(value); + case PostgresTypes.timestamp: + return (0, exports.toTimestampString)(value); // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + // Return the value for remaining types + return noop(value); } - - self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); - - const handler = self._handlers.SERVICE_REQUEST; - handler && handler(self, name); - }, - [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { - // S->C - /* - byte SSH_MSG_SERVICE_ACCEPT - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_ACCEPT packet' - ); +}; +exports.convertCell = convertCell; +const noop = (value) => { + return value; +}; +const toBoolean = (value) => { + switch (value) { + case 't': + return true; + case 'f': + return false; + default: + return value; + } +}; +exports.toBoolean = toBoolean; +const toNumber = (value) => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; +}; +exports.toNumber = toNumber; +const toJson = (value) => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } + catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; +}; +exports.toJson = toJson; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +const toArray = (value, type) => { + if (typeof value !== 'string') { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr; + const valTrim = value.slice(1, lastIdx); + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']'); + } + catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : []; + } + return arr.map((val) => (0, exports.convertCell)(type, val)); + } + return value; +}; +exports.toArray = toArray; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +const toTimestampString = (value) => { + if (typeof value === 'string') { + return value.replace(' ', 'T'); + } + return value; +}; +exports.toTimestampString = toTimestampString; +const httpEndpointURL = (socketUrl) => { + const wsUrl = new URL(socketUrl); + wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http'); + wsUrl.pathname = wsUrl.pathname + .replace(/\/+$/, '') // remove all trailing slashes + .replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path + .replace(/\/socket$/i, '') // remove the socket path + .replace(/\/websocket$/i, ''); // remove the websocket path + if (wsUrl.pathname === '' || wsUrl.pathname === '/') { + wsUrl.pathname = '/api/broadcast'; + } + else { + wsUrl.pathname = wsUrl.pathname + '/api/broadcast'; } + return wsUrl.href; +}; +exports.httpEndpointURL = httpEndpointURL; +//# sourceMappingURL=transformers.js.map - self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); +/***/ }), - const handler = self._handlers.SERVICE_ACCEPT; - handler && handler(self, name); - }, - [MESSAGE.EXT_INFO]: (self, payload) => { - /* - byte SSH_MSG_EXT_INFO - uint32 nr-extensions - repeat the following 2 fields "nr-extensions" times: - string extension-name - string extension-value (binary) - */ - bufferParser.init(payload, 1); - const numExts = bufferParser.readUInt32BE(); - let exts; - if (numExts !== undefined) { - exts = []; - for (let i = 0; i < numExts; ++i) { - const name = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data !== undefined) { - switch (name) { - case 'server-sig-algs': { - const algs = data.latin1Slice(0, data.length).split(','); - exts.push({ name, algs }); - continue; - } - default: - continue; - } - } - // Malformed - exts = undefined; - break; - } - } - bufferParser.clear(); +/***/ 318: +/***/ ((__unused_webpack_module, exports) => { - if (exts === undefined) - return doFatalError(self, 'Inbound: Malformed EXT_INFO packet'); +"use strict"; - self._debug && self._debug('Inbound: Received EXT_INFO'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map - const handler = self._handlers.EXT_INFO; - handler && handler(self, exts); - }, +/***/ }), - // User auth protocol -- generic ============================================= - [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_USERAUTH_REQUEST - string user name in ISO-10646 UTF-8 encoding [RFC3629] - string service name in US-ASCII - string method name in US-ASCII - .... method specific fields - */ - bufferParser.init(payload, 1); - const user = bufferParser.readString(true); - const service = bufferParser.readString(true); - const method = bufferParser.readString(true); - let methodData; - let methodDesc; - switch (method) { - case 'none': - methodData = null; - break; - case 'password': { - /* - boolean - string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] - [string new password] - */ - const isChange = bufferParser.readBool(); - if (isChange !== undefined) { - methodData = bufferParser.readString(true); - if (methodData !== undefined && isChange) { - const newPassword = bufferParser.readString(true); - if (newPassword !== undefined) - methodData = { oldPassword: methodData, newPassword }; - else - methodData = undefined; - } - } - break; - } - case 'publickey': { - /* - boolean - string public key algorithm name - string public key blob - [string signature] - */ - const hasSig = bufferParser.readBool(); - if (hasSig !== undefined) { - const keyAlgo = bufferParser.readString(true); - let realKeyAlgo = keyAlgo; - const key = bufferParser.readString(); - - let hashAlgo; - switch (keyAlgo) { - case 'rsa-sha2-256': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha256'; - break; - case 'rsa-sha2-512': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha512'; - break; - } +/***/ 3478: +/***/ ((__unused_webpack_module, exports) => { - if (hasSig) { - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } +"use strict"; - signature = sigSSHToASN1(signature, realKeyAlgo); - if (signature) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo: realKeyAlgo, - key, - signature, - blob, - hashAlgo, - }; - } - } - } else { - methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; - methodDesc = 'publickey -- check'; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebSocketFactory = void 0; +class WebSocketFactory { + static detectEnvironment() { + var _a; + if (typeof WebSocket !== 'undefined') { + return { type: 'native', constructor: WebSocket }; } - break; - } - case 'hostbased': { - /* - string public key algorithm for host key - string public host key and certificates for client host - string client host name expressed as the FQDN in US-ASCII - string user name on the client host in ISO-10646 UTF-8 encoding - [RFC3629] - string signature - */ - const keyAlgo = bufferParser.readString(true); - let realKeyAlgo = keyAlgo; - const key = bufferParser.readString(); - const localHostname = bufferParser.readString(true); - const localUsername = bufferParser.readString(true); - - let hashAlgo; - switch (keyAlgo) { - case 'rsa-sha2-256': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha256'; - break; - case 'rsa-sha2-512': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha512'; - break; + if (typeof globalThis !== 'undefined' && typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; } - - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, realKeyAlgo); - if (signature !== undefined) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo: realKeyAlgo, - key, - signature, - blob, - localHostname, - localUsername, - hashAlgo + if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') { + return { type: 'native', constructor: global.WebSocket }; + } + if (typeof globalThis !== 'undefined' && + typeof globalThis.WebSocketPair !== 'undefined' && + typeof globalThis.WebSocket === 'undefined') { + return { + type: 'cloudflare', + error: 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.', + workaround: 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.', }; - } } - break; - } - case 'keyboard-interactive': - /* - string language tag (as defined in [RFC-3066]) - string submethods (ISO-10646 UTF-8) - */ - // Skip/ignore language field -- it's deprecated in RFC 4256 - bufferParser.skipString(); - - methodData = bufferParser.readList(); - break; - default: - if (method !== undefined) - methodData = bufferParser.readRaw(); - } - bufferParser.clear(); - - if (methodData === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_REQUEST packet' - ); - } - - if (methodDesc === undefined) - methodDesc = method; - - self._authsQueue.push(method); - - self._debug - && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); - - const handler = self._handlers.USERAUTH_REQUEST; - handler && handler(self, user, service, method, methodData); - }, - [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_FAILURE - name-list authentications that can continue - boolean partial success - */ - bufferParser.init(payload, 1); - const authMethods = bufferParser.readList(); - const partialSuccess = bufferParser.readBool(); - bufferParser.clear(); - - if (partialSuccess === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_FAILURE packet' - ); + if ((typeof globalThis !== 'undefined' && globalThis.EdgeRuntime) || + (typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) { + return { + type: 'unsupported', + error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.', + workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.', + }; + } + if (typeof process !== 'undefined') { + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersions = process['versions']; + if (processVersions && processVersions['node']) { + // Remove 'v' prefix if present and parse the major version + const versionString = processVersions['node']; + const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]); + // Node.js 22+ should have native WebSocket + if (nodeVersion >= 22) { + // Check if native WebSocket is available (should be in Node.js 22+) + if (typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; + } + // If not available, user needs to provide it + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, + workaround: 'Provide a WebSocket implementation via the transport option.', + }; + } + // Node.js < 22 doesn't have native WebSocket + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected without native WebSocket support.`, + workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' + + 'import ws from "ws"\n' + + 'new RealtimeClient(url, { transport: ws })', + }; + } + } + return { + type: 'unsupported', + error: 'Unknown JavaScript runtime without WebSocket support.', + workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.", + }; } - - self._debug - && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_FAILURE; - handler && handler(self, authMethods, partialSuccess); - }, - [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_SUCCESS - */ - self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_SUCCESS; - handler && handler(self); - }, - [MESSAGE.USERAUTH_BANNER]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_BANNER - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_BANNER packet' - ); + static getWebSocketConstructor() { + const env = this.detectEnvironment(); + if (env.constructor) { + return env.constructor; + } + let errorMessage = env.error || 'WebSocket not supported in this environment.'; + if (env.workaround) { + errorMessage += `\n\nSuggested solution: ${env.workaround}`; + } + throw new Error(errorMessage); } - - self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); - - const handler = self._handlers.USERAUTH_BANNER; - handler && handler(self, msg); - }, - - // User auth protocol -- method-specific ===================================== - 60: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 60 without auth'); - return; + static createWebSocket(url, protocols) { + const WS = this.getWebSocketConstructor(); + return new WS(url, protocols); } - - switch (self._authsQueue[0]) { - case 'password': { - // S->C - /* - byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ - string prompt in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const prompt = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' - ); + static isWebSocketSupported() { + try { + const env = this.detectEnvironment(); + return env.type === 'native' || env.type === 'ws'; } - - self._debug - && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); - - const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; - handler && handler(self, prompt); - break; - } - case 'publickey': { - // S->C - /* - byte SSH_MSG_USERAUTH_PK_OK - string public key algorithm name from the request - string public key blob from the request - */ - bufferParser.init(payload, 1); - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - bufferParser.clear(); - - if (key === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PK_OK packet' - ); + catch (_a) { + return false; } + } +} +exports.WebSocketFactory = WebSocketFactory; +exports["default"] = WebSocketFactory; +//# sourceMappingURL=websocket-factory.js.map - self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_PK_OK; - handler && handler(self, keyAlgo, key); - break; - } - case 'keyboard-interactive': { - // S->C - /* - byte SSH_MSG_USERAUTH_INFO_REQUEST - string name (ISO-10646 UTF-8) - string instruction (ISO-10646 UTF-8) - string language tag (as defined in [RFC-3066]) - int num-prompts - string prompt[1] (ISO-10646 UTF-8) - boolean echo[1] - ... - string prompt[num-prompts] (ISO-10646 UTF-8) - boolean echo[num-prompts] - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const instructions = bufferParser.readString(true); - bufferParser.readString(); // skip lang - const numPrompts = bufferParser.readUInt32BE(); - let prompts; - if (numPrompts !== undefined) { - prompts = new Array(numPrompts); - let i; - for (i = 0; i < numPrompts; ++i) { - const prompt = bufferParser.readString(true); - const echo = bufferParser.readBool(); - if (echo === undefined) - break; - prompts[i] = { prompt, echo }; - } - if (i !== numPrompts) - prompts = undefined; - } - bufferParser.clear(); +/***/ }), - if (prompts === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' - ); - } +/***/ 4249: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); +"use strict"; - const handler = self._handlers.USERAUTH_INFO_REQUEST; - handler && handler(self, name, instructions, prompts); - break; - } - default: - self._debug - && self._debug('Inbound: Received unexpected payload type 60'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +const StorageFileApi_1 = tslib_1.__importDefault(__nccwpck_require__(710)); +const StorageBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(3528)); +const StorageAnalyticsApi_1 = tslib_1.__importDefault(__nccwpck_require__(7339)); +const vectors_1 = __nccwpck_require__(9380); +class StorageClient extends StorageBucketApi_1.default { + constructor(url, headers = {}, fetch, opts) { + super(url, headers, fetch, opts); } - }, - 61: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 61 without auth'); - return; + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id) { + return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch); } - /* - byte SSH_MSG_USERAUTH_INFO_RESPONSE - int num-responses - string response[1] (ISO-10646 UTF-8) - ... - string response[num-responses] (ISO-10646 UTF-8) - */ - if (self._authsQueue[0] !== 'keyboard-interactive') { - return doFatalError( - self, - 'Inbound: Received unexpected payload type 61' - ); + /** + * Access vector storage operations. + * + * @returns A StorageVectorsClient instance configured with the current storage settings. + */ + get vectors() { + return new vectors_1.StorageVectorsClient(this.url + '/vector', { + headers: this.headers, + fetch: this.fetch, + }); } - bufferParser.init(payload, 1); - const numResponses = bufferParser.readUInt32BE(); - let responses; - if (numResponses !== undefined) { - responses = new Array(numResponses); - let i; - for (i = 0; i < numResponses; ++i) { - const response = bufferParser.readString(true); - if (response === undefined) - break; - responses[i] = response; - } - if (i !== numResponses) - responses = undefined; + /** + * Access analytics storage operations using Iceberg tables. + * + * @returns A StorageAnalyticsApi instance configured with the current storage settings. + * @example + * ```typescript + * const client = createClient(url, key) + * const analytics = client.storage.analytics + * + * // Create an analytics bucket + * await analytics.createBucket('my-analytics-bucket') + * + * // List all analytics buckets + * const { data: buckets } = await analytics.listBuckets() + * + * // Delete an analytics bucket + * await analytics.deleteBucket('old-analytics-bucket') + * ``` + */ + get analytics() { + return new StorageAnalyticsApi_1.default(this.url + '/iceberg', this.headers, this.fetch); } - bufferParser.clear(); +} +exports.StorageClient = StorageClient; +//# sourceMappingURL=StorageClient.js.map - if (responses === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' - ); - } +/***/ }), - self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); +/***/ 5852: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const handler = self._handlers.USERAUTH_INFO_RESPONSE; - handler && handler(self, responses); - }, +"use strict"; - // Connection protocol -- generic ============================================ - [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_GLOBAL_REQUEST - string request name in US-ASCII only - boolean want reply - .... request-specific data follows - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (name) { - case 'tcpip-forward': - case 'cancel-tcpip-forward': { - /* - string address to bind (e.g., "0.0.0.0") - uint32 port number to bind - */ - const bindAddr = bufferParser.readString(true); - const bindPort = bufferParser.readUInt32BE(); - if (bindPort !== undefined) - data = { bindAddr, bindPort }; - break; - } - case 'streamlocal-forward@openssh.com': - case 'cancel-streamlocal-forward@openssh.com': { - /* - string socket path - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) - data = { socketPath }; - break; - } - case 'no-more-sessions@openssh.com': - data = null; - break; - case 'hostkeys-00@openssh.com': { - data = []; - while (bufferParser.avail() > 0) { - const keyRaw = bufferParser.readString(); - if (keyRaw === undefined) { - data = undefined; - break; - } - const key = parseKey(keyRaw); - if (!(key instanceof Error)) - data.push(key); - } - break; - } - default: - data = bufferParser.readRaw(); - } - } - bufferParser.clear(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageAnalyticsApi = exports.StorageClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +var StorageClient_1 = __nccwpck_require__(4249); +Object.defineProperty(exports, "StorageClient", ({ enumerable: true, get: function () { return StorageClient_1.StorageClient; } })); +var StorageAnalyticsApi_1 = __nccwpck_require__(7339); +Object.defineProperty(exports, "StorageAnalyticsApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(StorageAnalyticsApi_1).default; } })); +tslib_1.__exportStar(__nccwpck_require__(7222), exports); +tslib_1.__exportStar(__nccwpck_require__(2758), exports); +tslib_1.__exportStar(__nccwpck_require__(9380), exports); +//# sourceMappingURL=index.js.map - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed GLOBAL_REQUEST packet' - ); - } +/***/ }), - self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); +/***/ 9754: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const handler = self._handlers.GLOBAL_REQUEST; - if (handler) - handler(self, name, wantReply, data); - else - self.requestFailure(); // Auto reject - }, - [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_SUCCESS - .... response specific data - */ - const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); +"use strict"; - self._debug && self._debug('Inbound: REQUEST_SUCCESS'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_HEADERS = void 0; +const version_1 = __nccwpck_require__(4499); +exports.DEFAULT_HEADERS = { + 'X-Client-Info': `storage-js/${version_1.version}`, +}; +//# sourceMappingURL=constants.js.map - const handler = self._handlers.REQUEST_SUCCESS; - handler && handler(self, data); - }, - [MESSAGE.REQUEST_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_FAILURE - */ - self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); +/***/ }), - const handler = self._handlers.REQUEST_FAILURE; - handler && handler(self); - }, +/***/ 2758: +/***/ ((__unused_webpack_module, exports) => { - // Connection protocol -- channel-related ==================================== - [MESSAGE.CHANNEL_OPEN]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN - string channel type in US-ASCII only - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - bufferParser.init(payload, 1); - const type = bufferParser.readString(true); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - let channelInfo; +"use strict"; - switch (type) { - case 'forwarded-tcpip': // S->C - case 'direct-tcpip': { // C->S - /* - string address that was connected / host to connect - uint32 port that was connected / port to connect - string originator IP address - uint32 originator port - */ - const destIP = bufferParser.readString(true); - const destPort = bufferParser.readUInt32BE(); - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { destIP, destPort, srcIP, srcPort } - }; - } - break; - } - case 'forwarded-streamlocal@openssh.com': // S->C - case 'direct-streamlocal@openssh.com': { // C->S - /* - string socket path - string reserved for future use - - (direct-streamlocal@openssh.com additionally has:) - uint32 reserved - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { socketPath } - }; - } - break; - } - case 'x11': { // S->C - /* - string originator address (e.g., "192.168.7.38") - uint32 originator port - */ - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { srcIP, srcPort } - }; - } - break; - } - default: - // Includes: - // 'session' (C->S) - // 'auth-agent@openssh.com' (S->C) - channelInfo = { - type, - sender, - window, - packetSize, - data: {} - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageUnknownError = exports.StorageApiError = exports.StorageError = void 0; +exports.isStorageError = isStorageError; +class StorageError extends Error { + constructor(message) { + super(message); + this.__isStorageError = true; + this.name = 'StorageError'; } - bufferParser.clear(); - - if (channelInfo === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN packet' - ); +} +exports.StorageError = StorageError; +function isStorageError(error) { + return typeof error === 'object' && error !== null && '__isStorageError' in error; +} +class StorageApiError extends StorageError { + constructor(message, status, statusCode) { + super(message); + this.name = 'StorageApiError'; + this.status = status; + this.statusCode = statusCode; } - - self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); - - const handler = self._handlers.CHANNEL_OPEN; - if (handler) { - handler(self, channelInfo); - } else { - self.channelOpenFail( - channelInfo.sender, - CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, - '', - '' - ); + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode, + }; } - }, - [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION - uint32 recipient channel - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - // "The 'recipient channel' is the channel number given in the - // original open request, and 'sender channel' is the channel number - // allocated by the other side." - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); - bufferParser.clear(); - - if (packetSize === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' - ); +} +exports.StorageApiError = StorageApiError; +class StorageUnknownError extends StorageError { + constructor(message, originalError) { + super(message); + this.name = 'StorageUnknownError'; + this.originalError = originalError; } +} +exports.StorageUnknownError = StorageUnknownError; +//# sourceMappingURL=errors.js.map - self._debug && self._debug( - `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` - ); +/***/ }), - const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; - if (handler) - handler(self, { recipient, sender, window, packetSize, data }); - }, - [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_FAILURE - uint32 recipient channel - uint32 reason code - string description in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const reason = bufferParser.readUInt32BE(); - const description = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' - ); - } +/***/ 3146: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - self._debug - && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); +"use strict"; - const handler = self._handlers.CHANNEL_OPEN_FAILURE; - handler && handler(self, recipient, reason, description); - }, - [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_WINDOW_ADJUST - uint32 recipient channel - uint32 bytes to add - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const bytesToAdd = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (bytesToAdd === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.get = get; +exports.post = post; +exports.put = put; +exports.head = head; +exports.remove = remove; +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(2758); +const helpers_1 = __nccwpck_require__(5430); +const _getErrorMessage = (err) => { + var _a; + return err.msg || + err.message || + err.error_description || + (typeof err.error === 'string' ? err.error : (_a = err.error) === null || _a === void 0 ? void 0 : _a.message) || + JSON.stringify(err); +}; +const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + const Res = yield (0, helpers_1.resolveResponse)(); + if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + error + .json() + .then((err) => { + const status = error.status || 500; + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || status + ''; + reject(new errors_1.StorageApiError(_getErrorMessage(err), status, statusCode)); + }) + .catch((err) => { + reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err)); + }); } - - self._debug && self._debug( - `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` - ); - - const handler = self._handlers.CHANNEL_WINDOW_ADJUST; - handler && handler(self, recipient, bytesToAdd); - }, - [MESSAGE.CHANNEL_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_DATA - uint32 recipient channel - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_DATA packet' - ); + else { + reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error)); } - - self._debug - && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); - - const handler = self._handlers.CHANNEL_DATA; - handler && handler(self, recipient, data); - }, - [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EXTENDED_DATA - uint32 recipient channel - uint32 data_type_code - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' - ); +}); +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET' || !body) { + return params; } - - self._debug && self._debug( - `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` - ); - - const handler = self._handlers.CHANNEL_EXTENDED_DATA; - handler && handler(self, recipient, data, type); - }, - [MESSAGE.CHANNEL_EOF]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EOF - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EOF packet' - ); + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); } - - self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); - - const handler = self._handlers.CHANNEL_EOF; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_CLOSE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_CLOSE packet' - ); + else { + params.body = body; } - - self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_CLOSE; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_REQUEST - uint32 recipient channel - string request type in US-ASCII characters only - boolean want reply - .... type-specific data follows - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (type) { - case 'exit-status': // S->C - /* - uint32 exit_status - */ - data = bufferParser.readUInt32BE(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'exit-signal': { // S->C - /* - string signal name (without the "SIG" prefix) - boolean core dumped - string error message in ISO-10646 UTF-8 encoding - string language tag - */ - let signal; - let coreDumped; - if (self._compatFlags & COMPAT.OLD_EXIT) { - /* - Instead of `signal name` and `core dumped`, we have just: - uint32 signal number - */ - const num = bufferParser.readUInt32BE(); - switch (num) { - case 1: - signal = 'HUP'; - break; - case 2: - signal = 'INT'; - break; - case 3: - signal = 'QUIT'; - break; - case 6: - signal = 'ABRT'; - break; - case 9: - signal = 'KILL'; - break; - case 14: - signal = 'ALRM'; - break; - case 15: - signal = 'TERM'; - break; - default: - if (num !== undefined) { - // Unknown or OS-specific - signal = `UNKNOWN (${num})`; - } - } - coreDumped = false; - } else { - signal = bufferParser.readString(true); - coreDumped = bufferParser.readBool(); - if (coreDumped === undefined) - signal = undefined; - } - const errorMessage = bufferParser.readString(true); - if (bufferParser.skipString() !== undefined) - data = { signal, coreDumped, errorMessage }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` - ); - break; - } - case 'pty-req': { // C->S - /* - string TERM environment variable value (e.g., vt100) - uint32 terminal width, characters (e.g., 80) - uint32 terminal height, rows (e.g., 24) - uint32 terminal width, pixels (e.g., 640) - uint32 terminal height, pixels (e.g., 480) - string encoded terminal modes - */ - const term = bufferParser.readString(true); - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - const modesBinary = bufferParser.readString(); - if (modesBinary !== undefined) { - bufferParser.init(modesBinary, 1); - let modes = {}; - while (bufferParser.avail()) { - const opcode = bufferParser.readByte(); - if (opcode === TERMINAL_MODE.TTY_OP_END) - break; - const name = TERMINAL_MODE_BY_VALUE[opcode]; - const value = bufferParser.readUInt32BE(); - if (opcode === undefined - || name === undefined - || value === undefined) { - modes = undefined; - break; - } - modes[name] = value; - } - if (modes !== undefined) - data = { term, cols, rows, width, height, modes }; - } - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'window-change': { // C->S - /* - uint32 terminal width, columns - uint32 terminal height, rows - uint32 terminal width, pixels - uint32 terminal height, pixels - */ - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - if (height !== undefined) - data = { cols, rows, width, height }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'x11-req': { // C->S - /* - boolean single connection - string x11 authentication protocol - string x11 authentication cookie - uint32 x11 screen number - */ - const single = bufferParser.readBool(); - const protocol = bufferParser.readString(true); - const cookie = bufferParser.readString(); - const screen = bufferParser.readUInt32BE(); - if (screen !== undefined) - data = { single, protocol, cookie, screen }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'env': { // C->S - /* - string variable name - string variable value - */ - const name = bufferParser.readString(true); - const value = bufferParser.readString(true); - if (value !== undefined) - data = { name, value }; - if (self._debug) { - self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` - + `${name}=${value})` - ); - } - break; - } - case 'shell': // C->S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - case 'exec': // C->S - /* - string command - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'subsystem': // C->S - /* - string subsystem name - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'signal': // C->S - /* - string signal name (without the "SIG" prefix) - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'xon-xoff': // C->S - /* - boolean client can do - */ - data = bufferParser.readBool(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'auth-agent-req@openssh.com': // C-S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - default: - data = (bufferParser.avail() ? bufferParser.readRaw() : null); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - } + if (options === null || options === void 0 ? void 0 : options.duplex) { + params.duplex = options.duplex; } - bufferParser.clear(); + return Object.assign(Object.assign({}, params), parameters); +}; +function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)) + .then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + return result.json(); + }) + .then((data) => resolve(data)) + .catch((error) => handleError(error, reject, options)); + }); + }); +} +function get(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'GET', url, options, parameters); + }); +} +function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'POST', url, options, parameters, body); + }); +} +function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'PUT', url, options, parameters, body); + }); +} +function head(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); + }); +} +function remove(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); + }); +} +//# sourceMappingURL=fetch.js.map - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_REQUEST packet' - ); - } +/***/ }), - const handler = self._handlers.CHANNEL_REQUEST; - handler && handler(self, recipient, type, wantReply, data); - }, - [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_SUCCESS - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_SUCCESS packet' - ); - } +/***/ 5430: +/***/ ((__unused_webpack_module, exports) => { - self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); +"use strict"; - const handler = self._handlers.CHANNEL_SUCCESS; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_FAILURE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_FAILURE packet' - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isPlainObject = exports.recursiveToCamel = exports.resolveResponse = exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); } - - self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_FAILURE; - handler && handler(self, recipient); - }, + return (...args) => fetch(...args); }; - +exports.resolveFetch = resolveFetch; +const resolveResponse = () => { + return Response; +}; +exports.resolveResponse = resolveResponse; +const recursiveToCamel = (item) => { + if (Array.isArray(item)) { + return item.map((el) => (0, exports.recursiveToCamel)(el)); + } + else if (typeof item === 'function' || item !== Object(item)) { + return item; + } + const result = {}; + Object.entries(item).forEach(([key, value]) => { + const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, '')); + result[newKey] = (0, exports.recursiveToCamel)(value); + }); + return result; +}; +exports.recursiveToCamel = recursiveToCamel; +/** + * Determine if input is a plain object + * An object is plain if it's created by either {}, new Object(), or Object.create(null) + * source: https://github.com/sindresorhus/is-plain-obj + */ +const isPlainObject = (value) => { + if (typeof value !== 'object' || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return ((prototype === null || + prototype === Object.prototype || + Object.getPrototypeOf(prototype) === null) && + !(Symbol.toStringTag in value) && + !(Symbol.iterator in value)); +}; +exports.isPlainObject = isPlainObject; +//# sourceMappingURL=helpers.js.map /***/ }), -/***/ 64126: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7222: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=types.js.map -const { - createDiffieHellman, - createDiffieHellmanGroup, - createECDH, - createHash, - createPublicKey, - diffieHellman, - generateKeyPairSync, - randomFillSync, -} = __nccwpck_require__(6113); - -const { Ber } = __nccwpck_require__(80970); - -const { - COMPAT, - curve25519Supported, - DEFAULT_KEX, - DEFAULT_SERVER_HOST_KEY, - DEFAULT_CIPHER, - DEFAULT_MAC, - DEFAULT_COMPRESSION, - DISCONNECT_REASON, - MESSAGE, -} = __nccwpck_require__(36832); -const { - CIPHER_INFO, - createCipher, - createDecipher, - MAC_INFO, -} = __nccwpck_require__(45708); -const { parseDERKey } = __nccwpck_require__(22218); -const { - bufferFill, - bufferParser, - convertSignature, - doFatalError, - FastBuffer, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(49475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(26715); - -let MESSAGE_HANDLERS; +/***/ }), -const GEX_MIN_BITS = 2048; // RFC 8270 -const GEX_MAX_BITS = 8192; // RFC 8270 +/***/ 9403: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const EMPTY_BUFFER = Buffer.alloc(0); +"use strict"; -// Client/Server -function kexinit(self) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - - let payload; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - const entry = self._offer.lists.kex; - let kex = entry.array; - let found = false; - for (let i = 0; i < kex.length; ++i) { - if (kex[i].includes('group-exchange')) { - if (!found) { - found = true; - // Copy array lazily - kex = kex.slice(); - } - kex.splice(i--, 1); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +const VectorIndexApi_1 = tslib_1.__importDefault(__nccwpck_require__(9623)); +const VectorDataApi_1 = tslib_1.__importDefault(__nccwpck_require__(3073)); +const VectorBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(4268)); +/** + * Main client for interacting with S3 Vectors API + * Provides access to bucket, index, and vector data operations + * + * **Usage Patterns:** + * + * 1. **Via StorageClient (recommended for most use cases):** + * ```typescript + * import { StorageClient } from '@supabase/storage-js' + * + * const storageClient = new StorageClient(url, headers) + * const vectors = storageClient.vectors + * + * // Use vector operations + * await vectors.createBucket('embeddings-prod') + * const bucket = vectors.from('embeddings-prod') + * await bucket.createIndex({ ... }) + * ``` + * + * 2. **Standalone (for vector-only applications):** + * ```typescript + * import { StorageVectorsClient } from '@supabase/storage-js' + * + * const vectorsClient = new StorageVectorsClient('https://api.example.com', { + * headers: { 'Authorization': 'Bearer token' } + * }) + * + * // Access bucket operations + * await vectorsClient.createBucket('embeddings-prod') + * + * // Access index operations via buckets + * const bucket = vectorsClient.from('embeddings-prod') + * await bucket.createIndex({ + * indexName: 'documents', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine' + * }) + * + * // Access vector operations via index + * const index = bucket.index('documents') + * await index.putVectors({ + * vectors: [ + * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } + * ] + * }) + * + * // Query similar vectors + * const { data } = await index.queryVectors({ + * queryVector: { float32: [...] }, + * topK: 5, + * returnDistance: true + * }) + * ``` + */ +class StorageVectorsClient extends VectorBucketApi_1.default { + constructor(url, options = {}) { + super(url, options.headers || {}, options.fetch); } - if (found) { - let len = 1 + 16 + self._offer.totalSize + 1 + 4; - const newKexBuf = Buffer.from(kex.join(',')); - len -= (entry.buffer.length - newKexBuf.length); - - const all = self._offer.lists.all; - const rest = new Uint8Array( - all.buffer, - all.byteOffset + 4 + entry.buffer.length, - all.length - (4 + entry.buffer.length) - ); - - payload = Buffer.allocUnsafe(len); - writeUInt32BE(payload, newKexBuf.length, 17); - payload.set(newKexBuf, 17 + 4); - payload.set(rest, 17 + 4 + newKexBuf.length); + /** + * Access operations for a specific vector bucket + * Returns a scoped client for index and vector operations within the bucket + * + * @param vectorBucketName - Name of the vector bucket + * @returns Bucket-scoped client with index and vector operations + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * + * // Create an index in this bucket + * await bucket.createIndex({ + * indexName: 'documents-openai', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine' + * }) + * + * // List indexes in this bucket + * const { data } = await bucket.listIndexes() + * ``` + */ + from(vectorBucketName) { + return new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch); } - } - - if (payload === undefined) { - payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); - self._offer.copyAllTo(payload, 17); - } - - self._debug && self._debug('Outbound: Sending KEXINIT'); - - payload[0] = MESSAGE.KEXINIT; - randomFillSync(payload, 1, 16); - - // Zero-fill first_kex_packet_follows and reserved bytes - bufferFill(payload, 0, payload.length - 5); - - self._kexinit = payload; - - // Needed to correct the starting position in allocated "packets" when packets - // will be buffered due to active key exchange - self._packetRW.write.allocStart = 0; - - // TODO: only create single buffer and set _kexinit as slice of packet instead - { - const p = self._packetRW.write.allocStartKEX; - const packet = self._packetRW.write.alloc(payload.length, true); - packet.set(payload, p); - self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); - } } - -function handleKexInit(self, payload) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - const init = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - }; - - bufferParser.init(payload, 17); - - if ((init.kex = bufferParser.readList()) === undefined - || (init.serverHostKey = bufferParser.readList()) === undefined - || (init.cs.cipher = bufferParser.readList()) === undefined - || (init.sc.cipher = bufferParser.readList()) === undefined - || (init.cs.mac = bufferParser.readList()) === undefined - || (init.sc.mac = bufferParser.readList()) === undefined - || (init.cs.compress = bufferParser.readList()) === undefined - || (init.sc.compress = bufferParser.readList()) === undefined - || (init.cs.lang = bufferParser.readList()) === undefined - || (init.sc.lang = bufferParser.readList()) === undefined) { - bufferParser.clear(); - return doFatalError( - self, - 'Received malformed KEXINIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const pos = bufferParser.pos(); - const firstFollows = (pos < payload.length && payload[pos] === 1); - bufferParser.clear(); - - const local = self._offer; - const remote = init; - - let localKex = local.lists.kex.array; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - let found = false; - for (let i = 0; i < localKex.length; ++i) { - if (localKex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - localKex = localKex.slice(); - } - localKex.splice(i--, 1); - } +exports.StorageVectorsClient = StorageVectorsClient; +/** + * Scoped client for operations within a specific vector bucket + * Provides index management and access to vector operations + */ +class VectorBucketScope extends VectorIndexApi_1.default { + constructor(url, headers, vectorBucketName, fetch) { + super(url, headers, fetch); + this.vectorBucketName = vectorBucketName; } - } - - let clientList; - let serverList; - let i; - const debug = self._debug; - - debug && debug('Inbound: Handshake in progress'); - - // Key exchange method ======================================================= - debug && debug(`Handshake: (local) KEX method: ${localKex}`); - debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); - let remoteExtInfoEnabled; - if (self._server) { - serverList = localKex; - clientList = remote.kex; - remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1); - } else { - serverList = remote.kex; - clientList = localKex; - remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1); - } - if (self._strictMode === undefined) { - if (self._server) { - self._strictMode = - (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1); - } else { - self._strictMode = - (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1); - } - // Note: We check for seqno of 1 instead of 0 since we increment before - // calling the packet handler - if (self._strictMode) { - debug && debug('Handshake: strict KEX mode enabled'); - if (self._decipher.inSeqno !== 1) { - if (debug) - debug('Handshake: KEXINIT not first packet in strict KEX mode'); - return doFatalError( - self, - 'Handshake failed: KEXINIT not first packet in strict KEX mode', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + /** + * Creates a new vector index in this bucket + * Convenience method that automatically includes the bucket name + * + * @param options - Index configuration (vectorBucketName is automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * await bucket.createIndex({ + * indexName: 'documents-openai', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine', + * metadataConfiguration: { + * nonFilterableMetadataKeys: ['raw_text'] + * } + * }) + * ``` + */ + createIndex(options) { + const _super = Object.create(null, { + createIndex: { get: () => super.createIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.createIndex.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); } - } - // Check for agreeable key exchange algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: no matching key exchange algorithm'); - return doFatalError( - self, - 'Handshake failed: no matching key exchange algorithm', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.kex = clientList[i]; - debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); - if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { - // Ignore next inbound packet, it was a wrong first guess at KEX algorithm - self._skipNextInboundPacket = true; - } - - - // Server host key format ==================================================== - const localSrvHostKey = local.lists.serverHostKey.array; - debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug && debug( - `Handshake: (remote) Host key format: ${remote.serverHostKey}` - ); - if (self._server) { - serverList = localSrvHostKey; - clientList = remote.serverHostKey; - } else { - serverList = remote.serverHostKey; - clientList = localSrvHostKey; - } - // Check for agreeable server host key format - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching host key format'); - return doFatalError( - self, - 'Handshake failed: no matching host key format', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.serverHostKey = clientList[i]; - debug && debug(`Handshake: Host key format: ${clientList[i]}`); - - - // Client->Server cipher ===================================================== - const localCSCipher = local.lists.cs.cipher.array; - debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); - if (self._server) { - serverList = localCSCipher; - clientList = remote.cs.cipher; - } else { - serverList = remote.cs.cipher; - clientList = localCSCipher; - } - // Check for agreeable client->server cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S cipher'); - return doFatalError( - self, - 'Handshake failed: no matching C->S cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.cipher = clientList[i]; - debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); + /** + * Lists indexes in this bucket + * Convenience method that automatically includes the bucket name + * + * @param options - Listing options (vectorBucketName is automatically set) + * @returns Promise with list of indexes or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * const { data } = await bucket.listIndexes({ prefix: 'documents-' }) + * ``` + */ + listIndexes() { + const _super = Object.create(null, { + listIndexes: { get: () => super.listIndexes } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listIndexes.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); + } + /** + * Retrieves metadata for a specific index in this bucket + * Convenience method that automatically includes the bucket name + * + * @param indexName - Name of the index to retrieve + * @returns Promise with index metadata or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * const { data } = await bucket.getIndex('documents-openai') + * console.log('Dimension:', data?.index.dimension) + * ``` + */ + getIndex(indexName) { + const _super = Object.create(null, { + getIndex: { get: () => super.getIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * Deletes an index from this bucket + * Convenience method that automatically includes the bucket name + * + * @param indexName - Name of the index to delete + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * await bucket.deleteIndex('old-index') + * ``` + */ + deleteIndex(indexName) { + const _super = Object.create(null, { + deleteIndex: { get: () => super.deleteIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * Access operations for a specific index within this bucket + * Returns a scoped client for vector data operations + * + * @param indexName - Name of the index + * @returns Index-scoped client with vector data operations + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * + * // Insert vectors + * await index.putVectors({ + * vectors: [ + * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } + * ] + * }) + * + * // Query similar vectors + * const { data } = await index.queryVectors({ + * queryVector: { float32: [...] }, + * topK: 5 + * }) + * ``` + */ + index(indexName) { + return new VectorIndexScope(this.url, this.headers, this.vectorBucketName, indexName, this.fetch); + } +} +exports.VectorBucketScope = VectorBucketScope; +/** + * Scoped client for operations within a specific vector index + * Provides vector data operations (put, get, list, query, delete) + */ +class VectorIndexScope extends VectorDataApi_1.default { + constructor(url, headers, vectorBucketName, indexName, fetch) { + super(url, headers, fetch); + this.vectorBucketName = vectorBucketName; + this.indexName = indexName; + } + /** + * Inserts or updates vectors in this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Vector insertion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * await index.putVectors({ + * vectors: [ + * { + * key: 'doc-1', + * data: { float32: [0.1, 0.2, ...] }, + * metadata: { title: 'Introduction', page: 1 } + * } + * ] + * }) + * ``` + */ + putVectors(options) { + const _super = Object.create(null, { + putVectors: { get: () => super.putVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.putVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * Retrieves vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Vector retrieval options (bucket and index names automatically set) + * @returns Promise with array of vectors or error + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * const { data } = await index.getVectors({ + * keys: ['doc-1', 'doc-2'], + * returnMetadata: true + * }) + * ``` + */ + getVectors(options) { + const _super = Object.create(null, { + getVectors: { get: () => super.getVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * Lists vectors in this index with pagination + * Convenience method that automatically includes bucket and index names + * + * @param options - Listing options (bucket and index names automatically set) + * @returns Promise with array of vectors and pagination token + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * const { data } = await index.listVectors({ + * maxResults: 500, + * returnMetadata: true + * }) + * ``` + */ + listVectors() { + const _super = Object.create(null, { + listVectors: { get: () => super.listVectors } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * Queries for similar vectors in this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Query options (bucket and index names automatically set) + * @returns Promise with array of similar vectors ordered by distance + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * const { data } = await index.queryVectors({ + * queryVector: { float32: [0.1, 0.2, ...] }, + * topK: 5, + * filter: { category: 'technical' }, + * returnDistance: true, + * returnMetadata: true + * }) + * ``` + */ + queryVectors(options) { + const _super = Object.create(null, { + queryVectors: { get: () => super.queryVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.queryVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * Deletes vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Deletion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * await index.deleteVectors({ + * keys: ['doc-1', 'doc-2', 'doc-3'] + * }) + * ``` + */ + deleteVectors(options) { + const _super = Object.create(null, { + deleteVectors: { get: () => super.deleteVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } +} +exports.VectorIndexScope = VectorIndexScope; +//# sourceMappingURL=StorageVectorsClient.js.map +/***/ }), - // Server->Client cipher ===================================================== - const localSCCipher = local.lists.sc.cipher.array; - debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); - if (self._server) { - serverList = localSCCipher; - clientList = remote.sc.cipher; - } else { - serverList = remote.sc.cipher; - clientList = localSCCipher; - } - // Check for agreeable server->client cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C cipher'); - return doFatalError( - self, - 'Handshake failed: no matching S->C cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.cipher = clientList[i]; - debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); +/***/ 4268: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; - // Client->Server MAC ======================================================== - const localCSMAC = local.lists.cs.mac.array; - debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); - if (CIPHER_INFO[init.cs.cipher].authLen > 0) { - init.cs.mac = ''; - debug && debug('Handshake: C->S MAC: '); - } else { - if (self._server) { - serverList = localCSMAC; - clientList = remote.cs.mac; - } else { - serverList = remote.cs.mac; - clientList = localCSMAC; - } - // Check for agreeable client->server hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S MAC'); - return doFatalError( - self, - 'Handshake failed: no matching C->S MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(6876); +const errors_1 = __nccwpck_require__(3071); +const fetch_1 = __nccwpck_require__(2593); +const helpers_1 = __nccwpck_require__(1176); +/** + * API class for managing Vector Buckets + * Provides methods for creating, reading, listing, and deleting vector buckets + */ +class VectorBucketApi { + /** + * Creates a new VectorBucketApi instance + * @param url - The base URL for the storage vectors API + * @param headers - HTTP headers to include in requests + * @param fetch - Optional custom fetch implementation + */ + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); } - init.cs.mac = clientList[i]; - debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); - } - - - // Server->Client MAC ======================================================== - const localSCMAC = local.lists.sc.mac.array; - debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); - if (CIPHER_INFO[init.sc.cipher].authLen > 0) { - init.sc.mac = ''; - debug && debug('Handshake: S->C MAC: '); - } else { - if (self._server) { - serverList = localSCMAC; - clientList = remote.sc.mac; - } else { - serverList = remote.sc.mac; - clientList = localSCMAC; - } - // Check for agreeable server->client hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C MAC'); - return doFatalError( - self, - 'Handshake failed: no matching S->C MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + * @example + * ```typescript + * const client = new VectorBucketApi(url, headers) + * client.throwOnError() + * const { data } = await client.createBucket('my-bucket') // throws on error + * ``` + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; } - init.sc.mac = clientList[i]; - debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); - } - - - // Client->Server compression ================================================ - const localCSCompress = local.lists.cs.compress.array; - debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); - if (self._server) { - serverList = localCSCompress; - clientList = remote.cs.compress; - } else { - serverList = remote.cs.compress; - clientList = localCSCompress; - } - // Check for agreeable client->server compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S compression'); - return doFatalError( - self, - 'Handshake failed: no matching C->S compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.compress = clientList[i]; - debug && debug(`Handshake: C->S compression: ${clientList[i]}`); - - - // Server->Client compression ================================================ - const localSCCompress = local.lists.sc.compress.array; - debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); - if (self._server) { - serverList = localSCCompress; - clientList = remote.sc.compress; - } else { - serverList = remote.sc.compress; - clientList = localSCCompress; - } - // Check for agreeable server->client compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C compression'); - return doFatalError( - self, - 'Handshake failed: no matching S->C compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.compress = clientList[i]; - debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - - init.cs.lang = ''; - init.sc.lang = ''; - - // XXX: hack -- find a better way to do this - if (self._kex) { - if (!self._kexinit) { - // We received a rekey request, but we haven't sent a KEXINIT in response - // yet - kexinit(self); - } - self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); - } - - self._kex = createKeyExchange(init, self, payload); - self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; - self._kex.start(); -} - -const createKeyExchange = (() => { - function convertToMpint(buf) { - let idx = 0; - let length = buf.length; - while (buf[idx] === 0x00) { - ++idx; - --length; - } - let newBuf; - if (buf[idx] & 0x80) { - newBuf = Buffer.allocUnsafe(1 + length); - newBuf[0] = 0; - buf.copy(newBuf, 1, idx); - buf = newBuf; - } else if (length !== buf.length) { - newBuf = Buffer.allocUnsafe(length); - buf.copy(newBuf, 0, idx); - buf = newBuf; - } - return buf; - } - - class KeyExchange { - constructor(negotiated, protocol, remoteKexinit) { - this._protocol = protocol; - - this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); - this.negotiated = negotiated; - this.remoteExtInfoEnabled = false; - this._step = 1; - this._public = null; - this._dh = null; - this._sentNEWKEYS = false; - this._receivedNEWKEYS = false; - this._finished = false; - this._hostVerified = false; - - // Data needed for initializing cipher/decipher/etc. - this._kexinit = protocol._kexinit; - this._remoteKexinit = remoteKexinit; - this._identRaw = protocol._identRaw; - this._remoteIdentRaw = protocol._remoteIdentRaw; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - } - finish(scOnly) { - if (this._finished) - return false; - this._finished = true; - - const isServer = this._protocol._server; - const negotiated = this.negotiated; - - const pubKey = this.convertPublicKey(this._dhData); - let secret = this.computeSecret(this._dhData); - if (secret instanceof Error) { - secret.message = - `Error while computing DH secret (${this.type}): ${secret.message}`; - secret.level = 'handshake'; - return doFatalError( - this._protocol, - secret, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const hash = createHash(this.hashName); - // V_C - hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); - // "V_S" - hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); - // "I_C" - hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); - // "I_S" - hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); - // "K_S" - const serverPublicHostKey = (isServer - ? this._hostKey.getPublicSSH() - : this._hostKey); - hashString(hash, serverPublicHostKey); - - if (this.type === 'groupex') { - // Group exchange-specific - const params = this.getDHParams(); - const num = Buffer.allocUnsafe(4); - // min (uint32) - writeUInt32BE(num, this._minBits, 0); - hash.update(num); - // preferred (uint32) - writeUInt32BE(num, this._prefBits, 0); - hash.update(num); - // max (uint32) - writeUInt32BE(num, this._maxBits, 0); - hash.update(num); - // prime - hashString(hash, params.prime); - // generator - hashString(hash, params.generator); - } - - // method-specific data sent by client - hashString(hash, (isServer ? pubKey : this.getPublicKey())); - // method-specific data sent by server - const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); - hashString(hash, serverPublicKey); - // shared secret ("K") - hashString(hash, secret); - - // "H" - const exchangeHash = hash.digest(); - - if (!isServer) { - bufferParser.init(this._sig, 0); - const sigType = bufferParser.readString(true); - - if (!sigType) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (sigType !== negotiated.serverHostKey) { - return doFatalError( - this._protocol, - `Wrong signature type: ${sigType}, ` - + `expected: ${negotiated.serverHostKey}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // "s" - let sigValue = bufferParser.readString(); - - bufferParser.clear(); - - if (sigValue === undefined) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { - return doFatalError( - this._protocol, - 'Malformed signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - let parsedHostKey; - { - bufferParser.init(this._hostKey, 0); - const name = bufferParser.readString(true); - const hostKey = this._hostKey.slice(bufferParser.pos()); - bufferParser.clear(); - parsedHostKey = parseDERKey(hostKey, name); - if (parsedHostKey instanceof Error) { - parsedHostKey.level = 'handshake'; - return doFatalError( - this._protocol, - parsedHostKey, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug - && this._protocol._debug('Verifying signature ...'); - - const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); - if (verified !== true) { - if (verified instanceof Error) { - this._protocol._debug && this._protocol._debug( - `Signature verification failed: ${verified.stack}` - ); - } else { - this._protocol._debug && this._protocol._debug( - 'Signature verification failed' - ); - } - return doFatalError( - this._protocol, - 'Handshake failed: signature verification failed', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug('Verified signature'); - } else { - // Server - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug && this._protocol._debug( - 'Generating signature ...' - ); - - let signature = this._hostKey.sign(exchangeHash, hashAlgo); - if (signature instanceof Error) { - return doFatalError( - this._protocol, - 'Handshake failed: signature generation failed for ' - + `${this._hostKey.type} host key: ${signature.message}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - signature = convertSignature(signature, this._hostKey.type); - if (signature === false) { - return doFatalError( - this._protocol, - 'Handshake failed: signature conversion failed for ' - + `${this._hostKey.type} host key`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Send KEX reply - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - const sigType = this.negotiated.serverHostKey; - const sigTypeLen = Buffer.byteLength(sigType); - const sigLen = 4 + sigTypeLen + 4 + signature.length; - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 - + 4 + serverPublicHostKey.length - + 4 + serverPublicKey.length - + 4 + sigLen, - true - ); - - packet[p] = MESSAGE.KEXDH_REPLY; - - writeUInt32BE(packet, serverPublicHostKey.length, ++p); - packet.set(serverPublicHostKey, p += 4); - - writeUInt32BE(packet, - serverPublicKey.length, - p += serverPublicHostKey.length); - packet.set(serverPublicKey, p += 4); - - writeUInt32BE(packet, sigLen, p += serverPublicKey.length); - - writeUInt32BE(packet, sigTypeLen, p += 4); - packet.utf8Write(sigType, p += 4, sigTypeLen); - - writeUInt32BE(packet, signature.length, p += sigTypeLen); - packet.set(signature, p += 4); - - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_REPLY'; - break; - case 'groupex': - type = 'KEXDH_GEX_REPLY'; - break; - default: - type = 'KEXECDH_REPLY'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - - if (isServer || !scOnly) - trySendNEWKEYS(this); - - let hsCipherConfig; - let hsWrite; - const completeHandshake = (partial) => { - if (hsCipherConfig) { - trySendNEWKEYS(this); - hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; - this._protocol._cipher.free(); - this._protocol._cipher = createCipher(hsCipherConfig); - this._protocol._packetRW.write = hsWrite; - hsCipherConfig = undefined; - hsWrite = undefined; - this._protocol._onHandshakeComplete(negotiated); - - return false; - } - - if (!this.sessionID) - this.sessionID = exchangeHash; - - { - const newSecret = Buffer.allocUnsafe(4 + secret.length); - writeUInt32BE(newSecret, secret.length, 0); - newSecret.set(secret, 4); - secret = newSecret; - } - - // Initialize new ciphers, deciphers, etc. - - const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; - const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; - - const csIV = generateKEXVal(csCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'A'); - const scIV = generateKEXVal(scCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'B'); - const csKey = generateKEXVal(csCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'C'); - const scKey = generateKEXVal(scCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'D'); - let csMacInfo; - let csMacKey; - if (!csCipherInfo.authLen) { - csMacInfo = MAC_INFO[negotiated.cs.mac]; - csMacKey = generateKEXVal(csMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'E'); - } - let scMacInfo; - let scMacKey; - if (!scCipherInfo.authLen) { - scMacInfo = MAC_INFO[negotiated.sc.mac]; - scMacKey = generateKEXVal(scMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'F'); - } - - const config = { - inbound: { - onPayload: this._protocol._onPayload, - seqno: this._protocol._decipher.inSeqno, - decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), - decipherIV: (!isServer ? scIV : csIV), - decipherKey: (!isServer ? scKey : csKey), - macInfo: (!isServer ? scMacInfo : csMacInfo), - macKey: (!isServer ? scMacKey : csMacKey), - }, - outbound: { - onWrite: this._protocol._onWrite, - seqno: this._protocol._cipher.outSeqno, - cipherInfo: (isServer ? scCipherInfo : csCipherInfo), - cipherIV: (isServer ? scIV : csIV), - cipherKey: (isServer ? scKey : csKey), - macInfo: (isServer ? scMacInfo : csMacInfo), - macKey: (isServer ? scMacKey : csMacKey), - }, - }; - this._protocol._decipher.free(); - hsCipherConfig = config; - this._protocol._decipher = createDecipher(config); - - const rw = { - read: undefined, - write: undefined, - }; - switch (negotiated.cs.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.read = new PacketReader(); - else - rw.write = new PacketWriter(this._protocol); - } - switch (negotiated.sc.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.write = new PacketWriter(this._protocol); - else - rw.read = new PacketReader(); - } - this._protocol._packetRW.read.cleanup(); - this._protocol._packetRW.write.cleanup(); - this._protocol._packetRW.read = rw.read; - hsWrite = rw.write; - - // Cleanup/reset various state - this._public = null; - this._dh = null; - this._kexinit = this._protocol._kexinit = undefined; - this._remoteKexinit = undefined; - this._identRaw = undefined; - this._remoteIdentRaw = undefined; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - - if (!partial) - return completeHandshake(); - return false; - }; - - if (isServer || scOnly) - this.finish = completeHandshake; - - if (!isServer) - return completeHandshake(scOnly); + /** + * Creates a new vector bucket + * Vector buckets are containers for vector indexes and their data + * + * @param vectorBucketName - Unique name for the vector bucket + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorConflictException` if bucket already exists (HTTP 409) + * - `S3VectorMaxBucketsExceeded` if quota exceeded (HTTP 400) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.createBucket('embeddings-prod') + * if (error) { + * console.error('Failed to create bucket:', error.message) + * } + * ``` + */ + createBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - start() { - if (!this._protocol._server) { - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_INIT'; - break; - default: - type = 'KEXECDH_INIT'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - - const pubKey = this.getPublicKey(); - - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + pubKey.length, - true - ); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } + /** + * Retrieves metadata for a specific vector bucket + * Returns bucket configuration including encryption settings and creation time + * + * @param vectorBucketName - Name of the vector bucket to retrieve + * @returns Promise with bucket metadata or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.getBucket('embeddings-prod') + * if (data) { + * console.log('Bucket created at:', new Date(data.vectorBucket.creationTime! * 1000)) + * } + * ``` + */ + getBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Lists vector buckets with optional filtering and pagination + * Supports prefix-based filtering and paginated results + * + * @param options - Listing options + * @param options.prefix - Filter buckets by name prefix + * @param options.maxResults - Maximum results per page (default: 100) + * @param options.nextToken - Pagination token from previous response + * @returns Promise with list of buckets and pagination token + * + * @throws {StorageVectorsApiError} With code: + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // List all buckets with prefix 'prod-' + * const { data, error } = await client.listBuckets({ prefix: 'prod-' }) + * if (data) { + * console.log('Found buckets:', data.buckets.length) + * // Fetch next page if available + * if (data.nextToken) { + * const next = await client.listBuckets({ nextToken: data.nextToken }) + * } + * } + * ``` + */ + listBuckets() { + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectorBuckets`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes a vector bucket + * Bucket must be empty before deletion (all indexes must be removed first) + * + * @param vectorBucketName - Name of the vector bucket to delete + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorBucketNotEmpty` if bucket contains indexes (HTTP 400) + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Delete all indexes first, then delete bucket + * const { error } = await client.deleteBucket('old-bucket') + * if (error?.statusCode === 'S3VectorBucketNotEmpty') { + * console.error('Must delete all indexes first') + * } + * ``` + */ + deleteBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - getPublicKey() { - this.generateKeys(); +} +exports["default"] = VectorBucketApi; +//# sourceMappingURL=VectorBucketApi.js.map - const key = this._public; +/***/ }), - if (key) - return this.convertPublicKey(key); - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } +/***/ 3073: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (key[idx] & 0x80) { - newKey = Buffer.allocUnsafe(1 + len); - newKey[0] = 0; - key.copy(newKey, 1, idx); - return newKey; - } +"use strict"; - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(6876); +const errors_1 = __nccwpck_require__(3071); +const fetch_1 = __nccwpck_require__(2593); +const helpers_1 = __nccwpck_require__(1176); +/** + * API class for managing Vector Data within Vector Indexes + * Provides methods for inserting, querying, listing, and deleting vector embeddings + */ +class VectorDataApi { + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - return convertToMpint(this._dh.computeSecret(otherPublicKey)); - } catch (ex) { - return ex; - } + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + * @example + * ```typescript + * const client = new VectorDataApi(url, headers) + * client.throwOnError() + * const { data } = await client.putVectors(options) // throws on error + * ``` + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - // Server - if (type !== MESSAGE.KEXDH_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Init' - ); - /* - byte SSH_MSG_KEXDH_INIT - / SSH_MSG_KEX_ECDH_INIT - string - */ - bufferParser.init(payload, 1); - const dhData = bufferParser.readString(); - bufferParser.clear(); - if (dhData === undefined) { - return doFatalError( - this._protocol, - 'Received malformed KEX*_INIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Client public key - this._dhData = dhData; - - let hostKey = - this._protocol._hostKeys[this.negotiated.serverHostKey]; - if (Array.isArray(hostKey)) - hostKey = hostKey[0]; - this._hostKey = hostKey; - - this.finish(); - } else { - // Client - if (type !== MESSAGE.KEXDH_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Reply' - ); - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - bufferParser.init(payload, 1); - let hostPubKey; - let dhData; - let sig; - if ((hostPubKey = bufferParser.readString()) === undefined - || (dhData = bufferParser.readString()) === undefined - || (sig = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEX*_REPLY', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // Check that the host public key type matches what was negotiated - // during KEXINIT swap - bufferParser.init(hostPubKey, 0); - const hostPubKeyType = bufferParser.readString(true); - bufferParser.clear(); - if (hostPubKeyType === undefined) { - return doFatalError( - this._protocol, - 'Received malformed host public key', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (hostPubKeyType !== this.negotiated.serverHostKey) { - // Check if we need to make an exception - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': - case 'rsa-sha2-512': - if (hostPubKeyType === 'ssh-rsa') - break; - // FALLTHROUGH - default: - return doFatalError( - this._protocol, - 'Host key does not match negotiated type', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + /** + * Inserts or updates vectors in batch (upsert operation) + * Accepts 1-500 vectors per request. Larger batches should be split + * + * @param options - Vector insertion options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the target index + * @param options.vectors - Array of vectors to insert/update (1-500 items) + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorConflictException` if duplicate key conflict occurs (HTTP 409) + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.putVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * vectors: [ + * { + * key: 'doc-1', + * data: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions + * metadata: { title: 'Introduction', page: 1 } + * }, + * { + * key: 'doc-2', + * data: { float32: [0.4, 0.5, 0.6, ...] }, + * metadata: { title: 'Conclusion', page: 42 } + * } + * ] + * }) + * ``` + */ + putVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Validate batch size + if (options.vectors.length < 1 || options.vectors.length > 500) { + throw new Error('Vector batch size must be between 1 and 500 items'); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/PutVectors`, options, { + headers: this.headers, + }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves vectors by their keys in batch + * Optionally includes vector data and/or metadata in response + * Additional permissions required when returning data or metadata + * + * @param options - Vector retrieval options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.keys - Array of vector keys to retrieve + * @param options.returnData - Whether to include vector embeddings (requires permission) + * @param options.returnMetadata - Whether to include metadata (requires permission) + * @returns Promise with array of vectors or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.getVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * keys: ['doc-1', 'doc-2', 'doc-3'], + * returnData: false, // Don't return embeddings + * returnMetadata: true // Return metadata only + * }) + * if (data) { + * data.vectors.forEach(v => console.log(v.key, v.metadata)) + * } + * ``` + */ + getVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectors`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Lists/scans vectors in an index with pagination + * Supports parallel scanning via segment configuration for high-throughput scenarios + * Additional permissions required when returning data or metadata + * + * @param options - Vector listing options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.maxResults - Maximum results per page (default: 500, max: 1000) + * @param options.nextToken - Pagination token from previous response + * @param options.returnData - Whether to include vector embeddings (requires permission) + * @param options.returnMetadata - Whether to include metadata (requires permission) + * @param options.segmentCount - Total parallel segments (1-16) for distributed scanning + * @param options.segmentIndex - Zero-based segment index (0 to segmentCount-1) + * @returns Promise with array of vectors, pagination token, or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Simple pagination + * let nextToken: string | undefined + * do { + * const { data, error } = await client.listVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * maxResults: 500, + * nextToken, + * returnMetadata: true + * }) + * if (error) break + * console.log('Batch:', data.vectors.length) + * nextToken = data.nextToken + * } while (nextToken) + * + * // Parallel scanning (4 concurrent workers) + * const workers = [0, 1, 2, 3].map(async (segmentIndex) => { + * const { data } = await client.listVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * segmentCount: 4, + * segmentIndex, + * returnMetadata: true + * }) + * return data?.vectors || [] + * }) + * const results = await Promise.all(workers) + * ``` + */ + listVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Validate segment configuration + if (options.segmentCount !== undefined) { + if (options.segmentCount < 1 || options.segmentCount > 16) { + throw new Error('segmentCount must be between 1 and 16'); + } + if (options.segmentIndex !== undefined) { + if (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) { + throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`); + } + } + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectors`, options, { + headers: this.headers, + }); + return { data, error: null }; } - - this._hostKey = hostPubKey; - this._dhData = dhData; - this._sig = sig; - - let checked = false; - let ret; - if (this._protocol._hostVerifier === undefined) { - ret = true; - this._protocol._debug && this._protocol._debug( - 'Host accepted by default (no verification)' - ); - } else { - ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { - if (checked) - return; - checked = true; - if (permitted === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + catch (error) { + if (this.shouldThrowOnError) { + throw error; } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - if (this._receivedNEWKEYS) - this.finish(); - else - trySendNEWKEYS(this); - }); - } - if (ret === undefined) { - // Async host verification - ++this._step; - return; - } - checked = true; - if (ret === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - trySendNEWKEYS(this); - } - ++this._step; - break; - case 2: - if (type !== MESSAGE.NEWKEYS) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Inbound: NEWKEYS' - ); - this._receivedNEWKEYS = true; - if (this._protocol._strictMode) - this._protocol._decipher.inSeqno = 0; - ++this._step; - - return this.finish(!this._protocol._server && !this._hostVerified); - default: - return doFatalError( - this._protocol, - `Received unexpected packet ${type} after NEWKEYS`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - } - - class Curve25519Exchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - - this.type = '25519'; - this.hashName = hashName; - this._keys = null; - } - generateKeys() { - if (!this._keys) - this._keys = generateKeyPairSync('x25519'); - } - getPublicKey() { - this.generateKeys(); - - const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); - return key.slice(-32); // HACK: avoids parsing DER/BER header - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - - if (key.length === 32) - return key; - - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; - } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.110'); // id-X25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(otherPublicKey.length); - otherPublicKey.copy(asnWriter._buf, - asnWriter._offset, - 0, - otherPublicKey.length); - asnWriter._offset += otherPublicKey.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - - return convertToMpint(diffieHellman({ - privateKey: this._keys.privateKey, - publicKey: createPublicKey({ - key: asnWriter.buffer, - type: 'spki', - format: 'der', - }), - })); - } catch (ex) { - return ex; - } - } - } - - class ECDHExchange extends KeyExchange { - constructor(curveName, hashName, ...args) { - super(...args); - - this.type = 'ecdh'; - this.curveName = curveName; - this.hashName = hashName; - } - generateKeys() { - if (!this._dh) { - this._dh = createECDH(this.curveName); - this._public = this._dh.generateKeys(); - } - } - } - - class DHGroupExchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); - - this.type = 'groupex'; - this.hashName = hashName; - this._prime = null; - this._generator = null; - this._minBits = GEX_MIN_BITS; - this._prefBits = dhEstimate(this.negotiated); - if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) - this._prefBits = Math.min(this._prefBits, 4096); - this._maxBits = GEX_MAX_BITS; - } - start() { - if (this._protocol._server) - return; - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_REQUEST' - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + 4 + 4, - true - ); - packet[p] = MESSAGE.KEXDH_GEX_REQUEST; - writeUInt32BE(packet, this._minBits, ++p); - writeUInt32BE(packet, this._prefBits, p += 4); - writeUInt32BE(packet, this._maxBits, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - generateKeys() { - if (!this._dh && this._prime && this._generator) { - this._dh = createDiffieHellman(this._prime, this._generator); - this._public = this._dh.generateKeys(); - } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - setDHParams(prime, generator) { - if (!Buffer.isBuffer(prime)) - throw new Error('Invalid prime value'); - if (!Buffer.isBuffer(generator)) - throw new Error('Invalid generator value'); - this._prime = prime; - this._generator = generator; + /** + * Queries for similar vectors using approximate nearest neighbor (ANN) search + * Returns top-K most similar vectors based on the configured distance metric + * Supports optional metadata filtering (requires GetVectors permission) + * + * @param options - Query options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.queryVector - Query embedding to find similar vectors + * @param options.topK - Number of nearest neighbors to return (default: 10) + * @param options.filter - Optional JSON filter for metadata (requires GetVectors permission) + * @param options.returnDistance - Whether to include similarity distances + * @param options.returnMetadata - Whether to include metadata (requires GetVectors permission) + * @returns Promise with array of similar vectors ordered by distance + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Semantic search with filtering + * const { data, error } = await client.queryVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * queryVector: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions + * topK: 5, + * filter: { + * category: 'technical', + * published: true + * }, + * returnDistance: true, + * returnMetadata: true + * }) + * if (data) { + * data.matches.forEach(match => { + * console.log(`${match.key}: distance=${match.distance}`) + * console.log('Metadata:', match.metadata) + * }) + * } + * ``` + */ + queryVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/QueryVectors`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } + /** + * Deletes vectors by their keys in batch + * Accepts 1-500 keys per request + * + * @param options - Vector deletion options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.keys - Array of vector keys to delete (1-500 items) + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { error } = await client.deleteVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * keys: ['doc-1', 'doc-2', 'doc-3'] + * }) + * if (!error) { + * console.log('Vectors deleted successfully') + * } + * ``` + */ + deleteVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Validate batch size + if (options.keys.length < 1 || options.keys.length > 500) { + throw new Error('Keys batch size must be between 1 and 500 items'); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectors`, options, { + headers: this.headers, + }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: { - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_REQUEST) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ` - + MESSAGE.KEXDH_GEX_REQUEST, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - // TODO: allow user implementation to provide safe prime and - // generator on demand to support group exchange on server side - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (type !== MESSAGE.KEXDH_GEX_GROUP) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Group' - ); - - /* - byte SSH_MSG_KEX_DH_GEX_GROUP - mpint p, safe prime - mpint g, generator for subgroup in GF(p) - */ - bufferParser.init(payload, 1); - let prime; - let gen; - if ((prime = bufferParser.readString()) === undefined - || (gen = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEXDH_GEX_GROUP', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // TODO: validate prime - this.setDHParams(prime, gen); - this.generateKeys(); - const pubkey = this.getPublicKey(); - - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_INIT' - ); +} +exports["default"] = VectorDataApi; +//# sourceMappingURL=VectorDataApi.js.map - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); - packet[p] = MESSAGE.KEXDH_GEX_INIT; - writeUInt32BE(packet, pubkey.length, ++p); - packet.set(pubkey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); +/***/ }), - ++this._step; - break; - } - case 2: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Init' - ); - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Reply' - ); - this._step = 1; - payload[0] = MESSAGE.KEXDH_REPLY; - this.parse = KeyExchange.prototype.parse; - this.parse(payload); - } - } - } +/***/ 9623: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - class DHExchange extends KeyExchange { - constructor(groupName, hashName, ...args) { - super(...args); +"use strict"; - this.type = 'group'; - this.groupName = groupName; - this.hashName = hashName; - } - start() { - if (!this._protocol._server) { - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_INIT' - ); - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - generateKeys() { - if (!this._dh) { - this._dh = createDiffieHellmanGroup(this.groupName); - this._public = this._dh.generateKeys(); - } - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(6876); +const errors_1 = __nccwpck_require__(3071); +const fetch_1 = __nccwpck_require__(2593); +const helpers_1 = __nccwpck_require__(1176); +/** + * API class for managing Vector Indexes within Vector Buckets + * Provides methods for creating, reading, listing, and deleting vector indexes + */ +class VectorIndexApi { + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); } - } - - return (negotiated, ...args) => { - if (typeof negotiated !== 'object' || negotiated === null) - throw new Error('Invalid negotiated argument'); - const kexType = negotiated.kex; - if (typeof kexType === 'string') { - args = [negotiated, ...args]; - switch (kexType) { - case 'curve25519-sha256': - case 'curve25519-sha256@libssh.org': - if (!curve25519Supported) - break; - return new Curve25519Exchange('sha256', ...args); - - case 'ecdh-sha2-nistp256': - return new ECDHExchange('prime256v1', 'sha256', ...args); - case 'ecdh-sha2-nistp384': - return new ECDHExchange('secp384r1', 'sha384', ...args); - case 'ecdh-sha2-nistp521': - return new ECDHExchange('secp521r1', 'sha512', ...args); - - case 'diffie-hellman-group1-sha1': - return new DHExchange('modp2', 'sha1', ...args); - case 'diffie-hellman-group14-sha1': - return new DHExchange('modp14', 'sha1', ...args); - case 'diffie-hellman-group14-sha256': - return new DHExchange('modp14', 'sha256', ...args); - case 'diffie-hellman-group15-sha512': - return new DHExchange('modp15', 'sha512', ...args); - case 'diffie-hellman-group16-sha512': - return new DHExchange('modp16', 'sha512', ...args); - case 'diffie-hellman-group17-sha512': - return new DHExchange('modp17', 'sha512', ...args); - case 'diffie-hellman-group18-sha512': - return new DHExchange('modp18', 'sha512', ...args); - - case 'diffie-hellman-group-exchange-sha1': - return new DHGroupExchange('sha1', ...args); - case 'diffie-hellman-group-exchange-sha256': - return new DHGroupExchange('sha256', ...args); - } - throw new Error(`Unsupported key exchange algorithm: ${kexType}`); + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + * @example + * ```typescript + * const client = new VectorIndexApi(url, headers) + * client.throwOnError() + * const { data } = await client.createIndex(options) // throws on error + * ``` + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; } - throw new Error(`Invalid key exchange type: ${kexType}`); - }; -})(); - -const KexInit = (() => { - const KEX_PROPERTY_NAMES = [ - 'kex', - 'serverHostKey', - ['cs', 'cipher' ], - ['sc', 'cipher' ], - ['cs', 'mac' ], - ['sc', 'mac' ], - ['cs', 'compress' ], - ['sc', 'compress' ], - ['cs', 'lang' ], - ['sc', 'lang' ], - ]; - return class KexInit { - constructor(obj) { - if (typeof obj !== 'object' || obj === null) - throw new TypeError('Argument must be an object'); - - const lists = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - - all: undefined, - }; - let totalSize = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let base; - let val; - let desc; - let key; - if (typeof prop === 'string') { - base = lists; - val = obj[prop]; - desc = key = prop; - } else { - const parent = prop[0]; - base = lists[parent]; - key = prop[1]; - val = obj[parent][key]; - desc = `${parent}.${key}`; - } - const entry = { array: undefined, buffer: undefined }; - if (Buffer.isBuffer(val)) { - entry.array = ('' + val).split(','); - entry.buffer = val; - totalSize += 4 + val.length; - } else { - if (typeof val === 'string') - val = val.split(','); - if (Array.isArray(val)) { - entry.array = val; - entry.buffer = Buffer.from(val.join(',')); - } else { - throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); - } - totalSize += 4 + entry.buffer.length; - } - base[key] = entry; - } - - const all = Buffer.allocUnsafe(totalSize); - lists.all = all; - - let allPos = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let data; - if (typeof prop === 'string') - data = lists[prop].buffer; - else - data = lists[prop[0]][prop[1]].buffer; - allPos = writeUInt32BE(all, data.length, allPos); - all.set(data, allPos); - allPos += data.length; - } - - this.totalSize = totalSize; - this.lists = lists; + /** + * Creates a new vector index within a bucket + * Defines the schema for vectors including dimensionality, distance metric, and metadata config + * + * @param options - Index configuration + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Unique name for the index within the bucket + * @param options.dataType - Data type for vector components (currently only 'float32') + * @param options.dimension - Dimensionality of vectors (e.g., 384, 768, 1536) + * @param options.distanceMetric - Similarity metric ('cosine', 'euclidean', 'dotproduct') + * @param options.metadataConfiguration - Optional config for non-filterable metadata keys + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorConflictException` if index already exists (HTTP 409) + * - `S3VectorMaxIndexesExceeded` if quota exceeded (HTTP 400) + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.createIndex({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine', + * metadataConfiguration: { + * nonFilterableMetadataKeys: ['raw_text', 'internal_id'] + * } + * }) + * ``` + */ + createIndex(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateIndex`, options, { + headers: this.headers, + }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - copyAllTo(buf, offset) { - const src = this.lists.all; - if (typeof offset !== 'number') - throw new TypeError(`Invalid offset value: ${typeof offset}`); - if (buf.length - offset < src.length) - throw new Error('Insufficient space to copy list'); - buf.set(src, offset); - return src.length; + /** + * Retrieves metadata for a specific vector index + * Returns index configuration including dimension, distance metric, and metadata settings + * + * @param vectorBucketName - Name of the parent vector bucket + * @param indexName - Name of the index to retrieve + * @returns Promise with index metadata or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.getIndex('embeddings-prod', 'documents-openai-small') + * if (data) { + * console.log('Index dimension:', data.index.dimension) + * console.log('Distance metric:', data.index.distanceMetric) + * } + * ``` + */ + getIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - }; -})(); - -const hashString = (() => { - const LEN = Buffer.allocUnsafe(4); - return (hash, buf) => { - writeUInt32BE(LEN, buf.length, 0); - hash.update(LEN); - hash.update(buf); - }; -})(); - -function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { - let ret; - if (len) { - let digest = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(char) - .update(sessionID) - .digest(); - while (digest.length < len) { - const chunk = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(digest) - .digest(); - const extended = Buffer.allocUnsafe(digest.length + chunk.length); - extended.set(digest, 0); - extended.set(chunk, digest.length); - digest = extended; - } - if (digest.length === len) - ret = digest; - else - ret = new FastBuffer(digest.buffer, digest.byteOffset, len); - } else { - ret = EMPTY_BUFFER; - } - return ret; -} - -function onKEXPayload(state, payload) { - // XXX: move this to the Decipher implementations? - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - if (this._skipNextInboundPacket) { - this._skipNextInboundPacket = false; - return; - } - - payload = this._packetRW.read.read(payload); - - const type = payload[0]; - - if (!this._strictMode) { - switch (type) { - case MESSAGE.IGNORE: - case MESSAGE.UNIMPLEMENTED: - case MESSAGE.DEBUG: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = __nccwpck_require__(10172); - return MESSAGE_HANDLERS[type](this, payload); + /** + * Lists vector indexes within a bucket with optional filtering and pagination + * Supports prefix-based filtering and paginated results + * + * @param options - Listing options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.prefix - Filter indexes by name prefix + * @param options.maxResults - Maximum results per page (default: 100) + * @param options.nextToken - Pagination token from previous response + * @returns Promise with list of indexes and pagination token + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // List all indexes in a bucket + * const { data, error } = await client.listIndexes({ + * vectorBucketName: 'embeddings-prod', + * prefix: 'documents-' + * }) + * if (data) { + * console.log('Found indexes:', data.indexes.map(i => i.indexName)) + * // Fetch next page if available + * if (data.nextToken) { + * const next = await client.listIndexes({ + * vectorBucketName: 'embeddings-prod', + * nextToken: data.nextToken + * }) + * } + * } + * ``` + */ + listIndexes(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListIndexes`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - } - - switch (type) { - case MESSAGE.DISCONNECT: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = __nccwpck_require__(10172); - return MESSAGE_HANDLERS[type](this, payload); - case MESSAGE.KEXINIT: - if (!state.firstPacket) { - return doFatalError( - this, - 'Received extra KEXINIT during handshake', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - state.firstPacket = false; - return handleKexInit(this, payload); - default: - // Ensure packet is either an algorithm negotiation or KEX - // algorithm-specific packet - if (type < 20 || type > 49) { - return doFatalError( - this, - `Received unexpected packet type ${type}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - return this._kex.parse(payload); -} - -function dhEstimate(neg) { - const csCipher = CIPHER_INFO[neg.cs.cipher]; - const scCipher = CIPHER_INFO[neg.sc.cipher]; - // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will - // also need to be considered when calculating `bits` - const bits = Math.max( - 0, - (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), - csCipher.blockLen, - csCipher.ivLen, - (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), - scCipher.blockLen, - scCipher.ivLen - ) * 8; - if (bits <= 112) - return 2048; - if (bits <= 128) - return 3072; - if (bits <= 192) - return 7680; - return 8192; -} - -function trySendNEWKEYS(kex) { - if (!kex._sentNEWKEYS) { - kex._protocol._debug && kex._protocol._debug( - 'Outbound: Sending NEWKEYS' - ); - const p = kex._protocol._packetRW.write.allocStartKEX; - const packet = kex._protocol._packetRW.write.alloc(1, true); - packet[p] = MESSAGE.NEWKEYS; - kex._protocol._cipher.encrypt( - kex._protocol._packetRW.write.finalize(packet, true) - ); - kex._sentNEWKEYS = true; - if (kex._protocol._strictMode) - kex._protocol._cipher.outSeqno = 0; - } -} - -module.exports = { - KexInit, - kexinit, - onKEXPayload, - DEFAULT_KEXINIT_CLIENT: new KexInit({ - kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']), - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - DEFAULT_KEXINIT_SERVER: new KexInit({ - kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']), - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - HANDLERS: { - [MESSAGE.KEXINIT]: handleKexInit, - }, -}; - - -/***/ }), - -/***/ 22218: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// TODO: -// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` -// * handle multi-line header values (OpenSSH)? -// * more thorough validation? - - -const { - createDecipheriv, - createECDH, - createHash, - createHmac, - createSign, - createVerify, - getCiphers, - sign: sign_, - verify: verify_, -} = __nccwpck_require__(6113); -const supportedOpenSSLCiphers = getCiphers(); - -const { Ber } = __nccwpck_require__(80970); -const bcrypt_pbkdf = (__nccwpck_require__(45447).pbkdf); - -const { CIPHER_INFO } = __nccwpck_require__(45708); -const { eddsaSupported, SUPPORTED_CIPHER } = __nccwpck_require__(36832); -const { - bufferSlice, - makeBufferParser, - readString, - readUInt32BE, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const SYM_HASH_ALGO = Symbol('Hash Algorithm'); -const SYM_PRIV_PEM = Symbol('Private key PEM'); -const SYM_PUB_PEM = Symbol('Public key PEM'); -const SYM_PUB_SSH = Symbol('Public key SSH'); -const SYM_DECRYPTED = Symbol('Decrypted Key'); - -// Create OpenSSL cipher name -> SSH cipher name conversion table -const CIPHER_INFO_OPENSSL = Object.create(null); -{ - const keys = Object.keys(CIPHER_INFO); - for (let i = 0; i < keys.length; ++i) { - const cipherName = CIPHER_INFO[keys[i]].sslName; - if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) - continue; - CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; - } -} - -const binaryKeyParser = makeBufferParser(); - -function makePEM(type, data) { - data = data.base64Slice(0, data.length); - let formatted = data.replace(/.{64}/g, '$&\n'); - if (data.length & 63) - formatted += '\n'; - return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; -} - -function combineBuffers(buf1, buf2) { - const result = Buffer.allocUnsafe(buf1.length + buf2.length); - result.set(buf1, 0); - result.set(buf2, buf1.length); - return result; -} - -function skipFields(buf, nfields) { - const bufLen = buf.length; - let pos = (buf._pos || 0); - for (let i = 0; i < nfields; ++i) { - const left = (bufLen - pos); - if (pos >= bufLen || left < 4) - return false; - const len = readUInt32BE(buf, pos); - if (left < 4 + len) - return false; - pos += 4 + len; - } - buf._pos = pos; - return true; -} - -function genOpenSSLRSAPub(n, e) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption - // algorithm parameters (RSA has none) - asnWriter.writeNull(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.startSequence(); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHRSAPub(n, e) { - const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); - - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-rsa', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, e.length, i); - publicKey.set(e, i += 4); - - writeUInt32BE(publicKey, n.length, i += e.length); - publicKey.set(n, i + 4); - - return publicKey; -} - -const genOpenSSLRSAPriv = (() => { - function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.writeBuffer(d, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(dmp1, Ber.Integer); - asnWriter.writeBuffer(dmq1, Ber.Integer); - asnWriter.writeBuffer(iqmp, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - - function bigIntFromBuffer(buf) { - return BigInt(`0x${buf.hexSlice(0, buf.length)}`); - } - - function bigIntToBuffer(bn) { - let hex = bn.toString(16); - if ((hex.length & 1) !== 0) { - hex = `0${hex}`; - } else { - const sigbit = hex.charCodeAt(0); - // BER/DER integers require leading zero byte to denote a positive value - // when first byte >= 0x80 - if (sigbit === 56/* '8' */ - || sigbit === 57/* '9' */ - || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { - hex = `00${hex}`; - } + /** + * Deletes a vector index and all its data + * This operation removes the index schema and all vectors stored in the index + * + * @param vectorBucketName - Name of the parent vector bucket + * @param indexName - Name of the index to delete + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Delete an index and all its vectors + * const { error } = await client.deleteIndex('embeddings-prod', 'old-index') + * if (!error) { + * console.log('Index deleted successfully') + * } + * ``` + */ + deleteIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - return Buffer.from(hex, 'hex'); - } +} +exports["default"] = VectorIndexApi; +//# sourceMappingURL=VectorIndexApi.js.map - return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { - const bn_d = bigIntFromBuffer(d); - const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); - const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); - return makePEM('RSA PRIVATE', - genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); - }; -})(); +/***/ }), -function genOpenSSLDSAPub(p, q, g, y) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa - // algorithm parameters - asnWriter.startSequence(); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHDSAPub(p, q, g, y) { - const publicKey = Buffer.allocUnsafe( - 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length - ); +/***/ 6876: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-dss', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, p.length, i); - publicKey.set(p, i += 4); - - writeUInt32BE(publicKey, q.length, i += p.length); - publicKey.set(q, i += 4); - - writeUInt32BE(publicKey, g.length, i += q.length); - publicKey.set(g, i += 4); - - writeUInt32BE(publicKey, y.length, i += g.length); - publicKey.set(y, i + 4); - - return publicKey; -} - -function genOpenSSLDSAPriv(p, q, g, y, x) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.writeBuffer(x, Ber.Integer); - asnWriter.endSequence(); - return makePEM('DSA PRIVATE', asnWriter.buffer); -} - -function genOpenSSLEdPub(pub) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHEdPub(pub) { - const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); - - writeUInt32BE(publicKey, 11, 0); - publicKey.utf8Write('ssh-ed25519', 4, 11); - - writeUInt32BE(publicKey, pub.length, 15); - publicKey.set(pub, 19); - - return publicKey; -} - -function genOpenSSLEdPriv(priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x00, Ber.Integer); - - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PrivateKey - asnWriter.startSequence(Ber.OctetString); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPub(oid, Q) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey - // algorithm parameters (namedCurve) - asnWriter.writeOID(oid); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(Q.length); - asnWriter._buf.set(Q, asnWriter._offset); - asnWriter._offset += Q.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHECDSAPub(oid, Q) { - let curveName; - switch (oid) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - curveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - curveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - curveName = 'nistp521'; - break; - default: - return; - } +"use strict"; - const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); - - writeUInt32BE(publicKey, 19, 0); - publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); - - writeUInt32BE(publicKey, 8, 23); - publicKey.utf8Write(curveName, 27, 8); - - writeUInt32BE(publicKey, Q.length, 35); - publicKey.set(Q, 39); - - return publicKey; -} - -function genOpenSSLECDSAPriv(oid, pub, priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x01, Ber.Integer); - // privateKey - asnWriter.writeBuffer(priv, Ber.OctetString); - // parameters (optional) - asnWriter.startSequence(0xA0); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - // publicKey (optional) - asnWriter.startSequence(0xA1); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('EC PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPubFromPriv(curveName, priv) { - const tempECDH = createECDH(curveName); - tempECDH.setPrivateKey(priv); - return tempECDH.getPublicKey(); -} - -const BaseKey = { - sign: (() => { - if (typeof sign_ === 'function') { - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return sign_(algo, data, pem); - } catch (ex) { - return ex; - } - }; - } - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const signature = createSign(algo); - signature.update(data); - try { - return signature.sign(pem); - } catch (ex) { - return ex; - } - }; - })(), - verify: (() => { - if (typeof verify_ === 'function') { - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return verify_(algo, data, pem, signature); - } catch (ex) { - return ex; - } - }; - } - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const verifier = createVerify(algo); - verifier.update(data); - try { - return verifier.verify(pem, signature); - } catch (ex) { - return ex; - } - }; - })(), - isPrivateKey: function isPrivateKey() { - return (this[SYM_PRIV_PEM] !== null); - }, - getPrivatePEM: function getPrivatePEM() { - return this[SYM_PRIV_PEM]; - }, - getPublicPEM: function getPublicPEM() { - return this[SYM_PUB_PEM]; - }, - getPublicSSH: function getPublicSSH() { - return this[SYM_PUB_SSH]; - }, - equals: function equals(key) { - const parsed = parseKey(key); - if (parsed instanceof Error) - return false; - return ( - this.type === parsed.type - && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] - && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] - && this[SYM_PUB_SSH].equals(parsed[SYM_PUB_SSH]) - ); - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_HEADERS = void 0; +const version_1 = __nccwpck_require__(4499); +exports.DEFAULT_HEADERS = { + 'X-Client-Info': `storage-js/${version_1.version}`, + 'Content-Type': 'application/json', }; +//# sourceMappingURL=constants.js.map +/***/ }), -function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -OpenSSH_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; - OpenSSH_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let ret; - const data = Buffer.from(m[1], 'base64'); - if (data.length < 31) // magic (+ magic null term.) + minimum field lengths - return new Error('Malformed OpenSSH private key'); - const magic = data.utf8Slice(0, 15); - if (magic !== 'openssh-key-v1\0') - return new Error(`Unsupported OpenSSH key magic: ${magic}`); - - const cipherName = readString(data, 15, true); - if (cipherName === undefined) - return new Error('Malformed OpenSSH private key'); - if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) - return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); - - const kdfName = readString(data, data._pos, true); - if (kdfName === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'none') { - if (cipherName === 'none') - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'bcrypt') - return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); - if (!passphrase) { - return new Error( - 'Encrypted private OpenSSH key detected, but no passphrase given' - ); - } - } else if (cipherName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - let encInfo; - let cipherKey; - let cipherIV; - if (cipherName !== 'none') - encInfo = CIPHER_INFO[cipherName]; - const kdfOptions = readString(data, data._pos); - if (kdfOptions === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfOptions.length) { - switch (kdfName) { - case 'none': - return new Error('Malformed OpenSSH private key'); - case 'bcrypt': { - /* - string salt - uint32 rounds - */ - const salt = readString(kdfOptions, 0); - if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) - return new Error('Malformed OpenSSH private key'); - const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); - const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); - const r = bcrypt_pbkdf(passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds); - if (r !== 0) - return new Error('Failed to generate information to decrypt key'); - cipherKey = bufferSlice(gen, 0, encInfo.keyLen); - cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); - break; - } - } - } else if (kdfName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - if (data._pos + 3 >= data.length) - return new Error('Malformed OpenSSH private key'); - const keyCount = readUInt32BE(data, data._pos); - data._pos += 4; - - if (keyCount > 0) { - // TODO: place sensible limit on max `keyCount` - - // Read public keys first - for (let i = 0; i < keyCount; ++i) { - const pubData = readString(data, data._pos); - if (pubData === undefined) - return new Error('Malformed OpenSSH private key'); - const type = readString(pubData, 0, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - } - - let privBlob = readString(data, data._pos); - if (privBlob === undefined) - return new Error('Malformed OpenSSH private key'); - - if (cipherKey !== undefined) { - // Encrypted private key(s) - if (privBlob.length < encInfo.blockLen - || (privBlob.length % encInfo.blockLen) !== 0) { - return new Error('Malformed OpenSSH private key'); - } - try { - const options = { authTagLength: encInfo.authLen }; - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - cipherIV, - options); - decipher.setAutoPadding(false); - if (encInfo.authLen > 0) { - if (data.length - data._pos < encInfo.authLen) - return new Error('Malformed OpenSSH private key'); - decipher.setAuthTag( - bufferSlice(data, data._pos, data._pos += encInfo.authLen) - ); - } - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } - // Nothing should we follow the private key(s), except a possible - // authentication tag for relevant ciphers - if (data._pos !== data.length) - return new Error('Malformed OpenSSH private key'); - - ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); - } else { - ret = []; - } - if (ret instanceof Error) - return ret; - // This will need to change if/when OpenSSH ever starts storing multiple - // keys in their key files - return ret[0]; - }; - - function parseOpenSSHPrivKeys(data, nkeys, decrypted) { - const keys = []; - /* - uint32 checkint - uint32 checkint - string privatekey1 - string comment1 - string privatekey2 - string comment2 - ... - string privatekeyN - string commentN - char 1 - char 2 - char 3 - ... - char padlen % 255 - */ - if (data.length < 8) - return new Error('Malformed OpenSSH private key'); - const check1 = readUInt32BE(data, 0); - const check2 = readUInt32BE(data, 4); - if (check1 !== check2) { - if (decrypted) { - return new Error( - 'OpenSSH key integrity check failed -- bad passphrase?' - ); - } - return new Error('OpenSSH key integrity check failed'); - } - data._pos = 8; - let i; - let oid; - for (i = 0; i < nkeys; ++i) { - let algo; - let privPEM; - let pubPEM; - let pubSSH; - // The OpenSSH documentation for the key format actually lies, the - // entirety of the private key content is not contained with a string - // field, it's actually the literal contents of the private key, so to be - // able to find the end of the key data you need to know the layout/format - // of each key type ... - const type = readString(data, data._pos, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - - switch (type) { - case 'ssh-rsa': { - /* - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH private key'); - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed OpenSSH private key'); - const d = readString(data, data._pos); - if (d === undefined) - return new Error('Malformed OpenSSH private key'); - const iqmp = readString(data, data._pos); - if (iqmp === undefined) - return new Error('Malformed OpenSSH private key'); - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - /* - string p -- public - string q -- public - string g -- public - string y -- public - string x -- private - */ - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH private key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH private key'); - const x = readString(data, data._pos); - if (x === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - if (!eddsaSupported) - return new Error(`Unsupported OpenSSH private key type: ${type}`); - /* - * string public key - * string private key + public key - */ - const edpub = readString(data, data._pos); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH private key'); - const edpriv = readString(data, data._pos); - if (edpriv === undefined || edpriv.length !== 64) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - /* - string curve name - string Q -- public - string d -- private - */ - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH private key'); - const ecpub = readString(data, data._pos); - if (ecpub === undefined) - return new Error('Malformed OpenSSH private key'); - const ecpriv = readString(data, data._pos); - if (ecpriv === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); - break; - } - default: - return new Error(`Unsupported OpenSSH private key type: ${type}`); - } +/***/ 3071: +/***/ ((__unused_webpack_module, exports) => { - const privComment = readString(data, data._pos, true); - if (privComment === undefined) - return new Error('Malformed OpenSSH private key'); +"use strict"; - keys.push( - new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, - decrypted) - ); - } - let cnt = 0; - for (i = data._pos; i < data.length; ++i) { - if (data[i] !== (++cnt % 255)) - return new Error('Malformed OpenSSH private key'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = void 0; +exports.isStorageVectorsError = isStorageVectorsError; +/** + * Base error class for all Storage Vectors errors + */ +class StorageVectorsError extends Error { + constructor(message) { + super(message); + this.__isStorageVectorsError = true; + this.name = 'StorageVectorsError'; } - - return keys; - } } - - -function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; +exports.StorageVectorsError = StorageVectorsError; +/** + * Type guard to check if an error is a StorageVectorsError + * @param error - The error to check + * @returns True if the error is a StorageVectorsError + */ +function isStorageVectorsError(error) { + return typeof error === 'object' && error !== null && '__isStorageVectorsError' in error; } -OpenSSH_Old_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; - OpenSSH_Old_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let privBlob = Buffer.from(m[3], 'base64'); - let headers = m[2]; - let decrypted = false; - if (headers !== undefined) { - // encrypted key - headers = headers.split(/\r\n|\n/g); - for (let i = 0; i < headers.length; ++i) { - const header = headers[i]; - let sepIdx = header.indexOf(':'); - if (header.slice(0, sepIdx) === 'DEK-Info') { - const val = header.slice(sepIdx + 2); - sepIdx = val.indexOf(','); - if (sepIdx === -1) - continue; - const cipherName = val.slice(0, sepIdx).toLowerCase(); - if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const encInfo = CIPHER_INFO_OPENSSL[cipherName]; - if (!encInfo) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); - if (cipherIV.length !== encInfo.ivLen) - return new Error('Malformed encrypted OpenSSH private key'); - if (!passphrase) { - return new Error( - 'Encrypted OpenSSH private key detected, but no passphrase given' - ); - } - const ivSlice = bufferSlice(cipherIV, 0, 8); - let cipherKey = createHash('md5') - .update(passphrase) - .update(ivSlice) - .digest(); - while (cipherKey.length < encInfo.keyLen) { - cipherKey = combineBuffers( - cipherKey, - createHash('md5') - .update(cipherKey) - .update(passphrase) - .update(ivSlice) - .digest() - ); - } - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - decrypted = true; - } catch (ex) { - return ex; - } - } - } +/** + * API error returned from S3 Vectors service + * Includes HTTP status code and service-specific error code + */ +class StorageVectorsApiError extends StorageVectorsError { + constructor(message, status, statusCode) { + super(message); + this.name = 'StorageVectorsApiError'; + this.status = status; + this.statusCode = statusCode; } - - let type; - let privPEM; - let pubPEM; - let pubSSH; - let algo; - let reader; - let errMsg = 'Malformed OpenSSH private key'; - if (decrypted) - errMsg += '. Bad passphrase?'; - switch (m[1]) { - case 'RSA': - type = 'ssh-rsa'; - privPEM = makePEM('RSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const n = reader.readString(Ber.Integer, true); - if (n === null) - return new Error(errMsg); - const e = reader.readString(Ber.Integer, true); - if (e === null) - return new Error(errMsg); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'DSA': - type = 'ssh-dss'; - privPEM = makePEM('DSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const p = reader.readString(Ber.Integer, true); - if (p === null) - return new Error(errMsg); - const q = reader.readString(Ber.Integer, true); - if (q === null) - return new Error(errMsg); - const g = reader.readString(Ber.Integer, true); - if (g === null) - return new Error(errMsg); - const y = reader.readString(Ber.Integer, true); - if (y === null) - return new Error(errMsg); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'EC': { - let ecSSLName; - let ecPriv; - let ecOID; - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - ecPriv = reader.readString(Ber.OctetString, true); - reader.readByte(); // Skip "complex" context type byte - const offset = reader.readLength(); // Skip context length - if (offset !== null) { - reader._offset = offset; - ecOID = reader.readOID(); - if (ecOID === null) - return new Error(errMsg); - switch (ecOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - ecSSLName = 'prime256v1'; - type = 'ecdsa-sha2-nistp256'; - algo = 'sha256'; - break; - case '1.3.132.0.34': - // secp384r1 - ecSSLName = 'secp384r1'; - type = 'ecdsa-sha2-nistp384'; - algo = 'sha384'; - break; - case '1.3.132.0.35': - // secp521r1 - ecSSLName = 'secp521r1'; - type = 'ecdsa-sha2-nistp521'; - algo = 'sha512'; - break; - default: - return new Error(`Unsupported private key EC OID: ${ecOID}`); - } - } else { - return new Error(errMsg); - } - } catch { - return new Error(errMsg); - } - privPEM = makePEM('EC PRIVATE', privBlob); - const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); - pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); - pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); - break; - } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode, + }; } - - return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, - decrypted); - }; -} - - -function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; } -PPK_Private.prototype = BaseKey; -{ - const EMPTY_PASSPHRASE = Buffer.alloc(0); - const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - const PPK_PP1 = Buffer.from([0, 0, 0, 0]); - const PPK_PP2 = Buffer.from([0, 0, 0, 1]); - const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; - PPK_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = key type - // m[2] = encryption type - // m[3] = comment - // m[4] = base64-encoded public key data: - // for "ssh-rsa": - // string "ssh-rsa" - // mpint e (public exponent) - // mpint n (modulus) - // for "ssh-dss": - // string "ssh-dss" - // mpint p (modulus) - // mpint q (prime) - // mpint g (base number) - // mpint y (public key parameter: g^x mod p) - // m[5] = base64-encoded private key data: - // for "ssh-rsa": - // mpint d (private exponent) - // mpint p (prime 1) - // mpint q (prime 2) - // mpint iqmp ([inverse of q] mod p) - // for "ssh-dss": - // mpint x (private key parameter) - // m[6] = SHA1 HMAC over: - // string name of algorithm ("ssh-dss", "ssh-rsa") - // string encryption type - // string comment - // string public key data - // string private-plaintext (including the final padding) - const cipherName = m[2]; - const encrypted = (cipherName !== 'none'); - if (encrypted && !passphrase) { - return new Error( - 'Encrypted PPK private key detected, but no passphrase given' - ); - } - - let privBlob = Buffer.from(m[5], 'base64'); - - if (encrypted) { - const encInfo = CIPHER_INFO[cipherName]; - let cipherKey = combineBuffers( - createHash('sha1').update(PPK_PP1).update(passphrase).digest(), - createHash('sha1').update(PPK_PP2).update(passphrase).digest() - ); - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } - - const type = m[1]; - const comment = m[3]; - const pubBlob = Buffer.from(m[4], 'base64'); - - const mac = m[6]; - const typeLen = type.length; - const cipherNameLen = cipherName.length; - const commentLen = Buffer.byteLength(comment); - const pubLen = pubBlob.length; - const privLen = privBlob.length; - const macData = Buffer.allocUnsafe(4 + typeLen - + 4 + cipherNameLen - + 4 + commentLen - + 4 + pubLen - + 4 + privLen); - let p = 0; - - writeUInt32BE(macData, typeLen, p); - macData.utf8Write(type, p += 4, typeLen); - writeUInt32BE(macData, cipherNameLen, p += typeLen); - macData.utf8Write(cipherName, p += 4, cipherNameLen); - writeUInt32BE(macData, commentLen, p += cipherNameLen); - macData.utf8Write(comment, p += 4, commentLen); - writeUInt32BE(macData, pubLen, p += commentLen); - macData.set(pubBlob, p += 4); - writeUInt32BE(macData, privLen, p += pubLen); - macData.set(privBlob, p + 4); - - if (!passphrase) - passphrase = EMPTY_PASSPHRASE; - - const calcMAC = createHmac( - 'sha1', - createHash('sha1') - .update('putty-private-key-file-mac-key') - .update(passphrase) - .digest() - ).update(macData).digest('hex'); - - if (calcMAC !== mac) { - if (encrypted) { - return new Error( - 'PPK private key integrity check failed -- bad passphrase?' - ); - } - return new Error('PPK private key integrity check failed'); - } - - let pubPEM; - let pubSSH; - let privPEM; - pubBlob._pos = 0; - skipFields(pubBlob, 1); // skip (duplicate) key type - switch (type) { - case 'ssh-rsa': { - const e = readString(pubBlob, pubBlob._pos); - if (e === undefined) - return new Error('Malformed PPK public key'); - const n = readString(pubBlob, pubBlob._pos); - if (n === undefined) - return new Error('Malformed PPK public key'); - const d = readString(privBlob, 0); - if (d === undefined) - return new Error('Malformed PPK private key'); - const p = readString(privBlob, privBlob._pos); - if (p === undefined) - return new Error('Malformed PPK private key'); - const q = readString(privBlob, privBlob._pos); - if (q === undefined) - return new Error('Malformed PPK private key'); - const iqmp = readString(privBlob, privBlob._pos); - if (iqmp === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - break; - } - case 'ssh-dss': { - const p = readString(pubBlob, pubBlob._pos); - if (p === undefined) - return new Error('Malformed PPK public key'); - const q = readString(pubBlob, pubBlob._pos); - if (q === undefined) - return new Error('Malformed PPK public key'); - const g = readString(pubBlob, pubBlob._pos); - if (g === undefined) - return new Error('Malformed PPK public key'); - const y = readString(pubBlob, pubBlob._pos); - if (y === undefined) - return new Error('Malformed PPK public key'); - const x = readString(privBlob, 0); - if (x === undefined) - return new Error('Malformed PPK private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - break; - } +exports.StorageVectorsApiError = StorageVectorsApiError; +/** + * Unknown error that doesn't match expected error patterns + * Wraps the original error for debugging + */ +class StorageVectorsUnknownError extends StorageVectorsError { + constructor(message, originalError) { + super(message); + this.name = 'StorageVectorsUnknownError'; + this.originalError = originalError; } - - return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', - encrypted); - }; -} - - -function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -OpenSSH_Public.prototype = BaseKey; -{ - let regexp; - if (eddsaSupported) - regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - else - regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - OpenSSH_Public.parse = (str) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = full type - // m[2] = base type - // m[3] = base64-encoded public key - // m[4] = comment - - const fullType = m[1]; - const baseType = m[2]; - const data = Buffer.from(m[3], 'base64'); - const comment = (m[4] || ''); - - const type = readString(data, data._pos, true); - if (type === undefined || type.indexOf(baseType) !== 0) - return new Error('Malformed OpenSSH public key'); - - return parseDER(data, baseType, comment, fullType); - }; -} - - -function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; } -RFC4716_Public.prototype = BaseKey; -{ - const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; - const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; - const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; - const RE_HEADER_ENDS = /\\\r?\n/g; - RFC4716_Public.parse = (str) => { - let m = regexp.exec(str); - if (m === null) - return null; +exports.StorageVectorsUnknownError = StorageVectorsUnknownError; +/** + * Error codes specific to S3 Vectors API + * Maps AWS service errors to application-friendly error codes + */ +var StorageVectorsErrorCode; +(function (StorageVectorsErrorCode) { + /** Internal server fault (HTTP 500) */ + StorageVectorsErrorCode["InternalError"] = "InternalError"; + /** Resource already exists / conflict (HTTP 409) */ + StorageVectorsErrorCode["S3VectorConflictException"] = "S3VectorConflictException"; + /** Resource not found (HTTP 404) */ + StorageVectorsErrorCode["S3VectorNotFoundException"] = "S3VectorNotFoundException"; + /** Delete bucket while not empty (HTTP 400) */ + StorageVectorsErrorCode["S3VectorBucketNotEmpty"] = "S3VectorBucketNotEmpty"; + /** Exceeds bucket quota/limit (HTTP 400) */ + StorageVectorsErrorCode["S3VectorMaxBucketsExceeded"] = "S3VectorMaxBucketsExceeded"; + /** Exceeds index quota/limit (HTTP 400) */ + StorageVectorsErrorCode["S3VectorMaxIndexesExceeded"] = "S3VectorMaxIndexesExceeded"; +})(StorageVectorsErrorCode || (exports.StorageVectorsErrorCode = StorageVectorsErrorCode = {})); +//# sourceMappingURL=errors.js.map - const body = m[1]; - let dataStart = 0; - let comment = ''; +/***/ }), - while (m = RE_HEADER.exec(body)) { - const headerName = m[1]; - const headerValue = m[2].replace(RE_HEADER_ENDS, ''); - if (headerValue.length > 1024) { - RE_HEADER.lastIndex = 0; - return new Error('Malformed RFC4716 public key'); - } +/***/ 2593: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - dataStart = RE_HEADER.lastIndex; +"use strict"; - if (headerName.toLowerCase() === 'comment') { - comment = headerValue; - if (comment.length > 1 - && comment.charCodeAt(0) === 34/* '"' */ - && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { - comment = comment.slice(1, -1); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.get = get; +exports.post = post; +exports.put = put; +exports.remove = remove; +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(3071); +const helpers_1 = __nccwpck_require__(1176); +/** + * Extracts error message from various error response formats + * @param err - Error object from API + * @returns Human-readable error message + */ +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +/** + * Handles fetch errors and converts them to StorageVectors error types + * @param error - The error caught from fetch + * @param reject - Promise rejection function + * @param options - Fetch options that may affect error handling + */ +const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + // Check if error is a Response-like object (has status and ok properties) + // This is more reliable than instanceof which can fail across realms + const isResponseLike = error && + typeof error === 'object' && + 'status' in error && + 'ok' in error && + typeof error.status === 'number'; + if (isResponseLike && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + const status = error.status || 500; + const responseError = error; + // Try to parse JSON body if available + if (typeof responseError.json === 'function') { + responseError + .json() + .then((err) => { + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || (err === null || err === void 0 ? void 0 : err.code) || status + ''; + reject(new errors_1.StorageVectorsApiError(_getErrorMessage(err), status, statusCode)); + }) + .catch(() => { + // If JSON parsing fails, create an ApiError with the HTTP status code + const statusCode = status + ''; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); + }); + } + else { + // No json() method available, create error from status + const statusCode = status + ''; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); } - } - } - - let data = body.slice(dataStart); - if (!RE_DATA.test(data)) - return new Error('Malformed RFC4716 public key'); - - data = Buffer.from(data, 'base64'); - - const type = readString(data, 0, true); - if (type === undefined) - return new Error('Malformed RFC4716 public key'); - - let pubPEM = null; - let pubSSH = null; - switch (type) { - case 'ssh-rsa': { - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed RFC4716 public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed RFC4716 public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed RFC4716 public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed RFC4716 public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - break; - } - default: - return new Error('Malformed RFC4716 public key'); } - - return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); - }; -} - - -function parseDER(data, baseType, comment, fullType) { - if (!isSupportedKeyType(baseType)) - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - - let algo; - let oid; - let pubPEM = null; - let pubSSH = null; - - switch (baseType) { - case 'ssh-rsa': { - const e = readString(data, data._pos || 0); - if (e === undefined) - return new Error('Malformed OpenSSH public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - algo = 'sha1'; - break; + else { + reject(new errors_1.StorageVectorsUnknownError(_getErrorMessage(error), error)); } - case 'ssh-dss': { - const p = readString(data, data._pos || 0); - if (p === undefined) - return new Error('Malformed OpenSSH public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - algo = 'sha1'; - break; +}); +/** + * Builds request parameters for fetch calls + * @param method - HTTP method + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters like AbortSignal + * @param body - Request body (will be JSON stringified if plain object) + * @returns Complete fetch request parameters + */ +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET' || !body) { + return params; } - case 'ssh-ed25519': { - const edpub = readString(data, data._pos || 0); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - algo = null; - break; + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH public key'); - const ecpub = readString(data, data._pos || 0); - if (ecpub === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - break; + else { + params.body = body; } - default: - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - } - - return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); + return Object.assign(Object.assign({}, params), parameters); +}; +/** + * Internal request handler that wraps fetch with error handling + * @param fetcher - Fetch function to use + * @param method - HTTP method + * @param url - Request URL + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @param body - Request body + * @returns Promise with parsed response or error + */ +function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)) + .then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + // Handle empty responses (204, empty body) + const contentType = result.headers.get('content-type'); + if (!contentType || !contentType.includes('application/json')) { + return {}; + } + return result.json(); + }) + .then((data) => resolve(data)) + .catch((error) => handleError(error, reject, options)); + }); + }); } - -function isSupportedKeyType(type) { - switch (type) { - case 'ssh-rsa': - case 'ssh-dss': - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': - return true; - case 'ssh-ed25519': - if (eddsaSupported) - return true; - // FALLTHROUGH - default: - return false; - } +/** + * Performs a GET request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function get(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'GET', url, options, parameters); + }); } - -function isParsedKey(val) { - if (!val) - return false; - return (typeof val[SYM_DECRYPTED] === 'boolean'); +/** + * Performs a POST request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param body - Request body to be JSON stringified + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'POST', url, options, parameters, body); + }); } - -function parseKey(data, passphrase) { - if (isParsedKey(data)) - return data; - - let origBuffer; - if (Buffer.isBuffer(data)) { - origBuffer = data; - data = data.utf8Slice(0, data.length).trim(); - } else if (typeof data === 'string') { - data = data.trim(); - } else { - return new Error('Key data must be a Buffer or string'); - } - - // eslint-disable-next-line eqeqeq - if (passphrase != undefined) { - if (typeof passphrase === 'string') - passphrase = Buffer.from(passphrase); - else if (!Buffer.isBuffer(passphrase)) - return new Error('Passphrase must be a string or Buffer when supplied'); - } - - let ret; - - // First try as printable string format (e.g. PEM) - - // Private keys - if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = PPK_Private.parse(data, passphrase)) !== null) - return ret; - - // Public keys - if ((ret = OpenSSH_Public.parse(data)) !== null) - return ret; - if ((ret = RFC4716_Public.parse(data)) !== null) - return ret; - - // Finally try as a binary format if we were originally passed binary data - if (origBuffer) { - binaryKeyParser.init(origBuffer, 0); - const type = binaryKeyParser.readString(true); - if (type !== undefined) { - data = binaryKeyParser.readRaw(); - if (data !== undefined) { - ret = parseDER(data, type, '', type); - // Ignore potentially useless errors in case the data was not actually - // in the binary format - if (ret instanceof Error) - ret = null; - } - } - binaryKeyParser.clear(); - } - - if (ret) - return ret; - - return new Error('Unsupported key format'); +/** + * Performs a PUT request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param body - Request body to be JSON stringified + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'PUT', url, options, parameters, body); + }); } - -module.exports = { - isParsedKey, - isSupportedKeyType, - parseDERKey: (data, type) => parseDER(data, type, '', type), - parseKey, -}; - +/** + * Performs a DELETE request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param body - Request body to be JSON stringified + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function remove(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); + }); +} +//# sourceMappingURL=fetch.js.map /***/ }), -/***/ 47609: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1176: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -const assert = __nccwpck_require__(39491); -const { inspect } = __nccwpck_require__(73837); - -// Only use this for integers! Decimal numbers do not work with this function. -function addNumericalSeparator(val) { - let res = ''; - let i = val.length; - const start = val[0] === '-' ? 1 : 0; - for (; i >= start + 4; i -= 3) - res = `_${val.slice(i - 3, i)}${res}`; - return `${val.slice(0, i)}${res}`; -} - -function oneOf(expected, thing) { - assert(typeof thing === 'string', '`thing` has to be of type string'); - if (Array.isArray(expected)) { - const len = expected.length; - assert(len > 0, 'At least one expected value needs to be specified'); - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` - + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = void 0; +/** + * Resolves the fetch implementation to use + * Uses custom fetch if provided, otherwise uses native fetch + * + * @param customFetch - Optional custom fetch implementation + * @returns Resolved fetch function + */ +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); } - return `of ${thing} ${expected[0]}`; - } - return `of ${thing} ${String(expected)}`; -} - - -exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { - constructor(message) { - super(); - Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); - - const suffix = 'This is caused by either a bug in ssh2 ' - + 'or incorrect usage of ssh2 internals.\n' - + 'Please open an issue with this stack trace at ' - + 'https://github.com/mscdex/ssh2/issues\n'; - - this.message = (message === undefined ? suffix : `${message}\n${suffix}`); - } + return (...args) => fetch(...args); }; - -const MAX_32BIT_INT = 2 ** 32; -const MAX_32BIT_BIGINT = (() => { - try { - return new Function('return 2n ** 32n')(); - } catch {} -})(); -exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { - constructor(str, range, input, replaceDefaultBoolean) { - super(); - Error.captureStackTrace(this, ERR_OUT_OF_RANGE); - - assert(range, 'Missing "range" argument'); - let msg = (replaceDefaultBoolean - ? str - : `The value of "${str}" is out of range.`); - let received; - if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === 'bigint') { - received = String(input); - if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) - received = addNumericalSeparator(received); - received += 'n'; - } else { - received = inspect(input); +exports.resolveFetch = resolveFetch; +/** + * Resolves the Response constructor to use + * Returns native Response constructor + * + * @returns Response constructor + */ +const resolveResponse = () => { + return Response; +}; +exports.resolveResponse = resolveResponse; +/** + * Determine if input is a plain object + * An object is plain if it's created by either {}, new Object(), or Object.create(null) + * + * @param value - Value to check + * @returns True if value is a plain object + * @source https://github.com/sindresorhus/is-plain-obj + */ +const isPlainObject = (value) => { + if (typeof value !== 'object' || value === null) { + return false; } - msg += ` It must be ${range}. Received ${received}`; - - this.message = msg; - } + const prototype = Object.getPrototypeOf(value); + return ((prototype === null || + prototype === Object.prototype || + Object.getPrototypeOf(prototype) === null) && + !(Symbol.toStringTag in value) && + !(Symbol.iterator in value)); +}; +exports.isPlainObject = isPlainObject; +/** + * Normalizes a number array to float32 format + * Ensures all vector values are valid 32-bit floats + * + * @param values - Array of numbers to normalize + * @returns Normalized float32 array + */ +const normalizeToFloat32 = (values) => { + // Use Float32Array to ensure proper precision + return Array.from(new Float32Array(values)); }; - -class ERR_INVALID_ARG_TYPE extends TypeError { - constructor(name, expected, actual) { - super(); - Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); - - assert(typeof name === 'string', `'name' must be a string`); - - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && expected.startsWith('not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (name.endsWith(' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = (name.includes('.') ? 'property' : 'argument'); - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; +exports.normalizeToFloat32 = normalizeToFloat32; +/** + * Validates vector dimensions match expected dimension + * Throws error if dimensions don't match + * + * @param vector - Vector data to validate + * @param expectedDimension - Expected vector dimension + * @throws Error if dimensions don't match + */ +const validateVectorDimension = (vector, expectedDimension) => { + if (expectedDimension !== undefined && vector.float32.length !== expectedDimension) { + throw new Error(`Vector dimension mismatch: expected ${expectedDimension}, got ${vector.float32.length}`); } - - msg += `. Received type ${typeof actual}`; - - this.message = msg; - } -} -exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; - -exports.validateNumber = function validateNumber(value, name) { - if (typeof value !== 'number') - throw new ERR_INVALID_ARG_TYPE(name, 'number', value); }; - +exports.validateVectorDimension = validateVectorDimension; +//# sourceMappingURL=helpers.js.map /***/ }), -/***/ 49475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9380: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = exports.isStorageVectorsError = exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = exports.VectorDataApi = exports.VectorIndexApi = exports.VectorBucketApi = exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +// Main client +var StorageVectorsClient_1 = __nccwpck_require__(9403); +Object.defineProperty(exports, "StorageVectorsClient", ({ enumerable: true, get: function () { return StorageVectorsClient_1.StorageVectorsClient; } })); +Object.defineProperty(exports, "VectorBucketScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorBucketScope; } })); +Object.defineProperty(exports, "VectorIndexScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorIndexScope; } })); +// API classes (for advanced usage) +var VectorBucketApi_1 = __nccwpck_require__(4268); +Object.defineProperty(exports, "VectorBucketApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorBucketApi_1).default; } })); +var VectorIndexApi_1 = __nccwpck_require__(9623); +Object.defineProperty(exports, "VectorIndexApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorIndexApi_1).default; } })); +var VectorDataApi_1 = __nccwpck_require__(3073); +Object.defineProperty(exports, "VectorDataApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorDataApi_1).default; } })); +// Errors +var errors_1 = __nccwpck_require__(3071); +Object.defineProperty(exports, "StorageVectorsError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsError; } })); +Object.defineProperty(exports, "StorageVectorsApiError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsApiError; } })); +Object.defineProperty(exports, "StorageVectorsUnknownError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsUnknownError; } })); +Object.defineProperty(exports, "StorageVectorsErrorCode", ({ enumerable: true, get: function () { return errors_1.StorageVectorsErrorCode; } })); +Object.defineProperty(exports, "isStorageVectorsError", ({ enumerable: true, get: function () { return errors_1.isStorageVectorsError; } })); +// Helper utilities +var helpers_1 = __nccwpck_require__(1176); +Object.defineProperty(exports, "resolveFetch", ({ enumerable: true, get: function () { return helpers_1.resolveFetch; } })); +Object.defineProperty(exports, "resolveResponse", ({ enumerable: true, get: function () { return helpers_1.resolveResponse; } })); +Object.defineProperty(exports, "isPlainObject", ({ enumerable: true, get: function () { return helpers_1.isPlainObject; } })); +Object.defineProperty(exports, "normalizeToFloat32", ({ enumerable: true, get: function () { return helpers_1.normalizeToFloat32; } })); +Object.defineProperty(exports, "validateVectorDimension", ({ enumerable: true, get: function () { return helpers_1.validateVectorDimension; } })); +//# sourceMappingURL=index.js.map -const Ber = (__nccwpck_require__(80970).Ber); - -let DISCONNECT_REASON; - -const FastBuffer = Buffer[Symbol.species]; -const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; - -function readUInt32BE(buf, offset) { - return (buf[offset++] * 16777216) - + (buf[offset++] * 65536) - + (buf[offset++] * 256) - + buf[offset]; -} - -function bufferCopy(src, dest, srcStart, srcEnd, destStart) { - if (!destStart) - destStart = 0; - if (srcEnd > src.length) - srcEnd = src.length; - let nb = srcEnd - srcStart; - const destLeft = (dest.length - destStart); - if (nb > destLeft) - nb = destLeft; - dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), - destStart); - return nb; -} - -function bufferSlice(buf, start, end) { - if (end === undefined) - end = buf.length; - return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); -} - -function makeBufferParser() { - let pos = 0; - let buffer; - - const self = { - init: (buf, start) => { - buffer = buf; - pos = (typeof start === 'number' ? start : 0); - }, - pos: () => pos, - length: () => (buffer ? buffer.length : 0), - avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), - clear: () => { - buffer = undefined; - }, - readUInt32BE: () => { - if (!buffer || pos + 3 >= buffer.length) - return; - return (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - }, - readUInt64BE: (behavior) => { - if (!buffer || pos + 7 >= buffer.length) - return; - switch (behavior) { - case 'always': - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - case 'maybe': - if (buffer[pos] > 0x1F) - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - // FALLTHROUGH - default: - return (buffer[pos++] * 72057594037927940) - + (buffer[pos++] * 281474976710656) - + (buffer[pos++] * 1099511627776) - + (buffer[pos++] * 4294967296) - + (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - } - }, - skip: (n) => { - if (buffer && n > 0) - pos += n; - }, - skipString: () => { - const len = self.readUInt32BE(); - if (len === undefined) - return; - pos += len; - return (pos <= buffer.length ? len : undefined); - }, - readByte: () => { - if (buffer && pos < buffer.length) - return buffer[pos++]; - }, - readBool: () => { - if (buffer && pos < buffer.length) - return !!buffer[pos++]; - }, - readList: () => { - const list = self.readString(true); - if (list === undefined) - return; - return (list ? list.split(',') : []); - }, - readString: (dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } - - const len = self.readUInt32BE(); - if (len === undefined) - return; +/***/ }), - if ((buffer.length - pos) < len - || (typeof maxLen === 'number' && len > maxLen)) { - return; - } +/***/ 4499: +/***/ ((__unused_webpack_module, exports) => { - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, pos, pos += len); - return buffer.utf8Slice(pos, pos += len); - } - return bufferSlice(buffer, pos, pos += len); - }, - readRaw: (len) => { - if (!buffer) - return; - if (typeof len !== 'number') - return bufferSlice(buffer, pos, pos += (buffer.length - pos)); - if ((buffer.length - pos) >= len) - return bufferSlice(buffer, pos, pos += len); - }, - }; +"use strict"; - return self; -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map -function makeError(msg, level, fatal) { - const err = new Error(msg); - if (typeof level === 'boolean') { - fatal = level; - err.level = 'protocol'; - } else { - err.level = level || 'protocol'; - } - err.fatal = !!fatal; - return err; -} +/***/ }), -function writeUInt32BE(buf, value, offset) { - buf[offset++] = (value >>> 24); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 8); - buf[offset++] = value; - return offset; -} +/***/ 8475: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const utilBufferParser = makeBufferParser(); +"use strict"; -module.exports = { - bufferCopy, - bufferSlice, - FastBuffer, - bufferFill: (buf, value, start, end) => { - return TypedArrayFill.call(buf, value, start, end); - }, - makeError, - doFatalError: (protocol, msg, level, reason) => { - let err; - if (DISCONNECT_REASON === undefined) - ({ DISCONNECT_REASON } = __nccwpck_require__(36832)); - if (msg instanceof Error) { - // doFatalError(protocol, err[, reason]) - err = msg; - if (typeof level !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - else - reason = level; - } else { - // doFatalError(protocol, msg[, level[, reason]]) - err = makeError(msg, level, true); - } - if (typeof reason !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - protocol.disconnect(reason); - protocol._destruct(); - protocol._onError(err); - return Infinity; - }, - readUInt32BE, - writeUInt32BE, - writeUInt32LE: (buf, value, offset) => { - buf[offset++] = value; - buf[offset++] = (value >>> 8); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 24); - return offset; - }, - makeBufferParser, - bufferParser: makeBufferParser(), - readString: (buffer, start, dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(2758); +const StreamDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(7023)); +class BlobDownloadBuilder { + constructor(downloadFn, shouldThrowOnError) { + this.downloadFn = downloadFn; + this.shouldThrowOnError = shouldThrowOnError; + this[_a] = 'BlobDownloadBuilder'; + this.promise = null; } - - if (start === undefined) - start = 0; - - const left = (buffer.length - start); - if (start < 0 || start >= buffer.length || left < 4) - return; - - const len = readUInt32BE(buffer, start); - if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) - return; - - start += 4; - const end = start + len; - buffer._pos = end; - - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, start, end); - return buffer.utf8Slice(start, end); + asStream() { + return new StreamDownloadBuilder_1.default(this.downloadFn, this.shouldThrowOnError); } - return bufferSlice(buffer, start, end); - }, - sigSSHToASN1: (sig, type) => { - switch (type) { - case 'ssh-dss': { - if (sig.length > 40) - return sig; - // Change bare signature r and s values to ASN.1 BER values for OpenSSL - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - let r = sig.slice(0, 20); - let s = sig.slice(20); - if (r[0] & 0x80) { - const rNew = Buffer.allocUnsafe(21); - rNew[0] = 0x00; - r.copy(rNew, 1); - r = rNew; - } else if (r[0] === 0x00 && !(r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] & 0x80) { - const sNew = Buffer.allocUnsafe(21); - sNew[0] = 0x00; - s.copy(sNew, 1); - s = sNew; - } else if (s[0] === 0x00 && !(s[1] & 0x80)) { - s = s.slice(1); - } - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - utilBufferParser.init(sig, 0); - const r = utilBufferParser.readString(); - const s = utilBufferParser.readString(); - utilBufferParser.clear(); - if (r === undefined || s === undefined) - return; - - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - default: - return sig; + then(onfulfilled, onrejected) { + return this.getPromise().then(onfulfilled, onrejected); } - }, - convertSignature: (signature, keyType) => { - switch (keyType) { - case 'ssh-dss': { - if (signature.length <= 40) - return signature; - // This is a quick and dirty way to get from BER encoded r and s that - // OpenSSL gives us, to just the bare values back to back (40 bytes - // total) like OpenSSH (and possibly others) are expecting - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - let r = asnReader.readString(Ber.Integer, true); - let s = asnReader.readString(Ber.Integer, true); - let rOffset = 0; - let sOffset = 0; - if (r.length < 20) { - const rNew = Buffer.allocUnsafe(20); - rNew.set(r, 1); - r = rNew; - r[0] = 0; - } - if (s.length < 20) { - const sNew = Buffer.allocUnsafe(20); - sNew.set(s, 1); - s = sNew; - s[0] = 0; - } - if (r.length > 20 && r[0] === 0) - rOffset = 1; - if (s.length > 20 && s[0] === 0) - sOffset = 1; - const newSig = - Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); - bufferCopy(r, newSig, rOffset, r.length, 0); - bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); - return newSig; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - if (signature[0] === 0) - return signature; - // Convert SSH signature parameters to ASN.1 BER values for OpenSSL - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - const r = asnReader.readString(Ber.Integer, true); - const s = asnReader.readString(Ber.Integer, true); - if (r === null || s === null) - return; - const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); - writeUInt32BE(newSig, r.length, 0); - newSig.set(r, 4); - writeUInt32BE(newSig, s.length, 4 + r.length); - newSig.set(s, 4 + 4 + r.length); - return newSig; - } + catch(onrejected) { + return this.getPromise().catch(onrejected); } - - return signature; - }, - sendPacket: (proto, packet, bypass) => { - if (!bypass && proto._kexinit !== undefined) { - // We're currently in the middle of a handshake - - if (proto._queue === undefined) - proto._queue = []; - proto._queue.push(packet); - proto._debug && proto._debug('Outbound: ... packet queued'); - return false; + finally(onfinally) { + return this.getPromise().finally(onfinally); } - proto._cipher.encrypt(packet); - return true; - }, -}; - + getPromise() { + if (!this.promise) { + this.promise = this.execute(); + } + return this.promise; + } + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: yield result.blob(), + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } +} +_a = Symbol.toStringTag; +exports["default"] = BlobDownloadBuilder; +//# sourceMappingURL=BlobDownloadBuilder.js.map /***/ }), -/***/ 26715: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7339: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const { kMaxLength } = __nccwpck_require__(14300); -const { - createInflate, - constants: { - DEFLATE, - INFLATE, - Z_DEFAULT_CHUNK, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_MEMLEVEL, - Z_DEFAULT_STRATEGY, - Z_DEFAULT_WINDOWBITS, - Z_PARTIAL_FLUSH, - } -} = __nccwpck_require__(59796); -const ZlibHandle = createInflate()._handle.constructor; - -function processCallback() { - throw new Error('Should not get here'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(9754); +const errors_1 = __nccwpck_require__(2758); +const fetch_1 = __nccwpck_require__(3146); +const helpers_1 = __nccwpck_require__(5430); +/** + * API class for managing Analytics Buckets using Iceberg tables + * Provides methods for creating, listing, and deleting analytics buckets + */ +class StorageAnalyticsApi { + /** + * Creates a new StorageAnalyticsApi instance + * @param url - The base URL for the storage API + * @param headers - HTTP headers to include in requests + * @param fetch - Optional custom fetch implementation + */ + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Creates a new analytics bucket using Iceberg tables + * Analytics buckets are optimized for analytical queries and data processing + * + * @param name A unique name for the bucket you are creating + * @returns Promise with newly created bucket name or error + * + * @example + * ```typescript + * const { data, error } = await storage.analytics.createBucket('analytics-data') + * if (error) { + * console.error('Failed to create analytics bucket:', error.message) + * } else { + * console.log('Created bucket:', data.name) + * } + * ``` + */ + createBucket(name) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { name }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of all Analytics Storage buckets within an existing project + * Only returns buckets of type 'ANALYTICS' + * + * @param options Query parameters for listing buckets + * @param options.limit Maximum number of buckets to return + * @param options.offset Number of buckets to skip + * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at') + * @param options.sortOrder Sort order ('asc' or 'desc') + * @param options.search Search term to filter bucket names + * @returns Promise with list of analytics buckets or error + * + * @example + * ```typescript + * const { data, error } = await storage.analytics.listBuckets({ + * limit: 10, + * offset: 0, + * sortColumn: 'created_at', + * sortOrder: 'desc', + * search: 'analytics' + * }) + * if (data) { + * console.log('Found analytics buckets:', data.length) + * data.forEach(bucket => console.log(`- ${bucket.name}`)) + * } + * ``` + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Build query string from options + const queryParams = new URLSearchParams(); + if ((options === null || options === void 0 ? void 0 : options.limit) !== undefined) + queryParams.set('limit', options.limit.toString()); + if ((options === null || options === void 0 ? void 0 : options.offset) !== undefined) + queryParams.set('offset', options.offset.toString()); + if (options === null || options === void 0 ? void 0 : options.sortColumn) + queryParams.set('sortColumn', options.sortColumn); + if (options === null || options === void 0 ? void 0 : options.sortOrder) + queryParams.set('sortOrder', options.sortOrder); + if (options === null || options === void 0 ? void 0 : options.search) + queryParams.set('search', options.search); + const queryString = queryParams.toString(); + const url = queryString ? `${this.url}/bucket?${queryString}` : `${this.url}/bucket`; + const data = yield (0, fetch_1.get)(this.fetch, url, { headers: this.headers }); + return { data: data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing analytics bucket + * A bucket can't be deleted with existing objects inside it + * You must first empty the bucket before deletion + * + * @param bucketId The unique identifier of the bucket you would like to delete + * @returns Promise with success message or error + * + * @example + * ```typescript + * const { data, error } = await analyticsApi.deleteBucket('old-analytics-bucket') + * if (error) { + * console.error('Failed to delete bucket:', error.message) + * } else { + * console.log('Bucket deleted successfully:', data.message) + * } + * ``` + */ + deleteBucket(bucketId) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${bucketId}`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } } +exports["default"] = StorageAnalyticsApi; +//# sourceMappingURL=StorageAnalyticsApi.js.map -function zlibOnError(message, errno, code) { - const self = this._owner; - // There is no way to cleanly recover. - // Continuing only obscures problems. - - const error = new Error(message); - error.errno = errno; - error.code = code; - self._err = error; -} +/***/ }), -function _close(engine) { - // Caller may invoke .close after a zlib error (which will null _handle). - if (!engine._handle) - return; +/***/ 3528: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - engine._handle.close(); - engine._handle = null; -} - -class Zlib { - constructor(mode) { - const windowBits = Z_DEFAULT_WINDOWBITS; - const level = Z_DEFAULT_COMPRESSION; - const memLevel = Z_DEFAULT_MEMLEVEL; - const strategy = Z_DEFAULT_STRATEGY; - const dictionary = undefined; - - this._err = undefined; - this._writeState = new Uint32Array(2); - this._chunkSize = Z_DEFAULT_CHUNK; - this._maxOutputLength = kMaxLength; - this._outBuffer = Buffer.allocUnsafe(this._chunkSize); - this._outOffset = 0; - - this._handle = new ZlibHandle(mode); - this._handle._owner = this; - this._handle.onerror = zlibOnError; - this._handle.init(windowBits, - level, - memLevel, - strategy, - this._writeState, - processCallback, - dictionary); - } - - writeSync(chunk, retChunks) { - const handle = this._handle; - if (!handle) - throw new Error('Invalid Zlib instance'); - - let availInBefore = chunk.length; - let availOutBefore = this._chunkSize - this._outOffset; - let inOff = 0; - let availOutAfter; - let availInAfter; - - let buffers; - let nread = 0; - const state = this._writeState; - let buffer = this._outBuffer; - let offset = this._outOffset; - const chunkSize = this._chunkSize; +"use strict"; - while (true) { - handle.writeSync(Z_PARTIAL_FLUSH, - chunk, // in - inOff, // in_off - availInBefore, // in_len - buffer, // out - offset, // out_off - availOutBefore); // out_len - if (this._err) - throw this._err; - - availOutAfter = state[0]; - availInAfter = state[1]; - - const inDelta = availInBefore - availInAfter; - const have = availOutBefore - availOutAfter; - - if (have > 0) { - const out = (offset === 0 && have === buffer.length - ? buffer - : buffer.slice(offset, offset + have)); - offset += have; - if (!buffers) - buffers = out; - else if (buffers.push === undefined) - buffers = [buffers, out]; - else - buffers.push(out); - nread += out.byteLength; - - if (nread > this._maxOutputLength) { - _close(this); - throw new Error( - `Output length exceeded maximum of ${this._maxOutputLength}` - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(9754); +const errors_1 = __nccwpck_require__(2758); +const fetch_1 = __nccwpck_require__(3146); +const helpers_1 = __nccwpck_require__(5430); +class StorageBucketApi { + constructor(url, headers = {}, fetch, opts) { + this.shouldThrowOnError = false; + const baseUrl = new URL(url); + // if legacy uri is used, replace with new storage host (disables request buffering to allow > 50GB uploads) + // "project-ref.supabase.co" becomes "project-ref.storage.supabase.co" + if (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) { + const isSupabaseHost = /supabase\.(co|in|red)$/.test(baseUrl.hostname); + if (isSupabaseHost && !baseUrl.hostname.includes('storage.supabase.')) { + baseUrl.hostname = baseUrl.hostname.replace('supabase.', 'storage.supabase.'); + } } - } else if (have !== 0) { - throw new Error('have should not go down'); - } - - // Exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || offset >= chunkSize) { - availOutBefore = chunkSize; - offset = 0; - buffer = Buffer.allocUnsafe(chunkSize); - } - - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += inDelta; - availInBefore = availInAfter; - } else { - break; - } + this.url = baseUrl.href.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Enable throwing errors instead of returning them. + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const queryString = this.listBucketOptionsToQueryString(options); + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket${queryString}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + getBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details. + * - default bucket type is `STANDARD` + */ + createBucket(id_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (id, options = { + public: false, + }) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { + id, + name: id, + type: options.type, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + updateBucket(id, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - this._outBuffer = buffer; - this._outOffset = offset; - - if (nread === 0) - buffers = Buffer.alloc(0); - - if (retChunks) { - buffers.totalLen = nread; - return buffers; + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + emptyBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - if (buffers.push === undefined) - return buffers; - - const output = Buffer.allocUnsafe(nread); - for (let i = 0, p = 0; i < buffers.length; ++i) { - const buf = buffers[i]; - output.set(buf, p); - p += buf.length; + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + deleteBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - return output; - } -} - -class ZlibPacketWriter { - constructor(protocol) { - this.allocStart = 0; - this.allocStartKEX = 0; - this._protocol = protocol; - this._zlib = new Zlib(DEFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - alloc(payloadSize, force) { - return Buffer.allocUnsafe(payloadSize); - } - - finalize(payload, force) { - if (this._protocol._kexinit === undefined || force) { - const output = this._zlib.writeSync(payload, true); - const packet = this._protocol._cipher.allocPacket(output.totalLen); - if (output.push === undefined) { - packet.set(output, 5); - } else { - for (let i = 0, p = 5; i < output.length; ++i) { - const chunk = output[i]; - packet.set(chunk, p); - p += chunk.length; + listBucketOptionsToQueryString(options) { + const params = {}; + if (options) { + if ('limit' in options) { + params.limit = String(options.limit); + } + if ('offset' in options) { + params.offset = String(options.offset); + } + if (options.search) { + params.search = options.search; + } + if (options.sortColumn) { + params.sortColumn = options.sortColumn; + } + if (options.sortOrder) { + params.sortOrder = options.sortOrder; + } } - } - return packet; + return Object.keys(params).length > 0 ? '?' + new URLSearchParams(params).toString() : ''; } - return payload; - } -} - -class PacketWriter { - constructor(protocol) { - this.allocStart = 5; - this.allocStartKEX = 5; - this._protocol = protocol; - } - - cleanup() {} - - alloc(payloadSize, force) { - if (this._protocol._kexinit === undefined || force) - return this._protocol._cipher.allocPacket(payloadSize); - return Buffer.allocUnsafe(payloadSize); - } - - finalize(packet, force) { - return packet; - } -} - -class ZlibPacketReader { - constructor() { - this._zlib = new Zlib(INFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - read(data) { - return this._zlib.writeSync(data, false); - } -} - -class PacketReader { - cleanup() {} - - read(data) { - return data; - } } - -module.exports = { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -}; - +exports["default"] = StorageBucketApi; +//# sourceMappingURL=StorageBucketApi.js.map /***/ }), -/***/ 12986: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 710: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// TODO: -// * convert listenerCount() usage to emit() return value checking? -// * emit error when connection severed early (e.g. before handshake) -// * add '.connected' or similar property to connection objects to allow -// immediate connection status checking - - -const { Server: netServer } = __nccwpck_require__(41808); -const EventEmitter = __nccwpck_require__(82361); -const { listenerCount } = EventEmitter; - -const { - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(36832); -const { init: cryptoInit } = __nccwpck_require__(45708); -const { KexInit } = __nccwpck_require__(64126); -const { parseKey } = __nccwpck_require__(22218); -const Protocol = __nccwpck_require__(59031); -const { SFTP } = __nccwpck_require__(52026); -const { writeUInt32BE } = __nccwpck_require__(49475); - -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(83204); - -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(40834); - -const MAX_PENDING_AUTHS = 10; - -class AuthContext extends EventEmitter { - constructor(protocol, username, service, method, cb) { - super(); - - this.username = this.user = username; - this.service = service; - this.method = method; - this._initialResponse = false; - this._finalResponse = false; - this._multistep = false; - this._cbfinal = (allowed, methodsLeft, isPartial) => { - if (!this._finalResponse) { - this._finalResponse = true; - cb(this, allowed, methodsLeft, isPartial); - } - }; - this._protocol = protocol; - } - - accept() { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(true); - } - reject(methodsLeft, isPartial) { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(false, methodsLeft, isPartial); - } -} - - -class KeyboardAuthContext extends AuthContext { - constructor(protocol, username, service, method, submethods, cb) { - super(protocol, username, service, method, cb); - this._multistep = true; - - this._cb = undefined; - this._onInfoResponse = (responses) => { - const callback = this._cb; - if (callback) { - this._cb = undefined; - callback(responses); - } - }; - this.submethods = submethods; - this.on('abort', () => { - this._cb && this._cb(new Error('Authentication request aborted')); - }); - } - - prompt(prompts, title, instructions, cb) { - if (!Array.isArray(prompts)) - prompts = [ prompts ]; - - if (typeof title === 'function') { - cb = title; - title = instructions = undefined; - } else if (typeof instructions === 'function') { - cb = instructions; - instructions = undefined; - } else if (typeof cb !== 'function') { - cb = undefined; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(2758); +const fetch_1 = __nccwpck_require__(3146); +const helpers_1 = __nccwpck_require__(5430); +const BlobDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(8475)); +const DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: 'name', + order: 'asc', + }, +}; +const DEFAULT_FILE_OPTIONS = { + cacheControl: '3600', + contentType: 'text/plain;charset=UTF-8', + upsert: false, +}; +class StorageFileApi { + constructor(url, headers = {}, bucketId, fetch) { + this.shouldThrowOnError = false; + this.url = url; + this.headers = headers; + this.bucketId = bucketId; + this.fetch = (0, helpers_1.resolveFetch)(fetch); } - - for (let i = 0; i < prompts.length; ++i) { - if (typeof prompts[i] === 'string') { - prompts[i] = { - prompt: prompts[i], - echo: true - }; - } + /** + * Enable throwing errors instead of returning them. + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; } - - this._cb = cb; - this._initialResponse = true; - - this._protocol.authInfoReq(title, instructions, prompts); - } -} - -class PKAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.hashAlgo = pkInfo.hashAlgo; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - } - - accept() { - if (!this.signature) { - this._initialResponse = true; - this._protocol.authPKOK(this.key.algo, this.key.data); - } else { - AuthContext.prototype.accept.call(this); + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadOrUpdate(method, path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let body; + const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); + let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); + const metadata = options.metadata; + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + if (metadata) { + body.append('metadata', this.encodeMetadata(metadata)); + } + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + // Only append if not already present + if (!body.has('cacheControl')) { + body.append('cacheControl', options.cacheControl); + } + if (metadata && !body.has('metadata')) { + body.append('metadata', this.encodeMetadata(metadata)); + } + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + if (metadata) { + headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata)); + } + // Node.js streams require duplex option for fetch in Node 20+ + // Check for both web ReadableStream and Node.js streams + const isStream = (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) || + (body && typeof body === 'object' && 'pipe' in body && typeof body.pipe === 'function'); + if (isStream && !options.duplex) { + options.duplex = 'half'; + } + } + if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { + headers = Object.assign(Object.assign({}, headers), fileOptions.headers); + } + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const data = yield (method == 'PUT' ? fetch_1.put : fetch_1.post)(this.fetch, `${this.url}/object/${_path}`, body, Object.assign({ headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); + return { + data: { path: cleanPath, id: data.Id, fullPath: data.Key }, + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - } -} - -class HostbasedAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.hashAlgo = pkInfo.hashAlgo; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - this.localHostname = pkInfo.localHostname; - this.localUsername = pkInfo.localUsername; - } -} - -class PwdAuthContext extends AuthContext { - constructor(protocol, username, service, method, password, cb) { - super(protocol, username, service, method, cb); - - this.password = password; - this._changeCb = undefined; - } - - requestChange(prompt, cb) { - if (this._changeCb) - throw new Error('Change request already in progress'); - if (typeof prompt !== 'string') - throw new Error('prompt argument must be a string'); - if (typeof cb !== 'function') - throw new Error('Callback argument must be a function'); - this._changeCb = cb; - this._protocol.authPasswdChg(prompt); - } -} - - -class Session extends EventEmitter { - constructor(client, info, localChan) { - super(); - - this.type = 'session'; - this.subtype = undefined; - this.server = true; - this._ending = false; - this._channel = undefined; - this._chanInfo = { - type: 'session', - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - } -} - - -class Server extends EventEmitter { - constructor(cfg, listener) { - super(); - - if (typeof cfg !== 'object' || cfg === null) - throw new Error('Missing configuration object'); - - const hostKeys = Object.create(null); - const hostKeyAlgoOrder = []; - - const hostKeys_ = cfg.hostKeys; - if (!Array.isArray(hostKeys_)) - throw new Error('hostKeys must be an array'); - - const cfgAlgos = ( - typeof cfg.algorithms === 'object' && cfg.algorithms !== null - ? cfg.algorithms - : {} - ); - - const hostKeyAlgos = generateAlgorithmList( - cfgAlgos.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - for (let i = 0; i < hostKeys_.length; ++i) { - let privateKey; - if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') - privateKey = parseKey(hostKeys_[i]); - else - privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); - - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - - if (privateKey.getPrivatePEM() === null) - throw new Error('privateKey value contains an invalid private key'); - - // Discard key if we already found a key of the same type - if (hostKeyAlgoOrder.includes(privateKey.type)) - continue; - - if (privateKey.type === 'ssh-rsa') { - // SSH supports multiple signature hashing algorithms for RSA, so we add - // the algorithms in the desired order - let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); - const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); - const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); - if (sha1Pos === -1) { - // Fall back to giving SHA1 the lowest priority - sha1Pos = Infinity; - } - [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { - if (pos === -1) - return; - - let type; - switch (pos) { - case sha1Pos: type = 'ssh-rsa'; break; - case sha256Pos: type = 'rsa-sha2-256'; break; - case sha512Pos: type = 'rsa-sha2-512'; break; - default: return; - } - - // Store same RSA key under each hash algorithm name for convenience - hostKeys[type] = privateKey; - - hostKeyAlgoOrder.push(type); + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + upload(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('POST', path, fileBody, fileOptions); }); - } else { - hostKeys[privateKey.type] = privateKey; - hostKeyAlgoOrder.push(privateKey.type); - } } - - const algorithms = { - kex: generateAlgorithmList( - cfgAlgos.kex, - DEFAULT_KEX, - SUPPORTED_KEX - ).concat(['kex-strict-s-v00@openssh.com']), - serverHostKey: hostKeyAlgoOrder, - cs: { - cipher: generateAlgorithmList( - cfgAlgos.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ), - mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), - compress: generateAlgorithmList( - cfgAlgos.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ), - lang: [], - }, - sc: undefined, - }; - algorithms.sc = algorithms.cs; - - if (typeof listener === 'function') - this.on('connection', listener); - - const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); - const offer = new KexInit(algorithms); - - this._srv = new netServer((socket) => { - if (this._connections >= this.maxConnections) { - socket.destroy(); - return; - } - ++this._connections; - socket.once('close', () => { - --this._connections; - }); - - let debug; - if (origDebug) { - // Prepend debug output with a unique identifier in case there are - // multiple clients connected at the same time - const debugPrefix = `[${process.hrtime().join('.')}] `; - debug = (msg) => { - origDebug(`${debugPrefix}${msg}`); - }; - } - - // eslint-disable-next-line no-use-before-define - new Client(socket, hostKeys, ident, offer, debug, this, cfg); - }).on('error', (err) => { - this.emit('error', err); - }).on('listening', () => { - this.emit('listening'); - }).on('close', () => { - this.emit('close'); - }); - this._connections = 0; - this.maxConnections = Infinity; - } - - injectSocket(socket) { - this._srv.emit('connection', socket); - } - - listen(...args) { - this._srv.listen(...args); - return this; - } - - address() { - return this._srv.address(); - } - - getConnections(cb) { - this._srv.getConnections(cb); - return this; - } - - close(cb) { - this._srv.close(cb); - return this; - } - - ref() { - this._srv.ref(); - return this; - } - - unref() { - this._srv.unref(); - return this; - } -} -Server.KEEPALIVE_CLIENT_INTERVAL = 15000; -Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; - - -class Client extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { - super(); - - let exchanges = 0; - let acceptedAuthSvc = false; - let pendingAuths = []; - let authCtx; - let kaTimer; - let onPacket; - const unsentGlobalRequestsReplies = []; - this._sock = socket; - this._chanMgr = new ChannelManager(this); - this._debug = debug; - this.noMoreSessions = false; - this.authenticated = false; - - // Silence pre-header errors - function onClientPreHeaderError(err) {} - this.on('error', onClientPreHeaderError); - - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from client: ${JSON.stringify(msg)}`); - }); - - const kaIntvl = ( - typeof srvCfg.keepaliveInterval === 'number' - && isFinite(srvCfg.keepaliveInterval) - && srvCfg.keepaliveInterval > 0 - ? srvCfg.keepaliveInterval - : ( - typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) - && Server.KEEPALIVE_CLIENT_INTERVAL > 0 - ? Server.KEEPALIVE_CLIENT_INTERVAL - : -1 - ) - ); - const kaCountMax = ( - typeof srvCfg.keepaliveCountMax === 'number' - && isFinite(srvCfg.keepaliveCountMax) - && srvCfg.keepaliveCountMax >= 0 - ? srvCfg.keepaliveCountMax - : ( - typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) - && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 - ? Server.KEEPALIVE_CLIENT_COUNT_MAX - : -1 - ) - ); - let kaCurCount = 0; - if (kaIntvl !== -1 && kaCountMax !== -1) { - this.once('ready', () => { - const onClose = () => { - clearInterval(kaTimer); - }; - this.on('close', onClose).on('end', onClose); - kaTimer = setInterval(() => { - if (++kaCurCount > kaCountMax) { - clearInterval(kaTimer); - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - this.end(); - } else { - // XXX: if the server ever starts sending real global requests to - // the client, we will need to add a dummy callback here to - // keep the correct reply order - proto.ping(); - } - }, kaIntvl); - }); - // TODO: re-verify keepalive behavior with OpenSSH - onPacket = () => { - kaTimer && kaTimer.refresh(); - kaCurCount = 0; - }; + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadToSignedUrl(path, token, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const url = new URL(this.url + `/object/upload/sign/${_path}`); + url.searchParams.set('token', token); + try { + let body; + const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + } + const data = yield (0, fetch_1.put)(this.fetch, url.toString(), body, { headers }); + return { + data: { path: cleanPath, fullPath: data.Key }, + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - const proto = this._protocol = new Protocol({ - server: true, - hostKeys, - ident, - offer, - onPacket, - greeting: srvCfg.greeting, - banner: srvCfg.banner, - onWrite: (data) => { - if (isWritable(socket)) - socket.write(data); - }, - onError: (err) => { - if (!proto._destruct) - socket.removeAllListeners('data'); - this.emit('error', err); - try { - socket.end(); - } catch {} - }, - onHeader: (header) => { - this.removeListener('error', onClientPreHeaderError); - - const info = { - ip: socket.remoteAddress, - family: socket.remoteFamily, - port: socket.remotePort, - header, - }; - if (!server.emit('connection', this, info)) { - // auto reject - proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); - socket.end(); - return; - } - - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - if (++exchanges > 1) - this.emit('rekey'); - this.emit('handshake', negotiated); - }, - debug, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - socket.end(); - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from client - - // Do early reject in some cases to prevent wasteful channel - // allocation - if ((info.type === 'session' && this.noMoreSessions) - || !this.authenticated) { - const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - return proto.channelOpenFail(info.sender, reasonCode); - } - - let localChan = -1; - let reason; - let replied = false; - - let accept; - const reject = () => { - if (replied) - return; - replied = true; - - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for 2 hours. + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param options.upsert If set to true, allows the file to be overwritten if it already exists. + */ + createSignedUploadUrl(path, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + const headers = Object.assign({}, this.headers); + if (options === null || options === void 0 ? void 0 : options.upsert) { + headers['x-upsert'] = 'true'; + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); + const url = new URL(this.url + data.url); + const token = url.searchParams.get('token'); + if (!token) { + throw new errors_1.StorageError('No token returned by API'); + } + return { data: { signedUrl: url.toString(), path, token }, error: null }; } - - if (localChan !== -1) - this._chanMgr.remove(localChan); - proto.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = this._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug) { - debug('Automatic rejection of incoming channel open: ' - + 'no channels available'); - } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'session': - if (listenerCount(this, 'session') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const instance = new Session(this, info, localChan); - this._chanMgr.update(localChan, instance); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return instance; - }; - - this.emit('session', accept, reject); - return; - } - break; - case 'direct-tcpip': - if (listenerCount(this, 'tcpip') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; - }; - - this.emit('tcpip', accept, reject, data); - return; - } - break; - case 'direct-streamlocal@openssh.com': - if (listenerCount(this, 'openssh.streamlocal') - && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; - }; - - this.emit('openssh.streamlocal', accept, reject, data); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug) { - debug('Automatic rejection of unsupported incoming channel open' - + ` type: ${info.type}`); - } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug) { - debug('Automatic rejection of unexpected incoming channel open' - + ` for: ${info.type}`); + }); + } + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + update(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); + }); + } + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + * @param options The destination options. + */ + move(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; } - } - - reject(); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const chanInfo = { - type: channel.type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' + }); + } + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + * @param options The destination options. + */ + copy(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, + }, { headers: this.headers }); + return { data: { path: data.Key }, error: null }; } - }; - - const instance = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - // NOOP -- should not be sent by client - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const session = this._chanMgr.get(recipient); - if (typeof session !== 'object' || session === null) - return; - - let replied = false; - let accept; - let reject; - - if (session.constructor !== Session) { - // normal Channel instance - if (wantReply) - proto.channelFailure(session.outgoing.id); - return; - } - - if (wantReply) { - // "real session" requests will have custom accept behaviors - if (type !== 'shell' - && type !== 'exec' - && type !== 'subsystem') { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelSuccess(session._chanInfo.outgoing.id); - }; + }); + } + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + createSignedUrl(path, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); + data = { signedUrl }; + return { data, error: null }; } - - reject = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelFailure(session._chanInfo.outgoing.id); - }; - } - - if (session._ending) { - reject && reject(); - return; - } - - switch (type) { - // "pre-real session start" requests - case 'env': - if (listenerCount(session, 'env')) { - session.emit('env', accept, reject, { - key: data.name, - val: data.value - }); - return; - } - break; - case 'pty-req': - if (listenerCount(session, 'pty')) { - session.emit('pty', accept, reject, data); - return; - } - break; - case 'window-change': - if (listenerCount(session, 'window-change')) - session.emit('window-change', accept, reject, data); - else - reject && reject(); - break; - case 'x11-req': - if (listenerCount(session, 'x11')) { - session.emit('x11', accept, reject, data); - return; - } - break; - // "post-real session start" requests - case 'signal': - if (listenerCount(session, 'signal')) { - session.emit('signal', accept, reject, { - name: data - }); - return; - } - break; - // XXX: is `auth-agent-req@openssh.com` really "post-real session - // start"? - case 'auth-agent-req@openssh.com': - if (listenerCount(session, 'auth-agent')) { - session.emit('auth-agent', accept, reject); - return; - } - break; - // "real session start" requests - case 'shell': - if (listenerCount(session, 'shell')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; - }; - - session.emit('shell', accept, reject); - return; - } - break; - case 'exec': - if (listenerCount(session, 'exec')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + createSignedUrls(paths, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + return { + data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL + ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) + : null }))), + error: null, }; - - session.emit('exec', accept, reject, { - command: data - }); - return; - } - break; - case 'subsystem': { - let useSFTP = (data === 'sftp'); - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - let instance; - if (useSFTP) { - instance = new SFTP(this, session._chanInfo, { - server: true, - debug, - }); - } else { - instance = new Channel( - this, session._chanInfo, { server: true } - ); - instance.subtype = - session.subtype = `${type}:${data}`; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; } - session._channel = instance; - - return instance; - }; - - if (data === 'sftp') { - if (listenerCount(session, 'sftp')) { - session.emit('sftp', accept, reject); - return; + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; } - useSFTP = false; - } - if (listenerCount(session, 'subsystem')) { - session.emit('subsystem', accept, reject, { - name: data + throw error; + } + }); + } + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + download(path, options) { + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + const queryString = transformationQuery ? `?${transformationQuery}` : ''; + const _path = this._getFinalPath(path); + const downloadFn = () => (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true, + }); + return new BlobDownloadBuilder_1.default(downloadFn, this.shouldThrowOnError); + } + /** + * Retrieves the details of an existing file. + * @param path + */ + info(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, { + headers: this.headers, }); - return; - } - break; + return { data: (0, helpers_1.recursiveToCamel)(data), error: null }; } - } - debug && debug( - `Automatic rejection of incoming channel request: ${type}` - ); - reject && reject(); - }, - CHANNEL_EOF: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - if (!channel._ending) { - channel._ending = true; - channel.emit('eof'); - channel.emit('end'); + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; } - channel = channel._channel; - if (!channel) - return; - } - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel._ending = true; - channel.emit('close'); - channel = channel._channel; - if (!channel) - return; - } - - onCHANNEL_CLOSE(this, recipient, channel); - }, - // Begin service/auth-related ========================================== - SERVICE_REQUEST: (p, service) => { - if (exchanges === 0 - || acceptedAuthSvc - || this.authenticated - || service !== 'ssh-userauth') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - acceptedAuthSvc = true; - proto.serviceAccept(service); - }, - USERAUTH_REQUEST: (p, username, service, method, methodData) => { - if (exchanges === 0 - || this.authenticated - || (authCtx - && (authCtx.username !== username - || authCtx.service !== service)) - // TODO: support hostbased auth - || (method !== 'password' - && method !== 'publickey' - && method !== 'hostbased' - && method !== 'keyboard-interactive' - && method !== 'none') - || pendingAuths.length === MAX_PENDING_AUTHS) { - proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); - socket.end(); - return; - } else if (service !== 'ssh-connection') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - let ctx; - switch (method) { - case 'keyboard-interactive': - ctx = new KeyboardAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'publickey': - ctx = new PKAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'hostbased': - ctx = new HostbasedAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'password': - if (authCtx - && authCtx instanceof PwdAuthContext - && authCtx._changeCb) { - const cb = authCtx._changeCb; - authCtx._changeCb = undefined; - cb(methodData.newPassword); - return; - } - ctx = new PwdAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'none': - ctx = new AuthContext(proto, username, service, method, - onAuthDecide); - break; - } - - if (authCtx) { - if (!authCtx._initialResponse) { - return pendingAuths.push(ctx); - } else if (authCtx._multistep && !authCtx._finalResponse) { - // RFC 4252 says to silently abort the current auth request if a - // new auth request comes in before the final response from an - // auth method that requires additional request/response exchanges - // -- this means keyboard-interactive for now ... - authCtx._cleanup && authCtx._cleanup(); - authCtx.emit('abort'); + }); + } + /** + * Checks the existence of a file. + * @param path + */ + exists(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, { + headers: this.headers, + }); + return { data: true, error: null }; } - } - - authCtx = ctx; - - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - }, - USERAUTH_INFO_RESPONSE: (p, responses) => { - if (authCtx && authCtx instanceof KeyboardAuthContext) - authCtx._onInfoResponse(responses); - }, - // End service/auth-related ============================================ - GLOBAL_REQUEST: (p, name, wantReply, data) => { - const reply = { - type: null, - buf: null - }; - - function setReply(type, buf) { - reply.type = type; - reply.buf = buf; - sendReplies(); - } - - if (wantReply) - unsentGlobalRequestsReplies.push(reply); - - if ((name === 'tcpip-forward' - || name === 'cancel-tcpip-forward' - || name === 'no-more-sessions@openssh.com' - || name === 'streamlocal-forward@openssh.com' - || name === 'cancel-streamlocal-forward@openssh.com') - && listenerCount(this, 'request') - && this.authenticated) { - let accept; - let reject; - - if (wantReply) { - let replied = false; - accept = (chosenPort) => { - if (replied) - return; - replied = true; - let bufPort; - if (name === 'tcpip-forward' - && data.bindPort === 0 - && typeof chosenPort === 'number') { - bufPort = Buffer.allocUnsafe(4); - writeUInt32BE(bufPort, chosenPort, 0); + catch (error) { + if (this.shouldThrowOnError) { + throw error; } - setReply('SUCCESS', bufPort); - }; - reject = () => { - if (replied) - return; - replied = true; - setReply('FAILURE'); - }; - } - - if (name === 'no-more-sessions@openssh.com') { - this.noMoreSessions = true; - accept && accept(); - return; + if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) { + const originalError = error.originalError; + if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { + return { data: false, error }; + } + } + throw error; } - - this.emit('request', accept, reject, name, data); - } else if (wantReply) { - setReply('FAILURE'); - } - }, - }, - }); - - socket.pause(); - cryptoInit.then(() => { - proto.start(); - socket.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(socket)) - socket.end(); - } catch {} + }); + } + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl(path, options) { + const _path = this._getFinalPath(path); + const _queryString = []; + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `download=${options.download === true ? '' : options.download}` + : ''; + if (downloadQueryParam !== '') { + _queryString.push(downloadQueryParam); } - }); - socket.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - }); - socket.on('error', (err) => { - err.level = 'socket'; - this.emit('error', err); - }).once('end', () => { - debug && debug('Socket ended'); - proto.cleanup(); - this.emit('end'); - }).once('close', () => { - debug && debug('Socket closed'); - proto.cleanup(); - this.emit('close'); - - const err = new Error('No response from server'); - - // Simulate error for pending channels and close any open channels - this._chanMgr.cleanup(err); - }); - - const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { - if (authCtx === ctx && !this.authenticated) { - if (allowed) { - authCtx = undefined; - this.authenticated = true; - proto.authSuccess(); - pendingAuths = []; - this.emit('ready'); - } else { - proto.authFailure(methodsLeft, isPartial); - if (pendingAuths.length) { - authCtx = pendingAuths.pop(); - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - } + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + if (transformationQuery !== '') { + _queryString.push(transformationQuery); } - } - }; - - function sendReplies() { - while (unsentGlobalRequestsReplies.length > 0 - && unsentGlobalRequestsReplies[0].type) { - const reply = unsentGlobalRequestsReplies.shift(); - if (reply.type === 'SUCCESS') - proto.requestSuccess(reply.buf); - if (reply.type === 'FAILURE') - proto.requestFailure(); - } - } - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - - x11(originAddr, originPort, cb) { - const opts = { originAddr, originPort }; - openChannel(this, 'x11', opts, cb); - return this; - } - - forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { - const opts = { boundAddr, boundPort, remoteAddr, remotePort }; - openChannel(this, 'forwarded-tcpip', opts, cb); - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - const opts = { socketPath }; - openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); - return this; - } - - rekey(cb) { - let error; - - try { - this._protocol.rekey(); - } catch (ex) { - error = ex; - } - - // TODO: re-throw error if no callback? - - if (typeof cb === 'function') { - if (error) - process.nextTick(cb, error); - else - this.once('rekey', cb); + let queryString = _queryString.join('&'); + if (queryString !== '') { + queryString = `?${queryString}`; + } + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, + }; } - } - - setNoDelay(noDelay) { - if (this._sock && typeof this._sock.setNoDelay === 'function') - this._sock.setNoDelay(noDelay); - - return this; - } -} - - -function openChannel(self, type, opts, cb) { - // Ask the client to open a channel for some purpose (e.g. a forwarded TCP - // connection) - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'forwarded-tcpip': - self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'x11': - self._protocol.x11(localChan, initWindow, maxPacket, opts); - break; - case 'forwarded-streamlocal@openssh.com': - self._protocol.openssh_forwardedStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} - -function compareNumbers(a, b) { - return a - b; -} - -module.exports = Server; -module.exports.IncomingClient = Client; - - -/***/ }), - -/***/ 40834: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { SFTP } = __nccwpck_require__(52026); - -const MAX_CHANNEL = 2 ** 32 - 1; - -function onChannelOpenFailure(self, recipient, info, cb) { - self._chanMgr.remove(recipient); - if (typeof cb !== 'function') - return; - - let err; - if (info instanceof Error) { - err = info; - } else if (typeof info === 'object' && info !== null) { - err = new Error(`(SSH) Channel open failure: ${info.description}`); - err.reason = info.reason; - } else { - err = new Error( - '(SSH) Channel open failure: server closed channel unexpectedly' - ); - err.reason = ''; - } - - cb(err); -} - -function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { - if (typeof channel === 'function') { - // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when - // requesting to open a channel - onChannelOpenFailure(self, recipient, err, channel); - return; - } - - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.incoming && channel.incoming.state === 'closed') - return; - - self._chanMgr.remove(recipient); - - if (channel.server && channel.constructor.name === 'Session') - return; - - channel.incoming.state = 'closed'; - - if (channel.readable) - channel.push(null); - if (channel.server) { - if (channel.stderr.writable) - channel.stderr.end(); - } else if (channel.stderr.readable) { - channel.stderr.push(null); - } - - if (channel.constructor !== SFTP - && (channel.outgoing.state === 'open' - || channel.outgoing.state === 'eof') - && !dead) { - channel.close(); - } - if (channel.outgoing.state === 'closing') - channel.outgoing.state = 'closed'; - - const readState = channel._readableState; - const writeState = channel._writableState; - if (writeState && !writeState.ending && !writeState.finished && !dead) - channel.end(); - - // Take care of any outstanding channel requests - const chanCallbacks = channel._callbacks; - channel._callbacks = []; - for (let i = 0; i < chanCallbacks.length; ++i) - chanCallbacks[i](true); - - if (channel.server) { - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - channel.emit('close'); - } else { - channel.once('end', () => channel.emit('close')); + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + remove(paths) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - } else { - let doClose; - switch (channel.type) { - case 'direct-streamlocal@openssh.com': - case 'direct-tcpip': - doClose = () => channel.emit('close'); - break; - default: { - // Align more with node child processes, where the close event gets - // the same arguments as the exit event - const exit = channel._exit; - doClose = () => { - if (exit.code === null) - channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); - else - channel.emit('close', exit.code); - }; - } + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Lists all the files and folders within a path of the bucket. + * @param path The folder path. + * @param options Search options including limit (defaults to 100), offset, sortBy, and search + */ + list(path, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - doClose(); - } else { - channel.once('end', doClose); + /** + * @experimental this method signature might change in the future + * @param options search options + * @param parameters + */ + listV2(options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign({}, options); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list-v2/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - const errReadState = channel.stderr._readableState; - if (!channel.stderr.readable - || channel.stderr.destroyed - || (errReadState && errReadState.endEmitted)) { - channel.stderr.emit('close'); - } else { - channel.stderr.once('end', () => channel.stderr.emit('close')); + encodeMetadata(metadata) { + return JSON.stringify(metadata); } - } -} - -class ChannelManager { - constructor(client) { - this._client = client; - this._channels = {}; - this._cur = -1; - this._count = 0; - } - add(val) { - // Attempt to reserve an id - - let id; - // Optimized paths - if (this._cur < MAX_CHANNEL) { - id = ++this._cur; - } else if (this._count === 0) { - // Revert and reset back to fast path once we no longer have any channels - // open - this._cur = 0; - id = 0; - } else { - // Slower lookup path - - // This path is triggered we have opened at least MAX_CHANNEL channels - // while having at least one channel open at any given time, so we have - // to search for a free id. - const channels = this._channels; - for (let i = 0; i < MAX_CHANNEL; ++i) { - if (channels[i] === undefined) { - id = i; - break; + toBase64(data) { + if (typeof Buffer !== 'undefined') { + return Buffer.from(data).toString('base64'); } - } - } - - if (id === undefined) - return -1; - - this._channels[id] = (val || true); - ++this._count; - - return id; - } - update(id, val) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (val && this._channels[id]) - this._channels[id] = val; - } - get(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - return this._channels[id]; - } - remove(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (this._channels[id]) { - delete this._channels[id]; - if (this._count) - --this._count; + return btoa(data); } - } - cleanup(err) { - const channels = this._channels; - this._channels = {}; - this._cur = -1; - this._count = 0; - - const chanIDs = Object.keys(channels); - const client = this._client; - for (let i = 0; i < chanIDs.length; ++i) { - const id = +chanIDs[i]; - const channel = channels[id]; - onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); + _getFinalPath(path) { + return `${this.bucketId}/${path.replace(/^\/+/, '')}`; } - } -} - -const isRegExp = (() => { - const toString = Object.prototype.toString; - return (val) => toString.call(val) === '[object RegExp]'; -})(); - -function generateAlgorithmList(algoList, defaultList, supportedList) { - if (Array.isArray(algoList) && algoList.length > 0) { - // Exact list - for (let i = 0; i < algoList.length; ++i) { - if (supportedList.indexOf(algoList[i]) === -1) - throw new Error(`Unsupported algorithm: ${algoList[i]}`); + _removeEmptyFolders(path) { + return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); } - return algoList; - } - - if (typeof algoList === 'object' && algoList !== null) { - // Operations based on the default list - const keys = Object.keys(algoList); - let list = defaultList; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - let val = algoList[key]; - switch (key) { - case 'append': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const append = val[j]; - if (typeof append === 'string') { - if (!append || list.indexOf(append) !== -1) - continue; - if (supportedList.indexOf(append) === -1) - throw new Error(`Unsupported algorithm: ${append}`); - if (list === defaultList) - list = list.slice(); - list.push(append); - } else if (isRegExp(append)) { - for (let k = 0; k < supportedList.length; ++k) { - const algo = supportedList[k]; - if (append.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.push(algo); - } - } - } - } - } - break; - case 'prepend': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = val.length; j >= 0; --j) { - const prepend = val[j]; - if (typeof prepend === 'string') { - if (!prepend || list.indexOf(prepend) !== -1) - continue; - if (supportedList.indexOf(prepend) === -1) - throw new Error(`Unsupported algorithm: ${prepend}`); - if (list === defaultList) - list = list.slice(); - list.unshift(prepend); - } else if (isRegExp(prepend)) { - for (let k = supportedList.length; k >= 0; --k) { - const algo = supportedList[k]; - if (prepend.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.unshift(algo); - } - } - } - } - } - break; - case 'remove': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const search = val[j]; - if (typeof search === 'string') { - if (!search) - continue; - const idx = list.indexOf(search); - if (idx === -1) - continue; - if (list === defaultList) - list = list.slice(); - list.splice(idx, 1); - } else if (isRegExp(search)) { - for (let k = 0; k < list.length; ++k) { - if (search.test(list[k])) { - if (list === defaultList) - list = list.slice(); - list.splice(k, 1); - --k; - } - } - } - } - } - break; - } + transformOptsToQueryString(transform) { + const params = []; + if (transform.width) { + params.push(`width=${transform.width}`); + } + if (transform.height) { + params.push(`height=${transform.height}`); + } + if (transform.resize) { + params.push(`resize=${transform.resize}`); + } + if (transform.format) { + params.push(`format=${transform.format}`); + } + if (transform.quality) { + params.push(`quality=${transform.quality}`); + } + return params.join('&'); } - - return list; - } - - return defaultList; } - -module.exports = { - ChannelManager, - generateAlgorithmList, - onChannelOpenFailure, - onCHANNEL_CLOSE, - isWritable: (stream) => { - // XXX: hack to workaround regression in node - // See: https://github.com/nodejs/node/issues/36029 - return (stream - && stream.writable - && stream._readableState - && stream._readableState.ended === false); - }, -}; - +exports["default"] = StorageFileApi; +//# sourceMappingURL=StorageFileApi.js.map /***/ }), -/***/ 94841: +/***/ 7023: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// 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 Buffer = (__nccwpck_require__(21867).Buffer); -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(2758); +class StreamDownloadBuilder { + constructor(downloadFn, shouldThrowOnError) { + this.downloadFn = downloadFn; + this.shouldThrowOnError = shouldThrowOnError; } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } + then(onfulfilled, onrejected) { + return this.execute().then(onfulfilled, onrejected); } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: result.body, + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; } +exports["default"] = StreamDownloadBuilder; +//# sourceMappingURL=StreamDownloadBuilder.js.map /***/ }), -/***/ 366: +/***/ 1807: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var chownr = __nccwpck_require__(59051) -var tar = __nccwpck_require__(2283) -var pump = __nccwpck_require__(18341) -var mkdirp = __nccwpck_require__(97614) -var fs = __nccwpck_require__(57147) -var path = __nccwpck_require__(71017) -var os = __nccwpck_require__(22037) - -var win32 = os.platform() === 'win32' - -var noop = function () {} - -var echo = function (name) { - return name -} - -var normalize = !win32 ? echo : function (name) { - return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') -} - -var statAll = function (fs, stat, cwd, ignore, entries, sort) { - var queue = entries || ['.'] - - return function loop (callback) { - if (!queue.length) return callback() - var next = queue.shift() - var nextAbs = path.join(cwd, next) - - stat.call(fs, nextAbs, function (err, stat) { - if (err) return callback(err) - - if (!stat.isDirectory()) return callback(null, next, stat) - - fs.readdir(nextAbs, function (err, files) { - if (err) return callback(err) +"use strict"; - if (sort) files.sort() - for (var i = 0; i < files.length; i++) { - if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const functions_js_1 = __nccwpck_require__(8519); +const postgrest_js_1 = __nccwpck_require__(1178); +const realtime_js_1 = __nccwpck_require__(442); +const storage_js_1 = __nccwpck_require__(5852); +const constants_1 = __nccwpck_require__(4868); +const fetch_1 = __nccwpck_require__(785); +const helpers_1 = __nccwpck_require__(3575); +const SupabaseAuthClient_1 = __nccwpck_require__(7620); +/** + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. + */ +class SupabaseClient { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + const baseUrl = (0, helpers_1.validateSupabaseUrl)(supabaseUrl); + if (!supabaseKey) + throw new Error('supabaseKey is required.'); + this.realtimeUrl = new URL('realtime/v1', baseUrl); + this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws'); + this.authUrl = new URL('auth/v1', baseUrl); + this.storageUrl = new URL('storage/v1', baseUrl); + this.functionsUrl = new URL('functions/v1', baseUrl); + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`; + const DEFAULTS = { + db: constants_1.DEFAULT_DB_OPTIONS, + realtime: constants_1.DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: constants_1.DEFAULT_GLOBAL_OPTIONS, + }; + const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; + this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); + } + else { + this.accessToken = settings.accessToken; + this.auth = new Proxy({}, { + get: (_, prop) => { + throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); + }, + }); + } + this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); + this.rest = new postgrest_js_1.PostgrestClient(new URL('rest/v1', baseUrl).href, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch, + }); + this.storage = new storage_js_1.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); + if (!settings.accessToken) { + this._listenForAuthEvents(); } - - callback(null, next, stat) - }) - }) - } -} - -var strip = function (map, level) { - return function (header) { - header.name = header.name.split('/').slice(level).join('/') - - var linkname = header.linkname - if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { - header.linkname = linkname.split('/').slice(level).join('/') - } - - return map(header) - } -} - -exports.pack = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} - - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) - var strict = opts.strict !== false - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var pack = opts.pack || tar.pack() - var finish = opts.finish || noop - - if (opts.strip) map = strip(map, opts.strip) - - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) - } - - var onsymlink = function (filename, header) { - xfs.readlink(path.join(cwd, filename), function (err, linkname) { - if (err) return pack.destroy(err) - header.linkname = normalize(linkname) - pack.entry(header, onnextentry) - }) - } - - var onstat = function (err, filename, stat) { - if (err) return pack.destroy(err) - if (!filename) { - if (opts.finalize !== false) pack.finalize() - return finish(pack) - } - - if (stat.isSocket()) return onnextentry() // tar does not support sockets... - - var header = { - name: normalize(filename), - mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, - mtime: stat.mtime, - size: stat.size, - type: 'file', - uid: stat.uid, - gid: stat.gid - } - - if (stat.isDirectory()) { - header.size = 0 - header.type = 'directory' - header = map(header) || header - return pack.entry(header, onnextentry) - } - - if (stat.isSymbolicLink()) { - header.size = 0 - header.type = 'symlink' - header = map(header) || header - return onsymlink(filename, header) - } - - // TODO: add fifo etc... - - header = map(header) || header - - if (!stat.isFile()) { - if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) - return onnextentry() - } - - var entry = pack.entry(header, onnextentry) - if (!entry) return - - var rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header) - - rs.on('error', function (err) { // always forward errors on destroy - entry.destroy(err) - }) - - pump(rs, entry) - } - - var onnextentry = function (err) { - if (err) return pack.destroy(err) - statNext(onstat) - } - - onnextentry() - - return pack -} - -var head = function (list) { - return list.length ? list[list.length - 1] : null -} - -var processGetuid = function () { - return process.getuid ? process.getuid() : -1 -} - -var processUmask = function () { - return process.umask ? process.umask() : 0 -} - -exports.extract = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} - - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var own = opts.chown !== false && !win32 && processGetuid() === 0 - var extract = opts.extract || tar.extract() - var stack = [] - var now = new Date() - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var strict = opts.strict !== false - - if (opts.strip) map = strip(map, opts.strip) - - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) - } - - var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry - var top - while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() - if (!top) return cb() - xfs.utimes(top[0], now, top[1], cb) - } - - var utimes = function (name, header, cb) { - if (opts.utimes === false) return cb() - - if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) - if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? - - xfs.utimes(name, now, header.mtime, function (err) { - if (err) return cb(err) - utimesParent(name, cb) - }) - } - - var chperm = function (name, header, cb) { - var link = header.type === 'symlink' - - /* eslint-disable node/no-deprecated-api */ - var chmod = link ? xfs.lchmod : xfs.chmod - var chown = link ? xfs.lchown : xfs.chown - /* eslint-enable node/no-deprecated-api */ - - if (!chmod) return cb() - - var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask - - if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown) - else onchown(null) - - function onchown (err) { - if (err) return cb(err) - if (!chmod) return cb() - chmod.call(xfs, name, mode, cb) - } - } - - extract.on('entry', function (header, stream, next) { - header = map(header) || header - header.name = normalize(header.name) - var name = path.join(cwd, path.join('/', header.name)) - - if (ignore(name, header)) { - stream.resume() - return next() - } - - var stat = function (err) { - if (err) return next(err) - utimes(name, header, function (err) { - if (err) return next(err) - if (win32) return next() - chperm(name, header, next) - }) - } - - var onsymlink = function () { - if (win32) return next() // skip symlinks on win for now before it can be tested - xfs.unlink(name, function () { - var dst = path.resolve(path.dirname(name), header.linkname) - if (!inCwd(dst, cwd)) return next(new Error(name + ' is not a valid symlink')) - - xfs.symlink(header.linkname, name, stat) - }) - } - - var onlink = function () { - if (win32) return next() // skip links on win for now before it can be tested - xfs.unlink(name, function () { - var srcpath = path.join(cwd, path.join('/', header.linkname)) - - xfs.realpath(srcpath, function (err, dst) { - if (err || !inCwd(dst, cwd)) return next(new Error(name + ' is not a valid hardlink')) - - xfs.link(dst, name, function (err) { - if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { - stream = xfs.createReadStream(srcpath) - return onfile() - } - - stat(err) - }) - }) - }) } - - var onfile = function () { - var ws = xfs.createWriteStream(name) - var rs = mapStream(stream, header) - - ws.on('error', function (err) { // always forward errors on destroy - rs.destroy(err) - }) - - pump(rs, ws, function (err) { - if (err) return next(err) - ws.on('close', stat) - }) + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new functions_js_1.FunctionsClient(this.functionsUrl.href, { + headers: this.headers, + customFetch: this.fetch, + }); } - - if (header.type === 'directory') { - stack.push([name, header.mtime]) - return mkdirfix(name, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, stat) + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); } - - var dir = path.dirname(name) - - validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { - if (err) return next(err) - if (!valid) return next(new Error(dir + ' is not a valid path')) - - mkdirfix(dir, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, function (err) { - if (err) return next(err) - - switch (header.type) { - case 'file': return onfile() - case 'link': return onlink() - case 'symlink': return onsymlink() - } - - if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) - - stream.resume() - next() - }) - }) - }) - - if (opts.finish) extract.on('finish', opts.finish) - - return extract -} - -function validate (fs, name, root, cb) { - if (name === root) return cb(null, true) - fs.lstat(name, function (err, st) { - if (err && err.code !== 'ENOENT') return cb(err) - if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb) - cb(null, false) - }) -} - -function mkdirfix (name, opts, cb) { - mkdirp(name, { fs: opts.fs }, function (err, made) { - if (!err && made && opts.own) { - chownr(made, opts.uid, opts.gid, cb) - } else { - cb(err) + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return this.rest.schema(schema); } - }) -} - -function inCwd (dst, cwd) { - cwd = path.resolve(cwd) - return cwd === dst || dst.startsWith(cwd + path.sep) -} - - -/***/ }), - -/***/ 57882: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(73837) -var bl = __nccwpck_require__(20336) -var headers = __nccwpck_require__(68860) - -var Writable = (__nccwpck_require__(51642).Writable) -var PassThrough = (__nccwpck_require__(51642).PassThrough) - -var noop = function () {} - -var overflow = function (size) { - size &= 511 - return size && 512 - size -} - -var emptyStream = function (self, offset) { - var s = new Source(self, offset) - s.end() - return s -} - -var mixinPax = function (header, pax) { - if (pax.path) header.name = pax.path - if (pax.linkpath) header.linkname = pax.linkpath - if (pax.size) header.size = parseInt(pax.size, 10) - header.pax = pax - return header -} - -var Source = function (self, offset) { - this._parent = self - this.offset = offset - PassThrough.call(this, { autoDestroy: false }) -} - -util.inherits(Source, PassThrough) - -Source.prototype.destroy = function (err) { - this._parent.destroy(err) -} - -var Extract = function (opts) { - if (!(this instanceof Extract)) return new Extract(opts) - Writable.call(this, opts) - - opts = opts || {} - - this._offset = 0 - this._buffer = bl() - this._missing = 0 - this._partial = false - this._onparse = noop - this._header = null - this._stream = null - this._overflow = null - this._cb = null - this._locked = false - this._destroyed = false - this._pax = null - this._paxGlobal = null - this._gnuLongPath = null - this._gnuLongLinkPath = null - - var self = this - var b = self._buffer - - var oncontinue = function () { - self._continue() - } - - var onunlock = function (err) { - self._locked = false - if (err) return self.destroy(err) - if (!self._stream) oncontinue() - } - - var onstreamend = function () { - self._stream = null - var drain = overflow(self._header.size) - if (drain) self._parse(drain, ondrain) - else self._parse(512, onheader) - if (!self._locked) oncontinue() - } - - var ondrain = function () { - self._buffer.consume(overflow(self._header.size)) - self._parse(512, onheader) - oncontinue() - } - - var onpaxglobalheader = function () { - var size = self._header.size - self._paxGlobal = headers.decodePax(b.slice(0, size)) - b.consume(size) - onstreamend() - } - - var onpaxheader = function () { - var size = self._header.size - self._pax = headers.decodePax(b.slice(0, size)) - if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax) - b.consume(size) - onstreamend() - } - - var ongnulongpath = function () { - var size = self._header.size - this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() - } - - var ongnulonglinkpath = function () { - var size = self._header.size - this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() - } - - var onheader = function () { - var offset = self._offset - var header - try { - header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat) - } catch (err) { - self.emit('error', err) + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options = { + head: false, + get: false, + count: undefined, + }) { + return this.rest.rpc(fn, args, options); } - b.consume(512) - - if (!header) { - self._parse(512, onheader) - oncontinue() - return + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); } - if (header.type === 'gnu-long-path') { - self._parse(header.size, ongnulongpath) - oncontinue() - return + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); } - if (header.type === 'gnu-long-link-path') { - self._parse(header.size, ongnulonglinkpath) - oncontinue() - return + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); } - if (header.type === 'pax-global-header') { - self._parse(header.size, onpaxglobalheader) - oncontinue() - return + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); } - if (header.type === 'pax-header') { - self._parse(header.size, onpaxheader) - oncontinue() - return + async _getAccessToken() { + var _a, _b; + if (this.accessToken) { + return await this.accessToken(); + } + const { data } = await this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; } - - if (self._gnuLongPath) { - header.name = self._gnuLongPath - self._gnuLongPath = null + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError, }, headers, fetch) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + }; + return new SupabaseAuthClient_1.SupabaseAuthClient({ + url: this.authUrl.href, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + flowType, + lock, + debug, + throwOnError, + fetch, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === 'authorization'), + }); } - - if (self._gnuLongLinkPath) { - header.linkname = self._gnuLongLinkPath - self._gnuLongLinkPath = null + _initRealtimeClient(options) { + return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); } - - if (self._pax) { - self._header = header = mixinPax(header, self._pax) - self._pax = null + _listenForAuthEvents() { + const data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; } - - self._locked = true - - if (!header.size || header.type === 'directory') { - self._parse(512, onheader) - self.emit('entry', header, emptyStream(self, offset), onunlock) - return + _handleTokenChanged(event, source, token) { + if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token) { + this.changedAccessToken = token; + this.realtime.setAuth(token); + } + else if (event === 'SIGNED_OUT') { + this.realtime.setAuth(); + if (source == 'STORAGE') + this.auth.signOut(); + this.changedAccessToken = undefined; + } } - - self._stream = new Source(self, offset) - - self.emit('entry', header, self._stream, onunlock) - self._parse(header.size, onstreamend) - oncontinue() - } - - this._onheader = onheader - this._parse(512, onheader) -} - -util.inherits(Extract, Writable) - -Extract.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true - - if (err) this.emit('error', err) - this.emit('close') - if (this._stream) this._stream.emit('close') -} - -Extract.prototype._parse = function (size, onparse) { - if (this._destroyed) return - this._offset += size - this._missing = size - if (onparse === this._onheader) this._partial = false - this._onparse = onparse } - -Extract.prototype._continue = function () { - if (this._destroyed) return - var cb = this._cb - this._cb = noop - if (this._overflow) this._write(this._overflow, undefined, cb) - else cb() -} - -Extract.prototype._write = function (data, enc, cb) { - if (this._destroyed) return - - var s = this._stream - var b = this._buffer - var missing = this._missing - if (data.length) this._partial = true - - // we do not reach end-of-chunk now. just forward it - - if (data.length < missing) { - this._missing -= data.length - this._overflow = null - if (s) return s.write(data, cb) - b.append(data) - return cb() - } - - // end-of-chunk. the parser should call cb. - - this._cb = cb - this._missing = 0 - - var overflow = null - if (data.length > missing) { - overflow = data.slice(missing) - data = data.slice(0, missing) - } - - if (s) s.end(data) - else b.append(data) - - this._overflow = overflow - this._onparse() -} - -Extract.prototype._final = function (cb) { - if (this._partial) return this.destroy(new Error('Unexpected end of data')) - cb() -} - -module.exports = Extract - +exports["default"] = SupabaseClient; +//# sourceMappingURL=SupabaseClient.js.map /***/ }), -/***/ 68860: -/***/ ((__unused_webpack_module, exports) => { - -var alloc = Buffer.alloc - -var ZEROS = '0000000000000000000' -var SEVENS = '7777777777777777777' -var ZERO_OFFSET = '0'.charCodeAt(0) -var USTAR_MAGIC = Buffer.from('ustar\x00', 'binary') -var USTAR_VER = Buffer.from('00', 'binary') -var GNU_MAGIC = Buffer.from('ustar\x20', 'binary') -var GNU_VER = Buffer.from('\x20\x00', 'binary') -var MASK = parseInt('7777', 8) -var MAGIC_OFFSET = 257 -var VERSION_OFFSET = 263 - -var clamp = function (index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue - index = ~~index // Coerce to integer. - if (index >= len) return len - if (index >= 0) return index - index += len - if (index >= 0) return index - return 0 -} - -var toType = function (flag) { - switch (flag) { - case 0: - return 'file' - case 1: - return 'link' - case 2: - return 'symlink' - case 3: - return 'character-device' - case 4: - return 'block-device' - case 5: - return 'directory' - case 6: - return 'fifo' - case 7: - return 'contiguous-file' - case 72: - return 'pax-header' - case 55: - return 'pax-global-header' - case 27: - return 'gnu-long-link-path' - case 28: - case 30: - return 'gnu-long-path' - } - - return null -} - -var toTypeflag = function (flag) { - switch (flag) { - case 'file': - return 0 - case 'link': - return 1 - case 'symlink': - return 2 - case 'character-device': - return 3 - case 'block-device': - return 4 - case 'directory': - return 5 - case 'fifo': - return 6 - case 'contiguous-file': - return 7 - case 'pax-header': - return 72 - } - - return 0 -} - -var indexOf = function (block, num, offset, end) { - for (; offset < end; offset++) { - if (block[offset] === num) return offset - } - return end -} - -var cksum = function (block) { - var sum = 8 * 32 - for (var i = 0; i < 148; i++) sum += block[i] - for (var j = 156; j < 512; j++) sum += block[j] - return sum -} +/***/ 1206: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -var encodeOct = function (val, n) { - val = val.toString(8) - if (val.length > n) return SEVENS.slice(0, n) + ' ' - else return ZEROS.slice(0, n - val.length) + val + ' ' -} +"use strict"; -/* Copied from the node-tar repo and modified to meet - * tar-stream coding standard. - * - * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 +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 __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); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0; +const SupabaseClient_1 = __importDefault(__nccwpck_require__(1807)); +__exportStar(__nccwpck_require__(6748), exports); +var postgrest_js_1 = __nccwpck_require__(1178); +Object.defineProperty(exports, "PostgrestError", ({ enumerable: true, get: function () { return postgrest_js_1.PostgrestError; } })); +var functions_js_1 = __nccwpck_require__(8519); +Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsHttpError; } })); +Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsFetchError; } })); +Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsRelayError; } })); +Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsError; } })); +Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return functions_js_1.FunctionRegion; } })); +__exportStar(__nccwpck_require__(442), exports); +var SupabaseClient_2 = __nccwpck_require__(1807); +Object.defineProperty(exports, "SupabaseClient", ({ enumerable: true, get: function () { return __importDefault(SupabaseClient_2).default; } })); +/** + * Creates a new Supabase Client. */ -function parse256 (buf) { - // first byte MUST be either 80 or FF - // 80 for positive, FF for 2's comp - var positive - if (buf[0] === 0x80) positive = true - else if (buf[0] === 0xFF) positive = false - else return null - - // build up a base-256 tuple from the least sig to the highest - var tuple = [] - for (var i = buf.length - 1; i > 0; i--) { - var byte = buf[i] - if (positive) tuple.push(byte) - else tuple.push(0xFF - byte) - } - - var sum = 0 - var l = tuple.length - for (i = 0; i < l; i++) { - sum += tuple[i] * Math.pow(256, i) - } - - return positive ? sum : -1 * sum -} - -var decodeOct = function (val, offset, length) { - val = val.slice(offset, offset + length) - offset = 0 - - // If prefixed with 0x80 then parse as a base-256 integer - if (val[offset] & 0x80) { - return parse256(val) - } else { - // Older versions of tar can prefix with spaces - while (offset < val.length && val[offset] === 32) offset++ - var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) - while (offset < end && val[offset] === 0) offset++ - if (end === offset) return 0 - return parseInt(val.slice(offset, end).toString(), 8) - } -} - -var decodeStr = function (val, offset, length, encoding) { - return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding) -} - -var addLength = function (str) { - var len = Buffer.byteLength(str) - var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 - if (len + digits >= Math.pow(10, digits)) digits++ - - return (len + digits) + str -} - -exports.decodeLongPath = function (buf, encoding) { - return decodeStr(buf, 0, buf.length, encoding) -} - -exports.encodePax = function (opts) { // TODO: encode more stuff in pax - var result = '' - if (opts.name) result += addLength(' path=' + opts.name + '\n') - if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') - var pax = opts.pax - if (pax) { - for (var key in pax) { - result += addLength(' ' + key + '=' + pax[key] + '\n') +const createClient = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); +}; +exports.createClient = createClient; +// Check for Node.js <= 18 deprecation +function shouldShowDeprecationWarning() { + // Skip in browser environments + if (typeof window !== 'undefined') { + return false; } - } - return Buffer.from(result) -} - -exports.decodePax = function (buf) { - var result = {} - - while (buf.length) { - var i = 0 - while (i < buf.length && buf[i] !== 32) i++ - var len = parseInt(buf.slice(0, i).toString(), 10) - if (!len) return result - - var b = buf.slice(i + 1, len - 1).toString() - var keyIndex = b.indexOf('=') - if (keyIndex === -1) return result - result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) - - buf = buf.slice(len) - } - - return result -} - -exports.encode = function (opts) { - var buf = alloc(512) - var name = opts.name - var prefix = '' - - if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' - if (Buffer.byteLength(name) !== name.length) return null // utf-8 - - while (Buffer.byteLength(name) > 100) { - var i = name.indexOf('/') - if (i === -1) return null - prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) - name = name.slice(i + 1) - } - - if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null - if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null - - buf.write(name) - buf.write(encodeOct(opts.mode & MASK, 6), 100) - buf.write(encodeOct(opts.uid, 6), 108) - buf.write(encodeOct(opts.gid, 6), 116) - buf.write(encodeOct(opts.size, 11), 124) - buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) - - buf[156] = ZERO_OFFSET + toTypeflag(opts.type) - - if (opts.linkname) buf.write(opts.linkname, 157) - - USTAR_MAGIC.copy(buf, MAGIC_OFFSET) - USTAR_VER.copy(buf, VERSION_OFFSET) - if (opts.uname) buf.write(opts.uname, 265) - if (opts.gname) buf.write(opts.gname, 297) - buf.write(encodeOct(opts.devmajor || 0, 6), 329) - buf.write(encodeOct(opts.devminor || 0, 6), 337) - - if (prefix) buf.write(prefix, 345) - - buf.write(encodeOct(cksum(buf), 6), 148) - - return buf -} - -exports.decode = function (buf, filenameEncoding, allowUnknownFormat) { - var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET - - var name = decodeStr(buf, 0, 100, filenameEncoding) - var mode = decodeOct(buf, 100, 8) - var uid = decodeOct(buf, 108, 8) - var gid = decodeOct(buf, 116, 8) - var size = decodeOct(buf, 124, 12) - var mtime = decodeOct(buf, 136, 12) - var type = toType(typeflag) - var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) - var uname = decodeStr(buf, 265, 32) - var gname = decodeStr(buf, 297, 32) - var devmajor = decodeOct(buf, 329, 8) - var devminor = decodeOct(buf, 337, 8) - - var c = cksum(buf) - - // checksum is still initial value if header was null. - if (c === 8 * 32) return null - - // valid checksum - if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') - - if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { - // ustar (posix) format. - // prepend prefix, if present. - if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name - } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && - GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { - // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and - // multi-volume tarballs. - } else { - if (!allowUnknownFormat) { - throw new Error('Invalid tar header: unknown format.') + // Skip if process is not available (e.g., Edge Runtime) + if (typeof process === 'undefined') { + return false; } - } - - // to support old tar versions that use trailing / to indicate dirs - if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 - - return { - name, - mode, - uid, - gid, - size, - mtime: new Date(1000 * mtime), - type, - linkname, - uname, - gname, - devmajor, - devminor - } + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersion = process['version']; + if (processVersion === undefined || processVersion === null) { + return false; + } + const versionMatch = processVersion.match(/^v(\d+)\./); + if (!versionMatch) { + return false; + } + const majorVersion = parseInt(versionMatch[1], 10); + return majorVersion <= 18; } - +if (shouldShowDeprecationWarning()) { + console.warn(`āš ļø Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` + + `Please upgrade to Node.js 20 or later. ` + + `For more information, visit: https://github.com/orgs/supabase/discussions/37217`); +} +//# sourceMappingURL=index.js.map /***/ }), -/***/ 2283: +/***/ 7620: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.extract = __nccwpck_require__(57882) -exports.pack = __nccwpck_require__(94930) - - -/***/ }), - -/***/ 94930: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var constants = __nccwpck_require__(73186) -var eos = __nccwpck_require__(81205) -var inherits = __nccwpck_require__(44124) -var alloc = Buffer.alloc - -var Readable = (__nccwpck_require__(51642).Readable) -var Writable = (__nccwpck_require__(51642).Writable) -var StringDecoder = (__nccwpck_require__(71576).StringDecoder) - -var headers = __nccwpck_require__(68860) - -var DMODE = parseInt('755', 8) -var FMODE = parseInt('644', 8) - -var END_OF_TAR = alloc(1024) - -var noop = function () {} - -var overflow = function (self, size) { - size &= 511 - if (size) self.push(END_OF_TAR.slice(0, 512 - size)) -} - -function modeToType (mode) { - switch (mode & constants.S_IFMT) { - case constants.S_IFBLK: return 'block-device' - case constants.S_IFCHR: return 'character-device' - case constants.S_IFDIR: return 'directory' - case constants.S_IFIFO: return 'fifo' - case constants.S_IFLNK: return 'symlink' - } - - return 'file' -} - -var Sink = function (to) { - Writable.call(this) - this.written = 0 - this._to = to - this._destroyed = false -} - -inherits(Sink, Writable) - -Sink.prototype._write = function (data, enc, cb) { - this.written += data.length - if (this._to.push(data)) return cb() - this._to._drain = cb -} - -Sink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} - -var LinkSink = function () { - Writable.call(this) - this.linkname = '' - this._decoder = new StringDecoder('utf-8') - this._destroyed = false -} - -inherits(LinkSink, Writable) - -LinkSink.prototype._write = function (data, enc, cb) { - this.linkname += this._decoder.write(data) - cb() -} - -LinkSink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} - -var Void = function () { - Writable.call(this) - this._destroyed = false -} - -inherits(Void, Writable) - -Void.prototype._write = function (data, enc, cb) { - cb(new Error('No body allowed for this entry')) -} - -Void.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} - -var Pack = function (opts) { - if (!(this instanceof Pack)) return new Pack(opts) - Readable.call(this, opts) - - this._drain = noop - this._finalized = false - this._finalizing = false - this._destroyed = false - this._stream = null -} - -inherits(Pack, Readable) - -Pack.prototype.entry = function (header, buffer, callback) { - if (this._stream) throw new Error('already piping an entry') - if (this._finalized || this._destroyed) return - - if (typeof buffer === 'function') { - callback = buffer - buffer = null - } - - if (!callback) callback = noop - - var self = this - - if (!header.size || header.type === 'symlink') header.size = 0 - if (!header.type) header.type = modeToType(header.mode) - if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE - if (!header.uid) header.uid = 0 - if (!header.gid) header.gid = 0 - if (!header.mtime) header.mtime = new Date() - - if (typeof buffer === 'string') buffer = Buffer.from(buffer) - if (Buffer.isBuffer(buffer)) { - header.size = buffer.length - this._encode(header) - var ok = this.push(buffer) - overflow(self, header.size) - if (ok) process.nextTick(callback) - else this._drain = callback - return new Void() - } - - if (header.type === 'symlink' && !header.linkname) { - var linkSink = new LinkSink() - eos(linkSink, function (err) { - if (err) { // stream was closed - self.destroy() - return callback(err) - } - - header.linkname = linkSink.linkname - self._encode(header) - callback() - }) - - return linkSink - } - - this._encode(header) - - if (header.type !== 'file' && header.type !== 'contiguous-file') { - process.nextTick(callback) - return new Void() - } - - var sink = new Sink(this) - - this._stream = sink - - eos(sink, function (err) { - self._stream = null - - if (err) { // stream was closed - self.destroy() - return callback(err) - } +"use strict"; - if (sink.written !== header.size) { // corrupting tar - self.destroy() - return callback(new Error('size mismatch')) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SupabaseAuthClient = void 0; +const auth_js_1 = __nccwpck_require__(6748); +class SupabaseAuthClient extends auth_js_1.AuthClient { + constructor(options) { + super(options); } - - overflow(self, header.size) - if (self._finalizing) self.finalize() - callback() - }) - - return sink } +exports.SupabaseAuthClient = SupabaseAuthClient; +//# sourceMappingURL=SupabaseAuthClient.js.map -Pack.prototype.finalize = function () { - if (this._stream) { - this._finalizing = true - return - } +/***/ }), - if (this._finalized) return - this._finalized = true - this.push(END_OF_TAR) - this.push(null) -} +/***/ 4868: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Pack.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true +"use strict"; - if (err) this.emit('error', err) - this.emit('close') - if (this._stream && this._stream.destroy) this._stream.destroy() +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0; +const version_1 = __nccwpck_require__(6136); +let JS_ENV = ''; +// @ts-ignore +if (typeof Deno !== 'undefined') { + JS_ENV = 'deno'; } - -Pack.prototype._encode = function (header) { - if (!header.pax) { - var buf = headers.encode(header) - if (buf) { - this.push(buf) - return - } - } - this._encodePax(header) +else if (typeof document !== 'undefined') { + JS_ENV = 'web'; } - -Pack.prototype._encodePax = function (header) { - var paxHeader = headers.encodePax({ - name: header.name, - linkname: header.linkname, - pax: header.pax - }) - - var newHeader = { - name: 'PaxHeader', - mode: header.mode, - uid: header.uid, - gid: header.gid, - size: paxHeader.length, - mtime: header.mtime, - type: 'pax-header', - linkname: header.linkname && 'PaxHeader', - uname: header.uname, - gname: header.gname, - devmajor: header.devmajor, - devminor: header.devminor - } - - this.push(headers.encode(newHeader)) - this.push(paxHeader) - overflow(this, paxHeader.length) - - newHeader.size = header.size - newHeader.type = header.type - this.push(headers.encode(newHeader)) +else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + JS_ENV = 'react-native'; } - -Pack.prototype._read = function (n) { - var drain = this._drain - this._drain = noop - drain() +else { + JS_ENV = 'node'; } - -module.exports = Pack - +exports.DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version_1.version}` }; +exports.DEFAULT_GLOBAL_OPTIONS = { + headers: exports.DEFAULT_HEADERS, +}; +exports.DEFAULT_DB_OPTIONS = { + schema: 'public', +}; +exports.DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +}; +exports.DEFAULT_REALTIME_OPTIONS = {}; +//# sourceMappingURL=constants.js.map /***/ }), -/***/ 84256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 785: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - -var punycode = __nccwpck_require__(85477); -var mappingTable = __nccwpck_require__(72020); - -var PROCESSING_OPTIONS = { - TRANSITIONAL: 0, - NONTRANSITIONAL: 1 +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); }; +exports.resolveFetch = resolveFetch; +const resolveHeadersConstructor = () => { + return Headers; +}; +exports.resolveHeadersConstructor = resolveHeadersConstructor; +const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch = (0, exports.resolveFetch)(customFetch); + const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); + return async (input, init) => { + var _a; + const accessToken = (_a = (await getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey); + } + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`); + } + return fetch(input, Object.assign(Object.assign({}, init), { headers })); + }; +}; +exports.fetchWithAuth = fetchWithAuth; +//# sourceMappingURL=fetch.js.map -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); +/***/ 3575: +/***/ ((__unused_webpack_module, exports) => { - 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; - } - } +"use strict"; - return null; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBrowser = void 0; +exports.uuid = uuid; +exports.ensureTrailingSlash = ensureTrailingSlash; +exports.applySettingDefaults = applySettingDefaults; +exports.validateSupabaseUrl = validateSupabaseUrl; +function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); } - -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 ensureTrailingSlash(url) { + return url.endsWith('/') ? url : url + '/'; } - -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; +const isBrowser = () => typeof window !== 'undefined'; +exports.isBrowser = isBrowser; +function applySettingDefaults(options, defaults) { + var _a, _b; + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; + const result = { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + storage: {}, + global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, ((_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {})), ((_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {})) }), + accessToken: async () => '', + }; + if (options.accessToken) { + result.accessToken = options.accessToken; } - } - - 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; + else { + // hack around Required<> + delete result.accessToken; } - } - - return { - label: label, - error: error - }; + return result; } - -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; +/** + * Validates a Supabase client URL + * + * @param {string} supabaseUrl - The Supabase client URL string. + * @returns {URL} - The validated base URL. + * @throws {Error} + */ +function validateSupabaseUrl(supabaseUrl) { + const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); + if (!trimmedUrl) { + throw new Error('supabaseUrl is required.'); } - } - - 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 (!trimmedUrl.match(/^https?:\/\//i)) { + throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.'); } - }); - - if (verifyDnsLength) { - var total = labels.slice(0, labels.length - 1).join(".").length; - if (total.length > 253 || total.length === 0) { - result.error = true; + try { + return new URL(ensureTrailingSlash(trimmedUrl)); } - - for (var i=0; i < labels.length; ++i) { - if (labels.length > 63 || labels.length === 0) { - result.error = true; - break; - } + catch (_a) { + throw Error('Invalid supabaseUrl: Provided URL is malformed.'); } - } - - 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; - +} +//# sourceMappingURL=helpers.js.map /***/ }), -/***/ 4351: -/***/ ((module) => { +/***/ 6136: +/***/ ((__unused_webpack_module, exports) => { -/****************************************************************************** -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); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map /***/ }), -/***/ 74294: +/***/ 2225: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(54219); - +"use strict"; -/***/ }), -/***/ 54219: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const stringWidth = __nccwpck_require__(5537) -"use strict"; +function ansiAlign (text, opts) { + if (!text) return text + opts = opts || {} + const align = opts.align || 'center' -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); + // short-circuit `align: 'left'` as no-op + if (align === 'left') return text + const split = opts.split || '\n' + const pad = opts.pad || ' ' + const widthDiffFn = align !== 'right' ? halfDiff : fullDiff -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; + let returnString = false + if (!Array.isArray(text)) { + returnString = true + text = String(text).split(split) + } + let width + let maxWidth = 0 + text = text.map(function (str) { + str = String(str) + width = stringWidth(str) + maxWidth = Math.max(width, maxWidth) + return { + str, + width + } + }).map(function (obj) { + return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str + }) -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; + return returnString ? text.join(split) : text } -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; +ansiAlign.left = function left (text) { + return ansiAlign(text, { align: 'left' }) } -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; +ansiAlign.center = function center (text) { + return ansiAlign(text, { align: 'center' }) } -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; +ansiAlign.right = function right (text) { + return ansiAlign(text, { align: 'right' }) } +module.exports = ansiAlign -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); - }); +function halfDiff (maxWidth, curWidth) { + return Math.floor((maxWidth - curWidth) / 2) } -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)); +function fullDiff (maxWidth, curWidth) { + return maxWidth - curWidth +} - 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); - } +/***/ 140: +/***/ ((module) => { - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); - } - }); -}; +"use strict"; -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'); - } +module.exports = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); - 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(); + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; - 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(); +/***/ 3652: +/***/ ((module) => { - 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); - } +"use strict"; - 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); - } +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; -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 - }); +/***/ 5537: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} +"use strict"; +const stripAnsi = __nccwpck_require__(1411); +const isFullwidthCodePoint = __nccwpck_require__(4882); +const emojiRegex = __nccwpck_require__(3652); -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 -} +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } -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; -} + string = stripAnsi(string); + if (string.length === 0) { + return 0; + } -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 + string = string.replace(emojiRegex(), ' '); + let width = 0; -/***/ }), + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); -/***/ 68729: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } -(function(nacl) { -'use strict'; + // Surrogates + if (code > 0xFFFF) { + i++; + } -// 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/ + width += isFullwidthCodePoint(code) ? 2 : 1; + } -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; + return width; }; -// 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; -} +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports["default"] = stringWidth; -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); -} +/***/ 1411: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* -* Port of Andrew Moon's Poly1305-donna-16. Public domain. -* https://github.com/floodyberry/poly1305-donna -*/ +"use strict"; -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; -}; +const ansiRegex = __nccwpck_require__(140); -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; -}; +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; -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; - } +/***/ 3682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; - } -}; +var register = __nccwpck_require__(4670); +var addHook = __nccwpck_require__(5549); +var removeHook = __nccwpck_require__(6819); -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; -} +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); -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 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 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 HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; } -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 HookCollection() { + var state = { + registry: {}, + }; -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} + var hook = register.bind(null, state); + bindApi(hook, state); -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); + return hook; } -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; +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(); } -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; - } -} +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); -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); -} +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; -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 -]; +/***/ 5549: +/***/ ((module) => { -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; +module.exports = addHook; - bh3 = (c & 0xffff) | (d << 16); - bl3 = (a & 0xffff) | (b << 16); +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; + 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 (i%16 === 15) { - for (j = 0; j < 16; j++) { - // add - h = wh[j]; - l = wl[j]; + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} - 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))); +/***/ 4670: +/***/ ((module) => { - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +module.exports = register; - // 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))); +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (!options) { + options = {}; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - wh[j] = (c & 0xffff) | (d << 16); - wl[j] = (a & 0xffff) | (b << 16); - } - } + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - // add - h = ah0; - l = al0; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[0]; - l = hl[0]; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} - 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); +/***/ 6819: +/***/ ((module) => { - h = ah1; - l = al1; +module.exports = removeHook; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } - h = hh[1]; - l = hl[1]; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (index === -1) { + return; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + state.registry[name].splice(index, 1); +} - 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; +/***/ 2983: +/***/ ((module, exports) => { - h = hh[2]; - l = hl[2]; +// Chance.js 1.1.12 +// https://chancejs.com +// (c) 2013 Victor Quinn +// Chance may be freely distributed or modified under the MIT license. - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +(function () { - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + // Constants + var MAX_INT = 9007199254740992; + var MIN_INT = -MAX_INT; + var NUMBERS = '0123456789'; + var CHARS_LOWER = 'abcdefghijklmnopqrstuvwxyz'; + var CHARS_UPPER = CHARS_LOWER.toUpperCase(); + var HEX_POOL = NUMBERS + "abcdef"; - hh[2] = ah2 = (c & 0xffff) | (d << 16); - hl[2] = al2 = (a & 0xffff) | (b << 16); + // Errors + function UnsupportedError(message) { + this.name = 'UnsupportedError'; + this.message = message || 'This feature is not supported on this platform'; + } - h = ah3; - l = al3; + UnsupportedError.prototype = new Error(); + UnsupportedError.prototype.constructor = UnsupportedError; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + // Cached array helpers + var slice = Array.prototype.slice; - h = hh[3]; - l = hl[3]; + // Constructor + function Chance (seed) { + if (!(this instanceof Chance)) { + if (!seed) { seed = null; } // handle other non-truthy seeds, as described in issue #322 + return seed === null ? new Chance() : new Chance(seed); + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + // if user has provided a function, use that as the generator + if (typeof seed === 'function') { + this.random = seed; + return this; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + if (arguments.length) { + // set a starting value of zero so we can add to it + this.seed = 0; + } - hh[3] = ah3 = (c & 0xffff) | (d << 16); - hl[3] = al3 = (a & 0xffff) | (b << 16); + // otherwise, leave this.seed blank so that MT will receive a blank - h = ah4; - l = al4; + for (var i = 0; i < arguments.length; i++) { + var seedling = 0; + if (Object.prototype.toString.call(arguments[i]) === '[object String]') { + for (var j = 0; j < arguments[i].length; j++) { + // create a numeric hash for each argument, add to seedling + var hash = 0; + for (var k = 0; k < arguments[i].length; k++) { + hash = arguments[i].charCodeAt(k) + (hash << 6) + (hash << 16) - hash; + } + seedling += hash; + } + } else { + seedling = arguments[i]; + } + this.seed += (arguments.length - i) * seedling; + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + // If no generator function was provided, use our MT + this.mt = this.mersenne_twister(this.seed); + this.bimd5 = this.blueimp_md5(); + this.random = function () { + return this.mt.random(this.seed); + }; - h = hh[4]; - l = hl[4]; + return this; + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + Chance.prototype.VERSION = "1.1.13"; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + // Random helper functions + function initOptions(options, defaults) { + options = options || {}; - hh[4] = ah4 = (c & 0xffff) | (d << 16); - hl[4] = al4 = (a & 0xffff) | (b << 16); + if (defaults) { + for (var i in defaults) { + if (typeof options[i] === 'undefined') { + options[i] = defaults[i]; + } + } + } - h = ah5; - l = al5; + return options; + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + function range(size) { + return Array.apply(null, Array(size)).map(function (_, i) {return i;}); + } - h = hh[5]; - l = hl[5]; + function testRange(test, errorMessage) { + if (test) { + throw new RangeError(errorMessage); + } + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + /** + * Encode the input string with Base64. + */ + var base64 = function() { + throw new Error('No Base64 encoder available.'); + }; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + // Select proper Base64 encoder. + (function determineBase64Encoder() { + if (typeof btoa === 'function') { + base64 = btoa; + } else if (typeof Buffer === 'function') { + base64 = function(input) { + return new Buffer(input).toString('base64'); + }; + } + })(); - hh[5] = ah5 = (c & 0xffff) | (d << 16); - hl[5] = al5 = (a & 0xffff) | (b << 16); + // -- Basics -- - h = ah6; - l = al6; + /** + * Return a random bool, either true or false + * + * @param {Object} [options={ likelihood: 50 }] alter the likelihood of + * receiving a true or false value back. + * @throws {RangeError} if the likelihood is out of bounds + * @returns {Bool} either true or false + */ + Chance.prototype.bool = function (options) { + // likelihood of success (true) + options = initOptions(options, {likelihood : 50}); - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + // Note, we could get some minor perf optimizations by checking range + // prior to initializing defaults, but that makes code a bit messier + // and the check more complicated as we have to check existence of + // the object then existence of the key before checking constraints. + // Since the options initialization should be minor computationally, + // decision made for code cleanliness intentionally. This is mentioned + // here as it's the first occurrence, will not be mentioned again. + testRange( + options.likelihood < 0 || options.likelihood > 100, + "Chance: Likelihood accepts values from 0 to 100." + ); - h = hh[6]; - l = hl[6]; + return this.random() * 100 < options.likelihood; + }; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + Chance.prototype.falsy = function (options) { + // return a random falsy value + options = initOptions(options, {pool: [false, null, 0, NaN, '', undefined]}) + var pool = options.pool, + index = this.integer({min: 0, max: pool.length - 1}), + value = pool[index]; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + return value; + } - hh[6] = ah6 = (c & 0xffff) | (d << 16); - hl[6] = al6 = (a & 0xffff) | (b << 16); + Chance.prototype.animal = function (options){ + //returns a random animal + options = initOptions(options); - h = ah7; - l = al7; + if(typeof options.type !== 'undefined'){ + //if user does not put in a valid animal type, user will get an error + testRange( + !this.get("animals")[options.type.toLowerCase()], + "Please pick from desert, ocean, grassland, forest, zoo, pets, farm." + ); + //if user does put in valid animal type, will return a random animal of that type + return this.pick(this.get("animals")[options.type.toLowerCase()]); + } + //if user does not put in any animal type, will return a random animal regardless + var animalTypeArray = ["desert","forest","ocean","zoo","farm","pet","grassland"]; + return this.pick(this.get("animals")[this.pick(animalTypeArray)]); + }; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + /** + * Return a random character. + * + * @param {Object} [options={}] can specify a character pool or alpha, + * numeric, symbols and casing (lower or upper) + * @returns {String} a single random character + */ + Chance.prototype.character = function (options) { + options = initOptions(options); - h = hh[7]; - l = hl[7]; + var symbols = "!@#$%^&*()[]", + letters, pool; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + if (options.casing === 'lower') { + letters = CHARS_LOWER; + } else if (options.casing === 'upper') { + letters = CHARS_UPPER; + } else { + letters = CHARS_LOWER + CHARS_UPPER; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + if (options.pool) { + pool = options.pool; + } else { + pool = ''; + if (options.alpha) { + pool += letters; + } + if (options.numeric) { + pool += NUMBERS; + } + if (options.symbols) { + pool += symbols; + } + if (!pool) { + pool = letters + NUMBERS + symbols; + } + } - hh[7] = ah7 = (c & 0xffff) | (d << 16); - hl[7] = al7 = (a & 0xffff) | (b << 16); + return pool.charAt(this.natural({max: (pool.length - 1)})); + }; - pos += 128; - n -= 128; - } + // Note, wanted to use "float" or "double" but those are both JS reserved words. - return n; -} + // Note, fixed means N OR LESS digits after the decimal. This because + // It could be 14.9000 but in JavaScript, when this is cast as a number, + // the trailing zeroes are dropped. Left to the consumer if trailing zeroes are + // needed + /** + * Return a random floating point number + * + * @param {Object} [options={}] can specify a fixed precision, min, max + * @returns {Number} a single floating point number + * @throws {RangeError} Can only specify fixed or precision, not both. Also + * min cannot be greater than max + */ + Chance.prototype.floating = function (options) { + options = initOptions(options, {fixed : 4}); + testRange( + options.fixed && options.precision, + "Chance: Cannot specify both fixed and precision." + ); -function crypto_hash(out, m, n) { - var hh = new Int32Array(8), - hl = new Int32Array(8), - x = new Uint8Array(256), - i, b = n; + var num; + var fixed = Math.pow(10, options.fixed); - hh[0] = 0x6a09e667; - hh[1] = 0xbb67ae85; - hh[2] = 0x3c6ef372; - hh[3] = 0xa54ff53a; - hh[4] = 0x510e527f; - hh[5] = 0x9b05688c; - hh[6] = 0x1f83d9ab; - hh[7] = 0x5be0cd19; + var max = MAX_INT / fixed; + var min = -max; - hl[0] = 0xf3bcc908; - hl[1] = 0x84caa73b; - hl[2] = 0xfe94f82b; - hl[3] = 0x5f1d36f1; - hl[4] = 0xade682d1; - hl[5] = 0x2b3e6c1f; - hl[6] = 0xfb41bd6b; - hl[7] = 0x137e2179; + testRange( + options.min && options.fixed && options.min < min, + "Chance: Min specified is out of range with fixed. Min should be, at least, " + min + ); + testRange( + options.max && options.fixed && options.max > max, + "Chance: Max specified is out of range with fixed. Max should be, at most, " + max + ); - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; + options = initOptions(options, { min : min, max : max }); - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; + // Todo - Make this work! + // options.precision = (typeof options.precision !== "undefined") ? options.precision : false; - 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); + num = this.integer({min: options.min * fixed, max: options.max * fixed}); + var num_fixed = (num / fixed).toFixed(options.fixed); - for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); + return parseFloat(num_fixed); + }; - return 0; -} + /** + * Return a random integer + * + * NOTE the max and min are INCLUDED in the range. So: + * chance.integer({min: 1, max: 3}); + * would return either 1, 2, or 3. + * + * @param {Object} [options={}] can specify a min and/or max + * @returns {Number} a single random integer number + * @throws {RangeError} min cannot be greater than max + */ + Chance.prototype.integer = function (options) { + // 9007199254740992 (2^53) is the max integer number in JavaScript + // See: http://vq.io/132sa2j + options = initOptions(options, {min: MIN_INT, max: MAX_INT}); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); -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); - } -} + return Math.floor(this.random() * (options.max - options.min + 1) + options.min); + }; -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; -} + /** + * Return a random natural + * + * NOTE the max and min are INCLUDED in the range. So: + * chance.natural({min: 1, max: 3}); + * would return either 1, 2, or 3. + * + * @param {Object} [options={}] can specify a min and/or max or a numerals count. + * @returns {Number} a single random integer number + * @throws {RangeError} min cannot be greater than max + */ + Chance.prototype.natural = function (options) { + options = initOptions(options, {min: 0, max: MAX_INT}); + if (typeof options.numerals === 'number'){ + testRange(options.numerals < 1, "Chance: Numerals cannot be less than one."); + options.min = Math.pow(10, options.numerals - 1); + options.max = Math.pow(10, options.numerals) - 1; + } + testRange(options.min < 0, "Chance: Min cannot be less than zero."); -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); - } -} + if (options.exclude) { + testRange(!Array.isArray(options.exclude), "Chance: exclude must be an array.") -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); -} + for (var exclusionIndex in options.exclude) { + testRange(!Number.isInteger(options.exclude[exclusionIndex]), "Chance: exclude must be numbers.") + } -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; + var random = options.min + this.natural({max: options.max - options.min - options.exclude.length}) + var sortedExclusions = options.exclude.sort((a, b) => a - b); + for (var sortedExclusionIndex in sortedExclusions) { + if (random < sortedExclusions[sortedExclusionIndex]) { + break + } + random++ + } + return random + } + return this.integer(options); + }; - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; + /** + * Return a random prime number + * + * NOTE the max and min are INCLUDED in the range. + * + * @param {Object} [options={}] can specify a min and/or max + * @returns {Number} a single random prime number + * @throws {RangeError} min cannot be greater than max nor negative + */ + Chance.prototype.prime = function (options) { + options = initOptions(options, {min: 0, max: 10000}); + testRange(options.min < 0, "Chance: Min cannot be less than zero."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - scalarbase(p, d); - pack(pk, p); + var lastPrime = data.primes[data.primes.length - 1]; + if (options.max > lastPrime) { + for (var i = lastPrime + 2; i <= options.max; ++i) { + if (this.is_prime(i)) { + data.primes.push(i); + } + } + } + var targetPrimes = data.primes.filter(function (prime) { + return prime >= options.min && prime <= options.max; + }); + return this.pick(targetPrimes); + }; - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} + /** + * Determine whether a given number is prime or not. + */ + Chance.prototype.is_prime = function (n) { + if (n % 1 || n < 2) { + return false; + } + if (n % 2 === 0) { + return n === 2; + } + if (n % 3 === 0) { + return n === 3; + } + var m = Math.sqrt(n); + for (var i = 5; i <= m; i += 6) { + if (n % i === 0 || n % (i + 2) === 0) { + return false; + } + } + return true; + }; -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]); + /** + * Return a random hex number as string + * + * NOTE the max and min are INCLUDED in the range. So: + * chance.hex({min: '9', max: 'B'}); + * would return either '9', 'A' or 'B'. + * + * @param {Object} [options={}] can specify a min and/or max and/or casing + * @returns {String} a single random string hex number + * @throws {RangeError} min cannot be greater than max + */ + Chance.prototype.hex = function (options) { + options = initOptions(options, {min: 0, max: MAX_INT, casing: 'lower'}); + testRange(options.min < 0, "Chance: Min cannot be less than zero."); + var integer = this.natural({min: options.min, max: options.max}); + if (options.casing === 'upper') { + return integer.toString(16).toUpperCase(); + } + return integer.toString(16); + }; -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; + Chance.prototype.letter = function(options) { + options = initOptions(options, {casing: 'lower'}); + var pool = "abcdefghijklmnopqrstuvwxyz"; + var letter = this.character({pool: pool}); + if (options.casing === 'upper') { + letter = letter.toUpperCase(); + } + return letter; } - 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; + /** + * Return a random string + * + * @param {Object} [options={}] can specify a length or min and max + * @returns {String} a string of random length + * @throws {RangeError} length cannot be less than zero + */ + Chance.prototype.string = function (options) { + options = initOptions(options, { min: 5, max: 20 }); - 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]; + if (options.length !== 0 && !options.length) { + options.length = this.natural({ min: options.min, max: options.max }) + } - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); + testRange(options.length < 0, "Chance: Length cannot be less than zero."); + var length = options.length, + text = this.n(this.character, length, options); - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); + return text.join(""); + }; - 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]; + function CopyToken(c) { + this.c = c } - } - - 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); + CopyToken.prototype = { + substitute: function () { + return this.c + } + } - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); + function EscapeToken(c) { + this.c = c + } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); + EscapeToken.prototype = { + substitute: function () { + if (!/[{}\\]/.test(this.c)) { + throw new Error('Invalid escape sequence: "\\' + this.c + '".') + } + return this.c + } + } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; + function ReplaceToken(c) { + this.c = c + } - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + ReplaceToken.prototype = { + replacers: { + '#': function (chance) { return chance.character({ pool: NUMBERS }) }, + 'A': function (chance) { return chance.character({ pool: CHARS_UPPER }) }, + 'a': function (chance) { return chance.character({ pool: CHARS_LOWER }) }, + }, - M(r[3], r[0], r[1]); - return 0; -} + substitute: function (chance) { + var replacer = this.replacers[this.c] + if (!replacer) { + throw new Error('Invalid replacement character: "' + this.c + '".') + } + return replacer(chance) + } + } -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 -}; + function parseTemplate(template) { + var tokens = [] + var mode = 'identity' + for (var i = 0; i MAX_DUPLICATES) { + throw new RangeError("Chance: num is likely too large for sample set"); + } + } + return arr; + }; -nacl.box.after = nacl.secretbox; + /** + * Gives an array of n random terms + * + * @param {Function} fn the function that generates something random + * @param {Number} n number of terms to generate + * @returns {Array} an array of length `n` with items generated by `fn` + * + * There can be more parameters after these. All additional parameters are provided to the given function + */ + Chance.prototype.n = function(fn, n) { + testRange( + typeof fn !== "function", + "Chance: The first argument must be a function." + ); -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); -}; + if (typeof n === 'undefined') { + n = 1; + } + var i = n, arr = [], params = slice.call(arguments, 2); -nacl.box.open.after = nacl.secretbox.open; + // Providing a negative count should result in a noop. + i = Math.max( 0, i ); -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}; -}; + for (null; i--; null) { + arr.push(fn.apply(this, params)); + } -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)}; -}; + return arr; + }; -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; -}; + // H/T to SO for this one: http://vq.io/OtUrZ5 + Chance.prototype.pad = function (number, width, pad) { + // Default pad to 0 if none provided + pad = pad || '0'; + // Convert number to a string + number = number + ''; + return number.length >= width ? number : new Array(width - number.length + 1).join(pad) + number; + }; -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; -}; + // DEPRECATED on 2015-10-01 + Chance.prototype.pick = function (arr, count) { + if (arr.length === 0) { + throw new RangeError("Chance: Cannot pick() from an empty array"); + } + if (!count || count === 1) { + return arr[this.natural({max: arr.length - 1})]; + } else { + return this.shuffle(arr).slice(0, count); + } + }; -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; -}; + // Given an array, returns a single random element + Chance.prototype.pickone = function (arr) { + if (arr.length === 0) { + throw new RangeError("Chance: Cannot pickone() from an empty array"); + } + return arr[this.natural({max: arr.length - 1})]; + }; -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); -}; + // Given an array, returns a random set with 'count' elements + Chance.prototype.pickset = function (arr, count) { + if (count === 0) { + return []; + } + if (arr.length === 0) { + throw new RangeError("Chance: Cannot pickset() from an empty array"); + } + if (count < 0) { + throw new RangeError("Chance: Count must be a positive number"); + } + if (!count || count === 1) { + return [ this.pickone(arr) ]; + } else { + var array = arr.slice(0); + var end = array.length; -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}; -}; + return this.n(function () { + var index = this.natural({max: --end}); + var value = array[index]; + array[index] = array[end]; + return value; + }, Math.min(end, count)); + } + }; -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)}; -}; + Chance.prototype.shuffle = function (arr) { + var new_array = [], + j = 0, + length = Number(arr.length), + source_indexes = range(length), + last_source_index = length - 1, + selected_source_index; -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}; -}; + for (var i = 0; i < length; i++) { + // Pick a random index from the array + selected_source_index = this.natural({max: last_source_index}); + j = source_indexes[selected_source_index]; -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; + // Add it to the new array + new_array[i] = arr[j]; -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; -}; + // Mark the source index as used + source_indexes[selected_source_index] = source_indexes[last_source_index]; + last_source_index -= 1; + } -nacl.hash.hashLength = crypto_hash_BYTES; + return new_array; + }; -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; -}; + // Returns a single item from an array with relative weighting of odds + Chance.prototype.weighted = function (arr, weights, trim) { + if (arr.length !== weights.length) { + throw new RangeError("Chance: Length of array and weights must match"); + } -nacl.setPRNG = function(fn) { - randombytes = fn; -}; + // scan weights array and sum valid entries + var sum = 0; + var val; + for (var weightIndex = 0; weightIndex < weights.length; ++weightIndex) { + val = weights[weightIndex]; + if (isNaN(val)) { + throw new RangeError("Chance: All weights must be numbers"); + } -(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); - }); - } - } -})(); + if (val > 0) { + sum += val; + } + } -})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); + if (sum === 0) { + throw new RangeError("Chance: No valid entries in array weights"); + } + // select a value within range + var selected = this.random() * sum; -/***/ }), + // find array entry corresponding to selected value + var total = 0; + var lastGoodIdx = -1; + var chosenIdx; + for (weightIndex = 0; weightIndex < weights.length; ++weightIndex) { + val = weights[weightIndex]; + total += val; + if (val > 0) { + if (selected <= total) { + chosenIdx = weightIndex; + break; + } + lastGoodIdx = weightIndex; + } -/***/ 41773: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // handle any possible rounding error comparison to ensure something is picked + if (weightIndex === (weights.length - 1)) { + chosenIdx = lastGoodIdx; + } + } -"use strict"; + var chosen = arr[chosenIdx]; + trim = (typeof trim === 'undefined') ? false : trim; + if (trim) { + arr.splice(chosenIdx, 1); + weights.splice(chosenIdx, 1); + } + return chosen; + }; -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) + // -- End Helpers -- -let hasCrypto -try { - __nccwpck_require__(6113) - hasCrypto = true -} catch { - hasCrypto = false -} + // -- Text -- -Object.assign(Dispatcher.prototype, api) + Chance.prototype.paragraph = function (options) { + options = initOptions(options); -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 + var sentences = options.sentences || this.natural({min: 3, max: 7}), + sentence_array = this.n(this.sentence, sentences), + separator = options.linebreak === true ? '\n' : ' '; -module.exports.DecoratorHandler = DecoratorHandler -module.exports.RedirectHandler = RedirectHandler -module.exports.createRedirectInterceptor = createRedirectInterceptor + return sentence_array.join(separator); + }; -module.exports.buildConnector = buildConnector -module.exports.errors = errors + // Could get smarter about this than generating random words and + // chaining them together. Such as: http://vq.io/1a5ceOh + Chance.prototype.sentence = function (options) { + options = initOptions(options); -function makeDispatcher (fn) { - return (url, opts, handler) => { - if (typeof opts === 'function') { - handler = opts - opts = null - } + var words = options.words || this.natural({min: 12, max: 18}), + punctuation = options.punctuation, + text, word_array = this.n(this.word, words); - if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { - throw new InvalidArgumentError('invalid url') - } + text = word_array.join(' '); - if (opts != null && typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + // Capitalize first letter of sentence + text = this.capitalize(text); - if (opts && opts.path != null) { - if (typeof opts.path !== 'string') { - throw new InvalidArgumentError('invalid opts.path') - } + // Make sure punctuation has a usable value + if (punctuation !== false && !/^[.?;!:]$/.test(punctuation)) { + punctuation = '.'; + } - let path = opts.path - if (!opts.path.startsWith('/')) { - path = `/${path}` - } + // Add punctuation mark + if (punctuation) { + text += punctuation; + } - url = new URL(util.parseOrigin(url).origin + path) - } else { - if (!opts) { - opts = typeof url === 'object' ? url : {} - } + return text; + }; - url = util.parseURL(url) - } + Chance.prototype.syllable = function (options) { + options = initOptions(options); - const { agent, dispatcher = getGlobalDispatcher() } = opts + var length = options.length || this.natural({min: 2, max: 3}), + consonants = 'bcdfghjklmnprstvwz', // consonants except hard to speak ones + vowels = 'aeiou', // vowels + all = consonants + vowels, // all + text = '', + chr; - if (agent) { - throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') - } + // I'm sure there's a more elegant way to do this, but this works + // decently well. + for (var i = 0; i < length; i++) { + if (i === 0) { + // First character can be anything + chr = this.character({pool: all}); + } else if (consonants.indexOf(chr) === -1) { + // Last character was a vowel, now we want a consonant + chr = this.character({pool: consonants}); + } else { + // Last character was a consonant, now we want a vowel + chr = this.character({pool: vowels}); + } - 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) - } -} + text += chr; + } -module.exports.setGlobalDispatcher = setGlobalDispatcher -module.exports.getGlobalDispatcher = getGlobalDispatcher + if (options.capitalize) { + text = this.capitalize(text); + } -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) - } + return text; + }; - try { - return await fetchImpl(...arguments) - } catch (err) { - if (typeof err === 'object') { - Error.captureStackTrace(err, this) - } + Chance.prototype.word = function (options) { + options = initOptions(options); - 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 + testRange( + options.syllables && options.length, + "Chance: Cannot specify both syllables AND length." + ); - const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(71246) + var syllables = options.syllables || this.natural({min: 1, max: 3}), + text = ''; - module.exports.setGlobalOrigin = setGlobalOrigin - module.exports.getGlobalOrigin = getGlobalOrigin + if (options.length) { + // Either bound word by length + do { + text += this.syllable(); + } while (text.length < options.length); + text = text.substring(0, options.length); + } else { + // Or by number of syllables + for (var i = 0; i < syllables; i++) { + text += this.syllable(); + } + } - const { CacheStorage } = __nccwpck_require__(37907) - const { kConstruct } = __nccwpck_require__(29174) + if (options.capitalize) { + text = this.capitalize(text); + } - // 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) -} + return text; + }; -if (util.nodeMajor >= 16) { - const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(41724) + Chance.prototype.emoji = function (options) { + options = initOptions(options, { category: "all", length: 1 }); - module.exports.deleteCookie = deleteCookie - module.exports.getCookies = getCookies - module.exports.getSetCookies = getSetCookies - module.exports.setCookie = setCookie + testRange( + options.length < 1 || BigInt(options.length) > BigInt(MAX_INT), + "Chance: length must be between 1 and " + String(MAX_INT) + ); - const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) + var emojis = this.get("emojis"); - module.exports.parseMIMEType = parseMIMEType - module.exports.serializeAMimeType = serializeAMimeType -} + if (options.category === "all") { + options.category = this.pickone(Object.keys(emojis)); + } -if (util.nodeMajor >= 18 && hasCrypto) { - const { WebSocket } = __nccwpck_require__(54284) + var emojisForCategory = emojis[options.category]; - module.exports.WebSocket = WebSocket -} + testRange( + emojisForCategory === undefined, + "Chance: Unrecognised emoji category: [" + options.category + "]." + ); -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) + return this.pickset(emojisForCategory, options.length) + .map(function (codePoint) { + return String.fromCodePoint(codePoint); + }).join(""); + }; -module.exports.MockClient = MockClient -module.exports.MockPool = MockPool -module.exports.MockAgent = MockAgent -module.exports.mockErrors = mockErrors + // -- End Text -- + // -- Person -- -/***/ }), + Chance.prototype.age = function (options) { + options = initOptions(options); + var ageRange; -/***/ 7890: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + switch (options.type) { + case 'child': + ageRange = {min: 0, max: 12}; + break; + case 'teen': + ageRange = {min: 13, max: 19}; + break; + case 'adult': + ageRange = {min: 18, max: 65}; + break; + case 'senior': + ageRange = {min: 65, max: 100}; + break; + case 'all': + ageRange = {min: 0, max: 100}; + break; + default: + ageRange = {min: 18, max: 65}; + break; + } -"use strict"; + return this.natural(ageRange); + }; + Chance.prototype.birthday = function (options) { + var age = this.age(options); + var now = new Date() + var currentYear = now.getFullYear(); -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)() + if (options && options.type) { + var min = new Date(); + var max = new Date(); + min.setFullYear(currentYear - age - 1); + max.setFullYear(currentYear - age); -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') + options = initOptions(options, { + min: min, + max: max + }); + } else if (options && ((options.minAge !== undefined) || (options.maxAge !== undefined))) { + testRange(options.minAge < 0, "Chance: MinAge cannot be less than zero."); + testRange(options.minAge > options.maxAge, "Chance: MinAge cannot be greater than MaxAge."); -function defaultFactory (origin, opts) { - return opts && opts.connections === 1 - ? new Client(origin, opts) - : new Pool(origin, opts) -} + var minAge = options.minAge !== undefined ? options.minAge : 0; + var maxAge = options.maxAge !== undefined ? options.maxAge : 100; -class Agent extends DispatcherBase { - constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { - super() + var minDate = new Date(currentYear - maxAge - 1, now.getMonth(), now.getDate()); + var maxDate = new Date(currentYear - minAge, now.getMonth(), now.getDate()); - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } + minDate.setDate(minDate.getDate() +1); - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } + maxDate.setDate(maxDate.getDate() +1); + maxDate.setMilliseconds(maxDate.getMilliseconds() -1); - if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } + options = initOptions(options, { + min: minDate, + max: maxDate + }); + } else { + options = initOptions(options, { + year: currentYear - age + }); + } - if (connect && typeof connect !== 'function') { - connect = { ...connect } - } + return this.date(options); + }; - this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) - ? options.interceptors.Agent - : [createRedirectInterceptor({ maxRedirections })] + // CPF; ID to identify taxpayers in Brazil + Chance.prototype.cpf = function (options) { + options = initOptions(options, { + formatted: true + }); - 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) - } - }) + var n = this.n(this.natural, 9, { max: 9 }); + var d1 = n[8]*2+n[7]*3+n[6]*4+n[5]*5+n[4]*6+n[3]*7+n[2]*8+n[1]*9+n[0]*10; + d1 = 11 - (d1 % 11); + if (d1>=10) { + d1 = 0; + } + var d2 = d1*2+n[8]*3+n[7]*4+n[6]*5+n[5]*6+n[4]*7+n[3]*8+n[2]*9+n[1]*10+n[0]*11; + d2 = 11 - (d2 % 11); + if (d2>=10) { + d2 = 0; + } + var cpf = ''+n[0]+n[1]+n[2]+'.'+n[3]+n[4]+n[5]+'.'+n[6]+n[7]+n[8]+'-'+d1+d2; + return options.formatted ? cpf : cpf.replace(/\D/g,''); + }; - const agent = this + // CNPJ: ID to identify companies in Brazil + Chance.prototype.cnpj = function (options) { + options = initOptions(options, { + formatted: true + }); - this[kOnDrain] = (origin, targets) => { - agent.emit('drain', origin, [agent, ...targets]) - } + var n = this.n(this.natural, 12, { max: 12 }); + var d1 = n[11]*2+n[10]*3+n[9]*4+n[8]*5+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; + d1 = 11 - (d1 % 11); + if (d1<2) { + d1 = 0; + } + var d2 = d1*2+n[11]*3+n[10]*4+n[9]*5+n[8]*6+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; + d2 = 11 - (d2 % 11); + if (d2<2) { + d2 = 0; + } + var cnpj = ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/'+n[8]+n[9]+n[10]+n[11]+'-'+d1+d2; + return options.formatted ? cnpj : cnpj.replace(/\D/g,''); + }; - this[kOnConnect] = (origin, targets) => { - agent.emit('connect', origin, [agent, ...targets]) - } + Chance.prototype.first = function (options) { + options = initOptions(options, {gender: this.gender(), nationality: 'en'}); + return this.pick(this.get("firstNames")[options.gender.toLowerCase()][options.nationality.toLowerCase()]); + }; - this[kOnDisconnect] = (origin, targets, err) => { - agent.emit('disconnect', origin, [agent, ...targets], err) - } + Chance.prototype.profession = function (options) { + options = initOptions(options); + if(options.rank){ + return this.pick(['Apprentice ', 'Junior ', 'Senior ', 'Lead ']) + this.pick(this.get("profession")); + } else{ + return this.pick(this.get("profession")); + } + }; - this[kOnConnectionError] = (origin, targets, err) => { - agent.emit('connectionError', origin, [agent, ...targets], err) - } - } + Chance.prototype.company = function (){ + return this.pick(this.get("company")); + }; - 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 - } + Chance.prototype.gender = function (options) { + options = initOptions(options, {extraGenders: []}); + return this.pick(['Male', 'Female'].concat(options.extraGenders)); + }; - [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.') - } + Chance.prototype.last = function (options) { + options = initOptions(options, {nationality: '*'}); + if (options.nationality === "*") { + var allLastNames = [] + var lastNames = this.get("lastNames") + Object.keys(lastNames).forEach(function(key){ + allLastNames = allLastNames.concat(lastNames[key]) + }) + return this.pick(allLastNames) + } + else { + return this.pick(this.get("lastNames")[options.nationality.toLowerCase()]); + } - 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]) + Chance.prototype.israelId=function(){ + var x=this.string({pool: '0123456789',length:8}); + var y=0; + for (var i=0;i { + if (options.middle) { + name = first + ' ' + this.first(options) + ' ' + last; + } else if (options.middle_initial) { + name = first + ' ' + this.character({alpha: true, casing: 'upper'}) + '. ' + last; + } else { + name = first + ' ' + last; + } -const { addAbortListener } = __nccwpck_require__(83983) -const { RequestAbortedError } = __nccwpck_require__(48045) + if (options.prefix) { + name = this.prefix(options) + ' ' + name; + } -const kListener = Symbol('kListener') -const kSignal = Symbol('kSignal') + if (options.suffix) { + name = name + ' ' + this.suffix(options); + } -function abort (self) { - if (self.abort) { - self.abort() - } else { - self.onError(new RequestAbortedError()) - } -} + return name; + }; -function addSignal (self, signal) { - self[kSignal] = null - self[kListener] = null + // Return the list of available name prefixes based on supplied gender. + // @todo introduce internationalization + Chance.prototype.name_prefixes = function (gender) { + gender = gender || "all"; + gender = gender.toLowerCase(); - if (!signal) { - return - } + var prefixes = [ + { name: 'Doctor', abbreviation: 'Dr.' } + ]; - if (signal.aborted) { - abort(self) - return - } + if (gender === "male" || gender === "all") { + prefixes.push({ name: 'Mister', abbreviation: 'Mr.' }); + } - self[kSignal] = signal - self[kListener] = () => { - abort(self) - } + if (gender === "female" || gender === "all") { + prefixes.push({ name: 'Miss', abbreviation: 'Miss' }); + prefixes.push({ name: 'Misses', abbreviation: 'Mrs.' }); + } - addAbortListener(self[kSignal], self[kListener]) -} + return prefixes; + }; -function removeSignal (self) { - if (!self[kSignal]) { - return - } + // Alias for name_prefix + Chance.prototype.prefix = function (options) { + return this.name_prefix(options); + }; - if ('removeEventListener' in self[kSignal]) { - self[kSignal].removeEventListener('abort', self[kListener]) - } else { - self[kSignal].removeListener('abort', self[kListener]) - } + Chance.prototype.name_prefix = function (options) { + options = initOptions(options, { gender: "all" }); + return options.full ? + this.pick(this.name_prefixes(options.gender)).name : + this.pick(this.name_prefixes(options.gender)).abbreviation; + }; + //Hungarian ID number + Chance.prototype.HIDN= function(){ + //Hungarian ID nuber structure: XXXXXXYY (X=number,Y=Capital Latin letter) + var idn_pool="0123456789"; + var idn_chrs="ABCDEFGHIJKLMNOPQRSTUVWXYXZ"; + var idn=""; + idn+=this.string({pool:idn_pool,length:6}); + idn+=this.string({pool:idn_chrs,length:2}); + return idn; + }; - self[kSignal] = null - self[kListener] = null -} -module.exports = { - addSignal, - removeSignal -} + Chance.prototype.ssn = function (options) { + options = initOptions(options, {ssnFour: false, dashes: true}); + var ssn_pool = "1234567890", + ssn, + dash = options.dashes ? '-' : ''; + if(!options.ssnFour) { + ssn = this.string({pool: ssn_pool, length: 3}) + dash + + this.string({pool: ssn_pool, length: 2}) + dash + + this.string({pool: ssn_pool, length: 4}); + } else { + ssn = this.string({pool: ssn_pool, length: 4}); + } + return ssn; + }; -/***/ }), + // Aadhar is similar to ssn, used in India to uniquely identify a person + Chance.prototype.aadhar = function (options) { + options = initOptions(options, {onlyLastFour: false, separatedByWhiteSpace: true}); + var aadhar_pool = "1234567890", + aadhar, + whiteSpace = options.separatedByWhiteSpace ? ' ' : ''; -/***/ 29744: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if(!options.onlyLastFour) { + aadhar = this.string({pool: aadhar_pool, length: 4}) + whiteSpace + + this.string({pool: aadhar_pool, length: 4}) + whiteSpace + + this.string({pool: aadhar_pool, length: 4}); + } else { + aadhar = this.string({pool: aadhar_pool, length: 4}); + } + return aadhar; + }; -"use strict"; + // Return the list of available name suffixes + // @todo introduce internationalization + Chance.prototype.name_suffixes = function () { + var suffixes = [ + { name: 'Doctor of Osteopathic Medicine', abbreviation: 'D.O.' }, + { name: 'Doctor of Philosophy', abbreviation: 'Ph.D.' }, + { name: 'Esquire', abbreviation: 'Esq.' }, + { name: 'Junior', abbreviation: 'Jr.' }, + { name: 'Juris Doctor', abbreviation: 'J.D.' }, + { name: 'Master of Arts', abbreviation: 'M.A.' }, + { name: 'Master of Business Administration', abbreviation: 'M.B.A.' }, + { name: 'Master of Science', abbreviation: 'M.S.' }, + { name: 'Medical Doctor', abbreviation: 'M.D.' }, + { name: 'Senior', abbreviation: 'Sr.' }, + { name: 'The Third', abbreviation: 'III' }, + { name: 'The Fourth', abbreviation: 'IV' }, + { name: 'Bachelor of Engineering', abbreviation: 'B.E' }, + { name: 'Bachelor of Technology', abbreviation: 'B.TECH' } + ]; + return suffixes; + }; + // Alias for name_suffix + Chance.prototype.suffix = function (options) { + return this.name_suffix(options); + }; -const { AsyncResource } = __nccwpck_require__(50852) -const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(48045) -const util = __nccwpck_require__(83983) -const { addSignal, removeSignal } = __nccwpck_require__(7032) + Chance.prototype.name_suffix = function (options) { + options = initOptions(options); + return options.full ? + this.pick(this.name_suffixes()).name : + this.pick(this.name_suffixes()).abbreviation; + }; -class ConnectHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + Chance.prototype.nationalities = function () { + return this.get("nationalities"); + }; - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + // Generate random nationality based on json list + Chance.prototype.nationality = function () { + var nationality = this.pick(this.nationalities()); + return nationality.name; + }; - const { signal, opaque, responseHeaders } = opts + // Generate random zodiac sign + Chance.prototype.zodiac = function () { + const zodiacSymbols = ["Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn","Aquarius","Pisces"]; + return this.pickone(zodiacSymbols); + }; - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - super('UNDICI_CONNECT') + // -- End Person -- - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.callback = callback - this.abort = null + // -- Mobile -- + // Android GCM Registration ID + Chance.prototype.android_id = function () { + return "APA91" + this.string({ pool: "0123456789abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_", length: 178 }); + }; - addSignal(this, signal) - } + // Apple Push Token + Chance.prototype.apple_token = function () { + return this.string({ pool: "abcdef1234567890", length: 64 }); + }; - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } + // Windows Phone 8 ANID2 + Chance.prototype.wp8_anid2 = function () { + return base64( this.hash( { length : 32 } ) ); + }; - this.abort = abort - this.context = context - } + // Windows Phone 7 ANID + Chance.prototype.wp7_anid = function () { + return 'A=' + this.guid().replace(/-/g, '').toUpperCase() + '&E=' + this.hash({ length:3 }) + '&W=' + this.integer({ min:0, max:9 }); + }; - onHeaders () { - throw new SocketError('bad connect', null) - } + // BlackBerry Device PIN + Chance.prototype.bb_pin = function () { + return this.hash({ length: 8 }); + }; - onUpgrade (statusCode, rawHeaders, socket) { - const { callback, opaque, context } = this + // -- End Mobile -- - removeSignal(this) + // -- Web -- + Chance.prototype.avatar = function (options) { + var url = null; + var URL_BASE = '//www.gravatar.com/avatar/'; + var PROTOCOLS = { + http: 'http', + https: 'https' + }; + var FILE_TYPES = { + bmp: 'bmp', + gif: 'gif', + jpg: 'jpg', + png: 'png' + }; + var FALLBACKS = { + '404': '404', // Return 404 if not found + mm: 'mm', // Mystery man + identicon: 'identicon', // Geometric pattern based on hash + monsterid: 'monsterid', // A generated monster icon + wavatar: 'wavatar', // A generated face + retro: 'retro', // 8-bit icon + blank: 'blank' // A transparent png + }; + var RATINGS = { + g: 'g', + pg: 'pg', + r: 'r', + x: 'x' + }; + var opts = { + protocol: null, + email: null, + fileExtension: null, + size: null, + fallback: null, + rating: null + }; - this.callback = null + if (!options) { + // Set to a random email + opts.email = this.email(); + options = {}; + } + else if (typeof options === 'string') { + opts.email = options; + options = {}; + } + else if (typeof options !== 'object') { + return null; + } + else if (options.constructor === 'Array') { + return null; + } - let headers = rawHeaders - // Indicates is an HTTP2Session - if (headers != null) { - headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - } + opts = initOptions(options, opts); - this.runInAsyncScope(callback, null, null, { - statusCode, - headers, - socket, - opaque, - context - }) - } + if (!opts.email) { + // Set to a random email + opts.email = this.email(); + } - onError (err) { - const { callback, opaque } = this + // Safe checking for params + opts.protocol = PROTOCOLS[opts.protocol] ? opts.protocol + ':' : ''; + opts.size = parseInt(opts.size, 0) ? opts.size : ''; + opts.rating = RATINGS[opts.rating] ? opts.rating : ''; + opts.fallback = FALLBACKS[opts.fallback] ? opts.fallback : ''; + opts.fileExtension = FILE_TYPES[opts.fileExtension] ? opts.fileExtension : ''; - removeSignal(this) + url = + opts.protocol + + URL_BASE + + this.bimd5.md5(opts.email) + + (opts.fileExtension ? '.' + opts.fileExtension : '') + + (opts.size || opts.rating || opts.fallback ? '?' : '') + + (opts.size ? '&s=' + opts.size.toString() : '') + + (opts.rating ? '&r=' + opts.rating : '') + + (opts.fallback ? '&d=' + opts.fallback : '') + ; - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - } -} + return url; + }; -function connect (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - connect.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } + /** + * #Description: + * =============================================== + * Generate random color value base on color type: + * -> hex + * -> rgb + * -> rgba + * -> 0x + * -> named color + * + * #Examples: + * =============================================== + * * Geerate random hex color + * chance.color() => '#79c157' / 'rgb(110,52,164)' / '0x67ae0b' / '#e2e2e2' / '#29CFA7' + * + * * Generate Hex based color value + * chance.color({format: 'hex'}) => '#d67118' + * + * * Generate simple rgb value + * chance.color({format: 'rgb'}) => 'rgb(110,52,164)' + * + * * Generate Ox based color value + * chance.color({format: '0x'}) => '0x67ae0b' + * + * * Generate graiscale based value + * chance.color({grayscale: true}) => '#e2e2e2' + * + * * Return valide color name + * chance.color({format: 'name'}) => 'red' + * + * * Make color uppercase + * chance.color({casing: 'upper'}) => '#29CFA7' + * + * * Min Max values for RGBA + * var light_red = chance.color({format: 'hex', min_red: 200, max_red: 255, max_green: 0, max_blue: 0, min_alpha: .2, max_alpha: .3}); + * + * @param [object] options + * @return [string] color value + */ + Chance.prototype.color = function (options) { + function gray(value, delimiter) { + return [value, value, value].join(delimiter || ''); + } - 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 })) - } -} + function rgb(hasAlpha) { + var rgbValue = (hasAlpha) ? 'rgba' : 'rgb'; + var alphaChannel = (hasAlpha) ? (',' + this.floating({min:min_alpha, max:max_alpha})) : ""; + var colorValue = (isGrayscale) ? (gray(this.natural({min: min_rgb, max: max_rgb}), ',')) : (this.natural({min: min_green, max: max_green}) + ',' + this.natural({min: min_blue, max: max_blue}) + ',' + this.natural({max: 255})); + return rgbValue + '(' + colorValue + alphaChannel + ')'; + } -module.exports = connect + function hex(start, end, withHash) { + var symbol = (withHash) ? "#" : ""; + var hexstring = ""; + if (isGrayscale) { + hexstring = gray(this.pad(this.hex({min: min_rgb, max: max_rgb}), 2)); + if (options.format === "shorthex") { + hexstring = gray(this.hex({min: 0, max: 15})); + } + } + else { + if (options.format === "shorthex") { + hexstring = this.pad(this.hex({min: Math.floor(min_red / 16), max: Math.floor(max_red / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_green / 16), max: Math.floor(max_green / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_blue / 16), max: Math.floor(max_blue / 16)}), 1); + } + else if (min_red !== undefined || max_red !== undefined || min_green !== undefined || max_green !== undefined || min_blue !== undefined || max_blue !== undefined) { + hexstring = this.pad(this.hex({min: min_red, max: max_red}), 2) + this.pad(this.hex({min: min_green, max: max_green}), 2) + this.pad(this.hex({min: min_blue, max: max_blue}), 2); + } + else { + hexstring = this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2); + } + } -/***/ }), + return symbol + hexstring; + } -/***/ 28752: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + options = initOptions(options, { + format: this.pick(['hex', 'shorthex', 'rgb', 'rgba', '0x', 'name']), + grayscale: false, + casing: 'lower', + min: 0, + max: 255, + min_red: undefined, + max_red: undefined, + min_green: undefined, + max_green: undefined, + min_blue: undefined, + max_blue: undefined, + min_alpha: 0, + max_alpha: 1 + }); -"use strict"; + var isGrayscale = options.grayscale; + var min_rgb = options.min; + var max_rgb = options.max; + var min_red = options.min_red; + var max_red = options.max_red; + var min_green = options.min_green; + var max_green = options.max_green; + var min_blue = options.min_blue; + var max_blue = options.max_blue; + var min_alpha = options.min_alpha; + var max_alpha = options.max_alpha; + if (options.min_red === undefined) { min_red = min_rgb; } + if (options.max_red === undefined) { max_red = max_rgb; } + if (options.min_green === undefined) { min_green = min_rgb; } + if (options.max_green === undefined) { max_green = max_rgb; } + if (options.min_blue === undefined) { min_blue = min_rgb; } + if (options.max_blue === undefined) { max_blue = max_rgb; } + if (options.min_alpha === undefined) { min_alpha = 0; } + if (options.max_alpha === undefined) { max_alpha = 1; } + if (isGrayscale && min_rgb === 0 && max_rgb === 255 && min_red !== undefined && max_red !== undefined) { + min_rgb = ((min_red + min_green + min_blue) / 3); + max_rgb = ((max_red + max_green + max_blue) / 3); + } + var colorValue; + if (options.format === 'hex') { + colorValue = hex.call(this, 2, 6, true); + } + else if (options.format === 'shorthex') { + colorValue = hex.call(this, 1, 3, true); + } + else if (options.format === 'rgb') { + colorValue = rgb.call(this, false); + } + else if (options.format === 'rgba') { + colorValue = rgb.call(this, true); + } + else if (options.format === '0x') { + colorValue = '0x' + hex.call(this, 2, 6); + } + else if(options.format === 'name') { + return this.pick(this.get("colorNames")); + } + else { + throw new RangeError('Invalid format provided. Please provide one of "hex", "shorthex", "rgb", "rgba", "0x" or "name".'); + } -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) + if (options.casing === 'upper' ) { + colorValue = colorValue.toUpperCase(); + } -const kResume = Symbol('resume') + return colorValue; + }; -class PipelineRequest extends Readable { - constructor () { - super({ autoDestroy: true }) + Chance.prototype.domain = function (options) { + options = initOptions(options); + return this.word() + '.' + (options.tld || this.tld()); + }; - this[kResume] = null - } + Chance.prototype.email = function (options) { + options = initOptions(options); + return this.word({length: options.length}) + '@' + (options.domain || this.domain()); + }; - _read () { - const { [kResume]: resume } = this + /** + * #Description: + * =============================================== + * Generate a random Facebook id, aka fbid. + * + * NOTE: At the moment (Sep 2017), Facebook ids are + * "numeric strings" of length 16. + * However, Facebook Graph API documentation states that + * "it is extremely likely to change over time". + * @see https://developers.facebook.com/docs/graph-api/overview/ + * + * #Examples: + * =============================================== + * chance.fbid() => '1000035231661304' + * + * @return [string] facebook id + */ + Chance.prototype.fbid = function () { + return '10000' + this.string({pool: "1234567890", length: 11}); + }; - if (resume) { - this[kResume] = null - resume() - } - } + Chance.prototype.google_analytics = function () { + var account = this.pad(this.natural({max: 999999}), 6); + var property = this.pad(this.natural({max: 99}), 2); - _destroy (err, callback) { - this._read() + return 'UA-' + account + '-' + property; + }; - callback(err) - } -} + Chance.prototype.hashtag = function () { + return '#' + this.word(); + }; -class PipelineResponse extends Readable { - constructor (resume) { - super({ autoDestroy: true }) - this[kResume] = resume - } + Chance.prototype.ip = function () { + // Todo: This could return some reserved IPs. See http://vq.io/137dgYy + // this should probably be updated to account for that rare as it may be + return this.natural({min: 1, max: 254}) + '.' + + this.natural({max: 255}) + '.' + + this.natural({max: 255}) + '.' + + this.natural({min: 1, max: 254}); + }; - _read () { - this[kResume]() - } + Chance.prototype.ipv6 = function () { + var ip_addr = this.n(this.hash, 8, {length: 4}); - _destroy (err, callback) { - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } + return ip_addr.join(":"); + }; - callback(err) - } -} + Chance.prototype.klout = function () { + return this.natural({min: 1, max: 99}); + }; -class PipelineHandler extends AsyncResource { - constructor (opts, handler) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + Chance.prototype.mac = function (options) { + // Todo: This could also be extended to EUI-64 based MACs + // (https://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml#ethernet-numbers-4) + // Todo: This can return some reserved MACs (similar to IP function) + // this should probably be updated to account for that rare as it may be + options = initOptions(options, { delimiter: ':' }); + return this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2); + }; - if (typeof handler !== 'function') { - throw new InvalidArgumentError('invalid handler') - } + Chance.prototype.semver = function (options) { + options = initOptions(options, { include_prerelease: true }); - const { signal, method, opaque, onInfo, responseHeaders } = opts + var range = this.pickone(["^", "~", "<", ">", "<=", ">=", "="]); + if (options.range) { + range = options.range; + } - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } + var prerelease = ""; + if (options.include_prerelease) { + prerelease = this.weighted(["", "-dev", "-beta", "-alpha"], [50, 10, 5, 1]); + } + return range + this.rpg('3d10').join('.') + prerelease; + }; - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } + Chance.prototype.tlds = function () { + return ['com', 'org', 'edu', 'gov', 'co.uk', 'net', 'io', 'ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as', 'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bv', 'bw', 'by', 'bz', 'ca', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr', 'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'ee', 'eg', 'eh', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo', 'fr', 'ga', 'gb', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht', 'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je', 'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw', 'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv', 'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo', 'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om', 'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt', 'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sj', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st', 'su', 'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us', 'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye', 'yt', 'za', 'zm', 'zw']; + }; - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } + Chance.prototype.tld = function () { + return this.pick(this.tlds()); + }; - super('UNDICI_PIPELINE') + Chance.prototype.twitter = function () { + return '@' + this.word(); + }; - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.handler = handler - this.abort = null - this.context = null - this.onInfo = onInfo || null + Chance.prototype.url = function (options) { + options = initOptions(options, { protocol: "http", domain: this.domain(options), domain_prefix: "", path: this.word(), extensions: []}); - this.req = new PipelineRequest().on('error', util.nop) + var extension = options.extensions.length > 0 ? "." + this.pick(options.extensions) : ""; + var domain = options.domain_prefix ? options.domain_prefix + "." + options.domain : options.domain; - this.ret = new Duplex({ - readableObjectMode: opts.objectMode, - autoDestroy: true, - read: () => { - const { body } = this + return options.protocol + "://" + domain + "/" + options.path + extension; + }; - if (body && body.resume) { - body.resume() - } - }, - write: (chunk, encoding, callback) => { - const { req } = this + Chance.prototype.port = function() { + return this.integer({min: 0, max: 65535}); + }; - if (req.push(chunk, encoding) || req._readableState.destroyed) { - callback() + Chance.prototype.locale = function (options) { + options = initOptions(options); + if (options.region){ + return this.pick(this.get("locale_regions")); } else { - req[kResume] = callback + return this.pick(this.get("locale_languages")); } - }, - destroy: (err, callback) => { - const { body, req, res, ret, abort } = this + }; - if (!err && !ret._readableState.endEmitted) { - err = new RequestAbortedError() - } + Chance.prototype.locales = function (options) { + options = initOptions(options); + if (options.region){ + return this.get("locale_regions"); + } else { + return this.get("locale_languages"); + } + }; - if (abort && err) { - abort() - } + Chance.prototype.loremPicsum = function (options) { + options = initOptions(options, { width: 500, height: 500, greyscale: false, blurred: false }); - util.destroy(body, err) - util.destroy(req, err) - util.destroy(res, err) + var greyscale = options.greyscale ? 'g/' : ''; + var query = options.blurred ? '/?blur' : '/?random'; - removeSignal(this) + return 'https://picsum.photos/' + greyscale + options.width + '/' + options.height + query; + } - callback(err) - } - }).on('prefinish', () => { - const { req } = this + // -- End Web -- - // Node < 15 does not call _final in same tick. - req.push(null) - }) + // -- Location -- - this.res = null + Chance.prototype.address = function (options) { + options = initOptions(options); + return this.natural({min: 5, max: 2000}) + ' ' + this.street(options); + }; - addSignal(this, signal) - } + Chance.prototype.altitude = function (options) { + options = initOptions(options, {fixed: 5, min: 0, max: 8848}); + return this.floating({ + min: options.min, + max: options.max, + fixed: options.fixed + }); + }; - onConnect (abort, context) { - const { ret, res } = this + Chance.prototype.areacode = function (options) { + options = initOptions(options, {parens : true}); + // Don't want area codes to start with 1, or have a 9 as the second digit + var areacode = options.exampleNumber ? + "555" : + this.natural({min: 2, max: 9}).toString() + + this.natural({min: 0, max: 8}).toString() + + this.natural({min: 0, max: 9}).toString(); - assert(!res, 'pipeline cannot be retried') + return options.parens ? '(' + areacode + ')' : areacode; + }; - if (ret.destroyed) { - throw new RequestAbortedError() - } + Chance.prototype.city = function () { + return this.capitalize(this.word({syllables: 3})); + }; - this.abort = abort - this.context = context - } + Chance.prototype.coordinates = function (options) { + return this.latitude(options) + ', ' + this.longitude(options); + }; - onHeaders (statusCode, rawHeaders, resume) { - const { opaque, handler, context } = this + Chance.prototype.countries = function () { + return this.get("countries"); + }; - if (statusCode < 200) { - if (this.onInfo) { - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.onInfo({ statusCode, headers }) - } - return - } + Chance.prototype.country = function (options) { + options = initOptions(options); + var country = this.pick(this.countries()); + return options.raw ? country : options.full ? country.name : country.abbreviation; + }; - this.res = new PipelineResponse(resume) + Chance.prototype.depth = function (options) { + options = initOptions(options, {fixed: 5, min: -10994, max: 0}); + return this.floating({ + min: options.min, + max: options.max, + fixed: options.fixed + }); + }; - 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 - } + Chance.prototype.geohash = function (options) { + options = initOptions(options, { length: 7 }); + return this.string({ length: options.length, pool: '0123456789bcdefghjkmnpqrstuvwxyz' }); + }; - if (!body || typeof body.on !== 'function') { - throw new InvalidReturnValueError('expected Readable') - } + Chance.prototype.geojson = function (options) { + return this.latitude(options) + ', ' + this.longitude(options) + ', ' + this.altitude(options); + }; - body - .on('data', (chunk) => { - const { ret, body } = this + Chance.prototype.latitude = function (options) { + // Constants - Formats + var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; + + options = initOptions( +options, + options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? + {min: 0, max: 89, fixed: 4} : + {fixed: 5, min: -90, max: 90, format: DD} +); + + var format = options.format.toLowerCase(); + + if (format === DDM || format === DMS) { + testRange(options.min < 0 || options.min > 89, "Chance: Min specified is out of range. Should be between 0 - 89"); + testRange(options.max < 0 || options.max > 89, "Chance: Max specified is out of range. Should be between 0 - 89"); + testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); + } - if (!ret.push(chunk) && body.pause) { - body.pause() + switch (format) { + case DDM: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.floating({min: 0, max: 59, fixed: options.fixed}); + } + case DMS: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.integer({min: 0, max: 59}) + '’' + + this.floating({min: 0, max: 59, fixed: options.fixed}) + 'ā€'; + } + case DD: + default: { + return this.floating({min: options.min, max: options.max, fixed: options.fixed}); + } } - }) - .on('error', (err) => { - const { ret } = this + }; - util.destroy(ret, err) - }) - .on('end', () => { - const { ret } = this + Chance.prototype.longitude = function (options) { + // Constants - Formats + var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; - ret.push(null) - }) - .on('close', () => { - const { ret } = this + options = initOptions( +options, + options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? + {min: 0, max: 179, fixed: 4} : + {fixed: 5, min: -180, max: 180, format: DD} +); - if (!ret._readableState.ended) { - util.destroy(ret, new RequestAbortedError()) + var format = options.format.toLowerCase(); + + if (format === DDM || format === DMS) { + testRange(options.min < 0 || options.min > 179, "Chance: Min specified is out of range. Should be between 0 - 179"); + testRange(options.max < 0 || options.max > 179, "Chance: Max specified is out of range. Should be between 0 - 179"); + testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); } - }) - this.body = body - } + switch (format) { + case DDM: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.floating({min: 0, max: 59.9999, fixed: options.fixed}) + } + case DMS: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.integer({min: 0, max: 59}) + '’' + + this.floating({min: 0, max: 59.9999, fixed: options.fixed}) + 'ā€'; + } + case DD: + default: { + return this.floating({min: options.min, max: options.max, fixed: options.fixed}); + } + } + }; - onData (chunk) { - const { res } = this - return res.push(chunk) - } + Chance.prototype.phone = function (options) { + var self = this, + numPick, + ukNum = function (parts) { + var section = []; + //fills the section part of the phone number with random numbers. + parts.sections.forEach(function(n) { + section.push(self.string({ pool: '0123456789', length: n})); + }); + return parts.area + section.join(' '); + }; + options = initOptions(options, { + formatted: true, + country: 'us', + mobile: false, + exampleNumber: false, + }); + if (!options.formatted) { + options.parens = false; + } + var phone; + switch (options.country) { + case 'fr': + if (!options.mobile) { + numPick = this.pick([ + // Valid zone and dĆ©partement codes. + '01' + this.pick(['30', '34', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '53', '55', '56', '58', '60', '64', '69', '70', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83']) + self.string({ pool: '0123456789', length: 6}), + '02' + this.pick(['14', '18', '22', '23', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '40', '41', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '56', '57', '61', '62', '69', '72', '76', '77', '78', '85', '90', '96', '97', '98', '99']) + self.string({ pool: '0123456789', length: 6}), + '03' + this.pick(['10', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '39', '44', '45', '51', '52', '54', '55', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90']) + self.string({ pool: '0123456789', length: 6}), + '04' + this.pick(['11', '13', '15', '20', '22', '26', '27', '30', '32', '34', '37', '42', '43', '44', '50', '56', '57', '63', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '88', '89', '90', '91', '92', '93', '94', '95', '97', '98']) + self.string({ pool: '0123456789', length: 6}), + '05' + this.pick(['08', '16', '17', '19', '24', '31', '32', '33', '34', '35', '40', '45', '46', '47', '49', '53', '55', '56', '57', '58', '59', '61', '62', '63', '64', '65', '67', '79', '81', '82', '86', '87', '90', '94']) + self.string({ pool: '0123456789', length: 6}), + '09' + self.string({ pool: '0123456789', length: 8}), + ]); + phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; + } else { + numPick = this.pick(['06', '07']) + self.string({ pool: '0123456789', length: 8}); + phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; + } + break; + case 'uk': + if (!options.mobile) { + numPick = this.pick([ + //valid area codes of major cities/counties followed by random numbers in required format. - onComplete (trailers) { - const { res } = this - res.push(null) - } + { area: '01' + this.character({ pool: '234569' }) + '1 ', sections: [3,4] }, + { area: '020 ' + this.character({ pool: '378' }), sections: [3,4] }, + { area: '023 ' + this.character({ pool: '89' }), sections: [3,4] }, + { area: '024 7', sections: [3,4] }, + { area: '028 ' + this.pick(['25','28','37','71','82','90','92','95']), sections: [2,4] }, + { area: '012' + this.pick(['04','08','54','76','97','98']) + ' ', sections: [6] }, + { area: '013' + this.pick(['63','64','84','86']) + ' ', sections: [6] }, + { area: '014' + this.pick(['04','20','60','61','80','88']) + ' ', sections: [6] }, + { area: '015' + this.pick(['24','27','62','66']) + ' ', sections: [6] }, + { area: '016' + this.pick(['06','29','35','47','59','95']) + ' ', sections: [6] }, + { area: '017' + this.pick(['26','44','50','68']) + ' ', sections: [6] }, + { area: '018' + this.pick(['27','37','84','97']) + ' ', sections: [6] }, + { area: '019' + this.pick(['00','05','35','46','49','63','95']) + ' ', sections: [6] } + ]); + phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', '', 'g'); + } else { + numPick = this.pick([ + { area: '07' + this.pick(['4','5','7','8','9']), sections: [2,6] }, + { area: '07624 ', sections: [6] } + ]); + phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', ''); + } + break; + case 'za': + if (!options.mobile) { + numPick = this.pick([ + '01' + this.pick(['0', '1', '2', '3', '4', '5', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), + '02' + this.pick(['1', '2', '3', '4', '7', '8']) + self.string({ pool: '0123456789', length: 7}), + '03' + this.pick(['1', '2', '3', '5', '6', '9']) + self.string({ pool: '0123456789', length: 7}), + '04' + this.pick(['1', '2', '3', '4', '5','6','7', '8','9']) + self.string({ pool: '0123456789', length: 7}), + '05' + this.pick(['1', '3', '4', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), + ]); + phone = options.formatted || numPick; + } else { + numPick = this.pick([ + '060' + this.pick(['3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), + '061' + this.pick(['0','1','2','3','4','5','8']) + self.string({ pool: '0123456789', length: 6}), + '06' + self.string({ pool: '0123456789', length: 7}), + '071' + this.pick(['0','1','2','3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), + '07' + this.pick(['2','3','4','6','7','8','9']) + self.string({ pool: '0123456789', length: 7}), + '08' + this.pick(['0','1','2','3','4','5']) + self.string({ pool: '0123456789', length: 7}), + ]); + phone = options.formatted || numPick; + } + break; + case 'us': + var areacode = this.areacode(options).toString(); + var exchange = this.natural({ min: 2, max: 9 }).toString() + + this.natural({ min: 0, max: 9 }).toString() + + this.natural({ min: 0, max: 9 }).toString(); + var subscriber = this.natural({ min: 1000, max: 9999 }).toString(); // this could be random [0-9]{4} + phone = options.formatted ? areacode + ' ' + exchange + '-' + subscriber : areacode + exchange + subscriber; + break; + case 'br': + var areaCode = this.pick(["11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "24", "27", "28", "31", "32", "33", "34", "35", "37", "38", "41", "42", "43", "44", "45", "46", "47", "48", "49", "51", "53", "54", "55", "61", "62", "63", "64", "65", "66", "67", "68", "69", "71", "73", "74", "75", "77", "79", "81", "82", "83", "84", "85", "86", "87", "88", "89", "91", "92", "93", "94", "95", "96", "97", "98", "99"]); + var prefix; + if (options.mobile) { + // Brasilian official reference (mobile): http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=330 + prefix = '9' + self.string({ pool: '0123456789', length: 4}); + } else { + // Brasilian official reference: http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=331 + prefix = this.natural({ min: 2000, max: 5999 }).toString(); + } + var mcdu = self.string({ pool: '0123456789', length: 4}); + phone = options.formatted ? '(' + areaCode + ') ' + prefix + '-' + mcdu : areaCode + prefix + mcdu; + break; + } + return phone; + }; - onError (err) { - const { ret } = this - this.handler = null - util.destroy(ret, err) - } -} + Chance.prototype.postal = function () { + // Postal District + var pd = this.character({pool: "XVTSRPNKLMHJGECBA"}); + // Forward Sortation Area (FSA) + var fsa = pd + this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}); + // Local Delivery Unut (LDU) + var ldu = this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}) + this.natural({max: 9}); -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) - } -} + return fsa + " " + ldu; + }; -module.exports = pipeline + Chance.prototype.postcode = function () { + // Area + var area = this.pick(this.get("postcodeAreas")).code; + // District + var district = this.natural({max: 9}); + // Sub-District + var subDistrict = this.bool() ? this.character({alpha: true, casing: "upper"}) : ""; + // Outward Code + var outward = area + district + subDistrict; + // Sector + var sector = this.natural({max: 9}); + // Unit + var unit = this.character({alpha: true, casing: "upper"}) + this.character({alpha: true, casing: "upper"}); + // Inward Code + var inward = sector + unit; + return outward + " " + inward; + }; -/***/ }), + Chance.prototype.counties = function (options) { + options = initOptions(options, { country: 'uk' }); + return this.get("counties")[options.country.toLowerCase()]; + }; -/***/ 55448: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Chance.prototype.county = function (options) { + return this.pick(this.counties(options)).name; + }; -"use strict"; + Chance.prototype.provinces = function (options) { + options = initOptions(options, { country: 'ca' }); + return this.get("provinces")[options.country.toLowerCase()]; + }; + Chance.prototype.province = function (options) { + return (options && options.full) ? + this.pick(this.provinces(options)).name : + this.pick(this.provinces(options)).abbreviation; + }; -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) + Chance.prototype.state = function (options) { + return (options && options.full) ? + this.pick(this.states(options)).name : + this.pick(this.states(options)).abbreviation; + }; -class RequestHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + Chance.prototype.states = function (options) { + options = initOptions(options, { country: 'us', us_states_and_dc: true } ); - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts + var states; - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + switch (options.country.toLowerCase()) { + case 'us': + var us_states_and_dc = this.get("us_states_and_dc"), + territories = this.get("territories"), + armed_forces = this.get("armed_forces"); - if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { - throw new InvalidArgumentError('invalid highWaterMark') - } + states = []; - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } + if (options.us_states_and_dc) { + states = states.concat(us_states_and_dc); + } + if (options.territories) { + states = states.concat(territories); + } + if (options.armed_forces) { + states = states.concat(armed_forces); + } + break; + case 'it': + case 'mx': + states = this.get("country_regions")[options.country.toLowerCase()]; + break; + case 'uk': + states = this.get("counties")[options.country.toLowerCase()]; + break; + } - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } + return states; + }; - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } + Chance.prototype.street = function (options) { + options = initOptions(options, { country: 'us', syllables: 2 }); + var street; - super('UNDICI_REQUEST') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } + switch (options.country.toLowerCase()) { + case 'us': + street = this.word({ syllables: options.syllables }); + street = this.capitalize(street); + street += ' '; + street += options.short_suffix ? + this.street_suffix(options).abbreviation : + this.street_suffix(options).name; + break; + case 'it': + street = this.word({ syllables: options.syllables }); + street = this.capitalize(street); + street = (options.short_suffix ? + this.street_suffix(options).abbreviation : + this.street_suffix(options).name) + " " + street; + break; + } + return street; + }; - 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 + Chance.prototype.street_suffix = function (options) { + options = initOptions(options, { country: 'us' }); + return this.pick(this.street_suffixes(options)); + }; - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) - } + Chance.prototype.street_suffixes = function (options) { + options = initOptions(options, { country: 'us' }); + // These are the most common suffixes. + return this.get("street_suffixes")[options.country.toLowerCase()]; + }; - addSignal(this, signal) - } + // Note: only returning US zip codes, internationalization will be a whole + // other beast to tackle at some point. + Chance.prototype.zip = function (options) { + var zip = this.n(this.natural, 5, {max: 9}); - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } + if (options && options.plusfour === true) { + zip.push('-'); + zip = zip.concat(this.n(this.natural, 4, {max: 9})); + } - this.abort = abort - this.context = context - } + return zip.join(""); + }; - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + // -- End Location -- - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + // -- Time - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } - return - } + Chance.prototype.ampm = function () { + return this.bool() ? 'am' : 'pm'; + }; - const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers - const contentType = parsedHeaders['content-type'] - const body = new Readable({ resume, abort, contentType, highWaterMark }) + Chance.prototype.date = function (options) { + var date_string, date; - 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 - }) - } - } - } + // If interval is specified we ignore preset + if(options && (options.min || options.max)) { + options = initOptions(options, { + american: true, + string: false + }); + var min = typeof options.min !== "undefined" ? options.min.getTime() : 1; + // 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. http://es5.github.io/#x15.9.1.1 + var max = typeof options.max !== "undefined" ? options.max.getTime() : 8640000000000000; - onData (chunk) { - const { res } = this - return res.push(chunk) - } + date = new Date(this.integer({min: min, max: max})); + } else { + var m = this.month({raw: true}); + var daysInMonth = m.days; - onComplete (trailers) { - const { res } = this + if(options && options.month) { + // Mod 12 to allow months outside range of 0-11 (not encouraged, but also not prevented). + daysInMonth = this.get('months')[((options.month % 12) + 12) % 12].days; + } - removeSignal(this) + options = initOptions(options, { + year: parseInt(this.year(), 10), + // Necessary to subtract 1 because Date() 0-indexes month but not day or year + // for some reason. + month: m.numeric - 1, + day: this.natural({min: 1, max: daysInMonth}), + hour: this.hour({twentyfour: true}), + minute: this.minute(), + second: this.second(), + millisecond: this.millisecond(), + american: true, + string: false + }); - util.parseHeaders(trailers, this.trailers) + date = new Date(options.year, options.month, options.day, options.hour, options.minute, options.second, options.millisecond); + } - res.push(null) - } + if (options.american) { + // Adding 1 to the month is necessary because Date() 0-indexes + // months but not day for some odd reason. + date_string = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); + } else { + date_string = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); + } - onError (err) { - const { res, callback, body, opaque } = this + return options.string ? date_string : date; + }; - removeSignal(this) + Chance.prototype.hammertime = function (options) { + return this.date(options).getTime(); + }; - if (callback) { - // TODO: Does this need queueMicrotask? - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } + Chance.prototype.hour = function (options) { + options = initOptions(options, { + min: options && options.twentyfour ? 0 : 1, + max: options && options.twentyfour ? 23 : 12 + }); - if (res) { - this.res = null - // Ensure all queued handlers are invoked before destroying res. - queueMicrotask(() => { - util.destroy(res, err) - }) - } + testRange(options.min < 0, "Chance: Min cannot be less than 0."); + testRange(options.twentyfour && options.max > 23, "Chance: Max cannot be greater than 23 for twentyfour option."); + testRange(!options.twentyfour && options.max > 12, "Chance: Max cannot be greater than 12."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - if (body) { - this.body = null - util.destroy(body, err) - } - } -} + return this.natural({min: options.min, max: options.max}); + }; + + Chance.prototype.millisecond = function () { + return this.natural({max: 999}); + }; -function request (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - request.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } + Chance.prototype.minute = Chance.prototype.second = function (options) { + options = initOptions(options, {min: 0, max: 59}); - 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 })) - } -} + testRange(options.min < 0, "Chance: Min cannot be less than 0."); + testRange(options.max > 59, "Chance: Max cannot be greater than 59."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); -module.exports = request -module.exports.RequestHandler = RequestHandler + return this.natural({min: options.min, max: options.max}); + }; + Chance.prototype.month = function (options) { + options = initOptions(options, {min: 1, max: 12}); -/***/ }), + testRange(options.min < 1, "Chance: Min cannot be less than 1."); + testRange(options.max > 12, "Chance: Max cannot be greater than 12."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); -/***/ 75395: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var month = this.pick(this.months().slice(options.min - 1, options.max)); + return options.raw ? month : month.name; + }; -"use strict"; + Chance.prototype.months = function () { + return this.get("months"); + }; + Chance.prototype.second = function () { + return this.natural({max: 59}); + }; -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) + Chance.prototype.timestamp = function () { + return this.natural({min: 1, max: parseInt(new Date().getTime() / 1000, 10)}); + }; -class StreamHandler extends AsyncResource { - constructor (opts, factory, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + Chance.prototype.weekday = function (options) { + options = initOptions(options, {weekday_only: false}); + var weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; + if (!options.weekday_only) { + weekdays.push("Saturday"); + weekdays.push("Sunday"); + } + return this.pickone(weekdays); + }; - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + Chance.prototype.year = function (options) { + // Default to current year as min if none specified + options = initOptions(options, {min: new Date().getFullYear()}); - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + // Default to one century after current year as max if none specified + options.max = (typeof options.max !== "undefined") ? options.max : options.min + 100; - if (typeof factory !== 'function') { - throw new InvalidArgumentError('invalid factory') - } + return this.natural(options).toString(); + }; - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } + // -- End Time - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } + // -- Finance -- - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } + Chance.prototype.cc = function (options) { + options = initOptions(options); - super('UNDICI_STREAM') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } + var type, number, to_generate; - 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 + type = (options.type) ? + this.cc_type({ name: options.type, raw: true }) : + this.cc_type({ raw: true }); - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) - } + number = type.prefix.split(""); + to_generate = type.length - type.prefix.length - 1; - addSignal(this, signal) - } + // Generates n - 1 digits + number = number.concat(this.n(this.integer, to_generate, {min: 0, max: 9})); - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } + // Generates the last digit according to Luhn algorithm + number.push(this.luhn_calculate(number.join(""))); - this.abort = abort - this.context = context - } + return number.join(""); + }; - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { factory, opaque, context, callback, responseHeaders } = this + Chance.prototype.cc_types = function () { + // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 + return this.get("cc_types"); + }; - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + Chance.prototype.cc_type = function (options) { + options = initOptions(options); + var types = this.cc_types(), + type = null; - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } - return - } + if (options.name) { + for (var i = 0; i < types.length; i++) { + // Accept either name or short_name to specify card type + if (types[i].name === options.name || types[i].short_name === options.name) { + type = types[i]; + break; + } + } + if (type === null) { + throw new RangeError("Chance: Credit card type '" + options.name + "' is not supported"); + } + } else { + type = this.pick(types); + } - this.factory = null + return options.raw ? type : type.name; + }; - let res + // return all world currency by ISO 4217 + Chance.prototype.currency_types = function () { + return this.get("currency_types"); + }; - if (this.throwOnError && statusCode >= 400) { - const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers - const contentType = parsedHeaders['content-type'] - res = new PassThrough() + // return random world currency by ISO 4217 + Chance.prototype.currency = function () { + return this.pick(this.currency_types()); + }; - this.callback = null - this.runInAsyncScope(getResolveErrorBodyCallback, null, - { callback, body: res, contentType, statusCode, statusMessage, headers } - ) - } else { - if (factory === null) { - return - } + // return all timezones available + Chance.prototype.timezones = function () { + return this.get("timezones"); + }; - res = this.runInAsyncScope(factory, null, { - statusCode, - headers, - opaque, - context - }) + // return random timezone + Chance.prototype.timezone = function () { + return this.pick(this.timezones()); + }; - if ( - !res || - typeof res.write !== 'function' || - typeof res.end !== 'function' || - typeof res.on !== 'function' - ) { - throw new InvalidReturnValueError('expected Writable') - } + //Return random correct currency exchange pair (e.g. EUR/USD) or array of currency code + Chance.prototype.currency_pair = function (returnAsString) { + var currencies = this.unique(this.currency, 2, { + comparator: function(arr, val) { - // TODO: Avoid finished. It registers an unnecessary amount of listeners. - finished(res, { readable: false }, (err) => { - const { callback, res, opaque, trailers, abort } = this + return arr.reduce(function(acc, item) { + // If a match has been found, short circuit check and just return + return acc || (item.code === val.code); + }, false); + } + }); - this.res = null - if (err || !res.readable) { - util.destroy(res, err) + if (returnAsString) { + return currencies[0].code + '/' + currencies[1].code; + } else { + return currencies; } + }; - this.callback = null - this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + Chance.prototype.dollar = function (options) { + // By default, a somewhat more sane max for dollar than all available numbers + options = initOptions(options, {max : 10000, min : 0}); - if (err) { - abort() - } - }) - } + var dollar = this.floating({min: options.min, max: options.max, fixed: 2}).toString(), + cents = dollar.split('.')[1]; - res.on('drain', resume) + if (cents === undefined) { + dollar += '.00'; + } else if (cents.length < 2) { + dollar = dollar + '0'; + } - this.res = res + if (dollar < 0) { + return '-$' + dollar.replace('-', ''); + } else { + return '$' + dollar; + } + }; - const needDrain = res.writableNeedDrain !== undefined - ? res.writableNeedDrain - : res._writableState && res._writableState.needDrain + Chance.prototype.euro = function (options) { + return Number(this.dollar(options).replace("$", "")).toLocaleString() + "€"; + }; - return needDrain !== true - } + Chance.prototype.exp = function (options) { + options = initOptions(options); + var exp = {}; - onData (chunk) { - const { res } = this + exp.year = this.exp_year(); - return res ? res.write(chunk) : true - } + // If the year is this year, need to ensure month is greater than the + // current month or this expiration will not be valid + if (exp.year === (new Date().getFullYear()).toString()) { + exp.month = this.exp_month({future: true}); + } else { + exp.month = this.exp_month(); + } - onComplete (trailers) { - const { res } = this + return options.raw ? exp : exp.month + '/' + exp.year; + }; - removeSignal(this) + Chance.prototype.exp_month = function (options) { + options = initOptions(options); + var month, month_int, + // Date object months are 0 indexed + curMonth = new Date().getMonth() + 1; - if (!res) { - return - } + if (options.future && (curMonth !== 12)) { + do { + month = this.month({raw: true}).numeric; + month_int = parseInt(month, 10); + } while (month_int <= curMonth); + } else { + month = this.month({raw: true}).numeric; + } - this.trailers = util.parseHeaders(trailers) + return month; + }; - res.end() - } + Chance.prototype.exp_year = function () { + var curMonth = new Date().getMonth() + 1, + curYear = new Date().getFullYear(); - onError (err) { - const { res, callback, opaque, body } = this + return this.year({min: ((curMonth === 12) ? (curYear + 1) : curYear), max: (curYear + 10)}); + }; - removeSignal(this) + Chance.prototype.vat = function (options) { + options = initOptions(options, { country: 'it' }); + switch (options.country.toLowerCase()) { + case 'it': + return this.it_vat(); + } + }; - this.factory = null + /** + * Generate a string matching IBAN pattern (https://en.wikipedia.org/wiki/International_Bank_Account_Number). + * No country-specific formats support (yet) + */ + Chance.prototype.iban = function () { + var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + var alphanum = alpha + '0123456789'; + var iban = + this.string({ length: 2, pool: alpha }) + + this.pad(this.integer({ min: 0, max: 99 }), 2) + + this.string({ length: 4, pool: alphanum }) + + this.pad(this.natural(), this.natural({ min: 6, max: 26 })); + return iban; + }; - if (res) { - this.res = null - util.destroy(res, err) - } else if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } + // -- End Finance - if (body) { - this.body = null - util.destroy(body, err) - } - } -} + // -- Regional -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) - }) - }) - } + Chance.prototype.it_vat = function () { + var it_vat = this.natural({min: 1, max: 1800000}); - 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 })) - } -} + it_vat = this.pad(it_vat, 7) + this.pad(this.pick(this.provinces({ country: 'it' })).code, 3); + return it_vat + this.luhn_calculate(it_vat); + }; -module.exports = stream + /* + * this generator is written following the official algorithm + * all data can be passed explicitely or randomized by calling chance.cf() without options + * the code does not check that the input data is valid (it goes beyond the scope of the generator) + * + * @param [Object] options = { first: first name, + * last: last name, + * gender: female|male, + birthday: JavaScript date object, + city: string(4), 1 letter + 3 numbers + } + * @return [string] codice fiscale + * + */ + Chance.prototype.cf = function (options) { + options = options || {}; + var gender = !!options.gender ? options.gender : this.gender(), + first = !!options.first ? options.first : this.first( { gender: gender, nationality: 'it'} ), + last = !!options.last ? options.last : this.last( { nationality: 'it'} ), + birthday = !!options.birthday ? options.birthday : this.birthday(), + city = !!options.city ? options.city : this.pickone(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L', 'M', 'Z']) + this.pad(this.natural({max:999}), 3), + cf = [], + name_generator = function(name, isLast) { + var temp, + return_value = []; + if (name.length < 3) { + return_value = name.split("").concat("XXX".split("")).splice(0,3); + } + else { + temp = name.toUpperCase().split('').map(function(c){ + return ("BCDFGHJKLMNPRSTVWZ".indexOf(c) !== -1) ? c : undefined; + }).join(''); + if (temp.length > 3) { + if (isLast) { + temp = temp.substr(0,3); + } else { + temp = temp[0] + temp.substr(2,2); + } + } + if (temp.length < 3) { + return_value = temp; + temp = name.toUpperCase().split('').map(function(c){ + return ("AEIOU".indexOf(c) !== -1) ? c : undefined; + }).join('').substr(0, 3 - return_value.length); + } + return_value = return_value + temp; + } -/***/ }), + return return_value; + }, + date_generator = function(birthday, gender, that) { + var lettermonths = ['A', 'B', 'C', 'D', 'E', 'H', 'L', 'M', 'P', 'R', 'S', 'T']; -/***/ 36923: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return birthday.getFullYear().toString().substr(2) + + lettermonths[birthday.getMonth()] + + that.pad(birthday.getDate() + ((gender.toLowerCase() === "female") ? 40 : 0), 2); + }, + checkdigit_generator = function(cf) { + var range1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", + range2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ", + evens = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + odds = "BAKPLCQDREVOSFTGUHMINJWZYX", + digit = 0; -"use strict"; + for(var i = 0; i < 15; i++) { + if (i % 2 !== 0) { + digit += evens.indexOf(range2[range1.indexOf(cf[i])]); + } + else { + digit += odds.indexOf(range2[range1.indexOf(cf[i])]); + } + } + return evens[digit % 26]; + }; -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) + cf = cf.concat(name_generator(last, true), name_generator(first), date_generator(birthday, gender, this), city.toUpperCase().split("")).join(""); + cf += checkdigit_generator(cf.toUpperCase(), this); -class UpgradeHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + return cf.toUpperCase(); + }; - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + Chance.prototype.pl_pesel = function () { + var number = this.natural({min: 1, max: 9999999999}); + var arr = this.pad(number, 10).split(''); + for (var i = 0; i < arr.length; i++) { + arr[i] = parseInt(arr[i]); + } - const { signal, opaque, responseHeaders } = opts + var controlNumber = (1 * arr[0] + 3 * arr[1] + 7 * arr[2] + 9 * arr[3] + 1 * arr[4] + 3 * arr[5] + 7 * arr[6] + 9 * arr[7] + 1 * arr[8] + 3 * arr[9]) % 10; + if(controlNumber !== 0) { + controlNumber = 10 - controlNumber; + } - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } + return arr.join('') + controlNumber; + }; - super('UNDICI_UPGRADE') + Chance.prototype.pl_nip = function () { + var number = this.natural({min: 1, max: 999999999}); + var arr = this.pad(number, 9).split(''); + for (var i = 0; i < arr.length; i++) { + arr[i] = parseInt(arr[i]); + } - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.abort = null - this.context = null + var controlNumber = (6 * arr[0] + 5 * arr[1] + 7 * arr[2] + 2 * arr[3] + 3 * arr[4] + 4 * arr[5] + 5 * arr[6] + 6 * arr[7] + 7 * arr[8]) % 11; + if(controlNumber === 10) { + return this.pl_nip(); + } - addSignal(this, signal) - } + return arr.join('') + controlNumber; + }; - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } + Chance.prototype.pl_regon = function () { + var number = this.natural({min: 1, max: 99999999}); + var arr = this.pad(number, 8).split(''); + for (var i = 0; i < arr.length; i++) { + arr[i] = parseInt(arr[i]); + } - this.abort = abort - this.context = null - } + var controlNumber = (8 * arr[0] + 9 * arr[1] + 2 * arr[2] + 3 * arr[3] + 4 * arr[4] + 5 * arr[5] + 6 * arr[6] + 7 * arr[7]) % 11; + if(controlNumber === 10) { + controlNumber = 0; + } - onHeaders () { - throw new SocketError('bad upgrade', null) - } + return arr.join('') + controlNumber; + }; - onUpgrade (statusCode, rawHeaders, socket) { - const { callback, opaque, context } = this + // -- End Regional - assert.strictEqual(statusCode, 101) + // -- Music -- - removeSignal(this) + // Genre choices: + // Rock,Pop,Hip-Hop,Jazz,Classical,Electronic,Country,R&B,Reggae, + // Blues,Metal,Folk,Alternative,Punk,Disco,Funk,Techno, + // Indie,Gospel,Dance,Children's,World - this.callback = null - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.runInAsyncScope(callback, null, null, { - headers, - socket, - opaque, - context - }) - } + Chance.prototype.music_genre = function (genre = 'general') { + if (!(genre.toLowerCase() in data.music_genres)) { + throw new Error(`Unsupported genre: ${genre}`); + } - onError (err) { - const { callback, opaque } = this + const genres = data.music_genres[genre.toLowerCase()]; + const randomIndex = this.integer({ min: 0, max: genres.length - 1 }); - removeSignal(this) + return genres[randomIndex]; + }; - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) + Chance.prototype.note = function(options) { + // choices for 'notes' option: + // flatKey - chromatic scale with flat notes (default) + // sharpKey - chromatic scale with sharp notes + // flats - just flat notes + // sharps - just sharp notes + // naturals - just natural notes + // all - naturals, sharps and flats + options = initOptions(options, { notes : 'flatKey'}); + var scales = { + naturals: ['C', 'D', 'E', 'F', 'G', 'A', 'B'], + flats: ['Dā™­', 'Eā™­', 'Gā™­', 'Aā™­', 'Bā™­'], + sharps: ['C♯', 'D♯', 'F♯', 'G♯', 'A♯'] + }; + scales.all = scales.naturals.concat(scales.flats.concat(scales.sharps)) + scales.flatKey = scales.naturals.concat(scales.flats) + scales.sharpKey = scales.naturals.concat(scales.sharps) + return this.pickone(scales[options.notes]); } - } -} -function upgrade (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - upgrade.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } + Chance.prototype.midi_note = function(options) { + var min = 0; + var max = 127; + options = initOptions(options, { min : min, max : max }); + return this.integer({min: options.min, max: options.max}); + } - 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 + Chance.prototype.chord_quality = function(options) { + options = initOptions(options, { jazz: true }); + var chord_qualities = ['maj', 'min', 'aug', 'dim']; + if (options.jazz){ + chord_qualities = [ + 'maj7', + 'min7', + '7', + 'sus', + 'dim', + 'Ćø' + ]; + } + return this.pickone(chord_qualities); } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} -module.exports = upgrade + Chance.prototype.chord = function (options) { + options = initOptions(options); + return this.note(options) + this.chord_quality(options); + } + Chance.prototype.tempo = function (options) { + var min = 40; + var max = 320; + options = initOptions(options, {min: min, max: max}); + return this.integer({min: options.min, max: options.max}); + } -/***/ }), + // -- End Music -/***/ 44059: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // -- Miscellaneous -- -"use strict"; + // Coin - Flip, flip, flipadelphia + Chance.prototype.coin = function() { + return this.bool() ? "heads" : "tails"; + } + // Dice - For all the board game geeks out there, myself included ;) + function diceFn (range) { + return function () { + return this.natural(range); + }; + } + Chance.prototype.d4 = diceFn({min: 1, max: 4}); + Chance.prototype.d6 = diceFn({min: 1, max: 6}); + Chance.prototype.d8 = diceFn({min: 1, max: 8}); + Chance.prototype.d10 = diceFn({min: 1, max: 10}); + Chance.prototype.d12 = diceFn({min: 1, max: 12}); + Chance.prototype.d20 = diceFn({min: 1, max: 20}); + Chance.prototype.d30 = diceFn({min: 1, max: 30}); + Chance.prototype.d100 = diceFn({min: 1, max: 100}); -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) + Chance.prototype.rpg = function (thrown, options) { + options = initOptions(options); + if (!thrown) { + throw new RangeError("Chance: A type of die roll must be included"); + } else { + var bits = thrown.toLowerCase().split("d"), + rolls = []; + if (bits.length !== 2 || !parseInt(bits[0], 10) || !parseInt(bits[1], 10)) { + throw new Error("Chance: Invalid format provided. Please provide #d# where the first # is the number of dice to roll, the second # is the max of each die"); + } + for (var i = bits[0]; i > 0; i--) { + rolls[i - 1] = this.natural({min: 1, max: bits[1]}); + } + return (typeof options.sum !== 'undefined' && options.sum) ? rolls.reduce(function (p, c) { return p + c; }) : rolls; + } + }; -/***/ }), + // Guid + Chance.prototype.guid = function (options) { + options = initOptions(options, { version: 5 }); -/***/ 73858: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var guid_pool = "abcdef1234567890", + variant_pool = "ab89", + guid = this.string({ pool: guid_pool, length: 8 }) + '-' + + this.string({ pool: guid_pool, length: 4 }) + '-' + + // The Version + options.version + + this.string({ pool: guid_pool, length: 3 }) + '-' + + // The Variant + this.string({ pool: variant_pool, length: 1 }) + + this.string({ pool: guid_pool, length: 3 }) + '-' + + this.string({ pool: guid_pool, length: 12 }); + return guid; + }; -"use strict"; -// Ported from https://github.com/nodejs/undici/pull/907 + // Hash + Chance.prototype.hash = function (options) { + options = initOptions(options, {length : 40, casing: 'lower'}); + var pool = options.casing === 'upper' ? HEX_POOL.toUpperCase() : HEX_POOL; + return this.string({pool: pool, length: options.length}); + }; + Chance.prototype.luhn_check = function (num) { + var str = num.toString(); + var checkDigit = +str.substring(str.length - 1); + return checkDigit === this.luhn_calculate(+str.substring(0, str.length - 1)); + }; + Chance.prototype.luhn_calculate = function (num) { + var digits = num.toString().split("").reverse(); + var sum = 0; + var digit; -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) + for (var i = 0, l = digits.length; l > i; ++i) { + digit = +digits[i]; + if (i % 2 === 0) { + digit *= 2; + if (digit > 9) { + digit -= 9; + } + } + sum += digit; + } + return (sum * 9) % 10; + }; -let Blob + // MD5 Hash + Chance.prototype.md5 = function(options) { + var opts = { str: '', key: null, raw: false }; -const kConsume = Symbol('kConsume') -const kReading = Symbol('kReading') -const kBody = Symbol('kBody') -const kAbort = Symbol('abort') -const kContentType = Symbol('kContentType') + if (!options) { + opts.str = this.string(); + options = {}; + } + else if (typeof options === 'string') { + opts.str = options; + options = {}; + } + else if (typeof options !== 'object') { + return null; + } + else if(options.constructor === 'Array') { + return null; + } -const noop = () => {} + opts = initOptions(options, opts); -module.exports = class BodyReadable extends Readable { - constructor ({ - resume, - abort, - contentType = '', - highWaterMark = 64 * 1024 // Same as nodejs fs streams. - }) { - super({ - autoDestroy: true, - read: resume, - highWaterMark - }) + if(!opts.str){ + throw new Error('A parameter is required to return an md5 hash.'); + } - this._readableState.dataEmitted = false + return this.bimd5.md5(opts.str, opts.key, opts.raw); + }; - this[kAbort] = abort - this[kConsume] = null - this[kBody] = null - this[kContentType] = contentType + /** + * #Description: + * ===================================================== + * Generate random file name with extension + * + * The argument provide extension type + * -> raster + * -> vector + * -> 3d + * -> document + * + * If nothing is provided the function return random file name with random + * extension type of any kind + * + * The user can validate the file name length range + * If nothing provided the generated file name is random + * + * #Extension Pool : + * * Currently the supported extensions are + * -> some of the most popular raster image extensions + * -> some of the most popular vector image extensions + * -> some of the most popular 3d image extensions + * -> some of the most popular document extensions + * + * #Examples : + * ===================================================== + * + * Return random file name with random extension. The file extension + * is provided by a predefined collection of extensions. More about the extension + * pool can be found in #Extension Pool section + * + * chance.file() + * => dsfsdhjf.xml + * + * In order to generate a file name with specific length, specify the + * length property and integer value. The extension is going to be random + * + * chance.file({length : 10}) + * => asrtineqos.pdf + * + * In order to generate file with extension from some of the predefined groups + * of the extension pool just specify the extension pool category in fileType property + * + * chance.file({fileType : 'raster'}) + * => dshgssds.psd + * + * You can provide specific extension for your files + * chance.file({extension : 'html'}) + * => djfsd.html + * + * Or you could pass custom collection of extensions by array or by object + * chance.file({extensions : [...]}) + * => dhgsdsd.psd + * + * chance.file({extensions : { key : [...], key : [...]}}) + * => djsfksdjsd.xml + * + * @param [collection] options + * @return [string] + * + */ + Chance.prototype.file = function(options) { - // 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 - } + var fileOptions = options || {}; + var poolCollectionKey = "fileExtension"; + var typeRange = Object.keys(this.get("fileExtension"));//['raster', 'vector', '3d', 'document']; + var fileName; + var fileExtension; - destroy (err) { - if (this.destroyed) { - // Node < 16 - return this - } + // Generate random file name + fileName = this.word({length : fileOptions.length}); - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } + // Generate file by specific extension provided by the user + if(fileOptions.extension) { - if (err) { - this[kAbort]() - } + fileExtension = fileOptions.extension; + return (fileName + '.' + fileExtension); + } - return super.destroy(err) - } + // Generate file by specific extension collection + if(fileOptions.extensions) { - 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) - } + if(Array.isArray(fileOptions.extensions)) { - on (ev, ...args) { - if (ev === 'data' || ev === 'readable') { - this[kReading] = true - } - return super.on(ev, ...args) - } + fileExtension = this.pickone(fileOptions.extensions); + return (fileName + '.' + fileExtension); + } + else if(fileOptions.extensions.constructor === Object) { - addListener (ev, ...args) { - return this.on(ev, ...args) - } + var extensionObjectCollection = fileOptions.extensions; + var keys = Object.keys(extensionObjectCollection); - 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 - } + fileExtension = this.pickone(extensionObjectCollection[this.pickone(keys)]); + return (fileName + '.' + fileExtension); + } - removeListener (ev, ...args) { - return this.off(ev, ...args) - } + throw new Error("Chance: Extensions must be an Array or Object"); + } - 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) - } + // Generate file extension based on specific file type + if(fileOptions.fileType) { - // https://fetch.spec.whatwg.org/#dom-body-text - async text () { - return consume(this, 'text') - } + var fileType = fileOptions.fileType; + if(typeRange.indexOf(fileType) !== -1) { - // https://fetch.spec.whatwg.org/#dom-body-json - async json () { - return consume(this, 'json') - } + fileExtension = this.pickone(this.get(poolCollectionKey)[fileType]); + return (fileName + '.' + fileExtension); + } - // https://fetch.spec.whatwg.org/#dom-body-blob - async blob () { - return consume(this, 'blob') - } + throw new RangeError("Chance: Expect file type value to be 'raster', 'vector', '3d' or 'document'"); + } - // https://fetch.spec.whatwg.org/#dom-body-arraybuffer - async arrayBuffer () { - return consume(this, 'arrayBuffer') - } + // Generate random file name if no extension options are passed + fileExtension = this.pickone(this.get(poolCollectionKey)[this.pickone(typeRange)]); + return (fileName + '.' + fileExtension); + }; - // https://fetch.spec.whatwg.org/#dom-body-formdata - async formData () { - // TODO: Implement. - throw new NotSupportedError() - } + /** + * Generates file data of random bytes using the chance.file method for the file name + * + * @param {object} + * fileName: String + * fileExtention: String + * fileSize: Number <- in bytes + * @returns {object} fileName: String, fileData: Buffer + */ + Chance.prototype.fileWithContent = function (options){ + var fileOptions = options || {}; + var fileName = 'fileName' in fileOptions ? fileOptions.fileName : this.file().split(".")[0]; + fileName += "." + ('fileExtension' in fileOptions ? fileOptions.fileExtension : this.file().split(".")[1]); - // 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] - } + if (typeof fileOptions.fileSize !== "number") { + throw new Error('File size must be an integer') + } + var file = { + fileData: this.buffer({length: fileOptions.fileSize}), + fileName: fileName, + }; + return file; + } - dump (opts) { - let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 - const signal = opts && opts.signal + var data = { - 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) - } - } + firstNames: { + "male": { + "en": ["James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "George", "Donald", "Anthony", "Paul", "Mark", "Edward", "Steven", "Kenneth", "Andrew", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Frank", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Jonathan", "Scott", "Raymond", "Justin", "Brandon", "Gregory", "Samuel", "Benjamin", "Patrick", "Jack", "Henry", "Walter", "Dennis", "Jerry", "Alexander", "Peter", "Tyler", "Douglas", "Harold", "Aaron", "Jose", "Adam", "Arthur", "Zachary", "Carl", "Nathan", "Albert", "Kyle", "Lawrence", "Joe", "Willie", "Gerald", "Roger", "Keith", "Jeremy", "Terry", "Harry", "Ralph", "Sean", "Jesse", "Roy", "Louis", "Billy", "Austin", "Bruce", "Eugene", "Christian", "Bryan", "Wayne", "Russell", "Howard", "Fred", "Ethan", "Jordan", "Philip", "Alan", "Juan", "Randy", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Victor", "Clarence", "Ernest", "Martin", "Craig", "Stanley", "Shawn", "Travis", "Bradley", "Leonard", "Earl", "Gabriel", "Jimmy", "Francis", "Todd", "Noah", "Danny", "Dale", "Cody", "Carlos", "Allen", "Frederick", "Logan", "Curtis", "Alex", "Joel", "Luis", "Norman", "Marvin", "Glenn", "Tony", "Nathaniel", "Rodney", "Melvin", "Alfred", "Steve", "Cameron", "Chad", "Edwin", "Caleb", "Evan", "Antonio", "Lee", "Herbert", "Jeffery", "Isaac", "Derek", "Ricky", "Marcus", "Theodore", "Elijah", "Luke", "Jesus", "Eddie", "Troy", "Mike", "Dustin", "Ray", "Adrian", "Bernard", "Leroy", "Angel", "Randall", "Wesley", "Ian", "Jared", "Mason", "Hunter", "Calvin", "Oscar", "Clifford", "Jay", "Shane", "Ronnie", "Barry", "Lucas", "Corey", "Manuel", "Leo", "Tommy", "Warren", "Jackson", "Isaiah", "Connor", "Don", "Dean", "Jon", "Julian", "Miguel", "Bill", "Lloyd", "Charlie", "Mitchell", "Leon", "Jerome", "Darrell", "Jeremiah", "Alvin", "Brett", "Seth", "Floyd", "Jim", "Blake", "Micheal", "Gordon", "Trevor", "Lewis", "Erik", "Edgar", "Vernon", "Devin", "Gavin", "Jayden", "Chris", "Clyde", "Tom", "Derrick", "Mario", "Brent", "Marc", "Herman", "Chase", "Dominic", "Ricardo", "Franklin", "Maurice", "Max", "Aiden", "Owen", "Lester", "Gilbert", "Elmer", "Gene", "Francisco", "Glen", "Cory", "Garrett", "Clayton", "Sam", "Jorge", "Chester", "Alejandro", "Jeff", "Harvey", "Milton", "Cole", "Ivan", "Andre", "Duane", "Landon"], + // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0163 + "it": ["Adolfo", "Alberto", "Aldo", "Alessandro", "Alessio", "Alfredo", "Alvaro", "Andrea", "Angelo", "Angiolo", "Antonino", "Antonio", "Attilio", "Benito", "Bernardo", "Bruno", "Carlo", "Cesare", "Christian", "Claudio", "Corrado", "Cosimo", "Cristian", "Cristiano", "Daniele", "Dario", "David", "Davide", "Diego", "Dino", "Domenico", "Duccio", "Edoardo", "Elia", "Elio", "Emanuele", "Emiliano", "Emilio", "Enrico", "Enzo", "Ettore", "Fabio", "Fabrizio", "Federico", "Ferdinando", "Fernando", "Filippo", "Francesco", "Franco", "Gabriele", "Giacomo", "Giampaolo", "Giampiero", "Giancarlo", "Gianfranco", "Gianluca", "Gianmarco", "Gianni", "Gino", "Giorgio", "Giovanni", "Giuliano", "Giulio", "Giuseppe", "Graziano", "Gregorio", "Guido", "Iacopo", "Jacopo", "Lapo", "Leonardo", "Lorenzo", "Luca", "Luciano", "Luigi", "Manuel", "Marcello", "Marco", "Marino", "Mario", "Massimiliano", "Massimo", "Matteo", "Mattia", "Maurizio", "Mauro", "Michele", "Mirko", "Mohamed", "Nello", "Neri", "Niccolò", "Nicola", "Osvaldo", "Otello", "Paolo", "Pier Luigi", "Piero", "Pietro", "Raffaele", "Remo", "Renato", "Renzo", "Riccardo", "Roberto", "Rolando", "Romano", "Salvatore", "Samuele", "Sandro", "Sergio", "Silvano", "Simone", "Stefano", "Thomas", "Tommaso", "Ubaldo", "Ugo", "Umberto", "Valerio", "Valter", "Vasco", "Vincenzo", "Vittorio"], + // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html + "nl": ["Aaron","Abel","Adam","Adriaan","Albert","Alexander","Ali","Arjen","Arno","Bart","Bas","Bastiaan","Benjamin","Bob", "Boris","Bram","Brent","Cas","Casper","Chris","Christiaan","Cornelis","Daan","Daley","Damian","Dani","Daniel","DaniĆ«l","David","Dean","Dirk","Dylan","Egbert","Elijah","Erik","Erwin","Evert","Ezra","Fabian","Fedde","Finn","Florian","Floris","Frank","Frans","Frederik","Freek","Geert","Gerard","Gerben","Gerrit","Gijs","Guus","Hans","Hendrik","Henk","Herman","Hidde","Hugo","Jaap","Jan Jaap","Jan-Willem","Jack","Jacob","Jan","Jason","Jasper","Jayden","Jelle","Jelte","Jens","Jeroen","Jesse","Jim","Job","Joep","Johannes","John","Jonathan","Joris","Joshua","JoĆ«l","Julian","Kees","Kevin","Koen","Lars","Laurens","Leendert","Lennard","Lodewijk","Luc","Luca","Lucas","Lukas","Luuk","Maarten","Marcus","Martijn","Martin","Matthijs","Maurits","Max","Mees","Melle","Mick","Mika","Milan","Mohamed","Mohammed","Morris","Muhammed","Nathan","Nick","Nico","Niek","Niels","Noah","Noud","Olivier","Oscar","Owen","Paul","Pepijn","Peter","Pieter","Pim","Quinten","Reinier","Rens","Robin","Ruben","Sam","Samuel","Sander","Sebastiaan","Sem","Sep","Sepp","Siem","Simon","Stan","Stef","Steven","Stijn","Sven","Teun","Thijmen","Thijs","Thomas","Tijn","Tim","Timo","Tobias","Tom","Victor","Vince","Willem","Wim","Wouter","Yusuf"], + // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie + "fr": ["Aaron","Abdon","Abel","AbĆ©lard","Abelin","Abondance","Abraham","Absalon","Acace","Achaire","Achille","Adalard","Adalbald","AdalbĆ©ron","Adalbert","Adalric","Adam","Adegrin","Adel","Adelin","Andelin","Adelphe","Adam","AdĆ©odat","AdhĆ©mar","Adjutor","Adolphe","Adonis","Adon","Adrien","Agapet","Agathange","Agathon","Agilbert","AgĆ©nor","Agnan","Aignan","Agrippin","Aimable","AimĆ©","Alain","Alban","Albin","Aubin","AlbĆ©ric","Albert","Albertet","Alcibiade","Alcide","AlcĆ©e","Alcime","Aldonce","Aldric","AldĆ©ric","Aleaume","Alexandre","Alexis","Alix","Alliaume","Aleaume","Almine","Almire","AloĆÆs","AlphĆ©e","Alphonse","Alpinien","AlverĆØde","Amalric","Amaury","Amandin","Amant","Ambroise","AmĆ©dĆ©e","AmĆ©lien","Amiel","Amour","AnaĆ«l","Anastase","Anatole","Ancelin","AndĆ©ol","Andoche","AndrĆ©","Andoche","Ange","Angelin","Angilbe","Anglebert","Angoustan","Anicet","Anne","Annibal","Ansbert","Anselme","Anthelme","Antheaume","Anthime","Antide","Antoine","Antonius","Antonin","Apollinaire","Apollon","Aquilin","Arcade","Archambaud","Archambeau","Archange","Archibald","Arian","Ariel","Ariste","Aristide","Armand","Armel","Armin","Arnould","Arnaud","Arolde","ArsĆØne","ArsinoĆ©","Arthaud","ArthĆØme","Arthur","Ascelin","Athanase","Aubry","Audebert","Audouin","Audran","Audric","Auguste","Augustin","AurĆØle","AurĆ©lien","Aurian","Auxence","Axel","Aymard","Aymeric","Aymon","Aymond","Balthazar","Baptiste","BarnabĆ©","BarthĆ©lemy","BartimĆ©e","Basile","Bastien","Baudouin","BĆ©nigne","Benjamin","BenoĆ®t","BĆ©renger","BĆ©rard","Bernard","Bertrand","Blaise","Bon","Boniface","Bouchard","Brice","Brieuc","Bruno","Brunon","Calixte","Calliste","CamĆ©lien","Camille","Camillien","Candide","Caribert","Carloman","Cassandre","Cassien","CĆ©dric","CĆ©leste","CĆ©lestin","CĆ©lien","CĆ©saire","CĆ©sar","Charles","Charlemagne","Childebert","ChilpĆ©ric","ChrĆ©tien","Christian","Christodule","Christophe","Chrysostome","Clarence","Claude","Claudien","ClĆ©andre","ClĆ©ment","Clotaire","CĆ“me","Constance","Constant","Constantin","Corentin","Cyprien","Cyriaque","Cyrille","Cyril","Damien","Daniel","David","Delphin","Denis","DĆ©sirĆ©","Didier","DieudonnĆ©","Dimitri","Dominique","Dorian","DorothĆ©e","Edgard","Edmond","Ɖdouard","ƉleuthĆØre","Ɖlie","ƉlisĆ©e","Ɖmeric","Ɖmile","Ɖmilien","Emmanuel","Enguerrand","Ɖpiphane","Ɖric","Esprit","Ernest","Ɖtienne","Eubert","Eudes","Eudoxe","EugĆØne","EusĆØbe","Eustache","Ɖvariste","Ɖvrard","Fabien","Fabrice","Falba","FĆ©licitĆ©","FĆ©lix","Ferdinand","Fiacre","FidĆØle","Firmin","Flavien","Flodoard","Florent","Florentin","Florestan","Florian","FortunĆ©","Foulques","Francisque","FranƧois","FranƧais","Franciscus","Francs","FrĆ©dĆ©ric","Fulbert","Fulcran","Fulgence","Gabin","Gabriel","GaĆ«l","Garnier","Gaston","Gaspard","Gatien","Gaud","Gautier","GĆ©dĆ©on","Geoffroy","Georges","GĆ©raud","GĆ©rard","Gerbert","Germain","Gervais","Ghislain","Gilbert","Gilles","Girart","Gislebert","Gondebaud","Gonthier","Gontran","Gonzague","GrĆ©goire","GuĆ©rin","Gui","Guillaume","Gustave","Guy","Guyot","Hardouin","Hector","HĆ©delin","HĆ©lier","Henri","Herbert","Herluin","HervĆ©","Hilaire","Hildebert","Hincmar","Hippolyte","HonorĆ©","Hubert","Hugues","Innocent","Isabeau","Isidore","Jacques","Japhet","Jason","Jean","Jeannel","Jeannot","JĆ©rĆ©mie","JĆ©rĆ“me","Joachim","Joanny","Job","Jocelyn","JoĆ«l","Johan","Jonas","Jonathan","Joseph","Josse","Josselin","Jourdain","Jude","JudicaĆ«l","Jules","Julien","Juste","Justin","Lambert","Landry","Laurent","Lazare","LĆ©andre","LĆ©on","LĆ©onard","LĆ©opold","Leu","Loup","Leufroy","LibĆØre","LiĆ©tald","Lionel","LoĆÆc","Longin","Lorrain","Lorraine","Lothaire","Louis","Loup","Luc","Lucas","Lucien","Ludolphe","Ludovic","Macaire","Malo","Mamert","ManassĆ©","Marc","Marceau","Marcel","Marcelin","Marius","Marseille","Martial","Martin","Mathurin","Matthias","Mathias","Matthieu","Maugis","Maurice","Mauricet","Maxence","Maxime","Maximilien","Mayeul","MĆ©dĆ©ric","Melchior","Mence","Merlin","MĆ©rovĆ©e","MichaĆ«l","Michel","MoĆÆse","Morgan","Nathan","NathanaĆ«l","Narcisse","NĆ©hĆ©mie","Nestor","Nestor","NicĆ©phore","Nicolas","NoĆ©","NoĆ«l","Norbert","Normand","Normands","Octave","Odilon","Odon","Oger","Olivier","Oury","PacĆ“me","PalĆ©mon","Parfait","Pascal","Paterne","Patrice","Paul","PĆ©pin","Perceval","PhilĆ©mon","Philibert","Philippe","PhilothĆ©e","Pie","Pierre","Pierrick","Prosper","Quentin","Raoul","RaphaĆ«l","Raymond","RĆ©gis","RĆ©jean","RĆ©mi","Renaud","RenĆ©","Reybaud","Richard","Robert","Roch","Rodolphe","Rodrigue","Roger","Roland","Romain","Romuald","RomĆ©o","Rome","Ronan","Roselin","Salomon","Samuel","Savin","Savinien","Scholastique","SĆ©bastien","SĆ©raphin","Serge","SĆ©verin","Sidoine","Sigebert","Sigismond","SilvĆØre","Simon","SimĆ©on","Sixte","Stanislas","StĆ©phane","Stephan","Sylvain","Sylvestre","TancrĆØde","Tanguy","Taurin","ThĆ©odore","ThĆ©odose","ThĆ©ophile","ThĆ©ophraste","Thibault","Thibert","Thierry","Thomas","TimolĆ©on","TimothĆ©e","Titien","Tonnin","Toussaint","Trajan","Tristan","Turold","Tim","Ulysse","Urbain","Valentin","ValĆØre","ValĆ©ry","Venance","Venant","Venceslas","Vianney","Victor","Victorien","Victorin","Vigile","Vincent","Vital","Vitalien","Vivien","Waleran","Wandrille","Xavier","XĆ©nophon","Yves","Zacharie","ZachĆ©","ZĆ©phirin"] + }, - if (this.closed) { - return Promise.resolve(null) - } + "female": { + "en": ["Mary", "Emma", "Elizabeth", "Minnie", "Margaret", "Ida", "Alice", "Bertha", "Sarah", "Annie", "Clara", "Ella", "Florence", "Cora", "Martha", "Laura", "Nellie", "Grace", "Carrie", "Maude", "Mabel", "Bessie", "Jennie", "Gertrude", "Julia", "Hattie", "Edith", "Mattie", "Rose", "Catherine", "Lillian", "Ada", "Lillie", "Helen", "Jessie", "Louise", "Ethel", "Lula", "Myrtle", "Eva", "Frances", "Lena", "Lucy", "Edna", "Maggie", "Pearl", "Daisy", "Fannie", "Josephine", "Dora", "Rosa", "Katherine", "Agnes", "Marie", "Nora", "May", "Mamie", "Blanche", "Stella", "Ellen", "Nancy", "Effie", "Sallie", "Nettie", "Della", "Lizzie", "Flora", "Susie", "Maud", "Mae", "Etta", "Harriet", "Sadie", "Caroline", "Katie", "Lydia", "Elsie", "Kate", "Susan", "Mollie", "Alma", "Addie", "Georgia", "Eliza", "Lulu", "Nannie", "Lottie", "Amanda", "Belle", "Charlotte", "Rebecca", "Ruth", "Viola", "Olive", "Amelia", "Hannah", "Jane", "Virginia", "Emily", "Matilda", "Irene", "Kathryn", "Esther", "Willie", "Henrietta", "Ollie", "Amy", "Rachel", "Sara", "Estella", "Theresa", "Augusta", "Ora", "Pauline", "Josie", "Lola", "Sophia", "Leona", "Anne", "Mildred", "Ann", "Beulah", "Callie", "Lou", "Delia", "Eleanor", "Barbara", "Iva", "Louisa", "Maria", "Mayme", "Evelyn", "Estelle", "Nina", "Betty", "Marion", "Bettie", "Dorothy", "Luella", "Inez", "Lela", "Rosie", "Allie", "Millie", "Janie", "Cornelia", "Victoria", "Ruby", "Winifred", "Alta", "Celia", "Christine", "Beatrice", "Birdie", "Harriett", "Mable", "Myra", "Sophie", "Tillie", "Isabel", "Sylvia", "Carolyn", "Isabelle", "Leila", "Sally", "Ina", "Essie", "Bertie", "Nell", "Alberta", "Katharine", "Lora", "Rena", "Mina", "Rhoda", "Mathilda", "Abbie", "Eula", "Dollie", "Hettie", "Eunice", "Fanny", "Ola", "Lenora", "Adelaide", "Christina", "Lelia", "Nelle", "Sue", "Johanna", "Lilly", "Lucinda", "Minerva", "Lettie", "Roxie", "Cynthia", "Helena", "Hilda", "Hulda", "Bernice", "Genevieve", "Jean", "Cordelia", "Marian", "Francis", "Jeanette", "Adeline", "Gussie", "Leah", "Lois", "Lura", "Mittie", "Hallie", "Isabella", "Olga", "Phoebe", "Teresa", "Hester", "Lida", "Lina", "Winnie", "Claudia", "Marguerite", "Vera", "Cecelia", "Bess", "Emilie", "Rosetta", "Verna", "Myrtie", "Cecilia", "Elva", "Olivia", "Ophelia", "Georgie", "Elnora", "Violet", "Adele", "Lily", "Linnie", "Loretta", "Madge", "Polly", "Virgie", "Eugenia", "Lucile", "Lucille", "Mabelle", "Rosalie"], + // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0162 + "it": ["Ada", "Adriana", "Alessandra", "Alessia", "Alice", "Angela", "Anna", "Anna Maria", "Annalisa", "Annita", "Annunziata", "Antonella", "Arianna", "Asia", "Assunta", "Aurora", "Barbara", "Beatrice", "Benedetta", "Bianca", "Bruna", "Camilla", "Carla", "Carlotta", "Carmela", "Carolina", "Caterina", "Catia", "Cecilia", "Chiara", "Cinzia", "Clara", "Claudia", "Costanza", "Cristina", "Daniela", "Debora", "Diletta", "Dina", "Donatella", "Elena", "Eleonora", "Elisa", "Elisabetta", "Emanuela", "Emma", "Eva", "Federica", "Fernanda", "Fiorella", "Fiorenza", "Flora", "Franca", "Francesca", "Gabriella", "Gaia", "Gemma", "Giada", "Gianna", "Gina", "Ginevra", "Giorgia", "Giovanna", "Giulia", "Giuliana", "Giuseppa", "Giuseppina", "Grazia", "Graziella", "Greta", "Ida", "Ilaria", "Ines", "Iolanda", "Irene", "Irma", "Isabella", "Jessica", "Laura", "Lea", "Letizia", "Licia", "Lidia", "Liliana", "Lina", "Linda", "Lisa", "Livia", "Loretta", "Luana", "Lucia", "Luciana", "Lucrezia", "Luisa", "Manuela", "Mara", "Marcella", "Margherita", "Maria", "Maria Cristina", "Maria Grazia", "Maria Luisa", "Maria Pia", "Maria Teresa", "Marina", "Marisa", "Marta", "Martina", "Marzia", "Matilde", "Melissa", "Michela", "Milena", "Mirella", "Monica", "Natalina", "Nella", "Nicoletta", "Noemi", "Olga", "Paola", "Patrizia", "Piera", "Pierina", "Raffaella", "Rebecca", "Renata", "Rina", "Rita", "Roberta", "Rosa", "Rosanna", "Rossana", "Rossella", "Sabrina", "Sandra", "Sara", "Serena", "Silvana", "Silvia", "Simona", "Simonetta", "Sofia", "Sonia", "Stefania", "Susanna", "Teresa", "Tina", "Tiziana", "Tosca", "Valentina", "Valeria", "Vanda", "Vanessa", "Vanna", "Vera", "Veronica", "Vilma", "Viola", "Virginia", "Vittoria"], + // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html + "nl": ["Ada", "Arianne", "Afke", "Amanda", "Amber", "Amy", "Aniek", "Anita", "Anja", "Anna", "Anne", "Annelies", "Annemarie", "Annette", "Anouk", "Astrid", "Aukje", "Barbara", "Bianca", "Carla", "Carlijn", "Carolien", "Chantal", "Charlotte", "Claudia", "DaniĆ«lle", "Debora", "Diane", "Dora", "Eline", "Elise", "Ella", "Ellen", "Emma", "Esmee", "Evelien", "Esther", "Erica", "Eva", "Femke", "Fleur", "Floor", "Froukje", "Gea", "Gerda", "Hanna", "Hanneke", "Heleen", "Hilde", "Ilona", "Ina", "Inge", "Ingrid", "Iris", "Isabel", "Isabelle", "Janneke", "Jasmijn", "Jeanine", "Jennifer", "Jessica", "Johanna", "Joke", "Julia", "Julie", "Karen", "Karin", "Katja", "Kim", "Lara", "Laura", "Lena", "Lianne", "Lieke", "Lilian", "Linda", "Lisa", "Lisanne", "Lotte", "Louise", "Maaike", "Manon", "Marga", "Maria", "Marissa", "Marit", "Marjolein", "Martine", "Marleen", "Melissa", "Merel", "Miranda", "Michelle", "Mirjam", "Mirthe", "Naomi", "Natalie", 'Nienke', "Nina", "Noortje", "Olivia", "Patricia", "Paula", "Paulien", "Ramona", "Ria", "Rianne", "Roos", "Rosanne", "Ruth", "Sabrina", "Sandra", "Sanne", "Sara", "Saskia", "Silvia", "Sofia", "Sophie", "Sonja", "Suzanne", "Tamara", "Tess", "Tessa", "Tineke", "Valerie", "Vanessa", "Veerle", "Vera", "Victoria", "Wendy", "Willeke", "Yvonne", "ZoĆ«"], + // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie + "fr": ["Abdon","Abel","AbigaĆ«lle","AbigaĆÆl","Acacius","Acanthe","Adalbert","Adalsinde","Adegrine","AdĆ©laĆÆde","AdĆØle","AdĆ©lie","Adeline","Adeltrude","Adolphe","Adonis","AdrastĆ©e","Adrehilde","Adrienne","Agathe","Agilbert","AglaĆ©","Aignan","AgneflĆØte","AgnĆØs","Agrippine","AimĆ©","Alaine","AlaĆÆs","Albane","AlbĆ©rade","Alberte","Alcide","Alcine","Alcyone","Aldegonde","Aleth","Alexandrine","Alexine","Alice","AliĆ©nor","Aliette","Aline","Alix","AlizĆ©","AloĆÆse","Aloyse","Alphonsine","AlthĆ©e","Amaliane","AmalthĆ©e","Amande","Amandine","Amant","Amarande","Amaranthe","Amaryllis","Ambre","Ambroisie","AmĆ©lie","AmĆ©thyste","Aminte","AnaĆ«l","AnaĆÆs","Anastasie","Anatole","Ancelin","AndrĆ©e","AnĆ©mone","AngadrĆŖme","AngĆØle","Angeline","AngĆ©lique","Angilbert","Anicet","Annabelle","Anne","Annette","Annick","Annie","Annonciade","Ansbert","Anstrudie","Anthelme","Antigone","Antoinette","Antonine","AphĆ©lie","Apolline","Apollonie","Aquiline","Arabelle","Arcadie","Archange","Argine","Ariane","Aricie","Ariel","Arielle","Arlette","Armance","Armande","Armandine","Armelle","Armide","Armelle","Armin","Arnaud","ArsĆØne","ArsinoĆ©","ArtĆ©mis","Arthur","Ascelin","Ascension","Assomption","AstartĆ©","AstĆ©rie","AstrĆ©e","Astrid","Athalie","Athanasie","Athina","Aube","Albert","Aude","Audrey","Augustine","Aure","AurĆ©lie","AurĆ©lien","AurĆØle","Aurore","Auxence","Aveline","AbigaĆ«lle","Avoye","Axelle","Aymard","AzalĆ©e","AdĆØle","Adeline","Barbe","Basilisse","Bathilde","BĆ©atrice","BĆ©atrix","BĆ©nĆ©dicte","BĆ©rengĆØre","Bernadette","Berthe","Bertille","Beuve","Blanche","Blanc","Blandine","Brigitte","Brune","Brunehilde","Callista","Camille","Capucine","Carine","Caroline","Cassandre","Catherine","CĆ©cile","CĆ©leste","CĆ©lestine","CĆ©line","Chantal","CharlĆØne","Charline","Charlotte","ChloĆ©","Christelle","Christiane","Christine","Claire","Clara","Claude","Claudine","Clarisse","ClĆ©mence","ClĆ©mentine","ClĆ©o","Clio","Clotilde","Coline","Conception","Constance","Coralie","Coraline","Corentine","Corinne","Cyrielle","Daniel","Daniel","DaphnĆ©","DĆ©bora","Delphine","Denise","Diane","DieudonnĆ©","Dominique","Doriane","DorothĆ©e","Douce","Ɖdith","EdmĆ©e","ƉlĆ©onore","Ɖliane","Ɖlia","Ɖliette","Ɖlisabeth","Ɖlise","Ella","Ɖlodie","ƉloĆÆse","Elsa","Ɖmeline","ƉmĆ©rance","ƉmĆ©rentienne","ƉmĆ©rencie","Ɖmilie","Emma","Emmanuelle","Emmelie","Ernestine","Esther","Estelle","Eudoxie","EugĆ©nie","Eulalie","Euphrasie","EusĆ©bie","ƉvangĆ©line","Eva","ƈve","Ɖvelyne","Fanny","Fantine","Faustine","FĆ©licie","Fernande","Flavie","Fleur","Flore","Florence","Florie","FortunĆ©","France","Francia","FranƧoise","Francine","Gabrielle","GaĆ«lle","Garance","GeneviĆØve","Georgette","Gerberge","Germaine","Gertrude","GisĆØle","GueniĆØvre","Guilhemine","Guillemette","Gustave","Gwenael","HĆ©lĆØne","HĆ©loĆÆse","Henriette","Hermine","Hermione","Hippolyte","Honorine","Hortense","Huguette","Ines","IrĆØne","Irina","Iris","Isabeau","Isabelle","Iseult","Isolde","IsmĆ©rie","Jacinthe","Jacqueline","Jade","Janine","Jeanne","Jocelyne","JoĆ«lle","JosĆ©phine","Judith","Julia","Julie","Jules","Juliette","Justine","Katy","Kathy","Katie","Laura","Laure","Laureline","Laurence","Laurene","Lauriane","Laurianne","Laurine","LĆ©a","LĆ©na","LĆ©onie","LĆ©on","LĆ©ontine","Lorraine","Lucie","Lucienne","Lucille","Ludivine","Lydie","Lydie","Megane","Madeleine","Magali","Maguelone","Mallaury","Manon","Marceline","Margot","Marguerite","Marianne","Marie","Myriam","Marie","Marine","Marion","MarlĆØne","Marthe","Martine","Mathilde","Maud","Maureen","Mauricette","Maxime","MĆ©lanie","Melissa","MĆ©lissandre","MĆ©lisande","MĆ©lodie","Michel","Micheline","Mireille","Miriam","MoĆÆse","Monique","Morgane","Muriel","MylĆØne","NadĆØge","Nadine","Nathalie","Nicole","Nicolette","Nine","NoĆ«l","NoĆ©mie","OcĆ©ane","Odette","Odile","Olive","Olivia","Olympe","Ombline","Ombeline","OphĆ©lie","Oriande","Oriane","Ozanne","Pascale","Pascaline","Paule","Paulette","Pauline","Priscille","Prisca","Prisque","PĆ©cine","PĆ©lagie","PĆ©nĆ©lope","Perrine","PĆ©tronille","Philippine","PhilomĆØne","PhilothĆ©e","Primerose","Prudence","PulchĆ©rie","Quentine","QuiĆ©ta","Quintia","Quintilla","Rachel","RaphaĆ«lle","Raymonde","Rebecca","RĆ©gine","RĆ©jeanne","RenĆ©","Rita","Rita","Rolande","Romane","Rosalie","Rose","Roseline","Sabine","SalomĆ©","Sandra","Sandrine","Sarah","SĆ©golĆØne","SĆ©verine","Sibylle","Simone","Sixt","Solange","Soline","SolĆØne","Sophie","StĆ©phanie","Suzanne","Sylvain","Sylvie","Tatiana","ThaĆÆs","ThĆ©odora","ThĆ©rĆØse","Tiphaine","Ursule","Valentine","ValĆ©rie","VĆ©ronique","Victoire","Victorine","Vinciane","Violette","Virginie","Viviane","XaviĆØre","Yolande","Ysaline","Yvette","Yvonne","ZĆ©lie","Zita","ZoĆ©"] + } + }, + + lastNames: { + "en": ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis', 'Miller', 'Wilson', 'Moore', 'Taylor', 'Anderson', 'Thomas', 'Jackson', 'White', 'Harris', 'Martin', 'Thompson', 'Garcia', 'Martinez', 'Robinson', 'Clark', 'Rodriguez', 'Lewis', 'Lee', 'Walker', 'Hall', 'Allen', 'Young', 'Hernandez', 'King', 'Wright', 'Lopez', 'Hill', 'Scott', 'Green', 'Adams', 'Baker', 'Gonzalez', 'Nelson', 'Carter', 'Mitchell', 'Perez', 'Roberts', 'Turner', 'Phillips', 'Campbell', 'Parker', 'Evans', 'Edwards', 'Collins', 'Stewart', 'Sanchez', 'Morris', 'Rogers', 'Reed', 'Cook', 'Morgan', 'Bell', 'Murphy', 'Bailey', 'Rivera', 'Cooper', 'Richardson', 'Cox', 'Howard', 'Ward', 'Torres', 'Peterson', 'Gray', 'Ramirez', 'James', 'Watson', 'Brooks', 'Kelly', 'Sanders', 'Price', 'Bennett', 'Wood', 'Barnes', 'Ross', 'Henderson', 'Coleman', 'Jenkins', 'Perry', 'Powell', 'Long', 'Patterson', 'Hughes', 'Flores', 'Washington', 'Butler', 'Simmons', 'Foster', 'Gonzales', 'Bryant', 'Alexander', 'Russell', 'Griffin', 'Diaz', 'Hayes', 'Myers', 'Ford', 'Hamilton', 'Graham', 'Sullivan', 'Wallace', 'Woods', 'Cole', 'West', 'Jordan', 'Owens', 'Reynolds', 'Fisher', 'Ellis', 'Harrison', 'Gibson', 'McDonald', 'Cruz', 'Marshall', 'Ortiz', 'Gomez', 'Murray', 'Freeman', 'Wells', 'Webb', 'Simpson', 'Stevens', 'Tucker', 'Porter', 'Hunter', 'Hicks', 'Crawford', 'Henry', 'Boyd', 'Mason', 'Morales', 'Kennedy', 'Warren', 'Dixon', 'Ramos', 'Reyes', 'Burns', 'Gordon', 'Shaw', 'Holmes', 'Rice', 'Robertson', 'Hunt', 'Black', 'Daniels', 'Palmer', 'Mills', 'Nichols', 'Grant', 'Knight', 'Ferguson', 'Rose', 'Stone', 'Hawkins', 'Dunn', 'Perkins', 'Hudson', 'Spencer', 'Gardner', 'Stephens', 'Payne', 'Pierce', 'Berry', 'Matthews', 'Arnold', 'Wagner', 'Willis', 'Ray', 'Watkins', 'Olson', 'Carroll', 'Duncan', 'Snyder', 'Hart', 'Cunningham', 'Bradley', 'Lane', 'Andrews', 'Ruiz', 'Harper', 'Fox', 'Riley', 'Armstrong', 'Carpenter', 'Weaver', 'Greene', 'Lawrence', 'Elliott', 'Chavez', 'Sims', 'Austin', 'Peters', 'Kelley', 'Franklin', 'Lawson', 'Fields', 'Gutierrez', 'Ryan', 'Schmidt', 'Carr', 'Vasquez', 'Castillo', 'Wheeler', 'Chapman', 'Oliver', 'Montgomery', 'Richards', 'Williamson', 'Johnston', 'Banks', 'Meyer', 'Bishop', 'McCoy', 'Howell', 'Alvarez', 'Morrison', 'Hansen', 'Fernandez', 'Garza', 'Harvey', 'Little', 'Burton', 'Stanley', 'Nguyen', 'George', 'Jacobs', 'Reid', 'Kim', 'Fuller', 'Lynch', 'Dean', 'Gilbert', 'Garrett', 'Romero', 'Welch', 'Larson', 'Frazier', 'Burke', 'Hanson', 'Day', 'Mendoza', 'Moreno', 'Bowman', 'Medina', 'Fowler', 'Brewer', 'Hoffman', 'Carlson', 'Silva', 'Pearson', 'Holland', 'Douglas', 'Fleming', 'Jensen', 'Vargas', 'Byrd', 'Davidson', 'Hopkins', 'May', 'Terry', 'Herrera', 'Wade', 'Soto', 'Walters', 'Curtis', 'Neal', 'Caldwell', 'Lowe', 'Jennings', 'Barnett', 'Graves', 'Jimenez', 'Horton', 'Shelton', 'Barrett', 'Obrien', 'Castro', 'Sutton', 'Gregory', 'McKinney', 'Lucas', 'Miles', 'Craig', 'Rodriquez', 'Chambers', 'Holt', 'Lambert', 'Fletcher', 'Watts', 'Bates', 'Hale', 'Rhodes', 'Pena', 'Beck', 'Newman', 'Haynes', 'McDaniel', 'Mendez', 'Bush', 'Vaughn', 'Parks', 'Dawson', 'Santiago', 'Norris', 'Hardy', 'Love', 'Steele', 'Curry', 'Powers', 'Schultz', 'Barker', 'Guzman', 'Page', 'Munoz', 'Ball', 'Keller', 'Chandler', 'Weber', 'Leonard', 'Walsh', 'Lyons', 'Ramsey', 'Wolfe', 'Schneider', 'Mullins', 'Benson', 'Sharp', 'Bowen', 'Daniel', 'Barber', 'Cummings', 'Hines', 'Baldwin', 'Griffith', 'Valdez', 'Hubbard', 'Salazar', 'Reeves', 'Warner', 'Stevenson', 'Burgess', 'Santos', 'Tate', 'Cross', 'Garner', 'Mann', 'Mack', 'Moss', 'Thornton', 'Dennis', 'McGee', 'Farmer', 'Delgado', 'Aguilar', 'Vega', 'Glover', 'Manning', 'Cohen', 'Harmon', 'Rodgers', 'Robbins', 'Newton', 'Todd', 'Blair', 'Higgins', 'Ingram', 'Reese', 'Cannon', 'Strickland', 'Townsend', 'Potter', 'Goodwin', 'Walton', 'Rowe', 'Hampton', 'Ortega', 'Patton', 'Swanson', 'Joseph', 'Francis', 'Goodman', 'Maldonado', 'Yates', 'Becker', 'Erickson', 'Hodges', 'Rios', 'Conner', 'Adkins', 'Webster', 'Norman', 'Malone', 'Hammond', 'Flowers', 'Cobb', 'Moody', 'Quinn', 'Blake', 'Maxwell', 'Pope', 'Floyd', 'Osborne', 'Paul', 'McCarthy', 'Guerrero', 'Lindsey', 'Estrada', 'Sandoval', 'Gibbs', 'Tyler', 'Gross', 'Fitzgerald', 'Stokes', 'Doyle', 'Sherman', 'Saunders', 'Wise', 'Colon', 'Gill', 'Alvarado', 'Greer', 'Padilla', 'Simon', 'Waters', 'Nunez', 'Ballard', 'Schwartz', 'McBride', 'Houston', 'Christensen', 'Klein', 'Pratt', 'Briggs', 'Parsons', 'McLaughlin', 'Zimmerman', 'French', 'Buchanan', 'Moran', 'Copeland', 'Roy', 'Pittman', 'Brady', 'McCormick', 'Holloway', 'Brock', 'Poole', 'Frank', 'Logan', 'Owen', 'Bass', 'Marsh', 'Drake', 'Wong', 'Jefferson', 'Park', 'Morton', 'Abbott', 'Sparks', 'Patrick', 'Norton', 'Huff', 'Clayton', 'Massey', 'Lloyd', 'Figueroa', 'Carson', 'Bowers', 'Roberson', 'Barton', 'Tran', 'Lamb', 'Harrington', 'Casey', 'Boone', 'Cortez', 'Clarke', 'Mathis', 'Singleton', 'Wilkins', 'Cain', 'Bryan', 'Underwood', 'Hogan', 'McKenzie', 'Collier', 'Luna', 'Phelps', 'McGuire', 'Allison', 'Bridges', 'Wilkerson', 'Nash', 'Summers', 'Atkins'], + // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0164 (first 1000) + "it": ["Acciai", "Aglietti", "Agostini", "Agresti", "Ahmed", "Aiazzi", "Albanese", "Alberti", "Alessi", "Alfani", "Alinari", "Alterini", "Amato", "Ammannati", "Ancillotti", "Andrei", "Andreini", "Andreoni", "Angeli", "Anichini", "Antonelli", "Antonini", "Arena", "Ariani", "Arnetoli", "Arrighi", "Baccani", "Baccetti", "Bacci", "Bacherini", "Badii", "Baggiani", "Baglioni", "Bagni", "Bagnoli", "Baldassini", "Baldi", "Baldini", "Ballerini", "Balli", "Ballini", "Balloni", "Bambi", "Banchi", "Bandinelli", "Bandini", "Bani", "Barbetti", "Barbieri", "Barchielli", "Bardazzi", "Bardelli", "Bardi", "Barducci", "Bargellini", "Bargiacchi", "Barni", "Baroncelli", "Baroncini", "Barone", "Baroni", "Baronti", "Bartalesi", "Bartoletti", "Bartoli", "Bartolini", "Bartoloni", "Bartolozzi", "Basagni", "Basile", "Bassi", "Batacchi", "Battaglia", "Battaglini", "Bausi", "Becagli", "Becattini", "Becchi", "Becucci", "Bellandi", "Bellesi", "Belli", "Bellini", "Bellucci", "Bencini", "Benedetti", "Benelli", "Beni", "Benini", "Bensi", "Benucci", "Benvenuti", "Berlincioni", "Bernacchioni", "Bernardi", "Bernardini", "Berni", "Bernini", "Bertelli", "Berti", "Bertini", "Bessi", "Betti", "Bettini", "Biagi", "Biagini", "Biagioni", "Biagiotti", "Biancalani", "Bianchi", "Bianchini", "Bianco", "Biffoli", "Bigazzi", "Bigi", "Biliotti", "Billi", "Binazzi", "Bindi", "Bini", "Biondi", "Bizzarri", "Bocci", "Bogani", "Bolognesi", "Bonaiuti", "Bonanni", "Bonciani", "Boncinelli", "Bondi", "Bonechi", "Bongini", "Boni", "Bonini", "Borchi", "Boretti", "Borghi", "Borghini", "Borgioli", "Borri", "Borselli", "Boschi", "Bottai", "Bracci", "Braccini", "Brandi", "Braschi", "Bravi", "Brazzini", "Breschi", "Brilli", "Brizzi", "Brogelli", "Brogi", "Brogioni", "Brunelli", "Brunetti", "Bruni", "Bruno", "Brunori", "Bruschi", "Bucci", "Bucciarelli", "Buccioni", "Bucelli", "Bulli", "Burberi", "Burchi", "Burgassi", "Burroni", "Bussotti", "Buti", "Caciolli", "Caiani", "Calabrese", "Calamai", "Calamandrei", "Caldini", "Calo'", "Calonaci", "Calosi", "Calvelli", "Cambi", "Camiciottoli", "Cammelli", "Cammilli", "Campolmi", "Cantini", "Capanni", "Capecchi", "Caponi", "Cappelletti", "Cappelli", "Cappellini", "Cappugi", "Capretti", "Caputo", "Carbone", "Carboni", "Cardini", "Carlesi", "Carletti", "Carli", "Caroti", "Carotti", "Carrai", "Carraresi", "Carta", "Caruso", "Casalini", "Casati", "Caselli", "Casini", "Castagnoli", "Castellani", "Castelli", "Castellucci", "Catalano", "Catarzi", "Catelani", "Cavaciocchi", "Cavallaro", "Cavallini", "Cavicchi", "Cavini", "Ceccarelli", "Ceccatelli", "Ceccherelli", "Ceccherini", "Cecchi", "Cecchini", "Cecconi", "Cei", "Cellai", "Celli", "Cellini", "Cencetti", "Ceni", "Cenni", "Cerbai", "Cesari", "Ceseri", "Checcacci", "Checchi", "Checcucci", "Cheli", "Chellini", "Chen", "Cheng", "Cherici", "Cherubini", "Chiaramonti", "Chiarantini", "Chiarelli", "Chiari", "Chiarini", "Chiarugi", "Chiavacci", "Chiesi", "Chimenti", "Chini", "Chirici", "Chiti", "Ciabatti", "Ciampi", "Cianchi", "Cianfanelli", "Cianferoni", "Ciani", "Ciapetti", "Ciappi", "Ciardi", "Ciatti", "Cicali", "Ciccone", "Cinelli", "Cini", "Ciobanu", "Ciolli", "Cioni", "Cipriani", "Cirillo", "Cirri", "Ciucchi", "Ciuffi", "Ciulli", "Ciullini", "Clemente", "Cocchi", "Cognome", "Coli", "Collini", "Colombo", "Colzi", "Comparini", "Conforti", "Consigli", "Conte", "Conti", "Contini", "Coppini", "Coppola", "Corsi", "Corsini", "Corti", "Cortini", "Cosi", "Costa", "Costantini", "Costantino", "Cozzi", "Cresci", "Crescioli", "Cresti", "Crini", "Curradi", "D'Agostino", "D'Alessandro", "D'Amico", "D'Angelo", "Daddi", "Dainelli", "Dallai", "Danti", "Davitti", "De Angelis", "De Luca", "De Marco", "De Rosa", "De Santis", "De Simone", "De Vita", "Degl'Innocenti", "Degli Innocenti", "Dei", "Del Lungo", "Del Re", "Di Marco", "Di Stefano", "Dini", "Diop", "Dobre", "Dolfi", "Donati", "Dondoli", "Dong", "Donnini", "Ducci", "Dumitru", "Ermini", "Esposito", "Evangelisti", "Fabbri", "Fabbrini", "Fabbrizzi", "Fabbroni", "Fabbrucci", "Fabiani", "Facchini", "Faggi", "Fagioli", "Failli", "Faini", "Falciani", "Falcini", "Falcone", "Fallani", "Falorni", "Falsini", "Falugiani", "Fancelli", "Fanelli", "Fanetti", "Fanfani", "Fani", "Fantappie'", "Fantechi", "Fanti", "Fantini", "Fantoni", "Farina", "Fattori", "Favilli", "Fedi", "Fei", "Ferrante", "Ferrara", "Ferrari", "Ferraro", "Ferretti", "Ferri", "Ferrini", "Ferroni", "Fiaschi", "Fibbi", "Fiesoli", "Filippi", "Filippini", "Fini", "Fioravanti", "Fiore", "Fiorentini", "Fiorini", "Fissi", "Focardi", "Foggi", "Fontana", "Fontanelli", "Fontani", "Forconi", "Formigli", "Forte", "Forti", "Fortini", "Fossati", "Fossi", "Francalanci", "Franceschi", "Franceschini", "Franchi", "Franchini", "Franci", "Francini", "Francioni", "Franco", "Frassineti", "Frati", "Fratini", "Frilli", "Frizzi", "Frosali", "Frosini", "Frullini", "Fusco", "Fusi", "Gabbrielli", "Gabellini", "Gagliardi", "Galanti", "Galardi", "Galeotti", "Galletti", "Galli", "Gallo", "Gallori", "Gambacciani", "Gargani", "Garofalo", "Garuglieri", "Gashi", "Gasperini", "Gatti", "Gelli", "Gensini", "Gentile", "Gentili", "Geri", "Gerini", "Gheri", "Ghini", "Giachetti", "Giachi", "Giacomelli", "Gianassi", "Giani", "Giannelli", "Giannetti", "Gianni", "Giannini", "Giannoni", "Giannotti", "Giannozzi", "Gigli", "Giordano", "Giorgetti", "Giorgi", "Giovacchini", "Giovannelli", "Giovannetti", "Giovannini", "Giovannoni", "Giuliani", "Giunti", "Giuntini", "Giusti", "Gonnelli", "Goretti", "Gori", "Gradi", "Gramigni", "Grassi", "Grasso", "Graziani", "Grazzini", "Greco", "Grifoni", "Grillo", "Grimaldi", "Grossi", "Gualtieri", "Guarducci", "Guarino", "Guarnieri", "Guasti", "Guerra", "Guerri", "Guerrini", "Guidi", "Guidotti", "He", "Hoxha", "Hu", "Huang", "Iandelli", "Ignesti", "Innocenti", "Jin", "La Rosa", "Lai", "Landi", "Landini", "Lanini", "Lapi", "Lapini", "Lari", "Lascialfari", "Lastrucci", "Latini", "Lazzeri", "Lazzerini", "Lelli", "Lenzi", "Leonardi", "Leoncini", "Leone", "Leoni", "Lepri", "Li", "Liao", "Lin", "Linari", "Lippi", "Lisi", "Livi", "Lombardi", "Lombardini", "Lombardo", "Longo", "Lopez", "Lorenzi", "Lorenzini", "Lorini", "Lotti", "Lu", "Lucchesi", "Lucherini", "Lunghi", "Lupi", "Madiai", "Maestrini", "Maffei", "Maggi", "Maggini", "Magherini", "Magini", "Magnani", "Magnelli", "Magni", "Magnolfi", "Magrini", "Malavolti", "Malevolti", "Manca", "Mancini", "Manetti", "Manfredi", "Mangani", "Mannelli", "Manni", "Mannini", "Mannucci", "Manuelli", "Manzini", "Marcelli", "Marchese", "Marchetti", "Marchi", "Marchiani", "Marchionni", "Marconi", "Marcucci", "Margheri", "Mari", "Mariani", "Marilli", "Marinai", "Marinari", "Marinelli", "Marini", "Marino", "Mariotti", "Marsili", "Martelli", "Martinelli", "Martini", "Martino", "Marzi", "Masi", "Masini", "Masoni", "Massai", "Materassi", "Mattei", "Matteini", "Matteucci", "Matteuzzi", "Mattioli", "Mattolini", "Matucci", "Mauro", "Mazzanti", "Mazzei", "Mazzetti", "Mazzi", "Mazzini", "Mazzocchi", "Mazzoli", "Mazzoni", "Mazzuoli", "Meacci", "Mecocci", "Meini", "Melani", "Mele", "Meli", "Mengoni", "Menichetti", "Meoni", "Merlini", "Messeri", "Messina", "Meucci", "Miccinesi", "Miceli", "Micheli", "Michelini", "Michelozzi", "Migliori", "Migliorini", "Milani", "Miniati", "Misuri", "Monaco", "Montagnani", "Montagni", "Montanari", "Montelatici", "Monti", "Montigiani", "Montini", "Morandi", "Morandini", "Morelli", "Moretti", "Morganti", "Mori", "Morini", "Moroni", "Morozzi", "Mugnai", "Mugnaini", "Mustafa", "Naldi", "Naldini", "Nannelli", "Nanni", "Nannini", "Nannucci", "Nardi", "Nardini", "Nardoni", "Natali", "Ndiaye", "Nencetti", "Nencini", "Nencioni", "Neri", "Nesi", "Nesti", "Niccolai", "Niccoli", "Niccolini", "Nigi", "Nistri", "Nocentini", "Noferini", "Novelli", "Nucci", "Nuti", "Nutini", "Oliva", "Olivieri", "Olmi", "Orlandi", "Orlandini", "Orlando", "Orsini", "Ortolani", "Ottanelli", "Pacciani", "Pace", "Paci", "Pacini", "Pagani", "Pagano", "Paggetti", "Pagliai", "Pagni", "Pagnini", "Paladini", "Palagi", "Palchetti", "Palloni", "Palmieri", "Palumbo", "Pampaloni", "Pancani", "Pandolfi", "Pandolfini", "Panerai", "Panichi", "Paoletti", "Paoli", "Paolini", "Papi", "Papini", "Papucci", "Parenti", "Parigi", "Parisi", "Parri", "Parrini", "Pasquini", "Passeri", "Pecchioli", "Pecorini", "Pellegrini", "Pepi", "Perini", "Perrone", "Peruzzi", "Pesci", "Pestelli", "Petri", "Petrini", "Petrucci", "Pettini", "Pezzati", "Pezzatini", "Piani", "Piazza", "Piazzesi", "Piazzini", "Piccardi", "Picchi", "Piccini", "Piccioli", "Pieraccini", "Pieraccioni", "Pieralli", "Pierattini", "Pieri", "Pierini", "Pieroni", "Pietrini", "Pini", "Pinna", "Pinto", "Pinzani", "Pinzauti", "Piras", "Pisani", "Pistolesi", "Poggesi", "Poggi", "Poggiali", "Poggiolini", "Poli", "Pollastri", "Porciani", "Pozzi", "Pratellesi", "Pratesi", "Prosperi", "Pruneti", "Pucci", "Puccini", "Puccioni", "Pugi", "Pugliese", "Puliti", "Querci", "Quercioli", "Raddi", "Radu", "Raffaelli", "Ragazzini", "Ranfagni", "Ranieri", "Rastrelli", "Raugei", "Raveggi", "Renai", "Renzi", "Rettori", "Ricci", "Ricciardi", "Ridi", "Ridolfi", "Rigacci", "Righi", "Righini", "Rinaldi", "Risaliti", "Ristori", "Rizzo", "Rocchi", "Rocchini", "Rogai", "Romagnoli", "Romanelli", "Romani", "Romano", "Romei", "Romeo", "Romiti", "Romoli", "Romolini", "Rontini", "Rosati", "Roselli", "Rosi", "Rossetti", "Rossi", "Rossini", "Rovai", "Ruggeri", "Ruggiero", "Russo", "Sabatini", "Saccardi", "Sacchetti", "Sacchi", "Sacco", "Salerno", "Salimbeni", "Salucci", "Salvadori", "Salvestrini", "Salvi", "Salvini", "Sanesi", "Sani", "Sanna", "Santi", "Santini", "Santoni", "Santoro", "Santucci", "Sardi", "Sarri", "Sarti", "Sassi", "Sbolci", "Scali", "Scarpelli", "Scarselli", "Scopetani", "Secci", "Selvi", "Senatori", "Senesi", "Serafini", "Sereni", "Serra", "Sestini", "Sguanci", "Sieni", "Signorini", "Silvestri", "Simoncini", "Simonetti", "Simoni", "Singh", "Sodi", "Soldi", "Somigli", "Sorbi", "Sorelli", "Sorrentino", "Sottili", "Spina", "Spinelli", "Staccioli", "Staderini", "Stefanelli", "Stefani", "Stefanini", "Stella", "Susini", "Tacchi", "Tacconi", "Taddei", "Tagliaferri", "Tamburini", "Tanganelli", "Tani", "Tanini", "Tapinassi", "Tarchi", "Tarchiani", "Targioni", "Tassi", "Tassini", "Tempesti", "Terzani", "Tesi", "Testa", "Testi", "Tilli", "Tinti", "Tirinnanzi", "Toccafondi", "Tofanari", "Tofani", "Tognaccini", "Tonelli", "Tonini", "Torelli", "Torrini", "Tosi", "Toti", "Tozzi", "Trambusti", "Trapani", "Tucci", "Turchi", "Ugolini", "Ulivi", "Valente", "Valenti", "Valentini", "Vangelisti", "Vanni", "Vannini", "Vannoni", "Vannozzi", "Vannucchi", "Vannucci", "Ventura", "Venturi", "Venturini", "Vestri", "Vettori", "Vichi", "Viciani", "Vieri", "Vigiani", "Vignoli", "Vignolini", "Vignozzi", "Villani", "Vinci", "Visani", "Vitale", "Vitali", "Viti", "Viviani", "Vivoli", "Volpe", "Volpi", "Wang", "Wu", "Xu", "Yang", "Ye", "Zagli", "Zani", "Zanieri", "Zanobini", "Zecchi", "Zetti", "Zhang", "Zheng", "Zhou", "Zhu", "Zingoni", "Zini", "Zoppi"], + // http://www.voornamelijk.nl/meest-voorkomende-achternamen-in-nederland-en-amsterdam/ + "nl":["Albers", "Alblas", "Appelman", "Baars", "Baas", "Bakker", "Blank", "Bleeker", "Blok", "Blom", "Boer", "Boers", "Boldewijn", "Boon", "Boot", "Bos", "Bosch", "Bosma", "Bosman", "Bouma", "Bouman", "Bouwman", "Brands", "Brouwer", "Burger", "Buijs", "Buitenhuis", "Ceder", "Cohen", "Dekker", "Dekkers", "Dijkman", "Dijkstra", "Driessen", "Drost", "Engel", "Evers", "Faber", "Franke", "Gerritsen", "Goedhart", "Goossens", "Groen", "Groenenberg", "Groot", "Haan", "Hart", "Heemskerk", "Hendriks", "Hermans", "Hoekstra", "Hofman", "Hopman", "Huisman", "Jacobs", "Jansen", "Janssen", "Jonker", "Jaspers", "Keijzer", "Klaassen", "Klein", "Koek", "Koenders", "Kok", "Kool", "Koopman", "Koopmans", "Koning", "Koster", "Kramer", "Kroon", "Kuijpers", "Kuiper", "Kuipers", "Kurt", "Koster", "Kwakman", "Los", "Lubbers", "Maas", "Markus", "Martens", "Meijer", "Mol", "Molenaar", "Mulder", "Nieuwenhuis", "Peeters", "Peters", "Pengel", "Pieters", "Pool", "Post", "Postma", "Prins", "Pronk", "Reijnders", "Rietveld", "Roest", "Roos", "Sanders", "Schaap", "Scheffer", "Schenk", "Schilder", "Schipper", "Schmidt", "Scholten", "Schouten", "Schut", "Schutte", "Schuurman", "Simons", "Smeets", "Smit", "Smits", "Snel", "Swinkels", "Tas", "Terpstra", "Timmermans", "Tol", "Tromp", "Troost", "Valk", "Veenstra", "Veldkamp", "Verbeek", "Verheul", "Verhoeven", "Vermeer", "Vermeulen", "Verweij", "Vink", "Visser", "Voorn", "Vos", "Wagenaar", "Wiersema", "Willems", "Willemsen", "Witteveen", "Wolff", "Wolters", "Zijlstra", "Zwart", "de Beer", "de Boer", "de Bruijn", "de Bruin", "de Graaf", "de Groot", "de Haan", "de Haas", "de Jager", "de Jong", "de Jonge", "de Koning", "de Lange", "de Leeuw", "de Ridder", "de Rooij", "de Ruiter", "de Vos", "de Vries", "de Waal", "de Wit", "de Zwart", "van Beek", "van Boven", "van Dam", "van Dijk", "van Dongen", "van Doorn", "van Egmond", "van Eijk", "van Es", "van Gelder", "van Gelderen", "van Houten", "van Hulst", "van Kempen", "van Kesteren", "van Leeuwen", "van Loon", "van Mill", "van Noord", "van Ommen", "van Ommeren", "van Oosten", "van Oostveen", "van Rijn", "van Schaik", "van Veen", "van Vliet", "van Wijk", "van Wijngaarden", "van den Poel", "van de Pol", "van den Ploeg", "van de Ven", "van den Berg", "van den Bosch", "van den Brink", "van den Broek", "van den Heuvel", "van der Heijden", "van der Horst", "van der Hulst", "van der Kroon", "van der Laan", "van der Linden", "van der Meer", "van der Meij", "van der Meulen", "van der Molen", "van der Sluis", "van der Spek", "van der Veen", "van der Velde", "van der Velden", "van der Vliet", "van der Wal"], + // https://surnames.behindthename.com/top/lists/england-wales/1991 + "uk":["Smith","Jones","Williams","Taylor","Brown","Davies","Evans","Wilson","Thomas","Johnson","Roberts","Robinson","Thompson","Wright","Walker","White","Edwards","Hughes","Green","Hall","Lewis","Harris","Clarke","Patel","Jackson","Wood","Turner","Martin","Cooper","Hill","Ward","Morris","Moore","Clark","Lee","King","Baker","Harrison","Morgan","Allen","James","Scott","Phillips","Watson","Davis","Parker","Price","Bennett","Young","Griffiths","Mitchell","Kelly","Cook","Carter","Richardson","Bailey","Collins","Bell","Shaw","Murphy","Miller","Cox","Richards","Khan","Marshall","Anderson","Simpson","Ellis","Adams","Singh","Begum","Wilkinson","Foster","Chapman","Powell","Webb","Rogers","Gray","Mason","Ali","Hunt","Hussain","Campbell","Matthews","Owen","Palmer","Holmes","Mills","Barnes","Knight","Lloyd","Butler","Russell","Barker","Fisher","Stevens","Jenkins","Murray","Dixon","Harvey","Graham","Pearson","Ahmed","Fletcher","Walsh","Kaur","Gibson","Howard","Andrews","Stewart","Elliott","Reynolds","Saunders","Payne","Fox","Ford","Pearce","Day","Brooks","West","Lawrence","Cole","Atkinson","Bradley","Spencer","Gill","Dawson","Ball","Burton","O'brien","Watts","Rose","Booth","Perry","Ryan","Grant","Wells","Armstrong","Francis","Rees","Hayes","Hart","Hudson","Newman","Barrett","Webster","Hunter","Gregory","Carr","Lowe","Page","Marsh","Riley","Dunn","Woods","Parsons","Berry","Stone","Reid","Holland","Hawkins","Harding","Porter","Robertson","Newton","Oliver","Reed","Kennedy","Williamson","Bird","Gardner","Shah","Dean","Lane","Cooke","Bates","Henderson","Parry","Burgess","Bishop","Walton","Burns","Nicholson","Shepherd","Ross","Cross","Long","Freeman","Warren","Nicholls","Hamilton","Byrne","Sutton","Mcdonald","Yates","Hodgson","Robson","Curtis","Hopkins","O'connor","Harper","Coleman","Watkins","Moss","Mccarthy","Chambers","O'neill","Griffin","Sharp","Hardy","Wheeler","Potter","Osborne","Johnston","Gordon","Doyle","Wallace","George","Jordan","Hutchinson","Rowe","Burke","May","Pritchard","Gilbert","Willis","Higgins","Read","Miles","Stevenson","Stephenson","Hammond","Arnold","Buckley","Walters","Hewitt","Barber","Nelson","Slater","Austin","Sullivan","Whitehead","Mann","Frost","Lambert","Stephens","Blake","Akhtar","Lynch","Goodwin","Barton","Woodward","Thomson","Cunningham","Quinn","Barnett","Baxter","Bibi","Clayton","Nash","Greenwood","Jennings","Holt","Kemp","Poole","Gallagher","Bond","Stokes","Tucker","Davidson","Fowler","Heath","Norman","Middleton","Lawson","Banks","French","Stanley","Jarvis","Gibbs","Ferguson","Hayward","Carroll","Douglas","Dickinson","Todd","Barlow","Peters","Lucas","Knowles","Hartley","Miah","Simmons","Morton","Alexander","Field","Morrison","Norris","Townsend","Preston","Hancock","Thornton","Baldwin","Burrows","Briggs","Parkinson","Reeves","Macdonald","Lamb","Black","Abbott","Sanders","Thorpe","Holden","Tomlinson","Perkins","Ashton","Rhodes","Fuller","Howe","Bryant","Vaughan","Dale","Davey","Weston","Bartlett","Whittaker","Davison","Kent","Skinner","Birch","Morley","Daniels","Glover","Howell","Cartwright","Pugh","Humphreys","Goddard","Brennan","Wall","Kirby","Bowen","Savage","Bull","Wong","Dobson","Smart","Wilkins","Kirk","Fraser","Duffy","Hicks","Patterson","Bradshaw","Little","Archer","Warner","Waters","O'sullivan","Farrell","Brookes","Atkins","Kay","Dodd","Bentley","Flynn","John","Schofield","Short","Haynes","Wade","Butcher","Henry","Sanderson","Crawford","Sheppard","Bolton","Coates","Giles","Gould","Houghton","Gibbons","Pratt","Manning","Law","Hooper","Noble","Dyer","Rahman","Clements","Moran","Sykes","Chan","Doherty","Connolly","Joyce","Franklin","Hobbs","Coles","Herbert","Steele","Kerr","Leach","Winter","Owens","Duncan","Naylor","Fleming","Horton","Finch","Fitzgerald","Randall","Carpenter","Marsden","Browne","Garner","Pickering","Hale","Dennis","Vincent","Chadwick","Chandler","Sharpe","Nolan","Lyons","Hurst","Collier","Peacock","Howarth","Faulkner","Rice","Pollard","Welch","Norton","Gough","Sinclair","Blackburn","Bryan","Conway","Power","Cameron","Daly","Allan","Hanson","Gardiner","Boyle","Myers","Turnbull","Wallis","Mahmood","Sims","Swift","Iqbal","Pope","Brady","Chamberlain","Rowley","Tyler","Farmer","Metcalfe","Hilton","Godfrey","Holloway","Parkin","Bray","Talbot","Donnelly","Nixon","Charlton","Benson","Whitehouse","Barry","Hope","Lord","North","Storey","Connor","Potts","Bevan","Hargreaves","Mclean","Mistry","Bruce","Howells","Hyde","Parkes","Wyatt","Fry","Lees","O'donnell","Craig","Forster","Mckenzie","Humphries","Mellor","Carey","Ingram","Summers","Leonard"], + // https://surnames.behindthename.com/top/lists/germany/2017 + "de": ["Müller","Schmidt","Schneider","Fischer","Weber","Meyer","Wagner","Becker","Schulz","Hoffmann","SchƤfer","Koch","Bauer","Richter","Klein","Wolf","Schrƶder","Neumann","Schwarz","Zimmermann","Braun","Krüger","Hofmann","Hartmann","Lange","Schmitt","Werner","Schmitz","Krause","Meier","Lehmann","Schmid","Schulze","Maier","Kƶhler","Herrmann","Kƶnig","Walter","Mayer","Huber","Kaiser","Fuchs","Peters","Lang","Scholz","Mƶller","Weiß","Jung","Hahn","Schubert","Vogel","Friedrich","Keller","Günther","Frank","Berger","Winkler","Roth","Beck","Lorenz","Baumann","Franke","Albrecht","Schuster","Simon","Ludwig","Bƶhm","Winter","Kraus","Martin","Schumacher","KrƤmer","Vogt","Stein","JƤger","Otto","Sommer","Groß","Seidel","Heinrich","Brandt","Haas","Schreiber","Graf","Schulte","Dietrich","Ziegler","Kuhn","Kühn","Pohl","Engel","Horn","Busch","Bergmann","Thomas","Voigt","Sauer","Arnold","Wolff","Pfeiffer"], + // http://www.japantimes.co.jp/life/2009/10/11/lifestyle/japans-top-100-most-common-family-names/ + "jp": ["Sato","Suzuki","Takahashi","Tanaka","Watanabe","Ito","Yamamoto","Nakamura","Kobayashi","Kato","Yoshida","Yamada","Sasaki","Yamaguchi","Saito","Matsumoto","Inoue","Kimura","Hayashi","Shimizu","Yamazaki","Mori","Abe","Ikeda","Hashimoto","Yamashita","Ishikawa","Nakajima","Maeda","Fujita","Ogawa","Goto","Okada","Hasegawa","Murakami","Kondo","Ishii","Saito","Sakamoto","Endo","Aoki","Fujii","Nishimura","Fukuda","Ota","Miura","Fujiwara","Okamoto","Matsuda","Nakagawa","Nakano","Harada","Ono","Tamura","Takeuchi","Kaneko","Wada","Nakayama","Ishida","Ueda","Morita","Hara","Shibata","Sakai","Kudo","Yokoyama","Miyazaki","Miyamoto","Uchida","Takagi","Ando","Taniguchi","Ohno","Maruyama","Imai","Takada","Fujimoto","Takeda","Murata","Ueno","Sugiyama","Masuda","Sugawara","Hirano","Kojima","Otsuka","Chiba","Kubo","Matsui","Iwasaki","Sakurai","Kinoshita","Noguchi","Matsuo","Nomura","Kikuchi","Sano","Onishi","Sugimoto","Arai"], + // http://www.lowchensaustralia.com/names/popular-spanish-names.htm + "es": ["Garcia","Fernandez","Lopez","Martinez","Gonzalez","Rodriguez","Sanchez","Perez","Martin","Gomez","Ruiz","Diaz","Hernandez","Alvarez","Jimenez","Moreno","Munoz","Alonso","Romero","Navarro","Gutierrez","Torres","Dominguez","Gil","Vazquez","Blanco","Serrano","Ramos","Castro","Suarez","Sanz","Rubio","Ortega","Molina","Delgado","Ortiz","Morales","Ramirez","Marin","Iglesias","Santos","Castillo","Garrido","Calvo","Pena","Cruz","Cano","Nunez","Prieto","Diez","Lozano","Vidal","Pascual","Ferrer","Medina","Vega","Leon","Herrero","Vicente","Mendez","Guerrero","Fuentes","Campos","Nieto","Cortes","Caballero","Ibanez","Lorenzo","Pastor","Gimenez","Saez","Soler","Marquez","Carrasco","Herrera","Montero","Arias","Crespo","Flores","Andres","Aguilar","Hidalgo","Cabrera","Mora","Duran","Velasco","Rey","Pardo","Roman","Vila","Bravo","Merino","Moya","Soto","Izquierdo","Reyes","Redondo","Marcos","Carmona","Menendez"], + // Data taken from https://fr.wikipedia.org/wiki/Liste_des_noms_de_famille_les_plus_courants_en_France + "fr": ["Martin","Bernard","Thomas","Petit","Robert","Richard","Durand","Dubois","Moreau","Laurent","Simon","Michel","LefĆØvre","Leroy","Roux","David","Bertrand","Morel","Fournier","Girard","Bonnet","Dupont","Lambert","Fontaine","Rousseau","Vincent","Müller","LefĆØvre","Faure","AndrĆ©","Mercier","Blanc","GuĆ©rin","Boyer","Garnier","Chevalier","FranƧois","Legrand","Gauthier","Garcia","Perrin","Robin","ClĆ©ment","Morin","Nicolas","Henry","Roussel","Matthieu","Gautier","Masson","Marchand","Duval","Denis","Dumont","Marie","Lemaire","NoĆ«l","Meyer","Dufour","Meunier","Brun","Blanchard","Giraud","Joly","RiviĆØre","Lucas","Brunet","Gaillard","Barbier","Arnaud","MartĆ­nez","GĆ©rard","Roche","Renard","Schmitt","Roy","Leroux","Colin","Vidal","Caron","Picard","Roger","Fabre","Aubert","Lemoine","Renaud","Dumas","Lacroix","Olivier","Philippe","Bourgeois","Pierre","BenoĆ®t","Rey","Leclerc","Payet","Rolland","Leclercq","Guillaume","Lecomte","López","Jean","Dupuy","Guillot","Hubert","Berger","Carpentier","SĆ”nchez","Dupuis","Moulin","Louis","Deschamps","Huet","Vasseur","Perez","Boucher","Fleury","Royer","Klein","Jacquet","Adam","Paris","Poirier","Marty","Aubry","Guyot","CarrĆ©","Charles","Renault","Charpentier","MĆ©nard","Maillard","Baron","Bertin","Bailly","HervĆ©","Schneider","FernĆ”ndez","Le GallGall","Collet","LĆ©ger","Bouvier","Julien","PrĆ©vost","Millet","Perrot","Daniel","Le RouxRoux","Cousin","Germain","Breton","Besson","Langlois","RĆ©mi","Le GoffGoff","Pelletier","LĆ©vĆŖque","Perrier","Leblanc","BarrĆ©","Lebrun","Marchal","Weber","Mallet","Hamon","Boulanger","Jacob","Monnier","Michaud","RodrĆ­guez","Guichard","Gillet","Ɖtienne","Grondin","Poulain","Tessier","Chevallier","Collin","Chauvin","Da SilvaSilva","Bouchet","Gay","LemaĆ®tre","BĆ©nard","MarĆ©chal","Humbert","Reynaud","Antoine","Hoarau","Perret","BarthĆ©lemy","Cordier","Pichon","Lejeune","Gilbert","Lamy","Delaunay","Pasquier","Carlier","LaporteLaporte"] + }, - return new Promise((resolve, reject) => { - const signalListenerCleanup = signal - ? util.addAbortListener(signal, () => { - this.destroy() - }) - : noop + // Data taken from http://geoportal.statistics.gov.uk/datasets/ons-postcode-directory-latest-centroids + postcodeAreas: [{code: 'AB'}, {code: 'AL'}, {code: 'B'}, {code: 'BA'}, {code: 'BB'}, {code: 'BD'}, {code: 'BH'}, {code: 'BL'}, {code: 'BN'}, {code: 'BR'}, {code: 'BS'}, {code: 'BT'}, {code: 'CA'}, {code: 'CB'}, {code: 'CF'}, {code: 'CH'}, {code: 'CM'}, {code: 'CO'}, {code: 'CR'}, {code: 'CT'}, {code: 'CV'}, {code: 'CW'}, {code: 'DA'}, {code: 'DD'}, {code: 'DE'}, {code: 'DG'}, {code: 'DH'}, {code: 'DL'}, {code: 'DN'}, {code: 'DT'}, {code: 'DY'}, {code: 'E'}, {code: 'EC'}, {code: 'EH'}, {code: 'EN'}, {code: 'EX'}, {code: 'FK'}, {code: 'FY'}, {code: 'G'}, {code: 'GL'}, {code: 'GU'}, {code: 'GY'}, {code: 'HA'}, {code: 'HD'}, {code: 'HG'}, {code: 'HP'}, {code: 'HR'}, {code: 'HS'}, {code: 'HU'}, {code: 'HX'}, {code: 'IG'}, {code: 'IM'}, {code: 'IP'}, {code: 'IV'}, {code: 'JE'}, {code: 'KA'}, {code: 'KT'}, {code: 'KW'}, {code: 'KY'}, {code: 'L'}, {code: 'LA'}, {code: 'LD'}, {code: 'LE'}, {code: 'LL'}, {code: 'LN'}, {code: 'LS'}, {code: 'LU'}, {code: 'M'}, {code: 'ME'}, {code: 'MK'}, {code: 'ML'}, {code: 'N'}, {code: 'NE'}, {code: 'NG'}, {code: 'NN'}, {code: 'NP'}, {code: 'NR'}, {code: 'NW'}, {code: 'OL'}, {code: 'OX'}, {code: 'PA'}, {code: 'PE'}, {code: 'PH'}, {code: 'PL'}, {code: 'PO'}, {code: 'PR'}, {code: 'RG'}, {code: 'RH'}, {code: 'RM'}, {code: 'S'}, {code: 'SA'}, {code: 'SE'}, {code: 'SG'}, {code: 'SK'}, {code: 'SL'}, {code: 'SM'}, {code: 'SN'}, {code: 'SO'}, {code: 'SP'}, {code: 'SR'}, {code: 'SS'}, {code: 'ST'}, {code: 'SW'}, {code: 'SY'}, {code: 'TA'}, {code: 'TD'}, {code: 'TF'}, {code: 'TN'}, {code: 'TQ'}, {code: 'TR'}, {code: 'TS'}, {code: 'TW'}, {code: 'UB'}, {code: 'W'}, {code: 'WA'}, {code: 'WC'}, {code: 'WD'}, {code: 'WF'}, {code: 'WN'}, {code: 'WR'}, {code: 'WS'}, {code: 'WV'}, {code: 'YO'}, {code: 'ZE'}], - 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() - }) - } -} + // Data taken from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 + countries: [{"name":"Afghanistan","abbreviation":"AF"},{"name":"ƅland Islands","abbreviation":"AX"},{"name":"Albania","abbreviation":"AL"},{"name":"Algeria","abbreviation":"DZ"},{"name":"American Samoa","abbreviation":"AS"},{"name":"Andorra","abbreviation":"AD"},{"name":"Angola","abbreviation":"AO"},{"name":"Anguilla","abbreviation":"AI"},{"name":"Antarctica","abbreviation":"AQ"},{"name":"Antigua and Barbuda","abbreviation":"AG"},{"name":"Argentina","abbreviation":"AR"},{"name":"Armenia","abbreviation":"AM"},{"name":"Aruba","abbreviation":"AW"},{"name":"Australia","abbreviation":"AU"},{"name":"Austria","abbreviation":"AT"},{"name":"Azerbaijan","abbreviation":"AZ"},{"name":"Bahamas","abbreviation":"BS"},{"name":"Bahrain","abbreviation":"BH"},{"name":"Bangladesh","abbreviation":"BD"},{"name":"Barbados","abbreviation":"BB"},{"name":"Belarus","abbreviation":"BY"},{"name":"Belgium","abbreviation":"BE"},{"name":"Belize","abbreviation":"BZ"},{"name":"Benin","abbreviation":"BJ"},{"name":"Bermuda","abbreviation":"BM"},{"name":"Bhutan","abbreviation":"BT"},{"name":"Plurinational State of Bolivia","abbreviation":"BO"},{"name":"Bonaire, Sint Eustatius and Saba","abbreviation":"BQ"},{"name":"Bosnia and Herzegovina","abbreviation":"BA"},{"name":"Botswana","abbreviation":"BW"},{"name":"Bouvet Island","abbreviation":"BV"},{"name":"Brazil","abbreviation":"BR"},{"name":"British Indian Ocean Territory","abbreviation":"IO"},{"name":"Brunei Darussalam","abbreviation":"BN"},{"name":"Bulgaria","abbreviation":"BG"},{"name":"Burkina Faso","abbreviation":"BF"},{"name":"Burundi","abbreviation":"BI"},{"name":"Cabo Verde","abbreviation":"CV"},{"name":"Cambodia","abbreviation":"KH"},{"name":"Cameroon","abbreviation":"CM"},{"name":"Canada","abbreviation":"CA"},{"name":"Cayman Islands","abbreviation":"KY"},{"name":"Central African Republic","abbreviation":"CF"},{"name":"Chad","abbreviation":"TD"},{"name":"Chile","abbreviation":"CL"},{"name":"China","abbreviation":"CN"},{"name":"Christmas Island","abbreviation":"CX"},{"name":"Cocos (Keeling) Islands","abbreviation":"CC"},{"name":"Colombia","abbreviation":"CO"},{"name":"Comoros","abbreviation":"KM"},{"name":"Congo","abbreviation":"CG"},{"name":"Democratic Republic of the Congo","abbreviation":"CD"},{"name":"Cook Islands","abbreviation":"CK"},{"name":"Costa Rica","abbreviation":"CR"},{"name":"CĆ“te d'Ivoire","abbreviation":"CI"},{"name":"Croatia","abbreviation":"HR"},{"name":"Cuba","abbreviation":"CU"},{"name":"CuraƧao","abbreviation":"CW"},{"name":"Cyprus","abbreviation":"CY"},{"name":"Czechia","abbreviation":"CZ"},{"name":"Denmark","abbreviation":"DK"},{"name":"Djibouti","abbreviation":"DJ"},{"name":"Dominica","abbreviation":"DM"},{"name":"Dominican Republic","abbreviation":"DO"},{"name":"Ecuador","abbreviation":"EC"},{"name":"Egypt","abbreviation":"EG"},{"name":"El Salvador","abbreviation":"SV"},{"name":"Equatorial Guinea","abbreviation":"GQ"},{"name":"Eritrea","abbreviation":"ER"},{"name":"Estonia","abbreviation":"EE"},{"name":"Eswatini","abbreviation":"SZ"},{"name":"Ethiopia","abbreviation":"ET"},{"name":"Falkland Islands (Malvinas)","abbreviation":"FK"},{"name":"Faroe Islands","abbreviation":"FO"},{"name":"Fiji","abbreviation":"FJ"},{"name":"Finland","abbreviation":"FI"},{"name":"France","abbreviation":"FR"},{"name":"French Guiana","abbreviation":"GF"},{"name":"French Polynesia","abbreviation":"PF"},{"name":"French Southern Territories","abbreviation":"TF"},{"name":"Gabon","abbreviation":"GA"},{"name":"Gambia","abbreviation":"GM"},{"name":"Georgia","abbreviation":"GE"},{"name":"Germany","abbreviation":"DE"},{"name":"Ghana","abbreviation":"GH"},{"name":"Gibraltar","abbreviation":"GI"},{"name":"Greece","abbreviation":"GR"},{"name":"Greenland","abbreviation":"GL"},{"name":"Grenada","abbreviation":"GD"},{"name":"Guadeloupe","abbreviation":"GP"},{"name":"Guam","abbreviation":"GU"},{"name":"Guatemala","abbreviation":"GT"},{"name":"Guernsey","abbreviation":"GG"},{"name":"Guinea","abbreviation":"GN"},{"name":"Guinea-Bissau","abbreviation":"GW"},{"name":"Guyana","abbreviation":"GY"},{"name":"Haiti","abbreviation":"HT"},{"name":"Heard Island and McDonald Islands","abbreviation":"HM"},{"name":"Holy See","abbreviation":"VA"},{"name":"Honduras","abbreviation":"HN"},{"name":"Hong Kong","abbreviation":"HK"},{"name":"Hungary","abbreviation":"HU"},{"name":"Iceland","abbreviation":"IS"},{"name":"India","abbreviation":"IN"},{"name":"Indonesia","abbreviation":"ID"},{"name":"Islamic Republic of Iran","abbreviation":"IR"},{"name":"Iraq","abbreviation":"IQ"},{"name":"Ireland","abbreviation":"IE"},{"name":"Isle of Man","abbreviation":"IM"},{"name":"Israel","abbreviation":"IL"},{"name":"Italy","abbreviation":"IT"},{"name":"Jamaica","abbreviation":"JM"},{"name":"Japan","abbreviation":"JP"},{"name":"Jersey","abbreviation":"JE"},{"name":"Jordan","abbreviation":"JO"},{"name":"Kazakhstan","abbreviation":"KZ"},{"name":"Kenya","abbreviation":"KE"},{"name":"Kiribati","abbreviation":"KI"},{"name":"Democratic People's Republic of Korea","abbreviation":"KP"},{"name":"Republic of Korea","abbreviation":"KR"},{"name":"Kuwait","abbreviation":"KW"},{"name":"Kyrgyzstan","abbreviation":"KG"},{"name":"Lao People's Democratic Republic","abbreviation":"LA"},{"name":"Latvia","abbreviation":"LV"},{"name":"Lebanon","abbreviation":"LB"},{"name":"Lesotho","abbreviation":"LS"},{"name":"Liberia","abbreviation":"LR"},{"name":"Libya","abbreviation":"LY"},{"name":"Liechtenstein","abbreviation":"LI"},{"name":"Lithuania","abbreviation":"LT"},{"name":"Luxembourg","abbreviation":"LU"},{"name":"Macao","abbreviation":"MO"},{"name":"Madagascar","abbreviation":"MG"},{"name":"Malawi","abbreviation":"MW"},{"name":"Malaysia","abbreviation":"MY"},{"name":"Maldives","abbreviation":"MV"},{"name":"Mali","abbreviation":"ML"},{"name":"Malta","abbreviation":"MT"},{"name":"Marshall Islands","abbreviation":"MH"},{"name":"Martinique","abbreviation":"MQ"},{"name":"Mauritania","abbreviation":"MR"},{"name":"Mauritius","abbreviation":"MU"},{"name":"Mayotte","abbreviation":"YT"},{"name":"Mexico","abbreviation":"MX"},{"name":"Federated States of Micronesia","abbreviation":"FM"},{"name":"Republic of Moldova","abbreviation":"MD"},{"name":"Monaco","abbreviation":"MC"},{"name":"Mongolia","abbreviation":"MN"},{"name":"Montenegro","abbreviation":"ME"},{"name":"Montserrat","abbreviation":"MS"},{"name":"Morocco","abbreviation":"MA"},{"name":"Mozambique","abbreviation":"MZ"},{"name":"Myanmar","abbreviation":"MM"},{"name":"Namibia","abbreviation":"NA"},{"name":"Nauru","abbreviation":"NR"},{"name":"Nepal","abbreviation":"NP"},{"name":"Kingdom of the Netherlands","abbreviation":"NL"},{"name":"New Caledonia","abbreviation":"NC"},{"name":"New Zealand","abbreviation":"NZ"},{"name":"Nicaragua","abbreviation":"NI"},{"name":"Niger","abbreviation":"NE"},{"name":"Nigeria","abbreviation":"NG"},{"name":"Niue","abbreviation":"NU"},{"name":"Norfolk Island","abbreviation":"NF"},{"name":"North Macedonia","abbreviation":"MK"},{"name":"Northern Mariana Islands","abbreviation":"MP"},{"name":"Norway","abbreviation":"NO"},{"name":"Oman","abbreviation":"OM"},{"name":"Pakistan","abbreviation":"PK"},{"name":"Palau","abbreviation":"PW"},{"name":"State of Palestine","abbreviation":"PS"},{"name":"Panama","abbreviation":"PA"},{"name":"Papua New Guinea","abbreviation":"PG"},{"name":"Paraguay","abbreviation":"PY"},{"name":"Peru","abbreviation":"PE"},{"name":"Philippines","abbreviation":"PH"},{"name":"Pitcairn","abbreviation":"PN"},{"name":"Poland","abbreviation":"PL"},{"name":"Portugal","abbreviation":"PT"},{"name":"Puerto Rico","abbreviation":"PR"},{"name":"Qatar","abbreviation":"QA"},{"name":"RĆ©union","abbreviation":"RE"},{"name":"Romania","abbreviation":"RO"},{"name":"Russian Federation","abbreviation":"RU"},{"name":"Rwanda","abbreviation":"RW"},{"name":"Saint BarthĆ©lemy","abbreviation":"BL"},{"name":"Saint Helena, Ascension and Tristan da Cunha","abbreviation":"SH"},{"name":"Saint Kitts and Nevis","abbreviation":"KN"},{"name":"Saint Lucia","abbreviation":"LC"},{"name":"Saint Martin (French part)","abbreviation":"MF"},{"name":"Saint Pierre and Miquelon","abbreviation":"PM"},{"name":"Saint Vincent and the Grenadines","abbreviation":"VC"},{"name":"Samoa","abbreviation":"WS"},{"name":"San Marino","abbreviation":"SM"},{"name":"Sao Tome and Principe","abbreviation":"ST"},{"name":"Saudi Arabia","abbreviation":"SA"},{"name":"Senegal","abbreviation":"SN"},{"name":"Serbia","abbreviation":"RS"},{"name":"Seychelles","abbreviation":"SC"},{"name":"Sierra Leone","abbreviation":"SL"},{"name":"Singapore","abbreviation":"SG"},{"name":"Sint Maarten (Dutch part)","abbreviation":"SX"},{"name":"Slovakia","abbreviation":"SK"},{"name":"Slovenia","abbreviation":"SI"},{"name":"Solomon Islands","abbreviation":"SB"},{"name":"Somalia","abbreviation":"SO"},{"name":"South Africa","abbreviation":"ZA"},{"name":"South Georgia and the South Sandwich Islands","abbreviation":"GS"},{"name":"South Sudan","abbreviation":"SS"},{"name":"Spain","abbreviation":"ES"},{"name":"Sri Lanka","abbreviation":"LK"},{"name":"Sudan","abbreviation":"SD"},{"name":"Suriname","abbreviation":"SR"},{"name":"Svalbard and Jan Mayen","abbreviation":"SJ"},{"name":"Sweden","abbreviation":"SE"},{"name":"Switzerland","abbreviation":"CH"},{"name":"Syrian Arab Republic","abbreviation":"SY"},{"name":"Taiwan, Province of China","abbreviation":"TW"},{"name":"Tajikistan","abbreviation":"TJ"},{"name":"United Republic of Tanzania","abbreviation":"TZ"},{"name":"Thailand","abbreviation":"TH"},{"name":"Timor-Leste","abbreviation":"TL"},{"name":"Togo","abbreviation":"TG"},{"name":"Tokelau","abbreviation":"TK"},{"name":"Tonga","abbreviation":"TO"},{"name":"Trinidad and Tobago","abbreviation":"TT"},{"name":"Tunisia","abbreviation":"TN"},{"name":"Türkiye","abbreviation":"TR"},{"name":"Turkmenistan","abbreviation":"TM"},{"name":"Turks and Caicos Islands","abbreviation":"TC"},{"name":"Tuvalu","abbreviation":"TV"},{"name":"Uganda","abbreviation":"UG"},{"name":"Ukraine","abbreviation":"UA"},{"name":"United Arab Emirates","abbreviation":"AE"},{"name":"United Kingdom of Great Britain and Northern Ireland","abbreviation":"GB"},{"name":"United States Minor Outlying Islands","abbreviation":"UM"},{"name":"United States of America","abbreviation":"US"},{"name":"Uruguay","abbreviation":"UY"},{"name":"Uzbekistan","abbreviation":"UZ"},{"name":"Vanuatu","abbreviation":"VU"},{"name":"Bolivarian Republic of Venezuela","abbreviation":"VE"},{"name":"Viet Nam","abbreviation":"VN"},{"name":"Virgin Islands (British)","abbreviation":"VG"},{"name":"Virgin Islands (U.S.)","abbreviation":"VI"},{"name":"Wallis and Futuna","abbreviation":"WF"},{"name":"Western Sahara","abbreviation":"EH"},{"name":"Yemen","abbreviation":"YE"},{"name":"Zambia","abbreviation":"ZM"},{"name":"Zimbabwe","abbreviation":"ZW"}], -// https://streams.spec.whatwg.org/#readablestream-locked -function isLocked (self) { - // Consume is an implicit lock. - return (self[kBody] && self[kBody].locked === true) || self[kConsume] -} + counties: { + // Data taken from http://www.downloadexcelfiles.com/gb_en/download-excel-file-list-counties-uk + "uk": [ + {name: 'Bath and North East Somerset'}, + {name: 'Aberdeenshire'}, + {name: 'Anglesey'}, + {name: 'Angus'}, + {name: 'Bedford'}, + {name: 'Blackburn with Darwen'}, + {name: 'Blackpool'}, + {name: 'Bournemouth'}, + {name: 'Bracknell Forest'}, + {name: 'Brighton & Hove'}, + {name: 'Bristol'}, + {name: 'Buckinghamshire'}, + {name: 'Cambridgeshire'}, + {name: 'Carmarthenshire'}, + {name: 'Central Bedfordshire'}, + {name: 'Ceredigion'}, + {name: 'Cheshire East'}, + {name: 'Cheshire West and Chester'}, + {name: 'Clackmannanshire'}, + {name: 'Conwy'}, + {name: 'Cornwall'}, + {name: 'County Antrim'}, + {name: 'County Armagh'}, + {name: 'County Down'}, + {name: 'County Durham'}, + {name: 'County Fermanagh'}, + {name: 'County Londonderry'}, + {name: 'County Tyrone'}, + {name: 'Cumbria'}, + {name: 'Darlington'}, + {name: 'Denbighshire'}, + {name: 'Derby'}, + {name: 'Derbyshire'}, + {name: 'Devon'}, + {name: 'Dorset'}, + {name: 'Dumfries and Galloway'}, + {name: 'Dundee'}, + {name: 'East Lothian'}, + {name: 'East Riding of Yorkshire'}, + {name: 'East Sussex'}, + {name: 'Edinburgh?'}, + {name: 'Essex'}, + {name: 'Falkirk'}, + {name: 'Fife'}, + {name: 'Flintshire'}, + {name: 'Gloucestershire'}, + {name: 'Greater London'}, + {name: 'Greater Manchester'}, + {name: 'Gwent'}, + {name: 'Gwynedd'}, + {name: 'Halton'}, + {name: 'Hampshire'}, + {name: 'Hartlepool'}, + {name: 'Herefordshire'}, + {name: 'Hertfordshire'}, + {name: 'Highlands'}, + {name: 'Hull'}, + {name: 'Isle of Wight'}, + {name: 'Isles of Scilly'}, + {name: 'Kent'}, + {name: 'Lancashire'}, + {name: 'Leicester'}, + {name: 'Leicestershire'}, + {name: 'Lincolnshire'}, + {name: 'Lothian'}, + {name: 'Luton'}, + {name: 'Medway'}, + {name: 'Merseyside'}, + {name: 'Mid Glamorgan'}, + {name: 'Middlesbrough'}, + {name: 'Milton Keynes'}, + {name: 'Monmouthshire'}, + {name: 'Moray'}, + {name: 'Norfolk'}, + {name: 'North East Lincolnshire'}, + {name: 'North Lincolnshire'}, + {name: 'North Somerset'}, + {name: 'North Yorkshire'}, + {name: 'Northamptonshire'}, + {name: 'Northumberland'}, + {name: 'Nottingham'}, + {name: 'Nottinghamshire'}, + {name: 'Oxfordshire'}, + {name: 'Pembrokeshire'}, + {name: 'Perth and Kinross'}, + {name: 'Peterborough'}, + {name: 'Plymouth'}, + {name: 'Poole'}, + {name: 'Portsmouth'}, + {name: 'Powys'}, + {name: 'Reading'}, + {name: 'Redcar and Cleveland'}, + {name: 'Rutland'}, + {name: 'Scottish Borders'}, + {name: 'Shropshire'}, + {name: 'Slough'}, + {name: 'Somerset'}, + {name: 'South Glamorgan'}, + {name: 'South Gloucestershire'}, + {name: 'South Yorkshire'}, + {name: 'Southampton'}, + {name: 'Southend-on-Sea'}, + {name: 'Staffordshire'}, + {name: 'Stirlingshire'}, + {name: 'Stockton-on-Tees'}, + {name: 'Stoke-on-Trent'}, + {name: 'Strathclyde'}, + {name: 'Suffolk'}, + {name: 'Surrey'}, + {name: 'Swindon'}, + {name: 'Telford and Wrekin'}, + {name: 'Thurrock'}, + {name: 'Torbay'}, + {name: 'Tyne and Wear'}, + {name: 'Warrington'}, + {name: 'Warwickshire'}, + {name: 'West Berkshire'}, + {name: 'West Glamorgan'}, + {name: 'West Lothian'}, + {name: 'West Midlands'}, + {name: 'West Sussex'}, + {name: 'West Yorkshire'}, + {name: 'Western Isles'}, + {name: 'Wiltshire'}, + {name: 'Windsor and Maidenhead'}, + {name: 'Wokingham'}, + {name: 'Worcestershire'}, + {name: 'Wrexham'}, + {name: 'York'}] + }, + provinces: { + "ca": [ + {name: 'Alberta', abbreviation: 'AB'}, + {name: 'British Columbia', abbreviation: 'BC'}, + {name: 'Manitoba', abbreviation: 'MB'}, + {name: 'New Brunswick', abbreviation: 'NB'}, + {name: 'Newfoundland and Labrador', abbreviation: 'NL'}, + {name: 'Nova Scotia', abbreviation: 'NS'}, + {name: 'Ontario', abbreviation: 'ON'}, + {name: 'Prince Edward Island', abbreviation: 'PE'}, + {name: 'Quebec', abbreviation: 'QC'}, + {name: 'Saskatchewan', abbreviation: 'SK'}, -// https://fetch.spec.whatwg.org/#body-unusable -function isUnusable (self) { - return util.isDisturbed(self) || isLocked(self) -} + // The case could be made that the following are not actually provinces + // since they are technically considered "territories" however they all + // look the same on an envelope! + {name: 'Northwest Territories', abbreviation: 'NT'}, + {name: 'Nunavut', abbreviation: 'NU'}, + {name: 'Yukon', abbreviation: 'YT'} + ], + "it": [ + { name: "Agrigento", abbreviation: "AG", code: 84 }, + { name: "Alessandria", abbreviation: "AL", code: 6 }, + { name: "Ancona", abbreviation: "AN", code: 42 }, + { name: "Aosta", abbreviation: "AO", code: 7 }, + { name: "L'Aquila", abbreviation: "AQ", code: 66 }, + { name: "Arezzo", abbreviation: "AR", code: 51 }, + { name: "Ascoli-Piceno", abbreviation: "AP", code: 44 }, + { name: "Asti", abbreviation: "AT", code: 5 }, + { name: "Avellino", abbreviation: "AV", code: 64 }, + { name: "Bari", abbreviation: "BA", code: 72 }, + { name: "Barletta-Andria-Trani", abbreviation: "BT", code: 72 }, + { name: "Belluno", abbreviation: "BL", code: 25 }, + { name: "Benevento", abbreviation: "BN", code: 62 }, + { name: "Bergamo", abbreviation: "BG", code: 16 }, + { name: "Biella", abbreviation: "BI", code: 96 }, + { name: "Bologna", abbreviation: "BO", code: 37 }, + { name: "Bolzano", abbreviation: "BZ", code: 21 }, + { name: "Brescia", abbreviation: "BS", code: 17 }, + { name: "Brindisi", abbreviation: "BR", code: 74 }, + { name: "Cagliari", abbreviation: "CA", code: 92 }, + { name: "Caltanissetta", abbreviation: "CL", code: 85 }, + { name: "Campobasso", abbreviation: "CB", code: 70 }, + { name: "Carbonia Iglesias", abbreviation: "CI", code: 70 }, + { name: "Caserta", abbreviation: "CE", code: 61 }, + { name: "Catania", abbreviation: "CT", code: 87 }, + { name: "Catanzaro", abbreviation: "CZ", code: 79 }, + { name: "Chieti", abbreviation: "CH", code: 69 }, + { name: "Como", abbreviation: "CO", code: 13 }, + { name: "Cosenza", abbreviation: "CS", code: 78 }, + { name: "Cremona", abbreviation: "CR", code: 19 }, + { name: "Crotone", abbreviation: "KR", code: 101 }, + { name: "Cuneo", abbreviation: "CN", code: 4 }, + { name: "Enna", abbreviation: "EN", code: 86 }, + { name: "Fermo", abbreviation: "FM", code: 86 }, + { name: "Ferrara", abbreviation: "FE", code: 38 }, + { name: "Firenze", abbreviation: "FI", code: 48 }, + { name: "Foggia", abbreviation: "FG", code: 71 }, + { name: "Forli-Cesena", abbreviation: "FC", code: 71 }, + { name: "Frosinone", abbreviation: "FR", code: 60 }, + { name: "Genova", abbreviation: "GE", code: 10 }, + { name: "Gorizia", abbreviation: "GO", code: 31 }, + { name: "Grosseto", abbreviation: "GR", code: 53 }, + { name: "Imperia", abbreviation: "IM", code: 8 }, + { name: "Isernia", abbreviation: "IS", code: 94 }, + { name: "La-Spezia", abbreviation: "SP", code: 66 }, + { name: "Latina", abbreviation: "LT", code: 59 }, + { name: "Lecce", abbreviation: "LE", code: 75 }, + { name: "Lecco", abbreviation: "LC", code: 97 }, + { name: "Livorno", abbreviation: "LI", code: 49 }, + { name: "Lodi", abbreviation: "LO", code: 98 }, + { name: "Lucca", abbreviation: "LU", code: 46 }, + { name: "Macerata", abbreviation: "MC", code: 43 }, + { name: "Mantova", abbreviation: "MN", code: 20 }, + { name: "Massa-Carrara", abbreviation: "MS", code: 45 }, + { name: "Matera", abbreviation: "MT", code: 77 }, + { name: "Medio Campidano", abbreviation: "VS", code: 77 }, + { name: "Messina", abbreviation: "ME", code: 83 }, + { name: "Milano", abbreviation: "MI", code: 15 }, + { name: "Modena", abbreviation: "MO", code: 36 }, + { name: "Monza-Brianza", abbreviation: "MB", code: 36 }, + { name: "Napoli", abbreviation: "NA", code: 63 }, + { name: "Novara", abbreviation: "NO", code: 3 }, + { name: "Nuoro", abbreviation: "NU", code: 91 }, + { name: "Ogliastra", abbreviation: "OG", code: 91 }, + { name: "Olbia Tempio", abbreviation: "OT", code: 91 }, + { name: "Oristano", abbreviation: "OR", code: 95 }, + { name: "Padova", abbreviation: "PD", code: 28 }, + { name: "Palermo", abbreviation: "PA", code: 82 }, + { name: "Parma", abbreviation: "PR", code: 34 }, + { name: "Pavia", abbreviation: "PV", code: 18 }, + { name: "Perugia", abbreviation: "PG", code: 54 }, + { name: "Pesaro-Urbino", abbreviation: "PU", code: 41 }, + { name: "Pescara", abbreviation: "PE", code: 68 }, + { name: "Piacenza", abbreviation: "PC", code: 33 }, + { name: "Pisa", abbreviation: "PI", code: 50 }, + { name: "Pistoia", abbreviation: "PT", code: 47 }, + { name: "Pordenone", abbreviation: "PN", code: 93 }, + { name: "Potenza", abbreviation: "PZ", code: 76 }, + { name: "Prato", abbreviation: "PO", code: 100 }, + { name: "Ragusa", abbreviation: "RG", code: 88 }, + { name: "Ravenna", abbreviation: "RA", code: 39 }, + { name: "Reggio-Calabria", abbreviation: "RC", code: 35 }, + { name: "Reggio-Emilia", abbreviation: "RE", code: 35 }, + { name: "Rieti", abbreviation: "RI", code: 57 }, + { name: "Rimini", abbreviation: "RN", code: 99 }, + { name: "Roma", abbreviation: "Roma", code: 58 }, + { name: "Rovigo", abbreviation: "RO", code: 29 }, + { name: "Salerno", abbreviation: "SA", code: 65 }, + { name: "Sassari", abbreviation: "SS", code: 90 }, + { name: "Savona", abbreviation: "SV", code: 9 }, + { name: "Siena", abbreviation: "SI", code: 52 }, + { name: "Siracusa", abbreviation: "SR", code: 89 }, + { name: "Sondrio", abbreviation: "SO", code: 14 }, + { name: "Taranto", abbreviation: "TA", code: 73 }, + { name: "Teramo", abbreviation: "TE", code: 67 }, + { name: "Terni", abbreviation: "TR", code: 55 }, + { name: "Torino", abbreviation: "TO", code: 1 }, + { name: "Trapani", abbreviation: "TP", code: 81 }, + { name: "Trento", abbreviation: "TN", code: 22 }, + { name: "Treviso", abbreviation: "TV", code: 26 }, + { name: "Trieste", abbreviation: "TS", code: 32 }, + { name: "Udine", abbreviation: "UD", code: 30 }, + { name: "Varese", abbreviation: "VA", code: 12 }, + { name: "Venezia", abbreviation: "VE", code: 27 }, + { name: "Verbania", abbreviation: "VB", code: 27 }, + { name: "Vercelli", abbreviation: "VC", code: 2 }, + { name: "Verona", abbreviation: "VR", code: 23 }, + { name: "Vibo-Valentia", abbreviation: "VV", code: 102 }, + { name: "Vicenza", abbreviation: "VI", code: 24 }, + { name: "Viterbo", abbreviation: "VT", code: 56 } + ] + }, -async function consume (stream, type) { - if (isUnusable(stream)) { - throw new TypeError('unusable') - } + // from: https://github.com/samsargent/Useful-Autocomplete-Data/blob/master/data/nationalities.json + nationalities: [ + {name: 'Afghan'}, + {name: 'Albanian'}, + {name: 'Algerian'}, + {name: 'American'}, + {name: 'Andorran'}, + {name: 'Angolan'}, + {name: 'Antiguans'}, + {name: 'Argentinean'}, + {name: 'Armenian'}, + {name: 'Australian'}, + {name: 'Austrian'}, + {name: 'Azerbaijani'}, + {name: 'Bahami'}, + {name: 'Bahraini'}, + {name: 'Bangladeshi'}, + {name: 'Barbadian'}, + {name: 'Barbudans'}, + {name: 'Batswana'}, + {name: 'Belarusian'}, + {name: 'Belgian'}, + {name: 'Belizean'}, + {name: 'Beninese'}, + {name: 'Bhutanese'}, + {name: 'Bolivian'}, + {name: 'Bosnian'}, + {name: 'Brazilian'}, + {name: 'British'}, + {name: 'Bruneian'}, + {name: 'Bulgarian'}, + {name: 'Burkinabe'}, + {name: 'Burmese'}, + {name: 'Burundian'}, + {name: 'Cambodian'}, + {name: 'Cameroonian'}, + {name: 'Canadian'}, + {name: 'Cape Verdean'}, + {name: 'Central African'}, + {name: 'Chadian'}, + {name: 'Chilean'}, + {name: 'Chinese'}, + {name: 'Colombian'}, + {name: 'Comoran'}, + {name: 'Congolese'}, + {name: 'Costa Rican'}, + {name: 'Croatian'}, + {name: 'Cuban'}, + {name: 'Cypriot'}, + {name: 'Czech'}, + {name: 'Danish'}, + {name: 'Djibouti'}, + {name: 'Dominican'}, + {name: 'Dutch'}, + {name: 'East Timorese'}, + {name: 'Ecuadorean'}, + {name: 'Egyptian'}, + {name: 'Emirian'}, + {name: 'Equatorial Guinean'}, + {name: 'Eritrean'}, + {name: 'Estonian'}, + {name: 'Ethiopian'}, + {name: 'Fijian'}, + {name: 'Filipino'}, + {name: 'Finnish'}, + {name: 'French'}, + {name: 'Gabonese'}, + {name: 'Gambian'}, + {name: 'Georgian'}, + {name: 'German'}, + {name: 'Ghanaian'}, + {name: 'Greek'}, + {name: 'Grenadian'}, + {name: 'Guatemalan'}, + {name: 'Guinea-Bissauan'}, + {name: 'Guinean'}, + {name: 'Guyanese'}, + {name: 'Haitian'}, + {name: 'Herzegovinian'}, + {name: 'Honduran'}, + {name: 'Hungarian'}, + {name: 'I-Kiribati'}, + {name: 'Icelander'}, + {name: 'Indian'}, + {name: 'Indonesian'}, + {name: 'Iranian'}, + {name: 'Iraqi'}, + {name: 'Irish'}, + {name: 'Israeli'}, + {name: 'Italian'}, + {name: 'Ivorian'}, + {name: 'Jamaican'}, + {name: 'Japanese'}, + {name: 'Jordanian'}, + {name: 'Kazakhstani'}, + {name: 'Kenyan'}, + {name: 'Kittian and Nevisian'}, + {name: 'Kuwaiti'}, + {name: 'Kyrgyz'}, + {name: 'Laotian'}, + {name: 'Latvian'}, + {name: 'Lebanese'}, + {name: 'Liberian'}, + {name: 'Libyan'}, + {name: 'Liechtensteiner'}, + {name: 'Lithuanian'}, + {name: 'Luxembourger'}, + {name: 'Macedonian'}, + {name: 'Malagasy'}, + {name: 'Malawian'}, + {name: 'Malaysian'}, + {name: 'Maldivan'}, + {name: 'Malian'}, + {name: 'Maltese'}, + {name: 'Marshallese'}, + {name: 'Mauritanian'}, + {name: 'Mauritian'}, + {name: 'Mexican'}, + {name: 'Micronesian'}, + {name: 'Moldovan'}, + {name: 'Monacan'}, + {name: 'Mongolian'}, + {name: 'Moroccan'}, + {name: 'Mosotho'}, + {name: 'Motswana'}, + {name: 'Mozambican'}, + {name: 'Namibian'}, + {name: 'Nauruan'}, + {name: 'Nepalese'}, + {name: 'New Zealander'}, + {name: 'Nicaraguan'}, + {name: 'Nigerian'}, + {name: 'Nigerien'}, + {name: 'North Korean'}, + {name: 'Northern Irish'}, + {name: 'Norwegian'}, + {name: 'Omani'}, + {name: 'Pakistani'}, + {name: 'Palauan'}, + {name: 'Panamanian'}, + {name: 'Papua New Guinean'}, + {name: 'Paraguayan'}, + {name: 'Peruvian'}, + {name: 'Polish'}, + {name: 'Portuguese'}, + {name: 'Qatari'}, + {name: 'Romani'}, + {name: 'Russian'}, + {name: 'Rwandan'}, + {name: 'Saint Lucian'}, + {name: 'Salvadoran'}, + {name: 'Samoan'}, + {name: 'San Marinese'}, + {name: 'Sao Tomean'}, + {name: 'Saudi'}, + {name: 'Scottish'}, + {name: 'Senegalese'}, + {name: 'Serbian'}, + {name: 'Seychellois'}, + {name: 'Sierra Leonean'}, + {name: 'Singaporean'}, + {name: 'Slovakian'}, + {name: 'Slovenian'}, + {name: 'Solomon Islander'}, + {name: 'Somali'}, + {name: 'South African'}, + {name: 'South Korean'}, + {name: 'Spanish'}, + {name: 'Sri Lankan'}, + {name: 'Sudanese'}, + {name: 'Surinamer'}, + {name: 'Swazi'}, + {name: 'Swedish'}, + {name: 'Swiss'}, + {name: 'Syrian'}, + {name: 'Taiwanese'}, + {name: 'Tajik'}, + {name: 'Tanzanian'}, + {name: 'Thai'}, + {name: 'Togolese'}, + {name: 'Tongan'}, + {name: 'Trinidadian or Tobagonian'}, + {name: 'Tunisian'}, + {name: 'Turkish'}, + {name: 'Tuvaluan'}, + {name: 'Ugandan'}, + {name: 'Ukrainian'}, + {name: 'Uruguaya'}, + {name: 'Uzbekistani'}, + {name: 'Venezuela'}, + {name: 'Vietnamese'}, + {name: 'Wels'}, + {name: 'Yemenit'}, + {name: 'Zambia'}, + {name: 'Zimbabwe'}, + ], + // http://www.loc.gov/standards/iso639-2/php/code_list.php (ISO-639-1 codes) + locale_languages: [ + "aa", + "ab", + "ae", + "af", + "ak", + "am", + "an", + "ar", + "as", + "av", + "ay", + "az", + "ba", + "be", + "bg", + "bh", + "bi", + "bm", + "bn", + "bo", + "br", + "bs", + "ca", + "ce", + "ch", + "co", + "cr", + "cs", + "cu", + "cv", + "cy", + "da", + "de", + "dv", + "dz", + "ee", + "el", + "en", + "eo", + "es", + "et", + "eu", + "fa", + "ff", + "fi", + "fj", + "fo", + "fr", + "fy", + "ga", + "gd", + "gl", + "gn", + "gu", + "gv", + "ha", + "he", + "hi", + "ho", + "hr", + "ht", + "hu", + "hy", + "hz", + "ia", + "id", + "ie", + "ig", + "ii", + "ik", + "io", + "is", + "it", + "iu", + "ja", + "jv", + "ka", + "kg", + "ki", + "kj", + "kk", + "kl", + "km", + "kn", + "ko", + "kr", + "ks", + "ku", + "kv", + "kw", + "ky", + "la", + "lb", + "lg", + "li", + "ln", + "lo", + "lt", + "lu", + "lv", + "mg", + "mh", + "mi", + "mk", + "ml", + "mn", + "mr", + "ms", + "mt", + "my", + "na", + "nb", + "nd", + "ne", + "ng", + "nl", + "nn", + "no", + "nr", + "nv", + "ny", + "oc", + "oj", + "om", + "or", + "os", + "pa", + "pi", + "pl", + "ps", + "pt", + "qu", + "rm", + "rn", + "ro", + "ru", + "rw", + "sa", + "sc", + "sd", + "se", + "sg", + "si", + "sk", + "sl", + "sm", + "sn", + "so", + "sq", + "sr", + "ss", + "st", + "su", + "sv", + "sw", + "ta", + "te", + "tg", + "th", + "ti", + "tk", + "tl", + "tn", + "to", + "tr", + "ts", + "tt", + "tw", + "ty", + "ug", + "uk", + "ur", + "uz", + "ve", + "vi", + "vo", + "wa", + "wo", + "xh", + "yi", + "yo", + "za", + "zh", + "zu" + ], - assert(!stream[kConsume]) + // From http://data.okfn.org/data/core/language-codes#resource-language-codes-full (IETF language tags) + locale_regions: [ + "agq-CM", + "asa-TZ", + "ast-ES", + "bas-CM", + "bem-ZM", + "bez-TZ", + "brx-IN", + "cgg-UG", + "chr-US", + "dav-KE", + "dje-NE", + "dsb-DE", + "dua-CM", + "dyo-SN", + "ebu-KE", + "ewo-CM", + "fil-PH", + "fur-IT", + "gsw-CH", + "gsw-FR", + "gsw-LI", + "guz-KE", + "haw-US", + "hsb-DE", + "jgo-CM", + "jmc-TZ", + "kab-DZ", + "kam-KE", + "kde-TZ", + "kea-CV", + "khq-ML", + "kkj-CM", + "kln-KE", + "kok-IN", + "ksb-TZ", + "ksf-CM", + "ksh-DE", + "lag-TZ", + "lkt-US", + "luo-KE", + "luy-KE", + "mas-KE", + "mas-TZ", + "mer-KE", + "mfe-MU", + "mgh-MZ", + "mgo-CM", + "mua-CM", + "naq-NA", + "nmg-CM", + "nnh-CM", + "nus-SD", + "nyn-UG", + "rof-TZ", + "rwk-TZ", + "sah-RU", + "saq-KE", + "sbp-TZ", + "seh-MZ", + "ses-ML", + "shi-Latn", + "shi-Latn-MA", + "shi-Tfng", + "shi-Tfng-MA", + "smn-FI", + "teo-KE", + "teo-UG", + "twq-NE", + "tzm-Latn", + "tzm-Latn-MA", + "vai-Latn", + "vai-Latn-LR", + "vai-Vaii", + "vai-Vaii-LR", + "vun-TZ", + "wae-CH", + "xog-UG", + "yav-CM", + "zgh-MA", + "af-NA", + "af-ZA", + "ak-GH", + "am-ET", + "ar-001", + "ar-AE", + "ar-BH", + "ar-DJ", + "ar-DZ", + "ar-EG", + "ar-EH", + "ar-ER", + "ar-IL", + "ar-IQ", + "ar-JO", + "ar-KM", + "ar-KW", + "ar-LB", + "ar-LY", + "ar-MA", + "ar-MR", + "ar-OM", + "ar-PS", + "ar-QA", + "ar-SA", + "ar-SD", + "ar-SO", + "ar-SS", + "ar-SY", + "ar-TD", + "ar-TN", + "ar-YE", + "as-IN", + "az-Cyrl", + "az-Cyrl-AZ", + "az-Latn", + "az-Latn-AZ", + "be-BY", + "bg-BG", + "bm-Latn", + "bm-Latn-ML", + "bn-BD", + "bn-IN", + "bo-CN", + "bo-IN", + "br-FR", + "bs-Cyrl", + "bs-Cyrl-BA", + "bs-Latn", + "bs-Latn-BA", + "ca-AD", + "ca-ES", + "ca-ES-VALENCIA", + "ca-FR", + "ca-IT", + "cs-CZ", + "cy-GB", + "da-DK", + "da-GL", + "de-AT", + "de-BE", + "de-CH", + "de-DE", + "de-LI", + "de-LU", + "dz-BT", + "ee-GH", + "ee-TG", + "el-CY", + "el-GR", + "en-001", + "en-150", + "en-AG", + "en-AI", + "en-AS", + "en-AU", + "en-BB", + "en-BE", + "en-BM", + "en-BS", + "en-BW", + "en-BZ", + "en-CA", + "en-CC", + "en-CK", + "en-CM", + "en-CX", + "en-DG", + "en-DM", + "en-ER", + "en-FJ", + "en-FK", + "en-FM", + "en-GB", + "en-GD", + "en-GG", + "en-GH", + "en-GI", + "en-GM", + "en-GU", + "en-GY", + "en-HK", + "en-IE", + "en-IM", + "en-IN", + "en-IO", + "en-JE", + "en-JM", + "en-KE", + "en-KI", + "en-KN", + "en-KY", + "en-LC", + "en-LR", + "en-LS", + "en-MG", + "en-MH", + "en-MO", + "en-MP", + "en-MS", + "en-MT", + "en-MU", + "en-MW", + "en-MY", + "en-NA", + "en-NF", + "en-NG", + "en-NR", + "en-NU", + "en-NZ", + "en-PG", + "en-PH", + "en-PK", + "en-PN", + "en-PR", + "en-PW", + "en-RW", + "en-SB", + "en-SC", + "en-SD", + "en-SG", + "en-SH", + "en-SL", + "en-SS", + "en-SX", + "en-SZ", + "en-TC", + "en-TK", + "en-TO", + "en-TT", + "en-TV", + "en-TZ", + "en-UG", + "en-UM", + "en-US", + "en-US-POSIX", + "en-VC", + "en-VG", + "en-VI", + "en-VU", + "en-WS", + "en-ZA", + "en-ZM", + "en-ZW", + "eo-001", + "es-419", + "es-AR", + "es-BO", + "es-CL", + "es-CO", + "es-CR", + "es-CU", + "es-DO", + "es-EA", + "es-EC", + "es-ES", + "es-GQ", + "es-GT", + "es-HN", + "es-IC", + "es-MX", + "es-NI", + "es-PA", + "es-PE", + "es-PH", + "es-PR", + "es-PY", + "es-SV", + "es-US", + "es-UY", + "es-VE", + "et-EE", + "eu-ES", + "fa-AF", + "fa-IR", + "ff-CM", + "ff-GN", + "ff-MR", + "ff-SN", + "fi-FI", + "fo-FO", + "fr-BE", + "fr-BF", + "fr-BI", + "fr-BJ", + "fr-BL", + "fr-CA", + "fr-CD", + "fr-CF", + "fr-CG", + "fr-CH", + "fr-CI", + "fr-CM", + "fr-DJ", + "fr-DZ", + "fr-FR", + "fr-GA", + "fr-GF", + "fr-GN", + "fr-GP", + "fr-GQ", + "fr-HT", + "fr-KM", + "fr-LU", + "fr-MA", + "fr-MC", + "fr-MF", + "fr-MG", + "fr-ML", + "fr-MQ", + "fr-MR", + "fr-MU", + "fr-NC", + "fr-NE", + "fr-PF", + "fr-PM", + "fr-RE", + "fr-RW", + "fr-SC", + "fr-SN", + "fr-SY", + "fr-TD", + "fr-TG", + "fr-TN", + "fr-VU", + "fr-WF", + "fr-YT", + "fy-NL", + "ga-IE", + "gd-GB", + "gl-ES", + "gu-IN", + "gv-IM", + "ha-Latn", + "ha-Latn-GH", + "ha-Latn-NE", + "ha-Latn-NG", + "he-IL", + "hi-IN", + "hr-BA", + "hr-HR", + "hu-HU", + "hy-AM", + "id-ID", + "ig-NG", + "ii-CN", + "is-IS", + "it-CH", + "it-IT", + "it-SM", + "ja-JP", + "ka-GE", + "ki-KE", + "kk-Cyrl", + "kk-Cyrl-KZ", + "kl-GL", + "km-KH", + "kn-IN", + "ko-KP", + "ko-KR", + "ks-Arab", + "ks-Arab-IN", + "kw-GB", + "ky-Cyrl", + "ky-Cyrl-KG", + "lb-LU", + "lg-UG", + "ln-AO", + "ln-CD", + "ln-CF", + "ln-CG", + "lo-LA", + "lt-LT", + "lu-CD", + "lv-LV", + "mg-MG", + "mk-MK", + "ml-IN", + "mn-Cyrl", + "mn-Cyrl-MN", + "mr-IN", + "ms-Latn", + "ms-Latn-BN", + "ms-Latn-MY", + "ms-Latn-SG", + "mt-MT", + "my-MM", + "nb-NO", + "nb-SJ", + "nd-ZW", + "ne-IN", + "ne-NP", + "nl-AW", + "nl-BE", + "nl-BQ", + "nl-CW", + "nl-NL", + "nl-SR", + "nl-SX", + "nn-NO", + "om-ET", + "om-KE", + "or-IN", + "os-GE", + "os-RU", + "pa-Arab", + "pa-Arab-PK", + "pa-Guru", + "pa-Guru-IN", + "pl-PL", + "ps-AF", + "pt-AO", + "pt-BR", + "pt-CV", + "pt-GW", + "pt-MO", + "pt-MZ", + "pt-PT", + "pt-ST", + "pt-TL", + "qu-BO", + "qu-EC", + "qu-PE", + "rm-CH", + "rn-BI", + "ro-MD", + "ro-RO", + "ru-BY", + "ru-KG", + "ru-KZ", + "ru-MD", + "ru-RU", + "ru-UA", + "rw-RW", + "se-FI", + "se-NO", + "se-SE", + "sg-CF", + "si-LK", + "sk-SK", + "sl-SI", + "sn-ZW", + "so-DJ", + "so-ET", + "so-KE", + "so-SO", + "sq-AL", + "sq-MK", + "sq-XK", + "sr-Cyrl", + "sr-Cyrl-BA", + "sr-Cyrl-ME", + "sr-Cyrl-RS", + "sr-Cyrl-XK", + "sr-Latn", + "sr-Latn-BA", + "sr-Latn-ME", + "sr-Latn-RS", + "sr-Latn-XK", + "sv-AX", + "sv-FI", + "sv-SE", + "sw-CD", + "sw-KE", + "sw-TZ", + "sw-UG", + "ta-IN", + "ta-LK", + "ta-MY", + "ta-SG", + "te-IN", + "th-TH", + "ti-ER", + "ti-ET", + "to-TO", + "tr-CY", + "tr-TR", + "ug-Arab", + "ug-Arab-CN", + "uk-UA", + "ur-IN", + "ur-PK", + "uz-Arab", + "uz-Arab-AF", + "uz-Cyrl", + "uz-Cyrl-UZ", + "uz-Latn", + "uz-Latn-UZ", + "vi-VN", + "yi-001", + "yo-BJ", + "yo-NG", + "zh-Hans", + "zh-Hans-CN", + "zh-Hans-HK", + "zh-Hans-MO", + "zh-Hans-SG", + "zh-Hant", + "zh-Hant-HK", + "zh-Hant-MO", + "zh-Hant-TW", + "zu-ZA" + ], - return new Promise((resolve, reject) => { - stream[kConsume] = { - type, - stream, - resolve, - reject, - length: 0, - body: [] - } + us_states_and_dc: [ + {name: 'Alabama', abbreviation: 'AL'}, + {name: 'Alaska', abbreviation: 'AK'}, + {name: 'Arizona', abbreviation: 'AZ'}, + {name: 'Arkansas', abbreviation: 'AR'}, + {name: 'California', abbreviation: 'CA'}, + {name: 'Colorado', abbreviation: 'CO'}, + {name: 'Connecticut', abbreviation: 'CT'}, + {name: 'Delaware', abbreviation: 'DE'}, + {name: 'District of Columbia', abbreviation: 'DC'}, + {name: 'Florida', abbreviation: 'FL'}, + {name: 'Georgia', abbreviation: 'GA'}, + {name: 'Hawaii', abbreviation: 'HI'}, + {name: 'Idaho', abbreviation: 'ID'}, + {name: 'Illinois', abbreviation: 'IL'}, + {name: 'Indiana', abbreviation: 'IN'}, + {name: 'Iowa', abbreviation: 'IA'}, + {name: 'Kansas', abbreviation: 'KS'}, + {name: 'Kentucky', abbreviation: 'KY'}, + {name: 'Louisiana', abbreviation: 'LA'}, + {name: 'Maine', abbreviation: 'ME'}, + {name: 'Maryland', abbreviation: 'MD'}, + {name: 'Massachusetts', abbreviation: 'MA'}, + {name: 'Michigan', abbreviation: 'MI'}, + {name: 'Minnesota', abbreviation: 'MN'}, + {name: 'Mississippi', abbreviation: 'MS'}, + {name: 'Missouri', abbreviation: 'MO'}, + {name: 'Montana', abbreviation: 'MT'}, + {name: 'Nebraska', abbreviation: 'NE'}, + {name: 'Nevada', abbreviation: 'NV'}, + {name: 'New Hampshire', abbreviation: 'NH'}, + {name: 'New Jersey', abbreviation: 'NJ'}, + {name: 'New Mexico', abbreviation: 'NM'}, + {name: 'New York', abbreviation: 'NY'}, + {name: 'North Carolina', abbreviation: 'NC'}, + {name: 'North Dakota', abbreviation: 'ND'}, + {name: 'Ohio', abbreviation: 'OH'}, + {name: 'Oklahoma', abbreviation: 'OK'}, + {name: 'Oregon', abbreviation: 'OR'}, + {name: 'Pennsylvania', abbreviation: 'PA'}, + {name: 'Rhode Island', abbreviation: 'RI'}, + {name: 'South Carolina', abbreviation: 'SC'}, + {name: 'South Dakota', abbreviation: 'SD'}, + {name: 'Tennessee', abbreviation: 'TN'}, + {name: 'Texas', abbreviation: 'TX'}, + {name: 'Utah', abbreviation: 'UT'}, + {name: 'Vermont', abbreviation: 'VT'}, + {name: 'Virginia', abbreviation: 'VA'}, + {name: 'Washington', abbreviation: 'WA'}, + {name: 'West Virginia', abbreviation: 'WV'}, + {name: 'Wisconsin', abbreviation: 'WI'}, + {name: 'Wyoming', abbreviation: 'WY'} + ], - stream - .on('error', function (err) { - consumeFinish(this[kConsume], err) - }) - .on('close', function () { - if (this[kConsume].body !== null) { - consumeFinish(this[kConsume], new RequestAbortedError()) - } - }) + territories: [ + {name: 'American Samoa', abbreviation: 'AS'}, + {name: 'Federated States of Micronesia', abbreviation: 'FM'}, + {name: 'Guam', abbreviation: 'GU'}, + {name: 'Marshall Islands', abbreviation: 'MH'}, + {name: 'Northern Mariana Islands', abbreviation: 'MP'}, + {name: 'Puerto Rico', abbreviation: 'PR'}, + {name: 'Virgin Islands, U.S.', abbreviation: 'VI'} + ], - process.nextTick(consumeStart, stream[kConsume]) - }) -} + armed_forces: [ + {name: 'Armed Forces Europe', abbreviation: 'AE'}, + {name: 'Armed Forces Pacific', abbreviation: 'AP'}, + {name: 'Armed Forces the Americas', abbreviation: 'AA'} + ], -function consumeStart (consume) { - if (consume.body === null) { - return - } + country_regions: { + it: [ + { name: "Valle d'Aosta", abbreviation: "VDA" }, + { name: "Piemonte", abbreviation: "PIE" }, + { name: "Lombardia", abbreviation: "LOM" }, + { name: "Veneto", abbreviation: "VEN" }, + { name: "Trentino Alto Adige", abbreviation: "TAA" }, + { name: "Friuli Venezia Giulia", abbreviation: "FVG" }, + { name: "Liguria", abbreviation: "LIG" }, + { name: "Emilia Romagna", abbreviation: "EMR" }, + { name: "Toscana", abbreviation: "TOS" }, + { name: "Umbria", abbreviation: "UMB" }, + { name: "Marche", abbreviation: "MAR" }, + { name: "Abruzzo", abbreviation: "ABR" }, + { name: "Lazio", abbreviation: "LAZ" }, + { name: "Campania", abbreviation: "CAM" }, + { name: "Puglia", abbreviation: "PUG" }, + { name: "Basilicata", abbreviation: "BAS" }, + { name: "Molise", abbreviation: "MOL" }, + { name: "Calabria", abbreviation: "CAL" }, + { name: "Sicilia", abbreviation: "SIC" }, + { name: "Sardegna", abbreviation: "SAR" } + ], + mx: [ + { name: 'Aguascalientes', abbreviation: 'AGU' }, + { name: 'Baja California', abbreviation: 'BCN' }, + { name: 'Baja California Sur', abbreviation: 'BCS' }, + { name: 'Campeche', abbreviation: 'CAM' }, + { name: 'Chiapas', abbreviation: 'CHP' }, + { name: 'Chihuahua', abbreviation: 'CHH' }, + { name: 'Ciudad de MĆ©xico', abbreviation: 'DIF' }, + { name: 'Coahuila', abbreviation: 'COA' }, + { name: 'Colima', abbreviation: 'COL' }, + { name: 'Durango', abbreviation: 'DUR' }, + { name: 'Guanajuato', abbreviation: 'GUA' }, + { name: 'Guerrero', abbreviation: 'GRO' }, + { name: 'Hidalgo', abbreviation: 'HID' }, + { name: 'Jalisco', abbreviation: 'JAL' }, + { name: 'MĆ©xico', abbreviation: 'MEX' }, + { name: 'MichoacĆ”n', abbreviation: 'MIC' }, + { name: 'Morelos', abbreviation: 'MOR' }, + { name: 'Nayarit', abbreviation: 'NAY' }, + { name: 'Nuevo León', abbreviation: 'NLE' }, + { name: 'Oaxaca', abbreviation: 'OAX' }, + { name: 'Puebla', abbreviation: 'PUE' }, + { name: 'QuerĆ©taro', abbreviation: 'QUE' }, + { name: 'Quintana Roo', abbreviation: 'ROO' }, + { name: 'San Luis PotosĆ­', abbreviation: 'SLP' }, + { name: 'Sinaloa', abbreviation: 'SIN' }, + { name: 'Sonora', abbreviation: 'SON' }, + { name: 'Tabasco', abbreviation: 'TAB' }, + { name: 'Tamaulipas', abbreviation: 'TAM' }, + { name: 'Tlaxcala', abbreviation: 'TLA' }, + { name: 'Veracruz', abbreviation: 'VER' }, + { name: 'YucatĆ”n', abbreviation: 'YUC' }, + { name: 'Zacatecas', abbreviation: 'ZAC' } + ] + }, - const { _readableState: state } = consume.stream + street_suffixes: { + 'us': [ + {name: 'Avenue', abbreviation: 'Ave'}, + {name: 'Boulevard', abbreviation: 'Blvd'}, + {name: 'Center', abbreviation: 'Ctr'}, + {name: 'Circle', abbreviation: 'Cir'}, + {name: 'Court', abbreviation: 'Ct'}, + {name: 'Drive', abbreviation: 'Dr'}, + {name: 'Extension', abbreviation: 'Ext'}, + {name: 'Glen', abbreviation: 'Gln'}, + {name: 'Grove', abbreviation: 'Grv'}, + {name: 'Heights', abbreviation: 'Hts'}, + {name: 'Highway', abbreviation: 'Hwy'}, + {name: 'Junction', abbreviation: 'Jct'}, + {name: 'Key', abbreviation: 'Key'}, + {name: 'Lane', abbreviation: 'Ln'}, + {name: 'Loop', abbreviation: 'Loop'}, + {name: 'Manor', abbreviation: 'Mnr'}, + {name: 'Mill', abbreviation: 'Mill'}, + {name: 'Park', abbreviation: 'Park'}, + {name: 'Parkway', abbreviation: 'Pkwy'}, + {name: 'Pass', abbreviation: 'Pass'}, + {name: 'Path', abbreviation: 'Path'}, + {name: 'Pike', abbreviation: 'Pike'}, + {name: 'Place', abbreviation: 'Pl'}, + {name: 'Plaza', abbreviation: 'Plz'}, + {name: 'Point', abbreviation: 'Pt'}, + {name: 'Ridge', abbreviation: 'Rdg'}, + {name: 'River', abbreviation: 'Riv'}, + {name: 'Road', abbreviation: 'Rd'}, + {name: 'Square', abbreviation: 'Sq'}, + {name: 'Street', abbreviation: 'St'}, + {name: 'Terrace', abbreviation: 'Ter'}, + {name: 'Trail', abbreviation: 'Trl'}, + {name: 'Turnpike', abbreviation: 'Tpke'}, + {name: 'View', abbreviation: 'Vw'}, + {name: 'Way', abbreviation: 'Way'} + ], + 'it': [ + { name: 'Accesso', abbreviation: 'Acc.' }, + { name: 'Alzaia', abbreviation: 'Alz.' }, + { name: 'Arco', abbreviation: 'Arco' }, + { name: 'Archivolto', abbreviation: 'Acv.' }, + { name: 'Arena', abbreviation: 'Arena' }, + { name: 'Argine', abbreviation: 'Argine' }, + { name: 'Bacino', abbreviation: 'Bacino' }, + { name: 'Banchi', abbreviation: 'Banchi' }, + { name: 'Banchina', abbreviation: 'Ban.' }, + { name: 'Bastioni', abbreviation: 'Bas.' }, + { name: 'Belvedere', abbreviation: 'Belv.' }, + { name: 'Borgata', abbreviation: 'B.ta' }, + { name: 'Borgo', abbreviation: 'B.go' }, + { name: 'Calata', abbreviation: 'Cal.' }, + { name: 'Calle', abbreviation: 'Calle' }, + { name: 'Campiello', abbreviation: 'Cam.' }, + { name: 'Campo', abbreviation: 'Cam.' }, + { name: 'Canale', abbreviation: 'Can.' }, + { name: 'Carraia', abbreviation: 'Carr.' }, + { name: 'Cascina', abbreviation: 'Cascina' }, + { name: 'Case sparse', abbreviation: 'c.s.' }, + { name: 'Cavalcavia', abbreviation: 'Cv.' }, + { name: 'Circonvallazione', abbreviation: 'Cv.' }, + { name: 'Complanare', abbreviation: 'C.re' }, + { name: 'Contrada', abbreviation: 'C.da' }, + { name: 'Corso', abbreviation: 'C.so' }, + { name: 'Corte', abbreviation: 'C.te' }, + { name: 'Cortile', abbreviation: 'C.le' }, + { name: 'Diramazione', abbreviation: 'Dir.' }, + { name: 'Fondaco', abbreviation: 'F.co' }, + { name: 'Fondamenta', abbreviation: 'F.ta' }, + { name: 'Fondo', abbreviation: 'F.do' }, + { name: 'Frazione', abbreviation: 'Fr.' }, + { name: 'Isola', abbreviation: 'Is.' }, + { name: 'Largo', abbreviation: 'L.go' }, + { name: 'Litoranea', abbreviation: 'Lit.' }, + { name: 'Lungolago', abbreviation: 'L.go lago' }, + { name: 'Lungo Po', abbreviation: 'l.go Po' }, + { name: 'Molo', abbreviation: 'Molo' }, + { name: 'Mura', abbreviation: 'Mura' }, + { name: 'Passaggio privato', abbreviation: 'pass. priv.' }, + { name: 'Passeggiata', abbreviation: 'Pass.' }, + { name: 'Piazza', abbreviation: 'P.zza' }, + { name: 'Piazzale', abbreviation: 'P.le' }, + { name: 'Ponte', abbreviation: 'P.te' }, + { name: 'Portico', abbreviation: 'P.co' }, + { name: 'Rampa', abbreviation: 'Rampa' }, + { name: 'Regione', abbreviation: 'Reg.' }, + { name: 'Rione', abbreviation: 'R.ne' }, + { name: 'Rio', abbreviation: 'Rio' }, + { name: 'Ripa', abbreviation: 'Ripa' }, + { name: 'Riva', abbreviation: 'Riva' }, + { name: 'Rondò', abbreviation: 'Rondò' }, + { name: 'Rotonda', abbreviation: 'Rot.' }, + { name: 'Sagrato', abbreviation: 'Sagr.' }, + { name: 'Salita', abbreviation: 'Sal.' }, + { name: 'Scalinata', abbreviation: 'Scal.' }, + { name: 'Scalone', abbreviation: 'Scal.' }, + { name: 'Slargo', abbreviation: 'Sl.' }, + { name: 'Sottoportico', abbreviation: 'Sott.' }, + { name: 'Strada', abbreviation: 'Str.' }, + { name: 'Stradale', abbreviation: 'Str.le' }, + { name: 'Strettoia', abbreviation: 'Strett.' }, + { name: 'Traversa', abbreviation: 'Trav.' }, + { name: 'Via', abbreviation: 'V.' }, + { name: 'Viale', abbreviation: 'V.le' }, + { name: 'Vicinale', abbreviation: 'Vic.le' }, + { name: 'Vicolo', abbreviation: 'Vic.' } + ], + 'uk' : [ + {name: 'Avenue', abbreviation: 'Ave'}, + {name: 'Close', abbreviation: 'Cl'}, + {name: 'Court', abbreviation: 'Ct'}, + {name: 'Crescent', abbreviation: 'Cr'}, + {name: 'Drive', abbreviation: 'Dr'}, + {name: 'Garden', abbreviation: 'Gdn'}, + {name: 'Gardens', abbreviation: 'Gdns'}, + {name: 'Green', abbreviation: 'Gn'}, + {name: 'Grove', abbreviation: 'Gr'}, + {name: 'Lane', abbreviation: 'Ln'}, + {name: 'Mount', abbreviation: 'Mt'}, + {name: 'Place', abbreviation: 'Pl'}, + {name: 'Park', abbreviation: 'Pk'}, + {name: 'Ridge', abbreviation: 'Rdg'}, + {name: 'Road', abbreviation: 'Rd'}, + {name: 'Square', abbreviation: 'Sq'}, + {name: 'Street', abbreviation: 'St'}, + {name: 'Terrace', abbreviation: 'Ter'}, + {name: 'Valley', abbreviation: 'Val'} + ] + }, - for (const chunk of state.buffer) { - consumePush(consume, chunk) - } + months: [ + {name: 'January', short_name: 'Jan', numeric: '01', days: 31}, + // Not messing with leap years... + {name: 'February', short_name: 'Feb', numeric: '02', days: 28}, + {name: 'March', short_name: 'Mar', numeric: '03', days: 31}, + {name: 'April', short_name: 'Apr', numeric: '04', days: 30}, + {name: 'May', short_name: 'May', numeric: '05', days: 31}, + {name: 'June', short_name: 'Jun', numeric: '06', days: 30}, + {name: 'July', short_name: 'Jul', numeric: '07', days: 31}, + {name: 'August', short_name: 'Aug', numeric: '08', days: 31}, + {name: 'September', short_name: 'Sep', numeric: '09', days: 30}, + {name: 'October', short_name: 'Oct', numeric: '10', days: 31}, + {name: 'November', short_name: 'Nov', numeric: '11', days: 30}, + {name: 'December', short_name: 'Dec', numeric: '12', days: 31} + ], - if (state.endEmitted) { - consumeEnd(this[kConsume]) - } else { - consume.stream.on('end', function () { - consumeEnd(this[kConsume]) - }) - } + // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 + cc_types: [ + {name: "American Express", short_name: 'amex', prefix: '34', length: 15}, + {name: "Bankcard", short_name: 'bankcard', prefix: '5610', length: 16}, + {name: "China UnionPay", short_name: 'chinaunion', prefix: '62', length: 16}, + {name: "Diners Club Carte Blanche", short_name: 'dccarte', prefix: '300', length: 14}, + {name: "Diners Club enRoute", short_name: 'dcenroute', prefix: '2014', length: 15}, + {name: "Diners Club International", short_name: 'dcintl', prefix: '36', length: 14}, + {name: "Diners Club United States & Canada", short_name: 'dcusc', prefix: '54', length: 16}, + {name: "Discover Card", short_name: 'discover', prefix: '6011', length: 16}, + {name: "InstaPayment", short_name: 'instapay', prefix: '637', length: 16}, + {name: "JCB", short_name: 'jcb', prefix: '3528', length: 16}, + {name: "Laser", short_name: 'laser', prefix: '6304', length: 16}, + {name: "Maestro", short_name: 'maestro', prefix: '5018', length: 16}, + {name: "Mastercard", short_name: 'mc', prefix: '51', length: 16}, + {name: "Solo", short_name: 'solo', prefix: '6334', length: 16}, + {name: "Switch", short_name: 'switch', prefix: '4903', length: 16}, + {name: "Visa", short_name: 'visa', prefix: '4', length: 16}, + {name: "Visa Electron", short_name: 'electron', prefix: '4026', length: 16} + ], - consume.stream.resume() + //return all world currency by ISO 4217 + currency_types: [ + {'code' : 'AED', 'name' : 'United Arab Emirates Dirham'}, + {'code' : 'AFN', 'name' : 'Afghanistan Afghani'}, + {'code' : 'ALL', 'name' : 'Albania Lek'}, + {'code' : 'AMD', 'name' : 'Armenia Dram'}, + {'code' : 'ANG', 'name' : 'Netherlands Antilles Guilder'}, + {'code' : 'AOA', 'name' : 'Angola Kwanza'}, + {'code' : 'ARS', 'name' : 'Argentina Peso'}, + {'code' : 'AUD', 'name' : 'Australia Dollar'}, + {'code' : 'AWG', 'name' : 'Aruba Guilder'}, + {'code' : 'AZN', 'name' : 'Azerbaijan New Manat'}, + {'code' : 'BAM', 'name' : 'Bosnia and Herzegovina Convertible Marka'}, + {'code' : 'BBD', 'name' : 'Barbados Dollar'}, + {'code' : 'BDT', 'name' : 'Bangladesh Taka'}, + {'code' : 'BGN', 'name' : 'Bulgaria Lev'}, + {'code' : 'BHD', 'name' : 'Bahrain Dinar'}, + {'code' : 'BIF', 'name' : 'Burundi Franc'}, + {'code' : 'BMD', 'name' : 'Bermuda Dollar'}, + {'code' : 'BND', 'name' : 'Brunei Darussalam Dollar'}, + {'code' : 'BOB', 'name' : 'Bolivia Boliviano'}, + {'code' : 'BRL', 'name' : 'Brazil Real'}, + {'code' : 'BSD', 'name' : 'Bahamas Dollar'}, + {'code' : 'BTN', 'name' : 'Bhutan Ngultrum'}, + {'code' : 'BWP', 'name' : 'Botswana Pula'}, + {'code' : 'BYR', 'name' : 'Belarus Ruble'}, + {'code' : 'BZD', 'name' : 'Belize Dollar'}, + {'code' : 'CAD', 'name' : 'Canada Dollar'}, + {'code' : 'CDF', 'name' : 'Congo/Kinshasa Franc'}, + {'code' : 'CHF', 'name' : 'Switzerland Franc'}, + {'code' : 'CLP', 'name' : 'Chile Peso'}, + {'code' : 'CNY', 'name' : 'China Yuan Renminbi'}, + {'code' : 'COP', 'name' : 'Colombia Peso'}, + {'code' : 'CRC', 'name' : 'Costa Rica Colon'}, + {'code' : 'CUC', 'name' : 'Cuba Convertible Peso'}, + {'code' : 'CUP', 'name' : 'Cuba Peso'}, + {'code' : 'CVE', 'name' : 'Cape Verde Escudo'}, + {'code' : 'CZK', 'name' : 'Czech Republic Koruna'}, + {'code' : 'DJF', 'name' : 'Djibouti Franc'}, + {'code' : 'DKK', 'name' : 'Denmark Krone'}, + {'code' : 'DOP', 'name' : 'Dominican Republic Peso'}, + {'code' : 'DZD', 'name' : 'Algeria Dinar'}, + {'code' : 'EGP', 'name' : 'Egypt Pound'}, + {'code' : 'ERN', 'name' : 'Eritrea Nakfa'}, + {'code' : 'ETB', 'name' : 'Ethiopia Birr'}, + {'code' : 'EUR', 'name' : 'Euro Member Countries'}, + {'code' : 'FJD', 'name' : 'Fiji Dollar'}, + {'code' : 'FKP', 'name' : 'Falkland Islands (Malvinas) Pound'}, + {'code' : 'GBP', 'name' : 'United Kingdom Pound'}, + {'code' : 'GEL', 'name' : 'Georgia Lari'}, + {'code' : 'GGP', 'name' : 'Guernsey Pound'}, + {'code' : 'GHS', 'name' : 'Ghana Cedi'}, + {'code' : 'GIP', 'name' : 'Gibraltar Pound'}, + {'code' : 'GMD', 'name' : 'Gambia Dalasi'}, + {'code' : 'GNF', 'name' : 'Guinea Franc'}, + {'code' : 'GTQ', 'name' : 'Guatemala Quetzal'}, + {'code' : 'GYD', 'name' : 'Guyana Dollar'}, + {'code' : 'HKD', 'name' : 'Hong Kong Dollar'}, + {'code' : 'HNL', 'name' : 'Honduras Lempira'}, + {'code' : 'HRK', 'name' : 'Croatia Kuna'}, + {'code' : 'HTG', 'name' : 'Haiti Gourde'}, + {'code' : 'HUF', 'name' : 'Hungary Forint'}, + {'code' : 'IDR', 'name' : 'Indonesia Rupiah'}, + {'code' : 'ILS', 'name' : 'Israel Shekel'}, + {'code' : 'IMP', 'name' : 'Isle of Man Pound'}, + {'code' : 'INR', 'name' : 'India Rupee'}, + {'code' : 'IQD', 'name' : 'Iraq Dinar'}, + {'code' : 'IRR', 'name' : 'Iran Rial'}, + {'code' : 'ISK', 'name' : 'Iceland Krona'}, + {'code' : 'JEP', 'name' : 'Jersey Pound'}, + {'code' : 'JMD', 'name' : 'Jamaica Dollar'}, + {'code' : 'JOD', 'name' : 'Jordan Dinar'}, + {'code' : 'JPY', 'name' : 'Japan Yen'}, + {'code' : 'KES', 'name' : 'Kenya Shilling'}, + {'code' : 'KGS', 'name' : 'Kyrgyzstan Som'}, + {'code' : 'KHR', 'name' : 'Cambodia Riel'}, + {'code' : 'KMF', 'name' : 'Comoros Franc'}, + {'code' : 'KPW', 'name' : 'Korea (North) Won'}, + {'code' : 'KRW', 'name' : 'Korea (South) Won'}, + {'code' : 'KWD', 'name' : 'Kuwait Dinar'}, + {'code' : 'KYD', 'name' : 'Cayman Islands Dollar'}, + {'code' : 'KZT', 'name' : 'Kazakhstan Tenge'}, + {'code' : 'LAK', 'name' : 'Laos Kip'}, + {'code' : 'LBP', 'name' : 'Lebanon Pound'}, + {'code' : 'LKR', 'name' : 'Sri Lanka Rupee'}, + {'code' : 'LRD', 'name' : 'Liberia Dollar'}, + {'code' : 'LSL', 'name' : 'Lesotho Loti'}, + {'code' : 'LTL', 'name' : 'Lithuania Litas'}, + {'code' : 'LYD', 'name' : 'Libya Dinar'}, + {'code' : 'MAD', 'name' : 'Morocco Dirham'}, + {'code' : 'MDL', 'name' : 'Moldova Leu'}, + {'code' : 'MGA', 'name' : 'Madagascar Ariary'}, + {'code' : 'MKD', 'name' : 'Macedonia Denar'}, + {'code' : 'MMK', 'name' : 'Myanmar (Burma) Kyat'}, + {'code' : 'MNT', 'name' : 'Mongolia Tughrik'}, + {'code' : 'MOP', 'name' : 'Macau Pataca'}, + {'code' : 'MRO', 'name' : 'Mauritania Ouguiya'}, + {'code' : 'MUR', 'name' : 'Mauritius Rupee'}, + {'code' : 'MVR', 'name' : 'Maldives (Maldive Islands) Rufiyaa'}, + {'code' : 'MWK', 'name' : 'Malawi Kwacha'}, + {'code' : 'MXN', 'name' : 'Mexico Peso'}, + {'code' : 'MYR', 'name' : 'Malaysia Ringgit'}, + {'code' : 'MZN', 'name' : 'Mozambique Metical'}, + {'code' : 'NAD', 'name' : 'Namibia Dollar'}, + {'code' : 'NGN', 'name' : 'Nigeria Naira'}, + {'code' : 'NIO', 'name' : 'Nicaragua Cordoba'}, + {'code' : 'NOK', 'name' : 'Norway Krone'}, + {'code' : 'NPR', 'name' : 'Nepal Rupee'}, + {'code' : 'NZD', 'name' : 'New Zealand Dollar'}, + {'code' : 'OMR', 'name' : 'Oman Rial'}, + {'code' : 'PAB', 'name' : 'Panama Balboa'}, + {'code' : 'PEN', 'name' : 'Peru Nuevo Sol'}, + {'code' : 'PGK', 'name' : 'Papua New Guinea Kina'}, + {'code' : 'PHP', 'name' : 'Philippines Peso'}, + {'code' : 'PKR', 'name' : 'Pakistan Rupee'}, + {'code' : 'PLN', 'name' : 'Poland Zloty'}, + {'code' : 'PYG', 'name' : 'Paraguay Guarani'}, + {'code' : 'QAR', 'name' : 'Qatar Riyal'}, + {'code' : 'RON', 'name' : 'Romania New Leu'}, + {'code' : 'RSD', 'name' : 'Serbia Dinar'}, + {'code' : 'RUB', 'name' : 'Russia Ruble'}, + {'code' : 'RWF', 'name' : 'Rwanda Franc'}, + {'code' : 'SAR', 'name' : 'Saudi Arabia Riyal'}, + {'code' : 'SBD', 'name' : 'Solomon Islands Dollar'}, + {'code' : 'SCR', 'name' : 'Seychelles Rupee'}, + {'code' : 'SDG', 'name' : 'Sudan Pound'}, + {'code' : 'SEK', 'name' : 'Sweden Krona'}, + {'code' : 'SGD', 'name' : 'Singapore Dollar'}, + {'code' : 'SHP', 'name' : 'Saint Helena Pound'}, + {'code' : 'SLL', 'name' : 'Sierra Leone Leone'}, + {'code' : 'SOS', 'name' : 'Somalia Shilling'}, + {'code' : 'SPL', 'name' : 'Seborga Luigino'}, + {'code' : 'SRD', 'name' : 'Suriname Dollar'}, + {'code' : 'STD', 'name' : 'SĆ£o TomĆ© and PrĆ­ncipe Dobra'}, + {'code' : 'SVC', 'name' : 'El Salvador Colon'}, + {'code' : 'SYP', 'name' : 'Syria Pound'}, + {'code' : 'SZL', 'name' : 'Swaziland Lilangeni'}, + {'code' : 'THB', 'name' : 'Thailand Baht'}, + {'code' : 'TJS', 'name' : 'Tajikistan Somoni'}, + {'code' : 'TMT', 'name' : 'Turkmenistan Manat'}, + {'code' : 'TND', 'name' : 'Tunisia Dinar'}, + {'code' : 'TOP', 'name' : 'Tonga Pa\'anga'}, + {'code' : 'TRY', 'name' : 'Turkey Lira'}, + {'code' : 'TTD', 'name' : 'Trinidad and Tobago Dollar'}, + {'code' : 'TVD', 'name' : 'Tuvalu Dollar'}, + {'code' : 'TWD', 'name' : 'Taiwan New Dollar'}, + {'code' : 'TZS', 'name' : 'Tanzania Shilling'}, + {'code' : 'UAH', 'name' : 'Ukraine Hryvnia'}, + {'code' : 'UGX', 'name' : 'Uganda Shilling'}, + {'code' : 'USD', 'name' : 'United States Dollar'}, + {'code' : 'UYU', 'name' : 'Uruguay Peso'}, + {'code' : 'UZS', 'name' : 'Uzbekistan Som'}, + {'code' : 'VEF', 'name' : 'Venezuela Bolivar'}, + {'code' : 'VND', 'name' : 'Viet Nam Dong'}, + {'code' : 'VUV', 'name' : 'Vanuatu Vatu'}, + {'code' : 'WST', 'name' : 'Samoa Tala'}, + {'code' : 'XAF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BEAC) CFA Franc BEAC'}, + {'code' : 'XCD', 'name' : 'East Caribbean Dollar'}, + {'code' : 'XDR', 'name' : 'International Monetary Fund (IMF) Special Drawing Rights'}, + {'code' : 'XOF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BCEAO) Franc'}, + {'code' : 'XPF', 'name' : 'Comptoirs FranƧais du Pacifique (CFP) Franc'}, + {'code' : 'YER', 'name' : 'Yemen Rial'}, + {'code' : 'ZAR', 'name' : 'South Africa Rand'}, + {'code' : 'ZMW', 'name' : 'Zambia Kwacha'}, + {'code' : 'ZWD', 'name' : 'Zimbabwe Dollar'} + ], - while (consume.stream.read() != null) { - // Loop - } -} + // return the names of all valide colors + colorNames : [ "AliceBlue", "Black", "Navy", "DarkBlue", "MediumBlue", "Blue", "DarkGreen", "Green", "Teal", "DarkCyan", "DeepSkyBlue", "DarkTurquoise", "MediumSpringGreen", "Lime", "SpringGreen", + "Aqua", "Cyan", "MidnightBlue", "DodgerBlue", "LightSeaGreen", "ForestGreen", "SeaGreen", "DarkSlateGray", "LimeGreen", "MediumSeaGreen", "Turquoise", "RoyalBlue", "SteelBlue", "DarkSlateBlue", "MediumTurquoise", + "Indigo", "DarkOliveGreen", "CadetBlue", "CornflowerBlue", "RebeccaPurple", "MediumAquaMarine", "DimGray", "SlateBlue", "OliveDrab", "SlateGray", "LightSlateGray", "MediumSlateBlue", "LawnGreen", "Chartreuse", + "Aquamarine", "Maroon", "Purple", "Olive", "Gray", "SkyBlue", "LightSkyBlue", "BlueViolet", "DarkRed", "DarkMagenta", "SaddleBrown", "Ivory", "White", + "DarkSeaGreen", "LightGreen", "MediumPurple", "DarkViolet", "PaleGreen", "DarkOrchid", "YellowGreen", "Sienna", "Brown", "DarkGray", "LightBlue", "GreenYellow", "PaleTurquoise", "LightSteelBlue", "PowderBlue", + "FireBrick", "DarkGoldenRod", "MediumOrchid", "RosyBrown", "DarkKhaki", "Silver", "MediumVioletRed", "IndianRed", "Peru", "Chocolate", "Tan", "LightGray", "Thistle", "Orchid", "GoldenRod", "PaleVioletRed", + "Crimson", "Gainsboro", "Plum", "BurlyWood", "LightCyan", "Lavender", "DarkSalmon", "Violet", "PaleGoldenRod", "LightCoral", "Khaki", "AliceBlue", "HoneyDew", "Azure", "SandyBrown", "Wheat", "Beige", "WhiteSmoke", + "MintCream", "GhostWhite", "Salmon", "AntiqueWhite", "Linen", "LightGoldenRodYellow", "OldLace", "Red", "Fuchsia", "Magenta", "DeepPink", "OrangeRed", "Tomato", "HotPink", "Coral", "DarkOrange", "LightSalmon", "Orange", + "LightPink", "Pink", "Gold", "PeachPuff", "NavajoWhite", "Moccasin", "Bisque", "MistyRose", "BlanchedAlmond", "PapayaWhip", "LavenderBlush", "SeaShell", "Cornsilk", "LemonChiffon", "FloralWhite", "Snow", "Yellow", "LightYellow" + ], + + // Data taken from https://www.sec.gov/rules/other/4-460list.htm + company: [ "3Com Corp", + "3M Company", + "A.G. Edwards Inc.", + "Abbott Laboratories", + "Abercrombie & Fitch Co.", + "ABM Industries Incorporated", + "Ace Hardware Corporation", + "ACT Manufacturing Inc.", + "Acterna Corp.", + "Adams Resources & Energy, Inc.", + "ADC Telecommunications, Inc.", + "Adelphia Communications Corporation", + "Administaff, Inc.", + "Adobe Systems Incorporated", + "Adolph Coors Company", + "Advance Auto Parts, Inc.", + "Advanced Micro Devices, Inc.", + "AdvancePCS, Inc.", + "Advantica Restaurant Group, Inc.", + "The AES Corporation", + "Aetna Inc.", + "Affiliated Computer Services, Inc.", + "AFLAC Incorporated", + "AGCO Corporation", + "Agilent Technologies, Inc.", + "Agway Inc.", + "Apartment Investment and Management Company", + "Air Products and Chemicals, Inc.", + "Airborne, Inc.", + "Airgas, Inc.", + "AK Steel Holding Corporation", + "Alaska Air Group, Inc.", + "Alberto-Culver Company", + "Albertson's, Inc.", + "Alcoa Inc.", + "Alleghany Corporation", + "Allegheny Energy, Inc.", + "Allegheny Technologies Incorporated", + "Allergan, Inc.", + "ALLETE, Inc.", + "Alliant Energy Corporation", + "Allied Waste Industries, Inc.", + "Allmerica Financial Corporation", + "The Allstate Corporation", + "ALLTEL Corporation", + "The Alpine Group, Inc.", + "Amazon.com, Inc.", + "AMC Entertainment Inc.", + "American Power Conversion Corporation", + "Amerada Hess Corporation", + "AMERCO", + "Ameren Corporation", + "America West Holdings Corporation", + "American Axle & Manufacturing Holdings, Inc.", + "American Eagle Outfitters, Inc.", + "American Electric Power Company, Inc.", + "American Express Company", + "American Financial Group, Inc.", + "American Greetings Corporation", + "American International Group, Inc.", + "American Standard Companies Inc.", + "American Water Works Company, Inc.", + "AmerisourceBergen Corporation", + "Ames Department Stores, Inc.", + "Amgen Inc.", + "Amkor Technology, Inc.", + "AMR Corporation", + "AmSouth Bancorp.", + "Amtran, Inc.", + "Anadarko Petroleum Corporation", + "Analog Devices, Inc.", + "Anheuser-Busch Companies, Inc.", + "Anixter International Inc.", + "AnnTaylor Inc.", + "Anthem, Inc.", + "AOL Time Warner Inc.", + "Aon Corporation", + "Apache Corporation", + "Apple Computer, Inc.", + "Applera Corporation", + "Applied Industrial Technologies, Inc.", + "Applied Materials, Inc.", + "Aquila, Inc.", + "ARAMARK Corporation", + "Arch Coal, Inc.", + "Archer Daniels Midland Company", + "Arkansas Best Corporation", + "Armstrong Holdings, Inc.", + "Arrow Electronics, Inc.", + "ArvinMeritor, Inc.", + "Ashland Inc.", + "Astoria Financial Corporation", + "AT&T Corp.", + "Atmel Corporation", + "Atmos Energy Corporation", + "Audiovox Corporation", + "Autoliv, Inc.", + "Automatic Data Processing, Inc.", + "AutoNation, Inc.", + "AutoZone, Inc.", + "Avaya Inc.", + "Avery Dennison Corporation", + "Avista Corporation", + "Avnet, Inc.", + "Avon Products, Inc.", + "Baker Hughes Incorporated", + "Ball Corporation", + "Bank of America Corporation", + "The Bank of New York Company, Inc.", + "Bank One Corporation", + "Banknorth Group, Inc.", + "Banta Corporation", + "Barnes & Noble, Inc.", + "Bausch & Lomb Incorporated", + "Baxter International Inc.", + "BB&T Corporation", + "The Bear Stearns Companies Inc.", + "Beazer Homes USA, Inc.", + "Beckman Coulter, Inc.", + "Becton, Dickinson and Company", + "Bed Bath & Beyond Inc.", + "Belk, Inc.", + "Bell Microproducts Inc.", + "BellSouth Corporation", + "Belo Corp.", + "Bemis Company, Inc.", + "Benchmark Electronics, Inc.", + "Berkshire Hathaway Inc.", + "Best Buy Co., Inc.", + "Bethlehem Steel Corporation", + "Beverly Enterprises, Inc.", + "Big Lots, Inc.", + "BJ Services Company", + "BJ's Wholesale Club, Inc.", + "The Black & Decker Corporation", + "Black Hills Corporation", + "BMC Software, Inc.", + "The Boeing Company", + "Boise Cascade Corporation", + "Borders Group, Inc.", + "BorgWarner Inc.", + "Boston Scientific Corporation", + "Bowater Incorporated", + "Briggs & Stratton Corporation", + "Brightpoint, Inc.", + "Brinker International, Inc.", + "Bristol-Myers Squibb Company", + "Broadwing, Inc.", + "Brown Shoe Company, Inc.", + "Brown-Forman Corporation", + "Brunswick Corporation", + "Budget Group, Inc.", + "Burlington Coat Factory Warehouse Corporation", + "Burlington Industries, Inc.", + "Burlington Northern Santa Fe Corporation", + "Burlington Resources Inc.", + "C. H. Robinson Worldwide Inc.", + "Cablevision Systems Corp", + "Cabot Corp", + "Cadence Design Systems, Inc.", + "Calpine Corp.", + "Campbell Soup Co.", + "Capital One Financial Corp.", + "Cardinal Health Inc.", + "Caremark Rx Inc.", + "Carlisle Cos. Inc.", + "Carpenter Technology Corp.", + "Casey's General Stores Inc.", + "Caterpillar Inc.", + "CBRL Group Inc.", + "CDI Corp.", + "CDW Computer Centers Inc.", + "CellStar Corp.", + "Cendant Corp", + "Cenex Harvest States Cooperatives", + "Centex Corp.", + "CenturyTel Inc.", + "Ceridian Corp.", + "CH2M Hill Cos. Ltd.", + "Champion Enterprises Inc.", + "Charles Schwab Corp.", + "Charming Shoppes Inc.", + "Charter Communications Inc.", + "Charter One Financial Inc.", + "ChevronTexaco Corp.", + "Chiquita Brands International Inc.", + "Chubb Corp", + "Ciena Corp.", + "Cigna Corp", + "Cincinnati Financial Corp.", + "Cinergy Corp.", + "Cintas Corp.", + "Circuit City Stores Inc.", + "Cisco Systems Inc.", + "Citigroup, Inc", + "Citizens Communications Co.", + "CKE Restaurants Inc.", + "Clear Channel Communications Inc.", + "The Clorox Co.", + "CMGI Inc.", + "CMS Energy Corp.", + "CNF Inc.", + "Coca-Cola Co.", + "Coca-Cola Enterprises Inc.", + "Colgate-Palmolive Co.", + "Collins & Aikman Corp.", + "Comcast Corp.", + "Comdisco Inc.", + "Comerica Inc.", + "Comfort Systems USA Inc.", + "Commercial Metals Co.", + "Community Health Systems Inc.", + "Compass Bancshares Inc", + "Computer Associates International Inc.", + "Computer Sciences Corp.", + "Compuware Corp.", + "Comverse Technology Inc.", + "ConAgra Foods Inc.", + "Concord EFS Inc.", + "Conectiv, Inc", + "Conoco Inc", + "Conseco Inc.", + "Consolidated Freightways Corp.", + "Consolidated Edison Inc.", + "Constellation Brands Inc.", + "Constellation Emergy Group Inc.", + "Continental Airlines Inc.", + "Convergys Corp.", + "Cooper Cameron Corp.", + "Cooper Industries Ltd.", + "Cooper Tire & Rubber Co.", + "Corn Products International Inc.", + "Corning Inc.", + "Costco Wholesale Corp.", + "Countrywide Credit Industries Inc.", + "Coventry Health Care Inc.", + "Cox Communications Inc.", + "Crane Co.", + "Crompton Corp.", + "Crown Cork & Seal Co. Inc.", + "CSK Auto Corp.", + "CSX Corp.", + "Cummins Inc.", + "CVS Corp.", + "Cytec Industries Inc.", + "D&K Healthcare Resources, Inc.", + "D.R. Horton Inc.", + "Dana Corporation", + "Danaher Corporation", + "Darden Restaurants Inc.", + "DaVita Inc.", + "Dean Foods Company", + "Deere & Company", + "Del Monte Foods Co", + "Dell Computer Corporation", + "Delphi Corp.", + "Delta Air Lines Inc.", + "Deluxe Corporation", + "Devon Energy Corporation", + "Di Giorgio Corporation", + "Dial Corporation", + "Diebold Incorporated", + "Dillard's Inc.", + "DIMON Incorporated", + "Dole Food Company, Inc.", + "Dollar General Corporation", + "Dollar Tree Stores, Inc.", + "Dominion Resources, Inc.", + "Domino's Pizza LLC", + "Dover Corporation, Inc.", + "Dow Chemical Company", + "Dow Jones & Company, Inc.", + "DPL Inc.", + "DQE Inc.", + "Dreyer's Grand Ice Cream, Inc.", + "DST Systems, Inc.", + "DTE Energy Co.", + "E.I. Du Pont de Nemours and Company", + "Duke Energy Corp", + "Dun & Bradstreet Inc.", + "DURA Automotive Systems Inc.", + "DynCorp", + "Dynegy Inc.", + "E*Trade Group, Inc.", + "E.W. Scripps Company", + "Earthlink, Inc.", + "Eastman Chemical Company", + "Eastman Kodak Company", + "Eaton Corporation", + "Echostar Communications Corporation", + "Ecolab Inc.", + "Edison International", + "EGL Inc.", + "El Paso Corporation", + "Electronic Arts Inc.", + "Electronic Data Systems Corp.", + "Eli Lilly and Company", + "EMC Corporation", + "Emcor Group Inc.", + "Emerson Electric Co.", + "Encompass Services Corporation", + "Energizer Holdings Inc.", + "Energy East Corporation", + "Engelhard Corporation", + "Enron Corp.", + "Entergy Corporation", + "Enterprise Products Partners L.P.", + "EOG Resources, Inc.", + "Equifax Inc.", + "Equitable Resources Inc.", + "Equity Office Properties Trust", + "Equity Residential Properties Trust", + "Estee Lauder Companies Inc.", + "Exelon Corporation", + "Exide Technologies", + "Expeditors International of Washington Inc.", + "Express Scripts Inc.", + "ExxonMobil Corporation", + "Fairchild Semiconductor International Inc.", + "Family Dollar Stores Inc.", + "Farmland Industries Inc.", + "Federal Mogul Corp.", + "Federated Department Stores Inc.", + "Federal Express Corp.", + "Felcor Lodging Trust Inc.", + "Ferro Corp.", + "Fidelity National Financial Inc.", + "Fifth Third Bancorp", + "First American Financial Corp.", + "First Data Corp.", + "First National of Nebraska Inc.", + "First Tennessee National Corp.", + "FirstEnergy Corp.", + "Fiserv Inc.", + "Fisher Scientific International Inc.", + "FleetBoston Financial Co.", + "Fleetwood Enterprises Inc.", + "Fleming Companies Inc.", + "Flowers Foods Inc.", + "Flowserv Corp", + "Fluor Corp", + "FMC Corp", + "Foamex International Inc", + "Foot Locker Inc", + "Footstar Inc.", + "Ford Motor Co", + "Forest Laboratories Inc.", + "Fortune Brands Inc.", + "Foster Wheeler Ltd.", + "FPL Group Inc.", + "Franklin Resources Inc.", + "Freeport McMoran Copper & Gold Inc.", + "Frontier Oil Corp", + "Furniture Brands International Inc.", + "Gannett Co., Inc.", + "Gap Inc.", + "Gateway Inc.", + "GATX Corporation", + "Gemstar-TV Guide International Inc.", + "GenCorp Inc.", + "General Cable Corporation", + "General Dynamics Corporation", + "General Electric Company", + "General Mills Inc", + "General Motors Corporation", + "Genesis Health Ventures Inc.", + "Gentek Inc.", + "Gentiva Health Services Inc.", + "Genuine Parts Company", + "Genuity Inc.", + "Genzyme Corporation", + "Georgia Gulf Corporation", + "Georgia-Pacific Corporation", + "Gillette Company", + "Gold Kist Inc.", + "Golden State Bancorp Inc.", + "Golden West Financial Corporation", + "Goldman Sachs Group Inc.", + "Goodrich Corporation", + "The Goodyear Tire & Rubber Company", + "Granite Construction Incorporated", + "Graybar Electric Company Inc.", + "Great Lakes Chemical Corporation", + "Great Plains Energy Inc.", + "GreenPoint Financial Corp.", + "Greif Bros. Corporation", + "Grey Global Group Inc.", + "Group 1 Automotive Inc.", + "Guidant Corporation", + "H&R Block Inc.", + "H.B. Fuller Company", + "H.J. Heinz Company", + "Halliburton Co.", + "Harley-Davidson Inc.", + "Harman International Industries Inc.", + "Harrah's Entertainment Inc.", + "Harris Corp.", + "Harsco Corp.", + "Hartford Financial Services Group Inc.", + "Hasbro Inc.", + "Hawaiian Electric Industries Inc.", + "HCA Inc.", + "Health Management Associates Inc.", + "Health Net Inc.", + "Healthsouth Corp", + "Henry Schein Inc.", + "Hercules Inc.", + "Herman Miller Inc.", + "Hershey Foods Corp.", + "Hewlett-Packard Company", + "Hibernia Corp.", + "Hillenbrand Industries Inc.", + "Hilton Hotels Corp.", + "Hollywood Entertainment Corp.", + "Home Depot Inc.", + "Hon Industries Inc.", + "Honeywell International Inc.", + "Hormel Foods Corp.", + "Host Marriott Corp.", + "Household International Corp.", + "Hovnanian Enterprises Inc.", + "Hub Group Inc.", + "Hubbell Inc.", + "Hughes Supply Inc.", + "Humana Inc.", + "Huntington Bancshares Inc.", + "Idacorp Inc.", + "IDT Corporation", + "IKON Office Solutions Inc.", + "Illinois Tool Works Inc.", + "IMC Global Inc.", + "Imperial Sugar Company", + "IMS Health Inc.", + "Ingles Market Inc", + "Ingram Micro Inc.", + "Insight Enterprises Inc.", + "Integrated Electrical Services Inc.", + "Intel Corporation", + "International Paper Co.", + "Interpublic Group of Companies Inc.", + "Interstate Bakeries Corporation", + "International Business Machines Corp.", + "International Flavors & Fragrances Inc.", + "International Multifoods Corporation", + "Intuit Inc.", + "IT Group Inc.", + "ITT Industries Inc.", + "Ivax Corp.", + "J.B. Hunt Transport Services Inc.", + "J.C. Penny Co.", + "J.P. Morgan Chase & Co.", + "Jabil Circuit Inc.", + "Jack In The Box Inc.", + "Jacobs Engineering Group Inc.", + "JDS Uniphase Corp.", + "Jefferson-Pilot Co.", + "John Hancock Financial Services Inc.", + "Johnson & Johnson", + "Johnson Controls Inc.", + "Jones Apparel Group Inc.", + "KB Home", + "Kellogg Company", + "Kellwood Company", + "Kelly Services Inc.", + "Kemet Corp.", + "Kennametal Inc.", + "Kerr-McGee Corporation", + "KeyCorp", + "KeySpan Corp.", + "Kimball International Inc.", + "Kimberly-Clark Corporation", + "Kindred Healthcare Inc.", + "KLA-Tencor Corporation", + "K-Mart Corp.", + "Knight-Ridder Inc.", + "Kohl's Corp.", + "KPMG Consulting Inc.", + "Kroger Co.", + "L-3 Communications Holdings Inc.", + "Laboratory Corporation of America Holdings", + "Lam Research Corporation", + "LandAmerica Financial Group Inc.", + "Lands' End Inc.", + "Landstar System Inc.", + "La-Z-Boy Inc.", + "Lear Corporation", + "Legg Mason Inc.", + "Leggett & Platt Inc.", + "Lehman Brothers Holdings Inc.", + "Lennar Corporation", + "Lennox International Inc.", + "Level 3 Communications Inc.", + "Levi Strauss & Co.", + "Lexmark International Inc.", + "Limited Inc.", + "Lincoln National Corporation", + "Linens 'n Things Inc.", + "Lithia Motors Inc.", + "Liz Claiborne Inc.", + "Lockheed Martin Corporation", + "Loews Corporation", + "Longs Drug Stores Corporation", + "Louisiana-Pacific Corporation", + "Lowe's Companies Inc.", + "LSI Logic Corporation", + "The LTV Corporation", + "The Lubrizol Corporation", + "Lucent Technologies Inc.", + "Lyondell Chemical Company", + "M & T Bank Corporation", + "Magellan Health Services Inc.", + "Mail-Well Inc.", + "Mandalay Resort Group", + "Manor Care Inc.", + "Manpower Inc.", + "Marathon Oil Corporation", + "Mariner Health Care Inc.", + "Markel Corporation", + "Marriott International Inc.", + "Marsh & McLennan Companies Inc.", + "Marsh Supermarkets Inc.", + "Marshall & Ilsley Corporation", + "Martin Marietta Materials Inc.", + "Masco Corporation", + "Massey Energy Company", + "MasTec Inc.", + "Mattel Inc.", + "Maxim Integrated Products Inc.", + "Maxtor Corporation", + "Maxxam Inc.", + "The May Department Stores Company", + "Maytag Corporation", + "MBNA Corporation", + "McCormick & Company Incorporated", + "McDonald's Corporation", + "The McGraw-Hill Companies Inc.", + "McKesson Corporation", + "McLeodUSA Incorporated", + "M.D.C. Holdings Inc.", + "MDU Resources Group Inc.", + "MeadWestvaco Corporation", + "Medtronic Inc.", + "Mellon Financial Corporation", + "The Men's Wearhouse Inc.", + "Merck & Co., Inc.", + "Mercury General Corporation", + "Merrill Lynch & Co. Inc.", + "Metaldyne Corporation", + "Metals USA Inc.", + "MetLife Inc.", + "Metris Companies Inc", + "MGIC Investment Corporation", + "MGM Mirage", + "Michaels Stores Inc.", + "Micron Technology Inc.", + "Microsoft Corporation", + "Milacron Inc.", + "Millennium Chemicals Inc.", + "Mirant Corporation", + "Mohawk Industries Inc.", + "Molex Incorporated", + "The MONY Group Inc.", + "Morgan Stanley Dean Witter & Co.", + "Motorola Inc.", + "MPS Group Inc.", + "Murphy Oil Corporation", + "Nabors Industries Inc", + "Nacco Industries Inc", + "Nash Finch Company", + "National City Corp.", + "National Commerce Financial Corporation", + "National Fuel Gas Company", + "National Oilwell Inc", + "National Rural Utilities Cooperative Finance Corporation", + "National Semiconductor Corporation", + "National Service Industries Inc", + "Navistar International Corporation", + "NCR Corporation", + "The Neiman Marcus Group Inc.", + "New Jersey Resources Corporation", + "New York Times Company", + "Newell Rubbermaid Inc", + "Newmont Mining Corporation", + "Nextel Communications Inc", + "Nicor Inc", + "Nike Inc", + "NiSource Inc", + "Noble Energy Inc", + "Nordstrom Inc", + "Norfolk Southern Corporation", + "Nortek Inc", + "North Fork Bancorporation Inc", + "Northeast Utilities System", + "Northern Trust Corporation", + "Northrop Grumman Corporation", + "NorthWestern Corporation", + "Novellus Systems Inc", + "NSTAR", + "NTL Incorporated", + "Nucor Corp", + "Nvidia Corp", + "NVR Inc", + "Northwest Airlines Corp", + "Occidental Petroleum Corp", + "Ocean Energy Inc", + "Office Depot Inc.", + "OfficeMax Inc", + "OGE Energy Corp", + "Oglethorpe Power Corp.", + "Ohio Casualty Corp.", + "Old Republic International Corp.", + "Olin Corp.", + "OM Group Inc", + "Omnicare Inc", + "Omnicom Group", + "On Semiconductor Corp", + "ONEOK Inc", + "Oracle Corp", + "Oshkosh Truck Corp", + "Outback Steakhouse Inc.", + "Owens & Minor Inc.", + "Owens Corning", + "Owens-Illinois Inc", + "Oxford Health Plans Inc", + "Paccar Inc", + "PacifiCare Health Systems Inc", + "Packaging Corp. of America", + "Pactiv Corp", + "Pall Corp", + "Pantry Inc", + "Park Place Entertainment Corp", + "Parker Hannifin Corp.", + "Pathmark Stores Inc.", + "Paychex Inc", + "Payless Shoesource Inc", + "Penn Traffic Co.", + "Pennzoil-Quaker State Company", + "Pentair Inc", + "Peoples Energy Corp.", + "PeopleSoft Inc", + "Pep Boys Manny, Moe & Jack", + "Potomac Electric Power Co.", + "Pepsi Bottling Group Inc.", + "PepsiAmericas Inc.", + "PepsiCo Inc.", + "Performance Food Group Co.", + "Perini Corp", + "PerkinElmer Inc", + "Perot Systems Corp", + "Petco Animal Supplies Inc.", + "Peter Kiewit Sons', Inc.", + "PETsMART Inc", + "Pfizer Inc", + "Pacific Gas & Electric Corp.", + "Pharmacia Corp", + "Phar Mor Inc.", + "Phelps Dodge Corp.", + "Philip Morris Companies Inc.", + "Phillips Petroleum Co", + "Phillips Van Heusen Corp.", + "Phoenix Companies Inc", + "Pier 1 Imports Inc.", + "Pilgrim's Pride Corporation", + "Pinnacle West Capital Corp", + "Pioneer-Standard Electronics Inc.", + "Pitney Bowes Inc.", + "Pittston Brinks Group", + "Plains All American Pipeline LP", + "PNC Financial Services Group Inc.", + "PNM Resources Inc", + "Polaris Industries Inc.", + "Polo Ralph Lauren Corp", + "PolyOne Corp", + "Popular Inc", + "Potlatch Corp", + "PPG Industries Inc", + "PPL Corp", + "Praxair Inc", + "Precision Castparts Corp", + "Premcor Inc.", + "Pride International Inc", + "Primedia Inc", + "Principal Financial Group Inc.", + "Procter & Gamble Co.", + "Pro-Fac Cooperative Inc.", + "Progress Energy Inc", + "Progressive Corporation", + "Protective Life Corp", + "Provident Financial Group", + "Providian Financial Corp.", + "Prudential Financial Inc.", + "PSS World Medical Inc", + "Public Service Enterprise Group Inc.", + "Publix Super Markets Inc.", + "Puget Energy Inc.", + "Pulte Homes Inc", + "Qualcomm Inc", + "Quanta Services Inc.", + "Quantum Corp", + "Quest Diagnostics Inc.", + "Questar Corp", + "Quintiles Transnational", + "Qwest Communications Intl Inc", + "R.J. Reynolds Tobacco Company", + "R.R. Donnelley & Sons Company", + "Radio Shack Corporation", + "Raymond James Financial Inc.", + "Raytheon Company", + "Reader's Digest Association Inc.", + "Reebok International Ltd.", + "Regions Financial Corp.", + "Regis Corporation", + "Reliance Steel & Aluminum Co.", + "Reliant Energy Inc.", + "Rent A Center Inc", + "Republic Services Inc", + "Revlon Inc", + "RGS Energy Group Inc", + "Rite Aid Corp", + "Riverwood Holding Inc.", + "RoadwayCorp", + "Robert Half International Inc.", + "Rock-Tenn Co", + "Rockwell Automation Inc", + "Rockwell Collins Inc", + "Rohm & Haas Co.", + "Ross Stores Inc", + "RPM Inc.", + "Ruddick Corp", + "Ryder System Inc", + "Ryerson Tull Inc", + "Ryland Group Inc.", + "Sabre Holdings Corp", + "Safeco Corp", + "Safeguard Scientifics Inc.", + "Safeway Inc", + "Saks Inc", + "Sanmina-SCI Inc", + "Sara Lee Corp", + "SBC Communications Inc", + "Scana Corp.", + "Schering-Plough Corp", + "Scholastic Corp", + "SCI Systems Onc.", + "Science Applications Intl. Inc.", + "Scientific-Atlanta Inc", + "Scotts Company", + "Seaboard Corp", + "Sealed Air Corp", + "Sears Roebuck & Co", + "Sempra Energy", + "Sequa Corp", + "Service Corp. International", + "ServiceMaster Co", + "Shaw Group Inc", + "Sherwin-Williams Company", + "Shopko Stores Inc", + "Siebel Systems Inc", + "Sierra Health Services Inc", + "Sierra Pacific Resources", + "Silgan Holdings Inc.", + "Silicon Graphics Inc", + "Simon Property Group Inc", + "SLM Corporation", + "Smith International Inc", + "Smithfield Foods Inc", + "Smurfit-Stone Container Corp", + "Snap-On Inc", + "Solectron Corp", + "Solutia Inc", + "Sonic Automotive Inc.", + "Sonoco Products Co.", + "Southern Company", + "Southern Union Company", + "SouthTrust Corp.", + "Southwest Airlines Co", + "Southwest Gas Corp", + "Sovereign Bancorp Inc.", + "Spartan Stores Inc", + "Spherion Corp", + "Sports Authority Inc", + "Sprint Corp.", + "SPX Corp", + "St. Jude Medical Inc", + "St. Paul Cos.", + "Staff Leasing Inc.", + "StanCorp Financial Group Inc", + "Standard Pacific Corp.", + "Stanley Works", + "Staples Inc", + "Starbucks Corp", + "Starwood Hotels & Resorts Worldwide Inc", + "State Street Corp.", + "Stater Bros. Holdings Inc.", + "Steelcase Inc", + "Stein Mart Inc", + "Stewart & Stevenson Services Inc", + "Stewart Information Services Corp", + "Stilwell Financial Inc", + "Storage Technology Corporation", + "Stryker Corp", + "Sun Healthcare Group Inc.", + "Sun Microsystems Inc.", + "SunGard Data Systems Inc.", + "Sunoco Inc.", + "SunTrust Banks Inc", + "Supervalu Inc", + "Swift Transportation, Co., Inc", + "Symbol Technologies Inc", + "Synovus Financial Corp.", + "Sysco Corp", + "Systemax Inc.", + "Target Corp.", + "Tech Data Corporation", + "TECO Energy Inc", + "Tecumseh Products Company", + "Tektronix Inc", + "Teleflex Incorporated", + "Telephone & Data Systems Inc", + "Tellabs Inc.", + "Temple-Inland Inc", + "Tenet Healthcare Corporation", + "Tenneco Automotive Inc.", + "Teradyne Inc", + "Terex Corp", + "Tesoro Petroleum Corp.", + "Texas Industries Inc.", + "Texas Instruments Incorporated", + "Textron Inc", + "Thermo Electron Corporation", + "Thomas & Betts Corporation", + "Tiffany & Co", + "Timken Company", + "TJX Companies Inc", + "TMP Worldwide Inc", + "Toll Brothers Inc", + "Torchmark Corporation", + "Toro Company", + "Tower Automotive Inc.", + "Toys 'R' Us Inc", + "Trans World Entertainment Corp.", + "TransMontaigne Inc", + "Transocean Inc", + "TravelCenters of America Inc.", + "Triad Hospitals Inc", + "Tribune Company", + "Trigon Healthcare Inc.", + "Trinity Industries Inc", + "Trump Hotels & Casino Resorts Inc.", + "TruServ Corporation", + "TRW Inc", + "TXU Corp", + "Tyson Foods Inc", + "U.S. Bancorp", + "U.S. Industries Inc.", + "UAL Corporation", + "UGI Corporation", + "Unified Western Grocers Inc", + "Union Pacific Corporation", + "Union Planters Corp", + "Unisource Energy Corp", + "Unisys Corporation", + "United Auto Group Inc", + "United Defense Industries Inc.", + "United Parcel Service Inc", + "United Rentals Inc", + "United Stationers Inc", + "United Technologies Corporation", + "UnitedHealth Group Incorporated", + "Unitrin Inc", + "Universal Corporation", + "Universal Forest Products Inc", + "Universal Health Services Inc", + "Unocal Corporation", + "Unova Inc", + "UnumProvident Corporation", + "URS Corporation", + "US Airways Group Inc", + "US Oncology Inc", + "USA Interactive", + "USFreighways Corporation", + "USG Corporation", + "UST Inc", + "Valero Energy Corporation", + "Valspar Corporation", + "Value City Department Stores Inc", + "Varco International Inc", + "Vectren Corporation", + "Veritas Software Corporation", + "Verizon Communications Inc", + "VF Corporation", + "Viacom Inc", + "Viad Corp", + "Viasystems Group Inc", + "Vishay Intertechnology Inc", + "Visteon Corporation", + "Volt Information Sciences Inc", + "Vulcan Materials Company", + "W.R. Berkley Corporation", + "W.R. Grace & Co", + "W.W. Grainger Inc", + "Wachovia Corporation", + "Wakenhut Corporation", + "Walgreen Co", + "Wallace Computer Services Inc", + "Wal-Mart Stores Inc", + "Walt Disney Co", + "Walter Industries Inc", + "Washington Mutual Inc", + "Washington Post Co.", + "Waste Management Inc", + "Watsco Inc", + "Weatherford International Inc", + "Weis Markets Inc.", + "Wellpoint Health Networks Inc", + "Wells Fargo & Company", + "Wendy's International Inc", + "Werner Enterprises Inc", + "WESCO International Inc", + "Western Digital Inc", + "Western Gas Resources Inc", + "WestPoint Stevens Inc", + "Weyerhauser Company", + "WGL Holdings Inc", + "Whirlpool Corporation", + "Whole Foods Market Inc", + "Willamette Industries Inc.", + "Williams Companies Inc", + "Williams Sonoma Inc", + "Winn Dixie Stores Inc", + "Wisconsin Energy Corporation", + "Wm Wrigley Jr Company", + "World Fuel Services Corporation", + "WorldCom Inc", + "Worthington Industries Inc", + "WPS Resources Corporation", + "Wyeth", + "Wyndham International Inc", + "Xcel Energy Inc", + "Xerox Corp", + "Xilinx Inc", + "XO Communications Inc", + "Yellow Corporation", + "York International Corp", + "Yum Brands Inc.", + "Zale Corporation", + "Zions Bancorporation" + ], -function consumeEnd (consume) { - const { type, body, resolve, stream, length } = consume + fileExtension : { + "raster" : ["bmp", "gif", "gpl", "ico", "jpeg", "psd", "png", "psp", "raw", "tiff"], + "vector" : ["3dv", "amf", "awg", "ai", "cgm", "cdr", "cmx", "dxf", "e2d", "egt", "eps", "fs", "odg", "svg", "xar"], + "3d" : ["3dmf", "3dm", "3mf", "3ds", "an8", "aoi", "blend", "cal3d", "cob", "ctm", "iob", "jas", "max", "mb", "mdx", "obj", "x", "x3d"], + "document" : ["doc", "docx", "dot", "html", "xml", "odt", "odm", "ott", "csv", "rtf", "tex", "xhtml", "xps"] + }, - 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) + // Data taken from https://github.com/dmfilipenko/timezones.json/blob/master/timezones.json + timezones: [ + { + "name": "Dateline Standard Time", + "abbr": "DST", + "offset": -12, + "isdst": false, + "text": "(UTC-12:00) International Date Line West", + "utc": [ + "Etc/GMT+12" + ] + }, + { + "name": "UTC-11", + "abbr": "U", + "offset": -11, + "isdst": false, + "text": "(UTC-11:00) Coordinated Universal Time-11", + "utc": [ + "Etc/GMT+11", + "Pacific/Midway", + "Pacific/Niue", + "Pacific/Pago_Pago" + ] + }, + { + "name": "Hawaiian Standard Time", + "abbr": "HST", + "offset": -10, + "isdst": false, + "text": "(UTC-10:00) Hawaii", + "utc": [ + "Etc/GMT+10", + "Pacific/Honolulu", + "Pacific/Johnston", + "Pacific/Rarotonga", + "Pacific/Tahiti" + ] + }, + { + "name": "Alaskan Standard Time", + "abbr": "AKDT", + "offset": -8, + "isdst": true, + "text": "(UTC-09:00) Alaska", + "utc": [ + "America/Anchorage", + "America/Juneau", + "America/Nome", + "America/Sitka", + "America/Yakutat" + ] + }, + { + "name": "Pacific Standard Time (Mexico)", + "abbr": "PDT", + "offset": -7, + "isdst": true, + "text": "(UTC-08:00) Baja California", + "utc": [ + "America/Santa_Isabel" + ] + }, + { + "name": "Pacific Daylight Time", + "abbr": "PDT", + "offset": -7, + "isdst": true, + "text": "(UTC-07:00) Pacific Time (US & Canada)", + "utc": [ + "America/Dawson", + "America/Los_Angeles", + "America/Tijuana", + "America/Vancouver", + "America/Whitehorse" + ] + }, + { + "name": "Pacific Standard Time", + "abbr": "PST", + "offset": -8, + "isdst": false, + "text": "(UTC-08:00) Pacific Time (US & Canada)", + "utc": [ + "America/Dawson", + "America/Los_Angeles", + "America/Tijuana", + "America/Vancouver", + "America/Whitehorse", + "PST8PDT" + ] + }, + { + "name": "US Mountain Standard Time", + "abbr": "UMST", + "offset": -7, + "isdst": false, + "text": "(UTC-07:00) Arizona", + "utc": [ + "America/Creston", + "America/Dawson_Creek", + "America/Hermosillo", + "America/Phoenix", + "Etc/GMT+7" + ] + }, + { + "name": "Mountain Standard Time (Mexico)", + "abbr": "MDT", + "offset": -6, + "isdst": true, + "text": "(UTC-07:00) Chihuahua, La Paz, Mazatlan", + "utc": [ + "America/Chihuahua", + "America/Mazatlan" + ] + }, + { + "name": "Mountain Standard Time", + "abbr": "MDT", + "offset": -6, + "isdst": true, + "text": "(UTC-07:00) Mountain Time (US & Canada)", + "utc": [ + "America/Boise", + "America/Cambridge_Bay", + "America/Denver", + "America/Edmonton", + "America/Inuvik", + "America/Ojinaga", + "America/Yellowknife", + "MST7MDT" + ] + }, + { + "name": "Central America Standard Time", + "abbr": "CAST", + "offset": -6, + "isdst": false, + "text": "(UTC-06:00) Central America", + "utc": [ + "America/Belize", + "America/Costa_Rica", + "America/El_Salvador", + "America/Guatemala", + "America/Managua", + "America/Tegucigalpa", + "Etc/GMT+6", + "Pacific/Galapagos" + ] + }, + { + "name": "Central Standard Time", + "abbr": "CDT", + "offset": -5, + "isdst": true, + "text": "(UTC-06:00) Central Time (US & Canada)", + "utc": [ + "America/Chicago", + "America/Indiana/Knox", + "America/Indiana/Tell_City", + "America/Matamoros", + "America/Menominee", + "America/North_Dakota/Beulah", + "America/North_Dakota/Center", + "America/North_Dakota/New_Salem", + "America/Rainy_River", + "America/Rankin_Inlet", + "America/Resolute", + "America/Winnipeg", + "CST6CDT" + ] + }, + { + "name": "Central Standard Time (Mexico)", + "abbr": "CDT", + "offset": -5, + "isdst": true, + "text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey", + "utc": [ + "America/Bahia_Banderas", + "America/Cancun", + "America/Merida", + "America/Mexico_City", + "America/Monterrey" + ] + }, + { + "name": "Canada Central Standard Time", + "abbr": "CCST", + "offset": -6, + "isdst": false, + "text": "(UTC-06:00) Saskatchewan", + "utc": [ + "America/Regina", + "America/Swift_Current" + ] + }, + { + "name": "SA Pacific Standard Time", + "abbr": "SPST", + "offset": -5, + "isdst": false, + "text": "(UTC-05:00) Bogota, Lima, Quito", + "utc": [ + "America/Bogota", + "America/Cayman", + "America/Coral_Harbour", + "America/Eirunepe", + "America/Guayaquil", + "America/Jamaica", + "America/Lima", + "America/Panama", + "America/Rio_Branco", + "Etc/GMT+5" + ] + }, + { + "name": "Eastern Standard Time", + "abbr": "EDT", + "offset": -4, + "isdst": true, + "text": "(UTC-05:00) Eastern Time (US & Canada)", + "utc": [ + "America/Detroit", + "America/Havana", + "America/Indiana/Petersburg", + "America/Indiana/Vincennes", + "America/Indiana/Winamac", + "America/Iqaluit", + "America/Kentucky/Monticello", + "America/Louisville", + "America/Montreal", + "America/Nassau", + "America/New_York", + "America/Nipigon", + "America/Pangnirtung", + "America/Port-au-Prince", + "America/Thunder_Bay", + "America/Toronto", + "EST5EDT" + ] + }, + { + "name": "US Eastern Standard Time", + "abbr": "UEDT", + "offset": -4, + "isdst": true, + "text": "(UTC-05:00) Indiana (East)", + "utc": [ + "America/Indiana/Marengo", + "America/Indiana/Vevay", + "America/Indianapolis" + ] + }, + { + "name": "Venezuela Standard Time", + "abbr": "VST", + "offset": -4.5, + "isdst": false, + "text": "(UTC-04:30) Caracas", + "utc": [ + "America/Caracas" + ] + }, + { + "name": "Paraguay Standard Time", + "abbr": "PYT", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Asuncion", + "utc": [ + "America/Asuncion" + ] + }, + { + "name": "Atlantic Standard Time", + "abbr": "ADT", + "offset": -3, + "isdst": true, + "text": "(UTC-04:00) Atlantic Time (Canada)", + "utc": [ + "America/Glace_Bay", + "America/Goose_Bay", + "America/Halifax", + "America/Moncton", + "America/Thule", + "Atlantic/Bermuda" + ] + }, + { + "name": "Central Brazilian Standard Time", + "abbr": "CBST", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Cuiaba", + "utc": [ + "America/Campo_Grande", + "America/Cuiaba" + ] + }, + { + "name": "SA Western Standard Time", + "abbr": "SWST", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Georgetown, La Paz, Manaus, San Juan", + "utc": [ + "America/Anguilla", + "America/Antigua", + "America/Aruba", + "America/Barbados", + "America/Blanc-Sablon", + "America/Boa_Vista", + "America/Curacao", + "America/Dominica", + "America/Grand_Turk", + "America/Grenada", + "America/Guadeloupe", + "America/Guyana", + "America/Kralendijk", + "America/La_Paz", + "America/Lower_Princes", + "America/Manaus", + "America/Marigot", + "America/Martinique", + "America/Montserrat", + "America/Port_of_Spain", + "America/Porto_Velho", + "America/Puerto_Rico", + "America/Santo_Domingo", + "America/St_Barthelemy", + "America/St_Kitts", + "America/St_Lucia", + "America/St_Thomas", + "America/St_Vincent", + "America/Tortola", + "Etc/GMT+4" + ] + }, + { + "name": "Pacific SA Standard Time", + "abbr": "PSST", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Santiago", + "utc": [ + "America/Santiago", + "Antarctica/Palmer" + ] + }, + { + "name": "Newfoundland Standard Time", + "abbr": "NDT", + "offset": -2.5, + "isdst": true, + "text": "(UTC-03:30) Newfoundland", + "utc": [ + "America/St_Johns" + ] + }, + { + "name": "E. South America Standard Time", + "abbr": "ESAST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Brasilia", + "utc": [ + "America/Sao_Paulo" + ] + }, + { + "name": "Argentina Standard Time", + "abbr": "AST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Buenos Aires", + "utc": [ + "America/Argentina/La_Rioja", + "America/Argentina/Rio_Gallegos", + "America/Argentina/Salta", + "America/Argentina/San_Juan", + "America/Argentina/San_Luis", + "America/Argentina/Tucuman", + "America/Argentina/Ushuaia", + "America/Buenos_Aires", + "America/Catamarca", + "America/Cordoba", + "America/Jujuy", + "America/Mendoza" + ] + }, + { + "name": "SA Eastern Standard Time", + "abbr": "SEST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Cayenne, Fortaleza", + "utc": [ + "America/Araguaina", + "America/Belem", + "America/Cayenne", + "America/Fortaleza", + "America/Maceio", + "America/Paramaribo", + "America/Recife", + "America/Santarem", + "Antarctica/Rothera", + "Atlantic/Stanley", + "Etc/GMT+3" + ] + }, + { + "name": "Greenland Standard Time", + "abbr": "GDT", + "offset": -3, + "isdst": true, + "text": "(UTC-03:00) Greenland", + "utc": [ + "America/Godthab" + ] + }, + { + "name": "Montevideo Standard Time", + "abbr": "MST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Montevideo", + "utc": [ + "America/Montevideo" + ] + }, + { + "name": "Bahia Standard Time", + "abbr": "BST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Salvador", + "utc": [ + "America/Bahia" + ] + }, + { + "name": "UTC-02", + "abbr": "U", + "offset": -2, + "isdst": false, + "text": "(UTC-02:00) Coordinated Universal Time-02", + "utc": [ + "America/Noronha", + "Atlantic/South_Georgia", + "Etc/GMT+2" + ] + }, + { + "name": "Mid-Atlantic Standard Time", + "abbr": "MDT", + "offset": -1, + "isdst": true, + "text": "(UTC-02:00) Mid-Atlantic - Old", + "utc": [] + }, + { + "name": "Azores Standard Time", + "abbr": "ADT", + "offset": 0, + "isdst": true, + "text": "(UTC-01:00) Azores", + "utc": [ + "America/Scoresbysund", + "Atlantic/Azores" + ] + }, + { + "name": "Cape Verde Standard Time", + "abbr": "CVST", + "offset": -1, + "isdst": false, + "text": "(UTC-01:00) Cape Verde Is.", + "utc": [ + "Atlantic/Cape_Verde", + "Etc/GMT+1" + ] + }, + { + "name": "Morocco Standard Time", + "abbr": "MDT", + "offset": 1, + "isdst": true, + "text": "(UTC) Casablanca", + "utc": [ + "Africa/Casablanca", + "Africa/El_Aaiun" + ] + }, + { + "name": "UTC", + "abbr": "UTC", + "offset": 0, + "isdst": false, + "text": "(UTC) Coordinated Universal Time", + "utc": [ + "America/Danmarkshavn", + "Etc/GMT" + ] + }, + { + "name": "GMT Standard Time", + "abbr": "GMT", + "offset": 0, + "isdst": false, + "text": "(UTC) Edinburgh, London", + "utc": [ + "Europe/Isle_of_Man", + "Europe/Guernsey", + "Europe/Jersey", + "Europe/London" + ] + }, + { + "name": "British Summer Time", + "abbr": "BST", + "offset": 1, + "isdst": true, + "text": "(UTC+01:00) Edinburgh, London", + "utc": [ + "Europe/Isle_of_Man", + "Europe/Guernsey", + "Europe/Jersey", + "Europe/London" + ] + }, + { + "name": "GMT Standard Time", + "abbr": "GDT", + "offset": 1, + "isdst": true, + "text": "(UTC) Dublin, Lisbon", + "utc": [ + "Atlantic/Canary", + "Atlantic/Faeroe", + "Atlantic/Madeira", + "Europe/Dublin", + "Europe/Lisbon" + ] + }, + { + "name": "Greenwich Standard Time", + "abbr": "GST", + "offset": 0, + "isdst": false, + "text": "(UTC) Monrovia, Reykjavik", + "utc": [ + "Africa/Abidjan", + "Africa/Accra", + "Africa/Bamako", + "Africa/Banjul", + "Africa/Bissau", + "Africa/Conakry", + "Africa/Dakar", + "Africa/Freetown", + "Africa/Lome", + "Africa/Monrovia", + "Africa/Nouakchott", + "Africa/Ouagadougou", + "Africa/Sao_Tome", + "Atlantic/Reykjavik", + "Atlantic/St_Helena" + ] + }, + { + "name": "W. Europe Standard Time", + "abbr": "WEDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", + "utc": [ + "Arctic/Longyearbyen", + "Europe/Amsterdam", + "Europe/Andorra", + "Europe/Berlin", + "Europe/Busingen", + "Europe/Gibraltar", + "Europe/Luxembourg", + "Europe/Malta", + "Europe/Monaco", + "Europe/Oslo", + "Europe/Rome", + "Europe/San_Marino", + "Europe/Stockholm", + "Europe/Vaduz", + "Europe/Vatican", + "Europe/Vienna", + "Europe/Zurich" + ] + }, + { + "name": "Central Europe Standard Time", + "abbr": "CEDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", + "utc": [ + "Europe/Belgrade", + "Europe/Bratislava", + "Europe/Budapest", + "Europe/Ljubljana", + "Europe/Podgorica", + "Europe/Prague", + "Europe/Tirane" + ] + }, + { + "name": "Romance Standard Time", + "abbr": "RDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris", + "utc": [ + "Africa/Ceuta", + "Europe/Brussels", + "Europe/Copenhagen", + "Europe/Madrid", + "Europe/Paris" + ] + }, + { + "name": "Central European Standard Time", + "abbr": "CEDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb", + "utc": [ + "Europe/Sarajevo", + "Europe/Skopje", + "Europe/Warsaw", + "Europe/Zagreb" + ] + }, + { + "name": "W. Central Africa Standard Time", + "abbr": "WCAST", + "offset": 1, + "isdst": false, + "text": "(UTC+01:00) West Central Africa", + "utc": [ + "Africa/Algiers", + "Africa/Bangui", + "Africa/Brazzaville", + "Africa/Douala", + "Africa/Kinshasa", + "Africa/Lagos", + "Africa/Libreville", + "Africa/Luanda", + "Africa/Malabo", + "Africa/Ndjamena", + "Africa/Niamey", + "Africa/Porto-Novo", + "Africa/Tunis", + "Etc/GMT-1" + ] + }, + { + "name": "Namibia Standard Time", + "abbr": "NST", + "offset": 1, + "isdst": false, + "text": "(UTC+01:00) Windhoek", + "utc": [ + "Africa/Windhoek" + ] + }, + { + "name": "GTB Standard Time", + "abbr": "GDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Athens, Bucharest", + "utc": [ + "Asia/Nicosia", + "Europe/Athens", + "Europe/Bucharest", + "Europe/Chisinau" + ] + }, + { + "name": "Middle East Standard Time", + "abbr": "MEDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Beirut", + "utc": [ + "Asia/Beirut" + ] + }, + { + "name": "Egypt Standard Time", + "abbr": "EST", + "offset": 2, + "isdst": false, + "text": "(UTC+02:00) Cairo", + "utc": [ + "Africa/Cairo" + ] + }, + { + "name": "Syria Standard Time", + "abbr": "SDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Damascus", + "utc": [ + "Asia/Damascus" + ] + }, + { + "name": "E. Europe Standard Time", + "abbr": "EEDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) E. Europe", + "utc": [ + "Asia/Nicosia", + "Europe/Athens", + "Europe/Bucharest", + "Europe/Chisinau", + "Europe/Helsinki", + "Europe/Kiev", + "Europe/Mariehamn", + "Europe/Nicosia", + "Europe/Riga", + "Europe/Sofia", + "Europe/Tallinn", + "Europe/Uzhgorod", + "Europe/Vilnius", + "Europe/Zaporozhye" + ] + }, + { + "name": "South Africa Standard Time", + "abbr": "SAST", + "offset": 2, + "isdst": false, + "text": "(UTC+02:00) Harare, Pretoria", + "utc": [ + "Africa/Blantyre", + "Africa/Bujumbura", + "Africa/Gaborone", + "Africa/Harare", + "Africa/Johannesburg", + "Africa/Kigali", + "Africa/Lubumbashi", + "Africa/Lusaka", + "Africa/Maputo", + "Africa/Maseru", + "Africa/Mbabane", + "Etc/GMT-2" + ] + }, + { + "name": "FLE Standard Time", + "abbr": "FDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", + "utc": [ + "Europe/Helsinki", + "Europe/Kiev", + "Europe/Mariehamn", + "Europe/Riga", + "Europe/Sofia", + "Europe/Tallinn", + "Europe/Uzhgorod", + "Europe/Vilnius", + "Europe/Zaporozhye" + ] + }, + { + "name": "Turkey Standard Time", + "abbr": "TDT", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Istanbul", + "utc": [ + "Europe/Istanbul" + ] + }, + { + "name": "Israel Standard Time", + "abbr": "JDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Jerusalem", + "utc": [ + "Asia/Jerusalem" + ] + }, + { + "name": "Libya Standard Time", + "abbr": "LST", + "offset": 2, + "isdst": false, + "text": "(UTC+02:00) Tripoli", + "utc": [ + "Africa/Tripoli" + ] + }, + { + "name": "Jordan Standard Time", + "abbr": "JST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Amman", + "utc": [ + "Asia/Amman" + ] + }, + { + "name": "Arabic Standard Time", + "abbr": "AST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Baghdad", + "utc": [ + "Asia/Baghdad" + ] + }, + { + "name": "Kaliningrad Standard Time", + "abbr": "KST", + "offset": 3, + "isdst": false, + "text": "(UTC+02:00) Kaliningrad", + "utc": [ + "Europe/Kaliningrad" + ] + }, + { + "name": "Arab Standard Time", + "abbr": "AST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Kuwait, Riyadh", + "utc": [ + "Asia/Aden", + "Asia/Bahrain", + "Asia/Kuwait", + "Asia/Qatar", + "Asia/Riyadh" + ] + }, + { + "name": "E. Africa Standard Time", + "abbr": "EAST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Nairobi", + "utc": [ + "Africa/Addis_Ababa", + "Africa/Asmera", + "Africa/Dar_es_Salaam", + "Africa/Djibouti", + "Africa/Juba", + "Africa/Kampala", + "Africa/Khartoum", + "Africa/Mogadishu", + "Africa/Nairobi", + "Antarctica/Syowa", + "Etc/GMT-3", + "Indian/Antananarivo", + "Indian/Comoro", + "Indian/Mayotte" + ] + }, + { + "name": "Moscow Standard Time", + "abbr": "MSK", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Moscow, St. Petersburg, Volgograd, Minsk", + "utc": [ + "Europe/Kirov", + "Europe/Moscow", + "Europe/Simferopol", + "Europe/Volgograd", + "Europe/Minsk" + ] + }, + { + "name": "Samara Time", + "abbr": "SAMT", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Samara, Ulyanovsk, Saratov", + "utc": [ + "Europe/Astrakhan", + "Europe/Samara", + "Europe/Ulyanovsk" + ] + }, + { + "name": "Iran Standard Time", + "abbr": "IDT", + "offset": 4.5, + "isdst": true, + "text": "(UTC+03:30) Tehran", + "utc": [ + "Asia/Tehran" + ] + }, + { + "name": "Arabian Standard Time", + "abbr": "AST", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Abu Dhabi, Muscat", + "utc": [ + "Asia/Dubai", + "Asia/Muscat", + "Etc/GMT-4" + ] + }, + { + "name": "Azerbaijan Standard Time", + "abbr": "ADT", + "offset": 5, + "isdst": true, + "text": "(UTC+04:00) Baku", + "utc": [ + "Asia/Baku" + ] + }, + { + "name": "Mauritius Standard Time", + "abbr": "MST", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Port Louis", + "utc": [ + "Indian/Mahe", + "Indian/Mauritius", + "Indian/Reunion" + ] + }, + { + "name": "Georgian Standard Time", + "abbr": "GET", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Tbilisi", + "utc": [ + "Asia/Tbilisi" + ] + }, + { + "name": "Caucasus Standard Time", + "abbr": "CST", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Yerevan", + "utc": [ + "Asia/Yerevan" + ] + }, + { + "name": "Afghanistan Standard Time", + "abbr": "AST", + "offset": 4.5, + "isdst": false, + "text": "(UTC+04:30) Kabul", + "utc": [ + "Asia/Kabul" + ] + }, + { + "name": "West Asia Standard Time", + "abbr": "WAST", + "offset": 5, + "isdst": false, + "text": "(UTC+05:00) Ashgabat, Tashkent", + "utc": [ + "Antarctica/Mawson", + "Asia/Aqtau", + "Asia/Aqtobe", + "Asia/Ashgabat", + "Asia/Dushanbe", + "Asia/Oral", + "Asia/Samarkand", + "Asia/Tashkent", + "Etc/GMT-5", + "Indian/Kerguelen", + "Indian/Maldives" + ] + }, + { + "name": "Yekaterinburg Time", + "abbr": "YEKT", + "offset": 5, + "isdst": false, + "text": "(UTC+05:00) Yekaterinburg", + "utc": [ + "Asia/Yekaterinburg" + ] + }, + { + "name": "Pakistan Standard Time", + "abbr": "PKT", + "offset": 5, + "isdst": false, + "text": "(UTC+05:00) Islamabad, Karachi", + "utc": [ + "Asia/Karachi" + ] + }, + { + "name": "India Standard Time", + "abbr": "IST", + "offset": 5.5, + "isdst": false, + "text": "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi", + "utc": [ + "Asia/Kolkata" + ] + }, + { + "name": "Sri Lanka Standard Time", + "abbr": "SLST", + "offset": 5.5, + "isdst": false, + "text": "(UTC+05:30) Sri Jayawardenepura", + "utc": [ + "Asia/Colombo" + ] + }, + { + "name": "Nepal Standard Time", + "abbr": "NST", + "offset": 5.75, + "isdst": false, + "text": "(UTC+05:45) Kathmandu", + "utc": [ + "Asia/Kathmandu" + ] + }, + { + "name": "Central Asia Standard Time", + "abbr": "CAST", + "offset": 6, + "isdst": false, + "text": "(UTC+06:00) Nur-Sultan (Astana)", + "utc": [ + "Antarctica/Vostok", + "Asia/Almaty", + "Asia/Bishkek", + "Asia/Qyzylorda", + "Asia/Urumqi", + "Etc/GMT-6", + "Indian/Chagos" + ] + }, + { + "name": "Bangladesh Standard Time", + "abbr": "BST", + "offset": 6, + "isdst": false, + "text": "(UTC+06:00) Dhaka", + "utc": [ + "Asia/Dhaka", + "Asia/Thimphu" + ] + }, + { + "name": "Myanmar Standard Time", + "abbr": "MST", + "offset": 6.5, + "isdst": false, + "text": "(UTC+06:30) Yangon (Rangoon)", + "utc": [ + "Asia/Rangoon", + "Indian/Cocos" + ] + }, + { + "name": "SE Asia Standard Time", + "abbr": "SAST", + "offset": 7, + "isdst": false, + "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta", + "utc": [ + "Antarctica/Davis", + "Asia/Bangkok", + "Asia/Hovd", + "Asia/Jakarta", + "Asia/Phnom_Penh", + "Asia/Pontianak", + "Asia/Saigon", + "Asia/Vientiane", + "Etc/GMT-7", + "Indian/Christmas" + ] + }, + { + "name": "N. Central Asia Standard Time", + "abbr": "NCAST", + "offset": 7, + "isdst": false, + "text": "(UTC+07:00) Novosibirsk", + "utc": [ + "Asia/Novokuznetsk", + "Asia/Novosibirsk", + "Asia/Omsk" + ] + }, + { + "name": "China Standard Time", + "abbr": "CST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi", + "utc": [ + "Asia/Hong_Kong", + "Asia/Macau", + "Asia/Shanghai" + ] + }, + { + "name": "North Asia Standard Time", + "abbr": "NAST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Krasnoyarsk", + "utc": [ + "Asia/Krasnoyarsk" + ] + }, + { + "name": "Singapore Standard Time", + "abbr": "MPST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Kuala Lumpur, Singapore", + "utc": [ + "Asia/Brunei", + "Asia/Kuala_Lumpur", + "Asia/Kuching", + "Asia/Makassar", + "Asia/Manila", + "Asia/Singapore", + "Etc/GMT-8" + ] + }, + { + "name": "W. Australia Standard Time", + "abbr": "WAST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Perth", + "utc": [ + "Antarctica/Casey", + "Australia/Perth" + ] + }, + { + "name": "Taipei Standard Time", + "abbr": "TST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Taipei", + "utc": [ + "Asia/Taipei" + ] + }, + { + "name": "Ulaanbaatar Standard Time", + "abbr": "UST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Ulaanbaatar", + "utc": [ + "Asia/Choibalsan", + "Asia/Ulaanbaatar" + ] + }, + { + "name": "North Asia East Standard Time", + "abbr": "NAEST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Irkutsk", + "utc": [ + "Asia/Irkutsk" + ] + }, + { + "name": "Japan Standard Time", + "abbr": "JST", + "offset": 9, + "isdst": false, + "text": "(UTC+09:00) Osaka, Sapporo, Tokyo", + "utc": [ + "Asia/Dili", + "Asia/Jayapura", + "Asia/Tokyo", + "Etc/GMT-9", + "Pacific/Palau" + ] + }, + { + "name": "Korea Standard Time", + "abbr": "KST", + "offset": 9, + "isdst": false, + "text": "(UTC+09:00) Seoul", + "utc": [ + "Asia/Pyongyang", + "Asia/Seoul" + ] + }, + { + "name": "Cen. Australia Standard Time", + "abbr": "CAST", + "offset": 9.5, + "isdst": false, + "text": "(UTC+09:30) Adelaide", + "utc": [ + "Australia/Adelaide", + "Australia/Broken_Hill" + ] + }, + { + "name": "AUS Central Standard Time", + "abbr": "ACST", + "offset": 9.5, + "isdst": false, + "text": "(UTC+09:30) Darwin", + "utc": [ + "Australia/Darwin" + ] + }, + { + "name": "E. Australia Standard Time", + "abbr": "EAST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Brisbane", + "utc": [ + "Australia/Brisbane", + "Australia/Lindeman" + ] + }, + { + "name": "AUS Eastern Standard Time", + "abbr": "AEST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Canberra, Melbourne, Sydney", + "utc": [ + "Australia/Melbourne", + "Australia/Sydney" + ] + }, + { + "name": "West Pacific Standard Time", + "abbr": "WPST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Guam, Port Moresby", + "utc": [ + "Antarctica/DumontDUrville", + "Etc/GMT-10", + "Pacific/Guam", + "Pacific/Port_Moresby", + "Pacific/Saipan", + "Pacific/Truk" + ] + }, + { + "name": "Tasmania Standard Time", + "abbr": "TST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Hobart", + "utc": [ + "Australia/Currie", + "Australia/Hobart" + ] + }, + { + "name": "Yakutsk Standard Time", + "abbr": "YST", + "offset": 9, + "isdst": false, + "text": "(UTC+09:00) Yakutsk", + "utc": [ + "Asia/Chita", + "Asia/Khandyga", + "Asia/Yakutsk" + ] + }, + { + "name": "Central Pacific Standard Time", + "abbr": "CPST", + "offset": 11, + "isdst": false, + "text": "(UTC+11:00) Solomon Is., New Caledonia", + "utc": [ + "Antarctica/Macquarie", + "Etc/GMT-11", + "Pacific/Efate", + "Pacific/Guadalcanal", + "Pacific/Kosrae", + "Pacific/Noumea", + "Pacific/Ponape" + ] + }, + { + "name": "Vladivostok Standard Time", + "abbr": "VST", + "offset": 11, + "isdst": false, + "text": "(UTC+11:00) Vladivostok", + "utc": [ + "Asia/Sakhalin", + "Asia/Ust-Nera", + "Asia/Vladivostok" + ] + }, + { + "name": "New Zealand Standard Time", + "abbr": "NZST", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Auckland, Wellington", + "utc": [ + "Antarctica/McMurdo", + "Pacific/Auckland" + ] + }, + { + "name": "UTC+12", + "abbr": "U", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Coordinated Universal Time+12", + "utc": [ + "Etc/GMT-12", + "Pacific/Funafuti", + "Pacific/Kwajalein", + "Pacific/Majuro", + "Pacific/Nauru", + "Pacific/Tarawa", + "Pacific/Wake", + "Pacific/Wallis" + ] + }, + { + "name": "Fiji Standard Time", + "abbr": "FST", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Fiji", + "utc": [ + "Pacific/Fiji" + ] + }, + { + "name": "Magadan Standard Time", + "abbr": "MST", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Magadan", + "utc": [ + "Asia/Anadyr", + "Asia/Kamchatka", + "Asia/Magadan", + "Asia/Srednekolymsk" + ] + }, + { + "name": "Kamchatka Standard Time", + "abbr": "KDT", + "offset": 13, + "isdst": true, + "text": "(UTC+12:00) Petropavlovsk-Kamchatsky - Old", + "utc": [ + "Asia/Kamchatka" + ] + }, + { + "name": "Tonga Standard Time", + "abbr": "TST", + "offset": 13, + "isdst": false, + "text": "(UTC+13:00) Nuku'alofa", + "utc": [ + "Etc/GMT-13", + "Pacific/Enderbury", + "Pacific/Fakaofo", + "Pacific/Tongatapu" + ] + }, + { + "name": "Samoa Standard Time", + "abbr": "SST", + "offset": 13, + "isdst": false, + "text": "(UTC+13:00) Samoa", + "utc": [ + "Pacific/Apia" + ] + } + ], + //List source: http://answers.google.com/answers/threadview/id/589312.html + profession: [ + "Airline Pilot", + "Academic Team", + "Accountant", + "Account Executive", + "Actor", + "Actuary", + "Acquisition Analyst", + "Administrative Asst.", + "Administrative Analyst", + "Administrator", + "Advertising Director", + "Aerospace Engineer", + "Agent", + "Agricultural Inspector", + "Agricultural Scientist", + "Air Traffic Controller", + "Animal Trainer", + "Anthropologist", + "Appraiser", + "Architect", + "Art Director", + "Artist", + "Astronomer", + "Athletic Coach", + "Auditor", + "Author", + "Baker", + "Banker", + "Bankruptcy Attorney", + "Benefits Manager", + "Biologist", + "Bio-feedback Specialist", + "Biomedical Engineer", + "Biotechnical Researcher", + "Broadcaster", + "Broker", + "Building Manager", + "Building Contractor", + "Building Inspector", + "Business Analyst", + "Business Planner", + "Business Manager", + "Buyer", + "Call Center Manager", + "Career Counselor", + "Cash Manager", + "Ceramic Engineer", + "Chief Executive Officer", + "Chief Operation Officer", + "Chef", + "Chemical Engineer", + "Chemist", + "Child Care Manager", + "Chief Medical Officer", + "Chiropractor", + "Cinematographer", + "City Housing Manager", + "City Manager", + "Civil Engineer", + "Claims Manager", + "Clinical Research Assistant", + "Collections Manager", + "Compliance Manager", + "Comptroller", + "Computer Manager", + "Commercial Artist", + "Communications Affairs Director", + "Communications Director", + "Communications Engineer", + "Compensation Analyst", + "Computer Programmer", + "Computer Ops. Manager", + "Computer Engineer", + "Computer Operator", + "Computer Graphics Specialist", + "Construction Engineer", + "Construction Manager", + "Consultant", + "Consumer Relations Manager", + "Contract Administrator", + "Copyright Attorney", + "Copywriter", + "Corporate Planner", + "Corrections Officer", + "Cosmetologist", + "Credit Analyst", + "Cruise Director", + "Chief Information Officer", + "Chief Technology Officer", + "Customer Service Manager", + "Cryptologist", + "Dancer", + "Data Security Manager", + "Database Manager", + "Day Care Instructor", + "Dentist", + "Designer", + "Design Engineer", + "Desktop Publisher", + "Developer", + "Development Officer", + "Diamond Merchant", + "Dietitian", + "Direct Marketer", + "Director", + "Distribution Manager", + "Diversity Manager", + "Economist", + "EEO Compliance Manager", + "Editor", + "Education Adminator", + "Electrical Engineer", + "Electro Optical Engineer", + "Electronics Engineer", + "Embassy Management", + "Employment Agent", + "Engineer Technician", + "Entrepreneur", + "Environmental Analyst", + "Environmental Attorney", + "Environmental Engineer", + "Environmental Specialist", + "Escrow Officer", + "Estimator", + "Executive Assistant", + "Executive Director", + "Executive Recruiter", + "Facilities Manager", + "Family Counselor", + "Fashion Events Manager", + "Fashion Merchandiser", + "Fast Food Manager", + "Film Producer", + "Film Production Assistant", + "Financial Analyst", + "Financial Planner", + "Financier", + "Fine Artist", + "Wildlife Specialist", + "Fitness Consultant", + "Flight Attendant", + "Flight Engineer", + "Floral Designer", + "Food & Beverage Director", + "Food Service Manager", + "Forestry Technician", + "Franchise Management", + "Franchise Sales", + "Fraud Investigator", + "Freelance Writer", + "Fund Raiser", + "General Manager", + "Geologist", + "General Counsel", + "Geriatric Specialist", + "Gerontologist", + "Glamour Photographer", + "Golf Club Manager", + "Gourmet Chef", + "Graphic Designer", + "Grounds Keeper", + "Hazardous Waste Manager", + "Health Care Manager", + "Health Therapist", + "Health Service Administrator", + "Hearing Officer", + "Home Economist", + "Horticulturist", + "Hospital Administrator", + "Hotel Manager", + "Human Resources Manager", + "Importer", + "Industrial Designer", + "Industrial Engineer", + "Information Director", + "Inside Sales", + "Insurance Adjuster", + "Interior Decorator", + "Internal Controls Director", + "International Acct.", + "International Courier", + "International Lawyer", + "Interpreter", + "Investigator", + "Investment Banker", + "Investment Manager", + "IT Architect", + "IT Project Manager", + "IT Systems Analyst", + "Jeweler", + "Joint Venture Manager", + "Journalist", + "Labor Negotiator", + "Labor Organizer", + "Labor Relations Manager", + "Lab Services Director", + "Lab Technician", + "Land Developer", + "Landscape Architect", + "Law Enforcement Officer", + "Lawyer", + "Lead Software Engineer", + "Lead Software Test Engineer", + "Leasing Manager", + "Legal Secretary", + "Library Manager", + "Litigation Attorney", + "Loan Officer", + "Lobbyist", + "Logistics Manager", + "Maintenance Manager", + "Management Consultant", + "Managed Care Director", + "Managing Partner", + "Manufacturing Director", + "Manpower Planner", + "Marine Biologist", + "Market Res. Analyst", + "Marketing Director", + "Materials Manager", + "Mathematician", + "Membership Chairman", + "Mechanic", + "Mechanical Engineer", + "Media Buyer", + "Medical Investor", + "Medical Secretary", + "Medical Technician", + "Mental Health Counselor", + "Merchandiser", + "Metallurgical Engineering", + "Meteorologist", + "Microbiologist", + "MIS Manager", + "Motion Picture Director", + "Multimedia Director", + "Musician", + "Network Administrator", + "Network Specialist", + "Network Operator", + "New Product Manager", + "Novelist", + "Nuclear Engineer", + "Nuclear Specialist", + "Nutritionist", + "Nursing Administrator", + "Occupational Therapist", + "Oceanographer", + "Office Manager", + "Operations Manager", + "Operations Research Director", + "Optical Technician", + "Optometrist", + "Organizational Development Manager", + "Outplacement Specialist", + "Paralegal", + "Park Ranger", + "Patent Attorney", + "Payroll Specialist", + "Personnel Specialist", + "Petroleum Engineer", + "Pharmacist", + "Photographer", + "Physical Therapist", + "Physician", + "Physician Assistant", + "Physicist", + "Planning Director", + "Podiatrist", + "Political Analyst", + "Political Scientist", + "Politician", + "Portfolio Manager", + "Preschool Management", + "Preschool Teacher", + "Principal", + "Private Banker", + "Private Investigator", + "Probation Officer", + "Process Engineer", + "Producer", + "Product Manager", + "Product Engineer", + "Production Engineer", + "Production Planner", + "Professional Athlete", + "Professional Coach", + "Professor", + "Project Engineer", + "Project Manager", + "Program Manager", + "Property Manager", + "Public Administrator", + "Public Safety Director", + "PR Specialist", + "Publisher", + "Purchasing Agent", + "Publishing Director", + "Quality Assurance Specialist", + "Quality Control Engineer", + "Quality Control Inspector", + "Radiology Manager", + "Railroad Engineer", + "Real Estate Broker", + "Recreational Director", + "Recruiter", + "Redevelopment Specialist", + "Regulatory Affairs Manager", + "Registered Nurse", + "Rehabilitation Counselor", + "Relocation Manager", + "Reporter", + "Research Specialist", + "Restaurant Manager", + "Retail Store Manager", + "Risk Analyst", + "Safety Engineer", + "Sales Engineer", + "Sales Trainer", + "Sales Promotion Manager", + "Sales Representative", + "Sales Manager", + "Service Manager", + "Sanitation Engineer", + "Scientific Programmer", + "Scientific Writer", + "Securities Analyst", + "Security Consultant", + "Security Director", + "Seminar Presenter", + "Ship's Officer", + "Singer", + "Social Director", + "Social Program Planner", + "Social Research", + "Social Scientist", + "Social Worker", + "Sociologist", + "Software Developer", + "Software Engineer", + "Software Test Engineer", + "Soil Scientist", + "Special Events Manager", + "Special Education Teacher", + "Special Projects Director", + "Speech Pathologist", + "Speech Writer", + "Sports Event Manager", + "Statistician", + "Store Manager", + "Strategic Alliance Director", + "Strategic Planning Director", + "Stress Reduction Specialist", + "Stockbroker", + "Surveyor", + "Structural Engineer", + "Superintendent", + "Supply Chain Director", + "System Engineer", + "Systems Analyst", + "Systems Programmer", + "System Administrator", + "Tax Specialist", + "Teacher", + "Technical Support Specialist", + "Technical Illustrator", + "Technical Writer", + "Technology Director", + "Telecom Analyst", + "Telemarketer", + "Theatrical Director", + "Title Examiner", + "Tour Escort", + "Tour Guide Director", + "Traffic Manager", + "Trainer Translator", + "Transportation Manager", + "Travel Agent", + "Treasurer", + "TV Programmer", + "Underwriter", + "Union Representative", + "University Administrator", + "University Dean", + "Urban Planner", + "Veterinarian", + "Vendor Relations Director", + "Viticulturist", + "Warehouse Manager" + ], + animals : { + //list of ocean animals comes from https://owlcation.com/stem/list-of-ocean-animals + "ocean" : ["Acantharea","Anemone","Angelfish King","Ahi Tuna","Albacore","American Oyster","Anchovy","Armored Snail","Arctic Char","Atlantic Bluefin Tuna","Atlantic Cod","Atlantic Goliath Grouper","Atlantic Trumpetfish","Atlantic Wolffish","Baleen Whale","Banded Butterflyfish","Banded Coral Shrimp","Banded Sea Krait","Barnacle","Barndoor Skate","Barracuda","Basking Shark","Bass","Beluga Whale","Bluebanded Goby","Bluehead Wrasse","Bluefish","Bluestreak Cleaner-Wrasse","Blue Marlin","Blue Shark","Blue Spiny Lobster","Blue Tang","Blue Whale","Broadclub Cuttlefish","Bull Shark","Chambered Nautilus","Chilean Basket Star","Chilean Jack Mackerel","Chinook Salmon","Christmas Tree Worm","Clam","Clown Anemonefish","Clown Triggerfish","Cod","Coelacanth","Cockscomb Cup Coral","Common Fangtooth","Conch","Cookiecutter Shark","Copepod","Coral","Corydoras","Cownose Ray","Crab","Crown-of-Thorns Starfish","Cushion Star","Cuttlefish","California Sea Otters","Dolphin","Dolphinfish","Dory","Devil Fish","Dugong","Dumbo Octopus","Dungeness Crab","Eccentric Sand Dollar","Edible Sea Cucumber","Eel","Elephant Seal","Elkhorn Coral","Emperor Shrimp","Estuarine Crocodile","Fathead Sculpin","Fiddler Crab","Fin Whale","Flameback","Flamingo Tongue Snail","Flashlight Fish","Flatback Turtle","Flatfish","Flying Fish","Flounder","Fluke","French Angelfish","Frilled Shark","Fugu (also called Pufferfish)","Gar","Geoduck","Giant Barrel Sponge","Giant Caribbean Sea Anemone","Giant Clam","Giant Isopod","Giant Kingfish","Giant Oarfish","Giant Pacific Octopus","Giant Pyrosome","Giant Sea Star","Giant Squid","Glowing Sucker Octopus","Giant Tube Worm","Goblin Shark","Goosefish","Great White Shark","Greenland Shark","Grey Atlantic Seal","Grouper","Grunion","Guineafowl Puffer","Haddock","Hake","Halibut","Hammerhead Shark","Hapuka","Harbor Porpoise","Harbor Seal","Hatchetfish","Hawaiian Monk Seal","Hawksbill Turtle","Hector's Dolphin","Hermit Crab","Herring","Hoki","Horn Shark","Horseshoe Crab","Humpback Anglerfish","Humpback Whale","Icefish","Imperator Angelfish","Irukandji Jellyfish","Isopod","Ivory Bush Coral","Japanese Spider Crab","Jellyfish","John Dory","Juan Fernandez Fur Seal","Killer Whale","Kiwa Hirsuta","Krill","Lagoon Triggerfish","Lamprey","Leafy Seadragon","Leopard Seal","Limpet","Ling","Lionfish","Lions Mane Jellyfish","Lobe Coral","Lobster","Loggerhead Turtle","Longnose Sawshark","Longsnout Seahorse","Lophelia Coral","Marrus Orthocanna","Manatee","Manta Ray","Marlin","Megamouth Shark","Mexican Lookdown","Mimic Octopus","Moon Jelly","Mollusk","Monkfish","Moray Eel","Mullet","Mussel","Megaladon","Napoleon Wrasse","Nassau Grouper","Narwhal","Nautilus","Needlefish","Northern Seahorse","North Atlantic Right Whale","Northern Red Snapper","Norway Lobster","Nudibranch","Nurse Shark","Oarfish","Ocean Sunfish","Oceanic Whitetip Shark","Octopus","Olive Sea Snake","Orange Roughy","Ostracod","Otter","Oyster","Pacific Angelshark","Pacific Blackdragon","Pacific Halibut","Pacific Sardine","Pacific Sea Nettle Jellyfish","Pacific White Sided Dolphin","Pantropical Spotted Dolphin","Patagonian Toothfish","Peacock Mantis Shrimp","Pelagic Thresher Shark","Penguin","Peruvian Anchoveta","Pilchard","Pink Salmon","Pinniped","Plankton","Porpoise","Polar Bear","Portuguese Man o' War","Pycnogonid Sea Spider","Quahog","Queen Angelfish","Queen Conch","Queen Parrotfish","Queensland Grouper","Ragfish","Ratfish","Rattail Fish","Ray","Red Drum","Red King Crab","Ringed Seal","Risso's Dolphin","Ross Seals","Sablefish","Salmon","Sand Dollar","Sandbar Shark","Sawfish","Sarcastic Fringehead","Scalloped Hammerhead Shark","Seahorse","Sea Cucumber","Sea Lion","Sea Urchin","Seal","Shark","Shortfin Mako Shark","Shovelnose Guitarfish","Shrimp","Silverside Fish","Skipjack Tuna","Slender Snipe Eel","Smalltooth Sawfish","Smelts","Sockeye Salmon","Southern Stingray","Sponge","Spotted Porcupinefish","Spotted Dolphin","Spotted Eagle Ray","Spotted Moray","Squid","Squidworm","Starfish","Stickleback","Stonefish","Stoplight Loosejaw","Sturgeon","Swordfish","Tan Bristlemouth","Tasseled Wobbegong","Terrible Claw Lobster","Threespot Damselfish","Tiger Prawn","Tiger Shark","Tilefish","Toadfish","Tropical Two-Wing Flyfish","Tuna","Umbrella Squid","Velvet Crab","Venus Flytrap Sea Anemone","Vigtorniella Worm","Viperfish","Vampire Squid","Vaquita","Wahoo","Walrus","West Indian Manatee","Whale","Whale Shark","Whiptail Gulper","White-Beaked Dolphin","White-Ring Garden Eel","White Shrimp","Wobbegong","Wrasse","Wreckfish","Xiphosura","Yellowtail Damselfish","Yelloweye Rockfish","Yellow Cup Black Coral","Yellow Tube Sponge","Yellowfin Tuna","Zebrashark","Zooplankton"], + //list of desert, grassland, and forest animals comes from http://www.skyenimals.com/ + "desert" : ["Aardwolf","Addax","African Wild Ass","Ant","Antelope","Armadillo","Baboon","Badger","Bat","Bearded Dragon","Beetle","Bird","Black-footed Cat","Boa","Brown Bear","Bustard","Butterfly","Camel","Caracal","Caracara","Caterpillar","Centipede","Cheetah","Chipmunk","Chuckwalla","Climbing Mouse","Coati","Cobra","Cotton Rat","Cougar","Courser","Crane Fly","Crow","Dassie Rat","Dove","Dunnart","Eagle","Echidna","Elephant","Emu","Falcon","Fly","Fox","Frogmouth","Gecko","Geoffroy's Cat","Gerbil","Grasshopper","Guanaco","Gundi","Hamster","Hawk","Hedgehog","Hyena","Hyrax","Jackal","Kangaroo","Kangaroo Rat","Kestrel","Kowari","Kultarr","Leopard","Lion","Macaw","Meerkat","Mouse","Oryx","Ostrich","Owl","Pronghorn","Python","Rabbit","Raccoon","Rattlesnake","Rhinoceros","Sand Cat","Spectacled Bear","Spiny Mouse","Starling","Stick Bug","Tarantula","Tit","Toad","Tortoise","Tyrant Flycatcher","Viper","Vulture","Waxwing","Xerus","Zebra"], + "grassland" : ["Aardvark","Aardwolf","Accentor","African Buffalo","African Wild Dog","Alpaca","Anaconda","Ant","Anteater","Antelope","Armadillo","Baboon","Badger","Bandicoot","Barbet","Bat","Bee","Bee-eater","Beetle","Bird","Bison","Black-footed Cat","Black-footed Ferret","Bluebird","Boa","Bowerbird","Brown Bear","Bush Dog","Bushshrike","Bustard","Butterfly","Buzzard","Caracal","Caracara","Cardinal","Caterpillar","Cheetah","Chipmunk","Civet","Climbing Mouse","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Common Genet","Cotton Rat","Cougar","Courser","Coyote","Crane","Crane Fly","Cricket","Crow","Culpeo","Death Adder","Deer","Deer Mouse","Dingo","Dinosaur","Dove","Drongo","Duck","Duiker","Dunnart","Eagle","Echidna","Elephant","Elk","Emu","Falcon","Finch","Flea","Fly","Flying Frog","Fox","Frog","Frogmouth","Garter Snake","Gazelle","Gecko","Geoffroy's Cat","Gerbil","Giant Tortoise","Giraffe","Grasshopper","Grison","Groundhog","Grouse","Guanaco","Guinea Pig","Hamster","Harrier","Hartebeest","Hawk","Hedgehog","Helmetshrike","Hippopotamus","Hornbill","Hyena","Hyrax","Impala","Jackal","Jaguar","Jaguarundi","Kangaroo","Kangaroo Rat","Kestrel","Kultarr","Ladybug","Leopard","Lion","Macaw","Meerkat","Mouse","Newt","Oryx","Ostrich","Owl","Pangolin","Pheasant","Prairie Dog","Pronghorn","Przewalski's Horse","Python","Quoll","Rabbit","Raven","Rhinoceros","Shelduck","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Tamandua","Tasmanian Devil","Thornbill","Thrush","Toad","Tortoise"], + "forest" : ["Agouti","Anaconda","Anoa","Ant","Anteater","Antelope","Armadillo","Asian Black Bear","Aye-aye","Babirusa","Baboon","Badger","Bandicoot","Banteng","Barbet","Basilisk","Bat","Bearded Dragon","Bee","Bee-eater","Beetle","Bettong","Binturong","Bird-of-paradise","Bongo","Bowerbird","Bulbul","Bush Dog","Bushbaby","Bushshrike","Butterfly","Buzzard","Caecilian","Cardinal","Cassowary","Caterpillar","Centipede","Chameleon","Chimpanzee","Cicada","Civet","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Colugo","Cotinga","Cotton Rat","Cougar","Crane Fly","Cricket","Crocodile","Crow","Cuckoo","Cuscus","Death Adder","Deer","Dhole","Dingo","Dinosaur","Drongo","Duck","Duiker","Eagle","Echidna","Elephant","Finch","Flat-headed Cat","Flea","Flowerpecker","Fly","Flying Frog","Fossa","Frog","Frogmouth","Gaur","Gecko","Gorilla","Grison","Hawaiian Honeycreeper","Hawk","Hedgehog","Helmetshrike","Hornbill","Hyrax","Iguana","Jackal","Jaguar","Jaguarundi","Kestrel","Ladybug","Lemur","Leopard","Lion","Macaw","Mandrill","Margay","Monkey","Mouse","Mouse Deer","Newt","Okapi","Old World Flycatcher","Orangutan","Owl","Pangolin","Peafowl","Pheasant","Possum","Python","Quokka","Rabbit","Raccoon","Red Panda","Red River Hog","Rhinoceros","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Sun Bear","Tamandua","Tamarin","Tapir","Tarantula","Thrush","Tiger","Tit","Toad","Tortoise","Toucan","Trogon","Trumpeter","Turaco","Turtle","Tyrant Flycatcher","Viper","Vulture","Wallaby","Warbler","Wasp","Waxwing","Weaver","Weaver-finch","Whistler","White-eye","Whydah","Woodswallow","Worm","Wren","Xenops","Yellowjacket","Accentor","African Buffalo","American Black Bear","Anole","Bird","Bison","Boa","Brown Bear","Chipmunk","Common Genet","Copperhead","Coyote","Deer Mouse","Dormouse","Elk","Emu","Fisher","Fox","Garter Snake","Giant Panda","Giant Tortoise","Groundhog","Grouse","Guanaco","Himalayan Tahr","Kangaroo","Koala","Numbat","Quoll","Raccoon dog","Tasmanian Devil","Thornbill","Turkey","Vole","Weasel","Wildcat","Wolf","Wombat","Woodchuck","Woodpecker"], + //list of farm animals comes from https://www.buzzle.com/articles/farm-animals-list.html + "farm" : ["Alpaca","Buffalo","Banteng","Cow","Cat","Chicken","Carp","Camel","Donkey","Dog","Duck","Emu","Goat","Gayal","Guinea","Goose","Horse","Honey","Llama","Pig","Pigeon","Rhea","Rabbit","Sheep","Silkworm","Turkey","Yak","Zebu"], + //list of pet animals comes from https://www.dogbreedinfo.com/pets/pet.htm + "pet" : ["Bearded Dragon","Birds","Burro","Cats","Chameleons","Chickens","Chinchillas","Chinese Water Dragon","Cows","Dogs","Donkey","Ducks","Ferrets","Fish","Geckos","Geese","Gerbils","Goats","Guinea Fowl","Guinea Pigs","Hamsters","Hedgehogs","Horses","Iguanas","Llamas","Lizards","Mice","Mule","Peafowl","Pigs and Hogs","Pigeons","Ponies","Pot Bellied Pig","Rabbits","Rats","Sheep","Skinks","Snakes","Stick Insects","Sugar Gliders","Tarantula","Turkeys","Turtles"], + //list of zoo animals comes from https://bronxzoo.com/animals + "zoo" : ["Aardvark","African Wild Dog","Aldabra Tortoise","American Alligator","American Bison","Amur Tiger","Anaconda","Andean Condor","Asian Elephant","Baby Doll Sheep","Bald Eagle","Barred Owl","Blue Iguana","Boer Goat","California Sea Lion","Caribbean Flamingo","Chinchilla","Collared Lemur","Coquerel's Sifaka","Cuban Amazon Parrot","Ebony Langur","Fennec Fox","Fossa","Gelada","Giant Anteater","Giraffe","Gorilla","Grizzly Bear","Henkel's Leaf-tailed Gecko","Indian Gharial","Indian Rhinoceros","King Cobra","King Vulture","Komodo Dragon","Linne's Two-toed Sloth","Lion","Little Penguin","Madagascar Tree Boa","Magellanic Penguin","Malayan Tapir","Malayan Tiger","Matschies Tree Kangaroo","Mini Donkey","Monarch Butterfly","Nile crocodile","North American Porcupine","Nubian Ibex","Okapi","Poison Dart Frog","Polar Bear","Pygmy Marmoset","Radiated Tortoise","Red Panda","Red Ruffed Lemur","Ring-tailed Lemur","Ring-tailed Mongoose","Rock Hyrax","Small Clawed Asian Otter","Snow Leopard","Snowy Owl","Southern White-faced Owl","Southern White Rhinocerous","Squirrel Monkey","Tufted Puffin","White Cheeked Gibbon","White-throated Bee Eater","Zebra"] + }, + primes: [ + // 1230 first primes, i.e. all primes up to the first one greater than 10000, inclusive. + 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,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007 + ], + emotions: [ + "love", + "joy", + "surprise", + "anger", + "sadness", + "fear" + ], + music_genres: { + 'general': [ + 'Rock', + 'Pop', + 'Hip-Hop', + 'Jazz', + 'Classical', + 'Electronic', + 'Country', + 'R&B', + 'Reggae', + 'Blues', + 'Metal', + 'Folk', + 'Alternative', + 'Punk', + 'Disco', + 'Funk', + 'Techno', + 'Indie', + 'Gospel', + 'Dance', + 'Children\'s', + 'World' + ], + 'alternative': [ + 'Art Punk', + 'Alternative Rock', + 'Britpunk', + 'College Rock', + 'Crossover Thrash', + 'Crust Punk', + 'Emo / Emocore', + 'Experimental Rock', + 'Folk Punk', + 'Goth / Gothic Rock', + 'Grunge', + 'Hardcore Punk', + 'Hard Rock', + 'Indie Rock', + 'Lo-fi', + 'Musique ConcrĆØte', + 'New Wave', + 'Progressive Rock', + 'Punk', + 'Shoegaze', + 'Steampunk', + ], 'blues': [ + 'Acoustic Blues', + 'African Blues', + 'Blues Rock', + 'Blues Shouter', + 'British Blues', + 'Canadian Blues', + 'Chicago Blues', + 'Classic Blues', + 'Classic Female Blues', + 'Contemporary Blues', + 'Country Blues', + 'Dark Blues', + 'Delta Blues', + 'Detroit Blues', + 'Doom Blues', + 'Electric Blues', + 'Folk Blues', + 'Gospel Blues', + 'Harmonica Blues', + 'Hill Country Blues', + 'Hokum Blues', + 'Jazz Blues', + 'Jump Blues', + 'Kansas City Blues', + 'Louisiana Blues', + 'Memphis Blues', + 'Modern Blues', + 'New Orlean Blues', + 'NY Blues', + 'Piano Blues', + 'Piedmont Blues', + 'Punk Blues', + 'Ragtime Blues', + 'Rhythm Blues', + 'Soul Blues', + 'St.Louis Blues', + 'Soul Blues', + 'Swamp Blues', + 'Texas Blues', + 'Urban Blues', + 'Vandeville', + 'West Coast Blues', + ], 'children\'s': [ + 'Lullabies', + 'Sing - Along', + 'Stories' + ], 'classical': [ + 'Avant-Garde', + 'Ballet', + 'Baroque', + 'Cantata', + 'Chamber Music', + 'String Quartet', + 'Chant', + 'Choral', + 'Classical Crossover', + 'Concerto', + 'Concerto Grosso', + 'Contemporary Classical', + 'Early Music', + 'Expressionist', + 'High Classical', + 'Impressionist', + 'Mass Requiem', + 'Medieval', + 'Minimalism', + 'Modern Composition', + 'Modern Classical', + 'Opera', + 'Oratorio', + 'Orchestral', + 'Organum', + 'Renaissance', + 'Romantic (early period)', + 'Romantic (later period)', + 'Sonata', + 'Symphonic', + 'Symphony', + 'Twelve-tone', + 'Wedding Music' + ], 'country': [ + 'Alternative Country', + 'Americana', + 'Australian Country', + 'Bakersfield Sound', + 'Bluegrass', + 'Blues Country', + 'Cajun Fiddle Tunes', + 'Christian Country', + 'Classic Country', + 'Close Harmony', + 'Contemporary Bluegrass', + 'Contemporary Country', + 'Country Gospel', + 'Country Pop', + 'Country Rap', + 'Country Rock', + 'Country Soul', + 'Cowboy / Western', + 'Cowpunk', + 'Dansband', + 'Honky Tonk', + 'Franco-Country', + 'Gulf and Western', + 'Hellbilly Music', + 'Honky Tonk', + 'Instrumental Country', + 'Lubbock Sound', + 'Nashville Sound', + 'Neotraditional Country', + 'Outlaw Country', + 'Progressive', + 'Psychobilly / Punkabilly', + 'Red Dirt', + 'Sertanejo', + 'Texas County', + 'Traditional Bluegrass', + 'Traditional Country', + 'Truck-Driving Country', + 'Urban Cowboy', + 'Western Swing' + ], 'dance': [ + 'Club / Club Dance', + 'Breakcore', + 'Breakbeat / Breakstep', + 'Chillstep', + 'Deep House', + 'Dubstep', + 'Dancehall', + 'Electro House', + 'Electroswing', + 'Exercise', + 'Future Garage', + 'Garage', + 'Glitch Hop', + 'Glitch Pop', + 'Grime', + 'Hardcore', + 'Hard Dance', + 'Hi-NRG / Eurodance', + 'Horrorcore', + 'House', + 'Jackin House', + 'Jungle / Drum n bass', + 'Liquid Dub', + 'Regstep', + 'Speedcore', + 'Techno', + 'Trance', + 'Trap' + ], electronic: [ + '2-Step', + '8bit', + 'Ambient', + 'Asian Underground', + 'Bassline', + 'Chillwave', + 'Chiptune', + 'Crunk', + 'Downtempo', + 'Drum & Bass', + 'Hard Step', + 'Electro', + 'Electro-swing', + 'Electroacoustic', + 'Electronica', + 'Electronic Rock', + 'Eurodance', + 'Hardstyle', + 'Hi-Nrg', + 'IDM/Experimental', + 'Industrial', + 'Trip Hop', + 'Vaporwave', + 'UK Garage', + 'House', + 'Dubstep', + 'Deep House', + 'EDM', + 'Future Bass', + 'Psychedelic trance' + ], 'jazz' : [ + 'Acid Jazz', + 'Afro-Cuban Jazz', + 'Avant-Garde Jazz', + 'Bebop', + 'Big Band', + 'Blue Note', + 'British Dance Band (Jazz)', + 'Cape Jazz', + 'Chamber Jazz', + 'Contemporary Jazz', + 'Continental Jazz', + 'Cool Jazz', + 'Crossover Jazz', + 'Dark Jazz', + 'Dixieland', + 'Early Jazz', + 'Electro Swing (Jazz)', + 'Ethio-jazz', + 'Ethno-Jazz', + 'European Free Jazz', + 'Free Funk (Avant-Garde / Funk Jazz)', + 'Free Jazz', + 'Fusion', + 'Gypsy Jazz', + 'Hard Bop', + 'Indo Jazz', + 'Jazz Blues', + 'Jazz-Funk (see Free Funk)', + 'Jazz-Fusion', + 'Jazz Rap', + 'Jazz Rock', + 'Kansas City Jazz', + 'Latin Jazz', + 'M-Base Jazz', + 'Mainstream Jazz', + 'Modal Jazz', + 'Neo-Bop', + 'Neo-Swing', + 'Nu Jazz', + 'Orchestral Jazz', + 'Post-Bop', + 'Punk Jazz', + 'Ragtime', + 'Ska Jazz', + 'Skiffle (also Folk)', + 'Smooth Jazz', + 'Soul Jazz', + 'Swing Jazz', + 'Straight-Ahead Jazz', + 'Trad Jazz', + 'Third Stream', + 'Jazz-Funk', + 'Free Jazz', + 'West Coast Jazz' + ], 'metal': [ + 'Heavy Metal', + 'Speed Metal', + 'Thrash Metal', + 'Power Metal', + 'Death Metal', + 'Black Metal', + 'Pagan Metal', + 'Viking Metal', + 'Folk Metal', + 'Symphonic Metal', + 'Gothic Metal', + 'Glam Metal', + 'Hair Metal', + 'Doom Metal', + 'Groove Metal', + 'Industrial Metal', + 'Modern Metal', + 'Neoclassical Metal', + 'New Wave Of British Heavy Metal', + 'Post Metal', + 'Progressive Metal', + 'Avantgarde Metal', + 'Sludge', + 'Djent', + 'Drone', + 'Kawaii Metal', + 'Pirate Metal', + 'Nu Metal', + 'Neue Deutsche HƤrte', + 'Math Metal', + 'Crossover', + 'Grindcore', + 'Hardcore', + 'Metalcore', + 'Deathcore', + 'Post Hardcore', + 'Mathcore' + ], 'folk': [ + 'American Folk Revival', + 'Anti - Folk', + 'British Folk Revival', + 'Contemporary Folk', + 'Filk Music', + 'Freak Folk', + 'Indie Folk', + 'Industrial Folk', + 'Neofolk', + 'Progressive Folk', + 'Psychedelic Folk', + 'Sung Poetry', + 'Techno - Folk', + 'Folk Rock', + 'Old-time Music', + 'Bluegrass', + 'Appalachian', + 'Roots Revival', + 'Celtic', + 'Indie Folk' + ], 'pop': [ + 'Adult Contemporary', + 'Arab Pop', + 'Baroque', + 'Britpop', + 'Bubblegum Pop', + 'Chamber Pop', + 'Chanson', + 'Christian Pop', + 'Classical Crossover', + 'Europop', + 'Austropop', + 'Balkan Pop', + 'French Pop', + 'Korean Pop', + 'Japanese Pop', + 'Chinese Pop', + 'Latin Pop', + 'LaĆÆkó', + 'Nederpop', + 'Russian Pop', + 'Dance Pop', + 'Dream Pop', + 'Electro Pop', + 'Iranian Pop', + 'Jangle Pop', + 'Latin Ballad', + 'Levenslied', + 'Louisiana Swamp Pop', + 'Mexican Pop', + 'Motorpop', + 'New Romanticism', + 'Orchestral Pop', + 'Pop Rap', + 'Popera', + 'Pop / Rock', + 'Pop Punk', + 'Power Pop', + 'Psychedelic Pop', + 'Russian Pop', + 'Schlager', + 'Soft Rock', + 'Sophisti - Pop', + 'Space Age Pop', + 'Sunshine Pop', + 'Surf Pop', + 'Synthpop', + 'Teen Pop', + 'Traditional Pop Music', + 'Turkish Pop', + 'Vispop', + 'Wonky Pop' + ], 'r&b': [ + '(Carolina) Beach Music', + 'Contemporary R & B', + 'Disco', + 'Doo Wop', + 'Funk', + 'Modern Soul', + 'Motown', + 'Neo - Soul', + 'Northern Soul', + 'Psychedelic Soul', + 'Quiet Storm', + 'Soul', + 'Soul Blues', + 'Southern Soul' + ], 'reggae': [ + '2 - Tone', + 'Dub', + 'Roots Reggae', + 'Reggae Fusion', + 'Reggae en EspaƱol', + 'Spanish Reggae', + 'Reggae 110', + 'Reggae Bultrón', + 'Romantic Flow', + 'Lovers Rock', + 'Raggamuffin', + 'Ragga', + 'Dancehall', + 'Ska', + ], 'rock': [ + 'Acid Rock', + 'Adult - Oriented Rock', + 'Afro Punk', + 'Adult Alternative', + 'Alternative Rock', + 'American Traditional Rock', + 'Anatolian Rock', + 'Arena Rock', + 'Art Rock', + 'Blues - Rock', + 'British Invasion', + 'Cock Rock', + 'Death Metal / Black Metal', + 'Doom Metal', + 'Glam Rock', + 'Gothic Metal', + 'Grind Core', + 'Hair Metal', + 'Hard Rock', + 'Math Metal', + 'Math Rock', + 'Metal', + 'Metal Core', + 'Noise Rock', + 'Jam Bands', + 'Post Punk', + 'Post Rock', + 'Prog - Rock / Art Rock', + 'Progressive Metal', + 'Psychedelic', + 'Rock & Roll', + 'Rockabilly', + 'Roots Rock', + 'Singer / Songwriter', + 'Southern Rock', + 'Spazzcore', + 'Stoner Metal', + 'Surf', + 'Technical Death Metal', + 'Tex - Mex', + 'Thrash Metal', + 'Time Lord Rock(Trock)', + 'Trip - hop', + 'Yacht Rock', + 'School House Rock' + ], 'hip-hop': [ + 'Alternative Rap', + 'Avant - Garde', + 'Bounce', + 'Chap Hop', + 'Christian Hip Hop', + 'Conscious Hip Hop', + 'Country - Rap', + 'Grunk', + 'Crunkcore', + 'Cumbia Rap', + 'Dirty South', + 'East Coast', + 'Brick City Club', + 'Hardcore Hip Hop', + 'Mafioso Rap', + 'New Jersey Hip Hop', + 'Freestyle Rap', + 'G - Funk', + 'Gangsta Rap', + 'Golden Age', + 'Grime', + 'Hardcore Rap', + 'Hip - Hop', + 'Hip Pop', + 'Horrorcore', + 'Hyphy', + 'Industrial Hip Hop', + 'Instrumental Hip Hop', + 'Jazz Rap', + 'Latin Rap', + 'Low Bap', + 'Lyrical Hip Hop', + 'Merenrap', + 'Midwest Hip Hop', + 'Chicago Hip Hop', + 'Detroit Hip Hop', + 'Horrorcore', + 'St.Louis Hip Hop', + 'Twin Cities Hip Hop', + 'Motswako', + 'Nerdcore', + 'New Jack Swing', + 'New School Hip Hop', + 'Old School Rap', + 'Rap', + 'Trap', + 'Turntablism', + 'Underground Rap', + 'West Coast Rap', + 'East Coast Rap', + 'Trap', + 'UK Grime', + 'Hyphy', + 'Emo-rap', + 'Cloud rap', + 'G-funk', + 'Boom Bap', + 'Mumble', + 'Drill', + 'UK Drill', + 'Soundcloud Rap', + 'Lo-fi' + ], 'punk': [ + 'Afro-punk', + 'Anarcho punk', + 'Art punk', + 'Christian punk', + 'Crust punk', + 'Deathrock', + 'Egg punk', + 'Garage punk', + 'Glam punk', + 'Hardcore punk', + 'Horror punk', + 'Incelcore/e-punk', + 'Oi!', + 'Peace punk', + 'Punk pathetique', + 'Queercore', + 'Riot Grrrl', + 'Skate punk', + 'Street punk', + 'Taqwacore', + 'Trallpunk' + ], 'disco': [ + 'Nu-disco', + 'Disco-funk', + 'Hi-NRG', + 'Italo Disco', + 'Eurodisco', + 'Boogie', + 'Space Disco', + 'Post-disco', + 'Electro Disco', + 'Disco House', + 'Disco Pop', + 'Soulful House' + ], 'funk': [ + 'Funk Rock', + 'P-Funk (Parliament-Funkadelic)', + 'Psychedelic Funk', + 'Funk Metal', + 'Electro-Funk', + 'Go-go', + 'Boogie-Funk', + 'Jazz-Funk', + 'Soul-Funk', + 'Funky Disco', + 'Nu-Funk', + 'Afrobeat', + 'Latin Funk', + 'G-Funk', + 'Acid Jazz', + 'Funktronica', + 'Folk-Funk', + 'Space Funk', + 'Ambient Funk', + 'Hard Funk', + 'Fusion Funk' + ], 'techno': [ + 'Acid Techno', + 'Ambient Techno', + 'Detroit Techno', + 'Dub Techno', + 'Minimal Techno', + 'Industrial Techno', + 'Hard Techno', + 'Trance', + 'Progressive Techno', + 'Tech House', + 'Electronica', + 'Breakbeat Techno', + 'Electro Techno', + 'Melodic Techno', + 'Experimental Techno', + 'Dark Techno', + 'Ebm', + 'Hypnotic Techno', + 'Psychedelic Techno', + 'Rave Techno', + 'Techno-Pop' + ], 'indie': [ + 'Indie Rock', + 'Indie Pop', + 'Indie Folk', + 'Indie Electronic', + 'Indie Punk', + 'Indie Hip-Hop', + 'Dream Pop', + 'Shoegaze', + 'Lo-fi', + 'Chillwave', + 'Freak Folk', + 'Noise Pop', + 'Math Rock', + 'Post-Punk', + 'Garage Rock', + 'Experimental Indie', + 'Surf Rock', + 'Alternative Country', + 'Indie Soul', + 'Art Rock', + 'Indie R&B', + 'Indietronica', + 'Emo', + 'Post-Rock', + 'Indie Pop-Rock', + 'Indie Synthpop', + 'Noise Rock', + 'Psych Folk', + 'Indie Blues' + ], 'gospel': [ + 'Traditional Gospel', + 'Contemporary Gospel', + 'Southern Gospel', + 'Black Gospel', + 'Urban Contemporary Gospel', + 'Gospel Blues', + 'Bluegrass Gospel', + 'Country Gospel', + 'Praise and Worship', + 'Christian Hip-Hop', + 'Gospel Jazz', + 'Reggae Gospel', + 'African Gospel', + 'Latin Gospel', + 'R&B Gospel', + 'Gospel Choir', + 'Acappella Gospel', + 'Instrumental Gospel', + 'Gospel Rap' + ], 'world': [ + 'African', + 'Arabic', + 'Asian', + 'Caribbean', + 'Celtic', + 'European', + 'Latin American', + 'Middle Eastern', + 'Native American', + 'Polynesian', + 'Reggae', + 'Ska', + 'Salsa', + 'Flamenco', + 'Bossa Nova', + 'Tango', + 'Fado', + 'Klezmer', + 'Balkan', + 'Afrobeat', + 'Mongolian Throat Singing', + 'Indian Classical', + 'Gamelan', + 'Sufi Music', + 'Zydeco', + 'Kora Music', + 'Andean Music', + 'Irish Traditional', + 'Gypsy Jazz', + 'Bollywood', + 'Bhangra', + 'Jawaiian', + 'Hawaiian Slack Key Guitar', + 'Calypso', + 'Cuban Son', + 'Taiko Drumming', + 'African Highlife', + 'Merengue', + 'Tuvan Throat Singing' + ] + }, - let pos = 0 - for (const buf of body) { - dst.set(buf, pos) - pos += buf.byteLength - } + // Data sourced from https://unicode.org/emoji/charts/full-emoji-list.html + emojis: { + "smileys_and_emotion": [ + "0x1f600", + "0x1f603", + "0x1f604", + "0x1f601", + "0x1f606", + "0x1f605", + "0x1f923", + "0x1f602", + "0x1f642", + "0x1f643", + "0x1fae0", + "0x1f609", + "0x1f60a", + "0x1f607", + "0x1f970", + "0x1f60d", + "0x1f929", + "0x1f618", + "0x1f617", + "0x263a", + "0x1f61a", + "0x1f619", + "0x1f972", + "0x1f60b", + "0x1f61b", + "0x1f61c", + "0x1f92a", + "0x1f61d", + "0x1f911", + "0x1f917", + "0x1f92d", + "0x1fae2", + "0x1fae3", + "0x1f92b", + "0x1f914", + "0x1fae1", + "0x1f910", + "0x1f928", + "0x1f610", + "0x1f611", + "0x1f636", + "0x1fae5", + "0x1f636", + "0x200d", + "0x1f32b", + "0xfe0f", + "0x1f60f", + "0x1f612", + "0x1f644", + "0x1f62c", + "0x1f62e", + "0x200d", + "0x1f4a8", + "0x1f925", + "0x1fae8", + "0x1f642", + "0x200d", + "0x2194", + "0xfe0f", + "0x1f642", + "0x200d", + "0x2195", + "0xfe0f", + "0x1f60c", + "0x1f614", + "0x1f62a", + "0x1f924", + "0x1f634", + "0x1f637", + "0x1f912", + "0x1f915", + "0x1f922", + "0x1f92e", + "0x1f927", + "0x1f975", + "0x1f976", + "0x1f974", + "0x1f635", + "0x1f635", + "0x200d", + "0x1f4ab", + "0x1f92f", + "0x1f920", + "0x1f973", + "0x1f978", + "0x1f60e", + "0x1f913", + "0x1f9d0", + "0x1f615", + "0x1fae4", + "0x1f61f", + "0x1f641", + "0x2639", + "0x1f62e", + "0x1f62f", + "0x1f632", + "0x1f633", + "0x1f97a", + "0x1f979", + "0x1f626", + "0x1f627", + "0x1f628", + "0x1f630", + "0x1f625", + "0x1f622", + "0x1f62d", + "0x1f631", + "0x1f616", + "0x1f623", + "0x1f61e", + "0x1f613", + "0x1f629", + "0x1f62b", + "0x1f971", + "0x1f624", + "0x1f621", + "0x1f620", + "0x1f92c", + "0x1f608", + "0x1f47f", + "0x1f480", + "0x2620", + "0x1f4a9", + "0x1f921", + "0x1f479", + "0x1f47a", + "0x1f47b", + "0x1f47d", + "0x1f47e", + "0x1f916", + "0x1f63a", + "0x1f638", + "0x1f639", + "0x1f63b", + "0x1f63c", + "0x1f63d", + "0x1f640", + "0x1f63f", + "0x1f63e", + "0x1f648", + "0x1f649", + "0x1f64a", + "0x1f48c", + "0x1f498", + "0x1f49d", + "0x1f496", + "0x1f497", + "0x1f493", + "0x1f49e", + "0x1f495", + "0x1f49f", + "0x2763", + "0x1f494", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f525", + "0x2764", + "0xfe0f", + "0x200d", + "0x1fa79", + "0x2764", + "0x1fa77", + "0x1f9e1", + "0x1f49b", + "0x1f49a", + "0x1f499", + "0x1fa75", + "0x1f49c", + "0x1f90e", + "0x1f5a4", + "0x1fa76", + "0x1f90d", + "0x1f48b", + "0x1f4af", + "0x1f4a2", + "0x1f4a5", + "0x1f4ab", + "0x1f4a6", + "0x1f4a8", + "0x1f573", + "0x1f4ac", + "0x1f441", + "0xfe0f", + "0x200d", + "0x1f5e8", + "0xfe0f", + "0x1f5e8", + "0x1f5ef", + "0x1f4ad", + "0x1f4a4" + ], + "people_and_body": [ + "0x1f44b", + "0x1f91a", + "0x1f590", + "0x270b", + "0x1f596", + "0x1faf1", + "0x1faf2", + "0x1faf3", + "0x1faf4", + "0x1faf7", + "0x1faf8", + "0x1f44c", + "0x1f90c", + "0x1f90f", + "0x270c", + "0x1f91e", + "0x1faf0", + "0x1f91f", + "0x1f918", + "0x1f919", + "0x1f448", + "0x1f449", + "0x1f446", + "0x1f595", + "0x1f447", + "0x261d", + "0x1faf5", + "0x1f44d", + "0x1f44e", + "0x270a", + "0x1f44a", + "0x1f91b", + "0x1f91c", + "0x1f44f", + "0x1f64c", + "0x1faf6", + "0x1f450", + "0x1f932", + "0x1f91d", + "0x1f64f", + "0x270d", + "0x1f485", + "0x1f933", + "0x1f4aa", + "0x1f9be", + "0x1f9bf", + "0x1f9b5", + "0x1f9b6", + "0x1f442", + "0x1f9bb", + "0x1f443", + "0x1f9e0", + "0x1fac0", + "0x1fac1", + "0x1f9b7", + "0x1f9b4", + "0x1f440", + "0x1f441", + "0x1f445", + "0x1f444", + "0x1fae6", + "0x1f476", + "0x1f9d2", + "0x1f466", + "0x1f467", + "0x1f9d1", + "0x1f471", + "0x1f468", + "0x1f9d4", + "0x1f9d4", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d4", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9b0", + "0x1f468", + "0x200d", + "0x1f9b1", + "0x1f468", + "0x200d", + "0x1f9b3", + "0x1f468", + "0x200d", + "0x1f9b2", + "0x1f469", + "0x1f469", + "0x200d", + "0x1f9b0", + "0x1f9d1", + "0x200d", + "0x1f9b0", + "0x1f469", + "0x200d", + "0x1f9b1", + "0x1f9d1", + "0x200d", + "0x1f9b1", + "0x1f469", + "0x200d", + "0x1f9b3", + "0x1f9d1", + "0x200d", + "0x1f9b3", + "0x1f469", + "0x200d", + "0x1f9b2", + "0x1f9d1", + "0x200d", + "0x1f9b2", + "0x1f471", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f471", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d3", + "0x1f474", + "0x1f475", + "0x1f64d", + "0x1f64d", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f64d", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f64e", + "0x1f64e", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f64e", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f645", + "0x1f645", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f645", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f646", + "0x1f646", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f646", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f481", + "0x1f481", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f481", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f64b", + "0x1f64b", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f64b", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9cf", + "0x1f9cf", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9cf", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f647", + "0x1f647", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f647", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f926", + "0x1f926", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f926", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f937", + "0x1f937", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f937", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x2695", + "0xfe0f", + "0x1f468", + "0x200d", + "0x2695", + "0xfe0f", + "0x1f469", + "0x200d", + "0x2695", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f393", + "0x1f468", + "0x200d", + "0x1f393", + "0x1f469", + "0x200d", + "0x1f393", + "0x1f9d1", + "0x200d", + "0x1f3eb", + "0x1f468", + "0x200d", + "0x1f3eb", + "0x1f469", + "0x200d", + "0x1f3eb", + "0x1f9d1", + "0x200d", + "0x2696", + "0xfe0f", + "0x1f468", + "0x200d", + "0x2696", + "0xfe0f", + "0x1f469", + "0x200d", + "0x2696", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f33e", + "0x1f468", + "0x200d", + "0x1f33e", + "0x1f469", + "0x200d", + "0x1f33e", + "0x1f9d1", + "0x200d", + "0x1f373", + "0x1f468", + "0x200d", + "0x1f373", + "0x1f469", + "0x200d", + "0x1f373", + "0x1f9d1", + "0x200d", + "0x1f527", + "0x1f468", + "0x200d", + "0x1f527", + "0x1f469", + "0x200d", + "0x1f527", + "0x1f9d1", + "0x200d", + "0x1f3ed", + "0x1f468", + "0x200d", + "0x1f3ed", + "0x1f469", + "0x200d", + "0x1f3ed", + "0x1f9d1", + "0x200d", + "0x1f4bc", + "0x1f468", + "0x200d", + "0x1f4bc", + "0x1f469", + "0x200d", + "0x1f4bc", + "0x1f9d1", + "0x200d", + "0x1f52c", + "0x1f468", + "0x200d", + "0x1f52c", + "0x1f469", + "0x200d", + "0x1f52c", + "0x1f9d1", + "0x200d", + "0x1f4bb", + "0x1f468", + "0x200d", + "0x1f4bb", + "0x1f469", + "0x200d", + "0x1f4bb", + "0x1f9d1", + "0x200d", + "0x1f3a4", + "0x1f468", + "0x200d", + "0x1f3a4", + "0x1f469", + "0x200d", + "0x1f3a4", + "0x1f9d1", + "0x200d", + "0x1f3a8", + "0x1f468", + "0x200d", + "0x1f3a8", + "0x1f469", + "0x200d", + "0x1f3a8", + "0x1f9d1", + "0x200d", + "0x2708", + "0xfe0f", + "0x1f468", + "0x200d", + "0x2708", + "0xfe0f", + "0x1f469", + "0x200d", + "0x2708", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f680", + "0x1f468", + "0x200d", + "0x1f680", + "0x1f469", + "0x200d", + "0x1f680", + "0x1f9d1", + "0x200d", + "0x1f692", + "0x1f468", + "0x200d", + "0x1f692", + "0x1f469", + "0x200d", + "0x1f692", + "0x1f46e", + "0x1f46e", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f46e", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f575", + "0x1f575", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f575", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f482", + "0x1f482", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f482", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f977", + "0x1f477", + "0x1f477", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f477", + "0x200d", + "0x2640", + "0xfe0f", + "0x1fac5", + "0x1f934", + "0x1f478", + "0x1f473", + "0x1f473", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f473", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f472", + "0x1f9d5", + "0x1f935", + "0x1f935", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f935", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f470", + "0x1f470", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f470", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f930", + "0x1fac3", + "0x1fac4", + "0x1f931", + "0x1f469", + "0x200d", + "0x1f37c", + "0x1f468", + "0x200d", + "0x1f37c", + "0x1f9d1", + "0x200d", + "0x1f37c", + "0x1f47c", + "0x1f385", + "0x1f936", + "0x1f9d1", + "0x200d", + "0x1f384", + "0x1f9b8", + "0x1f9b8", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9b8", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9b9", + "0x1f9b9", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9b9", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d9", + "0x1f9d9", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d9", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9da", + "0x1f9da", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9da", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9db", + "0x1f9db", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9db", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9dc", + "0x1f9dc", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9dc", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9dd", + "0x1f9dd", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9dd", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9de", + "0x1f9de", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9de", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9df", + "0x1f9df", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9df", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9cc", + "0x1f486", + "0x1f486", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f486", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f487", + "0x1f487", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f487", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b6", + "0x1f6b6", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x2640", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x2642", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9cd", + "0x1f9cd", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9cd", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9ce", + "0x1f9ce", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x2640", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x2642", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f9af", + "0x1f9d1", + "0x200d", + "0x1f9af", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9af", + "0x1f468", + "0x200d", + "0x1f9af", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f469", + "0x200d", + "0x1f9af", + "0x1f469", + "0x200d", + "0x1f9af", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f9bc", + "0x1f9d1", + "0x200d", + "0x1f9bc", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9bc", + "0x1f468", + "0x200d", + "0x1f9bc", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f469", + "0x200d", + "0x1f9bc", + "0x1f469", + "0x200d", + "0x1f9bc", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f9bd", + "0x1f9d1", + "0x200d", + "0x1f9bd", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9bd", + "0x1f468", + "0x200d", + "0x1f9bd", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f469", + "0x200d", + "0x1f9bd", + "0x1f469", + "0x200d", + "0x1f9bd", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f3c3", + "0x1f3c3", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x2640", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x2642", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f483", + "0x1f57a", + "0x1f574", + "0x1f46f", + "0x1f46f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f46f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d6", + "0x1f9d6", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d6", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d7", + "0x1f9d7", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d7", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93a", + "0x1f3c7", + "0x26f7", + "0x1f3c2", + "0x1f3cc", + "0x1f3cc", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3cc", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3c4", + "0x1f3c4", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3c4", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6a3", + "0x1f6a3", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6a3", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3ca", + "0x1f3ca", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3ca", + "0x200d", + "0x2640", + "0xfe0f", + "0x26f9", + "0x26f9", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x26f9", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3cb", + "0x1f3cb", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3cb", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b4", + "0x1f6b4", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6b4", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b5", + "0x1f6b5", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6b5", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f938", + "0x1f938", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f938", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93c", + "0x1f93c", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f93c", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93d", + "0x1f93d", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f93d", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93e", + "0x1f93e", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f93e", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f939", + "0x1f939", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f939", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d8", + "0x1f9d8", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d8", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6c0", + "0x1f6cc", + "0x1f9d1", + "0x200d", + "0x1f91d", + "0x200d", + "0x1f9d1", + "0x1f46d", + "0x1f46b", + "0x1f46c", + "0x1f48f", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f48b", + "0x200d", + "0x1f468", + "0x1f468", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f48b", + "0x200d", + "0x1f468", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f48b", + "0x200d", + "0x1f469", + "0x1f491", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f468", + "0x1f468", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f468", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f469", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f5e3", + "0x1f464", + "0x1f465", + "0x1fac2", + "0x1f46a", + "0x1f9d1", + "0x200d", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x1f9d1", + "0x200d", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x200d", + "0x1f9d2", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x200d", + "0x1f9d2", + "0x1f463" + ], + "animals_and_nature": [ + "0x1f435", + "0x1f412", + "0x1f98d", + "0x1f9a7", + "0x1f436", + "0x1f415", + "0x1f9ae", + "0x1f415", + "0x200d", + "0x1f9ba", + "0x1f429", + "0x1f43a", + "0x1f98a", + "0x1f99d", + "0x1f431", + "0x1f408", + "0x1f408", + "0x200d", + "0x2b1b", + "0x1f981", + "0x1f42f", + "0x1f405", + "0x1f406", + "0x1f434", + "0x1face", + "0x1facf", + "0x1f40e", + "0x1f984", + "0x1f993", + "0x1f98c", + "0x1f9ac", + "0x1f42e", + "0x1f402", + "0x1f403", + "0x1f404", + "0x1f437", + "0x1f416", + "0x1f417", + "0x1f43d", + "0x1f40f", + "0x1f411", + "0x1f410", + "0x1f42a", + "0x1f42b", + "0x1f999", + "0x1f992", + "0x1f418", + "0x1f9a3", + "0x1f98f", + "0x1f99b", + "0x1f42d", + "0x1f401", + "0x1f400", + "0x1f439", + "0x1f430", + "0x1f407", + "0x1f43f", + "0x1f9ab", + "0x1f994", + "0x1f987", + "0x1f43b", + "0x1f43b", + "0x200d", + "0x2744", + "0xfe0f", + "0x1f428", + "0x1f43c", + "0x1f9a5", + "0x1f9a6", + "0x1f9a8", + "0x1f998", + "0x1f9a1", + "0x1f43e", + "0x1f983", + "0x1f414", + "0x1f413", + "0x1f423", + "0x1f424", + "0x1f425", + "0x1f426", + "0x1f427", + "0x1f54a", + "0x1f985", + "0x1f986", + "0x1f9a2", + "0x1f989", + "0x1f9a4", + "0x1fab6", + "0x1f9a9", + "0x1f99a", + "0x1f99c", + "0x1fabd", + "0x1f426", + "0x200d", + "0x2b1b", + "0x1fabf", + "0x1f426", + "0x200d", + "0x1f525", + "0x1f438", + "0x1f40a", + "0x1f422", + "0x1f98e", + "0x1f40d", + "0x1f432", + "0x1f409", + "0x1f995", + "0x1f996", + "0x1f433", + "0x1f40b", + "0x1f42c", + "0x1f9ad", + "0x1f41f", + "0x1f420", + "0x1f421", + "0x1f988", + "0x1f419", + "0x1f41a", + "0x1fab8", + "0x1fabc", + "0x1f40c", + "0x1f98b", + "0x1f41b", + "0x1f41c", + "0x1f41d", + "0x1fab2", + "0x1f41e", + "0x1f997", + "0x1fab3", + "0x1f577", + "0x1f578", + "0x1f982", + "0x1f99f", + "0x1fab0", + "0x1fab1", + "0x1f9a0", + "0x1f490", + "0x1f338", + "0x1f4ae", + "0x1fab7", + "0x1f3f5", + "0x1f339", + "0x1f940", + "0x1f33a", + "0x1f33b", + "0x1f33c", + "0x1f337", + "0x1fabb", + "0x1f331", + "0x1fab4", + "0x1f332", + "0x1f333", + "0x1f334", + "0x1f335", + "0x1f33e", + "0x1f33f", + "0x2618", + "0x1f340", + "0x1f341", + "0x1f342", + "0x1f343", + "0x1fab9", + "0x1faba", + "0x1f344" + ], + "food_and_drink": [ + "0x1f347", + "0x1f348", + "0x1f349", + "0x1f34a", + "0x1f34b", + "0x1f34b", + "0x200d", + "0x1f7e9", + "0x1f34c", + "0x1f34d", + "0x1f96d", + "0x1f34e", + "0x1f34f", + "0x1f350", + "0x1f351", + "0x1f352", + "0x1f353", + "0x1fad0", + "0x1f95d", + "0x1f345", + "0x1fad2", + "0x1f965", + "0x1f951", + "0x1f346", + "0x1f954", + "0x1f955", + "0x1f33d", + "0x1f336", + "0x1fad1", + "0x1f952", + "0x1f96c", + "0x1f966", + "0x1f9c4", + "0x1f9c5", + "0x1f95c", + "0x1fad8", + "0x1f330", + "0x1fada", + "0x1fadb", + "0x1f344", + "0x200d", + "0x1f7eb", + "0x1f35e", + "0x1f950", + "0x1f956", + "0x1fad3", + "0x1f968", + "0x1f96f", + "0x1f95e", + "0x1f9c7", + "0x1f9c0", + "0x1f356", + "0x1f357", + "0x1f969", + "0x1f953", + "0x1f354", + "0x1f35f", + "0x1f355", + "0x1f32d", + "0x1f96a", + "0x1f32e", + "0x1f32f", + "0x1fad4", + "0x1f959", + "0x1f9c6", + "0x1f95a", + "0x1f373", + "0x1f958", + "0x1f372", + "0x1fad5", + "0x1f963", + "0x1f957", + "0x1f37f", + "0x1f9c8", + "0x1f9c2", + "0x1f96b", + "0x1f371", + "0x1f358", + "0x1f359", + "0x1f35a", + "0x1f35b", + "0x1f35c", + "0x1f35d", + "0x1f360", + "0x1f362", + "0x1f363", + "0x1f364", + "0x1f365", + "0x1f96e", + "0x1f361", + "0x1f95f", + "0x1f960", + "0x1f961", + "0x1f980", + "0x1f99e", + "0x1f990", + "0x1f991", + "0x1f9aa", + "0x1f366", + "0x1f367", + "0x1f368", + "0x1f369", + "0x1f36a", + "0x1f382", + "0x1f370", + "0x1f9c1", + "0x1f967", + "0x1f36b", + "0x1f36c", + "0x1f36d", + "0x1f36e", + "0x1f36f", + "0x1f37c", + "0x1f95b", + "0x2615", + "0x1fad6", + "0x1f375", + "0x1f376", + "0x1f37e", + "0x1f377", + "0x1f378", + "0x1f379", + "0x1f37a", + "0x1f37b", + "0x1f942", + "0x1f943", + "0x1fad7", + "0x1f964", + "0x1f9cb", + "0x1f9c3", + "0x1f9c9", + "0x1f9ca", + "0x1f962", + "0x1f37d", + "0x1f374", + "0x1f944", + "0x1f52a", + "0x1fad9", + "0x1f3fa" + ], + "travel_and_places": [ + "0x1f30d", + "0x1f30e", + "0x1f30f", + "0x1f310", + "0x1f5fa", + "0x1f5fe", + "0x1f9ed", + "0x1f3d4", + "0x26f0", + "0x1f30b", + "0x1f5fb", + "0x1f3d5", + "0x1f3d6", + "0x1f3dc", + "0x1f3dd", + "0x1f3de", + "0x1f3df", + "0x1f3db", + "0x1f3d7", + "0x1f9f1", + "0x1faa8", + "0x1fab5", + "0x1f6d6", + "0x1f3d8", + "0x1f3da", + "0x1f3e0", + "0x1f3e1", + "0x1f3e2", + "0x1f3e3", + "0x1f3e4", + "0x1f3e5", + "0x1f3e6", + "0x1f3e8", + "0x1f3e9", + "0x1f3ea", + "0x1f3eb", + "0x1f3ec", + "0x1f3ed", + "0x1f3ef", + "0x1f3f0", + "0x1f492", + "0x1f5fc", + "0x1f5fd", + "0x26ea", + "0x1f54c", + "0x1f6d5", + "0x1f54d", + "0x26e9", + "0x1f54b", + "0x26f2", + "0x26fa", + "0x1f301", + "0x1f303", + "0x1f3d9", + "0x1f304", + "0x1f305", + "0x1f306", + "0x1f307", + "0x1f309", + "0x2668", + "0x1f3a0", + "0x1f6dd", + "0x1f3a1", + "0x1f3a2", + "0x1f488", + "0x1f3aa", + "0x1f682", + "0x1f683", + "0x1f684", + "0x1f685", + "0x1f686", + "0x1f687", + "0x1f688", + "0x1f689", + "0x1f68a", + "0x1f69d", + "0x1f69e", + "0x1f68b", + "0x1f68c", + "0x1f68d", + "0x1f68e", + "0x1f690", + "0x1f691", + "0x1f692", + "0x1f693", + "0x1f694", + "0x1f695", + "0x1f696", + "0x1f697", + "0x1f698", + "0x1f699", + "0x1f6fb", + "0x1f69a", + "0x1f69b", + "0x1f69c", + "0x1f3ce", + "0x1f3cd", + "0x1f6f5", + "0x1f9bd", + "0x1f9bc", + "0x1f6fa", + "0x1f6b2", + "0x1f6f4", + "0x1f6f9", + "0x1f6fc", + "0x1f68f", + "0x1f6e3", + "0x1f6e4", + "0x1f6e2", + "0x26fd", + "0x1f6de", + "0x1f6a8", + "0x1f6a5", + "0x1f6a6", + "0x1f6d1", + "0x1f6a7", + "0x2693", + "0x1f6df", + "0x26f5", + "0x1f6f6", + "0x1f6a4", + "0x1f6f3", + "0x26f4", + "0x1f6e5", + "0x1f6a2", + "0x2708", + "0x1f6e9", + "0x1f6eb", + "0x1f6ec", + "0x1fa82", + "0x1f4ba", + "0x1f681", + "0x1f69f", + "0x1f6a0", + "0x1f6a1", + "0x1f6f0", + "0x1f680", + "0x1f6f8", + "0x1f6ce", + "0x1f9f3", + "0x231b", + "0x23f3", + "0x231a", + "0x23f0", + "0x23f1", + "0x23f2", + "0x1f570", + "0x1f55b", + "0x1f567", + "0x1f550", + "0x1f55c", + "0x1f551", + "0x1f55d", + "0x1f552", + "0x1f55e", + "0x1f553", + "0x1f55f", + "0x1f554", + "0x1f560", + "0x1f555", + "0x1f561", + "0x1f556", + "0x1f562", + "0x1f557", + "0x1f563", + "0x1f558", + "0x1f564", + "0x1f559", + "0x1f565", + "0x1f55a", + "0x1f566", + "0x1f311", + "0x1f312", + "0x1f313", + "0x1f314", + "0x1f315", + "0x1f316", + "0x1f317", + "0x1f318", + "0x1f319", + "0x1f31a", + "0x1f31b", + "0x1f31c", + "0x1f321", + "0x2600", + "0x1f31d", + "0x1f31e", + "0x1fa90", + "0x2b50", + "0x1f31f", + "0x1f320", + "0x1f30c", + "0x2601", + "0x26c5", + "0x26c8", + "0x1f324", + "0x1f325", + "0x1f326", + "0x1f327", + "0x1f328", + "0x1f329", + "0x1f32a", + "0x1f32b", + "0x1f32c", + "0x1f300", + "0x1f308", + "0x1f302", + "0x2602", + "0x2614", + "0x26f1", + "0x26a1", + "0x2744", + "0x2603", + "0x26c4", + "0x2604", + "0x1f525", + "0x1f4a7", + "0x1f30a" + ], + "activities": [ + "0x1f383", + "0x1f384", + "0x1f386", + "0x1f387", + "0x1f9e8", + "0x2728", + "0x1f388", + "0x1f389", + "0x1f38a", + "0x1f38b", + "0x1f38d", + "0x1f38e", + "0x1f38f", + "0x1f390", + "0x1f391", + "0x1f9e7", + "0x1f380", + "0x1f381", + "0x1f397", + "0x1f39f", + "0x1f3ab", + "0x1f396", + "0x1f3c6", + "0x1f3c5", + "0x1f947", + "0x1f948", + "0x1f949", + "0x26bd", + "0x26be", + "0x1f94e", + "0x1f3c0", + "0x1f3d0", + "0x1f3c8", + "0x1f3c9", + "0x1f3be", + "0x1f94f", + "0x1f3b3", + "0x1f3cf", + "0x1f3d1", + "0x1f3d2", + "0x1f94d", + "0x1f3d3", + "0x1f3f8", + "0x1f94a", + "0x1f94b", + "0x1f945", + "0x26f3", + "0x26f8", + "0x1f3a3", + "0x1f93f", + "0x1f3bd", + "0x1f3bf", + "0x1f6f7", + "0x1f94c", + "0x1f3af", + "0x1fa80", + "0x1fa81", + "0x1f52b", + "0x1f3b1", + "0x1f52e", + "0x1fa84", + "0x1f3ae", + "0x1f579", + "0x1f3b0", + "0x1f3b2", + "0x1f9e9", + "0x1f9f8", + "0x1fa85", + "0x1faa9", + "0x1fa86", + "0x2660", + "0x2665", + "0x2666", + "0x2663", + "0x265f", + "0x1f0cf", + "0x1f004", + "0x1f3b4", + "0x1f3ad", + "0x1f5bc", + "0x1f3a8", + "0x1f9f5", + "0x1faa1", + "0x1f9f6", + "0x1faa2" + ], + "objects": [ + "0x1f453", + "0x1f576", + "0x1f97d", + "0x1f97c", + "0x1f9ba", + "0x1f454", + "0x1f455", + "0x1f456", + "0x1f9e3", + "0x1f9e4", + "0x1f9e5", + "0x1f9e6", + "0x1f457", + "0x1f458", + "0x1f97b", + "0x1fa71", + "0x1fa72", + "0x1fa73", + "0x1f459", + "0x1f45a", + "0x1faad", + "0x1f45b", + "0x1f45c", + "0x1f45d", + "0x1f6cd", + "0x1f392", + "0x1fa74", + "0x1f45e", + "0x1f45f", + "0x1f97e", + "0x1f97f", + "0x1f460", + "0x1f461", + "0x1fa70", + "0x1f462", + "0x1faae", + "0x1f451", + "0x1f452", + "0x1f3a9", + "0x1f393", + "0x1f9e2", + "0x1fa96", + "0x26d1", + "0x1f4ff", + "0x1f484", + "0x1f48d", + "0x1f48e", + "0x1f507", + "0x1f508", + "0x1f509", + "0x1f50a", + "0x1f4e2", + "0x1f4e3", + "0x1f4ef", + "0x1f514", + "0x1f515", + "0x1f3bc", + "0x1f3b5", + "0x1f3b6", + "0x1f399", + "0x1f39a", + "0x1f39b", + "0x1f3a4", + "0x1f3a7", + "0x1f4fb", + "0x1f3b7", + "0x1fa97", + "0x1f3b8", + "0x1f3b9", + "0x1f3ba", + "0x1f3bb", + "0x1fa95", + "0x1f941", + "0x1fa98", + "0x1fa87", + "0x1fa88", + "0x1f4f1", + "0x1f4f2", + "0x260e", + "0x1f4de", + "0x1f4df", + "0x1f4e0", + "0x1f50b", + "0x1faab", + "0x1f50c", + "0x1f4bb", + "0x1f5a5", + "0x1f5a8", + "0x2328", + "0x1f5b1", + "0x1f5b2", + "0x1f4bd", + "0x1f4be", + "0x1f4bf", + "0x1f4c0", + "0x1f9ee", + "0x1f3a5", + "0x1f39e", + "0x1f4fd", + "0x1f3ac", + "0x1f4fa", + "0x1f4f7", + "0x1f4f8", + "0x1f4f9", + "0x1f4fc", + "0x1f50d", + "0x1f50e", + "0x1f56f", + "0x1f4a1", + "0x1f526", + "0x1f3ee", + "0x1fa94", + "0x1f4d4", + "0x1f4d5", + "0x1f4d6", + "0x1f4d7", + "0x1f4d8", + "0x1f4d9", + "0x1f4da", + "0x1f4d3", + "0x1f4d2", + "0x1f4c3", + "0x1f4dc", + "0x1f4c4", + "0x1f4f0", + "0x1f5de", + "0x1f4d1", + "0x1f516", + "0x1f3f7", + "0x1f4b0", + "0x1fa99", + "0x1f4b4", + "0x1f4b5", + "0x1f4b6", + "0x1f4b7", + "0x1f4b8", + "0x1f4b3", + "0x1f9fe", + "0x1f4b9", + "0x2709", + "0x1f4e7", + "0x1f4e8", + "0x1f4e9", + "0x1f4e4", + "0x1f4e5", + "0x1f4e6", + "0x1f4eb", + "0x1f4ea", + "0x1f4ec", + "0x1f4ed", + "0x1f4ee", + "0x1f5f3", + "0x270f", + "0x2712", + "0x1f58b", + "0x1f58a", + "0x1f58c", + "0x1f58d", + "0x1f4dd", + "0x1f4bc", + "0x1f4c1", + "0x1f4c2", + "0x1f5c2", + "0x1f4c5", + "0x1f4c6", + "0x1f5d2", + "0x1f5d3", + "0x1f4c7", + "0x1f4c8", + "0x1f4c9", + "0x1f4ca", + "0x1f4cb", + "0x1f4cc", + "0x1f4cd", + "0x1f4ce", + "0x1f587", + "0x1f4cf", + "0x1f4d0", + "0x2702", + "0x1f5c3", + "0x1f5c4", + "0x1f5d1", + "0x1f512", + "0x1f513", + "0x1f50f", + "0x1f510", + "0x1f511", + "0x1f5dd", + "0x1f528", + "0x1fa93", + "0x26cf", + "0x2692", + "0x1f6e0", + "0x1f5e1", + "0x2694", + "0x1f4a3", + "0x1fa83", + "0x1f3f9", + "0x1f6e1", + "0x1fa9a", + "0x1f527", + "0x1fa9b", + "0x1f529", + "0x2699", + "0x1f5dc", + "0x2696", + "0x1f9af", + "0x1f517", + "0x26d3", + "0xfe0f", + "0x200d", + "0x1f4a5", + "0x26d3", + "0x1fa9d", + "0x1f9f0", + "0x1f9f2", + "0x1fa9c", + "0x2697", + "0x1f9ea", + "0x1f9eb", + "0x1f9ec", + "0x1f52c", + "0x1f52d", + "0x1f4e1", + "0x1f489", + "0x1fa78", + "0x1f48a", + "0x1fa79", + "0x1fa7c", + "0x1fa7a", + "0x1fa7b", + "0x1f6aa", + "0x1f6d7", + "0x1fa9e", + "0x1fa9f", + "0x1f6cf", + "0x1f6cb", + "0x1fa91", + "0x1f6bd", + "0x1faa0", + "0x1f6bf", + "0x1f6c1", + "0x1faa4", + "0x1fa92", + "0x1f9f4", + "0x1f9f7", + "0x1f9f9", + "0x1f9fa", + "0x1f9fb", + "0x1faa3", + "0x1f9fc", + "0x1fae7", + "0x1faa5", + "0x1f9fd", + "0x1f9ef", + "0x1f6d2", + "0x1f6ac", + "0x26b0", + "0x1faa6", + "0x26b1", + "0x1f9ff", + "0x1faac", + "0x1f5ff", + "0x1faa7", + "0x1faaa" + ], + "symbols": [ + "0x1f3e7", + "0x1f6ae", + "0x1f6b0", + "0x267f", + "0x1f6b9", + "0x1f6ba", + "0x1f6bb", + "0x1f6bc", + "0x1f6be", + "0x1f6c2", + "0x1f6c3", + "0x1f6c4", + "0x1f6c5", + "0x26a0", + "0x1f6b8", + "0x26d4", + "0x1f6ab", + "0x1f6b3", + "0x1f6ad", + "0x1f6af", + "0x1f6b1", + "0x1f6b7", + "0x1f4f5", + "0x1f51e", + "0x2622", + "0x2623", + "0x2b06", + "0x2197", + "0x27a1", + "0x2198", + "0x2b07", + "0x2199", + "0x2b05", + "0x2196", + "0x2195", + "0x2194", + "0x21a9", + "0x21aa", + "0x2934", + "0x2935", + "0x1f503", + "0x1f504", + "0x1f519", + "0x1f51a", + "0x1f51b", + "0x1f51c", + "0x1f51d", + "0x1f6d0", + "0x269b", + "0x1f549", + "0x2721", + "0x2638", + "0x262f", + "0x271d", + "0x2626", + "0x262a", + "0x262e", + "0x1f54e", + "0x1f52f", + "0x1faaf", + "0x2648", + "0x2649", + "0x264a", + "0x264b", + "0x264c", + "0x264d", + "0x264e", + "0x264f", + "0x2650", + "0x2651", + "0x2652", + "0x2653", + "0x26ce", + "0x1f500", + "0x1f501", + "0x1f502", + "0x25b6", + "0x23e9", + "0x23ed", + "0x23ef", + "0x25c0", + "0x23ea", + "0x23ee", + "0x1f53c", + "0x23eb", + "0x1f53d", + "0x23ec", + "0x23f8", + "0x23f9", + "0x23fa", + "0x23cf", + "0x1f3a6", + "0x1f505", + "0x1f506", + "0x1f4f6", + "0x1f6dc", + "0x1f4f3", + "0x1f4f4", + "0x2640", + "0x2642", + "0x26a7", + "0x2716", + "0x2795", + "0x2796", + "0x2797", + "0x1f7f0", + "0x267e", + "0x203c", + "0x2049", + "0x2753", + "0x2754", + "0x2755", + "0x2757", + "0x3030", + "0x1f4b1", + "0x1f4b2", + "0x2695", + "0x267b", + "0x269c", + "0x1f531", + "0x1f4db", + "0x1f530", + "0x2b55", + "0x2705", + "0x2611", + "0x2714", + "0x274c", + "0x274e", + "0x27b0", + "0x27bf", + "0x303d", + "0x2733", + "0x2734", + "0x2747", + "0x00a9", + "0x00ae", + "0x2122", + "0x0023", + "0xfe0f", + "0x20e3", + "0x002a", + "0xfe0f", + "0x20e3", + "0x0030", + "0xfe0f", + "0x20e3", + "0x0031", + "0xfe0f", + "0x20e3", + "0x0032", + "0xfe0f", + "0x20e3", + "0x0033", + "0xfe0f", + "0x20e3", + "0x0034", + "0xfe0f", + "0x20e3", + "0x0035", + "0xfe0f", + "0x20e3", + "0x0036", + "0xfe0f", + "0x20e3", + "0x0037", + "0xfe0f", + "0x20e3", + "0x0038", + "0xfe0f", + "0x20e3", + "0x0039", + "0xfe0f", + "0x20e3", + "0x1f51f", + "0x1f520", + "0x1f521", + "0x1f522", + "0x1f523", + "0x1f524", + "0x1f170", + "0x1f18e", + "0x1f171", + "0x1f191", + "0x1f192", + "0x1f193", + "0x2139", + "0x1f194", + "0x24c2", + "0x1f195", + "0x1f196", + "0x1f17e", + "0x1f197", + "0x1f17f", + "0x1f198", + "0x1f199", + "0x1f19a", + "0x1f201", + "0x1f202", + "0x1f237", + "0x1f236", + "0x1f22f", + "0x1f250", + "0x1f239", + "0x1f21a", + "0x1f232", + "0x1f251", + "0x1f238", + "0x1f234", + "0x1f233", + "0x3297", + "0x3299", + "0x1f23a", + "0x1f235", + "0x1f534", + "0x1f7e0", + "0x1f7e1", + "0x1f7e2", + "0x1f535", + "0x1f7e3", + "0x1f7e4", + "0x26ab", + "0x26aa", + "0x1f7e5", + "0x1f7e7", + "0x1f7e8", + "0x1f7e9", + "0x1f7e6", + "0x1f7ea", + "0x1f7eb", + "0x2b1b", + "0x2b1c", + "0x25fc", + "0x25fb", + "0x25fe", + "0x25fd", + "0x25aa", + "0x25ab", + "0x1f536", + "0x1f537", + "0x1f538", + "0x1f539", + "0x1f53a", + "0x1f53b", + "0x1f4a0", + "0x1f518", + "0x1f533", + "0x1f532" + ], + "flags": [ + "0x1f3c1", + "0x1f6a9", + "0x1f38c", + "0x1f3f4", + "0x1f3f3", + "0x1f3f3", + "0xfe0f", + "0x200d", + "0x1f308", + "0x1f3f3", + "0xfe0f", + "0x200d", + "0x26a7", + "0xfe0f", + "0x1f3f4", + "0x200d", + "0x2620", + "0xfe0f", + "0x1f1e6", + "0x1f1e8", + "0x1f1e6", + "0x1f1e9", + "0x1f1e6", + "0x1f1ea", + "0x1f1e6", + "0x1f1eb", + "0x1f1e6", + "0x1f1ec", + "0x1f1e6", + "0x1f1ee", + "0x1f1e6", + "0x1f1f1", + "0x1f1e6", + "0x1f1f2", + "0x1f1e6", + "0x1f1f4", + "0x1f1e6", + "0x1f1f6", + "0x1f1e6", + "0x1f1f7", + "0x1f1e6", + "0x1f1f8", + "0x1f1e6", + "0x1f1f9", + "0x1f1e6", + "0x1f1fa", + "0x1f1e6", + "0x1f1fc", + "0x1f1e6", + "0x1f1fd", + "0x1f1e6", + "0x1f1ff", + "0x1f1e7", + "0x1f1e6", + "0x1f1e7", + "0x1f1e7", + "0x1f1e7", + "0x1f1e9", + "0x1f1e7", + "0x1f1ea", + "0x1f1e7", + "0x1f1eb", + "0x1f1e7", + "0x1f1ec", + "0x1f1e7", + "0x1f1ed", + "0x1f1e7", + "0x1f1ee", + "0x1f1e7", + "0x1f1ef", + "0x1f1e7", + "0x1f1f1", + "0x1f1e7", + "0x1f1f2", + "0x1f1e7", + "0x1f1f3", + "0x1f1e7", + "0x1f1f4", + "0x1f1e7", + "0x1f1f6", + "0x1f1e7", + "0x1f1f7", + "0x1f1e7", + "0x1f1f8", + "0x1f1e7", + "0x1f1f9", + "0x1f1e7", + "0x1f1fb", + "0x1f1e7", + "0x1f1fc", + "0x1f1e7", + "0x1f1fe", + "0x1f1e7", + "0x1f1ff", + "0x1f1e8", + "0x1f1e6", + "0x1f1e8", + "0x1f1e8", + "0x1f1e8", + "0x1f1e9", + "0x1f1e8", + "0x1f1eb", + "0x1f1e8", + "0x1f1ec", + "0x1f1e8", + "0x1f1ed", + "0x1f1e8", + "0x1f1ee", + "0x1f1e8", + "0x1f1f0", + "0x1f1e8", + "0x1f1f1", + "0x1f1e8", + "0x1f1f2", + "0x1f1e8", + "0x1f1f3", + "0x1f1e8", + "0x1f1f4", + "0x1f1e8", + "0x1f1f5", + "0x1f1e8", + "0x1f1f7", + "0x1f1e8", + "0x1f1fa", + "0x1f1e8", + "0x1f1fb", + "0x1f1e8", + "0x1f1fc", + "0x1f1e8", + "0x1f1fd", + "0x1f1e8", + "0x1f1fe", + "0x1f1e8", + "0x1f1ff", + "0x1f1e9", + "0x1f1ea", + "0x1f1e9", + "0x1f1ec", + "0x1f1e9", + "0x1f1ef", + "0x1f1e9", + "0x1f1f0", + "0x1f1e9", + "0x1f1f2", + "0x1f1e9", + "0x1f1f4", + "0x1f1e9", + "0x1f1ff", + "0x1f1ea", + "0x1f1e6", + "0x1f1ea", + "0x1f1e8", + "0x1f1ea", + "0x1f1ea", + "0x1f1ea", + "0x1f1ec", + "0x1f1ea", + "0x1f1ed", + "0x1f1ea", + "0x1f1f7", + "0x1f1ea", + "0x1f1f8", + "0x1f1ea", + "0x1f1f9", + "0x1f1ea", + "0x1f1fa", + "0x1f1eb", + "0x1f1ee", + "0x1f1eb", + "0x1f1ef", + "0x1f1eb", + "0x1f1f0", + "0x1f1eb", + "0x1f1f2", + "0x1f1eb", + "0x1f1f4", + "0x1f1eb", + "0x1f1f7", + "0x1f1ec", + "0x1f1e6", + "0x1f1ec", + "0x1f1e7", + "0x1f1ec", + "0x1f1e9", + "0x1f1ec", + "0x1f1ea", + "0x1f1ec", + "0x1f1eb", + "0x1f1ec", + "0x1f1ec", + "0x1f1ec", + "0x1f1ed", + "0x1f1ec", + "0x1f1ee", + "0x1f1ec", + "0x1f1f1", + "0x1f1ec", + "0x1f1f2", + "0x1f1ec", + "0x1f1f3", + "0x1f1ec", + "0x1f1f5", + "0x1f1ec", + "0x1f1f6", + "0x1f1ec", + "0x1f1f7", + "0x1f1ec", + "0x1f1f8", + "0x1f1ec", + "0x1f1f9", + "0x1f1ec", + "0x1f1fa", + "0x1f1ec", + "0x1f1fc", + "0x1f1ec", + "0x1f1fe", + "0x1f1ed", + "0x1f1f0", + "0x1f1ed", + "0x1f1f2", + "0x1f1ed", + "0x1f1f3", + "0x1f1ed", + "0x1f1f7", + "0x1f1ed", + "0x1f1f9", + "0x1f1ed", + "0x1f1fa", + "0x1f1ee", + "0x1f1e8", + "0x1f1ee", + "0x1f1e9", + "0x1f1ee", + "0x1f1ea", + "0x1f1ee", + "0x1f1f1", + "0x1f1ee", + "0x1f1f2", + "0x1f1ee", + "0x1f1f3", + "0x1f1ee", + "0x1f1f4", + "0x1f1ee", + "0x1f1f6", + "0x1f1ee", + "0x1f1f7", + "0x1f1ee", + "0x1f1f8", + "0x1f1ee", + "0x1f1f9", + "0x1f1ef", + "0x1f1ea", + "0x1f1ef", + "0x1f1f2", + "0x1f1ef", + "0x1f1f4", + "0x1f1ef", + "0x1f1f5", + "0x1f1f0", + "0x1f1ea", + "0x1f1f0", + "0x1f1ec", + "0x1f1f0", + "0x1f1ed", + "0x1f1f0", + "0x1f1ee", + "0x1f1f0", + "0x1f1f2", + "0x1f1f0", + "0x1f1f3", + "0x1f1f0", + "0x1f1f5", + "0x1f1f0", + "0x1f1f7", + "0x1f1f0", + "0x1f1fc", + "0x1f1f0", + "0x1f1fe", + "0x1f1f0", + "0x1f1ff", + "0x1f1f1", + "0x1f1e6", + "0x1f1f1", + "0x1f1e7", + "0x1f1f1", + "0x1f1e8", + "0x1f1f1", + "0x1f1ee", + "0x1f1f1", + "0x1f1f0", + "0x1f1f1", + "0x1f1f7", + "0x1f1f1", + "0x1f1f8", + "0x1f1f1", + "0x1f1f9", + "0x1f1f1", + "0x1f1fa", + "0x1f1f1", + "0x1f1fb", + "0x1f1f1", + "0x1f1fe", + "0x1f1f2", + "0x1f1e6", + "0x1f1f2", + "0x1f1e8", + "0x1f1f2", + "0x1f1e9", + "0x1f1f2", + "0x1f1ea", + "0x1f1f2", + "0x1f1eb", + "0x1f1f2", + "0x1f1ec", + "0x1f1f2", + "0x1f1ed", + "0x1f1f2", + "0x1f1f0", + "0x1f1f2", + "0x1f1f1", + "0x1f1f2", + "0x1f1f2", + "0x1f1f2", + "0x1f1f3", + "0x1f1f2", + "0x1f1f4", + "0x1f1f2", + "0x1f1f5", + "0x1f1f2", + "0x1f1f6", + "0x1f1f2", + "0x1f1f7", + "0x1f1f2", + "0x1f1f8", + "0x1f1f2", + "0x1f1f9", + "0x1f1f2", + "0x1f1fa", + "0x1f1f2", + "0x1f1fb", + "0x1f1f2", + "0x1f1fc", + "0x1f1f2", + "0x1f1fd", + "0x1f1f2", + "0x1f1fe", + "0x1f1f2", + "0x1f1ff", + "0x1f1f3", + "0x1f1e6", + "0x1f1f3", + "0x1f1e8", + "0x1f1f3", + "0x1f1ea", + "0x1f1f3", + "0x1f1eb", + "0x1f1f3", + "0x1f1ec", + "0x1f1f3", + "0x1f1ee", + "0x1f1f3", + "0x1f1f1", + "0x1f1f3", + "0x1f1f4", + "0x1f1f3", + "0x1f1f5", + "0x1f1f3", + "0x1f1f7", + "0x1f1f3", + "0x1f1fa", + "0x1f1f3", + "0x1f1ff", + "0x1f1f4", + "0x1f1f2", + "0x1f1f5", + "0x1f1e6", + "0x1f1f5", + "0x1f1ea", + "0x1f1f5", + "0x1f1eb", + "0x1f1f5", + "0x1f1ec", + "0x1f1f5", + "0x1f1ed", + "0x1f1f5", + "0x1f1f0", + "0x1f1f5", + "0x1f1f1", + "0x1f1f5", + "0x1f1f2", + "0x1f1f5", + "0x1f1f3", + "0x1f1f5", + "0x1f1f7", + "0x1f1f5", + "0x1f1f8", + "0x1f1f5", + "0x1f1f9", + "0x1f1f5", + "0x1f1fc", + "0x1f1f5", + "0x1f1fe", + "0x1f1f6", + "0x1f1e6", + "0x1f1f7", + "0x1f1ea", + "0x1f1f7", + "0x1f1f4", + "0x1f1f7", + "0x1f1f8", + "0x1f1f7", + "0x1f1fa", + "0x1f1f7", + "0x1f1fc", + "0x1f1f8", + "0x1f1e6", + "0x1f1f8", + "0x1f1e7", + "0x1f1f8", + "0x1f1e8", + "0x1f1f8", + "0x1f1e9", + "0x1f1f8", + "0x1f1ea", + "0x1f1f8", + "0x1f1ec", + "0x1f1f8", + "0x1f1ed", + "0x1f1f8", + "0x1f1ee", + "0x1f1f8", + "0x1f1ef", + "0x1f1f8", + "0x1f1f0", + "0x1f1f8", + "0x1f1f1", + "0x1f1f8", + "0x1f1f2", + "0x1f1f8", + "0x1f1f3", + "0x1f1f8", + "0x1f1f4", + "0x1f1f8", + "0x1f1f7", + "0x1f1f8", + "0x1f1f8", + "0x1f1f8", + "0x1f1f9", + "0x1f1f8", + "0x1f1fb", + "0x1f1f8", + "0x1f1fd", + "0x1f1f8", + "0x1f1fe", + "0x1f1f8", + "0x1f1ff", + "0x1f1f9", + "0x1f1e6", + "0x1f1f9", + "0x1f1e8", + "0x1f1f9", + "0x1f1e9", + "0x1f1f9", + "0x1f1eb", + "0x1f1f9", + "0x1f1ec", + "0x1f1f9", + "0x1f1ed", + "0x1f1f9", + "0x1f1ef", + "0x1f1f9", + "0x1f1f0", + "0x1f1f9", + "0x1f1f1", + "0x1f1f9", + "0x1f1f2", + "0x1f1f9", + "0x1f1f3", + "0x1f1f9", + "0x1f1f4", + "0x1f1f9", + "0x1f1f7", + "0x1f1f9", + "0x1f1f9", + "0x1f1f9", + "0x1f1fb", + "0x1f1f9", + "0x1f1fc", + "0x1f1f9", + "0x1f1ff", + "0x1f1fa", + "0x1f1e6", + "0x1f1fa", + "0x1f1ec", + "0x1f1fa", + "0x1f1f2", + "0x1f1fa", + "0x1f1f3", + "0x1f1fa", + "0x1f1f8", + "0x1f1fa", + "0x1f1fe", + "0x1f1fa", + "0x1f1ff", + "0x1f1fb", + "0x1f1e6", + "0x1f1fb", + "0x1f1e8", + "0x1f1fb", + "0x1f1ea", + "0x1f1fb", + "0x1f1ec", + "0x1f1fb", + "0x1f1ee", + "0x1f1fb", + "0x1f1f3", + "0x1f1fb", + "0x1f1fa", + "0x1f1fc", + "0x1f1eb", + "0x1f1fc", + "0x1f1f8", + "0x1f1fd", + "0x1f1f0", + "0x1f1fe", + "0x1f1ea", + "0x1f1fe", + "0x1f1f9", + "0x1f1ff", + "0x1f1e6", + "0x1f1ff", + "0x1f1f2", + "0x1f1ff", + "0x1f1fc", + "0x1f3f4", + "0xe0067", + "0xe0062", + "0xe0065", + "0xe006e", + "0xe0067", + "0xe007f", + "0x1f3f4", + "0xe0067", + "0xe0062", + "0xe0073", + "0xe0063", + "0xe0074", + "0xe007f", + "0x1f3f4", + "0xe0067", + "0xe0062", + "0xe0077", + "0xe006c", + "0xe0073", + "0xe007f" + ] + } + }; - resolve(dst.buffer) - } else if (type === 'blob') { - if (!Blob) { - Blob = (__nccwpck_require__(14300).Blob) + var o_hasOwnProperty = Object.prototype.hasOwnProperty; + var o_keys = (Object.keys || function(obj) { + var result = []; + for (var key in obj) { + if (o_hasOwnProperty.call(obj, key)) { + result.push(key); + } } - 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])) + return result; + }); - 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() - }) + function _copyObject(source, target) { + var keys = o_keys(source); + var key; - 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 (var i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + target[key] = source[key] || target[key]; } - }) - - 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() + function _copyArray(source, target) { + for (var i = 0, l = source.length; i < l; i++) { + target[i] = source[i]; + } } - const dispatcher = this[kClients].find(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) - - if (!dispatcher) { - return - } + function copyObject(source, _target) { + var isArray = Array.isArray(source); + var target = _target || (isArray ? new Array(source.length) : {}); - const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + if (isArray) { + _copyArray(source, target); + } else { + _copyObject(source, target); + } - if (allClientsBusy) { - return + return target; } - 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] - } + /** Get the data based on key**/ + Chance.prototype.get = function (name) { + return copyObject(data[name]); + }; - // 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] + // Mac Address + Chance.prototype.mac_address = function(options){ + // typically mac addresses are separated by ":" + // however they can also be separated by "-" + // the network variant uses a dot every fourth byte - if (this[kCurrentWeight] <= 0) { - this[kCurrentWeight] = this[kMaxWeightPerServer] + options = initOptions(options); + if(!options.separator) { + options.separator = options.networkVersion ? "." : ":"; } - } - 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"; + var mac_pool="ABCDEF1234567890", + mac = ""; + if(!options.networkVersion) { + mac = this.n(this.string, 6, { pool: mac_pool, length:2 }).join(options.separator); + } else { + mac = this.n(this.string, 3, { pool: mac_pool, length:4 }).join(options.separator); + } -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) + return mac; + }; -/** - * @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 - */ + Chance.prototype.normal = function (options) { + options = initOptions(options, {mean : 0, dev : 1, pool : []}); -/** - * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list - * @typedef {[any, any][]} requestResponseList - */ + testRange( + options.pool.constructor !== Array, + "Chance: The pool option must be a valid array." + ); + testRange( + typeof options.mean !== 'number', + "Chance: Mean (mean) must be a number" + ); + testRange( + typeof options.dev !== 'number', + "Chance: Standard deviation (dev) must be a number" + ); -class Cache { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list - * @type {requestResponseList} - */ - #relevantRequestResponseList + // If a pool has been passed, then we are returning an item from that pool, + // using the normal distribution settings that were passed in + if (options.pool.length > 0) { + return this.normal_pool(options); + } - constructor () { - if (arguments[0] !== kConstruct) { - webidl.illegalConstructor() - } + // The Marsaglia Polar method + var s, u, v, norm, + mean = options.mean, + dev = options.dev; - this.#relevantRequestResponseList = arguments[1] - } + do { + // U and V are from the uniform distribution on (-1, 1) + u = this.random() * 2 - 1; + v = this.random() * 2 - 1; - async match (request, options = {}) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) + s = u * u + v * v; + } while (s >= 1); - request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) + // Compute the standard normal variate + norm = u * Math.sqrt(-2 * Math.log(s) / s); - const p = await this.matchAll(request, options) + // Shape and scale + return dev * norm + mean; + }; - if (p.length === 0) { - return - } + Chance.prototype.normal_pool = function(options) { + var performanceCounter = 0; + do { + var idx = Math.round(this.normal({ mean: options.mean, dev: options.dev })); + if (idx < options.pool.length && idx >= 0) { + return options.pool[idx]; + } else { + performanceCounter++; + } + } while(performanceCounter < 100); - return p[0] - } + throw new RangeError("Chance: Your pool is too small for the given mean and standard deviation. Please adjust."); + }; - async matchAll (request = undefined, options = {}) { - webidl.brandCheck(this, Cache) + Chance.prototype.radio = function (options) { + // Initial Letter (Typically Designated by Side of Mississippi River) + options = initOptions(options, {side : "?"}); + var fl = ""; + switch (options.side.toLowerCase()) { + case "east": + case "e": + fl = "W"; + break; + case "west": + case "w": + fl = "K"; + break; + default: + fl = this.character({pool: "KW"}); + break; + } - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) + return fl + this.character({alpha: true, casing: "upper"}) + + this.character({alpha: true, casing: "upper"}) + + this.character({alpha: true, casing: "upper"}); + }; - // 1. - let r = null + // Set the data as key and data or the data map + Chance.prototype.set = function (name, values) { + if (typeof name === "string") { + data[name] = values; + } else { + data = copyObject(name, data); + } + }; - // 2. - if (request !== undefined) { - if (request instanceof Request) { - // 2.1.1 - r = request[kState] + Chance.prototype.tv = function (options) { + return this.radio(options); + }; - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] + // ID number for Brazil companies + Chance.prototype.cnpj = function () { + var n = this.n(this.natural, 8, { max: 9 }); + var d1 = 2+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; + d1 = 11 - (d1 % 11); + if (d1>=10){ + d1 = 0; } - } else if (typeof request === 'string') { - // 2.2.1 - r = new Request(request)[kState] - } - } + var d2 = d1*2+3+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; + d2 = 11 - (d2 % 11); + if (d2>=10){ + d2 = 0; + } + return ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/0001-'+d1+d2; + }; - // 5. - // 5.1 - const responses = [] + Chance.prototype.emotion = function () { + return this.pick(this.get("emotions")); + }; - // 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) + // -- End Miscellaneous -- + + Chance.prototype.mersenne_twister = function (seed) { + return new MersenneTwister(seed); + }; - // 5.3.2 - for (const requestResponse of requestResponses) { - responses.push(requestResponse[1]) - } - } + Chance.prototype.blueimp_md5 = function () { + return new BlueImpMD5(); + }; - // 5.4 - // We don't implement CORs so we don't need to loop over the responses, yay! + // Mersenne Twister from https://gist.github.com/banksean/300494 + /* + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. - // 5.5.1 - const responseList = [] + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). - // 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' + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. - responseList.push(responseObject) - } + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: - // 6. - return Object.freeze(responseList) - } + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. - async add (request) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) + 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. - request = webidl.converters.RequestInfo(request) + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. - // 1. - const requests = [request] + 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. - // 2. - const responseArrayPromise = this.addAll(requests) - // 3. - return await responseArrayPromise - } + Any feedback is very welcome. + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) + */ + var MersenneTwister = function (seed) { + if (seed === undefined) { + // kept random number same size as time used previously to ensure no unexpected results downstream + seed = Math.floor(Math.random()*Math.pow(10,13)); + } + /* Period parameters */ + this.N = 624; + this.M = 397; + this.MATRIX_A = 0x9908b0df; /* constant vector a */ + this.UPPER_MASK = 0x80000000; /* most significant w-r bits */ + this.LOWER_MASK = 0x7fffffff; /* least significant r bits */ - async addAll (requests) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) + this.mt = new Array(this.N); /* the array for the state vector */ + this.mti = this.N + 1; /* mti==N + 1 means mt[N] is not initialized */ - requests = webidl.converters['sequence'](requests) + this.init_genrand(seed); + }; - // 1. - const responsePromises = [] + /* initializes mt[N] with a seed */ + MersenneTwister.prototype.init_genrand = function (s) { + this.mt[0] = s >>> 0; + for (this.mti = 1; this.mti < this.N; this.mti++) { + s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30); + this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti; + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + /* In the previous versions, MSBs of the seed affect */ + /* only MSBs of the array mt[]. */ + /* 2002/01/09 modified by Makoto Matsumoto */ + this.mt[this.mti] >>>= 0; + /* for >32 bit machines */ + } + }; - // 2. - const requestList = [] + /* initialize by an array with array-length */ + /* init_key is the array for initializing keys */ + /* key_length is its length */ + /* slight change for C++, 2004/2/26 */ + MersenneTwister.prototype.init_by_array = function (init_key, key_length) { + var i = 1, j = 0, k, s; + this.init_genrand(19650218); + k = (this.N > key_length ? this.N : key_length); + for (; k; k--) { + s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); + this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525))) + init_key[j] + j; /* non linear */ + this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ + i++; + j++; + if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } + if (j >= key_length) { j = 0; } + } + for (k = this.N - 1; k; k--) { + s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); + this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i; /* non linear */ + this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ + i++; + if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } + } - // 3. - for (const request of requests) { - if (typeof request === 'string') { - continue - } + this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ + }; - // 3.1 - const r = request[kState] + /* generates a random number on [0,0xffffffff]-interval */ + MersenneTwister.prototype.genrand_int32 = function () { + var y; + var mag01 = new Array(0x0, this.MATRIX_A); + /* mag01[x] = x * MATRIX_A for x=0,1 */ - // 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.' - }) - } - } + if (this.mti >= this.N) { /* generate N words at one time */ + var kk; - // 4. - /** @type {ReturnType[]} */ - const fetchControllers = [] + if (this.mti === this.N + 1) { /* if init_genrand() has not been called, */ + this.init_genrand(5489); /* a default initial seed is used */ + } + for (kk = 0; kk < this.N - this.M; kk++) { + y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); + this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 0x1]; + } + for (;kk < this.N - 1; kk++) { + y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); + this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 0x1]; + } + y = (this.mt[this.N - 1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK); + this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; - // 5. - for (const request of requests) { - // 5.1 - const r = new Request(request)[kState] + this.mti = 0; + } - // 5.2 - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: 'Cache.addAll', - message: 'Expected http/s scheme.' - }) - } + y = this.mt[this.mti++]; - // 5.4 - r.initiator = 'fetch' - r.destination = 'subresource' + /* Tempering */ + y ^= (y >>> 11); + y ^= (y << 7) & 0x9d2c5680; + y ^= (y << 15) & 0xefc60000; + y ^= (y >>> 18); - // 5.5 - requestList.push(r) + return y >>> 0; + }; - // 5.6 - const responsePromise = createDeferredPromise() + /* generates a random number on [0,0x7fffffff]-interval */ + MersenneTwister.prototype.genrand_int31 = function () { + return (this.genrand_int32() >>> 1); + }; - // 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')) + /* generates a random number on [0,1]-real-interval */ + MersenneTwister.prototype.genrand_real1 = function () { + return this.genrand_int32() * (1.0 / 4294967295.0); + /* divided by 2^32-1 */ + }; - // 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' - })) + /* generates a random number on [0,1)-real-interval */ + MersenneTwister.prototype.random = function () { + return this.genrand_int32() * (1.0 / 4294967296.0); + /* divided by 2^32 */ + }; - for (const controller of fetchControllers) { - controller.abort() - } + /* generates a random number on (0,1)-real-interval */ + MersenneTwister.prototype.genrand_real3 = function () { + return (this.genrand_int32() + 0.5) * (1.0 / 4294967296.0); + /* divided by 2^32 */ + }; - return - } - } - } - }, - processResponseEndOfBody (response) { - // 1. - if (response.aborted) { - responsePromise.reject(new DOMException('aborted', 'AbortError')) - return - } + /* generates a random number on [0,1) with 53-bit resolution*/ + MersenneTwister.prototype.genrand_res53 = function () { + var a = this.genrand_int32()>>>5, b = this.genrand_int32()>>>6; + return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); + }; - // 2. - responsePromise.resolve(response) - } - })) + // BlueImp MD5 hashing algorithm from https://github.com/blueimp/JavaScript-MD5 + var BlueImpMD5 = function () {}; - // 5.8 - responsePromises.push(responsePromise.promise) - } + BlueImpMD5.prototype.VERSION = '1.0.1'; - // 6. - const p = Promise.all(responsePromises) + /* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + BlueImpMD5.prototype.safe_add = function safe_add(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF), + msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); + }; - // 7. - const responses = await p + /* + * Bitwise rotate a 32-bit number to the left. + */ + BlueImpMD5.prototype.bit_roll = function (num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); + }; - // 7.1 - const operations = [] + /* + * These functions implement the five basic operations the algorithm uses. + */ + BlueImpMD5.prototype.md5_cmn = function (q, a, b, x, s, t) { + return this.safe_add(this.bit_roll(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s), b); + }; + BlueImpMD5.prototype.md5_ff = function (a, b, c, d, x, s, t) { + return this.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); + }; + BlueImpMD5.prototype.md5_gg = function (a, b, c, d, x, s, t) { + return this.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); + }; + BlueImpMD5.prototype.md5_hh = function (a, b, c, d, x, s, t) { + return this.md5_cmn(b ^ c ^ d, a, b, x, s, t); + }; + BlueImpMD5.prototype.md5_ii = function (a, b, c, d, x, s, t) { + return this.md5_cmn(c ^ (b | (~d)), a, b, x, s, t); + }; - // 7.2 - let index = 0 + /* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + BlueImpMD5.prototype.binl_md5 = function (x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << (len % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; - // 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 - } + var i, olda, oldb, oldc, oldd, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; - operations.push(operation) // 7.3.5 + for (i = 0; i < x.length; i += 16) { + olda = a; + oldb = b; + oldc = c; + oldd = d; - index++ // 7.3.6 - } + a = this.md5_ff(a, b, c, d, x[i], 7, -680876936); + d = this.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); + c = this.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); + b = this.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = this.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); + d = this.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = this.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = this.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); + a = this.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = this.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = this.md5_ff(c, d, a, b, x[i + 10], 17, -42063); + b = this.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = this.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = this.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); + c = this.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = this.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); - // 7.5 - const cacheJobPromise = createDeferredPromise() + a = this.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); + d = this.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = this.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); + b = this.md5_gg(b, c, d, a, x[i], 20, -373897302); + a = this.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); + d = this.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); + c = this.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); + b = this.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); + a = this.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); + d = this.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = this.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); + b = this.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = this.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = this.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); + c = this.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = this.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); - // 7.6.1 - let errorData = null + a = this.md5_hh(a, b, c, d, x[i + 5], 4, -378558); + d = this.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = this.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = this.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); + a = this.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = this.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = this.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); + b = this.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = this.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); + d = this.md5_hh(d, a, b, c, x[i], 11, -358537222); + c = this.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); + b = this.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); + a = this.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); + d = this.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); + c = this.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); + b = this.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); - // 7.6.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } + a = this.md5_ii(a, b, c, d, x[i], 6, -198630844); + d = this.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = this.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = this.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); + a = this.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = this.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = this.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); + b = this.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = this.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = this.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); + c = this.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = this.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = this.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); + d = this.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = this.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); + b = this.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); - // 7.6.3 - queueMicrotask(() => { - // 7.6.3.1 - if (errorData === null) { - cacheJobPromise.resolve(undefined) - } else { - // 7.6.3.2 - cacheJobPromise.reject(errorData) - } - }) + a = this.safe_add(a, olda); + b = this.safe_add(b, oldb); + c = this.safe_add(c, oldc); + d = this.safe_add(d, oldd); + } + return [a, b, c, d]; + }; - // 7.7 - return cacheJobPromise.promise - } + /* + * Convert an array of little-endian words to a string + */ + BlueImpMD5.prototype.binl2rstr = function (input) { + var i, + output = ''; + for (i = 0; i < input.length * 32; i += 8) { + output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); + } + return output; + }; - async put (request, response) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) + /* + * Convert a raw string to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + BlueImpMD5.prototype.rstr2binl = function (input) { + var i, + output = []; + output[(input.length >> 2) - 1] = undefined; + for (i = 0; i < output.length; i += 1) { + output[i] = 0; + } + for (i = 0; i < input.length * 8; i += 8) { + output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); + } + return output; + }; - request = webidl.converters.RequestInfo(request) - response = webidl.converters.Response(response) + /* + * Calculate the MD5 of a raw string + */ + BlueImpMD5.prototype.rstr_md5 = function (s) { + return this.binl2rstr(this.binl_md5(this.rstr2binl(s), s.length * 8)); + }; - // 1. - let innerRequest = null + /* + * Calculate the HMAC-MD5, of a key and some data (raw strings) + */ + BlueImpMD5.prototype.rstr_hmac_md5 = function (key, data) { + var i, + bkey = this.rstr2binl(key), + ipad = [], + opad = [], + hash; + ipad[15] = opad[15] = undefined; + if (bkey.length > 16) { + bkey = this.binl_md5(bkey, key.length * 8); + } + for (i = 0; i < 16; i += 1) { + ipad[i] = bkey[i] ^ 0x36363636; + opad[i] = bkey[i] ^ 0x5C5C5C5C; + } + hash = this.binl_md5(ipad.concat(this.rstr2binl(data)), 512 + data.length * 8); + return this.binl2rstr(this.binl_md5(opad.concat(hash), 512 + 128)); + }; + + /* + * Convert a raw string to a hex string + */ + BlueImpMD5.prototype.rstr2hex = function (input) { + var hex_tab = '0123456789abcdef', + output = '', + x, + i; + for (i = 0; i < input.length; i += 1) { + x = input.charCodeAt(i); + output += hex_tab.charAt((x >>> 4) & 0x0F) + + hex_tab.charAt(x & 0x0F); + } + return output; + }; + + /* + * Encode a string as utf-8 + */ + BlueImpMD5.prototype.str2rstr_utf8 = function (input) { + return unescape(encodeURIComponent(input)); + }; - // 2. - if (request instanceof Request) { - innerRequest = request[kState] - } else { // 3. - innerRequest = new Request(request)[kState] - } + /* + * Take string arguments and return either raw or hex encoded strings + */ + BlueImpMD5.prototype.raw_md5 = function (s) { + return this.rstr_md5(this.str2rstr_utf8(s)); + }; + BlueImpMD5.prototype.hex_md5 = function (s) { + return this.rstr2hex(this.raw_md5(s)); + }; + BlueImpMD5.prototype.raw_hmac_md5 = function (k, d) { + return this.rstr_hmac_md5(this.str2rstr_utf8(k), this.str2rstr_utf8(d)); + }; + BlueImpMD5.prototype.hex_hmac_md5 = function (k, d) { + return this.rstr2hex(this.raw_hmac_md5(k, d)); + }; - // 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' - }) - } + BlueImpMD5.prototype.md5 = function (string, key, raw) { + if (!key) { + if (!raw) { + return this.hex_md5(string); + } - // 5. - const innerResponse = response[kState] + return this.raw_md5(string); + } - // 6. - if (innerResponse.status === 206) { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got 206 status' - }) - } + if (!raw) { + return this.hex_hmac_md5(key, string); + } - // 7. - if (innerResponse.headersList.contains('vary')) { - // 7.1. - const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) + return this.raw_hmac_md5(key, string); + }; - // 7.2. - for (const fieldValue of fieldValues) { - // 7.2.1 - if (fieldValue === '*') { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got * vary field value' - }) + // CommonJS module + if (true) { + if ( true && module.exports) { + exports = module.exports = Chance; } - } + exports.Chance = Chance; } - // 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' - }) + // Register as an anonymous AMD module + if (typeof define === 'function' && define.amd) { + define([], function () { + return Chance; + }); } - // 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) + // if there is a importsScrips object define chance for worker + // allows worker to use full Chance functionality with seed + if (typeof importScripts !== 'undefined') { + chance = new Chance(); + self.Chance = Chance; } - // 12. - /** @type {CacheBatchOperation[]} */ - const operations = [] - - // 13. - /** @type {CacheBatchOperation} */ - const operation = { - type: 'put', // 14. - request: innerRequest, // 15. - response: clonedResponse // 16. + // If there is a window object, that at least has a document property, + // instantiate and define chance on the window + if (typeof window === "object" && typeof window.document === "object") { + window.Chance = Chance; + window.chance = new Chance(); } +})(); - // 17. - operations.push(operation) - - // 19. - const bytes = await bodyReadPromise.promise - if (clonedResponse.body != null) { - clonedResponse.body.source = bytes - } +/***/ }), - // 19.1 - const cacheJobPromise = createDeferredPromise() +/***/ 3733: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 19.2.1 - let errorData = null +"use strict"; - // 19.2.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } +const cliBoxes = __nccwpck_require__(94); - // 19.2.3 - queueMicrotask(() => { - // 19.2.3.1 - if (errorData === null) { - cacheJobPromise.resolve() - } else { // 19.2.3.2 - cacheJobPromise.reject(errorData) - } - }) +module.exports = cliBoxes; +// TODO: Remove this for the next major release +module.exports["default"] = cliBoxes; - 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) +/***/ 8932: +/***/ ((__unused_webpack_module, exports) => { - /** - * @type {Request} - */ - let r = null +"use strict"; - if (request instanceof Request) { - r = request[kState] - if (r.method !== 'GET' && !options.ignoreMethod) { - return false - } - } else { - assert(typeof request === 'string') +Object.defineProperty(exports, "__esModule", ({ value: true })); - r = new Request(request)[kState] - } +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - /** @type {CacheBatchOperation[]} */ - const operations = [] + /* istanbul ignore next */ - /** @type {CacheBatchOperation} */ - const operation = { - type: 'delete', - request: r, - options + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } - operations.push(operation) - - const cacheJobPromise = createDeferredPromise() + this.name = 'Deprecation'; + } - let errorData = null - let requestResponses +} - try { - requestResponses = this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } +exports.Deprecation = Deprecation; - 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) +/***/ 2437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) +const fs = __nccwpck_require__(7147) +const path = __nccwpck_require__(1017) +const os = __nccwpck_require__(2037) +const crypto = __nccwpck_require__(6113) +const packageJson = __nccwpck_require__(9968) - // 1. - let r = null +const version = packageJson.version - // 2. - if (request !== undefined) { - // 2.1 - if (request instanceof Request) { - // 2.1.1 - r = request[kState] +const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] - } - } else if (typeof request === 'string') { // 2.2 - r = new Request(request)[kState] - } - } +// Parse src into an Object +function parse (src) { + const obj = {} - // 4. - const promise = createDeferredPromise() + // Convert buffer to string + let lines = src.toString() - // 5. - // 5.1 - const requests = [] + // Convert line breaks to same format + lines = lines.replace(/\r\n?/mg, '\n') - // 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) + let match + while ((match = LINE.exec(lines)) != null) { + const key = match[1] - // 5.3.2 - for (const requestResponse of requestResponses) { - // 5.3.2.1 - requests.push(requestResponse[0]) - } - } + // Default undefined or null to empty string + let value = (match[2] || '') - // 5.4 - queueMicrotask(() => { - // 5.4.1 - const requestList = [] + // Remove whitespace + value = value.trim() - // 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 + // Check if double quoted + const maybeQuote = value[0] - // 5.4.2.1 - requestList.push(requestObject) - } + // Remove surrounding quotes + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2') - // 5.4.3 - promise.resolve(Object.freeze(requestList)) - }) + // Expand newlines if double quoted + if (maybeQuote === '"') { + value = value.replace(/\\n/g, '\n') + value = value.replace(/\\r/g, '\r') + } - return promise.promise + // Add to object + obj[key] = value } - /** - * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm - * @param {CacheBatchOperation[]} operations - * @returns {requestResponseList} - */ - #batchCacheOperations (operations) { - // 1. - const cache = this.#relevantRequestResponseList + return obj +} - // 2. - const backupCache = [...cache] +function _parseVault (options) { + options = options || {} - // 3. - const addedItems = [] + const vaultPath = _vaultPath(options) + options.path = vaultPath // parse .env.vault + const result = DotenvModule.configDotenv(options) + if (!result.parsed) { + const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`) + err.code = 'MISSING_DATA' + throw err + } - // 4.1 - const resultList = [] + // handle scenario for comma separated keys - for use with key rotation + // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod" + const keys = _dotenvKey(options).split(',') + const length = keys.length + let decrypted + for (let i = 0; i < length; i++) { 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 [] - } + // Get full key + const key = keys[i].trim() - // 4.2.5.2 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) + // Get instructions for decrypt + const attrs = _instructions(result, key) - // 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' - }) - } + // Decrypt + decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key) - // 4.2.6.2 - const r = operation.request + break + } catch (error) { + // last key + if (i + 1 >= length) { + throw error + } + // try next key + } + } - // 4.2.6.3 - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'expected http or https scheme' - }) - } + // Parse decrypted .env string + return DotenvModule.parse(decrypted) +} - // 4.2.6.4 - if (r.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'not get method' - }) - } +function _warn (message) { + console.log(`[dotenv@${version}][WARN] ${message}`) +} - // 4.2.6.5 - if (operation.options != null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'options must not be defined' - }) - } +function _debug (message) { + console.log(`[dotenv@${version}][DEBUG] ${message}`) +} - // 4.2.6.6 - requestResponses = this.#queryCache(operation.request) +function _log (message) { + console.log(`[dotenv@${version}] ${message}`) +} - // 4.2.6.7 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) +function _dotenvKey (options) { + // prioritize developer directly setting options.DOTENV_KEY + if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { + return options.DOTENV_KEY + } - // 4.2.6.7.1 - cache.splice(idx, 1) - } + // secondary infra already contains a DOTENV_KEY environment variable + if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { + return process.env.DOTENV_KEY + } - // 4.2.6.8 - cache.push([operation.request, operation.response]) + // fallback to empty string + return '' +} - // 4.2.6.10 - addedItems.push([operation.request, operation.response]) - } +function _instructions (result, dotenvKey) { + // Parse DOTENV_KEY. Format is a URI + let uri + try { + uri = new URL(dotenvKey) + } catch (error) { + if (error.code === 'ERR_INVALID_URL') { + const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development') + err.code = 'INVALID_DOTENV_KEY' + throw err + } - // 4.2.7 - resultList.push([operation.request, operation.response]) - } + throw error + } - // 4.3 - return resultList - } catch (e) { // 5. - // 5.1 - this.#relevantRequestResponseList.length = 0 + // Get decrypt key + const key = uri.password + if (!key) { + const err = new Error('INVALID_DOTENV_KEY: Missing key part') + err.code = 'INVALID_DOTENV_KEY' + throw err + } - // 5.2 - this.#relevantRequestResponseList = backupCache + // Get environment + const environment = uri.searchParams.get('environment') + if (!environment) { + const err = new Error('INVALID_DOTENV_KEY: Missing environment part') + err.code = 'INVALID_DOTENV_KEY' + throw err + } - // 5.3 - throw e - } + // Get ciphertext payload + const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}` + const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION + if (!ciphertext) { + const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`) + err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT' + throw err } - /** - * @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 = [] + return { ciphertext, key } +} - const storage = targetStorage ?? this.#relevantRequestResponseList +function _vaultPath (options) { + let possibleVaultPath = null - for (const requestResponse of storage) { - const [cachedRequest, cachedResponse] = requestResponse - if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { - resultList.push(requestResponse) + if (options && options.path && options.path.length > 0) { + if (Array.isArray(options.path)) { + for (const filepath of options.path) { + if (fs.existsSync(filepath)) { + possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault` + } } + } else { + possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault` } + } else { + possibleVaultPath = path.resolve(process.cwd(), '.env.vault') + } - return resultList + if (fs.existsSync(possibleVaultPath)) { + return possibleVaultPath } - /** - * @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 - // } + return null +} - const queryURL = new URL(requestQuery.url) +function _resolveHome (envPath) { + return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath +} - const cachedURL = new URL(request.url) +function _configVault (options) { + const debug = Boolean(options && options.debug) + const quiet = options && 'quiet' in options ? options.quiet : true - if (options?.ignoreSearch) { - cachedURL.search = '' + if (debug || !quiet) { + _log('Loading env from encrypted .env.vault') + } - queryURL.search = '' - } + const parsed = DotenvModule._parseVault(options) - if (!urlEquals(queryURL, cachedURL, true)) { - return false - } + let processEnv = process.env + if (options && options.processEnv != null) { + processEnv = options.processEnv + } - if ( - response == null || - options?.ignoreVary || - !response.headersList.contains('vary') - ) { - return true - } + DotenvModule.populate(processEnv, parsed, options) - const fieldValues = getFieldValues(response.headersList.get('vary')) + return { parsed } +} - for (const fieldValue of fieldValues) { - if (fieldValue === '*') { - return false - } +function configDotenv (options) { + const dotenvPath = path.resolve(process.cwd(), '.env') + let encoding = 'utf8' + const debug = Boolean(options && options.debug) + const quiet = options && 'quiet' in options ? options.quiet : true - const requestValue = request.headersList.get(fieldValue) - const queryValue = requestQuery.headersList.get(fieldValue) + if (options && options.encoding) { + encoding = options.encoding + } else { + if (debug) { + _debug('No encoding is specified. UTF-8 is used by default') + } + } - // 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 + let optionPaths = [dotenvPath] // default, look for .env + if (options && options.path) { + if (!Array.isArray(options.path)) { + optionPaths = [_resolveHome(options.path)] + } else { + optionPaths = [] // reset default + for (const filepath of options.path) { + optionPaths.push(_resolveHome(filepath)) } } - - 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 -}) + // Build the parsed data in a temporary object (because we need to return it). Once we have the final + // parsed data, we will combine it with process.env (or options.processEnv if provided). + let lastError + const parsedAll = {} + for (const path of optionPaths) { + try { + // Specifying an encoding returns a string instead of a buffer + const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding })) -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 + DotenvModule.populate(parsedAll, parsed, options) + } catch (e) { + if (debug) { + _debug(`Failed to load ${path} ${e.message}`) + } + lastError = e + } } -] - -webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) -webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ - ...cacheQueryOptionConverters, - { - key: 'cacheName', - converter: webidl.converters.DOMString + let processEnv = process.env + if (options && options.processEnv != null) { + processEnv = options.processEnv } -]) -webidl.converters.Response = webidl.interfaceConverter(Response) + DotenvModule.populate(processEnv, parsedAll, options) -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.RequestInfo -) + if (debug || !quiet) { + const keysCount = Object.keys(parsedAll).length + const shortPaths = [] + for (const filePath of optionPaths) { + try { + const relative = path.relative(process.cwd(), filePath) + shortPaths.push(relative) + } catch (e) { + if (debug) { + _debug(`Failed to load ${filePath} ${e.message}`) + } + lastError = e + } + } -module.exports = { - Cache + _log(`injecting env (${keysCount}) from ${shortPaths.join(',')}`) + } + + if (lastError) { + return { parsed: parsedAll, error: lastError } + } else { + return { parsed: parsedAll } + } } +// Populates process.env from .env file +function config (options) { + // fallback to original dotenv if DOTENV_KEY is not set + if (_dotenvKey(options).length === 0) { + return DotenvModule.configDotenv(options) + } -/***/ }), + const vaultPath = _vaultPath(options) -/***/ 37907: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // dotenvKey exists but .env.vault file does not exist + if (!vaultPath) { + _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`) -"use strict"; + return DotenvModule.configDotenv(options) + } + return DotenvModule._configVault(options) +} -const { kConstruct } = __nccwpck_require__(29174) -const { Cache } = __nccwpck_require__(66101) -const { webidl } = __nccwpck_require__(21744) -const { kEnumerableProperty } = __nccwpck_require__(83983) +function decrypt (encrypted, keyStr) { + const key = Buffer.from(keyStr.slice(-64), 'hex') + let ciphertext = Buffer.from(encrypted, 'base64') -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' }) +const DotenvModule = { + configDotenv, + _configVault, + _parseVault, + config, + decrypt, + parse, + populate +} - cacheName = webidl.converters.DOMString(cacheName) +module.exports.configDotenv = DotenvModule.configDotenv +module.exports._configVault = DotenvModule._configVault +module.exports._parseVault = DotenvModule._parseVault +module.exports.config = DotenvModule.config +module.exports.decrypt = DotenvModule.decrypt +module.exports.parse = DotenvModule.parse +module.exports.populate = DotenvModule.populate - // 2.1 - if (this.#caches.has(cacheName)) { - // await caches.open('v1') !== await caches.open('v1') +module.exports = DotenvModule - // 2.1.1 - const cache = this.#caches.get(cacheName) - // 2.1.1.1 - return new Cache(kConstruct, cache) - } +/***/ }), - // 2.2 - const cache = [] +/***/ 8212: +/***/ ((module) => { - // 2.3 - this.#caches.set(cacheName, cache) +module.exports = () => { + // https://mths.be/emoji + return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; +}; - // 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) +/***/ 4882: +/***/ ((module) => { - return this.#caches.delete(cacheName) - } +"use strict"; +/* eslint-disable yoda */ - /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys - * @returns {string[]} - */ - async keys () { - webidl.brandCheck(this, CacheStorage) - // 2.1 - const keys = this.#caches.keys() +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } - // 2.2 - return [...keys] - } -} + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } -Object.defineProperties(CacheStorage.prototype, { - [Symbol.toStringTag]: { - value: 'CacheStorage', - configurable: true - }, - match: kEnumerableProperty, - has: kEnumerableProperty, - open: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty -}) + return false; +}; -module.exports = { - CacheStorage -} +module.exports = isFullwidthCodePoint; +module.exports["default"] = isFullwidthCodePoint; /***/ }), -/***/ 29174: +/***/ 1917: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = { - kConstruct: (__nccwpck_require__(72785).kConstruct) + +var loader = __nccwpck_require__(1161); +var dumper = __nccwpck_require__(8866); + + +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__(1082); +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(8562); +module.exports.JSON_SCHEMA = __nccwpck_require__(1035); +module.exports.CORE_SCHEMA = __nccwpck_require__(2011); +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(8759); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.dump = dumper.dump; +module.exports.YAMLException = __nccwpck_require__(8179); + +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: __nccwpck_require__(7900), + float: __nccwpck_require__(2705), + map: __nccwpck_require__(6150), + null: __nccwpck_require__(721), + pairs: __nccwpck_require__(6860), + set: __nccwpck_require__(9548), + timestamp: __nccwpck_require__(9212), + bool: __nccwpck_require__(4993), + int: __nccwpck_require__(1615), + merge: __nccwpck_require__(6104), + omap: __nccwpck_require__(9046), + seq: __nccwpck_require__(7283), + str: __nccwpck_require__(3619) +}; + +// 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'); + + /***/ }), -/***/ 82396: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 6829: +/***/ ((module) => { "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) +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} - const serializedB = URLSerializer(B, excludeFragment) - return serializedA === serializedB +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); } -/** - * @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 = [] +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; +} - for (let value of header.split(',')) { - value = value.trim() - if (!value.length) { - continue - } else if (!isValidHeaderName(value)) { - continue - } +function repeat(string, count) { + var result = '', cycle; - values.push(value) + for (cycle = 0; cycle < count; cycle += 1) { + result += string; } - return values + return result; } -module.exports = { - urlEquals, - fieldValues + +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; + + /***/ }), -/***/ 33598: +/***/ 8866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// @ts-check +/*eslint-disable no-use-before-define*/ -/* global WebAssembly */ +var common = __nccwpck_require__(6829); +var YAMLException = __nccwpck_require__(8179); +var DEFAULT_SCHEMA = __nccwpck_require__(8759); -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) +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; -/** @type {import('http2')} */ -let http2 -try { - http2 = __nccwpck_require__(85158) -} catch { - // @ts-ignore - http2 = { constants: {} } -} +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; /* } */ -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 +var ESCAPE_SEQUENCES = {}; -// Experimental -let h2ExperimentalWarned = false +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'; -const FastBuffer = Buffer[Symbol.species] +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; -const kClosedResolve = Symbol('kClosedResolve') +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; -const channels = {} +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; -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 } -} + if (map === null) return {}; -/** - * @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() + result = {}; + keys = Object.keys(map); - if (keepAlive !== undefined) { - throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') - } + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); - if (socketTimeout !== undefined) { - throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); } + type = schema.compiledTypeMap['fallback'][tag]; - if (requestTimeout !== undefined) { - throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; } - if (idleTimeout !== undefined) { - throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') - } + result[tag] = style; + } - if (maxKeepAliveTimeout !== undefined) { - throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') - } + return result; +} - if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { - throw new InvalidArgumentError('invalid maxHeaderSize') - } +function encodeHex(character) { + var string, handle, length; - if (socketPath != null && typeof socketPath !== 'string') { - throw new InvalidArgumentError('invalid socketPath') - } + string = character.toString(16).toUpperCase(); - if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { - throw new InvalidArgumentError('invalid connectTimeout') - } + 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'); + } - if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveTimeout') - } + return '\\' + handle + common.repeat('0', length - string.length) + string; +} - if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveMaxTimeout') - } - if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { - throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') - } +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; - if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') - } +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; - if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') - } + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } + this.tag = null; + this.result = ''; - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } + this.duplicates = []; + this.usedDuplicates = null; +} - if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { - throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') - } +// 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; - if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { - throw new InvalidArgumentError('localAddress must be valid string IP address') + 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 (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { - throw new InvalidArgumentError('maxResponseSize must be a positive number') - } + if (line.length && line !== '\n') result += ind; - if ( - autoSelectFamilyAttemptTimeout != null && - (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) - ) { - throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') - } + result += line; + } - // h2 - if (allowH2 != null && typeof allowH2 !== 'boolean') { - throw new InvalidArgumentError('allowH2 must be a valid boolean value') - } + return result; +} - if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { - throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') - } +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) - } +function testImplicitResolving(state, str) { + var index, length, type; - 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' + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; - // 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}` : ''}` + if (type.resolve(str)) { + return true; + } + } - // 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). + return false; +} - this[kQueue] = [] - this[kRunningIdx] = 0 - this[kPendingIdx] = 0 - } +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} - get pipelining () { - return this[kPipelining] - } +// 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); +} - set pipelining (value) { - this[kPipelining] = value - resume(this, true) - } +// [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; +} - get [kPending] () { - return this[kQueue].length - this[kPendingIdx] - } +// [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 ':[^ ]' +} - get [kRunning] () { - return this[kPendingIdx] - this[kRunningIdx] - } +// 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; +} - get [kSize] () { - return this[kQueue].length - this[kRunningIdx] - } +// 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; +} - get [kConnected] () { - return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed +// 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; +} - get [kBusy] () { - const socket = this[kSocket] - return ( - (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || - (this[kSize] >= (this[kPipelining] || 1)) || - this[kPending] > 0 - ) - } +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} - /* istanbul ignore: only used for test */ - [kConnect] (cb) { - connect(this) - this.once('connect', cb) - } +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; - [kDispatch] (opts, handler) { - const origin = opts.origin || this[kUrl].origin +// 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) { - const request = this[kHTTPConnVersion] === 'h2' - ? Request[kHTTP2BuildRequest](origin, opts, handler) - : Request[kHTTP1BuildRequest](origin, opts, handler) + 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)); - 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 (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; } - - if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { - this[kNeedDrain] = 2 + } 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; } - - return this[kNeedDrain] < 2 + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); } - - 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 - } - }) + // 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; +} - 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) +// 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 + "'"); } + } - const callback = () => { - if (this[kClosedResolve]) { - // TODO (fix): Should we error here with ClientDestroyedError? - this[kClosedResolve]() - this[kClosedResolve] = null - } - resolve() - } + 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); - if (this[kHTTP2Session] != null) { - util.destroy(this[kHTTP2Session], err) - this[kHTTP2Session] = null - this[kHTTP2SessionState] = null - } + // 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); + } - if (!this[kSocket]) { - queueMicrotask(callback) - } else { - util.destroy(this[kSocket].on('close', callback), err) - } + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { - resume(this) - }) - } + 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'); + } + }()); } -function onHttp2SessionError (err) { - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - - this[kSocket][kError] = err - - onError(this[kClient], err) -} +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; -function onHttp2FrameError (type, code, id) { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + // 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 ? '' : '-'); - if (id === 0) { - this[kSocket][kError] = err - onError(this[kClient], err) - } + return indentIndicator + chomp + '\n'; } -function onHttp2SessionEnd () { - util.destroy(this, new SocketError('other side closed')) - util.destroy(this[kSocket], new SocketError('other side closed')) +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } -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) +// 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; - // 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 + // 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; - errorRequest(client, request, err) + // 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; } - client[kPendingIdx] = client[kRunningIdx] - - assert(client[kRunning] === 0) - - client.emit('disconnect', - client[kUrl], - [client], - err - ) - - resume(client) + return result; } -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 +// 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; - let mod - try { - mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(95627), 'base64')) - } catch (e) { - /* istanbul ignore next */ + // 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 = ''; - // 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')) + // 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; } - 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 - } + // 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); + } - /* eslint-enable camelcase */ - } - }) + return result.slice(1); // drop extra \n joiner } -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 +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; - this.keepAlive = '' - this.contentLength = '' - this.connection = '' - this.maxResponseSize = client[kMaxResponseSize] - } + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; - 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() - } + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); } } - resume () { - if (this.socket.destroyed || !this.paused) { - return - } + return result; +} - assert(this.ptr != null) - assert(currentParser == null) +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; - this.llhttp.llhttp_resume(this.ptr) + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; - assert(this.timeoutType === TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } + if (state.replacer) { + value = state.replacer.call(object, String(index), value); } - this.paused = false - this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. - this.readMore() - } + // 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))) { - readMore () { - while (!this.paused && this.ptr) { - const chunk = this.socket.read() - if (chunk === null) { - break - } - this.execute(chunk) + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; } } - execute (data) { - assert(this.ptr != null) - assert(currentParser == null) - assert(!this.paused) + state.tag = _tag; + state.dump = '[' + _result + ']'; +} - const { socket, llhttp } = this +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; - if (data.length > currentBufferSize) { - if (currentBufferPtr) { - llhttp.free(currentBufferPtr) - } - currentBufferSize = Math.ceil(data.length / 4096) * 4096 - currentBufferPtr = llhttp.malloc(currentBufferSize) - } + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; - new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } - // 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 + // 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))) { - 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 + if (!compact || _result !== '') { + _result += generateNextLine(state, level); } - 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)) + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; } - } catch (err) { - util.destroy(socket, err) + + _result += state.dump; } } - destroy () { - assert(this.ptr != null) - assert(currentParser == null) + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} - this.llhttp.llhttp_free(this.ptr) - this.ptr = null +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; - timers.clearTimeout(this.timeout) - this.timeout = null - this.timeoutValue = null - this.timeoutType = null + for (index = 0, length = objectKeyList.length; index < length; index += 1) { - this.paused = false - } + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; - onStatus (buf) { - this.statusText = buf.toString() - } + if (state.condenseFlow) pairBuffer += '"'; - onMessageBegin () { - const { socket, client } = this + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); } - const request = client[kQueue][client[kRunningIdx]] - if (!request) { - return -1 + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; } - } - onHeaderField (buf) { - const len = this.headers.length + if (state.dump.length > 1024) pairBuffer += '? '; - if ((len & 1) === 0) { - this.headers.push(buf) - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. } - this.trackHeader(buf.length) + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; } - onHeaderValue (buf) { - let len = this.headers.length + state.tag = _tag; + state.dump = '{' + _result + '}'; +} - if ((len & 1) === 1) { - this.headers.push(buf) - len += 1 - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) - } +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; - 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() + // 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); } - this.trackHeader(buf.length) - } + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; - trackHeader (len) { - this.headersSize += len - if (this.headersSize >= this.headersMaxSize) { - util.destroy(this.socket, new HeadersOverflowError()) + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); } - } - onUpgrade (head) { - const { upgrade, client, socket, headers, statusCode } = this + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } - assert(upgrade) + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); - const request = client[kQueue][client[kRunningIdx]] - assert(request) + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } - assert(!socket.destroyed) - assert(socket === client[kSocket]) - assert(!this.paused) - assert(request.upgrade || request.method === 'CONNECT') + pairBuffer += state.dump; - this.statusCode = null - this.statusText = '' - this.shouldKeepAlive = null + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } - socket.unshift(head) + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } - socket[kParser].destroy() - socket[kParser] = null + pairBuffer += state.dump; - socket[kClient] = null - socket[kError] = null - socket - .removeListener('error', onSocketError) - .removeListener('readable', onSocketReadable) - .removeListener('end', onSocketEnd) - .removeListener('close', onSocketClose) + // Both key and value are valid. + _result += pairBuffer; + } - client[kSocket] = null - client[kQueue][client[kRunningIdx]++] = null - client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} - try { - request.onUpgrade(statusCode, headers, socket) - } catch (err) { - util.destroy(socket, err) - } +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; - resume(client) - } + typeList = explicit ? state.explicitTypes : state.implicitTypes; - onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { - const { client, socket, headers, statusText } = this + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 - } + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { - const request = client[kQueue][client[kRunningIdx]] + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } - /* istanbul ignore next: difficult to make a test case for */ - if (!request) { - return -1 - } + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; - assert(!this.upgrade) - assert(this.statusCode < 200) + 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'); + } - if (statusCode === 100) { - util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) - return -1 - } + state.dump = _result; + } - /* this can only happen if server is misbehaving */ - if (upgrade && !request.upgrade) { - util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) - return -1 + return true; } + } - assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) + return false; +} - 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') - ) +// 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 (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 (!detectType(state, object, false)) { + detectType(state, object, true); + } - if (request.method === 'CONNECT') { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; - if (upgrade) { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; - if (this.shouldKeepAlive && client[kPipelining]) { - const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } - if (keepAliveTimeout != null) { - const timeout = Math.min( - keepAliveTimeout - client[kKeepAliveTimeoutThreshold], - client[kKeepAliveMaxTimeout] - ) - if (timeout <= 0) { - socket[kReset] = true + 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 { - client[kKeepAliveTimeoutValue] = timeout + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; } } else { - client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + 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 { - // Stop more requests from being dispatched. - socket[kReset] = true + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); } - const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + 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 (request.aborted) { - return -1 - } + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } - if (request.method === 'HEAD') { - return 1 + state.dump = tagStr + ' ' + state.dump; } + } - if (statusCode < 200) { - return 1 - } + return true; +} - if (socket[kBlocking]) { - socket[kBlocking] = false - resume(client) - } +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; - return pause ? constants.ERROR.PAUSED : 0 + 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); +} - onBody (buf) { - const { client, socket, statusCode, maxResponseSize } = this +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; - if (socket.destroyed) { - return -1 - } + 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); - const request = client[kQueue][client[kRunningIdx]] - assert(request) + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); - assert.strictEqual(this.timeoutType, TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } } } + } +} - assert(statusCode >= 200) +function dump(input, options) { + options = options || {}; - if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { - util.destroy(socket, new ResponseExceededMaxSizeError()) - return -1 - } + var state = new State(options); - this.bytesRead += buf.length + if (!state.noRefs) getDuplicateReferences(input, state); - if (request.onData(buf) === false) { - return constants.ERROR.PAUSED - } + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); } - onMessageComplete () { - const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; - if (socket.destroyed && (!statusCode || shouldKeepAlive)) { - return -1 - } + return ''; +} - if (upgrade) { - return - } +module.exports.dump = dump; - 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 = '' +/***/ 8179: +/***/ ((module) => { - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 +"use strict"; +// YAML error class. http://stackoverflow.com/questions/8458984 +// - 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) +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; - client[kQueue][client[kRunningIdx]++] = null + if (!exception.mark) return message; - 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) - } + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; } -} -function onParserTimeout (parser) { - const { socket, timeoutType, client } = parser + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; - /* 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')) + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; } + + return message + ' ' + where; } -function onSocketReadable () { - const { [kParser]: parser } = this - if (parser) { - parser.readMore() + +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 || ''; } } -function onSocketError (err) { - const { [kClient]: client, [kParser]: parser } = this - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; - 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 +YAMLException.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; - 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. +module.exports = YAMLException; - 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 +/***/ 1161: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (client[kHTTPConnVersion] !== 'h2') { - if (parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so far as a valid response. - parser.onMessageComplete() - return - } - } +"use strict"; - util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) -} -function onSocketClose () { - const { [kClient]: client, [kParser]: parser } = this +/*eslint-disable max-len,no-use-before-define*/ - 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() - } +var common = __nccwpck_require__(6829); +var YAMLException = __nccwpck_require__(8179); +var makeSnippet = __nccwpck_require__(6975); +var DEFAULT_SCHEMA = __nccwpck_require__(8759); - this[kParser].destroy() - this[kParser] = null - } - const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) +var _hasOwnProperty = Object.prototype.hasOwnProperty; - client[kSocket] = null - if (client.destroyed) { - assert(client[kPending] === 0) +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; - // 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) - } +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; - client[kPendingIdx] = client[kRunningIdx] - assert(client[kRunning] === 0) +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; - client.emit('disconnect', client[kUrl], [client], err) - resume(client) +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } -async function connect (client) { - assert(!client[kConnecting]) - assert(!client[kSocket]) +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} - let { host, hostname, protocol, port } = client[kUrl] +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} - // Resolve ipv6 - if (hostname[0] === '[') { - const idx = hostname.indexOf(']') +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} - assert(idx !== -1) - const ip = hostname.substring(1, idx) +function fromHexCode(c) { + var lc; - assert(net.isIP(ip)) - hostname = ip + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; } - client[kConnecting] = true + /*eslint-disable no-bitwise*/ + lc = c | 0x20; - if (channels.beforeConnect.hasSubscribers) { - channels.beforeConnect.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector] - }) + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; } - 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 - } + return -1; +} - client[kConnecting] = false +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} - assert(socket) +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } - 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' - }) - } + return -1; +} - const session = http2.connect(client[kUrl], { - createConnection: () => socket, - peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams - }) +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' : ''; +} - 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() +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 + ); +} - client[kHTTP2Session] = session - socket[kHTTP2Session] = session - } else { - if (!llhttpInstance) { - llhttpInstance = await llhttpPromise - llhttpPromise = null - } +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); +} - 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 +function State(input, options) { + this.input = input; - socket - .on('error', onSocketError) - .on('readable', onSocketReadable) - .on('end', onSocketEnd) - .on('close', onSocketClose) + 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; - client[kSocket] = socket + this.json = options['json'] || false; + this.listener = options['listener'] || null; - 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 - } + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; - client[kConnecting] = false + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; - if (channels.connectError.hasSubscribers) { - channels.connectError.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector], - error: err - }) - } + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; - 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) - } + this.documents = []; - client.emit('connectionError', client[kUrl], [client], err) - } + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ - resume(client) } -function emitDrain (client) { - client[kNeedDrain] = 0 - client.emit('drain', client[kUrl], [client]) -} -function resume (client, sync) { - if (client[kResuming] === 2) { - return - } +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 + }; - client[kResuming] = 2 + mark.snippet = makeSnippet(mark); - _resume(client, sync) - client[kResuming] = 0 + return new YAMLException(message, mark); +} - if (client[kRunningIdx] > 256) { - client[kQueue].splice(0, client[kRunningIdx]) - client[kPendingIdx] -= client[kRunningIdx] - client[kRunningIdx] = 0 +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); } } -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 - } +var directiveHandlers = { - const socket = client[kSocket] + YAML: function handleYamlDirective(state, name, args) { - 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 - } + var match, major, minor; - 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 (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); } - 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 (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); } - if (client[kPending] === 0) { - return - } + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - if (client[kRunning] >= (client[kPipelining] || 1)) { - return + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); } - const request = client[kQueue][client[kPendingIdx]] + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); - if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { - if (client[kRunning] > 0) { - return - } + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } - client[kServerName] = request.servername + state.version = args[0]; + state.checkLineBreaks = (minor < 2); - if (socket && socket.servername !== request.servername) { - util.destroy(socket, new InformationalError('servername changed')) - return - } + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); } + }, - if (client[kConnecting]) { - return + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); } - if (!socket && !client[kHTTP2Session]) { - connect(client) - return + 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 (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { - return + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } - 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 (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); } - 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 + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); } - 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. + state.tagMap[handle] = prefix; + } +}; - // 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) +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; } } -// 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 mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; -function write (client, request) { - if (client[kHTTPConnVersion] === 'h2') { - writeH2(client, client[kHTTP2Session], request) - return + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } - const { body, method, path, host, upgrade, headers, blocking, reset } = request + sourceKeys = Object.keys(source); - // 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 + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; - // 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. + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) - } + var index, quantity; - const bodyLength = util.bodyLength(body) + // 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); - let contentLength = bodyLength + 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 (contentLength === null) { - contentLength = request.contentLength + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } } - 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. + // 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]'; + } - contentLength = null + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; } - // 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 + 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'); } - process.emitWarning(new RequestContentLengthMismatchError()) + // 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]; } - const socket = client[kSocket] + return _result; +} - try { - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } +function readLineBreak(state) { + var ch; - errorRequest(client, request, err || new RequestAbortedError()) + ch = state.input.charCodeAt(state.position); - util.destroy(socket, new InformationalError('aborted')) - }) - } catch (err) { - errorRequest(client, request, err) + 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'); } - if (request.aborted) { - return false - } + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} - 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. +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); - socket[kReset] = true - } + 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 (upgrade || method === 'CONNECT') { - // On CONNECT or upgrade, block pipeline from dispatching further - // requests on this connection. + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } - socket[kReset] = true - } + if (is_EOL(ch)) { + readLineBreak(state); - if (reset != null) { - socket[kReset] = reset - } + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; - if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { - socket[kReset] = true + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } } - if (blocking) { - socket[kBlocking] = true + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); } - let header = `${method} ${path} HTTP/1.1\r\n` + return lineBreaks; +} - if (typeof host === 'string') { - header += `host: ${host}\r\n` - } else { - header += client[kHostHeader] - } +function testDocumentSeparator(state) { + var _position = state.position, + ch; - 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' - } + ch = state.input.charCodeAt(_position); - if (headers) { - header += headers - } + // 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)) { - if (channels.sendHeaders.hasSubscribers) { - channels.sendHeaders.publish({ request, headers: header, socket }) - } + _position += 3; - /* 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') + ch = state.input.charCodeAt(_position); - 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 }) + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; } - } 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 + return false; } -function writeH2 (client, session, request) { - const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} - 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 - } +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; - try { - // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } + ch = state.input.charCodeAt(state.position); - errorRequest(client, request, err || new RequestAbortedError()) - }) - } catch (err) { - errorRequest(client, request, err) + 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 (request.aborted) { - 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; + } } - /** @type {import('node:http2').ClientHttp2Stream} */ - let stream - const h2State = client[kHTTP2SessionState] + 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; - headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] - headers[HTTP2_HEADER_METHOD] = method + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); - 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 (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 (stream.id && !stream.pending) { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - } else { - stream.once('ready', () => { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - }) + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; } - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) session.unref() - }) + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } - return true + ch = state.input.charCodeAt(++state.position); } - // https://tools.ietf.org/html/rfc7540#section-8.3 - // :path and :scheme headers must be omited when sending CONNECT + captureSegment(state, captureStart, captureEnd, false); - headers[HTTP2_HEADER_PATH] = path - headers[HTTP2_HEADER_SCHEME] = 'https' + if (state.result) { + return true; + } - // 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 + state.kind = _kind; + state.result = _result; + return false; +} - // 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. +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) + ch = state.input.charCodeAt(state.position); - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) + if (ch !== 0x27/* ' */) { + return false; } - let contentLength = util.bodyLength(body) + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - if (contentLength == null) { - contentLength = request.contentLength - } + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - 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. + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } - contentLength = null - } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; - // 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 - } + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); - process.emitWarning(new RequestContentLengthMismatchError()) + } else { + state.position++; + captureEnd = state.position; + } } - if (contentLength != null) { - assert(body, 'no body must not have content length') - headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` - } + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} - session.ref() +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; - const shouldEndStream = method === 'GET' || method === 'HEAD' - if (expectContinue) { - headers[HTTP2_HEADER_EXPECT] = '100-continue' - stream = session.request(headers, { endStream: shouldEndStream, signal }) + ch = state.input.charCodeAt(state.position); - stream.once('continue', writeBodyH2) - } else { - stream = session.request(headers, { - endStream: shouldEndStream, - signal - }) - writeBodyH2() + if (ch !== 0x22/* " */) { + return false; } - // Increment counter as we have new several streams open - ++h2State.openStreams + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; - stream.once('response', headers => { - const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; - if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { - stream.pause() - } - }) + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); - stream.once('end', () => { - request.onComplete([]) - }) + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); - stream.on('data', (chunk) => { - if (request.onData(chunk) === false) { - stream.pause() - } - }) + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) { - session.unref() - } - }) + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; - stream.once('error', function (err) { - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); - stream.once('frameError', (type, code) => { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - errorRequest(client, request, err) + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) + } else { + throwError(state, 'expected hexadecimal character'); + } + } - // stream.on('aborted', () => { - // // TODO(HTTP/2): Support aborted - // }) + state.result += charFromCodepoint(hexResult); - // stream.on('timeout', () => { - // // TODO(HTTP/2): Support timeout - // }) + state.position++; - // stream.on('push', headers => { - // // TODO(HTTP/2): Suppor push - // }) + } else { + throwError(state, 'unknown escape sequence'); + } - // stream.on('trailers', headers => { - // // TODO(HTTP/2): Support trailers - // }) + captureStart = captureEnd = state.position; - 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 double quoted scalar'); - 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) + state.position++; + captureEnd = state.position; } } -} -function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} - 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() - } - } - ) +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; - pipe.on('data', onPipeData) - pipe.once('end', () => { - pipe.removeListener('data', onPipeData) - util.destroy(pipe) - }) + ch = state.input.charCodeAt(state.position); - function onPipeData (chunk) { - request.onBodySent(chunk) - } + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } - return + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; } - let finished = false + ch = state.input.charCodeAt(++state.position); - const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); - const onData = function (chunk) { - if (finished) { - return + 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 ','"); } - try { - if (!writer.write(chunk) && this.pause) { - this.pause() + 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); } - } catch (err) { - util.destroy(this, err) } - } - const onDrain = function () { - if (finished) { - return + + _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 (body.resume) { - body.resume() + 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); } - } - const onAbort = function () { - if (finished) { - return + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; } - const err = new RequestAbortedError() - queueMicrotask(() => onFinished(err)) } - const onFinished = function (err) { - if (finished) { - return - } - finished = true + throwError(state, 'unexpected end of the stream within a flow collection'); +} - assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; - socket - .off('drain', onDrain) - .off('error', onFinished) + ch = state.input.charCodeAt(state.position); - body - .removeListener('data', onData) - .removeListener('end', onFinished) - .removeListener('error', onFinished) - .removeListener('close', onAbort) + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } - if (!err) { - try { - writer.end() - } catch (er) { - err = er + 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'); } - } - - writer.destroy(err) - if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { - util.destroy(body, err) } else { - util.destroy(body) + break; } } - body - .on('data', onData) - .on('end', onFinished) - .on('error', onFinished) - .on('close', onAbort) + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); - if (body.resume) { - body.resume() + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } } - socket - .on('drain', onDrain) - .on('error', onFinished) -} + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; -async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength === body.size, 'blob body must have content length') + ch = state.input.charCodeAt(state.position); - const isH2 = client[kHTTPConnVersion] === 'h2' - try { - if (contentLength != null && contentLength !== body.size) { - throw new RequestContentLengthMismatchError() + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - 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() + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; } - request.onBodySent(buffer) - request.onRequestSent() - - if (!expectsPayload) { - socket[kReset] = true + if (is_EOL(ch)) { + emptyLines++; + continue; } - resume(client) - } catch (err) { - util.destroy(isH2 ? h2stream : socket, err) - } -} + // End of the scalar. + if (state.lineIndent < textIndent) { -async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + // 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'; + } + } - let callback = null - function onDrain () { - if (callback) { - const cb = callback - callback = null - cb() + // Break this `while` cycle and go to the funciton's epilogue. + break; } - } - const waitForDrain = () => new Promise((resolve, reject) => { - assert(callback === null) + // Folded style: use fancy rules to handle line breaks. + if (folding) { - if (socket[kError]) { - reject(socket[kError]) - } else { - callback = resolve - } - }) + // 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); - if (client[kHTTPConnVersion] === 'h2') { - h2stream - .on('close', onDrain) - .on('drain', onDrain) + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); - 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] + // 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 += ' '; } - const res = h2stream.write(chunk) - request.onBodySent(chunk) - if (!res) { - await waitForDrain() - } + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); } - } 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) + // 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); + } - 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] - } + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; - if (!writer.write(chunk)) { - await waitForDrain() - } + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); } - writer.end() - } catch (err) { - writer.destroy(err) - } finally { - socket - .off('close', onDrain) - .off('drain', onDrain) + captureSegment(state, captureStart, state.position, false); } + + return true; } -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 +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; - socket[kWriting] = true + // 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; } - write (chunk) { - const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + ch = state.input.charCodeAt(state.position); - if (socket[kError]) { - throw socket[kError] + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); } - if (socket.destroyed) { - return false + if (ch !== 0x2D/* - */) { + break; } - const len = Buffer.byteLength(chunk) - if (!len) { - return true + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; } - // We should defer writing chunks. - if (contentLength !== null && bytesWritten + len > contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } + detected = true; + state.position++; - process.emitWarning(new RequestContentLengthMismatchError()) + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } } - socket.cork() + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); - if (bytesWritten === 0) { - if (!expectsPayload) { - socket[kReset] = true - } + ch = state.input.charCodeAt(state.position); - 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 ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; } + } - if (contentLength === null) { - socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') - } + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} - this.bytesWritten += len +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; - const ret = socket.write(chunk) + // 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; - socket.uncork() + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } - request.onBodySent(chunk) + ch = state.input.charCodeAt(state.position); - 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() - } - } + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); } - return ret - } - - end () { - const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this - request.onRequestSent() + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. - socket[kWriting] = false + // + // 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 (socket[kError]) { - throw socket[kError] - } + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } - if (socket.destroyed) { - return - } + detected = true; + atExplicitKey = true; + allowCompact = true; - 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. + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; - socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') } else { - socket.write(`${header}\r\n`, 'latin1') + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } - } 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()) - } - } + state.position += 1; + ch = following; - if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { - // istanbul ignore else: only for jest - if (socket[kParser].timeout.refresh) { - socket[kParser].timeout.refresh() + // + // 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; } - } - resume(client) - } + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); - destroy (err) { - const { socket, client } = this + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - socket[kWriting] = false + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); - if (err) { - assert(client[kRunning] <= 1, 'pipeline should only contain this request') - util.destroy(socket, err) - } - } -} + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } -function errorRequest (client, request, err) { - try { - request.onError(err) - assert(request.aborted) - } catch (err) { - client.emit('error', err) - } -} + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -module.exports = Client + 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`. + } -/***/ 56436: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); -"use strict"; + } 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; + } + } -/* istanbul ignore file: only for Node 12 */ + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -const { kConnected, kSize } = __nccwpck_require__(72785) + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } -class CompatWeakRef { - constructor (value) { - this.value = value + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } } - deref () { - return this.value[kConnected] === 0 && this.value[kSize] === 0 - ? undefined - : this.value - } -} + // + // Epilogue. + // -class CompatFinalizer { - constructor (finalizer) { - this.finalizer = finalizer + // 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); } - register (dispatcher, key) { - if (dispatcher.on) { - dispatcher.on('disconnect', () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key) - } - }) - } + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; } -} -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 - } + return detected; } +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; -/***/ }), + ch = state.input.charCodeAt(state.position); -/***/ 20663: -/***/ ((module) => { + if (ch !== 0x21/* ! */) return false; -"use strict"; + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + ch = state.input.charCodeAt(++state.position); -// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size -const maxAttributeValueSize = 1024 + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); -// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size -const maxNameValuePairSize = 4096 + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); -module.exports = { - maxAttributeValueSize, - maxNameValuePairSize -} + } else { + tagHandle = '!'; + } + _position = state.position; -/***/ }), + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); -/***/ 41724: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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)) { -"use strict"; + 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'); + } -const { parseSetCookie } = __nccwpck_require__(24408) -const { stringify } = __nccwpck_require__(43121) -const { webidl } = __nccwpck_require__(21744) -const { Headers } = __nccwpck_require__(10554) + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } -/** - * @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 - */ + ch = state.input.charCodeAt(++state.position); + } -/** - * @param {Headers} headers - * @returns {Record} - */ -function getCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) + tagName = state.input.slice(_position, state.position); - webidl.brandCheck(headers, Headers, { strict: false }) + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } - const cookie = headers.get('cookie') - const out = {} + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } - if (!cookie) { - return out + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); } - for (const piece of cookie.split(';')) { - const [name, ...value] = piece.split('=') + if (isVerbatim) { + state.tag = tagName; - out[name.trim()] = value.join('=') + } 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 out + return true; } -/** - * @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 }) +function readAnchorProperty(state) { + var _position, + ch; - name = webidl.converters.DOMString(name) - attributes = webidl.converters.DeleteCookieAttributes(attributes) + ch = state.input.charCodeAt(state.position); - // Matches behavior of - // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 - setCookie(headers, { - name, - value: '', - expires: new Date(0), - ...attributes - }) -} + if (ch !== 0x26/* & */) return false; -/** - * @param {Headers} headers - * @returns {Cookie[]} - */ -function getSetCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } - webidl.brandCheck(headers, Headers, { strict: false }) + ch = state.input.charCodeAt(++state.position); + _position = state.position; - const cookies = headers.getSetCookie() + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } - if (!cookies) { - return [] + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); } - return cookies.map((pair) => parseSetCookie(pair)) + state.anchor = state.input.slice(_position, state.position); + return true; } -/** - * @param {Headers} headers - * @param {Cookie} cookie - * @returns {void} - */ -function setCookie (headers, cookie) { - webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) +function readAlias(state) { + var _position, alias, + ch; - webidl.brandCheck(headers, Headers, { strict: false }) + ch = state.input.charCodeAt(state.position); - cookie = webidl.converters.Cookie(cookie) + if (ch !== 0x2A/* * */) return false; - const str = stringify(cookie) + ch = state.input.charCodeAt(++state.position); + _position = state.position; - if (str) { - headers.append('Set-Cookie', stringify(cookie)) + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } -} -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 + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); } -]) -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) - } + alias = state.input.slice(_position, state.position); - 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: [] + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); } -]) -module.exports = { - getCookies, - deleteCookie, - getSetCookies, - setCookie + 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 { + if (state.listener !== null) { + state.listener('open', state); + } -"use strict"; + state.tag = null; + state.anchor = null; + state.kind = null; + state.result = null; + allowBlockStyles = allowBlockScalars = allowBlockCollections = + CONTEXT_BLOCK_OUT === nodeContext || + CONTEXT_BLOCK_IN === nodeContext; -const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(20663) -const { isCTLExcludingHtab } = __nccwpck_require__(43121) -const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) -const assert = __nccwpck_require__(39491) + if (allowToSeek) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; -/** - * @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 + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } } - 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: + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; - // 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 + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } } - // 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) + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; } - // 4. Remove any leading or trailing WSP characters from the name - // string and the value string. - name = name.trim() - value = value.trim() + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } - // 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 - } + blockIndent = state.position - state.lineStart; - // 6. The cookie-name is the name string, and the cookie-value is the - // value string. - return { - name, value, ...parseUnparsedAttributes(unparsedAttributes) - } -} + 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; -/** - * 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 - } + } else if (readAlias(state)) { + hasContent = true; - // 2. Discard the first character of the unparsed-attributes (which - // will be a %x3B (";") character). - assert(unparsedAttributes[0] === ';') - unparsedAttributes = unparsedAttributes.slice(1) + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } - let cookieAv = '' + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; - // 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: + if (state.tag === null) { + state.tag = '?'; + } + } - // 1. Consume the remainder of the unparsed-attributes. - cookieAv = unparsedAttributes - unparsedAttributes = '' + 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); + } } - // Let the cookie-av string be the characters consumed in this step. + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } - let attributeName = '' - let attributeValue = '' + } 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 + '"'); + } - // 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 } + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; - attributeName = collectASequenceOfCodePointsFast( - '=', - cookieAv, - position - ) - attributeValue = cookieAv.slice(position.position + 1) - } else { - // Otherwise: + 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; + } + } + } - // 1. The attribute-name string consists of the entire cookie-av - // string, and the attribute-value string is empty. - attributeName = cookieAv - } + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } - // 5. Remove any leading or trailing WSP characters from the attribute- - // name string and the attribute-value string. - attributeName = attributeName.trim() - attributeValue = attributeValue.trim() + 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 + '"'); + } - // 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) + 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; + } + } } - // 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() + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} - // 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) +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; - // 2. If the attribute-value failed to parse as a cookie date, ignore - // the cookie-av. + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); - 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. + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); - // 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) + ch = state.input.charCodeAt(state.position); - if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; } - // 2. If the remainder of attribute-value contains a non-DIGIT - // character, ignore the cookie-av. - if (!/^\d+$/.test(attributeValue)) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + 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); } - // 3. Let delta-seconds be the attribute-value converted to an integer. - const deltaSeconds = Number(attributeValue) + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; - // 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). + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } - // 5. Set delta-seconds to the smaller of its present value and cookie- - // age-limit. - // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - // 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 + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } - // 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. + if (is_EOL(ch)) break; - // 1. Let cookie-domain be the attribute-value. - let cookieDomain = attributeValue + _position = state.position; - // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be - // cookie-domain without its leading %x2E ("."). - if (cookieDomain[0] === '.') { - cookieDomain = cookieDomain.slice(1) - } + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } - // 3. Convert the cookie-domain to lower case. - cookieDomain = cookieDomain.toLowerCase() + directiveArgs.push(state.input.slice(_position, state.position)); + } - // 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. + if (ch !== 0) readLineBreak(state); - // 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 = '/' + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { - // Otherwise: - - // 1. Let cookie-path be the attribute-value. - cookiePath = attributeValue + throwWarning(state, 'unknown document directive "' + directiveName + '"'); } + } - // 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. + skipSeparationSpace(state, true, -1); - 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. + 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); - 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: + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } - // 1. Let enforcement be "Default". - let enforcement = 'Default' + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); - 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' - } + 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'); + } - // 3. If cookie-av's attribute-value is a case-insensitive match for - // "Strict", set enforcement to "Strict". - if (attributeValueLowercase.includes('strict')) { - enforcement = 'Strict' - } + state.documents.push(state.result); - // 4. If cookie-av's attribute-value is a case-insensitive match for - // "Lax", set enforcement to "Lax". - if (attributeValueLowercase.includes('lax')) { - enforcement = 'Lax' + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); } + return; + } - // 5. Append an attribute to the cookie-attribute-list with an - // attribute-name of "SameSite" and an attribute-value of - // enforcement. - cookieAttributeList.sameSite = enforcement + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); } else { - cookieAttributeList.unparsed ??= [] - - cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + return; } - - // 8. Return to Step 1 of this algorithm. - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } -module.exports = { - parseSetCookie, - parseUnparsedAttributes -} +function loadDocuments(input, options) { + input = String(input); + options = options || {}; -/***/ }), + if (input.length !== 0) { -/***/ 43121: -/***/ ((module) => { + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } -"use strict"; + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + var state = new State(input, options); -/** - * @param {string} value - * @returns {boolean} - */ -function isCTLExcludingHtab (value) { - if (value.length === 0) { - return false + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); } - for (const char of value) { - const code = char.charCodeAt(0) + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; - if ( - (code >= 0x00 || code <= 0x08) || - (code >= 0x0A || code <= 0x1F) || - code === 0x7F - ) { - return false - } + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; } -} - -/** - 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') - } + while (state.position < (state.length - 1)) { + readDocument(state); } + + return state.documents; } -/** - 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') - } +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; } -} -/** - * path-value = - * @param {string} path - */ -function validateCookiePath (path) { - for (const char of path) { - const code = char.charCodeAt(0) + var documents = loadDocuments(input, options); - if (code < 0x21 || char === ';') { - throw new Error('Invalid cookie path') - } + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); } } -/** - * 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') + +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'); } -/** - * @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 +module.exports.loadAll = loadAll; +module.exports.load = load; - 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) +/***/ 1082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - hour = 2DIGIT - minute = 2DIGIT - second = 2DIGIT - */ -function toIMFDate (date) { - if (typeof date === 'number') { - date = new Date(date) - } +"use strict"; - const days = [ - 'Sun', 'Mon', 'Tue', 'Wed', - 'Thu', 'Fri', 'Sat' - ] - const months = [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' - ] +/*eslint-disable max-len*/ - 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') +var YAMLException = __nccwpck_require__(8179); +var Type = __nccwpck_require__(6073); - 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') - } -} +function compileList(schema, name) { + var result = []; -/** - * @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 - } + schema[name].forEach(function (currentType) { + var newIndex = result.length; - validateCookieName(cookie.name) - validateCookieValue(cookie.value) + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { - const out = [`${cookie.name}=${cookie.value}`] + newIndex = previousIndex; + } + }); - // 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 - } + result[newIndex] = currentType; + }); - if (cookie.name.startsWith('__Host-')) { - cookie.secure = true - cookie.domain = null - cookie.path = '/' + 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; + } } - if (cookie.secure) { - out.push('Secure') + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); } + return result; +} - if (cookie.httpOnly) { - out.push('HttpOnly') - } - if (typeof cookie.maxAge === 'number') { - validateCookieMaxAge(cookie.maxAge) - out.push(`Max-Age=${cookie.maxAge}`) - } +function Schema(definition) { + return this.extend(definition); +} - if (cookie.domain) { - validateCookieDomain(cookie.domain) - out.push(`Domain=${cookie.domain}`) - } - if (cookie.path) { - validateCookiePath(cookie.path) - out.push(`Path=${cookie.path}`) - } +Schema.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; - if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { - out.push(`Expires=${toIMFDate(cookie.expires)}`) - } + if (definition instanceof Type) { + // Schema.extend(type) + explicit.push(definition); - if (cookie.sameSite) { - out.push(`SameSite=${cookie.sameSite}`) + } 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: [...] })'); } - for (const part of cookie.unparsed) { - if (!part.includes('=')) { - throw new Error('Invalid unparsed') + 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.'); } - const [key, ...value] = part.split('=') + 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.'); + } - out.push(`${key.trim()}=${value.join('=')}`) - } + 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.'); + } + }); - return out.join('; ') -} + 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.'); + } + }); -module.exports = { - isCTLExcludingHtab, - validateCookieName, - validateCookiePath, - validateCookieValue, - toIMFDate, - stringify -} + 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; /***/ }), -/***/ 82067: +/***/ 2011: /***/ ((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. -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 - } +module.exports = __nccwpck_require__(1035); - 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 - } +/***/ 8759: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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() - } +"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/) - 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') - } +module.exports = (__nccwpck_require__(2011).extend)({ + implicit: [ + __nccwpck_require__(9212), + __nccwpck_require__(6104) + ], + explicit: [ + __nccwpck_require__(7900), + __nccwpck_require__(9046), + __nccwpck_require__(6860), + __nccwpck_require__(9548) + ] +}); - 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) +/***/ 8562: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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 - }) +"use strict"; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 - 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() +var Schema = __nccwpck_require__(1082); - if (callback) { - const cb = callback - callback = null - cb(err) - } - }) - return socket - } -} +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(3619), + __nccwpck_require__(7283), + __nccwpck_require__(6150) + ] +}); -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) - } -} +/***/ }), + +/***/ 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. + -function onConnectTimeout (socket) { - util.destroy(socket, new ConnectTimeoutError()) -} -module.exports = buildConnector + + +module.exports = (__nccwpck_require__(8562).extend)({ + implicit: [ + __nccwpck_require__(721), + __nccwpck_require__(4993), + __nccwpck_require__(1615), + __nccwpck_require__(2705) + ] +}); /***/ }), -/***/ 14462: -/***/ ((module) => { +/***/ 6975: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/** @type {Record} */ -const headerNameLowerCasedRecord = {} -// https://developer.mozilla.org/docs/Web/HTTP/Headers -const wellknownHeaderNames = [ - 'Accept', - 'Accept-Encoding', - 'Accept-Language', - 'Accept-Ranges', - 'Access-Control-Allow-Credentials', - 'Access-Control-Allow-Headers', - 'Access-Control-Allow-Methods', - 'Access-Control-Allow-Origin', - 'Access-Control-Expose-Headers', - 'Access-Control-Max-Age', - 'Access-Control-Request-Headers', - 'Access-Control-Request-Method', - 'Age', - 'Allow', - 'Alt-Svc', - 'Alt-Used', - 'Authorization', - 'Cache-Control', - 'Clear-Site-Data', - 'Connection', - 'Content-Disposition', - 'Content-Encoding', - 'Content-Language', - 'Content-Length', - 'Content-Location', - 'Content-Range', - 'Content-Security-Policy', - 'Content-Security-Policy-Report-Only', - 'Content-Type', - 'Cookie', - 'Cross-Origin-Embedder-Policy', - 'Cross-Origin-Opener-Policy', - 'Cross-Origin-Resource-Policy', - 'Date', - 'Device-Memory', - 'Downlink', - 'ECT', - 'ETag', - 'Expect', - 'Expect-CT', - 'Expires', - 'Forwarded', - 'From', - 'Host', - 'If-Match', - 'If-Modified-Since', - 'If-None-Match', - 'If-Range', - 'If-Unmodified-Since', - 'Keep-Alive', - 'Last-Modified', - 'Link', - 'Location', - 'Max-Forwards', - 'Origin', - 'Permissions-Policy', - 'Pragma', - 'Proxy-Authenticate', - 'Proxy-Authorization', - 'RTT', - 'Range', - 'Referer', - 'Referrer-Policy', - 'Refresh', - 'Retry-After', - 'Sec-WebSocket-Accept', - 'Sec-WebSocket-Extensions', - 'Sec-WebSocket-Key', - 'Sec-WebSocket-Protocol', - 'Sec-WebSocket-Version', - 'Server', - 'Server-Timing', - 'Service-Worker-Allowed', - 'Service-Worker-Navigation-Preload', - 'Set-Cookie', - 'SourceMap', - 'Strict-Transport-Security', - 'Supports-Loading-Mode', - 'TE', - 'Timing-Allow-Origin', - 'Trailer', - 'Transfer-Encoding', - 'Upgrade', - 'Upgrade-Insecure-Requests', - 'User-Agent', - 'Vary', - 'Via', - 'WWW-Authenticate', - 'X-Content-Type-Options', - 'X-DNS-Prefetch-Control', - 'X-Frame-Options', - 'X-Permitted-Cross-Domain-Policies', - 'X-Powered-By', - 'X-Requested-With', - 'X-XSS-Protection' -] +var common = __nccwpck_require__(6829); -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = wellknownHeaderNames[i] - const lowerCasedKey = key.toLowerCase() - headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = - lowerCasedKey + +// 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 + }; } -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(headerNameLowerCasedRecord, null) -module.exports = { - wellknownHeaderNames, - headerNameLowerCasedRecord +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; } -/***/ }), +function makeSnippet(mark, options) { + options = Object.create(options || null); -/***/ 48045: -/***/ ((module) => { + if (!mark.buffer) return null; -"use strict"; + 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; -class UndiciError extends Error { - constructor (message) { - super(message) - this.name = 'UndiciError' - this.code = 'UND_ERR' - } -} + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); -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' + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } } -} -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' + 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; } -} -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' + 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'; } -} -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' - } + return result.replace(/\n$/, ''); } -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' - } -} +module.exports = makeSnippet; -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' - } -} +/***/ 6073: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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' - } -} +"use strict"; -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' - } -} +var YAMLException = __nccwpck_require__(8179); -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' - } -} +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; -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 - } -} +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; -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' - } -} +function compileStyleAliases(map) { + var result = {}; -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' + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); } -} -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 - } + return result; } -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' - } -} +function Type(tag, options) { + options = options || {}; -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 + 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 = { - HTTPParserError, - UndiciError, - HeadersTimeoutError, - HeadersOverflowError, - BodyTimeoutError, - RequestContentLengthMismatchError, - ConnectTimeoutError, - ResponseStatusCodeError, - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError, - ClientDestroyedError, - ClientClosedError, - InformationalError, - SocketError, - NotSupportedError, - ResponseContentLengthMismatchError, - BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError, - RequestRetryError -} +module.exports = Type; /***/ }), -/***/ 62905: +/***/ 7900: /***/ ((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) +/*eslint-disable no-bitwise*/ -// 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!#$%&'*+.|~]+$/ +var Type = __nccwpck_require__(6073); -/** - * 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]/ +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; -const kHandler = Symbol('handler') -const channels = {} +function resolveYamlBinary(data) { + if (data === null) return false; -let extractBody + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; -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 } -} + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); -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') - } + // Skip CR/LF + if (code > 64) continue; - if (typeof method !== 'string') { - throw new InvalidArgumentError('method must be a string') - } else if (tokenRegExp.exec(method) === null) { - throw new InvalidArgumentError('invalid request method') - } + // Fail on illegal characters + if (code < 0) return false; - if (upgrade && typeof upgrade !== 'string') { - throw new InvalidArgumentError('upgrade must be a string') - } + bitlen += 6; + } - if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('invalid headersTimeout') - } + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} - if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('invalid bodyTimeout') - } +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 = []; - if (reset != null && typeof reset !== 'boolean') { - throw new InvalidArgumentError('invalid reset') - } + // Collect by 6*4 bits (3 bytes) - if (expectContinue != null && typeof expectContinue !== 'boolean') { - throw new InvalidArgumentError('invalid expectContinue') + 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); } - this.headersTimeout = headersTimeout + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } - this.bodyTimeout = bodyTimeout + // Dump tail - this.throwOnError = throwOnError === true + tailbits = (max % 4) * 6; - this.method = method + 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); + } - this.abort = null + return new Uint8Array(result); +} - if (body == null) { - this.body = null - } else if (util.isStream(body)) { - this.body = body +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; - const rState = this.body._readableState - if (!rState || !rState.autoDestroy) { - this.endHandler = function autoDestroy () { - util.destroy(this) - } - this.body.on('end', this.endHandler) - } + // Convert every three bytes to 4 ASCII characters. - 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') + 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]; } - this.completed = false + bits = (bits << 8) + object[idx]; + } - this.aborted = false + // Dump tail - this.upgrade = upgrade || null + tail = max % 3; - this.path = query ? util.buildURL(path, query) : path + 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]; + } - this.origin = origin + return result; +} - this.idempotent = idempotent == null - ? method === 'HEAD' || method === 'GET' - : idempotent +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} - this.blocking = blocking == null ? false : blocking +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); - this.reset = reset == null ? null : reset - this.host = null +/***/ }), - this.contentLength = null +/***/ 4993: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.contentType = null +"use strict"; - this.headers = '' - // Only for H2 - this.expectContinue = expectContinue != null ? expectContinue : false +var Type = __nccwpck_require__(6073); - 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') - } +function resolveYamlBoolean(data) { + if (data === null) return false; - 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.') - } + var max = data.length; - if (!extractBody) { - extractBody = (__nccwpck_require__(41472).extractBody) - } + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} - 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` - } +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' +}); - util.validateHandler(handler, method, upgrade) - this.servername = util.getServerName(this.host) +/***/ }), - this[kHandler] = handler +/***/ 2705: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (channels.create.hasSubscribers) { - channels.create.publish({ request: this }) - } - } +"use strict"; - 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 }) - } +var common = __nccwpck_require__(6829); +var Type = __nccwpck_require__(6073); - if (this[kHandler].onRequestSent) { - try { - return this[kHandler].onRequestSent() - } catch (err) { - this.abort(err) - } - } - } +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))$'); - onConnect (abort) { - assert(!this.aborted) - assert(!this.completed) +function resolveYamlFloat(data) { + if (data === null) return false; - if (this.error) { - abort(this.error) - } else { - this.abort = abort - return this[kHandler].onConnect(abort) - } + 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; } - onHeaders (statusCode, headers, resume, statusText) { - assert(!this.aborted) - assert(!this.completed) - - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) - } + return true; +} - try { - return this[kHandler].onHeaders(statusCode, headers, resume, statusText) - } catch (err) { - this.abort(err) - } - } +function constructYamlFloat(data) { + var value, sign; - onData (chunk) { - assert(!this.aborted) - assert(!this.completed) + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; - try { - return this[kHandler].onData(chunk) - } catch (err) { - this.abort(err) - return false - } + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); } - onUpgrade (statusCode, headers, socket) { - assert(!this.aborted) - assert(!this.completed) + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - return this[kHandler].onUpgrade(statusCode, headers, socket) + } else if (value === '.nan') { + return NaN; } + return sign * parseFloat(value, 10); +} - onComplete (trailers) { - this.onFinally() - assert(!this.aborted) +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - this.completed = true - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers }) - } +function representYamlFloat(object, style) { + var res; - try { - return this[kHandler].onComplete(trailers) - } catch (err) { - // TODO (fix): This might be a bad idea? - this.onError(err) + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; } - } - - onError (error) { - this.onFinally() - - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }) + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; } - - if (this.aborted) { - return + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; } - this.aborted = true - - return this[kHandler].onError(error) + } else if (common.isNegativeZero(object)) { + return '-0.0'; } - onFinally () { - if (this.errorHandler) { - this.body.off('error', this.errorHandler) - this.errorHandler = null - } + res = object.toString(10); - if (this.endHandler) { - this.body.off('end', this.endHandler) - this.endHandler = null - } - } + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack - // TODO: adjust to support H2 - addHeader (key, value) { - processHeader(this, key, value) - return this - } + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} - static [kHTTP1BuildRequest] (origin, opts, handler) { - // TODO: Migrate header parsing here, to make Requests - // HTTP agnostic - return new Request(origin, opts, handler) - } +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} - static [kHTTP2BuildRequest] (origin, opts, handler) { - const headers = opts.headers - opts = { ...opts, headers: null } +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); - 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') - } +/***/ 1615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return request - } +"use strict"; - static [kHTTP2CopyHeaders] (raw) { - const rawHeaders = raw.split('\r\n') - const headers = {} - for (const header of rawHeaders) { - const [key, value] = header.split(': ') +var common = __nccwpck_require__(6829); +var Type = __nccwpck_require__(6073); - if (value == null || value.length === 0) continue +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} - if (headers[key]) headers[key] += `,${value}` - else headers[key] = value - } +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} - return headers - } +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } -function processHeaderValue (key, val, skipAppend) { - if (val && typeof val === 'object') { - throw new InvalidArgumentError(`invalid ${key} header`) - } +function resolveYamlInteger(data) { + if (data === null) return false; - val = val != null ? `${val}` : '' + var max = data.length, + index = 0, + hasDigits = false, + ch; - if (headerCharRegex.exec(val) !== null) { - throw new InvalidArgumentError(`invalid ${key} header`) - } + if (!max) return false; - return skipAppend ? val : `${key}: ${val}\r\n` -} + ch = data[index]; -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 + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; } - 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') + 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 !== '_'; } - } 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 + + + 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 !== '_'; } - } 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]) - } + + + 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; } - } else { - if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) - else request.headers += processHeaderValue(key, val) + return hasDigits && ch !== '_'; } } -} -module.exports = Request + // 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; + } -/***/ 72785: -/***/ ((module) => { + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; -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') + return true; } +function constructYamlInteger(data) { + var value = data, sign = 1, ch; -/***/ }), - -/***/ 83983: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + ch = value[0]; -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 { headerNameLowerCasedRecord } = __nccwpck_require__(14462) + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } -const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + if (value === '0') return 0; -function nop () {} + 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); + } -function isStream (obj) { - return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' + return sign * parseInt(value, 10); } -// 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 isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); } -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 +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' ] } +}); - 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 - } +/***/ 6150: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!url || typeof url !== 'object') { - throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') - } +"use strict"; - 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.') - } +var Type = __nccwpck_require__(6073); - if (url.path != null && typeof url.path !== 'string') { - throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') - } +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); - 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.') - } +/***/ 6104: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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 || ''}` +"use strict"; - 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) - } +var Type = __nccwpck_require__(6073); - return url +function resolveYamlMerge(data) { + return data === '<<' || data === null; } -function parseOrigin (url) { - url = parseURL(url) - - if (url.pathname !== '/' || url.search || url.hash) { - throw new InvalidArgumentError('invalid url') - } - - return url -} +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); -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 +/***/ 721: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return host.substring(0, idx) -} +"use strict"; -// 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') +var Type = __nccwpck_require__(6073); - const servername = getHostname(host) - if (net.isIP(servername)) { - return '' - } +function resolveYamlNull(data) { + if (data === null) return true; - return servername -} + var max = data.length; -function deepClone (obj) { - return JSON.parse(JSON.stringify(obj)) + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } -function isAsyncIterable (obj) { - return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +function constructYamlNull() { + return null; } -function isIterable (obj) { - return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +function isNull(object) { + return object === null; } -function bodyLength (body) { - if (body == null) { - return 0 - } else if (isStream(body)) { - const state = body._readableState - return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) - ? state.length - : null - } else if (isBlobLike(body)) { - return body.size != null ? body.size : null - } else if (isBuffer(body)) { - return body.byteLength - } +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' +}); - 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 -} +/***/ 9046: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function destroy (stream, err) { - if (stream == null || !isStream(stream) || isDestroyed(stream)) { - return - } +"use strict"; - 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) - } +var Type = __nccwpck_require__(6073); - if (stream.destroyed !== true) { - stream[kDestroyed] = true - } -} +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; -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 resolveYamlOmap(data) { + if (data === null) return true; -/** - * Retrieves a header name and returns its lowercase value. - * @param {string | Buffer} value Header name - * @returns {string} - */ -function headerNameToString (value) { - return headerNameLowerCasedRecord[value] || value.toLowerCase() -} + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; -function parseHeaders (headers, obj = {}) { - // For H2 support - if (!Array.isArray(headers)) return headers + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; - for (let i = 0; i < headers.length; i += 2) { - const key = headers[i].toString().toLowerCase() - let val = obj[key] + if (_toString.call(pair) !== '[object Object]') return false; - 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 + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; } - 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') + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; } - return obj + return true; } -function parseRawHeaders (headers) { - const ret = [] - let hasContentLength = false - let contentDispositionIdx = -1 +function constructYamlOmap(data) { + return data !== null ? data : []; +} - for (let n = 0; n < headers.length; n += 2) { - const key = headers[n + 0].toString() - const val = headers[n + 1].toString('utf8') +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); - 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 -} +/***/ 6860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function isBuffer (buffer) { - // See, https://github.com/mcollina/undici/pull/319 - return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) -} +"use strict"; -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') - } +var Type = __nccwpck_require__(6073); - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } +var _toString = Object.prototype.toString; - if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { - throw new InvalidArgumentError('invalid onBodySent method') - } +function resolveYamlPairs(data) { + if (data === null) return true; - 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') - } + var index, length, pair, keys, result, + object = data; - if (typeof handler.onData !== 'function') { - throw new InvalidArgumentError('invalid onData method') - } + result = new Array(object.length); - if (typeof handler.onComplete !== 'function') { - throw new InvalidArgumentError('invalid onComplete method') - } - } -} + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; -// 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) - )) -} + if (_toString.call(pair) !== '[object Object]') return false; -function isErrored (body) { - return !!(body && ( - stream.isErrored - ? stream.isErrored(body) - : /state: 'errored'/.test(nodeUtil.inspect(body) - ))) -} + keys = Object.keys(pair); -function isReadable (body) { - return !!(body && ( - stream.isReadable - ? stream.isReadable(body) - : /state: 'readable'/.test(nodeUtil.inspect(body) - ))) -} + if (keys.length !== 1) return false; -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 + result[index] = [ keys[0], pair[keys[0]] ]; } -} -async function * convertIterableToBuffer (iterable) { - for await (const chunk of iterable) { - yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) - } + return true; } -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 - ) -} +function constructYamlPairs(data) { + if (data === null) return []; -// 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' - ) -} + var index, length, pair, keys, result, + object = data; -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 - } - } -} + result = new Array(object.length); -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) -} + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; -const hasToWellFormed = !!String.prototype.toWellFormed + keys = Object.keys(pair); -/** - * @param {string} val - */ -function toUSVString (val) { - if (hasToWellFormed) { - return `${val}`.toWellFormed() - } else if (nodeUtil.toUSVString) { - return nodeUtil.toUSVString(val) + result[index] = [ keys[0], pair[keys[0]] ]; } - return `${val}` + return result; } -// 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 -} +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); -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, - headerNameToString, - 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'] -} +/***/ }), + +/***/ 7283: +/***/ ((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 : []; } +}); /***/ }), -/***/ 74839: +/***/ 9548: /***/ ((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) +var Type = __nccwpck_require__(6073); -const kDestroyed = Symbol('destroyed') -const kClosed = Symbol('closed') -const kOnDestroyed = Symbol('onDestroyed') -const kOnClosed = Symbol('onClosed') -const kInterceptedDispatch = Symbol('Intercepted Dispatch') +var _hasOwnProperty = Object.prototype.hasOwnProperty; -class DispatcherBase extends Dispatcher { - constructor () { - super() +function resolveYamlSet(data) { + if (data === null) return true; - this[kDestroyed] = false - this[kOnDestroyed] = null - this[kClosed] = false - this[kOnClosed] = [] - } + var key, object = data; - get destroyed () { - return this[kDestroyed] + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } } - get closed () { - return this[kClosed] - } + return true; +} - get interceptors () { - return this[kInterceptors] - } +function constructYamlSet(data) { + return data !== null ? data : {}; +} - 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') - } - } - } +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); - 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') - } +/***/ 3619: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this[kDestroyed]) { - queueMicrotask(() => callback(new ClientDestroyedError(), null)) - return - } +"use strict"; - if (this[kClosed]) { - if (this[kOnClosed]) { - this[kOnClosed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } - this[kClosed] = true - this[kOnClosed].push(callback) +var Type = __nccwpck_require__(6073); - const onClosed = () => { - const callbacks = this[kOnClosed] - this[kOnClosed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) - } - } +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); - // 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) - }) - }) - } +/***/ 9212: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } +"use strict"; - if (this[kDestroyed]) { - if (this[kOnDestroyed]) { - this[kOnDestroyed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } - if (!err) { - err = new ClientDestroyedError() - } +var Type = __nccwpck_require__(6073); - this[kDestroyed] = true - this[kOnDestroyed] = this[kOnDestroyed] || [] - this[kOnDestroyed].push(callback) +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 - const onDestroyed = () => { - const callbacks = this[kOnDestroyed] - this[kOnDestroyed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) - } - } +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 - // Should not error. - this[kDestroy](err).then(() => { - queueMicrotask(onDestroyed) - }) +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)); } - [kInterceptedDispatch] (opts, handler) { - if (!this[kInterceptors] || this[kInterceptors].length === 0) { - this[kInterceptedDispatch] = this[kDispatch] - return this[kDispatch](opts, handler) - } + // match: [4] hour [5] minute [6] second [7] fraction - let dispatch = this[kDispatch].bind(this) - for (let i = this[kInterceptors].length - 1; i >= 0; i--) { - dispatch = this[kInterceptors][i](dispatch) + 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'; } - this[kInterceptedDispatch] = dispatch - return dispatch(opts, handler) + fraction = +fraction; } - dispatch (opts, handler) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - try { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('opts must be an object.') - } + 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; + } - if (this[kDestroyed] || this[kOnDestroyed]) { - throw new ClientDestroyedError() - } + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - if (this[kClosed]) { - throw new ClientClosedError() - } + if (delta) date.setTime(date.getTime() - delta); - return this[kInterceptedDispatch](opts, handler) - } catch (err) { - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } + return date; +} - handler.onError(err) +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} - return false - } +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + + +/***/ }), + +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var wrappy = __nccwpck_require__(2940) +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 } -module.exports = DispatcherBase +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 +} + + +/***/ }), + +/***/ 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); /***/ }), -/***/ 60412: +/***/ 4294: /***/ ((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 +module.exports = __nccwpck_require__(4219); /***/ }), -/***/ 41472: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Busboy = __nccwpck_require__(50727) -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 random -try { - const crypto = __nccwpck_require__(6005) - random = (max) => crypto.randomInt(0, max) -} catch { - random = (max) => Math.floor(Math.random(max)) -} - -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${`${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 } +/***/ 4219: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 14. Return (body, type). - return [body, type] -} +"use strict"; -// 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: +var net = __nccwpck_require__(1808); +var tls = __nccwpck_require__(4404); +var http = __nccwpck_require__(3685); +var https = __nccwpck_require__(5687); +var events = __nccwpck_require__(2361); +var assert = __nccwpck_require__(9491); +var util = __nccwpck_require__(3837); - // 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) -} +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; -function cloneBody (body) { - // To clone a body body, run these steps: - // https://fetch.spec.whatwg.org/#concept-body-clone +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} - // 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() +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - // 2. Set body’s stream to out1. - body.stream = out1 +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} - // 3. Return a body whose stream is out2 and other members are copied from body. - return { - stream: finalClone, - length: body.length, - source: body.source - } +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; } -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.') - } +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 = []; - if (stream.locked) { - throw new TypeError('The stream is locked.') + 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); - // Compat. - stream[kBodyUsed] = true +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - yield * stream - } + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; } -} -function throwIfAborted (state) { - if (state.aborted) { - throw new DOMException('The operation was aborted.', 'AbortError') + // 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'); } -} -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) + 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(); - if (mimeType === 'failure') { - mimeType = '' - } else if (mimeType) { - mimeType = serializeAMimeType(mimeType) - } + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } - // Return a Blob whose contents are bytes and type attribute - // is mimeType. - return new Blob([bytes], { type: mimeType }) - }, instance) - }, + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } - 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) - }, + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); - 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) - }, + 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); + } - 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) - }, + function onError(cause) { + connectReq.removeAllListeners(); - async formData () { - webidl.brandCheck(this, instance) + 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); + } +}; - throwIfAborted(this[kState]) +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); - const contentType = this.headers.get('Content-Type') + 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); + }); + } +}; - // 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 +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 + }); - const responseFormData = new FormData() + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} - let busboy - try { - busboy = new Busboy({ - headers, - preservePath: true - }) - } catch (err) { - throw new DOMException(`${err}`, 'AbortError') +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; +} - 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 = '' +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 - 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 })) - }) - } - }) +/***/ 1773: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const busboyResolve = new Promise((resolve, reject) => { - busboy.on('finish', resolve) - busboy.on('error', (err) => reject(new TypeError(err))) - }) +"use strict"; - 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: +const Client = __nccwpck_require__(3598) +const Dispatcher = __nccwpck_require__(412) +const errors = __nccwpck_require__(8045) +const Pool = __nccwpck_require__(4634) +const BalancedPool = __nccwpck_require__(7931) +const Agent = __nccwpck_require__(7890) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(4059) +const buildConnector = __nccwpck_require__(2067) +const MockClient = __nccwpck_require__(8687) +const MockAgent = __nccwpck_require__(6771) +const MockPool = __nccwpck_require__(6193) +const mockErrors = __nccwpck_require__(888) +const ProxyAgent = __nccwpck_require__(7858) +const RetryHandler = __nccwpck_require__(2286) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(1892) +const DecoratorHandler = __nccwpck_require__(6930) +const RedirectHandler = __nccwpck_require__(2860) +const createRedirectInterceptor = __nccwpck_require__(8861) - // 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 }) +let hasCrypto +try { + __nccwpck_require__(6113) + hasCrypto = true +} catch { + hasCrypto = false +} - 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 }) - } +Object.assign(Dispatcher.prototype, api) - // 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() +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 - throwIfAborted(this[kState]) +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor - // Otherwise, throw a TypeError. - throw webidl.errors.exception({ - header: `${instance.name}.formData`, - message: 'Could not parse content as FormData.' - }) - } +module.exports.buildConnector = buildConnector +module.exports.errors = errors + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null } - } - return methods -} + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } -function mixinBody (prototype) { - Object.assign(prototype.prototype, bodyMixinMethods(prototype)) -} + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } -/** - * @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) + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } - throwIfAborted(object[kState]) + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } - // 1. If object is unusable, then return a promise rejected - // with a TypeError. - if (bodyUnusable(object[kState].body)) { - throw new TypeError('Body is unusable') - } + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } - // 2. Let promise be a new promise. - const promise = createDeferredPromise() + url = util.parseURL(url) + } - // 3. Let errorSteps given error be to reject promise with error. - const errorSteps = (error) => promise.reject(error) + const { agent, dispatcher = getGlobalDispatcher() } = opts - // 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) + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') } - } - // 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 + 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) } +} - // 6. Otherwise, fully read object’s body given successSteps, - // errorSteps, and object’s relevant global object. - await fullyReadBody(object[kState].body, successSteps, errorSteps) +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher - // 7. Return promise. - return promise.promise -} +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__(4881).fetch) + } -// 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)) -} + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) + } -/** - * @see https://encoding.spec.whatwg.org/#utf-8-decode - * @param {Buffer} buffer - */ -function utf8DecodeBytes (buffer) { - if (buffer.length === 0) { - return '' + throw err + } } + module.exports.Headers = __nccwpck_require__(554).Headers + module.exports.Response = __nccwpck_require__(7823).Response + module.exports.Request = __nccwpck_require__(8359).Request + module.exports.FormData = __nccwpck_require__(2015).FormData + module.exports.File = __nccwpck_require__(8511).File + module.exports.FileReader = __nccwpck_require__(1446).FileReader - // 1. Let buffer be the result of peeking three bytes from - // ioQueue, converted to a byte sequence. + const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1246) - // 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) - } + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin - // 3. Process a queue with an instance of UTF-8’s - // decoder, ioQueue, output, and "replacement". - const output = textDecoder.decode(buffer) + const { CacheStorage } = __nccwpck_require__(7907) + const { kConstruct } = __nccwpck_require__(9174) - // 4. Return output. - return output + // 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) } -/** - * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value - * @param {Uint8Array} bytes - */ -function parseJSONFromBytes (bytes) { - return JSON.parse(utf8DecodeBytes(bytes)) -} +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(1724) -/** - * @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') + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie - if (contentType === null) { - return 'failure' - } + const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) - return parseMIMEType(contentType) + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType } -module.exports = { - extractBody, - safelyExtractBody, - cloneBody, - mixinBody +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = __nccwpck_require__(4284) + + 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 + /***/ }), -/***/ 41037: +/***/ 7890: /***/ ((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 { InvalidArgumentError } = __nccwpck_require__(8045) +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(2785) +const DispatcherBase = __nccwpck_require__(4839) +const Pool = __nccwpck_require__(4634) +const Client = __nccwpck_require__(3598) +const util = __nccwpck_require__(3983) +const createRedirectInterceptor = __nccwpck_require__(8861) +const { WeakRef, FinalizationRegistry } = __nccwpck_require__(6436)() -const nullBodyStatus = [101, 204, 205, 304] +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') -const redirectStatus = [301, 302, 303, 307, 308] -const redirectStatusSet = new Set(redirectStatus) +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} -// 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' -] +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() -const badPortsSet = new Set(badPorts) + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } -// 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) + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } -const requestRedirect = ['follow', 'manual', 'error'] + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } -const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] -const safeMethodsSet = new Set(safeMethods) + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } -const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] -const requestCredentials = ['omit', 'same-origin', 'include'] + 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 requestCache = [ - 'default', - 'no-store', - 'reload', - 'no-cache', - 'force-cache', - 'only-if-cached' -] + const agent = this -// 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' -] + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } -// https://fetch.spec.whatwg.org/#enumdef-requestduplex -const requestDuplex = [ - 'half' -] + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } -// http://fetch.spec.whatwg.org/#forbidden-method -const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] -const forbiddenMethodsSet = new Set(forbiddenMethods) + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } -const subresource = [ - 'audio', - 'audioworklet', - 'font', - 'image', - 'manifest', - 'paintworklet', - 'script', - 'style', - 'track', - 'video', - 'xslt', - '' -] -const subresourceSet = new Set(subresource) + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } + } -/** @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 + 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 } -})() -let channel + [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.') + } -/** @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') + 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) } - if (!channel) { - channel = new MessageChannel() + 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()) + } } - channel.port1.unref() - channel.port2.unref() - channel.port1.postMessage(value, options?.transfer) - return receiveMessageOnPort(channel.port2).message + + await Promise.all(closePromises) } -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 + 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 + /***/ }), -/***/ 685: +/***/ 7032: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const assert = __nccwpck_require__(39491) -const { atob } = __nccwpck_require__(14300) -const { isomorphicDecode } = __nccwpck_require__(52538) +const { addAbortListener } = __nccwpck_require__(3983) +const { RequestAbortedError } = __nccwpck_require__(8045) -const encoder = new TextEncoder() +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') -/** - * @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 +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) + } +} -// 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:') +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null - // 2. Let input be the result of running the URL - // serializer on dataURL with exclude fragment - // set to true. - let input = URLSerializer(dataURL, true) + if (!signal) { + return + } - // 3. Remove the leading "data:" string from input. - input = input.slice(5) + if (signal.aborted) { + abort(self) + return + } - // 4. Let position point at the start of input. - const position = { position: 0 } + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } - // 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 - ) + addAbortListener(self[kSignal], self[kListener]) +} - // 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) +function removeSignal (self) { + if (!self[kSignal]) { + return + } - // 7. If position is past the end of input, then - // return failure - if (position.position >= input.length) { - return 'failure' + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) } - // 8. Advance position by 1. - position.position++ + self[kSignal] = null + self[kListener] = null +} - // 9. Let encodedBody be the remainder of input. - const encodedBody = input.slice(mimeTypeLength + 1) +module.exports = { + addSignal, + removeSignal +} - // 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) +/***/ 9744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 3. If body is failure, then return failure. - if (body === 'failure') { - return 'failure' +"use strict"; + + +const { AsyncResource } = __nccwpck_require__(852) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - // 4. Remove the last 6 code points from mimeType. - mimeType = mimeType.slice(0, -6) + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - // 5. Remove trailing U+0020 SPACE code points from mimeType, - // if any. - mimeType = mimeType.replace(/(\u0020)+$/, '') + const { signal, opaque, responseHeaders } = opts - // 6. Remove the last U+003B (;) code point from mimeType. - mimeType = mimeType.slice(0, -1) - } + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - // 12. If mimeType starts with U+003B (;), then prepend - // "text/plain" to mimeType. - if (mimeType.startsWith(';')) { - mimeType = 'text/plain' + mimeType - } + super('UNDICI_CONNECT') - // 13. Let mimeTypeRecord be the result of parsing - // mimeType. - let mimeTypeRecord = parseMIMEType(mimeType) + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null - // 14. If mimeTypeRecord is failure, then set - // mimeTypeRecord to text/plain;charset=US-ASCII. - if (mimeTypeRecord === 'failure') { - mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + addSignal(this, signal) } - // 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 } -} + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -// https://url.spec.whatwg.org/#concept-url-serializer -/** - * @param {URL} url - * @param {boolean} excludeFragment - */ -function URLSerializer (url, excludeFragment = false) { - if (!excludeFragment) { - return url.href + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) } - const href = url.href - const hashLength = url.hash.length + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - return hashLength === 0 ? href : href.substring(0, href.length - hashLength) -} + removeSignal(this) -// 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 = '' + this.callback = null - // 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] + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } - // 2. Advance position by 1. - position.position++ + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) } - // 3. Return result. - return result -} + onError (err) { + const { callback, opaque } = this -/** - * 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 + removeSignal(this) - if (idx === -1) { - position.position = input.length - return input.slice(start) + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } } - - 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) +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - // 2. Return the percent-decoding of bytes. - return percentDecode(bytes) + 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 })) + } } -// 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) +module.exports = connect - // 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) +/***/ 8752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 3. Skip the next two bytes in input. - i += 2 - } - } +"use strict"; - // 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) +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(2781) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) - // 2. Let position be a position variable for input, - // initially pointing at the start of input. - const position = { position: 0 } +const kResume = Symbol('resume') - // 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 - ) +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) - // 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' + this[kResume] = null } - // 5. If position is past the end of input, then return - // failure - if (position.position > input.length) { - return 'failure' + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } } - // 6. Advance position by 1. (This skips past U+002F (/).) - position.position++ + _destroy (err, callback) { + this._read() - // 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 - ) + callback(err) + } +} - // 8. Remove any trailing HTTP whitespace from subtype. - subtype = removeHTTPWhitespace(subtype, false, true) +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } - // 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' + _read () { + this[kResume]() } - const typeLowercase = type.toLowerCase() - const subtypeLowercase = subtype.toLowerCase() + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } - // 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}` + callback(err) } +} - // 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 - ) +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - // 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 - ) + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } - // 4. Set parameterName to parameterName, in ASCII - // lowercase. - parameterName = parameterName.toLowerCase() + const { signal, method, opaque, onInfo, responseHeaders } = opts - // 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 - } + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - // 2. Advance position by 1. (This skips past U+003D (=).) - position.position++ + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') } - // 6. If position is past the end of input, then break. - if (position.position > input.length) { - break + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') } - // 7. Let parameterValue be null. - let parameterValue = null + super('UNDICI_PIPELINE') - // 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) + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null - // 2. Collect a sequence of code points that are not - // U+003B (;) from input, given position. - collectASequenceOfCodePointsFast( - ';', - input, - position - ) + this.req = new PipelineRequest().on('error', util.nop) - // 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 - ) + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this - // 2. Remove any trailing HTTP whitespace from parameterValue. - parameterValue = removeHTTPWhitespace(parameterValue, false, true) + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this - // 3. If parameterValue is the empty string, then continue. - if (parameterValue.length === 0) { - continue - } - } + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this - // 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) - } - } + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } - // 12. Return mimeType. - return mimeType -} + if (abort && err) { + abort() + } -// 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 + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) - // 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(/=?=$/, '') - } + removeSignal(this) - // 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' - } + callback(err) + } + }).on('prefinish', () => { + const { req } = this - // 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' - } + // Node < 15 does not call _final in same tick. + req.push(null) + }) - const binary = atob(data) - const bytes = new Uint8Array(binary.length) + this.res = null - for (let byte = 0; byte < binary.length; byte++) { - bytes[byte] = binary.charCodeAt(byte) + addSignal(this, signal) } - return bytes -} + onConnect (abort, context) { + const { ret, res } = this -// 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 + assert(!res, 'pipeline cannot be retried') - // 2. Let value be the empty string. - let value = '' + if (ret.destroyed) { + throw new RequestAbortedError() + } - // 3. Assert: the code point at position within input - // is U+0022 ("). - assert(input[position.position] === '"') + this.abort = abort + this.context = context + } - // 4. Advance position by 1. - position.position++ + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this - // 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 - ) + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } - // 2. If position is past the end of input, then break. - if (position.position >= input.length) { - break + 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 } - // 3. Let quoteOrBackslash be the code point at position within - // input. - const quoteOrBackslash = input[position.position] + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } - // 4. Advance position by 1. - position.position++ + body + .on('data', (chunk) => { + const { ret, body } = this - // 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 - } + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this - // 2. Append the code point at position within input to value. - value += input[position.position] + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this - // 3. Advance position by 1. - position.position++ + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) - // 6. Otherwise: - } else { - // 1. Assert: quoteOrBackslash is U+0022 ("). - assert(quoteOrBackslash === '"') + this.body = body + } - // 2. Break. - break - } + onData (chunk) { + const { res } = this + return res.push(chunk) } - // 6. If the extract-value flag is set, then return value. - if (extractValue) { - return value + onComplete (trailers) { + const { res } = this + res.push(null) } - // 7. Return the code points from positionStart to position, - // inclusive, within input. - return input.slice(positionStart, position.position) + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } } -/** - * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type - */ -function serializeAMimeType (mimeType) { - assert(mimeType !== 'failure') - const { parameters, essence } = mimeType +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) + } +} - // 1. Let serialization be the concatenation of mimeType’s - // type, U+002F (/), and mimeType’s subtype. - let serialization = essence +module.exports = pipeline - // 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 += '=' +/***/ 5448: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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') +"use strict"; - // 2. Prepend U+0022 (") to value. - value = '"' + value - // 3. Append U+0022 (") to value. - value += '"' - } +const Readable = __nccwpck_require__(3858) +const { + InvalidArgumentError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) - // 5. Append value to serialization. - serialization += value - } +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - // 3. Return serialization. - return serialization -} + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts -/** - * @see https://fetch.spec.whatwg.org/#http-whitespace - * @param {string} char - */ -function isHTTPWhiteSpace (char) { - return char === '\r' || char === '\n' || char === '\t' || char === ' ' -} + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } -/** - * @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 (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } - if (leading) { - for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); - } + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - if (trailing) { - for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); - } + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - return str.slice(lead, trail + 1) -} + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } -/** - * @see https://infra.spec.whatwg.org/#ascii-whitespace - * @param {string} char - */ -function isASCIIWhitespace (char) { - return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' -} + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } -/** - * @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 + 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 (leading) { - for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); - } + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } - if (trailing) { - for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + addSignal(this, signal) } - return str.slice(lead, trail + 1) -} - -module.exports = { - dataURLProcessor, - URLSerializer, - collectASequenceOfCodePoints, - collectASequenceOfCodePointsFast, - stringPercentDecode, - parseMIMEType, - collectAnHTTPQuotedString, - serializeAMimeType -} - - -/***/ }), + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -/***/ 78511: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.abort = abort + this.context = context + } -"use strict"; + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) -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() + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } -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' }) + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) - fileBits = webidl.converters['sequence'](fileBits) - fileName = webidl.converters.USVString(fileName) - options = webidl.converters.FilePropertyBag(options) + 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 + }) + } + } + } - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. - // Note: Blob handles this for us + onData (chunk) { + const { res } = this + return res.push(chunk) + } - // 2. Let n be the fileName argument to the constructor. - const n = fileName + onComplete (trailers) { + const { res } = this - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: + removeSignal(this) - // 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 + util.parseHeaders(trailers, this.trailers) - // eslint-disable-next-line no-labels - substep: { - if (t) { - t = parseMIMEType(t) + res.push(null) + } - if (t === 'failure') { - t = '' - // eslint-disable-next-line no-labels - break substep - } + onError (err) { + const { res, callback, body, opaque } = this - t = serializeAMimeType(t).toLowerCase() - } + removeSignal(this) - // 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 + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - // 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. + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } - super(processBlobParts(fileBits, options), { type: t }) - this[kState] = { - name: n, - lastModified: d, - type: t + if (body) { + this.body = null + util.destroy(body, err) } } +} - get name () { - webidl.brandCheck(this, File) +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - return this[kState].name + 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 })) } +} - get lastModified () { - webidl.brandCheck(this, File) +module.exports = request +module.exports.RequestHandler = RequestHandler - return this[kState].lastModified - } - get type () { - webidl.brandCheck(this, File) +/***/ }), - return this[kState].type - } -} +/***/ 5395: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -class FileLike { - constructor (blobLike, fileName, options = {}) { - // TODO: argument idl type check +"use strict"; - // 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. +const { finished, PassThrough } = __nccwpck_require__(2781) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) - // 2. Let n be the fileName argument to the constructor. - const n = fileName +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts - // 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 + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - // 2. Convert every character in t to ASCII lowercase. - // TODO + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } - // 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() + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - // 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. + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - this[kState] = { - blobLike, - name: n, - type: t, - lastModified: d + 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 } - } - stream (...args) { - webidl.brandCheck(this, FileLike) + 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 - return this[kState].blobLike.stream(...args) + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) } - arrayBuffer (...args) { - webidl.brandCheck(this, FileLike) + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - return this[kState].blobLike.arrayBuffer(...args) + this.abort = abort + this.context = context } - slice (...args) { - webidl.brandCheck(this, FileLike) + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this - return this[kState].blobLike.slice(...args) - } + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - text (...args) { - webidl.brandCheck(this, FileLike) + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } - return this[kState].blobLike.text(...args) - } + this.factory = null - get size () { - webidl.brandCheck(this, FileLike) + let res - return this[kState].blobLike.size - } + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() - get type () { - webidl.brandCheck(this, FileLike) + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } - return this[kState].blobLike.type - } + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) - get name () { - webidl.brandCheck(this, FileLike) + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } - return this[kState].name - } + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this - get lastModified () { - webidl.brandCheck(this, FileLike) + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } - return this[kState].lastModified - } + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + } - get [Symbol.toStringTag] () { - return 'File' - } -} + res.on('drain', resume) -Object.defineProperties(File.prototype, { - [Symbol.toStringTag]: { - value: 'File', - configurable: true - }, - name: kEnumerableProperty, - lastModified: kEnumerableProperty -}) + this.res = res -webidl.converters.Blob = webidl.interfaceConverter(Blob) + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain -webidl.converters.BlobPart = function (V, opts) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) - } + return needDrain !== true + } - if ( - ArrayBuffer.isView(V) || - types.isAnyArrayBuffer(V) - ) { - return webidl.converters.BufferSource(V, opts) - } + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true } - return webidl.converters.USVString(V, opts) -} + onComplete (trailers) { + const { res } = this -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.BlobPart -) + removeSignal(this) -// 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() + if (!res) { + return } - }, - { - key: 'type', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'endings', - converter: (value) => { - value = webidl.converters.DOMString(value) - value = value.toLowerCase() - if (value !== 'native') { - value = 'transparent' - } + this.trailers = util.parseHeaders(trailers) - return value - }, - defaultValue: 'transparent' + res.end() } -]) -/** - * @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 = [] + onError (err) { + const { res, callback, opaque, body } = this - // 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 + removeSignal(this) - // 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) - } + this.factory = null - // 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) + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - } - // 3. Return bytes. - return bytes + if (body) { + this.body = null + util.destroy(body, err) + } + } } -/** - * @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' +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } - return 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' - ) - ) + 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 = { File, FileLike, isFileLike } +module.exports = stream /***/ }), -/***/ 72015: +/***/ 6923: /***/ ((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) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const { AsyncResource } = __nccwpck_require__(852) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } -// 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'] - }) + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - this[kState] = [] - } + const { signal, opaque, responseHeaders } = opts - append (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + super('UNDICI_UPGRADE') - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" - ) - } + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null - // 1. Let value be value if given; otherwise blobValue. + addSignal(this, signal) + } - 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 + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - // 2. Let entry be the result of creating an entry with - // name, value, and filename if given. - const entry = makeEntry(name, value, filename) + this.abort = abort + this.context = null + } - // 3. Append entry to this’s entry list. - this[kState].push(entry) + onHeaders () { + throw new SocketError('bad upgrade', null) } - delete (name) { - webidl.brandCheck(this, FormData) + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) + assert.strictEqual(statusCode, 101) - name = webidl.converters.USVString(name) + removeSignal(this) - // 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) + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) } - get (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + onError (err) { + const { callback, opaque } = this - name = webidl.converters.USVString(name) + removeSignal(this) - // 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 + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } + } +} - // 2. Return the value of the first entry whose name is name from - // this’s entry list. - return this[kState][idx].value +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } - getAll (name) { - webidl.brandCheck(this, FormData) + 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 })) + } +} - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) +module.exports = upgrade - 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) +/***/ 4059: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) +"use strict"; - 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 - } +module.exports.request = __nccwpck_require__(5448) +module.exports.stream = __nccwpck_require__(5395) +module.exports.pipeline = __nccwpck_require__(8752) +module.exports.upgrade = __nccwpck_require__(6923) +module.exports.connect = __nccwpck_require__(9744) - 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'" - ) - } +/***/ 3858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // The set(name, value) and set(name, blobValue, filename) method steps - // are: +"use strict"; +// Ported from https://github.com/nodejs/undici/pull/907 - // 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) +const assert = __nccwpck_require__(9491) +const { Readable } = __nccwpck_require__(2781) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3983) - // 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) - } - } +let Blob - entries () { - webidl.brandCheck(this, FormData) +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key+value' - ) - } +const noop = () => {} - keys () { - webidl.brandCheck(this, FormData) +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key' - ) - } + this._readableState.dataEmitted = false - values () { - webidl.brandCheck(this, FormData) + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'value' - ) + // 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 } - /** - * @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'." - ) + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this } - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() } - } -} -FormData.prototype[Symbol.iterator] = FormData.prototype.entries + if (err) { + this[kAbort]() + } -Object.defineProperties(FormData.prototype, { - [Symbol.toStringTag]: { - value: 'FormData', - configurable: true + return super.destroy(err) } -}) - -/** - * @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: + 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) + } - // 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 }) + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true } + return super.on(ev, ...args) + } - // 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 - } + addListener (ev, ...args) { + return this.on(ev, ...args) + } - value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile - ? new File([value], filename, options) - : new FileLike(value, filename, options) + 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 } - // 4. Return an entry whose name is name and whose value is value. - return { name, value } -} + removeListener (ev, ...args) { + return this.off(ev, ...args) + } -module.exports = { FormData } + 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') + } -/***/ 71246: -/***/ ((module) => { + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } -"use strict"; + // 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() + } -// In case of breaking changes, increase the version -// number to avoid conflicts. -const globalOrigin = Symbol.for('undici.globalOrigin.1') + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } -function getGlobalOrigin () { - return globalThis[globalOrigin] -} + // 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] + } -function setGlobalOrigin (newOrigin) { - if (newOrigin === undefined) { - Object.defineProperty(globalThis, globalOrigin, { - value: undefined, - writable: true, - enumerable: false, - configurable: false - }) + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal - return - } + 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) + } + } - const parsedURL = new URL(newOrigin) + if (this.closed) { + return Promise.resolve(null) + } - if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { - throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) - } + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop - Object.defineProperty(globalThis, globalOrigin, { - value: parsedURL, - writable: true, - enumerable: false, - configurable: false - }) + 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() + }) + } } -module.exports = { - getGlobalOrigin, - setGlobalOrigin +// 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') + } -/***/ 10554: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + assert(!stream[kConsume]) -"use strict"; -// https://github.com/Ethan-Arrowood/undici-fetch + 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]) + }) +} -const { kHeadersList, kConstruct } = __nccwpck_require__(72785) -const { kGuard } = __nccwpck_require__(15861) -const { kEnumerableProperty } = __nccwpck_require__(83983) -const { - makeIterator, - isValidHeaderName, - isValidHeaderValue -} = __nccwpck_require__(52538) -const util = __nccwpck_require__(73837) -const { webidl } = __nccwpck_require__(21744) -const assert = __nccwpck_require__(39491) +function consumeStart (consume) { + if (consume.body === null) { + return + } -const kHeadersMap = Symbol('headers map') -const kHeadersSortedMap = Symbol('headers map sorted') + const { _readableState: state } = consume.stream -/** - * @param {number} code - */ -function isHTTPWhiteSpaceCharCode (code) { - return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 -} + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } -/** - * @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 + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + consume.stream.resume() - return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) + while (consume.stream.read() != null) { + // Loop + } } -function fill (headers, object) { - // To fill a Headers object headers with a given object object, run these steps: +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume - // 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}.` - }) + 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 } - // 2. Append (header’s first item, header’s second item) to headers. - appendHeader(headers, header[0], header[1]) + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = (__nccwpck_require__(4300).Blob) + } + resolve(new Blob(body, { type: stream[kContentType] })) } - } 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'] - }) + consumeFinish(consume) + } catch (err) { + stream.destroy(err) } } -/** - * @see https://fetch.spec.whatwg.org/#concept-headers-append - */ -function appendHeader (headers, name, value) { - // 1. Normalize value. - value = headerValueNormalize(value) +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} - // 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' - }) +function consumeFinish (consume, err) { + if (consume.body === null) { + return } - // 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 + if (err) { + consume.reject(err) + } else { + consume.resolve() } - // 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 + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null } -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 - } +/***/ 7474: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // https://fetch.spec.whatwg.org/#concept-header-list-append - append (name, value) { - this[kHeadersSortedMap] = null +const assert = __nccwpck_require__(9491) +const { + ResponseStatusCodeError +} = __nccwpck_require__(8045) +const { toUSVString } = __nccwpck_require__(3983) - // 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) +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) - // 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 }) - } + let chunks = [] + let limit = 0 - if (lowercaseName === 'set-cookie') { - this.cookies ??= [] - this.cookies.push(value) + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break } } - // 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 }) + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return } - // https://fetch.spec.whatwg.org/#concept-header-list-delete - delete (name) { - this[kHeadersSortedMap] = null - - name = name.toLowerCase() - - if (name === 'set-cookie') { - this.cookies = null + 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 } - 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] + 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 } - get entries () { - const headers = {} + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} - if (this[kHeadersMap].size) { - for (const { name, value } of this[kHeadersMap].values()) { - headers[name] = value - } - } +module.exports = { getResolveErrorBodyCallback } - 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: +/***/ 7931: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 1. Set this’s guard to "none". - this[kGuard] = 'none' +"use strict"; - // 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) +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(3198) +const Pool = __nccwpck_require__(4634) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const { parseOrigin } = __nccwpck_require__(3983) +const kFactory = Symbol('factory') - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) +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') - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} - return appendHeader(this, name, value) - } +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} - // https://fetch.spec.whatwg.org/#dom-headers-delete - delete (name) { - webidl.brandCheck(this, Headers) +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 - name = webidl.converters.ByteString(name) + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 - // 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' - }) + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] } - // 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 + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') } - // 6. If this’s header list does not contain name, then - // return. - if (!this[kHeadersList].contains(name)) { - return - } + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory - // 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) + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() } - // 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) + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - // 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' - }) + 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])) - // 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) + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) - name = webidl.converters.ByteString(name) + 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() + } + }) - // 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' - }) + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] } - // 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) + this._updateBalancedPoolStats() - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) + return this + } - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) + } - // 1. Normalize value. - value = headerValueNormalize(value) + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - // 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' - }) - } + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) - // 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 + if (pool) { + this[kRemoveClient](pool) } - // 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) + return this } - // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie - getSetCookie () { - webidl.brandCheck(this, Headers) + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } - // 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. + [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 list = this[kHeadersList].cookies + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) - if (list) { - return [...list] + if (!dispatcher) { + return } - return [] - } + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine - get [kHeadersSortedMap] () { - if (this[kHeadersList][kHeadersSortedMap]) { - return this[kHeadersList][kHeadersSortedMap] + if (allClientsBusy) { + return } - // 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 + let counter = 0 - // 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. + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) - // 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: + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] - // 1. Let value be the result of getting name from list. + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } - // 2. Assert: value is non-null. - assert(value !== null) + // 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] - // 3. Append (name, value) to headers. - headers.push([name, value]) + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool } } - this[kHeadersList][kHeadersSortedMap] = headers - - // 4. Return headers. - return headers + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] } +} - keys () { - webidl.brandCheck(this, Headers) +module.exports = BalancedPool - 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) +/***/ 6101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'value') - } +"use strict"; - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'value' - ) - } - entries () { - webidl.brandCheck(this, Headers) +const { kConstruct } = __nccwpck_require__(9174) +const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(2396) +const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3983) +const { kHeadersList } = __nccwpck_require__(2785) +const { webidl } = __nccwpck_require__(1744) +const { Response, cloneResponse } = __nccwpck_require__(7823) +const { Request } = __nccwpck_require__(8359) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { fetching } = __nccwpck_require__(4881) +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(2538) +const assert = __nccwpck_require__(9491) +const { getGlobalDispatcher } = __nccwpck_require__(1892) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key+value') - } +/** + * @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 + */ - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key+value' - ) - } +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ +class Cache { /** - * @param {(value: string, key: string, self: Headers) => void} callbackFn - * @param {unknown} thisArg + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) + #relevantRequestResponseList - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." - ) + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() } - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) - } + this.#relevantRequestResponseList = arguments[1] } - [Symbol.for('nodejs.util.inspect.custom')] () { - webidl.brandCheck(this, Headers) + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) - return this[kHeadersList] - } -} + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) -Headers.prototype[Symbol.iterator] = Headers.prototype.entries + const p = await this.matchAll(request, options) -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 - }, - [util.inspect.custom]: { - enumerable: false + if (p.length === 0) { + return + } + + return p[0] } -}) -webidl.converters.HeadersInit = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (V[Symbol.iterator]) { - return webidl.converters['sequence>'](V) + 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] + } } - return webidl.converters['record'](V) - } + // 5. + // 5.1 + const responses = [] - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] - }) -} + // 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) -module.exports = { - fill, - Headers, - HeadersList -} + // 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 = [] -/***/ 74881: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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' -"use strict"; -// https://github.com/Ethan-Arrowood/undici-fetch + responseList.push(responseObject) + } + // 6. + return Object.freeze(responseList) + } + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) -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'] + request = webidl.converters.RequestInfo(request) -/** @type {import('buffer').resolveObjectURL} */ -let resolveObjectURL -let ReadableStream = globalThis.ReadableStream + // 1. + const requests = [request] -class Fetch extends EE { - constructor (dispatcher) { - super() + // 2. + const responseArrayPromise = this.addAll(requests) - 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) + // 3. + return await responseArrayPromise } - terminate (reason) { - if (this.state !== 'ongoing') { - return - } + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) - this.state = 'terminated' - this.connection?.destroy(reason) - this.emit('terminated', reason) - } + requests = webidl.converters['sequence'](requests) - // https://fetch.spec.whatwg.org/#fetch-controller-abort - abort (error) { - if (this.state !== 'ongoing') { - return - } + // 1. + const responsePromises = [] - // 1. Set controller’s state to "aborted". - this.state = 'aborted' + // 2. + const requestList = [] - // 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') - } + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } - // 4. Let serializedError be StructuredSerialize(error). - // If that threw an exception, catch it, and let - // serializedError be StructuredSerialize(fallbackError). + // 3.1 + const r = request[kState] - // 5. Set controller’s serialized abort reason to serializedError. - this.serializedAbortReason = error + // 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.' + }) + } + } - this.connection?.destroy(error) - this.emit('terminated', error) - } -} + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] -// https://fetch.spec.whatwg.org/#fetch-method -function fetch (input, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] - // 1. Let p be a new promise. - const p = createDeferredPromise() + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) + } - // 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 + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' - try { - requestObject = new Request(input, init) - } catch (e) { - p.reject(e) - return p.promise - } + // 5.5 + requestList.push(r) - // 3. Let request be requestObject’s request. - const request = requestObject[kState] + // 5.6 + const responsePromise = createDeferredPromise() - // 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) + // 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. Return p. - return p.promise - } + // 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' + })) - // 5. Let globalObject be request’s client’s global object. - const globalObject = request.client.globalObject + for (const controller of fetchControllers) { + controller.abort() + } - // 6. If globalObject is a ServiceWorkerGlobalScope object, then set - // request’s service-workers mode to "none". - if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { - request.serviceWorkers = 'none' - } + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } - // 7. Let responseObject be null. - let responseObject = null + // 2. + responsePromise.resolve(response) + } + })) - // 8. Let relevantRealm be this’s relevant Realm. - const relevantRealm = null + // 5.8 + responsePromises.push(responsePromise.promise) + } - // 9. Let locallyAborted be false. - let locallyAborted = false + // 6. + const p = Promise.all(responsePromises) - // 10. Let controller be null. - let controller = null + // 7. + const responses = await p - // 11. Add the following abort steps to requestObject’s signal: - addAbortListener( - requestObject.signal, - () => { - // 1. Set locallyAborted to true. - locallyAborted = true + // 7.1 + const operations = [] - // 2. Assert: controller is non-null. - assert(controller != null) + // 7.2 + let index = 0 - // 3. Abort controller with requestObject’s signal’s abort reason. - controller.abort(requestObject.signal.reason) + // 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 + } - // 4. Abort the fetch() call with p, request, responseObject, - // and requestObject’s signal’s abort reason. - abortFetch(p, request, responseObject, requestObject.signal.reason) + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 } - ) - // 12. Let handleFetchDone given response response be to finalize and - // report timing with response, globalObject, and "fetch". - const handleFetchDone = (response) => - finalizeAndReportTiming(response, 'fetch') + // 7.5 + const cacheJobPromise = createDeferredPromise() - // 13. Set controller to the result of calling fetch given request, - // with processResponseEndOfBody set to handleFetchDone, and processResponse - // given response being these substeps: + // 7.6.1 + let errorData = null - const processResponse = (response) => { - // 1. If locallyAborted is true, terminate these substeps. - if (locallyAborted) { - return Promise.resolve() + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e } - // 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. + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) - // 2. Abort the fetch() call with p, request, responseObject, and - // deserializedError. + // 7.7 + return cacheJobPromise.promise + } - abortFetch(p, request, responseObject, controller.serializedAbortReason) - return Promise.resolve() - } + async put (request, response) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) - // 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() + 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. 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 + // 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. Resolve p with responseObject. - p.resolve(responseObject) - } + // 5. + const innerResponse = response[kState] - controller = fetching({ - request, - processResponseEndOfBody: handleFetchDone, - processResponse, - dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici - }) + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) + } - // 14. Return p. - return p.promise -} + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) -// 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 - } + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } + } - // 2. If response’s URL list is null or empty, then return. - if (!response.urlList?.length) { - return - } + // 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' + }) + } - // 3. Let originalURL be response’s URL list[0]. - const originalURL = response.urlList[0] + // 9. + const clonedResponse = cloneResponse(innerResponse) - // 4. Let timingInfo be response’s timing info. - let timingInfo = response.timingInfo + // 10. + const bodyReadPromise = createDeferredPromise() - // 5. Let cacheState be response’s cache state. - let cacheState = response.cacheState + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream - // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. - if (!urlIsHttpHttpsScheme(originalURL)) { - return - } + // 11.2 + const reader = stream.getReader() - // 7. If timingInfo is null, then return. - if (timingInfo === null) { - return - } + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } - // 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 - }) + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] - // 2. Set cacheState to the empty string. - cacheState = '' - } + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } - // 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() + // 17. + operations.push(operation) - // 10. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo + // 19. + const bytes = await bodyReadPromise.promise - // 11. Mark resource timing for timingInfo, originalURL, initiatorType, - // global, and cacheState. - markResourceTiming( - timingInfo, - originalURL, - initiatorType, - globalThis, - cacheState - ) -} + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } -// 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) - } -} + // 19.1 + const cacheJobPromise = createDeferredPromise() -// 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') - } + // 19.2.1 + let errorData = null - // 1. Reject promise with error. - p.reject(error) + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } - // 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 + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) } - throw err }) - } - // 3. If responseObject is null, then return. - if (responseObject == null) { - return + return cacheJobPromise.promise } - // 4. Let response be responseObject’s response. - const response = responseObject[kState] + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) - // 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 + 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 } - throw err - }) - } -} + } else { + assert(typeof request === 'string') -// 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 + r = new Request(request)[kState] + } - // 2. Let crossOriginIsolatedCapability be false. - let crossOriginIsolatedCapability = false + /** @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 + } - // 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 + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) - // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin - // isolated capability. - crossOriginIsolatedCapability = - request.client.crossOriginIsolatedCapability + return cacheJobPromise.promise } - // 4. If useParallelQueue is true, then set taskDestination to the result of - // starting a new parallel queue. - // TODO + /** + * @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) - // 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 - }) + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - // 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 - } + // 1. + let r = null - // 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) + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] - // 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' - } + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } + } - // 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 - } + // 4. + const promise = createDeferredPromise() - // 10. If all of the following conditions are true: - // TODO + // 5. + // 5.1 + const requests = [] - // 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() + // 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]) + } } - } - // 12. If request’s header list does not contain `Accept`, then: - if (!request.headersList.contains('accept')) { - // 1. Let value be `*/*`. - const value = '*/*' + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] - // 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 + // 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 - // 3. Append `Accept`/value to request’s header list. - request.headersList.append('accept', value) - } + // 5.4.2.1 + requestList.push(requestObject) + } - // 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', '*') - } + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) - // 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 + return promise.promise } - // 15. If request is a subresource request, then: - if (subresourceSet.has(request.destination)) { - // TODO - } + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList - // 16. Run main fetch given fetchParams. - mainFetch(fetchParams) - .catch(err => { - fetchParams.controller.terminate(err) - }) + // 2. + const backupCache = [...cache] - // 17. Return fetchParam's controller - return fetchParams.controller -} + // 3. + const addedItems = [] -// 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 + // 4.1 + const resultList = [] - // 2. Let response be null. - let response = null + 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"' + }) + } - // 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.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. Run report Content Security Policy violations for request. - // TODO + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } - // 5. Upgrade request to a potentially trustworthy URL, if appropriate. - tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + // 4.2.4 + let requestResponses - // 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? + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) - // 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 - } + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } - // 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) - } + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - // 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 + // 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' + }) + } - // 10. If recursive is false, then run the remaining steps in parallel. - // TODO + // 4.2.6.2 + const r = operation.request - // 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) + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } - 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' + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } - // 2. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } - // request’s mode is "same-origin" - if (request.mode === 'same-origin') { - // 1. Return a network error. - return makeNetworkError('request mode cannot be "same-origin"') - } + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) - // 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' - ) - } + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - // 2. Set request’s response tainting to "opaque". - request.responseTainting = 'opaque' + // 4.2.6.7.1 + cache.splice(idx, 1) + } - // 3. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } + // 4.2.6.8 + cache.push([operation.request, operation.response]) - // 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') + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } + + // 4.2.7 + resultList.push([operation.request, operation.response]) } - // - 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 + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 - // Otherwise - // 1. Set request’s response tainting to "cors". - request.responseTainting = 'cors' + // 5.2 + this.#relevantRequestResponseList = backupCache - // 2. Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) - })() + // 5.3 + throw e + } } - // 12. If recursive is true, then return response. - if (recursive) { - return response - } + /** + * @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 = [] - // 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 - } + const storage = targetStorage ?? this.#relevantRequestResponseList - // 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) + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } } - } - - // 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) + return resultList } - // 16. If request’s timing allow failed flag is unset, then set - // internalResponse’s timing allow passed flag. - if (!request.timingAllowFailed) { - response.timingAllowPassed = true - } + /** + * @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 + // } - // 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 + const queryURL = new URL(requestQuery.url) - // 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() - } + const cachedURL = new URL(request.url) - // 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 - } + if (options?.ignoreSearch) { + cachedURL.search = '' - // 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)) + queryURL.search = '' + } - // 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 + if (!urlEquals(queryURL, cachedURL, true)) { + return false } - // 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 + 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 } - // 2. Set response’s body to bytes as a body. - response.body = safelyExtractBody(bytes)[0] + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) - // 3. Run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) + // 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 + } } - // 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) + return true } } -// 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)) +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 } +] - // 2. Let request be fetchParams’s request. - const { request } = fetchParams +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) - const { protocol: scheme } = requestCurrentURL(request) +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) - // 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. +webidl.converters.Response = webidl.interfaceConverter(Response) - // Otherwise, return a network error. - return Promise.resolve(makeNetworkError('about scheme is not supported')) - } - case 'blob:': { - if (!resolveObjectURL) { - resolveObjectURL = (__nccwpck_require__(14300).resolveObjectURL) - } +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) - // 1. Let blobURLEntry be request’s current URL’s blob URL entry. - const blobURLEntry = requestCurrentURL(request) +module.exports = { + Cache +} - // 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')) - } +/***/ 7907: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. - const bodyWithType = safelyExtractBody(blobURLEntryObject) +"use strict"; - // 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}`) +const { kConstruct } = __nccwpck_require__(9174) +const { Cache } = __nccwpck_require__(6101) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) - // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. - const type = bodyWithType[1] ?? '' +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map makeNetworkError(err)) - } - default: { - return Promise.resolve(makeNetworkError('unknown scheme')) + if (response !== undefined) { + return response + } + } } } -} -// https://fetch.spec.whatwg.org/#finalize-response -function finalizeResponse (fetchParams, response) { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-has + * @param {string} cacheName + * @returns {Promise} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) - // 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)) + cacheName = webidl.converters.DOMString(cacheName) + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) } -} -// 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]] + /** + * @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' }) - // 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 - }) - } + cacheName = webidl.converters.DOMString(cacheName) - // 2. Let processResponseEndOfBody be the following steps: - const processResponseEndOfBody = () => { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') - // 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)) + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) } - } - // 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)) - } + // 2.2 + const cache = [] - // 4. If response’s body is null, then run processResponseEndOfBody. - if (response.body == null) { - processResponseEndOfBody() - } else { - // 5. Otherwise: + // 2.3 + this.#caches.set(cacheName, cache) - // 1. Let transformStream be a new a TransformStream. + // 2.4 + return new Cache(kConstruct, cache) + } - // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, - // enqueues chunk in transformStream. - const identityTransformAlgorithm = (chunk, controller) => { - controller.enqueue(chunk) - } + /** + * @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' }) - // 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 - } - }) + cacheName = webidl.converters.DOMString(cacheName) - // 4. Set response’s body to the result of piping response’s body through transformStream. - response.body = { stream: response.body.stream.pipeThrough(transformStream) } + return this.#caches.delete(cacheName) } - // 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) + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) - // 2. Let processBodyError be this step: run fetchParams’s process - // response consume body given response and failure. - const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + // 2.1 + const keys = this.#caches.keys() - // 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() + // 2.2 + return [...keys] } } -// https://fetch.spec.whatwg.org/#http-fetch -async function httpFetch (fetchParams) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) - // 2. Let response be null. - let response = null +module.exports = { + CacheStorage +} - // 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 - } +/***/ 9174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 6. If response is null, then: - if (response === null) { - // 1. If makeCORSPreflight is true and one of these conditions is true: - // TODO +"use strict"; - // 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) +module.exports = { + kConstruct: (__nccwpck_require__(2785).kConstruct) +} - // 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') - } +/***/ 2396: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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() - } +"use strict"; - // 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 +const assert = __nccwpck_require__(9491) +const { URLSerializer } = __nccwpck_require__(685) +const { isValidHeaderName } = __nccwpck_require__(2538) - // 10. Return response. - return response -} +/** + * @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) -// https://fetch.spec.whatwg.org/#http-redirect-fetch -function httpRedirectFetch (fetchParams, response) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request + const serializedB = URLSerializer(B, excludeFragment) - // 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 + return serializedA === serializedB +} - // 3. Let locationURL be actualResponse’s location URL given request’s current - // URL’s fragment. - let locationURL +/** + * @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) - try { - locationURL = responseLocationURL( - actualResponse, - requestCurrentURL(request).hash - ) + const values = [] - // 4. If locationURL is null, then return response. - if (locationURL == null) { - return response + for (let value of header.split(',')) { + value = value.trim() + + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue } - } 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')) + values.push(value) } - // 7. If request’s redirect count is 20, then return a network error. - if (request.redirectCount === 20) { - return Promise.resolve(makeNetworkError('redirect count exceeded')) - } + return values +} - // 8. Increase request’s redirect count by 1. - request.redirectCount += 1 +module.exports = { + urlEquals, + fieldValues +} - // 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()) - } +/***/ 3598: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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 +"use strict"; +// @ts-check - // 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) +/* global WebAssembly */ - // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. - request.headersList.delete('cookie') - request.headersList.delete('host') - } +const assert = __nccwpck_require__(9491) +const net = __nccwpck_require__(1808) +const http = __nccwpck_require__(3685) +const { pipeline } = __nccwpck_require__(2781) +const util = __nccwpck_require__(3983) +const timers = __nccwpck_require__(9459) +const Request = __nccwpck_require__(2905) +const DispatcherBase = __nccwpck_require__(4839) +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) +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__(2785) - // 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] - } +/** @type {import('http2')} */ +let http2 +try { + http2 = __nccwpck_require__(5158) +} catch { + // @ts-ignore + http2 = { constants: {} } +} - // 15. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo +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 - // 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) +// Experimental +let h2ExperimentalWarned = false - // 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 - } +const FastBuffer = Buffer[Symbol.species] - // 18. Append locationURL to request’s URL list. - request.urlList.push(locationURL) +const kClosedResolve = Symbol('kClosedResolve') - // 19. Invoke set request’s referrer policy on redirect on request and - // actualResponse. - setRequestReferrerPolicyOnRedirect(request, actualResponse) +const channels = {} - // 20. Return the result of running main fetch given fetchParams and true. - return mainFetch(fetchParams, true) +try { + const diagnosticsChannel = __nccwpck_require__(7643) + 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 } } -// 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 +/** + * @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() - // 3. Let httpRequest be null. - let httpRequest = null + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } - // 4. Let response be null. - let response = null + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } - // 5. Let storedResponse be null. - // TODO: cache + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } - // 6. Let httpCache be null. - const httpCache = null + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } - // 7. Let the revalidatingFlag be unset. - const revalidatingFlag = false + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } - // 8. Run these steps, but abort when the ongoing fetch is terminated: + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } - // 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: + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } - // 1. Set httpRequest to a clone of request. - httpRequest = makeRequest(request) + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } - // 2. Set httpFetchParams to a copy of fetchParams. - httpFetchParams = { ...fetchParams } + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } - // 3. Set httpFetchParams’s request to httpRequest. - httpFetchParams.request = httpRequest - } + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } - // 3. Let includeCredentials be true if one of - const includeCredentials = - request.credentials === 'include' || - (request.credentials === 'same-origin' && - request.responseTainting === 'basic') + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } - // 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 + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } - // 5. Let contentLengthHeaderValue be null. - let contentLengthHeaderValue = null + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } - // 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' - } + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } - // 7. If contentLength is non-null, then set contentLengthHeaderValue to - // contentLength, serialized and isomorphic encoded. - if (contentLength != null) { - contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) - } + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - // 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) - } + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } - // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, - // contentLengthHeaderValue) to httpRequest’s header list. + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } - // 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. - } + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } - // 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)) - } + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } - // 12. Append a request `Origin` header for httpRequest. - appendRequestOriginHeader(httpRequest) + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } - // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] - appendFetchMetadata(httpRequest) + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') + } - // 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') - } + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } - // 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' - } + 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' - // 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') - } + // 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}` : ''}` - // 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') - } + // 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). - // 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') - } + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 } - // 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') + get pipelining () { + return this[kPipelining] } - // 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') - } + set pipelining (value) { + this[kPipelining] = value + resume(this, true) } - 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 + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] } - // 21. If there’s a proxy-authentication entry, use it as appropriate. - // TODO: proxy-authentication + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } - // 22. Set httpCache to the result of determining the HTTP cache - // partition, given httpRequest. - // TODO: cache + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } - // 23. If httpCache is null, then set httpRequest’s cache mode to - // "no-store". - if (httpCache == null) { - httpRequest.cache = 'no-store' + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed } - // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", - // then: - if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { - // TODO: cache + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) } - // 9. If aborted, then return the appropriate network error for fetchParams. - // TODO + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } - // 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') - } + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin - // 2. Let forwardResponse be the result of running HTTP-network fetch - // given httpFetchParams, includeCredentials, and isNewConnectionFetch. - const forwardResponse = await httpNetworkFetch( - httpFetchParams, - includeCredentials, - isNewConnectionFetch - ) + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler) - // 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 + 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) } - // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, - // then: - if (revalidatingFlag && forwardResponse.status === 304) { - // TODO: cache + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 } - // 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 - } + return this[kNeedDrain] < 2 } - // 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 + 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 + } + }) } - // 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() - } + 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) + } - // 2. ??? + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } - // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) - } + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null + } - // 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? + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) + } - // 5. Set response to the result of running HTTP-network-or-cache fetch given - // fetchParams. - // TODO - return makeNetworkError('proxy authentication required') + resume(this) + }) } +} - // 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) - } +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - // 2. Set response to the result of running HTTP-network-or-cache - // fetch given fetchParams, isAuthenticationFetch, and true. + this[kSocket][kError] = err - // 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() + onError(this[kClient], err) +} - response = await httpNetworkOrCacheFetch( - fetchParams, - isAuthenticationFetch, - true - ) - } +function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - // 17. If isAuthenticationFetch is true, then create an authentication entry - if (isAuthenticationFetch) { - // TODO + if (id === 0) { + this[kSocket][kError] = err + onError(this[kClient], err) } +} - // 18. Return response. - return response +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) } -// https://fetch.spec.whatwg.org/#http-network-fetch -async function httpNetworkFetch ( - fetchParams, - includeCredentials = false, - forceNewConnection = false -) { - assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) +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 - 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')) - } + 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) } - // 1. Let request be fetchParams’s request. - const request = fetchParams.request + client[kPendingIdx] = client[kRunningIdx] - // 2. Let response be null. - let response = null + assert(client[kRunning] === 0) - // 3. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo + client.emit('disconnect', + client[kUrl], + [client], + err + ) - // 4. Let httpCache be the result of determining the HTTP cache partition, - // given request. - // TODO: cache - const httpCache = null + resume(client) +} - // 5. If httpCache is null, then set request’s cache mode to "no-store". - if (httpCache == null) { - request.cache = 'no-store' - } +const constants = __nccwpck_require__(953) +const createRedirectInterceptor = __nccwpck_require__(8861) +const EMPTY_BUF = Buffer.alloc(0) - // 6. Let networkPartitionKey be the result of determining the network - // partition key given request. - // TODO +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(1145) : undefined - // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise - // "no". - const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + let mod + try { + mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(5627), 'base64')) + } catch (e) { + /* istanbul ignore next */ - // 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 + // 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__(1145), 'base64')) } - // 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. + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ - // 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. + 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 + } - // 4. Set timingInfo’s final network-request start time to the coarsened - // shared current time given fetchParams’s cross-origin isolated - // capability. + /* eslint-enable camelcase */ + } + }) +} - // 5. Set response to the result of making an HTTP request over connection - // using request with the following caveats: +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() - // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] - // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null - // - 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. +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 - // - 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). +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) - // - Wait until all the headers are transmitted. + 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) - // - 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. + this.bytesRead = 0 - // - If request’s header list contains `Transfer-Encoding`/`chunked` and - // response is transferred via HTTP/1.0 or older, then return a network - // error. + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } - // - If the HTTP request results in a TLS client certificate dialog, then: + 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() + } + } + } - // 1. If request’s window is an environment settings object, make the - // dialog available in request’s window. + resume () { + if (this.socket.destroyed || !this.paused) { + return + } - // 2. Otherwise, return a network error. + assert(this.ptr != null) + assert(currentParser == null) - // 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: + this.llhttp.llhttp_resume(this.ptr) - // 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 + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() } + } - // 2. Run this step in parallel: transmit bytes. - yield bytes + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } - // 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) + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) } + } - // 2. Let processEndOfBody be these steps: - const processEndOfBody = () => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) + + const { socket, llhttp } = this - // 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() + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) } - // 3. Let processBodyError given e be these steps: - const processBodyError = (e) => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) - // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. - if (e.name === 'AbortError') { - fetchParams.controller.abort() - } else { - fetchParams.controller.terminate(e) - } - } + // 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 - // 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() + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ } catch (err) { - processBodyError(err) + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null } - })() - } - - 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() + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr - response = makeResponse({ status, statusText, headersList }) + 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) } - } 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) - } + destroy () { + assert(this.ptr != null) + assert(currentParser == null) - return makeNetworkError(err) - } + this.llhttp.llhttp_free(this.ptr) + this.ptr = null - // 11. Let pullAlgorithm be an action that resumes the ongoing fetch - // if it is suspended. - const pullAlgorithm = () => { - fetchParams.controller.resume() - } + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null - // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s - // controller with reason, given reason. - const cancelAlgorithm = (reason) => { - fetchParams.controller.abort(reason) + this.paused = false } - // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by - // the user agent. - // TODO + onStatus (buf) { + this.statusText = buf.toString() + } - // 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 + onMessageBegin () { + const { socket, client } = this - // 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) - } + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } - 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 - } + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 } - ) + } - // 17. Run these steps, but abort when the ongoing fetch is terminated: + onHeaderField (buf) { + const len = this.headers.length - // 1. Set response’s body to a new body whose stream is stream. - response.body = { stream } + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } - // 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 + this.trackHeader(buf.length) + } - // 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 + onHeaderValue (buf) { + let len = this.headers.length - // 18. If aborted, then: - // TODO + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } - // 19. Run these steps in parallel: + 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() + } - // 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... + this.trackHeader(buf.length) + } - // 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() + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } - if (isAborted(fetchParams)) { - break - } + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this - bytes = done ? undefined : value - } catch (err) { - if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { - // zlib doesn't like empty streams. - bytes = undefined - } else { - bytes = err + assert(upgrade) - // 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 - } - } + const request = client[kQueue][client[kRunningIdx]] + assert(request) - 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) + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') - finalizeResponse(fetchParams, response) + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null - return - } + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - // 5. Increase timingInfo’s decoded body size by bytes’s length. - timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + socket.unshift(head) - // 6. If bytes is failure, then terminate fetchParams’s controller. - if (isFailure) { - fetchParams.controller.terminate(bytes) - return - } + socket[kParser].destroy() + socket[kParser] = null - // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes - // into stream. - fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) - // 8. If stream is errored, then terminate the ongoing fetch. - if (isErrored(stream)) { - fetchParams.controller.terminate() - return - } + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) - // 9. If stream doesn’t need more data ask the user agent to suspend - // the ongoing fetch. - if (!fetchParams.controller.controller.desiredSize) { - return - } + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) } + + resume(client) } - // 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 + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this - // 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 - })) - } + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 } - // 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() - } + const request = client[kQueue][client[kRunningIdx]] - // 20. Return response. - return response + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } - async function dispatch ({ body }) { - const url = requestCurrentURL(request) - /** @type {import('../..').Agent} */ - const agent = fetchParams.controller.dispatcher + assert(!this.upgrade) + assert(this.statusCode < 200) - 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, + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } - onConnect (abort) { - // TODO (fix): Do we need connection here? - const { connection } = fetchParams.controller + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } - if (connection.destroyed) { - abort(new DOMException('The operation was aborted.', 'AbortError')) - } else { - fetchParams.controller.on('terminated', abort) - this.abort = connection.abort = abort - } - }, + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) - onHeaders (status, headersList, resume, statusText) { - if (status < 200) { - return - } + 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') + ) - let codings = [] - let location = '' + 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() + } + } - const headers = new Headers() + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } - // 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 - } + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } - 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 - } + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - headers[kHeadersList].append(key, val) - } - } + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null - this.body = new Readable({ read: resume }) + 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 decoders = [] + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false - const willFollow = request.redirect === 'follow' && - location && - redirectStatusSet.has(status) + if (request.aborted) { + return -1 + } - // 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 - } - } - } + if (request.method === 'HEAD') { + return 1 + } - resolve({ - status, - statusText, - headersList: headers[kHeadersList], - body: decoders.length - ? pipeline(this.body, ...decoders, () => { }) - : this.body.on('error', () => {}) - }) + if (statusCode < 200) { + return 1 + } - return true - }, + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } - onData (chunk) { - if (fetchParams.controller.dump) { - return - } + return pause ? constants.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this - // 1. If one or more bytes have been transmitted from response’s - // message body, then: + if (socket.destroyed) { + return -1 + } - // 1. Let bytes be the transmitted bytes. - const bytes = chunk + const request = client[kQueue][client[kRunningIdx]] + assert(request) - // 2. Let codings be the result of extracting header list values - // given `Content-Encoding` and response’s header list. - // See pullAlgorithm. + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } - // 3. Increase timingInfo’s encoded body size by bytes’s length. - timingInfo.encodedBodySize += bytes.byteLength + assert(statusCode >= 200) - // 4. See pullAlgorithm... + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } - return this.body.push(bytes) - }, + this.bytesRead += buf.length - onComplete () { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } - fetchParams.controller.ended = true + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this - this.body.push(null) - }, + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } - onError (error) { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } + if (upgrade) { + return + } - this.body?.destroy(error) + const request = client[kQueue][client[kRunningIdx]] + assert(request) - fetchParams.controller.terminate(error) + assert(statusCode >= 100) - reject(error) - }, + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' - onUpgrade (status, headersList, socket) { - if (status !== 101) { - return - } + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - const headers = new Headers() + if (statusCode < 200) { + return + } - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } - headers[kHeadersList].append(key, val) - } + request.onComplete(headers) - resolve({ - status, - statusText: STATUS_CODES[status], - headersList: headers[kHeadersList], - socket - }) + client[kQueue][client[kRunningIdx]++] = null - return true - } - } - )) + 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) + } } } -module.exports = { - fetch, - Fetch, - fetching, - finalizeAndReportTiming +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 -/***/ 48359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') -"use strict"; -/* globals AbortController */ + 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) +} -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) +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. -let TransformStream = globalThis.TransformStream + assert(client[kPendingIdx] === client[kRunningIdx]) -const kAbortController = Symbol('abortController') + 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) + } +} -const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { - signal.removeEventListener('abort', abort) -}) +function onSocketEnd () { + const { [kParser]: parser, [kClient]: client } = this -// https://fetch.spec.whatwg.org/#request-class -class Request { - // https://fetch.spec.whatwg.org/#dom-request - constructor (input, init = {}) { - if (input === kConstruct) { + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() return } + } - webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} - input = webidl.converters.RequestInfo(input) - init = webidl.converters.RequestInit(init) +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this - // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object - this[kRealm] = { - settingsObject: { - baseUrl: getGlobalOrigin(), - get origin () { - return this.baseUrl?.origin - }, - policyContainer: makePolicyContainer() - } + 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() } - // 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] }) + this[kParser].destroy() + this[kParser] = null + } - // 5. Set fallbackMode to "cors". - fallbackMode = 'cors' - } else { - // 6. Otherwise: + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) - // 7. Assert: input is a Request object. - assert(input instanceof Request) + client[kSocket] = null - // 8. Set request to input’s request. - request = input[kState] + if (client.destroyed) { + assert(client[kPending] === 0) - // 9. Set signal to input’s signal. - signal = input[kSignal] + // 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 - // 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' + errorRequest(client, request, err) + } - // 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 - } + client[kPendingIdx] = client[kRunningIdx] - // 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`) - } + assert(client[kRunning] === 0) - // 11. If init["window"] exists, then set window to "no-window". - if ('window' in init) { - window = 'no-window' - } + client.emit('disconnect', client[kUrl], [client], err) - // 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] - }) + resume(client) +} - const initHasKey = Object.keys(init).length !== 0 +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) - // 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' - } + let { host, hostname, protocol, port } = client[kUrl] - // 2. Unset request’s reload-navigation flag. - request.reloadNavigation = false + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') - // 3. Unset request’s history-navigation flag. - request.historyNavigation = false + assert(idx !== -1) + const ip = hostname.substring(1, idx) - // 4. Set request’s origin to "client". - request.origin = 'client' + assert(net.isIP(ip)) + hostname = ip + } - // 5. Set request’s referrer to "client" - request.referrer = 'client' + client[kConnecting] = true - // 6. Set request’s referrer policy to the empty string. - request.referrerPolicy = '' + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } - // 7. Set request’s URL to request’s current URL. - request.url = request.urlList[request.urlList.length - 1] + 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) + } + }) + }) - // 8. Set request’s URL list to Ā« request’s URL Ā». - request.urlList = [request.url] + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return } - // 14. If init["referrer"] exists, then: - if (init.referrer !== undefined) { - // 1. Let referrer be init["referrer"]. - const referrer = init.referrer + client[kConnecting] = false - // 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 }) - } + assert(socket) - // 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 - } + 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' + }) } - } - // 15. If init["referrerPolicy"] exists, then set request’s referrer policy - // to it. - if (init.referrerPolicy !== undefined) { - request.referrerPolicy = init.referrerPolicy - } + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) - // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. - let mode - if (init.mode !== undefined) { - mode = init.mode + 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 { - mode = fallbackMode + 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) } - // 17. If mode is "navigate", then throw a TypeError. - if (mode === 'navigate') { - throw webidl.errors.exception({ - header: 'Request constructor', - message: 'invalid request mode navigate.' - }) - } + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null - // 18. If mode is non-null, set request’s mode to mode. - if (mode != null) { - request.mode = mode - } + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) - // 19. If init["credentials"] exists, then set request’s credentials mode - // to it. - if (init.credentials !== undefined) { - request.credentials = init.credentials - } + client[kSocket] = socket - // 18. If init["cache"] exists, then set request’s cache mode to it. - if (init.cache !== undefined) { - request.cache = init.cache + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) } - - // 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" - ) + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return } - // 22. If init["redirect"] exists, then set request’s redirect mode to it. - if (init.redirect !== undefined) { - request.redirect = init.redirect - } + client[kConnecting] = false - // 23. If init["integrity"] exists, then set request’s integrity metadata to it. - if (init.integrity != null) { - request.integrity = String(init.integrity) + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) } - // 24. If init["keepalive"] exists, then set request’s keepalive to it. - if (init.keepalive !== undefined) { - request.keepalive = Boolean(init.keepalive) + 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) } - // 25. If init["method"] exists, then: - if (init.method !== undefined) { - // 1. Let method be init["method"]. - let method = init.method + client.emit('connectionError', client[kUrl], [client], err) + } - // 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.`) - } + resume(client) +} - if (forbiddenMethodsSet.has(method.toUpperCase())) { - throw new TypeError(`'${method}' HTTP method is unsupported.`) - } +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} - // 3. Normalize method. - method = normalizeMethodRecord[method] ?? normalizeMethod(method) +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } - // 4. Set request’s method to method. - request.method = method - } + client[kResuming] = 2 - // 26. If init["signal"] exists, then set signal to it. - if (init.signal !== undefined) { - signal = init.signal - } + _resume(client, sync) + client[kResuming] = 0 - // 27. Set this’s request to request. - this[kState] = request + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} - // 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] +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } - // 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 (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } - 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 socket = client[kSocket] - const acRef = new WeakRef(ac) - const abort = function () { - const ac = acRef.deref() - if (ac !== undefined) { - ac.abort(this.reason) - } + if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true } - - // 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 }) + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false } - } - - // 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.` - ) + 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) + } } - - // 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 + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) } else { - // 5. Otherwise, fill this’s headers with headers. - fillHeaders(this[kHeaders], headers) + emitDrain(client) } + continue } - // 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.') + if (client[kPending] === 0) { + return } - // 35. Let initBody be null. - let initBody = null + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } - // 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 + const request = client[kQueue][client[kPendingIdx]] - // 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) + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return } - } - // 37. Let inputOrInitBody be initBody if it is non-null; otherwise - // inputBody. - const inputOrInitBody = initBody ?? inputBody + client[kServerName] = request.servername - // 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.') + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return } + } - // 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"' - ) - } + if (client[kConnecting]) { + return + } - // 3. Set this’s request’s use-CORS-preflight flag. - request.useCORSPreflightFlag = true + if (!socket && !client[kHTTP2Session]) { + connect(client) + return } - // 39. Let finalBody be inputOrInitBody. - let finalBody = inputOrInitBody + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } - // 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.' - ) - } + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } - // 2. Set finalBody to the result of creating a proxy for inputBody. - if (!TransformStream) { - TransformStream = (__nccwpck_require__(35356).TransformStream) - } + 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 + } - // 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 - } + 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 } - // 41. Set this’s request’s body to finalBody. - this[kState].body = finalBody + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } } +} - // Returns request’s HTTP method, which is "GET" by default. - get method () { - webidl.brandCheck(this, Request) +// 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' +} - // The method getter steps are to return this’s request’s method. - return this[kState].method +function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request) + return } - // Returns the URL of request as a string. - get url () { - webidl.brandCheck(this, Request) + const { body, method, path, host, upgrade, headers, blocking, reset } = request - // The url getter steps are to return this’s request’s URL, serialized. - return URLSerializer(this[kState].url) - } + // 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 - // 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) + // 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. - // The headers getter steps are to return this’s headers. - return this[kHeaders] + 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) } - // Returns the kind of resource requested by request, e.g., "document" - // or "script". - get destination () { - webidl.brandCheck(this, Request) + const bodyLength = util.bodyLength(body) - // The destination getter are to return this’s request’s destination. - return this[kState].destination + let contentLength = bodyLength + + if (contentLength === null) { + contentLength = request.contentLength } - // 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) + 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. - // 1. If this’s request’s referrer is "no-referrer", then return the - // empty string. - if (this[kState].referrer === 'no-referrer') { - return '' - } + contentLength = null + } - // 2. If this’s request’s referrer is "client", then return - // "about:client". - if (this[kState].referrer === 'client') { - return 'about:client' + // 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 } - // Return this’s request’s referrer, serialized. - return this[kState].referrer.toString() + process.emitWarning(new RequestContentLengthMismatchError()) } - // 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) + const socket = client[kSocket] - // The referrerPolicy getter steps are to return this’s request’s referrer policy. - return this[kState].referrerPolicy - } + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } - // 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) + errorRequest(client, request, err || new RequestAbortedError()) - // The mode getter steps are to return this’s request’s mode. - return this[kState].mode + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) } - // 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 + 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 } - // 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) + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. - // The cache getter steps are to return this’s request’s cache mode. - return this[kState].cache + socket[kReset] = true } - // 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 + if (reset != null) { + socket[kReset] = reset } - // 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) + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } - // The integrity getter steps are to return this’s request’s integrity - // metadata. - return this[kState].integrity + if (blocking) { + socket[kBlocking] = true } - // Returns a boolean indicating whether or not request can outlive the - // global in which it was created. - get keepalive () { - webidl.brandCheck(this, Request) + let header = `${method} ${path} HTTP/1.1\r\n` - // The keepalive getter steps are to return this’s request’s keepalive. - return this[kState].keepalive + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] } - // 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 + 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' } - // 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) + if (headers) { + header += headers + } - // The isHistoryNavigation getter steps are to return true if this’s request’s - // history-navigation flag is set; otherwise false. - return this[kState].historyNavigation + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) } - // 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) + /* 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') - // The signal getter steps are to return this’s signal. - return this[kSignal] + 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) } - get body () { - webidl.brandCheck(this, Request) + return true +} - return this[kState].body ? this[kState].body.stream : null - } +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request - get bodyUsed () { - webidl.brandCheck(this, Request) + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false } - get duplex () { - webidl.brandCheck(this, Request) + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } - return 'half' + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) } - // Returns a clone of request. - clone () { - webidl.brandCheck(this, Request) + if (request.aborted) { + return false + } - // 1. If this is unusable, then throw a TypeError. - if (this.bodyUsed || this.body?.locked) { - throw new TypeError('unusable') - } + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + const h2State = client[kHTTP2SessionState] - // 2. Let clonedRequest be the result of cloning this’s request. - const clonedRequest = cloneRequest(this[kState]) + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method - // 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] + 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 }) - // 4. Make clonedRequestObject’s signal follow this’s signal. - const ac = new AbortController() - if (this.signal.aborted) { - ac.abort(this.signal.reason) + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams } else { - util.addAbortListener( - this.signal, - () => { - ac.abort(this.signal.reason) - } - ) + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) } - clonedRequestObject[kSignal] = ac.signal - // 4. Return clonedRequestObject. - return clonedRequestObject + 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 } -} -mixinBody(Request) + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT -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 -} + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' -// https://fetch.spec.whatwg.org/#concept-request-clone -function cloneRequest (request) { - // To clone a request request, run these steps: + // 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 - // 1. Let newRequest be a copy of request, except for its body. - const newRequest = makeRequest({ ...request, body: null }) + // 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. - // 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) + 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) } - // 3. Return newRequest. - return newRequest -} + let contentLength = util.bodyLength(body) -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 + if (contentLength == null) { + contentLength = request.contentLength } -}) -webidl.converters.Request = webidl.interfaceConverter( - Request -) + 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. -// https://fetch.spec.whatwg.org/#requestinfo -webidl.converters.RequestInfo = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) + contentLength = null } - if (V instanceof Request) { - return webidl.converters.Request(V) + // 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()) } - return webidl.converters.USVString(V) -} + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } -webidl.converters.AbortSignal = webidl.interfaceConverter( - AbortSignal -) + session.ref() -// 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 + 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() } -]) -module.exports = { Request, makeRequest } + // 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() + } + }) -/***/ 27823: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + stream.once('end', () => { + request.onComplete([]) + }) -"use strict"; + 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() + } + }) -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) + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) -const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(35356).ReadableStream) -const textEncoder = new TextEncoder('utf-8') + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) -// https://fetch.spec.whatwg.org/#response-class -class Response { - // Creates network error Response. - static error () { - // TODO - const relevantRealm = { settingsObject: {} } + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) - // 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 - } + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) + + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) - // https://fetch.spec.whatwg.org/#dom-response-json - static json (data, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) - if (init !== null) { - init = webidl.converters.ResponseInit(init) + // 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) } + } +} - // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = textEncoder.encode( - serializeJavascriptValueToJSONString(data) - ) +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') - // 2. Let body be the result of extracting bytes. - const body = extractBody(bytes) + 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() + } + } + ) - // 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 + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) - // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). - initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + function onPipeData (chunk) { + request.onBodySent(chunk) + } - // 5. Return responseObject. - return responseObject + return } - // Creates a redirect Response that redirects to url with status status. - static redirect (url, status = 302) { - const relevantRealm = { settingsObject: {} } + let finished = false - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - url = webidl.converters.USVString(url) - status = webidl.converters['unsigned short'](status) + const onData = function (chunk) { + if (finished) { + return + } - // 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()) + if (!writer.write(chunk) && this.pause) { + this.pause() + } } catch (err) { - throw Object.assign(new TypeError('Failed to parse URL from ' + url), { - cause: err - }) + util.destroy(this, err) } - - // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatusSet.has(status)) { - throw new RangeError('Invalid status code ' + status) + } + const onDrain = function () { + if (finished) { + return } - // 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 + if (body.resume) { + body.resume() + } } - - // https://fetch.spec.whatwg.org/#dom-response - constructor (body = null, init = {}) { - if (body !== null) { - body = webidl.converters.BodyInit(body) + const onAbort = function () { + if (finished) { + return + } + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + const onFinished = function (err) { + if (finished) { + return } - init = webidl.converters.ResponseInit(init) - - // TODO - this[kRealm] = { settingsObject: {} } + finished = true - // 1. Set this’s response to a new response. - this[kState] = makeResponse({}) + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) - // 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] + socket + .off('drain', onDrain) + .off('error', onFinished) - // 3. Let bodyWithType be null. - let bodyWithType = null + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) - // 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 } + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } } - // 5. Perform initialize a response given this, init, and bodyWithType. - initializeResponse(this, init, bodyWithType) + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } } - // Returns response’s type, e.g., "cors". - get type () { - webidl.brandCheck(this, Response) + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) - // The type getter steps are to return this’s response’s type. - return this[kState].type + if (body.resume) { + body.resume() } - // Returns response’s URL, if it has one; otherwise the empty string. - get url () { - webidl.brandCheck(this, Response) - - const urlList = this[kState].urlList + socket + .on('drain', onDrain) + .on('error', onFinished) +} - // 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 +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') - if (url === null) { - return '' + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() } - return URLSerializer(url, true) - } + const buffer = Buffer.from(await body.arrayBuffer()) - // Returns whether response was obtained through a redirect. - get redirected () { - webidl.brandCheck(this, Response) + 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() + } - // 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 - } + request.onBodySent(buffer) + request.onRequestSent() - // Returns response’s status. - get status () { - webidl.brandCheck(this, Response) + if (!expectsPayload) { + socket[kReset] = true + } - // The status getter steps are to return this’s response’s status. - return this[kState].status + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) } +} - // Returns whether response’s status is an ok status. - get ok () { - webidl.brandCheck(this, Response) +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') - // 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 + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } } - // Returns response’s status message. - get statusText () { - webidl.brandCheck(this, Response) + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) - // The statusText getter steps are to return this’s response’s status - // message. - return this[kState].statusText - } + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) - // Returns response’s headers as Headers. - get headers () { - webidl.brandCheck(this, Response) + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) - // The headers getter steps are to return this’s headers. - return this[kHeaders] - } + 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] + } - get body () { - webidl.brandCheck(this, Response) + 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 this[kState].body ? this[kState].body.stream : null + return } - get bodyUsed () { - webidl.brandCheck(this, Response) - - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } + socket + .on('close', onDrain) + .on('drain', onDrain) - // Returns a clone of response. - clone () { - webidl.brandCheck(this, Response) + 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] + } - // 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.' - }) + if (!writer.write(chunk)) { + await waitForDrain() + } } - // 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 + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) } } -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: +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 - // 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 - ) + socket[kWriting] = true } - // 2. Let newResponse be a copy of response, except for its body. - const newResponse = makeResponse({ ...response, body: null }) + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this - // 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) - } + if (socket[kError]) { + throw socket[kError] + } - // 4. Return newResponse. - return newResponse -} + if (socket.destroyed) { + return false + } -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] : [] - } -} + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } -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' - }) -} + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } -function makeFilteredResponse (response, state) { - state = { - internalResponse: response, - ...state - } + process.emitWarning(new RequestContentLengthMismatchError()) + } - 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 + 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') + } } - }) -} -// 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. + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } - // 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. + this.bytesWritten += len - // 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. + const ret = socket.write(chunk) - 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. + socket.uncork() - return makeFilteredResponse(response, { - type: 'opaqueredirect', - status: 0, - statusText: '', - headersList: [], - body: null - }) - } else { - assert(false) + 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 } -} -// https://fetch.spec.whatwg.org/#appropriate-network-error -function makeAppropriateNetworkError (fetchParams, err = null) { - // 1. Assert: fetchParams is canceled. - assert(isCancelled(fetchParams)) + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() - // 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 })) -} + socket[kWriting] = false -// 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.') - } + if (socket[kError]) { + throw socket[kError] + } - // 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') + if (socket.destroyed) { + return } - } - // 3. Set response’s response’s status to init["status"]. - if ('status' in init && init.status != null) { - response[kState].status = init.status - } + 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. - // 4. Set response’s response’s status message to init["statusText"]. - if ('statusText' in init && init.statusText != null) { - response[kState].statusText = init.statusText - } + 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') + } - // 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) - } + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } - // 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 - }) + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } } - // 2. Set response's body to body's body. - response[kState].body = body.body + resume(client) + } - // 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) + 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) } } } -webidl.converters.ReadableStream = webidl.interfaceConverter( - ReadableStream -) +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} -webidl.converters.FormData = webidl.interfaceConverter( - FormData -) +module.exports = Client -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 }) - } +/***/ 6436: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { - return webidl.converters.BufferSource(V) - } +"use strict"; - if (util.isFormDataLike(V)) { - return webidl.converters.FormData(V, { strict: false }) - } - if (V instanceof URLSearchParams) { - return webidl.converters.URLSearchParams(V) +/* istanbul ignore file: only for Node 12 */ + +const { kConnected, kSize } = __nccwpck_require__(2785) + +class CompatWeakRef { + constructor (value) { + this.value = value } - return webidl.converters.DOMString(V) + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } } -// https://fetch.spec.whatwg.org/#bodyinit -webidl.converters.BodyInit = function (V) { - if (V instanceof ReadableStream) { - return webidl.converters.ReadableStream(V) +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer } - // Note: the spec doesn't include async iterables, - // this is an undici extension. - if (V?.[Symbol.asyncIterator]) { - return V + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } } - - 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 = 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 } -]) - -module.exports = { - makeNetworkError, - makeResponse, - makeAppropriateNetworkError, - filterResponse, - Response, - cloneResponse } /***/ }), -/***/ 15861: +/***/ 663: /***/ ((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 = { - kUrl: Symbol('url'), - kHeaders: Symbol('headers'), - kSignal: Symbol('signal'), - kState: Symbol('state'), - kGuard: Symbol('guard'), - kRealm: Symbol('realm') + maxAttributeValueSize, + maxNameValuePairSize } /***/ }), -/***/ 52538: +/***/ 1724: /***/ ((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) - -let supportedHashes = [] - -// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable -/** @type {import('crypto')|undefined} */ -let crypto - -try { - crypto = __nccwpck_require__(6113) - const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] - supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) -/* c8 ignore next 3 */ -} catch { -} +const { parseSetCookie } = __nccwpck_require__(4408) +const { stringify } = __nccwpck_require__(3121) +const { webidl } = __nccwpck_require__(1744) +const { Headers } = __nccwpck_require__(554) -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() -} +/** + * @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 + */ -// 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 - } +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) - // 2. Let location be the result of extracting header list values given - // `Location` and response’s header list. - let location = response.headersList.get('location') + webidl.brandCheck(headers, Headers, { strict: false }) - // 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)) - } + const cookie = headers.get('cookie') + const out = {} - // 4. If location is a URL whose fragment is null, then set location’s - // fragment to requestFragment. - if (location && !location.hash) { - location.hash = requestFragment + if (!cookie) { + return out } - // 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) + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') - // 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' + out[name.trim()] = value.join('=') } - // 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 + return out } /** - * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 - * @param {number} c + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} */ -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 - } -} +function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) -/** - * @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 -} + webidl.brandCheck(headers, Headers, { strict: false }) -/** - * @see https://fetch.spec.whatwg.org/#header-name - * @param {string} potentialValue - */ -function isValidHeaderName (potentialValue) { - return isValidHTTPToken(potentialValue) + 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 + }) } /** - * @see https://fetch.spec.whatwg.org/#header-value - * @param {string} potentialValue + * @param {Headers} headers + * @returns {Cookie[]} */ -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 - } +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) - if ( - potentialValue.includes('\0') || - potentialValue.includes('\r') || - potentialValue.includes('\n') - ) { - return false + const cookies = headers.getSetCookie() + + if (!cookies) { + return [] } - return true + return cookies.map((pair) => parseSetCookie(pair)) } -// 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. +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) - // 1. Let policy be the result of executing § 8.1 Parse a referrer policy - // from a Referrer-Policy header on actualResponse. + webidl.brandCheck(headers, Headers, { strict: false }) - // 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(',') + cookie = webidl.converters.Cookie(cookie) - // 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 - } - } - } + const str = stringify(cookie) - // 2. If policy is not the empty string, then set request’s referrer policy to policy. - if (policy !== '') { - request.referrerPolicy = policy + if (str) { + headers.append('Set-Cookie', stringify(cookie)) } } -// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check -function crossOriginResourcePolicyCheck () { - // TODO - return 'allowed' -} +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 + } +]) -// https://fetch.spec.whatwg.org/#concept-cors-check -function corsCheck () { - // TODO - return 'success' -} +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) + } -// https://fetch.spec.whatwg.org/#concept-tao-check -function TAOCheck () { - // TODO - return 'success' + 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 } -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 +/***/ 4408: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 2. Let header be a Structured Header whose value is a token. - let header = null +"use strict"; - // 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) +const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(663) +const { isCTLExcludingHtab } = __nccwpck_require__(3121) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) +const assert = __nccwpck_require__(9491) - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header - // TODO +/** + * @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 + } - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header - // TODO -} + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' -// 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 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 } - // 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) - } + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: - // 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. - } + // 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 + } - if (serializedOrigin) { - // 2. Append (`Origin`, serializedOrigin) to request’s header list. - request.headersList.append('origin', serializedOrigin) - } + // 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) } -} -function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { - // TODO - return performance.now() -} + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() -// 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 + // 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 } -} -// 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 + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. return { - referrerPolicy: 'strict-origin-when-cross-origin' + name, value, ...parseUnparsedAttributes(unparsedAttributes) } } -// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container -function clonePolicyContainer (policyContainer) { - return { - referrerPolicy: policyContainer.referrerPolicy +/** + * 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 } -} -// 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 + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) - // Note: policy cannot (shouldn't) be null or an empty string. - assert(policy) + let cookieAv = '' - // 2. Let environment be request’s client. + // 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: - let referrerSource = null + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } - // 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. + // Let the cookie-av string be the characters consumed in this step. - const globalOrigin = getGlobalOrigin() + let attributeName = '' + let attributeValue = '' - if (!globalOrigin || globalOrigin.origin === 'null') { - return 'no-referrer' - } + // 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 } - // 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 - } + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: - // 4. Let request’s referrerURL be the result of stripping referrerSource for - // use as a referrer. - let referrerURL = stripURLForReferrer(referrerSource) + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } - // 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) + // 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 result of serializing referrerURL is a string whose length is - // greater than 4096, set referrerURL to referrerOrigin. - if (referrerURL.toString().length > 4096) { - referrerURL = referrerOrigin + // 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) } - const areSameOrigin = sameOrigin(request, referrerURL) - const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && - !isURLPotentiallyTrustworthy(request.url) + // 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() - // 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) + // 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) - // 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 the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. - // 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' - } + 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. - // 3. Return referrerOrigin. - return referrerOrigin + // 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) } - 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 - } -} + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } -/** - * @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) + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) - // 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' - } + // 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). - // 3. Set url’s username to the empty string. - url.username = '' + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) - // 4. Set url’s password to the empty string. - url.password = '' + // 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 - // 5. Set url’s fragment to null. - url.hash = '' + // 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. - // 6. If the origin-only flag is true, then: - if (originOnly) { - // 1. Set url’s path to Ā« the empty string Ā». - url.pathname = '' + // 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) + } - // 2. Set url’s query to null. - url.search = '' - } + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() - // 7. Return url. - return url -} + // 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. -function isURLPotentiallyTrustworthy (url) { - if (!(url instanceof URL)) { - return false - } + // 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: - // If child of about, return true - if (url.href === 'about:blank' || url.href === 'about:srcdoc') { - return true - } + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } - // If scheme is data, return true - if (url.protocol === 'data:') return true + // 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. - // If file, return true - if (url.protocol === 'file:') return true + 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. - return isOriginPotentiallyTrustworthy(url.origin) + 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: - function isOriginPotentiallyTrustworthy (origin) { - // If origin is explicitly null, return false - if (origin == null || origin === 'null') return false + // 1. Let enforcement be "Default". + let enforcement = 'Default' - const originAsURL = new URL(origin) + 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' + } - // If secure, return true - if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { - return true + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' } - // 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 + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' } - // If any other, return false - return false - } -} + // 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 ??= [] -/** - * @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 + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } - // 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 - } + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} - // 3. If response is not eligible for integrity validation, return false. - // TODO +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} - // 4. If parsedMetadata is the empty set, return true. - if (parsedMetadata.length === 0) { - return true - } - // 5. Let metadata be the result of getting the strongest - // metadata from parsedMetadata. - const strongest = getStrongestMetadata(parsedMetadata) - const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) +/***/ }), - // 6. For each item in metadata: - for (const item of metadata) { - // 1. Let algorithm be the alg component of item. - const algorithm = item.algo +/***/ 3121: +/***/ ((module) => { - // 2. Let expectedValue be the val component of item. - const expectedValue = item.hash +"use strict"; - // 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. - // 3. Let actualValue be the result of applying algorithm to bytes. - let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') +/** + * @param {string} value + * @returns {boolean} + */ +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } - if (actualValue[actualValue.length - 1] === '=') { - if (actualValue[actualValue.length - 2] === '=') { - actualValue = actualValue.slice(0, -2) - } else { - actualValue = actualValue.slice(0, -1) - } - } + for (const char of value) { + const code = char.charCodeAt(0) - // 4. If actualValue is a case-sensitive match for expectedValue, - // return true. - if (compareBase64Mixed(actualValue, expectedValue)) { - return true + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false } } - - // 7. 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-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i - /** - * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata - * @param {string} metadata + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name */ -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 - - // 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) +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) - // 3. If token does not parse, continue to the next token. if ( - parsedToken === null || - parsedToken.groups === undefined || - parsedToken.groups.algo === undefined + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' ) { - // 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.toLowerCase() - - // 5. If algorithm is a hash function recognized by the user - // agent, add the parsed token to result. - if (supportedHashes.includes(algorithm)) { - result.push(parsedToken.groups) + throw new Error('Invalid cookie name') } } - - // 4. Return no metadata if empty is true, otherwise return result. - if (empty === true) { - return 'no metadata' - } - - return result } /** - * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + 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 getStrongestMetadata (metadataList) { - // Let algorithm be the algo component of the first item in metadataList. - // Can be sha256 - let algorithm = metadataList[0].algo - // If the algorithm is sha512, then it is the strongest - // and we can return immediately - if (algorithm[3] === '5') { - return algorithm - } +function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0) - for (let i = 1; i < metadataList.length; ++i) { - const metadata = metadataList[i] - // If the algorithm is sha512, then it is the strongest - // and we can break the loop immediately - if (metadata.algo[3] === '5') { - algorithm = 'sha512' - break - // If the algorithm is sha384, then a potential sha256 or sha384 is ignored - } else if (algorithm[3] === '3') { - continue - // algorithm is sha256, check if algorithm is sha384 and if so, set it as - // the strongest - } else if (metadata.algo[3] === '3') { - algorithm = 'sha384' + 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') } } - return algorithm } -function filterMetadataListByAlgorithm (metadataList, algorithm) { - if (metadataList.length === 1) { - return metadataList - } +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) - let pos = 0 - for (let i = 0; i < metadataList.length; ++i) { - if (metadataList[i].algo === algorithm) { - metadataList[pos++] = metadataList[i] + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') } } - - metadataList.length = pos - - return metadataList } /** - * Compares two base64 strings, allowing for base64url - * in the second string. - * -* @param {string} actualValue always base64 - * @param {string} expectedValue base64 or base64url - * @returns {boolean} + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain */ -function compareBase64Mixed (actualValue, expectedValue) { - if (actualValue.length !== expectedValue.length) { - return false - } - for (let i = 0; i < actualValue.length; ++i) { - if (actualValue[i] !== expectedValue[i]) { - if ( - (actualValue[i] === '+' && expectedValue[i] === '-') || - (actualValue[i] === '/' && expectedValue[i] === '_') - ) { - continue - } - return false - } +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') } - - return true -} - -// 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 - } + * @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] - // 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 - } + 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 - // 3. Return false. - return false -} + 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 -function createDeferredPromise () { - let res - let rej - const promise = new Promise((resolve, reject) => { - res = resolve - rej = reject - }) + GMT = %x47.4D.54 ; "GMT", case-sensitive - return { promise, resolve: res, reject: rej } -} + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) -function isAborted (fetchParams) { - return fetchParams.controller.state === 'aborted' -} + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } -function isCancelled (fetchParams) { - return fetchParams.controller.state === 'aborted' || - fetchParams.controller.state === 'terminated' -} + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] -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' -} + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(normalizeMethodRecord, null) + 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') -/** - * @see https://fetch.spec.whatwg.org/#concept-method-normalize - * @param {string} method - */ -function normalizeMethod (method) { - return normalizeMethodRecord[method.toLowerCase()] ?? method + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` } -// 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') +/** + 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') } - - // 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 + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie */ -function makeIterator (iterator, name, kind) { - const object = { - index: 0, - kind, - target: iterator +function stringify (cookie) { + if (cookie.name.length === 0) { + return null } - 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). + validateCookieName(cookie.name) + validateCookieValue(cookie.value) - // 4. If object is a platform object, then perform a security - // check, passing: + const out = [`${cookie.name}=${cookie.value}`] - // 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.` - ) - } + // 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 + } - // 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() + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } - // 9. Let len be the length of values. - const len = values.length + if (cookie.secure) { + out.push('Secure') + } - // 10. If index is greater than or equal to len, then return - // CreateIterResultObject(undefined, true). - if (index >= len) { - return { value: undefined, done: true } - } + if (cookie.httpOnly) { + out.push('HttpOnly') + } - // 11. Let pair be the entry in values at index index. - const pair = values[index] + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } - // 12. Set object’s index to index + 1. - object.index = index + 1 + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } - // 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` + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) } - // 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) -} + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } -// https://webidl.spec.whatwg.org/#iterator-result -function iteratorResult (pair, kind) { - let result + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } - // 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 + 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('=')}`) } - // 2. Return CreateIterResultObject(result, false). - return { value: result, done: false } + return out.join('; ') } -/** - * @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. +module.exports = { + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify +} - // 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 +/***/ 2067: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - reader = body.stream.getReader() - } catch (e) { - errorSteps(e) - return - } +"use strict"; - // 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 +const net = __nccwpck_require__(1808) +const assert = __nccwpck_require__(9491) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8045) -function isReadableStreamLike (stream) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(35356).ReadableStream) - } +let tls // include tls conditionally since it is not always available - return stream instanceof ReadableStream || ( - stream[Symbol.toStringTag] === 'ReadableStream' && - typeof stream.tee === 'function' - ) -} +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. -const MAXIMUM_ARGUMENT_LENGTH = 65535 +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 + } -/** - * @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. + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } - if (input.length < MAXIMUM_ARGUMENT_LENGTH) { - return String.fromCharCode(...input) + 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() + } - return input.reduce((previous, current) => previous + String.fromCharCode(current), '') -} + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } -/** - * @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 + 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) } } } -/** - * @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) +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') } - // 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 -} + 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__(4404) + } + servername = servername || options.servername || util.getServerName(host) || null -/** - * @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 + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null - while (true) { - const { done, value: chunk } = await reader.read() + assert(sessionKey) - if (done) { - // 1. Call successSteps with bytes. - return Buffer.concat(bytes, byteLength) + 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 + }) } - // 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') + // 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) } - // 2. Append the bytes represented by chunk to bytes. - bytes.push(chunk) - byteLength += chunk.length + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) - // 3. Read-loop given reader, bytes, successSteps, and failureSteps. - } -} + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() -/** - * @see https://fetch.spec.whatwg.org/#is-local - * @param {URL} url - */ -function urlIsLocal (url) { - assert('protocol' in url) // ensure it's a url object + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + cancelTimeout() - const protocol = url.protocol + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) - return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' + return socket + } } -/** - * @param {string|URL} url - */ -function urlHasHttpsScheme (url) { - if (typeof url === 'string') { - return url.startsWith('https:') +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} } - return url.protocol === 'https:' + 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) + } } -/** - * @see https://fetch.spec.whatwg.org/#http-scheme - * @param {URL} url - */ -function urlIsHttpHttpsScheme (url) { - assert('protocol' in url) // ensure it's a url object +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} - const protocol = url.protocol +module.exports = buildConnector - return protocol === 'http:' || protocol === 'https:' + +/***/ }), + +/***/ 4462: +/***/ ((module) => { + +"use strict"; + + +/** @type {Record} */ +const headerNameLowerCasedRecord = {} + +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey } -/** - * 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)) +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) 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, - parseMetadata + wellknownHeaderNames, + headerNameLowerCasedRecord } /***/ }), -/***/ 21744: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 8045: +/***/ ((module) => { "use strict"; -const { types } = __nccwpck_require__(73837) -const { hasOwn, toUSVString } = __nccwpck_require__(52538) +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } +} -/** @type {import('../../types/webidl').Webidl} */ -const webidl = {} -webidl.converters = {} -webidl.util = {} -webidl.errors = {} +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' + } +} -webidl.errors.exception = function (message) { - return new TypeError(`${message.header}: ${message.message}`) +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' + } } -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(', ')}.` +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' + } +} - return webidl.errors.exception({ - header: context.prefix, - message - }) +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' + } } -webidl.errors.invalidArgument = function (context) { - return webidl.errors.exception({ - header: context.prefix, - message: `"${context.value}" is an invalid ${context.type}.` - }) +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 + } } -// 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] +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' } } -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 - }) +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' } } -webidl.illegalConstructor = function () { - throw webidl.errors.exception({ - header: 'TypeError', - message: 'Illegal constructor' - }) +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' + } } -// 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' - } +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' + } +} - return 'Object' - } +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' } } -// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint -webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { - let upperBound - let lowerBound +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' + } +} - // 1. If bitLength is 64, then: - if (bitLength === 64) { - // 1. Let upperBound be 2^53 āˆ’ 1. - upperBound = Math.pow(2, 53) - 1 +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' + } +} - // 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: +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' + } +} - // 1. Let lowerBound be 0. - lowerBound = 0 +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 + } +} - // 2. Let upperBound be 2^bitLength āˆ’ 1. - upperBound = Math.pow(2, bitLength) - 1 - } else { - // 3. Otherwise: +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' + } +} - // 1. Let lowerBound be -2^bitLength āˆ’ 1. - lowerBound = Math.pow(-2, bitLength) - 1 +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' + } +} - // 2. Let upperBound be 2^bitLength āˆ’ 1 āˆ’ 1. - upperBound = Math.pow(2, bitLength - 1) - 1 +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 } +} - // 4. Let x be ? ToNumber(V). - let x = Number(V) +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' + } +} - // 5. If x is āˆ’0, then set x to +0. - if (x === 0) { - x = 0 +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 } +} - // 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.` - }) - } +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError +} - // 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 - } +/***/ 2905: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) +"use strict"; - // 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 - } +const { + InvalidArgumentError, + NotSupportedError +} = __nccwpck_require__(8045) +const assert = __nccwpck_require__(9491) +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(2785) +const util = __nccwpck_require__(3983) - // 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 - } +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js - // 9. Set x to IntegerPart(x). - x = webidl.util.IntegerPart(x) +/** + * 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!#$%&'*+.|~]+$/ - // 10. Set x to x modulo 2^bitLength. - x = x % Math.pow(2, bitLength) +/** + * 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]/ - // 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) - } +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ - // 12. Otherwise, return x. - return x -} +const kHandler = Symbol('handler') -// 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)) +const channels = {} - // 2. If n < 0, then return -1 Ɨ r. - if (n < 0) { - return -1 * r - } +let extractBody - // 3. Otherwise, return r. - return r +try { + const diagnosticsChannel = __nccwpck_require__(7643) + 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 } } -// 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.` - }) +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') } - // 2. Let method be ? GetMethod(V, @@iterator). - /** @type {Generator} */ - const method = V?.[Symbol.iterator]?.() - const seq = [] + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } - // 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.' - }) + 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') } - // https://webidl.spec.whatwg.org/#create-sequence-from-iterable - while (true) { - const { done, value } = method.next() + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } - if (done) { - break - } + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } - seq.push(converter(value)) + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') } - return seq - } -} + this.headersTimeout = headersTimeout -// 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.` - }) - } + this.bodyTimeout = bodyTimeout - // 2. Let result be a new empty instance of record. - const result = {} + this.throwOnError = throwOnError === true - if (!types.isProxy(O)) { - // Object.keys only returns enumerable properties - const keys = Object.keys(O) + this.method = method - for (const key of keys) { - // 1. Let typedKey be key converted to an IDL value of type K. - const typedKey = keyConverter(key) + this.abort = null - // 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]) + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + util.destroy(this) + } + this.body.on('end', this.endHandler) } - // 5. Return result. - return result + 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') } - // 3. Let keys be ? O.[[OwnPropertyKeys]](). - const keys = Reflect.ownKeys(O) + this.completed = false - // 4. For each key of keys. - for (const key of keys) { - // 1. Let desc be ? O.[[GetOwnProperty]](key). - const desc = Reflect.getOwnPropertyDescriptor(O, key) + this.aborted = false - // 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) + this.upgrade = upgrade || null - // 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]) + this.path = query ? util.buildURL(path, query) : path - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } - } + this.origin = origin - // 5. Return result. - return result - } -} + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent -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}.` - }) - } + this.blocking = blocking == null ? false : blocking - return V - } -} + this.reset = reset == null ? null : reset -webidl.dictionaryConverter = function (converters) { - return (dictionary) => { - const type = webidl.util.Type(dictionary) - const dict = {} + this.host = null - 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.` - }) - } + this.contentLength = null - for (const options of converters) { - const { key, defaultValue, required, converter } = options + this.contentType = null - if (required === true) { - if (!hasOwn(dictionary, key)) { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `Missing required key "${key}".` - }) - } - } + this.headers = '' - let value = dictionary[key] - const hasDefault = hasOwn(options, 'defaultValue') + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false - // Only use defaultValue if value is undefined and - // a defaultValue options was provided. - if (hasDefault && value !== null) { - value = value ?? defaultValue + 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') + } - // 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 (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 ( - 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(', ')}.` - }) - } + if (!extractBody) { + extractBody = (__nccwpck_require__(1472).extractBody) + } - dict[key] = value + 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` } - return dict - } -} + util.validateHandler(handler, method, upgrade) -webidl.nullableConverter = function (converter) { - return (V) => { - if (V === null) { - return V + this.servername = util.getServerName(this.host) + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) } + } - return converter(V) + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } } -} -// 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 '' + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } } - // 2. Let x be ? ToString(V). - if (typeof V === 'symbol') { - throw new TypeError('Could not convert argument of type symbol to string.') + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } } - // 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) -} + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) -// 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) + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } - // 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.` - ) + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) } } - // 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 -} + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) -// https://webidl.spec.whatwg.org/#es-USVString -webidl.converters.USVString = toUSVString + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } + } -// 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) + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) - // 2. Return the IDL boolean value that is the one that represents - // the same truth value as the ECMAScript Boolean value x. - return x -} + return this[kHandler].onUpgrade(statusCode, headers, socket) + } -// https://webidl.spec.whatwg.org/#es-any -webidl.converters.any = function (V) { - return V -} + onComplete (trailers) { + this.onFinally() -// 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') + assert(!this.aborted) - // 2. Return the IDL long long value that represents - // the same numeric value as x. - return x -} + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } -// 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') + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } - // 2. Return the IDL unsigned long long value that - // represents the same numeric value as x. - return x -} + onError (error) { + this.onFinally() -// 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') + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } - // 2. Return the IDL unsigned long value that - // represents the same numeric value as x. - return x -} + if (this.aborted) { + return + } + this.aborted = true -// 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) + return this[kHandler].onError(error) + } - // 2. Return the IDL unsigned short value that represents - // the same numeric value as x. - return x -} + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } -// 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'] - }) + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } } - // 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.' - }) + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this } - // 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. + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } - // 4. Return the IDL ArrayBuffer value that is a - // reference to the same object as V. - return V -} + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } -webidl.converters.TypedArray = function (V, T, opts = {}) { - // 1. Let T be the IDL type V is being converted to. + const request = new Request(origin, opts, handler) - // 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] - }) - } + request.headers = {} - // 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.' - }) - } + 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') + } - // 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 + return request + } - // 5. Return the IDL value of type T that is a reference - // to the same object as V. - return V -} + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} -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.' - }) - } + for (const header of rawHeaders) { + const [key, value] = header.split(': ') - // 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.' - }) - } + if (value == null || value.length === 0) continue - // 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 + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value + } - // 4. Return the IDL DataView value that is a reference - // to the same object as V. - return V + return headers + } } -// https://webidl.spec.whatwg.org/#BufferSource -webidl.converters.BufferSource = function (V, opts = {}) { - if (types.isAnyArrayBuffer(V)) { - return webidl.converters.ArrayBuffer(V, opts) +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) } - if (types.isTypedArray(V)) { - return webidl.converters.TypedArray(V, V.constructor) + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) } - if (types.isDataView(V)) { - return webidl.converters.DataView(V, opts) + 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 } - throw new TypeError(`Could not convert ${V} to a BufferSource.`) + 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) + } + } } -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.ByteString -) +module.exports = Request -webidl.converters['sequence>'] = webidl.sequenceConverter( - webidl.converters['sequence'] -) -webidl.converters['record'] = webidl.recordConverter( - webidl.converters.ByteString, - webidl.converters.ByteString -) +/***/ }), + +/***/ 2785: +/***/ ((module) => { module.exports = { - webidl + 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') } /***/ }), -/***/ 84854: -/***/ ((module) => { +/***/ 3983: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/** - * @see https://encoding.spec.whatwg.org/#concept-encoding-get - * @param {string|undefined} label - */ -function getEncoding (label) { - if (!label) { - return 'failure' +const assert = __nccwpck_require__(9491) +const { kDestroyed, kBodyUsed } = __nccwpck_require__(2785) +const { IncomingMessage } = __nccwpck_require__(3685) +const stream = __nccwpck_require__(2781) +const net = __nccwpck_require__(1808) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { Blob } = __nccwpck_require__(4300) +const nodeUtil = __nccwpck_require__(3837) +const { stringify } = __nccwpck_require__(3477) +const { headerNameLowerCasedRecord } = __nccwpck_require__(4462) + +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 "#".') } - // 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' + 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 } -module.exports = { - getEncoding +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) + } -/***/ 1446: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const idx = host.indexOf(':') + if (idx === -1) return host -"use strict"; + 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 + } -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) + assert.strictEqual(typeof host, 'string') -class FileReader extends EventTarget { - constructor () { - super() + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } - this[kState] = 'empty' - this[kResult] = null - this[kError] = null - this[kEvents] = { - loadend: null, - error: null, - abort: null, - load: null, - progress: null, - loadstart: null - } + 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 } - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer - * @param {import('buffer').Blob} blob - */ - readAsArrayBuffer (blob) { - webidl.brandCheck(this, FileReader) + return null +} - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) +} - blob = webidl.converters.Blob(blob, { strict: false }) +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} - // The readAsArrayBuffer(blob) method, when invoked, - // must initiate a read operation for blob with ArrayBuffer. - readOperation(this, blob, 'ArrayBuffer') +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return } - /** - * @see https://w3c.github.io/FileAPI/#readAsBinaryString - * @param {import('buffer').Blob} blob - */ - readAsBinaryString (blob) { - webidl.brandCheck(this, FileReader) + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) + } - blob = webidl.converters.Blob(blob, { strict: false }) + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} - // The readAsBinaryString(blob) method, when invoked, - // must initiate a read operation for blob with BinaryString. - readOperation(this, blob, 'BinaryString') +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 +} + +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return headerNameLowerCasedRecord[value] || value.toLowerCase() +} + +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://w3c.github.io/FileAPI/#readAsDataText - * @param {import('buffer').Blob} blob - * @param {string?} encoding - */ - readAsText (blob, encoding = undefined) { - webidl.brandCheck(this, FileReader) + // 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') + } - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + return obj +} - blob = webidl.converters.Blob(blob, { strict: false }) +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 - if (encoding !== undefined) { - encoding = webidl.converters.DOMString(encoding) + 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) } + } - // 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://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') } - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL - * @param {import('buffer').Blob} blob - */ - readAsDataURL (blob) { - webidl.brandCheck(this, FileReader) + return ret +} - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} - blob = webidl.converters.Blob(blob, { strict: false }) +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } - // The readAsDataURL(blob) method, when invoked, must - // initiate a read operation for blob with DataURL. - readOperation(this, blob, 'DataURL') + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') } - /** - * @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 + 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') } - // 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 + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') } - // 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 + 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__(5356).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, + headerNameToString, + 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'] +} - // 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) - } - } +/***/ 4839: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate - */ - get readyState () { - webidl.brandCheck(this, FileReader) +"use strict"; - 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) +const Dispatcher = __nccwpck_require__(412) +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(2785) - // The result attribute’s getter, when invoked, must return - // this's result. - return this[kResult] - } +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-error - */ - get error () { - webidl.brandCheck(this, FileReader) +class DispatcherBase extends Dispatcher { + constructor () { + super() - // The error attribute’s getter, when invoked, must return - // this's error. - return this[kError] + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] } - get onloadend () { - webidl.brandCheck(this, FileReader) + get destroyed () { + return this[kDestroyed] + } - return this[kEvents].loadend + get closed () { + return this[kClosed] } - set onloadend (fn) { - webidl.brandCheck(this, FileReader) + get interceptors () { + return this[kInterceptors] + } - if (this[kEvents].loadend) { - this.removeEventListener('loadend', this[kEvents].loadend) + 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') + } + } } - if (typeof fn === 'function') { - this[kEvents].loadend = fn - this.addEventListener('loadend', fn) - } else { - this[kEvents].loadend = null - } + this[kInterceptors] = newInterceptors } - get onerror () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].error - } + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - set onerror (fn) { - webidl.brandCheck(this, FileReader) + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - if (this[kEvents].error) { - this.removeEventListener('error', this[kEvents].error) + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return } - if (typeof fn === 'function') { - this[kEvents].error = fn - this.addEventListener('error', fn) - } else { - this[kEvents].error = null + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return } - } - get onloadstart () { - webidl.brandCheck(this, FileReader) + this[kClosed] = true + this[kOnClosed].push(callback) - return this[kEvents].loadstart + 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) + }) } - set onloadstart (fn) { - webidl.brandCheck(this, FileReader) + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } - if (this[kEvents].loadstart) { - this.removeEventListener('loadstart', this[kEvents].loadstart) + 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 fn === 'function') { - this[kEvents].loadstart = fn - this.addEventListener('loadstart', fn) - } else { - this[kEvents].loadstart = null + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - } - get onprogress () { - webidl.brandCheck(this, FileReader) + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } - return this[kEvents].progress - } + if (!err) { + err = new ClientDestroyedError() + } - set onprogress (fn) { - webidl.brandCheck(this, FileReader) + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) - if (this[kEvents].progress) { - this.removeEventListener('progress', this[kEvents].progress) + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } } - if (typeof fn === 'function') { - this[kEvents].progress = fn - this.addEventListener('progress', fn) - } else { - this[kEvents].progress = null - } + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) } - get onload () { - webidl.brandCheck(this, FileReader) + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } - return this[kEvents].load + 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) } - set onload (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].load) { - this.removeEventListener('load', this[kEvents].load) + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') } - if (typeof fn === 'function') { - this[kEvents].load = fn - this.addEventListener('load', fn) - } else { - this[kEvents].load = null - } - } + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } - get onabort () { - webidl.brandCheck(this, FileReader) + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } - return this[kEvents].abort - } + if (this[kClosed]) { + throw new ClientClosedError() + } - set onabort (fn) { - webidl.brandCheck(this, FileReader) + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } - if (this[kEvents].abort) { - this.removeEventListener('abort', this[kEvents].abort) - } + handler.onError(err) - if (typeof fn === 'function') { - this[kEvents].abort = fn - this.addEventListener('abort', fn) - } else { - this[kEvents].abort = null + return false } } } -// 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 -} +module.exports = DispatcherBase /***/ }), -/***/ 55504: +/***/ 412: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { webidl } = __nccwpck_require__(21744) - -const kState = Symbol('ProgressEvent state') +const EventEmitter = __nccwpck_require__(2361) -/** - * @see https://xhr.spec.whatwg.org/#progressevent - */ -class ProgressEvent extends Event { - constructor (type, eventInitDict = {}) { - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } - super(type, eventInitDict) + close () { + throw new Error('not implemented') + } - this[kState] = { - lengthComputable: eventInitDict.lengthComputable, - loaded: eventInitDict.loaded, - total: eventInitDict.total - } + destroy () { + throw new Error('not implemented') } +} - get lengthComputable () { - webidl.brandCheck(this, ProgressEvent) +module.exports = Dispatcher - return this[kState].lengthComputable - } - get loaded () { - webidl.brandCheck(this, ProgressEvent) +/***/ }), - return this[kState].loaded - } +/***/ 1472: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get total () { - webidl.brandCheck(this, ProgressEvent) +"use strict"; - 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 - } -]) +const Busboy = __nccwpck_require__(727) +const util = __nccwpck_require__(3983) +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = __nccwpck_require__(2538) +const { FormData } = __nccwpck_require__(2015) +const { kState } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { DOMException, structuredClone } = __nccwpck_require__(1037) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { isErrored } = __nccwpck_require__(3983) +const { isUint8Array, isArrayBuffer } = __nccwpck_require__(9830) +const { File: UndiciFile } = __nccwpck_require__(8511) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) -module.exports = { - ProgressEvent +let random +try { + const crypto = __nccwpck_require__(6005) + random = (max) => crypto.randomInt(0, max) +} catch { + random = (max) => Math.floor(Math.random(max)) } +let ReadableStream = globalThis.ReadableStream -/***/ }), +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() -/***/ 29054: -/***/ ((module) => { +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } -"use strict"; + // 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 + }) + } -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') -} + // 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 -/***/ 87530: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 8. Let length be null. + let length = null -"use strict"; + // 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 -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) + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} + // 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 -/** - * @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') - } + // 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 - // 2. Set fr’s state to "loading". - fr[kState] = 'loading' + // 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${`${random(1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` - // 3. Set fr’s result to null. - fr[kResult] = null + /*! 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') - // 4. Set fr’s error to null. - fr[kError] = null + // 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. - // 5. Let stream be the result of calling get stream on blob. - /** @type {import('stream/web').ReadableStream} */ - const stream = blob.stream() + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false - // 6. Let reader be the result of getting a reader from stream. - const reader = stream.getReader() + 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 + } + } + } - // 7. Let bytes be an empty byte sequence. - /** @type {Uint8Array[]} */ - const bytes = [] + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } - // 8. Let chunkPromise be the result of reading a chunk from - // stream with reader. - let chunkPromise = reader.read() + // Set source to object. + source = object - // 9. Let isFirstChunk be true. - let isFirstChunk = true + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } - // 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 + // 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 - // 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) - }) - } + // Set source to object. + source = object - // 3. Set isFirstChunk to false. - isFirstChunk = false + // Set length to object’s size. + length = object.size - // 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. + // 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') + } - // 2. Append bs to bytes. - bytes.push(value) + // 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' + ) + } - // 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) - }) - } + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } - // 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: + // 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(() => { - // 1. Set fr’s state to "done". - fr[kState] = 'done' + 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 + }) + } - // 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) + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } - // 4. Else: + // 14. Return (body, type). + return [body, type] +} - if (fr[kAborted]) { - return - } +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } - // 1. Set fr’s result to result. - fr[kResult] = result + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: - // 2. Fire a progress event called load at the fr. - fireAProgressEvent('load', fr) - } catch (error) { - // 3. If package data threw an exception error: + // 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.') + } - // 1. Set fr’s error to error. - fr[kError] = error + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} - // 2. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) - } +function cloneBody (body) { + // To clone a body body, run these steps: - // 5. If fr’s state is not "loading", fire a progress - // event called loadend at the fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) + // https://fetch.spec.whatwg.org/#concept-body-clone - break - } - } catch (error) { - if (fr[kAborted]) { - return - } + // 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() - // 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 body’s stream to out1. + body.stream = out1 - // 2. Set fr’s error to error. - fr[kError] = error + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } +} - // 3. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream - // 4. If fr’s state is not "loading", fire a progress - // event called loadend at fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } - break + if (stream.locked) { + throw new TypeError('The stream is locked.') } + + // Compat. + stream[kBodyUsed] = true + + yield * stream } - })() + } } -/** - * @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) +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } } -/** - * @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: +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) - 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]. + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } - // 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:' + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, - const parsed = parseMIMEType(mimeType || 'application/octet-stream') + 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) + }, - if (parsed !== 'failure') { - dataURL += serializeAMimeType(parsed) - } + 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) + }, - dataURL += ';base64,' + 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) + }, - const decoder = new StringDecoder('latin1') + async formData () { + webidl.brandCheck(this, instance) - for (const chunk of bytes) { - dataURL += btoa(decoder.write(chunk)) - } + throwIfAborted(this[kState]) - dataURL += btoa(decoder.end()) + const contentType = this.headers.get('Content-Type') - return dataURL - } - case 'Text': { - // 1. Let encoding be failure - let encoding = 'failure' + // 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 - // 2. If the encodingName is present, set encoding to the - // result of getting an encoding from encodingName. - if (encodingName) { - encoding = getEncoding(encodingName) - } + const responseFormData = new FormData() - // 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) + let busboy - // 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')) + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') } - } - // 4. If encoding is failure, then set encoding to UTF-8. - if (encoding === 'failure') { - encoding = 'UTF-8' - } + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] - // 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) + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' - 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 = '' + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') - const decoder = new StringDecoder('latin1') + 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 }) + } - for (const chunk of bytes) { - binaryString += decoder.write(chunk) - } + // 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() - binaryString += decoder.end() + throwIfAborted(this[kState]) - return binaryString + // 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://encoding.spec.whatwg.org/#decode - * @param {Uint8Array[]} ioQueue - * @param {string} encoding + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance */ -function decode (ioQueue, encoding) { - const bytes = combineByteSequences(ioQueue) +async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) - // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. - const BOMEncoding = BOMSniffing(bytes) + throwIfAborted(object[kState]) - let slice = 0 + // 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. If BOMEncoding is non-null: - if (BOMEncoding !== null) { - // 1. Set encoding to BOMEncoding. - encoding = BOMEncoding + // 2. Let promise be a new promise. + const promise = createDeferredPromise() - // 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. 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) + } } - // 3. Process a queue with an instance of encoding’s - // decoder, ioQueue, output, and "replacement". + // 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 + } - // 4. Return output. + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) - const sliced = bytes.slice(slice) - return new TextDecoder(encoding).decode(sliced) + // 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/#bom-sniff - * @param {Uint8Array} ioQueue + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer */ -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' +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' } - return null -} + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. -/** - * @param {Uint8Array[]} sequences - */ -function combineByteSequences (sequences) { - const size = sequences.reduce((a, b) => { - return a + b.byteLength - }, 0) + // 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) + } - let offset = 0 + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) - return sequences.reduce((a, b) => { - a.set(b, offset) - offset += b.byteLength - return a - }, new Uint8Array(size)) + // 4. Return output. + return output } -module.exports = { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent +/** + * @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') -/***/ }), - -/***/ 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') + if (contentType === null) { + return 'failure' } - Object.defineProperty(globalThis, globalDispatcher, { - value: agent, - writable: true, - enumerable: false, - configurable: false - }) -} -function getGlobalDispatcher () { - return globalThis[globalDispatcher] + return parseMIMEType(contentType) } module.exports = { - setGlobalDispatcher, - getGlobalDispatcher + extractBody, + safelyExtractBody, + cloneBody, + mixinBody } /***/ }), -/***/ 46930: -/***/ ((module) => { +/***/ 1037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = class DecoratorHandler { - constructor (handler) { - this.handler = handler - } +const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) - onConnect (...args) { - return this.handler.onConnect(...args) - } +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) - onError (...args) { - return this.handler.onError(...args) - } +const nullBodyStatus = [101, 204, 205, 304] - onUpgrade (...args) { - return this.handler.onUpgrade(...args) - } +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) - onHeaders (...args) { - return this.handler.onHeaders(...args) - } +// 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' +] - onData (...args) { - return this.handler.onData(...args) - } +const badPortsSet = new Set(badPorts) - onComplete (...args) { - return this.handler.onComplete(...args) - } +// 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) - onBodySent (...args) { - return this.handler.onBodySent(...args) - } -} +const requestRedirect = ['follow', 'manual', 'error'] +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) -/***/ }), +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] -/***/ 72860: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const requestCredentials = ['omit', 'same-origin', 'include'] -"use strict"; +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' +] -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) +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] -const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) -const kBody = Symbol('body') +const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +] +const subresourceSet = new Set(subresource) -class BodyAsyncIterable { - constructor (body) { - this[kBody] = body - this[kBodyUsed] = false +/** @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 } +})() - async * [Symbol.asyncIterator] () { - assert(!this[kBodyUsed], 'disturbed') - this[kBodyUsed] = true - yield * this[kBody] - } -} +let channel -class RedirectHandler { - constructor (dispatch, maxRedirections, opts, handler) { - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') +/** @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') } - 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) + if (!channel) { + channel = new MessageChannel() } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message } - onConnect (abort) { - this.abort = abort - this.handler.onConnect(abort, { history: this.history }) - } +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 +} - 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) +/***/ 685: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.opts.origin) { - this.history.push(new URL(this.opts.path, this.opts.origin)) - } +const assert = __nccwpck_require__(9491) +const { atob } = __nccwpck_require__(4300) +const { isomorphicDecode } = __nccwpck_require__(2538) - if (!this.location) { - return this.handler.onHeaders(statusCode, headers, resume, statusText) - } +const encoder = new TextEncoder() - 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 +/** + * @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 - // 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://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') - // 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 - } - } + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) - onData (chunk) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 + // 3. Remove the leading "data:" string from input. + input = input.slice(5) - TLDR: undici always ignores 3xx response bodies. + // 4. Let position point at the start of input. + const position = { position: 0 } - 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. + // 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 + ) - 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. + // 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) - 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) - } + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' } - onComplete (trailers) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 + // 8. Advance position by 1. + position.position++ - TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections - and neither are useful if present. + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) - See comment on onData method above for more detailed informations. - */ + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) - this.location = null - this.abort = null + // 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) - this.dispatch(this.opts, this) - } else { - this.handler.onComplete(trailers) - } - } + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) - onBodySent (chunk) { - if (this.handler.onBodySent) { - this.handler.onBodySent(chunk) + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' } - } -} -function parseLocation (statusCode, headers) { - if (redirectableStatusCodes.indexOf(statusCode) === -1) { - return null - } + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) - for (let i = 0; i < headers.length; i += 2) { - if (headers[i].toString().toLowerCase() === 'location') { - return headers[i + 1] - } - } -} + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') -// https://tools.ietf.org/html/rfc7231#section-6.4.4 -function shouldRemoveHeader (header, removeContent, unknownOrigin) { - if (header.length === 4) { - return util.headerNameToString(header) === 'host' - } - if (removeContent && util.headerNameToString(header).startsWith('content-')) { - return true - } - if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { - const name = util.headerNameToString(header) - return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) } - return false -} -// 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') + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType } - return ret -} -module.exports = RedirectHandler + // 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 } +} -/***/ 82286: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// 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 assert = __nccwpck_require__(39491) + const href = url.href + const hashLength = url.hash.length -const { kRetryHandlerDefaultRetry } = __nccwpck_require__(72785) -const { RequestRetryError } = __nccwpck_require__(48045) -const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(83983) + return hashLength === 0 ? href : href.substring(0, href.length - hashLength) +} -function calculateRetryAfterHeader (retryAfter) { - const current = Date.now() - const diff = new Date(retryAfter).getTime() - current +// 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 = '' - return diff -} + // 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] -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 ?? {} + // 2. Advance position by 1. + position.position++ + } - 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' - ] - } + // 3. Return result. + return result +} - this.retryCount = 0 - this.start = 0 - this.end = null - this.etag = null - this.resume = null +/** + * 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 - // Handle possible onConnect duplication - this.handler.onConnect(reason => { - this.aborted = true - if (this.abort) { - this.abort(reason) - } else { - this.reason = reason - } - }) + if (idx === -1) { + position.position = input.length + return input.slice(start) } - onRequestSent () { - if (this.handler.onRequestSent) { - this.handler.onRequestSent() - } - } + position.position = idx + return input.slice(start, position.position) +} - onUpgrade (statusCode, headers, socket) { - if (this.handler.onUpgrade) { - this.handler.onUpgrade(statusCode, headers, socket) - } - } +// 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) - onConnect (abort) { - if (this.aborted) { - abort(this.reason) - } else { - this.abort = abort - } - } + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} - onBodySent (chunk) { - if (this.handler.onBodySent) return this.handler.onBodySent(chunk) - } +// 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 = [] - 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 + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] - currentTimeout = - currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) - // 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) + // 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])) ) { - cb(err) - return - } + output.push(0x25) - // 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 - } + // 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) - // 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 - } + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) - // If we reached the max number of retries - if (counter > maxRetries) { - cb(err) - return + // 3. Skip the next two bytes in input. + i += 2 } + } - let retryAfterHeader = headers != null && headers['retry-after'] - if (retryAfterHeader) { - retryAfterHeader = Number(retryAfterHeader) - retryAfterHeader = isNaN(retryAfterHeader) - ? calculateRetryAfterHeader(retryAfterHeader) - : retryAfterHeader * 1e3 // Retry-After is in seconds - } + // 3. Return output. + return Uint8Array.from(output) +} - const retryTimeout = - retryAfterHeader > 0 - ? Math.min(retryAfterHeader, maxTimeout) - : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) +// 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) - state.currentTimeout = retryTimeout + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } - setTimeout(() => cb(null), retryTimeout) + // 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' } - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const headers = parseHeaders(rawHeaders) + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } - this.retryCount += 1 + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ - if (statusCode >= 300) { - this.abort( - new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } + // 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 + ) - // Checkpoint for resume from where we left it - if (this.resume != null) { - this.resume = null + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) - if (statusCode !== 206) { - return 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 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 - } + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() - // 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 - } + // 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}` + } - const { start, size, end = size } = contentRange + // 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++ - assert(this.start === start, 'content-range mismatch') - assert(this.end == null || this.end === end, 'content-range mismatch') + // 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 + ) - this.resume = resume - return true - } + // 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 + ) - if (this.end == null) { - if (statusCode === 206) { - // First time we receive 206 - const range = parseRangeHeader(headers['content-range']) + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() - if (range == null) { - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } + // 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 + } - const { start, size, end = size } = range + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } - 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' - ) + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } - this.start = start - this.end = end - } + // 7. Let parameterValue be null. + let parameterValue = null - // 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 - } + // 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) - assert(Number.isFinite(this.start)) - assert( - this.end == null || Number.isFinite(this.end), - 'invalid content-length' + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position ) - this.resume = resume - this.etag = headers.etag != null ? headers.etag : null - - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage + // 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 ) - } - const err = new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) - this.abort(err) + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } - return false + // 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) + } } - onData (chunk) { - this.start += chunk.length + // 12. Return mimeType. + return mimeType +} - return this.handler.onData(chunk) - } +// 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 - onComplete (rawTrailers) { - this.retryCount = 0 - return this.handler.onComplete(rawTrailers) + // 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(/=?=$/, '') } - 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) - ) + // 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' + } - function onRetry (err) { - if (err != null || this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } + // 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' + } - if (this.start !== 0) { - this.opts = { - ...this.opts, - headers: { - ...this.opts.headers, - range: `bytes=${this.start}-${this.end ?? ''}` - } - } - } + const binary = atob(data) + const bytes = new Uint8Array(binary.length) - try { - this.dispatch(this.opts, this) - } catch (err) { - this.handler.onError(err) - } - } + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) } + + return bytes } -module.exports = RetryHandler +// 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] === '"') -/***/ 38861: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 4. Advance position by 1. + position.position++ -"use strict"; + // 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 + } -const RedirectHandler = __nccwpck_require__(72860) + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] -function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { - return (dispatch) => { - return function Intercept (opts, handler) { - const { maxRedirections = defaultMaxRedirections } = opts + // 4. Advance position by 1. + position.position++ - if (!maxRedirections) { - return dispatch(opts, handler) + // 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 } - const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) - opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. - return dispatch(opts, redirectHandler) + // 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) } -module.exports = createRedirectInterceptor +/** + * @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 += ';' -/***/ 30953: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 2. Append name to serialization. + serialization += name -"use strict"; + // 3. Append U+003D (=) to serialization. + serialization += '=' -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 + // 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 -/***/ 61145: -/***/ ((module) => { + // 3. Append U+0022 (") to value. + value += '"' + } -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=' + // 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 === ' ' +} -/***/ 95627: -/***/ ((module) => { +/** + * @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 -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==' + 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) +} -/***/ 41891: -/***/ ((__unused_webpack_module, exports) => { +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ +function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' +} -"use strict"; +/** + * @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 -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; + 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) } -exports.enumToMap = enumToMap; -//# sourceMappingURL=utils.js.map + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} + /***/ }), -/***/ 66771: +/***/ 8511: /***/ ((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) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { types } = __nccwpck_require__(3837) +const { kState } = __nccwpck_require__(5861) +const { isBlobLike } = __nccwpck_require__(2538) +const { webidl } = __nccwpck_require__(1744) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const encoder = new TextEncoder() -class FakeWeakRef { - constructor (value) { - this.value = value - } +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' }) - deref () { - return this.value - } -} + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) -class MockAgent extends Dispatcher { - constructor (opts) { - super(opts) + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us - this[kNetConnect] = true - this[kIsMockActive] = true + // 2. Let n be the fileName argument to the constructor. + const n = fileName - // 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 + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: - this[kClients] = agent[kClients] - this[kOptions] = buildMockOptions(opts) - } + // 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 - get (origin) { - let dispatcher = this[kMockAgentGet](origin) + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) - if (!dispatcher) { - dispatcher = this[kFactory](origin) - this[kMockAgentSet](origin, dispatcher) + 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 } - 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) - } + // 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. - async close () { - await this[kAgent].close() - this[kClients].clear() + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t + } } - deactivate () { - this[kIsMockActive] = false - } + get name () { + webidl.brandCheck(this, File) - activate () { - this[kIsMockActive] = true + return this[kState].name } - 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.') - } - } + get lastModified () { + webidl.brandCheck(this, File) - disableNetConnect () { - this[kNetConnect] = false + return this[kState].lastModified } - // This is required to bypass issues caused by using global symbols - see: - // https://github.com/nodejs/undici/issues/1447 - get isMockActive () { - return this[kIsMockActive] - } + get type () { + webidl.brandCheck(this, File) - [kMockAgentSet] (origin, dispatcher) { - this[kClients].set(origin, new FakeWeakRef(dispatcher)) + return this[kState].type } +} - [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) - } +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check - [kMockAgentGet] (origin) { - // First check if we can immediately find it - const ref = this[kClients].get(origin) - if (ref) { - return ref.deref() - } + // 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: - // 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 - } + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. - // 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 - } - } - } + // 2. Let n be the fileName argument to the constructor. + const n = fileName - [kGetNetConnect] () { - return this[kNetConnect] - } + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: - pendingInterceptors () { - const mockAgentClients = this[kClients] + // 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 - return Array.from(mockAgentClients.entries()) - .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) - .filter(({ pending }) => pending) - } + // 2. Convert every character in t to ASCII lowercase. + // TODO - assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { - const pending = this.pendingInterceptors() + // 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() - if (pending.length === 0) { - return - } + // 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. - const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } - throw new UndiciError(` -${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + stream (...args) { + webidl.brandCheck(this, FileLike) -${pendingInterceptorsFormatter.format(pending)} -`.trim()) + return this[kState].blobLike.stream(...args) } -} -module.exports = MockAgent + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) + return this[kState].blobLike.arrayBuffer(...args) + } -/***/ }), + slice (...args) { + webidl.brandCheck(this, FileLike) -/***/ 58687: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this[kState].blobLike.slice(...args) + } -"use strict"; + text (...args) { + webidl.brandCheck(this, FileLike) + return this[kState].blobLike.text(...args) + } -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) + get size () { + webidl.brandCheck(this, FileLike) -/** - * MockClient provides an API that extends the Client to influence the mockDispatches. - */ -class MockClient extends Client { - constructor (origin, opts) { - super(origin, opts) + return this[kState].blobLike.size + } - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } + get type () { + webidl.brandCheck(this, FileLike) - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) + return this[kState].blobLike.type + } - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] + get name () { + webidl.brandCheck(this, FileLike) + + return this[kState].name } - get [Symbols.kConnected] () { - return this[kConnected] + get lastModified () { + webidl.brandCheck(this, FileLike) + + return this[kState].lastModified } - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) + get [Symbol.toStringTag] () { + return 'File' } +} - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) +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) } -module.exports = MockClient +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' + } -/***/ 50888: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return value + }, + defaultValue: 'transparent' + } +]) -"use strict"; +/** + * @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 -const { UndiciError } = __nccwpck_require__(48045) + // 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) + } -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' + // 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) } -module.exports = { - MockNotMatchedError +// 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 } + /***/ }), -/***/ 90410: +/***/ 2015: /***/ ((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) +const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(2538) +const { kState } = __nccwpck_require__(5861) +const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(8511) +const { webidl } = __nccwpck_require__(1744) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) -/** - * Defines the scope API for an interceptor reply - */ -class MockScope { - constructor (mockDispatch) { - this[kMockDispatch] = mockDispatch - } +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile - /** - * 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') +// 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[kMockDispatch].delay = waitInMs - return this - } - - /** - * For a defined reply, never mark as consumed. - */ - persist () { - this[kMockDispatch].persist = true - return this + this[kState] = [] } - /** - * 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') - } + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) - this[kMockDispatch].times = repeatTimes - return this - } -} + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) -/** - * 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() + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) } - this[kDispatchKey] = buildKey(opts) - this[kDispatches] = mockDispatches - this[kDefaultHeaders] = {} - this[kDefaultTrailers] = {} - this[kContentLength] = false - } + // 1. Let value be value if given; otherwise blobValue. - 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 } + 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 - return { statusCode, data, headers, trailers } - } + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) - 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') - } + // 3. Append entry to this’s entry list. + this[kState].push(entry) } - /** - * 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) + delete (name) { + webidl.brandCheck(this, FormData) - // Check if it is in the right format - if (typeof resolvedData !== 'object') { - throw new InvalidArgumentError('reply options callback must return an object') - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) - 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) - } - } + name = webidl.converters.USVString(name) - // 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) - } + // 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) + } - // 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) + get (name) { + webidl.brandCheck(this, FormData) - // 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) - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) - /** - * Mock an undici request with a defined error. - */ - replyWithError (error) { - if (typeof error === 'undefined') { - throw new InvalidArgumentError('error must be defined') + 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 } - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) - return new MockScope(newMockDispatch) + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value } - /** - * Set default reply headers on the interceptor for subsequent replies - */ - defaultReplyHeaders (headers) { - if (typeof headers === 'undefined') { - throw new InvalidArgumentError('headers must be defined') - } + getAll (name) { + webidl.brandCheck(this, FormData) - this[kDefaultHeaders] = headers - return this - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) - /** - * Set default reply trailers on the interceptor for subsequent replies - */ - defaultReplyTrailers (trailers) { - if (typeof trailers === 'undefined') { - throw new InvalidArgumentError('trailers must be defined') - } + name = webidl.converters.USVString(name) - this[kDefaultTrailers] = trailers - return this + // 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) } - /** - * Set reply content length header for replies on the interceptor - */ - replyContentLength () { - this[kContentLength] = true - return this - } -} + has (name) { + webidl.brandCheck(this, FormData) -module.exports.MockInterceptor = MockInterceptor -module.exports.MockScope = MockScope + 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 + } -/***/ 26193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) -"use strict"; + 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'" + ) + } -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) + // The set(name, value) and set(name, blobValue, filename) method steps + // are: -/** - * MockPool provides an API that extends the Pool to influence the mockDispatches. - */ -class MockPool extends Pool { - constructor (origin, opts) { - super(origin, opts) + // 1. Let value be value if given; otherwise blobValue. - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } + 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 - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] + // 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) + } } - get [Symbols.kConnected] () { - return this[kConnected] - } + entries () { + webidl.brandCheck(this, FormData) - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) } - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) - } -} + keys () { + webidl.brandCheck(this, FormData) -module.exports = MockPool + 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' + ) + } -/***/ 24347: -/***/ ((module) => { + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) -"use strict"; + 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'." + ) + } -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') + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } } +FormData.prototype[Symbol.iterator] = FormData.prototype.entries -/***/ }), - -/***/ 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 +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: 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 + * @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 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] - } - } +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') - return undefined - } else if (typeof headers.get === 'function') { - return headers.get(key) + // 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 { - 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) -} + // 3. Otherwise: -function matchHeaders (mockDispatch, headers) { - if (typeof mockDispatch.headers === 'function') { - if (Array.isArray(headers)) { // fetch HeadersList - headers = buildHeadersFromArray(headers) + // 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 }) } - 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) + // 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 + } - if (!matchValue(matchHeaderValue, headerValue)) { - return false + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) } } - return true + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } } -function safeUrl (path) { - if (typeof path !== 'string') { - return path - } +module.exports = { FormData } - const pathSegments = path.split('?') - if (pathSegments.length !== 2) { - return path - } +/***/ }), - const qp = new URLSearchParams(pathSegments.pop()) - qp.sort() - return [...pathSegments, qp.toString()].join('?') -} +/***/ 1246: +/***/ ((module) => { -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 -} +"use strict"; -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 +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') - // 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}'`) - } +function getGlobalOrigin () { + return globalThis[globalOrigin] +} - // 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}'`) - } +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) - // 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}'`) + return } - // 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}'`) + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) } - return matchedMockDispatches[0] + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) } -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 +module.exports = { + getGlobalOrigin, + setGlobalOrigin } -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}`) - ], []) +/***/ 554: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch + + + +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const { kGuard } = __nccwpck_require__(5861) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = __nccwpck_require__(2538) +const util = __nccwpck_require__(3837) +const { webidl } = __nccwpck_require__(1744) +const assert = __nccwpck_require__(9491) + +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://developer.mozilla.org/en-US/docs/Web/HTTP/Status - * @param {number} statusCode + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue */ -function getStatusText (statusCode) { - return STATUS_CODES[statusCode] || 'unknown' +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) } -async function getResponse (body) { - const buffers = [] - for await (const data of body) { - buffers.push(data) +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'] + }) } - return Buffer.concat(buffers).toString('utf8') } /** - * Mock dispatch function used to simulate undici dispatches + * @see https://fetch.spec.whatwg.org/#concept-headers-append */ -function mockDispatch (opts, handler) { - // Get mock dispatch from built key - const key = buildKey(opts) - const mockDispatch = getMockDispatch(this[kDispatches], key) +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) - mockDispatch.timesInvoked++ + // 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' + }) + } - // 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) } + // 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 } - // Parse mockDispatch data - const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch - const { timesInvoked, times } = mockDispatch + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. - // If it's used up and not persistent, mark as consumed - mockDispatch.consumed = !persist && timesInvoked >= times - mockDispatch.pending = timesInvoked < times + // 7. Append (name, value) to headers’s header list. + return headers[kHeadersList].append(name, value) - // If specified, trigger dispatch error - if (error !== null) { - deleteMockDispatch(this[kDispatches], key) - handler.onError(error) - return true + // 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 + } } - // Handle the request with a delay if necessary - if (typeof delay === 'number' && delay > 0) { - setTimeout(() => { - handleReply(this[kDispatches]) - }, delay) - } else { - handleReply(this[kDispatches]) + // 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) } - 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 + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } - // 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 - } + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null - const responseData = getResponseData(body) - const responseHeaders = generateKeyValues(headers) - const responseTrailers = generateKeyValues(trailers) + // 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) - handler.abort = nop - handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) - handler.onData(Buffer.from(responseData)) - handler.onComplete(responseTrailers) - deleteMockDispatch(mockDispatches, key) + // 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) + } } - function resume () {} + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null + const lowercaseName = name.toLowerCase() - return true -} + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } -function buildMockDispatch () { - const agent = this[kMockAgent] - const origin = this[kOrigin] - const originalDispatch = this[kOriginalDispatch] + // 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 }) + } - 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) + // 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) } -} -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 + // 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 } - return false -} -function buildMockOptions (opts) { - if (opts) { - const { agent, ...mockOptions } = opts - return mockOptions + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } } -} -module.exports = { - getResponseData, - getMockDispatch, - addMockDispatch, - deleteMockDispatch, - buildKey, - generateKeyValues, - matchValue, - getResponse, - getStatusText, - mockDispatch, - buildMockDispatch, - checkNetConnect, - buildMockOptions, - getHeaderByName + 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: -/***/ 86823: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 1. Set this’s guard to "none". + this[kGuard] = 'none' -"use strict"; + // 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) -const { Transform } = __nccwpck_require__(12781) -const { Console } = __nccwpck_require__(96206) + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) -/** - * 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) - } - }) + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) - this.logger = new Console({ - stdout: this.transform, - inspectOptions: { - colors: !disableColors && !process.env.CI - } - }) + return appendHeader(this, name, value) } - 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 - })) + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) - this.logger.table(withPrettyHeaders) - return this.transform.read().toString() - } -} + 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 + } -/***/ 78891: -/***/ ((module) => { + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } -"use strict"; + // 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) -const singulars = { - pronoun: 'it', - is: 'is', - was: 'was', - this: 'this' -} + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) -const plurals = { - pronoun: 'they', - is: 'are', - was: 'were', - this: 'these' -} + name = webidl.converters.ByteString(name) -module.exports = class Pluralizer { - constructor (singular, plural) { - this.singular = singular - this.plural = plural - } + // 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' + }) + } - pluralize (count) { - const one = count === 1 - const keys = one ? singulars : plurals - const noun = one ? this.singular : this.plural - return { ...keys, count, noun } + // 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) -/***/ 68266: -/***/ ((module) => { + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) -"use strict"; -/* eslint-disable */ + 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) + } -// Extracted from node/lib/internal/fixed_queue.js + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) -// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. -const kSize = 2048; -const kMask = kSize - 1; + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) -// 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. + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) -class FixedCircularBuffer { - constructor() { - this.bottom = 0; - this.top = 0; - this.list = new Array(kSize); - this.next = null; - } + // 1. Normalize value. + value = headerValueNormalize(value) - isEmpty() { - return this.top === this.bottom; - } + // 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' + }) + } - isFull() { - return ((this.top + 1) & kMask) === this.bottom; - } + // 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 + } - push(data) { - this.list[this.top] = data; - this.top = (this.top + 1) & kMask; + // 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) } - 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; - } -} + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) -module.exports = class FixedQueue { - constructor() { - this.head = this.tail = new FixedCircularBuffer(); - } + // 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. - isEmpty() { - return this.head.isEmpty(); - } + const list = this[kHeadersList].cookies - 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(); + if (list) { + return [...list] } - this.head.push(data); + + return [] } - 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; + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] } - return next; - } -}; + // 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 -/***/ 73198: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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. -"use strict"; + // 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. -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) + // 2. Assert: value is non-null. + assert(value !== null) -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') + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } -class PoolBase extends DispatcherBase { - constructor () { - super() + this[kHeadersList][kHeadersSortedMap] = headers - this[kQueue] = new FixedQueue() - this[kClients] = [] - this[kQueued] = 0 + // 4. Return headers. + return headers + } - const pool = this + keys () { + webidl.brandCheck(this, Headers) - this[kOnDrain] = function onDrain (origin, targets) { - const queue = pool[kQueue] + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key') + } - let needDrain = false + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } - while (!needDrain) { - const item = queue.shift() - if (!item) { - break - } - pool[kQueued]-- - needDrain = !this.dispatch(item.opts, item.handler) - } + values () { + webidl.brandCheck(this, Headers) - this[kNeedDrain] = needDrain + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'value') + } - if (!this[kNeedDrain] && pool[kNeedDrain]) { - pool[kNeedDrain] = false - pool.emit('drain', origin, [pool, ...targets]) - } + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } - if (pool[kClosedResolve] && queue.isEmpty()) { - Promise - .all(pool[kClients].map(c => c.close())) - .then(pool[kClosedResolve]) - } - } + entries () { + webidl.brandCheck(this, Headers) - this[kOnConnect] = (origin, targets) => { - pool.emit('connect', origin, [pool, ...targets]) + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key+value') } - this[kOnDisconnect] = (origin, targets, err) => { - pool.emit('disconnect', origin, [pool, ...targets], err) - } + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } - this[kOnConnectionError] = (origin, targets, err) => { - pool.emit('connectionError', origin, [pool, ...targets], err) + /** + * @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'." + ) } - this[kStats] = new PoolStats(this) + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } } - get [kBusy] () { - return this[kNeedDrain] - } + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) - get [kConnected] () { - return this[kClients].filter(client => client[kConnected]).length + return this[kHeadersList] } +} - get [kFree] () { - return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length - } +Headers.prototype[Symbol.iterator] = Headers.prototype.entries - get [kPending] () { - let ret = this[kQueued] - for (const { [kPending]: pending } of this[kClients]) { - ret += pending - } - return ret +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 + }, + [util.inspect.custom]: { + enumerable: false } +}) - get [kRunning] () { - let ret = 0 - for (const { [kRunning]: running } of this[kClients]) { - ret += running +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) } - return ret - } - get [kSize] () { - let ret = this[kQueued] - for (const { [kSize]: size } of this[kClients]) { - ret += size - } - return ret + return webidl.converters['record'](V) } - get stats () { - return this[kStats] - } + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + Headers, + HeadersList +} + + +/***/ }), + +/***/ 4881: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch + + + +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = __nccwpck_require__(7823) +const { Headers } = __nccwpck_require__(554) +const { Request, makeRequest } = __nccwpck_require__(8359) +const zlib = __nccwpck_require__(9796) +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__(2538) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const assert = __nccwpck_require__(9491) +const { safelyExtractBody } = __nccwpck_require__(1472) +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = __nccwpck_require__(1037) +const { kHeadersList } = __nccwpck_require__(2785) +const EE = __nccwpck_require__(2361) +const { Readable, pipeline } = __nccwpck_require__(2781) +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3983) +const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(685) +const { TransformStream } = __nccwpck_require__(5356) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { webidl } = __nccwpck_require__(1744) +const { STATUS_CODES } = __nccwpck_require__(3685) +const GET_OR_HEAD = ['GET', 'HEAD'] - async [kClose] () { - if (this[kQueue].isEmpty()) { - return Promise.all(this[kClients].map(c => c.close())) - } else { - return new Promise((resolve) => { - this[kClosedResolve] = resolve - }) - } - } +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream - async [kDestroy] (err) { - while (true) { - const item = this[kQueue].shift() - if (!item) { - break - } - item.handler.onError(err) - } +class Fetch extends EE { + constructor (dispatcher) { + super() - return Promise.all(this[kClients].map(c => c.destroy(err))) + 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) } - [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]() + terminate (reason) { + if (this.state !== 'ongoing') { + return } - return !this[kNeedDrain] + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) } - [kAddClient] (client) { - client - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', this[kOnDisconnect]) - .on('connectionError', this[kOnConnectionError]) + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } - this[kClients].push(client) + // 1. Set controller’s state to "aborted". + this.state = 'aborted' - if (this[kNeedDrain]) { - process.nextTick(() => { - if (this[kNeedDrain]) { - this[kOnDrain](client[kUrl], [this, client]) - } - }) + // 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') } - return this - } + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). - [kRemoveClient] (client) { - client.close(() => { - const idx = this[kClients].indexOf(client) - if (idx !== -1) { - this[kClients].splice(idx, 1) - } - }) + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error - this[kNeedDrain] = this[kClients].some(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) + this.connection?.destroy(error) + this.emit('terminated', error) } } -module.exports = { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kGetDispatcher -} - - -/***/ }), - -/***/ 39689: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) -const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(72785) -const kPool = Symbol('pool') + // 1. Let p be a new promise. + const p = createDeferredPromise() -class PoolStats { - constructor (pool) { - this[kPool] = pool - } + // 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 - get connected () { - return this[kPool][kConnected] + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise } - get free () { - return this[kPool][kFree] - } + // 3. Let request be requestObject’s request. + const request = requestObject[kState] - get pending () { - return this[kPool][kPending] - } + // 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) - get queued () { - return this[kPool][kQueued] + // 2. Return p. + return p.promise } - get running () { - return this[kPool][kRunning] - } + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject - get size () { - return this[kPool][kSize] + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' } -} - -module.exports = PoolStats - -/***/ }), - -/***/ 4634: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 7. Let responseObject be null. + let responseObject = null -"use strict"; + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null + // 9. Let locallyAborted be false. + let locallyAborted = false -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) + // 10. Let controller be null. + let controller = null -const kOptions = Symbol('options') -const kConnections = Symbol('connections') -const kFactory = Symbol('factory') + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true -function defaultFactory (origin, opts) { - return new Client(origin, opts) -} + // 2. Assert: controller is non-null. + assert(controller != null) -class Pool extends PoolBase { - constructor (origin, { - connections, - factory = defaultFactory, - connect, - connectTimeout, - tls, - maxCachedSessions, - socketPath, - autoSelectFamily, - autoSelectFamilyAttemptTimeout, - allowH2, - ...options - } = {}) { - super() + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) - if (connections != null && (!Number.isFinite(connections) || connections < 0)) { - throw new InvalidArgumentError('invalid connections') + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) } + ) - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() } - 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 - - this.on('connectionError', (origin, targets, error) => { - // If a connection error occurs, we remove the client from the pool, - // and emit a connectionError event. They will not be re-used. - // Fixes https://github.com/nodejs/undici/issues/3895 - for (const target of targets) { - // Do not use kRemoveClient here, as it will close the client, - // but the client cannot be closed in this state. - const idx = this[kClients].indexOf(target) - if (idx !== -1) { - this[kClients].splice(idx, 1) - } - } - }) - } + // 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. - [kGetDispatcher] () { - let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. - if (dispatcher) { - return dispatcher + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return Promise.resolve() } - if (!this[kConnections] || this[kClients].length < this[kConnections]) { - dispatcher = this[kFactory](this[kUrl], this[kOptions]) - this[kAddClient](dispatcher) + // 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() } - return dispatcher - } -} - -module.exports = Pool - - -/***/ }), - -/***/ 97858: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - + // 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 -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) + // 5. Resolve p with responseObject. + p.resolve(responseObject) + } -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') + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) -function defaultProtocolPort (protocol) { - return protocol === 'https:' ? 443 : 80 + // 14. Return p. + return p.promise } -function buildProxyOptions (opts) { - if (typeof opts === 'string') { - opts = { uri: opts } +// 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 } - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return } - return { - uri: opts.uri, - protocol: opts.protocol || 'https' - } -} + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] -function defaultFactory (origin, opts) { - return new Pool(origin, opts) -} + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo -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 - : [] + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState - if (typeof opts === 'string') { - opts = { uri: opts } - } + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') - } + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } - const { clientFactory = defaultFactory } = opts + // 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 + }) - if (typeof clientFactory !== 'function') { - throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') - } + // 2. Set cacheState to the empty string. + cacheState = '' + } - this[kRequestTls] = opts.requestTls - this[kProxyTls] = opts.proxyTls - this[kProxyHeaders] = opts.headers || {} + // 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() - const resolvedUrl = new URL(opts.uri) - const { origin, port, host, username, password } = resolvedUrl + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo - 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')}` - } + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) +} - 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) - } - } - }) +// 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') } - 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 - ) + // 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 + }) } - async [kClose] () { - await this[kAgent].close() - await this[kClient].close() + // 3. If responseObject is null, then return. + if (responseObject == null) { + return } - async [kDestroy] () { - await this[kAgent].destroy() - await this[kClient].destroy() + // 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 + }) } } -/** - * @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] - } +// 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 - return headersPair - } + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false - return headers -} + // 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 -/** - * @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') + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability } -} -module.exports = ProxyAgent + // 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 + } -/***/ 29459: -/***/ ((module) => { + // 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) -"use strict"; + // 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 + } -let fastNow = Date.now() -let fastNowTimeout + // 10. If all of the following conditions are true: + // TODO -const fastTimers = [] + // 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() + } + } -function onTimeout () { - fastNow = Date.now() + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' - let len = fastTimers.length - let idx = 0 - while (idx < len) { - const timer = fastTimers[idx] + // 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 - if (timer.state === 0) { - timer.state = fastNow + timer.delay - } else if (timer.state > 0 && fastNow >= timer.state) { - timer.state = -1 - timer.callback(timer.opaque) - } + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) + } - if (timer.state === -1) { - timer.state = -2 - if (idx !== len - 1) { - fastTimers[idx] = fastTimers.pop() - } else { - fastTimers.pop() - } - len -= 1 - } else { - idx += 1 - } + // 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', '*') } - if (fastTimers.length > 0) { - refreshTimeout() + // 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 } -} -function refreshTimeout () { - if (fastNowTimeout && fastNowTimeout.refresh) { - fastNowTimeout.refresh() - } else { - clearTimeout(fastNowTimeout) - fastNowTimeout = setTimeout(onTimeout, 1e3) - if (fastNowTimeout.unref) { - fastNowTimeout.unref() - } + // 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 } -class Timeout { - constructor (callback, delay, opaque) { - this.callback = callback - this.delay = delay - this.opaque = opaque +// 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 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 + // 2. Let response be null. + let response = null - this.refresh() + // 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') } - refresh () { - if (this.state === -2) { - fastTimers.push(this) - if (!fastNowTimeout || fastTimers.length === 1) { - refreshTimeout() - } - } + // 4. Run report Content Security Policy violations for request. + // TODO - this.state = 0 + // 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? - clear () { - this.state = -1 + // 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 } -} -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) - } + // 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 -/***/ 35354: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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) -"use strict"; + 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) + } -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) + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } -const channels = {} -channels.open = diagnosticsChannel.channel('undici:websocket:open') -channels.close = diagnosticsChannel.channel('undici:websocket:close') -channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + // 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' + ) + } -/** @type {import('crypto')} */ -let crypto -try { - crypto = __nccwpck_require__(6113) -} catch { + // 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) + } -/** - * @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 + // 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') + } - requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + // - 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 - // 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' - }) + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' - // Note: undici extension, allow setting custom headers. - if (options.headers) { - const headersList = new Headers(options.headers)[kHeadersList] + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } - request.headersList = headersList + // 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 } - // 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 + // 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 + } - // 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') + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] - // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s - // header list. - request.headersList.append('sec-websocket-key', keyValue) + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } - // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s - // header list. - request.headersList.append('sec-websocket-version', '13') + // 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) + } +} - // 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) +// 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)) } - // 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' + // 2. Let request be fetchParams’s request. + const { request } = fetchParams - // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to - // request’s header list. - // request.headersList.append('sec-websocket-extensions', permessageDeflate) + const { protocol: scheme } = requestCurrentURL(request) - // 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 - } + // 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. - // 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 + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = (__nccwpck_require__(4300).resolveObjectURL) } - // 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. + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) - // 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 + // 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.')) } - // 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 - } + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) - // 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 + // 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')) } - // 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') + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) - if (secExtension !== null && secExtension !== permessageDeflate) { - failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') - return - } + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] - // 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') + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) - if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { - failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') - return - } + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' - response.socket.on('data', onSocketData) - response.socket.on('close', onSocketClose) - response.socket.on('error', onSocketError) + // 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 }] + ] + }) - if (channels.open.hasSubscribers) { - channels.open.publish({ - address: response.socket.address(), - protocol: secProtocol, - extensions: secExtension - }) + 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')) } - onEstablish(response) + // 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 controller + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } } -/** - * @param {Buffer} chunk - */ -function onSocketData (chunk) { - if (!this.ws[kByteParser].write(chunk)) { - this.pause() +// 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)) } } -/** - * @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 +// 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]] - // 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] + // 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 + }) + } - let code = 1005 - let reason = '' + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true - const result = ws[kByteParser].closingInfo + // 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)) + } + } - 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 + // 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)) } - // 1. Change the ready state to CLOSED (3). - ws[kReadyState] = states.CLOSED + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: - // 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 + // 1. Let transformStream be a new a TransformStream. - // 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 - }) + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) + } - if (channels.close.hasSubscribers) { - channels.close.publish({ - websocket: ws, - code, - reason + // 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) } } -} -function onSocketError (error) { - const { ws } = this + // 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) - ws[kReadyState] = states.CLOSING + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) - if (channels.socketError.hasSubscribers) { - channels.socketError.publish(error) + // 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() } - - this.destroy() -} - -module.exports = { - establishWebSocketConnection } +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request -/***/ }), - -/***/ 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' + // 2. Let response be null. + let response = null -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} + // 3. Let actualResponse be null. + let actualResponse = null -const states = { - CONNECTING: 0, - OPEN: 1, - CLOSING: 2, - CLOSED: 3 -} + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo -const opcodes = { - CONTINUATION: 0x0, - TEXT: 0x1, - BINARY: 0x2, - CLOSE: 0x8, - PING: 0x9, - PONG: 0xA -} + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } -const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO -const parserStates = { - INFO: 0, - PAYLOADLENGTH_16: 2, - PAYLOADLENGTH_64: 3, - READ_DATA: 4 -} + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } -const emptyBuffer = Buffer.allocUnsafe(0) + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) -module.exports = { - uid, - staticPropertyDescriptors, - states, - opcodes, - maxUnsigned16Bit, - parserStates, - emptyBuffer -} + // 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') + } -/***/ 52611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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() + } -"use strict"; + // 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 -const { webidl } = __nccwpck_require__(21744) -const { kEnumerableProperty } = __nccwpck_require__(83983) -const { MessagePort } = __nccwpck_require__(71267) + // 10. Return response. + return response +} -/** - * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent - */ -class MessageEvent extends Event { - #eventInit +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request - constructor (type, eventInitDict = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) + // 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 - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.MessageEventInit(eventInitDict) + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL - super(type, eventInitDict) + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) - this.#eventInit = eventInitDict + // 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)) } - get data () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.data + // 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')) } - get origin () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.origin + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) } - get lastEventId () { - webidl.brandCheck(this, MessageEvent) + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 - return this.#eventInit.lastEventId + // 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"')) } - get source () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.source + // 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"' + )) } - get ports () { - webidl.brandCheck(this, MessageEvent) - - if (!Object.isFrozen(this.#eventInit.ports)) { - Object.freeze(this.#eventInit.ports) - } - - return this.#eventInit.ports + // 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()) } - initMessageEvent ( - type, - bubbles = false, - cancelable = false, - data = null, - origin = '', - lastEventId = '', - source = null, - ports = [] + // 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)) ) { - webidl.brandCheck(this, MessageEvent) - - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null - return new MessageEvent(type, { - bubbles, cancelable, data, origin, lastEventId, source, ports - }) + // 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) + } } -} - -/** - * @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) + // 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') - super(type, eventInitDict) + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) - this.#eventInit = eventInitDict + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') } - get wasClean () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.wasClean + // 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] } - get code () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.code - } + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo - get reason () { - webidl.brandCheck(this, CloseEvent) + // 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) - return this.#eventInit.reason + // 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 } -} -// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface -class ErrorEvent extends Event { - #eventInit + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) - constructor (type, eventInitDict) { - webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) - super(type, eventInitDict) + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) +// 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 - this.#eventInit = eventInitDict - } + // 2. Let httpFetchParams be null. + let httpFetchParams = null - get message () { - webidl.brandCheck(this, ErrorEvent) + // 3. Let httpRequest be null. + let httpRequest = null - return this.#eventInit.message - } + // 4. Let response be null. + let response = null - get filename () { - webidl.brandCheck(this, ErrorEvent) + // 5. Let storedResponse be null. + // TODO: cache - return this.#eventInit.filename - } + // 6. Let httpCache be null. + const httpCache = null - get lineno () { - webidl.brandCheck(this, ErrorEvent) + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false - return this.#eventInit.lineno - } + // 8. Run these steps, but abort when the ongoing fetch is terminated: - get colno () { - webidl.brandCheck(this, ErrorEvent) + // 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: - return this.#eventInit.colno - } + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) - get error () { - webidl.brandCheck(this, ErrorEvent) + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } - return this.#eventInit.error + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest } -} - -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) + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.MessagePort -) + // 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 -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 - } -] + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null -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 [] - } + // 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' } -]) -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: '' + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) } -]) -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 + // 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) } -]) - -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 { -} + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. -class WebsocketFrameSend { - /** - * @param {Buffer|undefined} data - */ - constructor (data) { - this.frameData = data - this.maskKey = crypto.randomBytes(4) + // 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. } - createFrame (opcode) { - const bodyLength = this.frameData?.byteLength ?? 0 - - /** @type {number} */ - let payloadLength = bodyLength // 0-125 - let offset = 6 + // 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)) + } - 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 - } + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) - const buffer = Buffer.allocUnsafe(bodyLength + offset) + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) - // Clear first 2 bytes, everything else is overwritten - buffer[0] = buffer[1] = 0 - buffer[0] |= 0x80 // FIN - buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + // 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') + } - /*! 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] + // 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' + } - buffer[1] = payloadLength + // 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') + } - 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) + // 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') } - buffer[1] |= 0x80 // MASK - - // mask body - for (let i = 0; i < bodyLength; i++) { - buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + // 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') } + } - return buffer + // 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') } -} -module.exports = { - WebsocketFrameSend -} + // 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 + } -/***/ 11688: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication -"use strict"; + // 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' + } -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) + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache + } -// 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 + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO -const channels = {} -channels.ping = diagnosticsChannel.channel('undici:websocket:ping') -channels.pong = diagnosticsChannel.channel('undici:websocket:pong') + // 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') + } -class ByteParser extends Writable { - #buffers = [] - #byteOffset = 0 + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) - #state = parserStates.INFO + // 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 + } - #info = {} - #fragments = [] + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } - constructor (ws) { - super() + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse - this.ws = ws + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } } - /** - * @param {Buffer} chunk - * @param {() => void} callback - */ - _write (chunk, _, callback) { - this.#buffers.push(chunk) - this.#byteOffset += chunk.length + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] - this.run(callback) + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true } - /** - * 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() - } + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials - const buffer = this.consume(2) + // 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 - this.#info.fin = (buffer[0] & 0x80) !== 0 - this.#info.opcode = buffer[0] & 0x0F + // 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() + } - // 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 + // 2. ??? - this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } - 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 - } + // 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? - const payloadLength = buffer[1] & 0x7F + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } - 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 - } + // 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: - 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 - } + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } - const body = this.consume(payloadLength) + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. - this.#info.closeInfo = this.parseCloseBody(false, body) + // 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() - 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) + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } - this.ws[kResponse].socket.write( - closeFrame.createFrame(opcodes.CLOSE), - (err) => { - if (!err) { - this.ws[kSentClose] = true - } - } - ) - } + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } - // 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 + // 18. Return response. + return response +} - this.end() +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) - 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" + 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')) + } + } + } - const body = this.consume(payloadLength) + // 1. Let request be fetchParams’s request. + const request = fetchParams.request - if (!this.ws[kReceivedClose]) { - const frame = new WebsocketFrameSend(body) + // 2. Let response be null. + let response = null - this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo - if (channels.ping.hasSubscribers) { - channels.ping.publish({ - payload: body - }) - } - } + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null - this.#state = parserStates.INFO + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } - 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. + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO - const body = this.consume(payloadLength) + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars - if (channels.pong.hasSubscribers) { - channels.pong.publish({ - payload: body - }) - } + // 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 + } - if (this.#byteOffset > 0) { - continue - } else { - callback() - return - } - } - } else if (this.#state === parserStates.PAYLOADLENGTH_16) { - if (this.#byteOffset < 2) { - return callback() - } + // 9. Run these steps, but abort when the ongoing fetch is terminated: - const buffer = this.consume(2) + // 1. If connection is failure, then return a network error. - this.#info.payloadLength = buffer.readUInt16BE(0) - this.#state = parserStates.READ_DATA - } else if (this.#state === parserStates.PAYLOADLENGTH_64) { - if (this.#byteOffset < 8) { - return callback() - } + // 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. - const buffer = this.consume(8) - const upper = buffer.readUInt32BE(0) + // 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. - // 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 - } + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. - const lower = buffer.readUInt32BE(4) + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: - 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 + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] - const body = this.consume(this.#info.payloadLength) + // - 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. - this.#fragments.push(body) + // - 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). - // 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) + // - Wait until all the headers are transmitted. - websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) + // - 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. - this.#info = {} - this.#fragments.length = 0 - } + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. - this.#state = parserStates.INFO - } - } + // - If the HTTP request results in a TLS client certificate dialog, then: - if (this.#byteOffset > 0) { - continue - } else { - callback() - break + // 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 } - } - } - /** - * 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 - } + // 2. Run this step in parallel: transmit bytes. + yield bytes - if (this.#buffers[0].length === n) { - this.#byteOffset -= this.#buffers[0].length - return this.#buffers.shift() + // 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) } - const buffer = Buffer.allocUnsafe(n) - let offset = 0 - - while (offset !== n) { - const next = this.#buffers[0] - const { length } = next + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } - 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 + // 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() } } - this.#byteOffset -= n - - return buffer - } - - parseCloseBody (onlyCode, data) { - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 - /** @type {number|undefined} */ - let code + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } - 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) + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } } - if (onlyCode) { - if (!isValidStatusCode(code)) { - return null + // 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) } + })() + } - return { code } - } - - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 - /** @type {Buffer} */ - let reason = data.subarray(2) + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) - // Remove BOM - if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { - reason = reason.subarray(3) - } + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() - if (code !== undefined && !isValidStatusCode(code)) { - return null + 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() - try { - // TODO: optimize this - reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) - } catch { - return null + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) } - return { code, reason } + return makeNetworkError(err) } - get closingInfo () { - return this.#info.closeInfo + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() } -} -module.exports = { - ByteParser -} + // 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 -/***/ 37578: -/***/ ((module) => { + // 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__(5356).ReadableStream) + } -"use strict"; + 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: -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') -} + // 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 -/***/ 25515: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 18. If aborted, then: + // TODO -"use strict"; + // 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... -const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(37578) -const { states, opcodes } = __nccwpck_require__(19188) -const { MessageEvent, ErrorEvent } = __nccwpck_require__(52611) + // 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() -/* globals Blob */ + if (isAborted(fetchParams)) { + break + } -/** - * @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 -} + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err -/** - * @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 -} + // 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 + } + } -/** - * @param {import('./websocket').WebSocket} ws - */ -function isClosed (ws) { - return ws[kReadyState] === states.CLOSED -} + 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) -/** - * @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. + finalizeResponse(fetchParams, response) - // 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 + return + } - // 4. Initialize any other IDL attributes of event as described in the - // invocation of this algorithm. + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 - // 5. Return the result of dispatching event at target, with legacy target - // override flag set if set. - target.dispatchEvent(event) -} + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } -/** - * @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 - } + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) - // 2. Let dataForEvent be determined by switching on type and binary type: - let dataForEvent + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } - 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 + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } } } - // 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) + // 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 - 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 + // 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 + })) + } } - } - - 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) - }) + // 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() } -} -module.exports = { - isEstablished, - isClosing, - isClosed, - fireEvent, - isValidSubprotocol, - isValidStatusCode, - failWebsocketConnection, - websocketMessageReceived -} - - -/***/ }), + // 20. Return response. + return response -/***/ 54284: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher -"use strict"; + 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 -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) + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, -let experimentalWarned = false + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } -// https://websockets.spec.whatwg.org/#interface-definition -class WebSocket extends EventTarget { - #events = { - open: null, - error: null, - close: null, - message: null - } + let codings = [] + let location = '' - #bufferedAmount = 0 - #protocol = '' - #extensions = '' + const headers = new Headers() - /** - * @param {string} url - * @param {string|string[]} protocols - */ - constructor (url, protocols = []) { - super() + // 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 + } - webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) + 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 + } - if (!experimentalWarned) { - experimentalWarned = true - process.emitWarning('WebSockets are experimental, expect them to change at any time.', { - code: 'UNDICI-WS' - }) - } + headers[kHeadersList].append(key, val) + } + } - const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) + this.body = new Readable({ read: resume }) - url = webidl.converters.USVString(url) - protocols = options.protocols + const decoders = [] - // 1. Let baseURL be this's relevant settings object's API base URL. - const baseURL = getGlobalOrigin() + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) - // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. - let urlRecord + // 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 + } + } + } - try { - urlRecord = new URL(url, baseURL) - } catch (e) { - // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. - throw new DOMException(e, 'SyntaxError') - } + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) - // 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:' - } + return true + }, - // 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' - ) - } + onData (chunk) { + if (fetchParams.controller.dump) { + return + } - // 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') - } + // 1. If one or more bytes have been transmitted from response’s + // message body, then: - // 8. If protocols is a string, set protocols to a sequence consisting - // of just that string. - if (typeof protocols === 'string') { - protocols = [protocols] - } + // 1. Let bytes be the transmitted bytes. + const bytes = chunk - // 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') - } + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. - if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { - throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') - } + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength - // 10. Set this's url to urlRecord. - this[kWebSocketURL] = new URL(urlRecord.href) + // 4. See pullAlgorithm... - // 11. Let client be this's relevant settings object. + return this.body.push(bytes) + }, - // 12. Run this step in parallel: + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } - // 1. Establish a WebSocket connection given urlRecord, protocols, - // and client. - this[kController] = establishWebSocketConnection( - urlRecord, - protocols, - this, - (response) => this.#onConnectionEstablished(response), - options - ) + fetchParams.controller.ended = true - // 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 + this.body.push(null) + }, - // The extensions attribute must initially return the empty string. + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } - // The protocol attribute must initially return the empty string. + this.body?.destroy(error) - // Each WebSocket object has an associated binary type, which is a - // BinaryType. Initially it must be "blob". - this[kBinaryType] = 'blob' - } + fetchParams.controller.terminate(error) - /** - * @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) + reject(error) + }, - if (code !== undefined) { - code = webidl.converters['unsigned short'](code, { clamp: true }) - } + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } - if (reason !== undefined) { - reason = webidl.converters.USVString(reason) - } + const headers = new Headers() - // 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') - } - } + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') - let reasonByteLength = 0 + headers[kHeadersList].append(key, val) + } - // 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) + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) - if (reasonByteLength > 123) { - throw new DOMException( - `Reason must be less than 123 bytes; received ${reasonByteLength}`, - 'SyntaxError' - ) + return true + } } - } - - // 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() +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} - // 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 +/***/ 8359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - socket.write(frame.createFrame(opcodes.CLOSE), (err) => { - if (!err) { - this[kSentClose] = true - } - }) +"use strict"; +/* globals AbortController */ - // 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' }) +const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(1472) +const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(554) +const { FinalizationRegistry } = __nccwpck_require__(6436)() +const util = __nccwpck_require__(3983) +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer, + normalizeMethodRecord +} = __nccwpck_require__(2538) +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = __nccwpck_require__(1037) +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(2361) - data = webidl.converters.WebSocketSendData(data) +let TransformStream = globalThis.TransformStream - // 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') - } +const kAbortController = Symbol('abortController') - // 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 +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) - if (!isEstablished(this) || isClosing(this)) { +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kConstruct) { return } - /** @type {import('stream').Duplex} */ - const socket = this[kResponse].socket + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) - // 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. + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) - const value = Buffer.from(data) - const frame = new WebsocketFrameSend(value) - const buffer = frame.createFrame(opcodes.TEXT) + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } + } - 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. + // 1. Let request be null. + let request = null - const value = Buffer.from(data) - const frame = new WebsocketFrameSend(value) - const buffer = frame.createFrame(opcodes.BINARY) + // 2. Let fallbackMode be null. + let fallbackMode = null - 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. + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl - const ab = Buffer.from(data, data.byteOffset, data.byteLength) + // 4. Let signal be null. + let signal = null - const frame = new WebsocketFrameSend(ab) - const buffer = frame.createFrame(opcodes.BINARY) + // 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 }) + } - 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. + // 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 + ) + } - const frame = new WebsocketFrameSend() + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) - data.arrayBuffer().then((ab) => { - const value = Buffer.from(ab) - frame.frameData = value - const buffer = frame.createFrame(opcodes.BINARY) + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - }) + // 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] } - } - get readyState () { - webidl.brandCheck(this, WebSocket) + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin - // The readyState getter steps are to return this's ready state. - return this[kReadyState] - } + // 8. Let window be "client". + let window = 'client' - get bufferedAmount () { - webidl.brandCheck(this, WebSocket) + // 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 + } - return this.#bufferedAmount - } + // 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`) + } - get url () { - webidl.brandCheck(this, WebSocket) + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } - // The url getter steps are to return this's url, serialized. - return URLSerializer(this[kWebSocketURL]) - } + // 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] + }) - get extensions () { - webidl.brandCheck(this, WebSocket) + const initHasKey = Object.keys(init).length !== 0 - return this.#extensions - } + // 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' + } - get protocol () { - webidl.brandCheck(this, WebSocket) + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false - return this.#protocol - } + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false - get onopen () { - webidl.brandCheck(this, WebSocket) + // 4. Set request’s origin to "client". + request.origin = 'client' - return this.#events.open - } + // 5. Set request’s referrer to "client" + request.referrer = 'client' - set onopen (fn) { - webidl.brandCheck(this, WebSocket) + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' - if (this.#events.open) { - this.removeEventListener('open', this.#events.open) - } + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] - if (typeof fn === 'function') { - this.#events.open = fn - this.addEventListener('open', fn) - } else { - this.#events.open = null + // 8. Set request’s URL list to Ā« request’s URL Ā». + request.urlList = [request.url] } - } - get onerror () { - webidl.brandCheck(this, WebSocket) + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer - return this.#events.error - } + // 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 }) + } - set onerror (fn) { - webidl.brandCheck(this, WebSocket) + // 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 + } + } + } - if (this.#events.error) { - this.removeEventListener('error', this.#events.error) + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy } - if (typeof fn === 'function') { - this.#events.error = fn - this.addEventListener('error', fn) + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode } else { - this.#events.error = null + mode = fallbackMode } - } - - 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) + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) } - if (typeof fn === 'function') { - this.#events.close = fn - this.addEventListener('close', fn) - } else { - this.#events.close = null + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode } - } - - 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) + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials } - if (typeof fn === 'function') { - this.#events.message = fn - this.addEventListener('message', fn) - } else { - this.#events.message = null + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache } - } - - 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 + // 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" + ) } - } - - /** - * @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 + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect } - // 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 + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) } - // 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) - } + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } - return webidl.converters.DOMString(V) -} + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method -// 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) - } -]) + // 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.`) + } -webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { - if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { - return webidl.converters.WebSocketInit(V) - } + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } - return { protocols: webidl.converters['DOMString or sequence'](V) } -} + // 3. Normalize method. + method = normalizeMethodRecord[method] ?? normalizeMethod(method) -webidl.converters.WebSocketSendData = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) + // 4. Set request’s method to method. + request.method = method } - if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { - return webidl.converters.BufferSource(V) + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal } - } - - return webidl.converters.USVString(V) -} -module.exports = { - WebSocket -} + // 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." + ) + } -/***/ 45030: -/***/ ((__unused_webpack_module, exports) => { + 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 -"use strict"; + 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 {} -Object.defineProperty(exports, "__esModule", ({ value: true })); + util.addAbortListener(signal, abort) + requestFinalizer.register(ac, { signal, abort }) + } + } -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } + // 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] - if (typeof process === "object" && process.version !== undefined) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } + // 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.` + ) + } - return ""; -} + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map + // 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) + } + } -/***/ 65278: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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.') + } -/** - * For Node.js, simply re-export the core `util.deprecate` function. - */ + // 35. Let initBody be null. + let initBody = null -module.exports = __nccwpck_require__(73837).deprecate; + // 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 -/***/ 82116: -/***/ ((module) => { + // 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.') + } -"use strict"; + // 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 + } -var conversions = {}; -module.exports = conversions; + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody -function sign(x) { - return x < 0 ? -1 : 1; -} + // 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.' + ) + } -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); - } -} + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = (__nccwpck_require__(5356).TransformStream) + } -function createNumberConversion(bitLength, typeOpts) { - if (!typeOpts.unsigned) { - --bitLength; + // 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 + } } - 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); + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } - return function(V, opts) { - if (!opts) opts = {}; + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) - let x = +V; + // The method getter steps are to return this’s request’s method. + return this[kState].method + } - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite number"); - } + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) - x = sign(x) * Math.floor(Math.abs(x)); - if (x < lowerBound || x > upperBound) { - throw new TypeError("Argument is not in byte range"); - } + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } - return x; - } + // 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) - if (!isNaN(x) && opts.clamp) { - x = evenRound(x); + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } - if (x < lowerBound) x = lowerBound; - if (x > upperBound) x = upperBound; - return x; - } + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) - if (!Number.isFinite(x) || x === 0) { - return 0; - } + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } - x = sign(x) * Math.floor(Math.abs(x)); - x = x % moduloVal; + // 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) - 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; - } - } + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } - return x; + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' } -} -conversions["void"] = function () { - return undefined; -}; + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } -conversions["boolean"] = function (val) { - return !!val; -}; + // 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) -conversions["byte"] = createNumberConversion(8, { unsigned: false }); -conversions["octet"] = createNumberConversion(8, { unsigned: true }); + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } -conversions["short"] = createNumberConversion(16, { unsigned: false }); -conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + // 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) -conversions["long"] = createNumberConversion(32, { unsigned: false }); -conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } -conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); -conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + // 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 + } -conversions["double"] = function (V) { - const x = +V; + // 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) - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite floating-point value"); - } + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } - return x; -}; + // 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) -conversions["unrestricted double"] = function (V) { - const x = +V; + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } - if (isNaN(x)) { - throw new TypeError("Argument is NaN"); - } + // 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) - return x; -}; + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } -// not quite valid, but good enough for JS -conversions["float"] = conversions["double"]; -conversions["unrestricted float"] = conversions["unrestricted double"]; + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) -conversions["DOMString"] = function (V, opts) { - if (!opts) opts = {}; + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) - return String(V); -}; + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } -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"); - } - } + // 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) - return x; -}; + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } -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)); - } - } - } - } + // 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) - return U.join(''); -}; + // The signal getter steps are to return this’s signal. + return this[kSignal] + } -conversions["Date"] = function (V, opts) { - if (!(V instanceof Date)) { - throw new TypeError("Argument is not a Date object"); - } - if (isNaN(V)) { - return undefined; - } + get body () { + webidl.brandCheck(this, Request) - return V; -}; + return this[kState].body ? this[kState].body.stream : null + } -conversions["RegExp"] = function (V, opts) { - if (!(V instanceof RegExp)) { - V = new RegExp(V); - } + get bodyUsed () { + webidl.brandCheck(this, Request) - return V; -}; + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + get duplex () { + webidl.brandCheck(this, Request) -/***/ }), + return 'half' + } -/***/ 97537: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) -"use strict"; + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } -const usm = __nccwpck_require__(2158); + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) -exports.implementation = class URLImpl { - constructor(constructorArgs) { - const url = constructorArgs[0]; - const base = constructorArgs[1]; + // 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] - let parsedBase = null; - if (base !== undefined) { - parsedBase = usm.basicURLParse(base); - if (parsedBase === "failure") { - throw new TypeError("Invalid base URL"); - } + // 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 - const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } + // 4. Return clonedRequestObject. + return clonedRequestObject + } +} - this._url = parsedURL; +mixinBody(Request) - // TODO: query stuff +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 +} - get href() { - return usm.serializeURL(this._url); - } +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: - set href(v) { - const parsedURL = usm.basicURLParse(v); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) - this._url = parsedURL; + // 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) } - get origin() { - return usm.serializeURLOrigin(this._url); - } + // 3. Return newRequest. + return newRequest +} - get protocol() { - return this._url.scheme + ":"; +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 +) - set protocol(v) { - usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) } - get username() { - return this._url.username; + if (V instanceof Request) { + return webidl.converters.Request(V) } - set username(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } + return webidl.converters.USVString(V) +} - usm.setTheUsername(this._url, v); - } +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) - get password() { - return this._url.password; +// 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 } +]) - set password(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } +module.exports = { Request, makeRequest } - usm.setThePassword(this._url, v); - } - get host() { - const url = this._url; +/***/ }), - if (url.host === null) { - return ""; - } +/***/ 7823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (url.port === null) { - return usm.serializeHost(url.host); - } +"use strict"; - return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); - } - set host(v) { - if (this._url.cannotBeABaseURL) { - return; - } +const { Headers, HeadersList, fill } = __nccwpck_require__(554) +const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(1472) +const util = __nccwpck_require__(3983) +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = __nccwpck_require__(2538) +const { + redirectStatusSet, + nullBodyStatus, + DOMException +} = __nccwpck_require__(1037) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { FormData } = __nccwpck_require__(2015) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { types } = __nccwpck_require__(3837) - usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); - } +const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') - get hostname() { - if (this._url.host === null) { - return ""; - } +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } - return usm.serializeHost(this._url.host); + // 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 } - set hostname(v) { - if (this._url.cannotBeABaseURL) { - return; + // 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) } - usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); - } + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) - get port() { - if (this._url.port === null) { - return ""; - } + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) - return usm.serializeInteger(this._url.port); - } + // 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 - set port(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) - if (v === "") { - this._url.port = null; - } else { - usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); - } + // 5. Return responseObject. + return responseObject } - get pathname() { - if (this._url.cannotBeABaseURL) { - return this._url.path[0]; + // 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 + }) } - if (this._url.path.length === 0) { - return ""; + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) } - return "/" + this._url.path.join("/"); - } + // 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)) - set pathname(v) { - if (this._url.cannotBeABaseURL) { - return; - } + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) - this._url.path = []; - usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + // 8. Return responseObject. + return responseObject } - get search() { - if (this._url.query === null || this._url.query === "") { - return ""; + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) } - return "?" + this._url.query; - } + init = webidl.converters.ResponseInit(init) - set search(v) { - // TODO: query stuff + // TODO + this[kRealm] = { settingsObject: {} } - const url = this._url; + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) - if (v === "") { - url.query = null; - return; - } + // 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] - const input = v[0] === "?" ? v.substring(1) : v; - url.query = ""; - usm.basicURLParse(input, { url, stateOverride: "query" }); - } + // 3. Let bodyWithType be null. + let bodyWithType = null - get hash() { - if (this._url.fragment === null || this._url.fragment === "") { - return ""; + // 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 } } - return "#" + this._url.fragment; + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) } - 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" }); - } + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) - toJSON() { - return this.href; + // 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) -/***/ 63394: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const urlList = this[kState].urlList -"use strict"; + // 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 '' + } -const conversions = __nccwpck_require__(82116); -const utils = __nccwpck_require__(83185); -const Impl = __nccwpck_require__(97537); + return URLSerializer(url, true) + } -const impl = utils.implSymbol; + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) -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]); + // 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 } - module.exports.setup(this, args); -} + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) -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]; + // The status getter steps are to return this’s response’s status. + return this[kState].status } - 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"); + // 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 } - return this.href; -}; -Object.defineProperty(URL.prototype, "origin", { - get() { - return this[impl].origin; - }, - enumerable: true, - configurable: true -}); + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) -Object.defineProperty(URL.prototype, "protocol", { - get() { - return this[impl].protocol; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].protocol = V; - }, - enumerable: true, - configurable: true -}); + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } -Object.defineProperty(URL.prototype, "username", { - get() { - return this[impl].username; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].username = V; - }, - enumerable: true, - configurable: true -}); + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) -Object.defineProperty(URL.prototype, "password", { - get() { - return this[impl].password; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].password = V; - }, - enumerable: true, - configurable: true -}); + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } -Object.defineProperty(URL.prototype, "host", { - get() { - return this[impl].host; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].host = V; - }, - enumerable: true, - configurable: true -}); + get body () { + webidl.brandCheck(this, Response) -Object.defineProperty(URL.prototype, "hostname", { - get() { - return this[impl].hostname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hostname = V; - }, - enumerable: true, - configurable: true -}); + return this[kState].body ? this[kState].body.stream : null + } -Object.defineProperty(URL.prototype, "port", { - get() { - return this[impl].port; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].port = V; - }, - enumerable: true, - configurable: true -}); + get bodyUsed () { + webidl.brandCheck(this, Response) -Object.defineProperty(URL.prototype, "pathname", { - get() { - return this[impl].pathname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].pathname = V; - }, - enumerable: true, - configurable: true -}); + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } -Object.defineProperty(URL.prototype, "search", { - get() { - return this[impl].search; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].search = V; - }, - enumerable: true, - configurable: true -}); + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) -Object.defineProperty(URL.prototype, "hash", { - get() { - return this[impl].hash; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hash = V; - }, - enumerable: true, - configurable: true -}); + // 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]) -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; + // 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] - obj[impl] = new Impl.implementation(constructorArgs, privateData); - obj[impl][utils.wrapperSymbol] = obj; - }, - interface: URL, - expose: { - Window: { URL: URL }, - Worker: { URL: URL } + return clonedResponseObject } -}; - - +} -/***/ }), +mixinBody(Response) -/***/ 28665: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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 + } +}) -"use strict"; +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: -exports.URL = __nccwpck_require__(63394)["interface"]; -exports.serializeURL = __nccwpck_require__(2158).serializeURL; -exports.serializeURLOrigin = __nccwpck_require__(2158).serializeURLOrigin; -exports.basicURLParse = __nccwpck_require__(2158).basicURLParse; -exports.setTheUsername = __nccwpck_require__(2158).setTheUsername; -exports.setThePassword = __nccwpck_require__(2158).setThePassword; -exports.serializeHost = __nccwpck_require__(2158).serializeHost; -exports.serializeInteger = __nccwpck_require__(2158).serializeInteger; -exports.parseURL = __nccwpck_require__(2158).parseURL; + // 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) + } -/***/ 2158: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 4. Return newResponse. + return newResponse +} -"use strict"; - -const punycode = __nccwpck_require__(85477); -const tr46 = __nccwpck_require__(84256); - -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 }); -}; +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 + } -/***/ 83185: -/***/ ((module) => { + 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 + } + }) +} -"use strict"; +// 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. -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])); - } -}; + // 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. -module.exports.wrapperSymbol = Symbol("wrapper"); -module.exports.implSymbol = Symbol("impl"); + 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. -module.exports.wrapperForImpl = function (impl) { - return impl[module.exports.wrapperSymbol]; -}; + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} -module.exports.implForWrapper = function (wrapper) { - return wrapper[module.exports.implSymbol]; -}; +// 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') + } + } -/***/ 62940: -/***/ ((module) => { + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status + } -// 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) + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') + // 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) + } - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) + // 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 + }) + } - return wrapper + // 2. Set response's body to body's body. + response[kState].body = body.body - 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] - }) + // 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) } - return ret } } +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 +} + /***/ }), -/***/ 9887: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 5861: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.mainRun = mainRun; -const core = __importStar(__nccwpck_require__(42186)); -const commit_use_case_1 = __nccwpck_require__(85016); -const issue_comment_use_case_1 = __nccwpck_require__(50854); -const issue_use_case_1 = __nccwpck_require__(58675); -const pull_request_review_comment_use_case_1 = __nccwpck_require__(67883); -const pull_request_use_case_1 = __nccwpck_require__(53478); -const single_action_use_case_1 = __nccwpck_require__(6479); -const logger_1 = __nccwpck_require__(38836); -const constants_1 = __nccwpck_require__(8593); -const chalk_1 = __importDefault(__nccwpck_require__(77037)); -const boxen_1 = __importDefault(__nccwpck_require__(46192)); -const queue_utils_1 = __nccwpck_require__(99800); -async function mainRun(execution) { - const results = []; - await execution.setup(); - if (!execution.welcome) { - /** - * Wait for previous runs to finish - */ - await (0, queue_utils_1.waitForPreviousRuns)(execution).catch((err) => { - (0, logger_1.logError)(`Error waiting for previous runs: ${err}`); - process.exit(1); - }); - } - if (execution.runnedByToken) { - if (execution.isSingleAction && execution.singleAction.validSingleAction) { - (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Executing single action.`); - results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); - return results; - } - (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Ignoring.`); - return results; - } - if (execution.issueNumber === -1) { - if (execution.isSingleAction && execution.singleAction.isSingleActionWithoutIssue) { - results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); - } - else { - (0, logger_1.logInfo)(`Issue number not found. Skipping.`); - } - return results; - } - if (execution.welcome) { - (0, logger_1.logInfo)((0, boxen_1.default)(chalk_1.default.cyan(execution.welcome.title) + '\n' + - execution.welcome.messages.map(message => chalk_1.default.gray(message)).join('\n'), { - padding: 1, - margin: 1, - borderStyle: 'round', - borderColor: 'cyan', - title: constants_1.TITLE, - titleAlignment: 'center' - })); - } - try { - if (execution.isSingleAction) { - results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); - } - else if (execution.isIssue) { - if (execution.issue.isIssueComment) { - results.push(...await new issue_comment_use_case_1.IssueCommentUseCase().invoke(execution)); - } - else { - results.push(...await new issue_use_case_1.IssueUseCase().invoke(execution)); - } - } - else if (execution.isPullRequest) { - if (execution.pullRequest.isPullRequestReviewComment) { - results.push(...await new pull_request_review_comment_use_case_1.PullRequestReviewCommentUseCase().invoke(execution)); - } - else { - results.push(...await new pull_request_use_case_1.PullRequestUseCase().invoke(execution)); - } - } - else if (execution.isPush) { - results.push(...await new commit_use_case_1.CommitUseCase().invoke(execution)); - } - else { - core.setFailed(`Action not handled.`); - } - return results; + +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') +} + + +/***/ }), + +/***/ 2538: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(1037) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { performance } = __nccwpck_require__(4074) +const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3983) +const assert = __nccwpck_require__(9491) +const { isUint8Array } = __nccwpck_require__(9830) + +let supportedHashes = [] + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = __nccwpck_require__(6113) + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} 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 } - catch (error) { - core.setFailed(error.message); - return []; + } + 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 + } -/***/ 87002: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } -"use strict"; + return true +} -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.runLocalAction = runLocalAction; -const chalk_1 = __importDefault(__nccwpck_require__(77037)); -const ai_1 = __nccwpck_require__(64470); -const branches_1 = __nccwpck_require__(45308); -const docker_config_1 = __nccwpck_require__(61684); -const emoji_1 = __nccwpck_require__(9463); -const execution_1 = __nccwpck_require__(87550); -const hotfix_1 = __nccwpck_require__(87341); -const images_1 = __nccwpck_require__(51721); -const issue_1 = __nccwpck_require__(42632); -const issue_types_1 = __nccwpck_require__(71975); -const labels_1 = __nccwpck_require__(10818); -const locale_1 = __nccwpck_require__(82152); -const projects_1 = __nccwpck_require__(1938); -const pull_request_1 = __nccwpck_require__(84179); -const release_1 = __nccwpck_require__(12551); -const single_action_1 = __nccwpck_require__(28024); -const size_threshold_1 = __nccwpck_require__(23835); -const size_thresholds_1 = __nccwpck_require__(98237); -const supabase_config_1 = __nccwpck_require__(149); -const tokens_1 = __nccwpck_require__(53421); -const welcome_1 = __nccwpck_require__(89471); -const workflows_1 = __nccwpck_require__(38553); -const project_repository_1 = __nccwpck_require__(67917); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -const yml_utils_1 = __nccwpck_require__(48198); -const common_action_1 = __nccwpck_require__(9887); -const boxen_1 = __importDefault(__nccwpck_require__(46192)); -async function runLocalAction(additionalParams) { - const projectRepository = new project_repository_1.ProjectRepository(); - const actionInputs = (0, yml_utils_1.getActionInputsWithDefaults)(); - /** - * Debug - */ - const debug = (additionalParams[constants_1.INPUT_KEYS.DEBUG] ?? actionInputs[constants_1.INPUT_KEYS.DEBUG]) == 'true'; - /** - * Welcome - */ - const welcomeTitle = additionalParams[constants_1.INPUT_KEYS.WELCOME_TITLE] ?? actionInputs[constants_1.INPUT_KEYS.WELCOME_TITLE]; - const welcomeMessages = additionalParams[constants_1.INPUT_KEYS.WELCOME_MESSAGES] ?? actionInputs[constants_1.INPUT_KEYS.WELCOME_MESSAGES]; - /** - * Docker - */ - const dockerContainerName = additionalParams[constants_1.INPUT_KEYS.DOCKER_CONTAINER_NAME] ?? actionInputs[constants_1.INPUT_KEYS.DOCKER_CONTAINER_NAME]; - const dockerDomain = additionalParams[constants_1.INPUT_KEYS.DOCKER_DOMAIN] ?? actionInputs[constants_1.INPUT_KEYS.DOCKER_DOMAIN]; - const dockerPort = parseInt(additionalParams[constants_1.INPUT_KEYS.DOCKER_PORT] ?? actionInputs[constants_1.INPUT_KEYS.DOCKER_PORT]); - const dockerCacheOs = additionalParams[constants_1.INPUT_KEYS.DOCKER_CACHE_OS] ?? actionInputs[constants_1.INPUT_KEYS.DOCKER_CACHE_OS]; - const dockerCacheArch = additionalParams[constants_1.INPUT_KEYS.DOCKER_CACHE_ARCH] ?? actionInputs[constants_1.INPUT_KEYS.DOCKER_CACHE_ARCH]; - /** - * Single action - */ - const singleAction = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION]; - const singleActionIssue = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]; - const singleActionVersion = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION]; - const singleActionTitle = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE]; - const singleActionChangelog = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG]; - /** - * Tokens - */ - const token = additionalParams[constants_1.INPUT_KEYS.TOKEN] ?? actionInputs[constants_1.INPUT_KEYS.TOKEN]; - const classicToken = additionalParams[constants_1.INPUT_KEYS.CLASSIC_TOKEN] ?? actionInputs[constants_1.INPUT_KEYS.CLASSIC_TOKEN]; - /** - * AI - */ - const openrouterApiKey = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_API_KEY] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_API_KEY]; - const openrouterModel = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_MODEL] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_MODEL]; - const aiPullRequestDescription = (additionalParams[constants_1.INPUT_KEYS.AI_PULL_REQUEST_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.AI_PULL_REQUEST_DESCRIPTION]) === 'true'; - const aiMembersOnly = (additionalParams[constants_1.INPUT_KEYS.AI_MEMBERS_ONLY] ?? actionInputs[constants_1.INPUT_KEYS.AI_MEMBERS_ONLY]) === 'true'; - const aiIncludeReasoning = (additionalParams[constants_1.INPUT_KEYS.AI_INCLUDE_REASONING] ?? actionInputs[constants_1.INPUT_KEYS.AI_INCLUDE_REASONING]) === 'true'; - const aiIgnoreFilesInput = additionalParams[constants_1.INPUT_KEYS.AI_IGNORE_FILES] ?? actionInputs[constants_1.INPUT_KEYS.AI_IGNORE_FILES]; - const aiIgnoreFiles = aiIgnoreFilesInput - .split(',') - .map(path => path.trim()) - .filter(path => path.length > 0); - // Provider routing configuration - const openRouterProviderOrderInput = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER]; - const openRouterProviderOrder = openRouterProviderOrderInput - .split(',') - .map(provider => provider.trim()) - .filter(provider => provider.length > 0); - const openRouterProviderAllowFallbacks = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS]) === 'true'; - const openRouterProviderRequireParameters = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS]) === 'true'; - const openRouterProviderDataCollection = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION]); - const openRouterProviderIgnoreInput = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE]; - const openRouterProviderIgnore = openRouterProviderIgnoreInput - .split(',') - .map(provider => provider.trim()) - .filter(provider => provider.length > 0); - const openRouterProviderQuantizationsInput = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS]; - const openRouterProviderQuantizations = openRouterProviderQuantizationsInput - .split(',') - .map(level => level.trim()) - .filter(level => level.length > 0); - const openRouterProviderSort = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT]); - const providerRouting = { - ...(openRouterProviderOrder.length > 0 && { order: openRouterProviderOrder }), - ...(openRouterProviderAllowFallbacks !== undefined && { allow_fallbacks: openRouterProviderAllowFallbacks }), - ...(openRouterProviderRequireParameters !== undefined && { require_parameters: openRouterProviderRequireParameters }), - ...(openRouterProviderDataCollection && { data_collection: openRouterProviderDataCollection }), - ...(openRouterProviderIgnore.length > 0 && { ignore: openRouterProviderIgnore }), - ...(openRouterProviderQuantizations.length > 0 && { quantizations: openRouterProviderQuantizations }), - ...(openRouterProviderSort && { sort: openRouterProviderSort }) - }; - /** - * Projects Details - */ - const projectIdsInput = additionalParams[constants_1.INPUT_KEYS.PROJECT_IDS] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_IDS]; - const projectIds = projectIdsInput - .split(',') - .map(id => id.trim()) - .filter(id => id.length > 0); - const projects = []; - for (const projectId of projectIds) { - const detail = await projectRepository.getProjectDetail(projectId, token); - projects.push(detail); - } - const projectColumnIssueCreated = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_CREATED] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_CREATED]; - const projectColumnPullRequestCreated = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_CREATED] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_CREATED]; - const projectColumnIssueInProgress = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_IN_PROGRESS] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_IN_PROGRESS]; - const projectColumnPullRequestInProgress = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS]; - /** - * Images - */ - const imagesOnIssue = (additionalParams[constants_1.INPUT_KEYS.IMAGES_ON_ISSUE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ON_ISSUE]) === 'true'; - const imagesOnPullRequest = (additionalParams[constants_1.INPUT_KEYS.IMAGES_ON_PULL_REQUEST] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ON_PULL_REQUEST]) === 'true'; - const imagesOnCommit = (additionalParams[constants_1.INPUT_KEYS.IMAGES_ON_COMMIT] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ON_COMMIT]) === 'true'; - const imagesIssueAutomaticInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_AUTOMATIC] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_AUTOMATIC]; - const imagesIssueAutomatic = imagesIssueAutomaticInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueAutomatic.length === 0) { - imagesIssueAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.automatic); - } - const imagesIssueFeatureInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_FEATURE]; - const imagesIssueFeature = imagesIssueFeatureInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueFeature.length === 0) { - imagesIssueFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.feature); - } - const imagesIssueBugfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_BUGFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_BUGFIX]; - const imagesIssueBugfix = imagesIssueBugfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueBugfix.length === 0) { - imagesIssueBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.bugfix); - } - const imagesIssueDocsInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_DOCS] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_DOCS]; - const imagesIssueDocs = imagesIssueDocsInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueDocs.length === 0) { - imagesIssueDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.docs); - } - const imagesIssueChoreInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_CHORE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_CHORE]; - const imagesIssueChore = imagesIssueChoreInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueChore.length === 0) { - imagesIssueChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.chore); - } - const imagesIssueReleaseInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_RELEASE]; - const imagesIssueRelease = imagesIssueReleaseInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueRelease.length === 0) { - imagesIssueRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.release); - } - const imagesIssueHotfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_HOTFIX]; - const imagesIssueHotfix = imagesIssueHotfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueHotfix.length === 0) { - imagesIssueHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.hotfix); - } - const imagesPullRequestAutomaticInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_AUTOMATIC] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_AUTOMATIC]; - const imagesPullRequestAutomatic = imagesPullRequestAutomaticInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestAutomatic.length === 0) { - imagesPullRequestAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.automatic); - } - const imagesPullRequestFeatureInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_FEATURE]; - const imagesPullRequestFeature = imagesPullRequestFeatureInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestFeature.length === 0) { - imagesPullRequestFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.feature); - } - const imagesPullRequestBugfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_BUGFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_BUGFIX]; - const imagesPullRequestBugfix = imagesPullRequestBugfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestBugfix.length === 0) { - imagesPullRequestBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.bugfix); - } - const imagesPullRequestReleaseInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_RELEASE]; - const imagesPullRequestRelease = imagesPullRequestReleaseInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestRelease.length === 0) { - imagesPullRequestRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.release); - } - const imagesPullRequestHotfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_HOTFIX]; - const imagesPullRequestHotfix = imagesPullRequestHotfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestHotfix.length === 0) { - imagesPullRequestHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.hotfix); - } - const imagesPullRequestDocsInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_DOCS] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_DOCS]; - const imagesPullRequestDocs = imagesPullRequestDocsInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestDocs.length === 0) { - imagesPullRequestDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.docs); - } - const imagesPullRequestChoreInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_CHORE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_CHORE]; - const imagesPullRequestChore = imagesPullRequestChoreInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestChore.length === 0) { - imagesPullRequestChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.chore); - } - const imagesCommitAutomaticInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_AUTOMATIC] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_AUTOMATIC]; - const imagesCommitAutomatic = imagesCommitAutomaticInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitAutomatic.length === 0) { - imagesCommitAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.automatic); - } - const imagesCommitFeatureInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_FEATURE]; - const imagesCommitFeature = imagesCommitFeatureInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitFeature.length === 0) { - imagesCommitFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.feature); - } - const imagesCommitBugfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_BUGFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_BUGFIX]; - const imagesCommitBugfix = imagesCommitBugfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitBugfix.length === 0) { - imagesCommitBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.bugfix); - } - const imagesCommitReleaseInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_RELEASE]; - const imagesCommitRelease = imagesCommitReleaseInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitRelease.length === 0) { - imagesCommitRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.release); - } - const imagesCommitHotfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_HOTFIX]; - const imagesCommitHotfix = imagesCommitHotfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitHotfix.length === 0) { - imagesCommitHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.hotfix); - } - const imagesCommitDocsInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_DOCS] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_DOCS]; - const imagesCommitDocs = imagesCommitDocsInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitDocs.length === 0) { - imagesCommitDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.docs); - } - const imagesCommitChoreInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_CHORE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_CHORE]; - const imagesCommitChore = imagesCommitChoreInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitChore.length === 0) { - imagesCommitChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.chore); - } - /** - * Workflows - */ - const releaseWorkflow = additionalParams[constants_1.INPUT_KEYS.RELEASE_WORKFLOW] ?? actionInputs[constants_1.INPUT_KEYS.RELEASE_WORKFLOW]; - const hotfixWorkflow = additionalParams[constants_1.INPUT_KEYS.HOTFIX_WORKFLOW] ?? actionInputs[constants_1.INPUT_KEYS.HOTFIX_WORKFLOW]; - /** - * Emoji-title - */ - const titleEmoji = (additionalParams[constants_1.INPUT_KEYS.EMOJI_LABELED_TITLE] ?? actionInputs[constants_1.INPUT_KEYS.EMOJI_LABELED_TITLE]) === 'true'; - const branchManagementEmoji = additionalParams[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_EMOJI] ?? actionInputs[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_EMOJI]; - /** - * Labels - */ - const branchManagementLauncherLabel = additionalParams[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_LAUNCHER_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_LAUNCHER_LABEL]; - const bugfixLabel = additionalParams[constants_1.INPUT_KEYS.BUGFIX_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.BUGFIX_LABEL]; - const bugLabel = additionalParams[constants_1.INPUT_KEYS.BUG_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.BUG_LABEL]; - const hotfixLabel = additionalParams[constants_1.INPUT_KEYS.HOTFIX_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.HOTFIX_LABEL]; - const enhancementLabel = additionalParams[constants_1.INPUT_KEYS.ENHANCEMENT_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.ENHANCEMENT_LABEL]; - const featureLabel = additionalParams[constants_1.INPUT_KEYS.FEATURE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.FEATURE_LABEL]; - const releaseLabel = additionalParams[constants_1.INPUT_KEYS.RELEASE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.RELEASE_LABEL]; - const questionLabel = additionalParams[constants_1.INPUT_KEYS.QUESTION_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.QUESTION_LABEL]; - const helpLabel = additionalParams[constants_1.INPUT_KEYS.HELP_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.HELP_LABEL]; - const deployLabel = additionalParams[constants_1.INPUT_KEYS.DEPLOY_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DEPLOY_LABEL]; - const deployedLabel = additionalParams[constants_1.INPUT_KEYS.DEPLOYED_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DEPLOYED_LABEL]; - const docsLabel = additionalParams[constants_1.INPUT_KEYS.DOCS_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DOCS_LABEL]; - const documentationLabel = additionalParams[constants_1.INPUT_KEYS.DOCUMENTATION_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DOCUMENTATION_LABEL]; - const choreLabel = additionalParams[constants_1.INPUT_KEYS.CHORE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.CHORE_LABEL]; - const maintenanceLabel = additionalParams[constants_1.INPUT_KEYS.MAINTENANCE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.MAINTENANCE_LABEL]; - const priorityHighLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_HIGH_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_HIGH_LABEL]; - const priorityMediumLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_MEDIUM_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_MEDIUM_LABEL]; - const priorityLowLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_LOW_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_LOW_LABEL]; - const priorityNoneLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_NONE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_NONE_LABEL]; - const sizeXxlLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_LABEL]; - const sizeXlLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_XL_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_LABEL]; - const sizeLLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_L_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_LABEL]; - const sizeMLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_M_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_LABEL]; - const sizeSLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_S_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_LABEL]; - const sizeXsLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_XS_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_LABEL]; - /** - * Issue Types - */ - const issueTypeBug = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG]; - const issueTypeBugDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_DESCRIPTION]; - const issueTypeBugColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_COLOR]; - const issueTypeHotfix = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX]; - const issueTypeHotfixDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_DESCRIPTION]; - const issueTypeHotfixColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_COLOR]; - const issueTypeFeature = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE]; - const issueTypeFeatureDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_DESCRIPTION]; - const issueTypeFeatureColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_COLOR]; - const issueTypeDocumentation = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION]; - const issueTypeDocumentationDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_DESCRIPTION]; - const issueTypeDocumentationColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_COLOR]; - const issueTypeMaintenance = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE]; - const issueTypeMaintenanceDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_DESCRIPTION]; - const issueTypeMaintenanceColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_COLOR]; - const issueTypeRelease = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE]; - const issueTypeReleaseDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_DESCRIPTION]; - const issueTypeReleaseColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_COLOR]; - const issueTypeQuestion = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION]; - const issueTypeQuestionDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_DESCRIPTION]; - const issueTypeQuestionColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_COLOR]; - const issueTypeHelp = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP]; - const issueTypeHelpDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_DESCRIPTION]; - const issueTypeHelpColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_COLOR]; - const issueTypeTask = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK]; - const issueTypeTaskDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_DESCRIPTION]; - const issueTypeTaskColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_COLOR]; - /** - * Locale - */ - const issueLocale = additionalParams[constants_1.INPUT_KEYS.ISSUES_LOCALE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUES_LOCALE] ?? locale_1.Locale.DEFAULT; - const pullRequestLocale = additionalParams[constants_1.INPUT_KEYS.PULL_REQUESTS_LOCALE] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUESTS_LOCALE] ?? locale_1.Locale.DEFAULT; - /** - * Size Thresholds - */ - const sizeXxlThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_LINES]) ?? 1000; - const sizeXxlThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_FILES]) ?? 20; - const sizeXxlThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_COMMITS]) ?? 10; - const sizeXlThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_LINES]) ?? 500; - const sizeXlThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_FILES]) ?? 10; - const sizeXlThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_COMMITS]) ?? 5; - const sizeLThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_LINES]) ?? 250; - const sizeLThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_FILES]) ?? 5; - const sizeLThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_COMMITS]) ?? 3; - const sizeMThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_LINES]) ?? 100; - const sizeMThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_FILES]) ?? 3; - const sizeMThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_COMMITS]) ?? 2; - const sizeSThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_LINES]) ?? 50; - const sizeSThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_FILES]) ?? 2; - const sizeSThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_COMMITS]) ?? 1; - const sizeXsThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_LINES]) ?? 25; - const sizeXsThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_FILES]) ?? 1; - const sizeXsThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_COMMITS]) ?? 1; - /** - * Branches - */ - const mainBranch = additionalParams[constants_1.INPUT_KEYS.MAIN_BRANCH] ?? actionInputs[constants_1.INPUT_KEYS.MAIN_BRANCH]; - const developmentBranch = additionalParams[constants_1.INPUT_KEYS.DEVELOPMENT_BRANCH] ?? actionInputs[constants_1.INPUT_KEYS.DEVELOPMENT_BRANCH]; - const featureTree = additionalParams[constants_1.INPUT_KEYS.FEATURE_TREE] ?? actionInputs[constants_1.INPUT_KEYS.FEATURE_TREE]; - const bugfixTree = additionalParams[constants_1.INPUT_KEYS.BUGFIX_TREE] ?? actionInputs[constants_1.INPUT_KEYS.BUGFIX_TREE]; - const hotfixTree = additionalParams[constants_1.INPUT_KEYS.HOTFIX_TREE] ?? actionInputs[constants_1.INPUT_KEYS.HOTFIX_TREE]; - const releaseTree = additionalParams[constants_1.INPUT_KEYS.RELEASE_TREE] ?? actionInputs[constants_1.INPUT_KEYS.RELEASE_TREE]; - const docsTree = additionalParams[constants_1.INPUT_KEYS.DOCS_TREE] ?? actionInputs[constants_1.INPUT_KEYS.DOCS_TREE]; - const choreTree = additionalParams[constants_1.INPUT_KEYS.CHORE_TREE] ?? actionInputs[constants_1.INPUT_KEYS.CHORE_TREE]; - /** - * Prefix builder - */ - let commitPrefixBuilder = additionalParams[constants_1.INPUT_KEYS.COMMIT_PREFIX_TRANSFORMS] ?? actionInputs[constants_1.INPUT_KEYS.COMMIT_PREFIX_TRANSFORMS] ?? ''; - if (commitPrefixBuilder.length === 0) { - commitPrefixBuilder = 'replace-slash'; - } - /** - * Issue - */ - const branchManagementAlways = (additionalParams[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_ALWAYS] ?? actionInputs[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_ALWAYS]) === 'true'; - const reopenIssueOnPush = (additionalParams[constants_1.INPUT_KEYS.REOPEN_ISSUE_ON_PUSH] ?? actionInputs[constants_1.INPUT_KEYS.REOPEN_ISSUE_ON_PUSH]) === 'true'; - const issueDesiredAssigneesCount = parseInt(additionalParams[constants_1.INPUT_KEYS.DESIRED_ASSIGNEES_COUNT] ?? actionInputs[constants_1.INPUT_KEYS.DESIRED_ASSIGNEES_COUNT]) ?? 0; - /** - * Pull Request - */ - const pullRequestDesiredAssigneesCount = parseInt(additionalParams[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_ASSIGNEES_COUNT] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_ASSIGNEES_COUNT]) ?? 0; - const pullRequestDesiredReviewersCount = parseInt(additionalParams[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_REVIEWERS_COUNT] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_REVIEWERS_COUNT]) ?? 0; - const pullRequestMergeTimeout = parseInt(additionalParams[constants_1.INPUT_KEYS.PULL_REQUEST_MERGE_TIMEOUT] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUEST_MERGE_TIMEOUT]) ?? 0; - /** - * Supabase - */ - const supabaseUrl = additionalParams[constants_1.INPUT_KEYS.SUPABASE_URL] ?? actionInputs[constants_1.INPUT_KEYS.SUPABASE_URL]; - const supabaseKey = additionalParams[constants_1.INPUT_KEYS.SUPABASE_KEY] ?? actionInputs[constants_1.INPUT_KEYS.SUPABASE_KEY]; - let supabaseConfig = undefined; - if (supabaseUrl.length > 0 && supabaseKey.length > 0) { - supabaseConfig = new supabase_config_1.SupabaseConfig(supabaseUrl, supabaseKey); - } - const execution = new execution_1.Execution(debug, new docker_config_1.DockerConfig(dockerContainerName, dockerDomain, dockerPort, dockerCacheOs, dockerCacheArch), new single_action_1.SingleAction(singleAction, singleActionIssue, singleActionVersion, singleActionTitle, singleActionChangelog), commitPrefixBuilder, new issue_1.Issue(branchManagementAlways, reopenIssueOnPush, issueDesiredAssigneesCount, additionalParams), new pull_request_1.PullRequest(pullRequestDesiredAssigneesCount, pullRequestDesiredReviewersCount, pullRequestMergeTimeout, additionalParams), new emoji_1.Emoji(titleEmoji, branchManagementEmoji), new images_1.Images(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, imagesIssueAutomatic, imagesIssueFeature, imagesIssueBugfix, imagesIssueDocs, imagesIssueChore, imagesIssueRelease, imagesIssueHotfix, imagesPullRequestAutomatic, imagesPullRequestFeature, imagesPullRequestBugfix, imagesPullRequestRelease, imagesPullRequestHotfix, imagesPullRequestDocs, imagesPullRequestChore, imagesCommitAutomatic, imagesCommitFeature, imagesCommitBugfix, imagesCommitRelease, imagesCommitHotfix, imagesCommitDocs, imagesCommitChore), new tokens_1.Tokens(token, classicToken), new ai_1.Ai(openrouterApiKey, openrouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, Object.keys(providerRouting).length > 0 ? providerRouting : undefined), new labels_1.Labels(branchManagementLauncherLabel, bugLabel, bugfixLabel, hotfixLabel, enhancementLabel, featureLabel, releaseLabel, questionLabel, helpLabel, deployLabel, deployedLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel, priorityHighLabel, priorityMediumLabel, priorityLowLabel, priorityNoneLabel, sizeXxlLabel, sizeXlLabel, sizeLLabel, sizeMLabel, sizeSLabel, sizeXsLabel), new issue_types_1.IssueTypes(issueTypeTask, issueTypeTaskDescription, issueTypeTaskColor, issueTypeBug, issueTypeBugDescription, issueTypeBugColor, issueTypeFeature, issueTypeFeatureDescription, issueTypeFeatureColor, issueTypeDocumentation, issueTypeDocumentationDescription, issueTypeDocumentationColor, issueTypeMaintenance, issueTypeMaintenanceDescription, issueTypeMaintenanceColor, issueTypeHotfix, issueTypeHotfixDescription, issueTypeHotfixColor, issueTypeRelease, issueTypeReleaseDescription, issueTypeReleaseColor, issueTypeQuestion, issueTypeQuestionDescription, issueTypeQuestionColor, issueTypeHelp, issueTypeHelpDescription, issueTypeHelpColor), new locale_1.Locale(issueLocale, pullRequestLocale), new size_thresholds_1.SizeThresholds(new size_threshold_1.SizeThreshold(sizeXxlThresholdLines, sizeXxlThresholdFiles, sizeXxlThresholdCommits), new size_threshold_1.SizeThreshold(sizeXlThresholdLines, sizeXlThresholdFiles, sizeXlThresholdCommits), new size_threshold_1.SizeThreshold(sizeLThresholdLines, sizeLThresholdFiles, sizeLThresholdCommits), new size_threshold_1.SizeThreshold(sizeMThresholdLines, sizeMThresholdFiles, sizeMThresholdCommits), new size_threshold_1.SizeThreshold(sizeSThresholdLines, sizeSThresholdFiles, sizeSThresholdCommits), new size_threshold_1.SizeThreshold(sizeXsThresholdLines, sizeXsThresholdFiles, sizeXsThresholdCommits)), new branches_1.Branches(mainBranch, developmentBranch, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree), new release_1.Release(), new hotfix_1.Hotfix(), new workflows_1.Workflows(releaseWorkflow, hotfixWorkflow), new projects_1.Projects(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress), supabaseConfig, new welcome_1.Welcome(welcomeTitle, welcomeMessages), additionalParams); - const results = await (0, common_action_1.mainRun)(execution); - let content = ''; - const stepsContent = results - .filter(result => result.executed && result.steps.length > 0) - .map(result => chalk_1.default.gray(result.steps.join('\n'))).join('\n'); - if (stepsContent.length > 0) { - content += '\n' + chalk_1.default.cyan('Steps:') + '\n' + stepsContent; - } - const errorsContent = results - .filter(result => !result.executed && result.errors.length > 0) - .map(result => chalk_1.default.gray(result.errors.join('\n'))).join('\n'); - if (errorsContent.length > 0) { - content += '\n' + chalk_1.default.red('Errors:') + '\n' + errorsContent; - } - const reminderContent = results - .filter(result => result.executed && result.reminders.length > 0) - .map(result => chalk_1.default.gray(result.reminders.join('\n'))).join('\n'); - if (reminderContent.length > 0) { - content += '\n' + chalk_1.default.cyan('Reminder:') + '\n' + reminderContent; +// 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 + } } - (0, logger_1.logInfo)('\n'); - (0, logger_1.logInfo)((0, boxen_1.default)(content, { - padding: 1, - margin: 1, - borderStyle: 'round', - borderColor: 'cyan', - title: constants_1.TITLE, - titleAlignment: 'center' - })); + } + + // 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' +} -/***/ 56733: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} -"use strict"; +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO -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]; } }; + // 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) } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const child_process_1 = __nccwpck_require__(32081); -const commander_1 = __nccwpck_require__(14379); -const dotenv = __importStar(__nccwpck_require__(12437)); -const local_action_1 = __nccwpck_require__(87002); -const issue_repository_1 = __nccwpck_require__(40057); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -// Load environment variables from .env file -dotenv.config(); -const program = new commander_1.Command(); -// Function to get git repository info -function getGitInfo() { - try { - const remoteUrl = (0, child_process_1.execSync)('git config --get remote.origin.url').toString().trim(); - const match = remoteUrl.match(/github\.com[/:]([^/]+)\/([^/]+)(?:\.git)?$/); - if (!match) { - return { error: constants_1.ERRORS.GIT_REPOSITORY_NOT_FOUND }; + + // 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 } - return { - owner: match[1], - repo: match[2].replace('.git', '') - }; + 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. } - catch (error) { - return { error: constants_1.ERRORS.GIT_REPOSITORY_NOT_FOUND }; + + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) } + } } -program - .name(constants_1.COMMAND) - .description(`CLI tool for ${constants_1.TITLE}`) - .version('1.0.0'); -program - .command('compile-vector-server') - .description('Compile vector server container') - .option('-d, --debug', 'Debug mode', false) - .option('-p, --platforms ', 'Platforms', 'linux/amd64,linux/arm64,linux/arm/v7,linux/ppc64le,linux/s390x') - .option('-v, --version ', 'Version', 'latest') - .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) - .option('-c, --classic-token ', 'Classic personal access token', process.env.CLASSIC_TOKEN) - .action(async (options) => { - const gitInfo = getGitInfo(); - if ('error' in gitInfo) { - console.log(gitInfo.error); - return; - } - const params = { - [constants_1.INPUT_KEYS.DEBUG]: options.debug.toString(), - [constants_1.INPUT_KEYS.SINGLE_ACTION]: constants_1.ACTIONS.COMPILE_VECTOR_SERVER, - [constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION]: options.version, - [constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]: 1, - [constants_1.INPUT_KEYS.SUPABASE_URL]: process.env.SUPABASE_URL, - [constants_1.INPUT_KEYS.SUPABASE_KEY]: process.env.SUPABASE_KEY, - [constants_1.INPUT_KEYS.TOKEN]: options.token || process.env.PERSONAL_ACCESS_TOKEN, - [constants_1.INPUT_KEYS.CLASSIC_TOKEN]: options.classictoken || process.env.CLASSIC_TOKEN, - [constants_1.INPUT_KEYS.AI_IGNORE_FILES]: 'build/*', - repo: { - owner: gitInfo.owner, - repo: gitInfo.repo, - }, - issue: { - number: 1, - }, - }; - params[constants_1.INPUT_KEYS.WELCOME_TITLE] = 'šŸ‘·šŸ› ļø Vector Server Container Build'; - params[constants_1.INPUT_KEYS.WELCOME_MESSAGES] = [ - `Building vector server container for ${gitInfo.owner}/${gitInfo.repo}...`, - ]; - await (0, local_action_1.runLocalAction)(params); -}); -program - .command('build-ai') - .description('Build AI container and execute vector indexing') - .option('-d, --debug', 'Debug mode', false) - .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) - .option('-c, --classic-token ', 'Classic personal access token', process.env.CLASSIC_TOKEN) - .action(async (options) => { - const gitInfo = getGitInfo(); - if ('error' in gitInfo) { - console.log(gitInfo.error); - return; - } - const params = { - [constants_1.INPUT_KEYS.DEBUG]: options.debug.toString(), - [constants_1.INPUT_KEYS.SINGLE_ACTION]: constants_1.ACTIONS.VECTOR_LOCAL, - [constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]: 1, - [constants_1.INPUT_KEYS.SUPABASE_URL]: process.env.SUPABASE_URL, - [constants_1.INPUT_KEYS.SUPABASE_KEY]: process.env.SUPABASE_KEY, - [constants_1.INPUT_KEYS.TOKEN]: options.token || process.env.PERSONAL_ACCESS_TOKEN, - [constants_1.INPUT_KEYS.CLASSIC_TOKEN]: options.classictoken || process.env.CLASSIC_TOKEN, - [constants_1.INPUT_KEYS.AI_IGNORE_FILES]: 'build/*', - repo: { - owner: gitInfo.owner, - repo: gitInfo.repo, - }, - issue: { - number: 1, - }, - }; - params[constants_1.INPUT_KEYS.WELCOME_TITLE] = 'šŸš€ AI Container Build'; - params[constants_1.INPUT_KEYS.WELCOME_MESSAGES] = [ - `Building AI container for ${gitInfo.owner}/${gitInfo.repo}...`, - ]; - await (0, local_action_1.runLocalAction)(params); -}); -/** - * Run the asking AI scenario on issues or pull requests. - * - * For the action of asking the AI to be executed, the bot user managing the repository must be mentioned. - */ -program - .command('ask-ai') - .description('Ask AI') - .option('-i, --issue ', 'Issue number to process', '1') - .option('-b, --branch ', 'Branch name', 'master') - .option('-d, --debug', 'Debug mode', false) - .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) - .option('-q, --question ', 'Question', '') - .option('--openrouter-api-key ', 'OpenRouter API key', '') - .option('--openrouter-model ', 'OpenRouter model', '') - .option('--openrouter-provider-order ', 'OpenRouter provider', '') - .option('--openrouter-provider-allow-fallbacks ', 'OpenRouter fallback', '') - .option('--openrouter-provider-require-parameters ', 'OpenRouter require', '') - .option('--openrouter-provider-data-collection ', 'OpenRouter collection', '') - .option('--openrouter-provider-ignore ', 'OpenRouter ignore', '') - .option('--openrouter-provider-quantizations ', 'OpenRouter quantizations', '') - .option('--openrouter-provider-sort ', 'OpenRouter sort', '') - .option('--ai-ignore-files ', 'AI ignore files', 'node_modules/*,build/*') - .option('--include-reasoning ', 'Include reasoning', 'false') - .action(async (options) => { - const gitInfo = getGitInfo(); - if ('error' in gitInfo) { - console.log(gitInfo.error); - return; - } - const commentBody = (options.question || []).join(' '); - const params = { - [constants_1.INPUT_KEYS.DEBUG]: options.debug.toString(), - [constants_1.INPUT_KEYS.SUPABASE_URL]: options?.supabaseUrl?.length > 0 ? options.supabaseUrl : process.env.SUPABASE_URL, - [constants_1.INPUT_KEYS.SUPABASE_KEY]: options?.supabaseKey?.length > 0 ? options.supabaseKey : process.env.SUPABASE_KEY, - [constants_1.INPUT_KEYS.TOKEN]: options?.token?.length > 0 ? options.token : process.env.PERSONAL_ACCESS_TOKEN, - [constants_1.INPUT_KEYS.OPENROUTER_API_KEY]: options?.openrouterApiKey?.length > 0 ? options.openrouterApiKey : process.env.OPENROUTER_API_KEY, - [constants_1.INPUT_KEYS.OPENROUTER_MODEL]: options?.openrouterModel?.length > 0 ? options.openrouterModel : process.env.OPENROUTER_MODEL, - [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER]: options?.openrouterProviderOrder?.length > 0 ? options.openrouterProviderOrder : process.env.OPENROUTER_PROVIDER_ORDER, - [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS]: options?.openrouterProviderAllowFallbacks?.length > 0 ? options.openrouterProviderAllowFallbacks : process.env.OPENROUTER_PROVIDER_ALLOW_FALLBACKS, - [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS]: options?.openrouterProviderRequireParameters?.length > 0 ? options.openrouterProviderRequireParameters : process.env.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS, - [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION]: options?.openrouterProviderDataCollection?.length > 0 ? options.openrouterProviderDataCollection : process.env.OPENROUTER_PROVIDER_DATA_COLLECTION, - [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE]: options?.openrouterProviderIgnore?.length > 0 ? options.openrouterProviderIgnore : process.env.OPENROUTER_PROVIDER_IGNORE, - [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS]: options?.openrouterProviderQuantizations?.length > 0 ? options.openrouterProviderQuantizations : process.env.OPENROUTER_PROVIDER_QUANTIZATIONS, - [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT]: options?.openrouterProviderSort?.length > 0 ? options.openrouterProviderSort : process.env.OPENROUTER_PROVIDER_SORT, - [constants_1.INPUT_KEYS.AI_IGNORE_FILES]: options?.aiIgnoreFiles?.length > 0 ? options.aiIgnoreFiles : process.env.AI_IGNORE_FILES, - [constants_1.INPUT_KEYS.AI_INCLUDE_REASONING]: options?.includeReasoning?.length > 0 ? options.includeReasoning : process.env.AI_INCLUDE_REASONING, - repo: { - owner: gitInfo.owner, - repo: gitInfo.repo, - }, - commits: { - ref: `refs/heads/${options.branch}`, - }, - }; - const issueRepository = new issue_repository_1.IssueRepository(); - const isIssue = await issueRepository.isIssue(gitInfo.owner, gitInfo.repo, parseInt(options.issue), params[constants_1.INPUT_KEYS.TOKEN] ?? ''); - const isPullRequest = await issueRepository.isPullRequest(gitInfo.owner, gitInfo.repo, parseInt(options.issue), params[constants_1.INPUT_KEYS.TOKEN] ?? ''); - if (isIssue) { - params.eventName = 'issue_comment'; - params.issue = { - number: parseInt(options.issue), - }; - params.comment = { - body: commentBody, - }; - } - else if (isPullRequest) { - params.eventName = 'pull_request_review_comment'; - params.pull_request = { - number: parseInt(options.issue), - }; - params.pull_request_review_comment = { - body: commentBody, - }; - } - params[constants_1.INPUT_KEYS.WELCOME_TITLE] = 'šŸš€ Asking AI started'; - params[constants_1.INPUT_KEYS.WELCOME_MESSAGES] = [ - `Asking AI on ${gitInfo.owner}/${gitInfo.repo}/${options.branch}...`, - ]; - (0, logger_1.logInfo)(JSON.stringify(params, null, 2)); - (0, local_action_1.runLocalAction)(params); -}); -program.parse(process.argv); - -/***/ }), +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} -/***/ 64470: -/***/ ((__unused_webpack_module, exports) => { +// 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 + } +} -"use strict"; +// 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' + } +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Ai = void 0; -class Ai { - constructor(openRouterApiKey, openRouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, providerRouting) { - this.openRouterApiKey = openRouterApiKey; - this.openRouterModel = openRouterModel; - this.aiPullRequestDescription = aiPullRequestDescription; - this.aiMembersOnly = aiMembersOnly; - this.aiIgnoreFiles = aiIgnoreFiles; - this.aiIncludeReasoning = aiIncludeReasoning; - this.providerRouting = providerRouting || {}; - } - getOpenRouterApiKey() { - return this.openRouterApiKey; - } - getAiPullRequestDescription() { - return this.aiPullRequestDescription; - } - getAiMembersOnly() { - return this.aiMembersOnly; - } - getAiIgnoreFiles() { - return this.aiIgnoreFiles; - } - getAiIncludeReasoning() { - return this.aiIncludeReasoning; - } - getOpenRouterModel() { - return this.openRouterModel; - } - getProviderRouting() { - return this.providerRouting; - } +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } } -exports.Ai = Ai; +// 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) -/***/ 12141: -/***/ ((__unused_webpack_module, exports) => { + // 2. Let environment be request’s client. -"use strict"; + let referrerSource = null -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BranchConfiguration = void 0; -class BranchConfiguration { - constructor(data) { - this.name = data['name'] ?? ''; - this.oid = data['oid'] ?? ''; - this.children = []; - if (data['children'] !== undefined && data['children'].length > 0) { - for (let child of data['children']) { - this.children.push(new BranchConfiguration(child)); - } - } + // 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' } -} -exports.BranchConfiguration = BranchConfiguration; + // 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) -/***/ 45308: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + // 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) -"use strict"; + // 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 + } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Branches = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class Branches { - get defaultBranch() { - return github.context.payload.repository?.default_branch ?? ''; - } - constructor(main, development, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree) { - this.main = main; - this.development = development; - this.featureTree = featureTree; - this.bugfixTree = bugfixTree; - this.hotfixTree = hotfixTree; - this.releaseTree = releaseTree; - this.docsTree = docsTree; - this.choreTree = choreTree; + 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 + } } -exports.Branches = Branches; +/** + * @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 = '' -/***/ 2469: -/***/ ((__unused_webpack_module, exports) => { + // 4. Set url’s password to the empty string. + url.password = '' -"use strict"; + // 5. Set url’s fragment to null. + url.hash = '' -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChunkedFile = void 0; -class ChunkedFile { - constructor(path, index, type, content, shasum, chunks) { - this.shasum = ''; - this.vector = []; - this.path = path; - this.index = index; - this.content = content; - this.chunks = chunks; - this.shasum = shasum; - this.type = type; - } -} -exports.ChunkedFile = ChunkedFile; + // 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 +} -/***/ 64370: -/***/ ((__unused_webpack_module, exports) => { +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } -"use strict"; + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChunkedFileChunk = void 0; -class ChunkedFileChunk { - constructor(owner, repository, branch, path, type, index, chunkIndex, chunk, shasum, vector) { - this.shasum = ''; - this.vector = []; - this.owner = owner; - this.repository = repository; - this.branch = branch; - this.path = path; - this.type = type; - this.index = index; - this.chunkIndex = chunkIndex; - this.chunk = chunk; - this.shasum = shasum; - this.vector = vector; - } -} -exports.ChunkedFileChunk = ChunkedFileChunk; + // 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) -/***/ 83993: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false -"use strict"; + const originAsURL = new URL(origin) -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Commit = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class Commit { - constructor(inputs = undefined) { - this.inputs = undefined; - this.inputs = inputs; - } - get branchReference() { - return this.inputs?.commits?.ref ?? github.context.payload.ref ?? ''; - } - get branch() { - return this.branchReference.replace('refs/heads/', ''); + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true } - get commits() { - return github.context.payload.commits || []; + + // 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 + } } -exports.Commit = Commit; +/** + * @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) -/***/ 41106: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } -"use strict"; + // 3. If response is not eligible for integrity validation, return false. + // TODO -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Config = void 0; -const branch_configuration_1 = __nccwpck_require__(12141); -class Config { - constructor(data) { - this.results = []; - this.branchType = data['branchType'] ?? ''; - this.hotfixOriginBranch = data['hotfixOriginBranch']; - this.hotfixBranch = data['hotfixBranch']; - this.releaseBranch = data['releaseBranch']; - this.parentBranch = data['parentBranch']; - this.workingBranch = data['workingBranch']; - if (data['branchConfiguration'] !== undefined) { - this.branchConfiguration = new branch_configuration_1.BranchConfiguration(data['branchConfiguration']); - } - } -} -exports.Config = Config; + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + // 6. 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. + const expectedValue = item.hash -/***/ 61684: -/***/ ((__unused_webpack_module, exports) => { + // 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. -"use strict"; + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DockerConfig = void 0; -class DockerConfig { - constructor(containerName, domain, port, cacheOs, cacheArch) { - this.containerName = containerName; - this.domain = domain; - this.port = port; - this.cacheOs = cacheOs; - this.cacheArch = cacheArch; - } - getContainerName() { - return this.containerName; - } - getDomain() { - return this.domain; - } - getPort() { - return this.port; - } - getCacheOs() { - return this.cacheOs; - } - getCacheArch() { - return this.cacheArch; + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) + } else { + actualValue = actualValue.slice(0, -1) + } } -} -exports.DockerConfig = DockerConfig; + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true + } + } -/***/ }), + // 7. Return false. + return false +} -/***/ 9463: -/***/ ((__unused_webpack_module, exports) => { +// 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-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i -"use strict"; +/** + * @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 = [] -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Emoji = void 0; -class Emoji { - constructor(emojiLabeledTitle, branchManagementEmoji) { - this.emojiLabeledTitle = emojiLabeledTitle; - this.branchManagementEmoji = branchManagementEmoji; - } -} -exports.Emoji = Emoji; + // 2. Let empty be equal to true. + let empty = true + // 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) -/***/ 87550: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === 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 + } -"use strict"; + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Execution = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const configuration_handler_1 = __nccwpck_require__(34509); -const get_hotfix_version_use_case_1 = __nccwpck_require__(8243); -const get_release_type_use_case_1 = __nccwpck_require__(35966); -const get_release_version_use_case_1 = __nccwpck_require__(3827); -const constants_1 = __nccwpck_require__(8593); -const label_utils_1 = __nccwpck_require__(31479); -const logger_1 = __nccwpck_require__(38836); -const title_utils_1 = __nccwpck_require__(26676); -const version_utils_1 = __nccwpck_require__(29887); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const commit_1 = __nccwpck_require__(83993); -const config_1 = __nccwpck_require__(41106); -class Execution { - get eventName() { - return this.inputs?.eventName ?? github.context.eventName; - } - get actor() { - return this.inputs?.actor ?? github.context.actor; - } - get isSingleAction() { - return this.singleAction.enabledSingleAction; - } - get isIssue() { - return this.issue.isIssue || this.issue.isIssueComment || this.singleAction.isIssue; - } - get isPullRequest() { - return this.pullRequest.isPullRequest || this.pullRequest.isPullRequestReviewComment || this.singleAction.isPullRequest; - } - get isPush() { - return this.eventName === 'push'; - } - get repo() { - return this.inputs?.repo?.repo ?? github.context.repo.repo; - } - get owner() { - return this.inputs?.repo?.owner ?? github.context.repo.owner; - } - get isFeature() { - return this.issueType === this.branches.featureTree; - } - get isBugfix() { - return this.issueType === this.branches.bugfixTree; - } - get isDocs() { - return this.issueType === this.branches.docsTree; - } - get isChore() { - return this.issueType === this.branches.choreTree; - } - get isBranched() { - return this.issue.branchManagementAlways || - this.labels.containsBranchedLabel || - this.labels.isMandatoryBranchedLabel; - } - get issueNotBranched() { - return this.isIssue && !this.isBranched; - } - get managementBranch() { - return (0, label_utils_1.branchesForManagement)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); - } - get issueType() { - return (0, label_utils_1.typesForIssue)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); - } - get cleanIssueBranches() { - return this.isIssue - && this.previousConfiguration !== undefined - && this.previousConfiguration?.branchType != this.currentConfiguration.branchType; - } - get commit() { - return new commit_1.Commit(this.inputs); - } - get runnedByToken() { - return this.tokenUser === this.actor; + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) } - constructor(debug, dockerConfig, singleAction, commitPrefixBuilder, issue, pullRequest, emoji, giphy, tokens, ai, labels, issueTypes, locale, sizeThresholds, branches, release, hotfix, workflows, project, supabaseConfig, welcome, inputs) { - this.debug = false; - /** - * Every usage of this field should be checked. - * PRs with no issue ID in the head branch won't have it. - * - * master <- develop - */ - this.issueNumber = -1; - this.commitPrefixBuilderParams = {}; - this.setup = async () => { - (0, logger_1.setGlobalLoggerDebug)(this.debug, this.inputs === undefined); - const issueRepository = new issue_repository_1.IssueRepository(); - const projectRepository = new project_repository_1.ProjectRepository(); - this.tokenUser = await projectRepository.getUserFromToken(this.tokens.token); - if (!this.tokenUser) { - throw new Error('Failed to get user from token'); - } - /** - * Set the issue number - */ - if (this.isSingleAction) { - /** - * Single actions can run as isolated processes or as part of a workflow. - * In the case of a workflow, the issue number is got from the workflow. - * In the case of a single action, the issue number is set. - */ - if (this.inputs?.[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]) { - this.issueNumber = this.inputs[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]; - this.singleAction.issue = this.issueNumber; - } - else if (this.isIssue) { - this.singleAction.isIssue = true; - this.issueNumber = this.issue.number; - this.singleAction.issue = this.issueNumber; - } - else if (this.isPullRequest) { - this.singleAction.isPullRequest = true; - this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); - this.singleAction.issue = this.issueNumber; - } - else if (this.isPush) { - this.singleAction.isPush = true; - this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); - this.singleAction.issue = this.issueNumber; - } - else { - this.singleAction.isPullRequest = await issueRepository.isPullRequest(this.owner, this.repo, this.singleAction.issue, this.tokens.token); - this.singleAction.isIssue = await issueRepository.isIssue(this.owner, this.repo, this.singleAction.issue, this.tokens.token); - if (this.singleAction.isIssue) { - this.issueNumber = this.singleAction.issue; - } - else if (this.singleAction.isPullRequest) { - const head = await issueRepository.getHeadBranch(this.owner, this.repo, this.singleAction.issue, this.tokens.token); - if (head === undefined) { - return; - } - this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(head); - } - } - } - else if (this.isIssue) { - this.issueNumber = this.issue.number; - } - else if (this.isPullRequest) { - this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); - } - else if (this.isPush) { - this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); - } - this.previousConfiguration = await new configuration_handler_1.ConfigurationHandler().get(this); - /** - * Get labels of issue - */ - this.labels.currentIssueLabels = await issueRepository.getLabels(this.owner, this.repo, this.issueNumber, this.tokens.token); - /** - * Contains release label - */ - this.release.active = this.labels.isRelease; - this.hotfix.active = this.labels.isHotfix; - /** - * Get previous state - */ - if (this.release.active) { - const previousReleaseBranch = this.previousConfiguration?.releaseBranch; - if (previousReleaseBranch) { - this.release.version = previousReleaseBranch.split('/')[1] ?? ''; - this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; - this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; - this.currentConfiguration.releaseBranch = this.release.branch; - } - } - else if (this.hotfix.active) { - const previousHotfixOriginBranch = this.previousConfiguration?.hotfixOriginBranch; - if (previousHotfixOriginBranch) { - this.hotfix.baseVersion = previousHotfixOriginBranch.split('/v')[1] ?? ''; - this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; - this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; - this.currentConfiguration.parentBranch = this.hotfix.baseBranch; - } - const previousHotfixBranch = this.previousConfiguration?.hotfixBranch; - if (previousHotfixBranch) { - this.hotfix.version = previousHotfixBranch.split('/')[1] ?? ''; - this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; - this.currentConfiguration.hotfixBranch = this.hotfix.branch; - } - } - else { - this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; - } - if (this.isSingleAction) { - /** - * Nothing to do here (for now) - */ - } - else if (this.isIssue) { - const branchRepository = new branch_repository_1.BranchRepository(); - if (this.release.active && this.release.version === undefined) { - const versionResult = await new get_release_version_use_case_1.GetReleaseVersionUseCase().invoke(this); - const versionInfo = versionResult[versionResult.length - 1]; - if (versionInfo.executed && versionInfo.success) { - this.release.version = versionInfo.payload['releaseVersion']; - } - else { - const typeResult = await new get_release_type_use_case_1.GetReleaseTypeUseCase().invoke(this); - const typeInfo = typeResult[typeResult.length - 1]; - if (typeInfo.executed && typeInfo.success) { - this.release.type = typeInfo.payload['releaseType']; - if (this.release.type === undefined) { - return; - } - const lastTag = await branchRepository.getLatestTag(); - if (lastTag === undefined) { - return; - } - this.release.version = (0, version_utils_1.incrementVersion)(lastTag, this.release.type); - } - } - this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; - } - else if (this.hotfix.active && this.hotfix.version === undefined) { - const versionResult = await new get_hotfix_version_use_case_1.GetHotfixVersionUseCase().invoke(this); - const versionInfo = versionResult[versionResult.length - 1]; - if (versionInfo.executed && versionInfo.success) { - this.hotfix.baseVersion = versionInfo.payload['baseVersion']; - this.hotfix.version = versionInfo.payload['hotfixVersion']; - } - else { - this.hotfix.baseVersion = await branchRepository.getLatestTag(); - if (this.hotfix.baseVersion === undefined) { - return; - } - this.hotfix.version = (0, version_utils_1.incrementVersion)(this.hotfix.baseVersion, 'Patch'); - } - this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; - this.currentConfiguration.hotfixBranch = this.hotfix.branch; - this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; - this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; - } - } - else if (this.isPullRequest) { - this.labels.currentPullRequestLabels = await issueRepository.getLabels(this.owner, this.repo, this.pullRequest.number, this.tokens.token); - this.release.active = this.pullRequest.base.indexOf(`${this.branches.releaseTree}/`) > -1; - this.hotfix.active = this.pullRequest.base.indexOf(`${this.branches.hotfixTree}/`) > -1; - } - this.currentConfiguration.branchType = this.issueType; - (0, logger_1.logDebugInfo)(`Current configuration: ${JSON.stringify(this.currentConfiguration, null, 2)}`); - }; - this.debug = debug; - this.dockerConfig = dockerConfig; - this.singleAction = singleAction; - this.commitPrefixBuilder = commitPrefixBuilder; - this.issue = issue; - this.pullRequest = pullRequest; - this.images = giphy; - this.tokens = tokens; - this.ai = ai; - this.emoji = emoji; - this.labels = labels; - this.issueTypes = issueTypes; - this.locale = locale; - this.sizeThresholds = sizeThresholds; - this.branches = branches; - this.release = release; - this.hotfix = hotfix; - this.project = project; - this.workflows = workflows; - this.currentConfiguration = new config_1.Config({}); - this.supabaseConfig = supabaseConfig; - this.inputs = inputs; - this.welcome = welcome; + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result +} + +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm + } + + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' } + } + return algorithm } -exports.Execution = Execution; +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList + } -/***/ }), + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] + } + } -/***/ 87341: -/***/ ((__unused_webpack_module, exports) => { + metadataList.length = pos -"use strict"; + return metadataList +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Hotfix = void 0; -class Hotfix { - constructor() { - this.active = false; +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false + } + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false } -} -exports.Hotfix = Hotfix; + } + return true +} -/***/ }), +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} -/***/ 51721: -/***/ ((__unused_webpack_module, exports) => { +/** + * @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 + } -"use strict"; + // 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 + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Images = void 0; -class Images { - constructor(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, cleanUpGifs, featureGifs, bugfixGifs, docsGifs, choreGifs, releaseGifs, hotfixGifs, prLinkGifs, prFeatureGifs, prBugfixGifs, prReleaseGifs, prHotfixGifs, prDocsGifs, prChoreGifs, commitAutomaticActions, commitFeatureGifs, commitBugfixGifs, commitReleaseGifs, commitHotfixGifs, commitDocsGifs, commitChoreGifs) { - this.imagesOnIssue = imagesOnIssue; - this.imagesOnPullRequest = imagesOnPullRequest; - this.imagesOnCommit = imagesOnCommit; - this.issueAutomaticActions = cleanUpGifs; - this.issueFeatureGifs = featureGifs; - this.issueBugfixGifs = bugfixGifs; - this.issueReleaseGifs = releaseGifs; - this.issueHotfixGifs = hotfixGifs; - this.issueDocsGifs = docsGifs; - this.issueChoreGifs = choreGifs; - this.pullRequestAutomaticActions = prLinkGifs; - this.pullRequestFeatureGifs = prFeatureGifs; - this.pullRequestBugfixGifs = prBugfixGifs; - this.pullRequestReleaseGifs = prReleaseGifs; - this.pullRequestHotfixGifs = prHotfixGifs; - this.pullRequestDocsGifs = prDocsGifs; - this.pullRequestChoreGifs = prChoreGifs; - this.commitAutomaticActions = commitAutomaticActions; - this.commitFeatureGifs = commitFeatureGifs; - this.commitBugfixGifs = commitBugfixGifs; - this.commitReleaseGifs = commitReleaseGifs; - this.commitHotfixGifs = commitHotfixGifs; - this.commitDocsGifs = commitDocsGifs; - this.commitChoreGifs = commitChoreGifs; - } + // 3. Return false. + return false } -exports.Images = Images; +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) -/***/ }), + return { promise, resolve: res, reject: rej } +} -/***/ 42632: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} -"use strict"; +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Issue = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class Issue { - get title() { - return this.inputs?.issue?.title ?? github.context.payload.issue?.title ?? ''; - } - get number() { - return this.inputs?.issue?.number ?? github.context.payload.issue?.number ?? -1; - } - get creator() { - return this.inputs?.issue?.user?.login ?? github.context.payload.issue?.user.login ?? ''; - } - get url() { - return this.inputs?.issue?.html_url ?? github.context.payload.issue?.html_url ?? ''; - } - get body() { - return this.inputs?.issue?.body ?? github.context.payload.issue?.body ?? ''; - } - get opened() { - return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); - } - get labeled() { - return (this.inputs?.action ?? github.context.payload.action) === 'labeled'; - } - get labelAdded() { - return this.inputs?.label?.name ?? github.context.payload.label?.name ?? ''; - } - get isIssue() { - return (this.inputs?.eventName ?? github.context.eventName) === 'issues'; - } - get isIssueComment() { - return (this.inputs?.eventName ?? github.context.eventName) === 'issue_comment'; - } - get commentId() { - return this.inputs?.comment?.id ?? github.context.payload.comment?.id ?? -1; - } - get commentBody() { - return this.inputs?.comment?.body ?? github.context.payload.comment?.body ?? ''; - } - get commentAuthor() { - return this.inputs?.comment?.user?.login ?? github.context.payload.comment?.user.login ?? ''; - } - get commentUrl() { - return this.inputs?.comment?.html_url ?? github.context.payload.comment?.html_url ?? ''; - } - constructor(branchManagementAlways, reopenOnPush, desiredAssigneesCount, inputs = undefined) { - this.inputs = undefined; - this.branchManagementAlways = branchManagementAlways; - this.reopenOnPush = reopenOnPush; - this.desiredAssigneesCount = desiredAssigneesCount; - this.inputs = inputs; - } +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' } -exports.Issue = Issue; +// 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) -/***/ 71975: -/***/ ((__unused_webpack_module, exports) => { + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } -"use strict"; + // 3. Assert: result is a string. + assert(typeof result === 'string') -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueTypes = void 0; -class IssueTypes { - constructor(task, taskDescription, taskColor, bug, bugDescription, bugColor, feature, featureDescription, featureColor, documentation, documentationDescription, documentationColor, maintenance, maintenanceDescription, maintenanceColor, hotfix, hotfixDescription, hotfixColor, release, releaseDescription, releaseColor, question, questionDescription, questionColor, help, helpDescription, helpColor) { - this.task = task; - this.taskDescription = taskDescription; - this.taskColor = taskColor; - this.bug = bug; - this.bugDescription = bugDescription; - this.bugColor = bugColor; - this.feature = feature; - this.featureDescription = featureDescription; - this.featureColor = featureColor; - this.documentation = documentation; - this.documentationDescription = documentationDescription; - this.documentationColor = documentationColor; - this.maintenance = maintenance; - this.maintenanceDescription = maintenanceDescription; - this.maintenanceColor = maintenanceColor; - this.hotfix = hotfix; - this.hotfixDescription = hotfixDescription; - this.hotfixColor = hotfixColor; - this.release = release; - this.releaseDescription = releaseDescription; - this.releaseColor = releaseColor; - this.question = question; - this.questionDescription = questionDescription; - this.questionColor = questionColor; - this.help = help; - this.helpDescription = helpDescription; - this.helpColor = helpColor; - } + // 4. Return result. + return result } -exports.IssueTypes = IssueTypes; +// 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 + } -/***/ 10818: -/***/ ((__unused_webpack_module, exports) => { + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. -"use strict"; + // 2. Let thisValue be the this value. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Labels = void 0; -class Labels { - get isMandatoryBranchedLabel() { - return this.isHotfix || this.isRelease; - } - get containsBranchedLabel() { - return this.currentIssueLabels.includes(this.branchManagementLauncherLabel); - } - get isDeploy() { - return this.currentIssueLabels.includes(this.deploy); - } - get isDeployed() { - return this.currentIssueLabels.includes(this.deployed); - } - get isHelp() { - return this.currentIssueLabels.includes(this.help); - } - get isQuestion() { - return this.currentIssueLabels.includes(this.question); - } - get isFeature() { - return this.currentIssueLabels.includes(this.feature); - } - get isEnhancement() { - return this.currentIssueLabels.includes(this.enhancement); - } - get isBugfix() { - return this.currentIssueLabels.includes(this.bugfix); - } - get isBug() { - return this.currentIssueLabels.includes(this.bug); - } - get isHotfix() { - return this.currentIssueLabels.includes(this.hotfix); - } - get isRelease() { - return this.currentIssueLabels.includes(this.release); - } - get isDocs() { - return this.currentIssueLabels.includes(this.docs); - } - get isDocumentation() { - return this.currentIssueLabels.includes(this.documentation); - } - get isChore() { - return this.currentIssueLabels.includes(this.chore); - } - get isMaintenance() { - return this.currentIssueLabels.includes(this.maintenance); - } - get sizeLabels() { - return [this.sizeXxl, this.sizeXl, this.sizeL, this.sizeM, this.sizeS, this.sizeXs]; - } - get sizedLabelOnIssue() { - if (this.currentIssueLabels.includes(this.sizeXxl)) { - return this.sizeXxl; - } - else if (this.currentIssueLabels.includes(this.sizeXl)) { - return this.sizeXl; - } - else if (this.currentIssueLabels.includes(this.sizeL)) { - return this.sizeL; - } - else if (this.currentIssueLabels.includes(this.sizeM)) { - return this.sizeM; - } - else if (this.currentIssueLabels.includes(this.sizeS)) { - return this.sizeS; - } - else if (this.currentIssueLabels.includes(this.sizeXs)) { - return this.sizeXs; - } - return undefined; - } - get sizedLabelOnPullRequest() { - if (this.currentPullRequestLabels.includes(this.sizeXxl)) { - return this.sizeXxl; - } - else if (this.currentPullRequestLabels.includes(this.sizeXl)) { - return this.sizeXl; - } - else if (this.currentPullRequestLabels.includes(this.sizeL)) { - return this.sizeL; - } - else if (this.currentPullRequestLabels.includes(this.sizeM)) { - return this.sizeM; - } - else if (this.currentPullRequestLabels.includes(this.sizeS)) { - return this.sizeS; - } - else if (this.currentPullRequestLabels.includes(this.sizeXs)) { - return this.sizeXs; - } - return undefined; - } - get isIssueSized() { - return this.sizedLabelOnIssue !== undefined; - } - get isPullRequestSized() { - return this.sizedLabelOnPullRequest !== undefined; - } - get priorityLabels() { - return [this.priorityHigh, this.priorityMedium, this.priorityLow, this.priorityNone]; - } - get priorityLabelOnIssue() { - if (this.currentIssueLabels.includes(this.priorityHigh)) { - return this.priorityHigh; - } - else if (this.currentIssueLabels.includes(this.priorityMedium)) { - return this.priorityMedium; - } - else if (this.currentIssueLabels.includes(this.priorityLow)) { - return this.priorityLow; - } - else if (this.currentIssueLabels.includes(this.priorityNone)) { - return this.priorityNone; - } - return undefined; - } - get priorityLabelOnIssueProcessable() { - return this.currentIssueLabels.includes(this.priorityHigh) || - this.currentIssueLabels.includes(this.priorityMedium) || - this.currentIssueLabels.includes(this.priorityLow); - } - get priorityLabelOnPullRequest() { - if (this.currentPullRequestLabels.includes(this.priorityHigh)) { - return this.priorityHigh; - } - else if (this.currentPullRequestLabels.includes(this.priorityMedium)) { - return this.priorityMedium; - } - else if (this.currentPullRequestLabels.includes(this.priorityLow)) { - return this.priorityLow; - } - else if (this.currentPullRequestLabels.includes(this.priorityNone)) { - return this.priorityNone; - } - return undefined; - } - get priorityLabelOnPullRequestProcessable() { - return this.currentPullRequestLabels.includes(this.priorityHigh) || - this.currentPullRequestLabels.includes(this.priorityMedium) || - this.currentPullRequestLabels.includes(this.priorityLow); - } - get isIssuePrioritized() { - return this.priorityLabelOnIssue !== undefined && this.priorityLabelOnIssue !== this.priorityNone; + // 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 } - get isPullRequestPrioritized() { - return this.priorityLabelOnPullRequest !== undefined && this.priorityLabelOnPullRequest !== this.priorityNone; + 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 } - constructor(branchManagementLauncherLabel, bug, bugfix, hotfix, enhancement, feature, release, question, help, deploy, deployed, docs, documentation, chore, maintenance, priorityHigh, priorityMedium, priorityLow, priorityNone, sizeXxl, sizeXl, sizeL, sizeM, sizeS, sizeXs) { - this.currentIssueLabels = []; - this.currentPullRequestLabels = []; - this.branchManagementLauncherLabel = branchManagementLauncherLabel; - this.bug = bug; - this.bugfix = bugfix; - this.hotfix = hotfix; - this.enhancement = enhancement; - this.feature = feature; - this.release = release; - this.question = question; - this.help = help; - this.deploy = deploy; - this.deployed = deployed; - this.docs = docs; - this.documentation = documentation; - this.chore = chore; - this.maintenance = maintenance; - this.sizeXxl = sizeXxl; - this.sizeXl = sizeXl; - this.sizeL = sizeL; - this.sizeM = sizeM; - this.sizeS = sizeS; - this.sizeXs = sizeXs; - this.priorityHigh = priorityHigh; - this.priorityMedium = priorityMedium; - this.priorityLow = priorityLow; - this.priorityNone = priorityNone; + 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 } } -exports.Labels = Labels; +/** + * @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 -/***/ 82152: -/***/ ((__unused_webpack_module, exports) => { + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError -"use strict"; + // 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 -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Locale = void 0; -class Locale { - constructor(issue, pullRequest) { - this.issue = issue; - this.pullRequest = pullRequest; - } + 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) + } } -exports.Locale = Locale; -Locale.DEFAULT = 'en-US'; +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream + +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } -/***/ }), + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} -/***/ 52298: -/***/ ((__unused_webpack_module, exports) => { +const MAXIMUM_ARGUMENT_LENGTH = 65535 -"use strict"; +/** + * @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. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Milestone = void 0; -class Milestone { - constructor(id, title, description) { - this.id = id; - this.title = title; - this.description = description; + 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 } + } } -exports.Milestone = Milestone; +/** + * @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 +} -/***/ 93765: -/***/ ((__unused_webpack_module, exports) => { +/** + * @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 -"use strict"; + while (true) { + const { done, value: chunk } = await reader.read() -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProjectDetail = void 0; -class ProjectDetail { - constructor(data) { - this.id = data[`id`] ?? ''; - this.title = data[`title`] ?? ''; - this.type = data[`type`] ?? ''; - this.owner = data[`owner`] ?? ''; - this.url = data[`url`] ?? ''; - this.number = data[`number`] ?? -1; + 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. + } } -exports.ProjectDetail = ProjectDetail; +/** + * @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 -/***/ 1938: -/***/ ((__unused_webpack_module, exports) => { + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} -"use strict"; +/** + * @param {string|URL} url + */ +function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Projects = void 0; -class Projects { - constructor(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress) { - this.projects = projects; - this.projectColumnIssueCreated = projectColumnIssueCreated; - this.projectColumnPullRequestCreated = projectColumnPullRequestCreated; - this.projectColumnIssueInProgress = projectColumnIssueInProgress; - this.projectColumnPullRequestInProgress = projectColumnPullRequestInProgress; - } - getProjects() { - return this.projects; - } - getProjectColumnIssueCreated() { - return this.projectColumnIssueCreated; - } - getProjectColumnPullRequestCreated() { - return this.projectColumnPullRequestCreated; - } - getProjectColumnIssueInProgress() { - return this.projectColumnIssueInProgress; - } - getProjectColumnPullRequestInProgress() { - return this.projectColumnPullRequestInProgress; - } + 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, + parseMetadata } -exports.Projects = Projects; /***/ }), -/***/ 84179: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 1744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequest = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class PullRequest { - get action() { - return this.inputs?.action ?? github.context.payload.action ?? ''; - } - get id() { - return this.inputs?.pull_request?.node_id ?? github.context.payload.pull_request?.node_id ?? ''; - } - get title() { - return this.inputs?.pull_request?.title ?? github.context.payload.pull_request?.title ?? ''; - } - get creator() { - return this.inputs?.pull_request?.user?.login ?? github.context.payload.pull_request?.user.login ?? ''; - } - get number() { - return this.inputs?.pull_request?.number ?? github.context.payload.pull_request?.number ?? -1; - } - get url() { - return this.inputs?.pull_request?.html_url ?? github.context.payload.pull_request?.html_url ?? ''; - } - get body() { - return this.inputs?.pull_request?.body ?? github.context.payload.pull_request?.body ?? ''; - } - get head() { - return this.inputs?.pull_request?.head?.ref ?? github.context.payload.pull_request?.head.ref ?? ''; - } - get base() { - return this.inputs?.pull_request?.base?.ref ?? github.context.payload.pull_request?.base.ref ?? ''; - } - get isMerged() { - return this.inputs?.pull_request?.merged ?? github.context.payload.pull_request?.merged ?? false; - } - get opened() { - return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); - } - get isOpened() { - return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'open' - && this.action !== 'closed'; - } - get isClosed() { - return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'closed' - || this.action === 'closed'; - } - get isSynchronize() { - return this.action === 'synchronize'; - } - get isPullRequest() { - return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request'; - } - get isPullRequestReviewComment() { - return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request_review_comment'; - } - get commentId() { - return this.inputs?.pull_request_review_comment?.id ?? github.context.payload.pull_request_review_comment?.id ?? -1; - } - get commentBody() { - return this.inputs?.pull_request_review_comment?.body ?? github.context.payload.pull_request_review_comment?.body ?? ''; - } - get commentAuthor() { - return this.inputs?.pull_request_review_comment?.user?.login ?? github.context.payload.pull_request_review_comment?.user.login ?? ''; - } - get commentUrl() { - return this.inputs?.pull_request_review_comment?.html_url ?? github.context.payload.pull_request_review_comment?.html_url ?? ''; - } - constructor(desiredAssigneesCount, desiredReviewersCount, mergeTimeout, inputs = undefined) { - this.inputs = undefined; - this.desiredAssigneesCount = desiredAssigneesCount; - this.desiredReviewersCount = desiredReviewersCount; - this.mergeTimeout = mergeTimeout; - this.inputs = inputs; + +const { types } = __nccwpck_require__(3837) +const { hasOwn, toUSVString } = __nccwpck_require__(2538) + +/** @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' } + } } -exports.PullRequest = PullRequest; +// 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 -/***/ 12551: -/***/ ((__unused_webpack_module, exports) => { + // 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: -"use strict"; + // 1. Let lowerBound be 0. + lowerBound = 0 -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Release = void 0; -class Release { - constructor() { - this.active = false; - } -} -exports.Release = Release; + // 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 + } -/***/ 27305: -/***/ ((__unused_webpack_module, exports) => { + // 4. Let x be ? ToNumber(V). + let x = Number(V) -"use strict"; + // 5. If x is āˆ’0, then set x to +0. + if (x === 0) { + x = 0 + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Result = void 0; -class Result { - constructor(data) { - this.id = data['id'] ?? ''; - this.success = data['success'] ?? false; - this.executed = data['executed'] ?? false; - this.steps = data['steps'] ?? []; - this.errors = data['errors'] ?? []; - this.payload = data['payload']; - this.reminders = data['reminders'] ?? []; + // 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.` + }) } -} -exports.Result = Result; + // 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}.` + }) + } -/***/ 28024: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 4. Return x. + return x + } -"use strict"; + // 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) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SingleAction = void 0; -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class SingleAction { - get isDeployedAction() { - return this.currentSingleAction === constants_1.ACTIONS.DEPLOYED; - } - get isCompileVectorServerAction() { - return this.currentSingleAction === constants_1.ACTIONS.COMPILE_VECTOR_SERVER; - } - get isVectorAction() { - return this.currentSingleAction === constants_1.ACTIONS.VECTOR || this.currentSingleAction === constants_1.ACTIONS.VECTOR_LOCAL; - } - get isVectorLocalAction() { - return this.currentSingleAction === constants_1.ACTIONS.VECTOR_LOCAL; - } - get isVectorRemovalAction() { - return this.currentSingleAction === constants_1.ACTIONS.VECTOR_REMOVAL; - } - get isPublishGithubAction() { - return this.currentSingleAction === constants_1.ACTIONS.PUBLISH_GITHUB_ACTION; - } - get isCreateReleaseAction() { - return this.currentSingleAction === constants_1.ACTIONS.CREATE_RELEASE; - } - get isCreateTagAction() { - return this.currentSingleAction === constants_1.ACTIONS.CREATE_TAG; - } - get enabledSingleAction() { - return this.currentSingleAction.length > 0; - } - get validSingleAction() { - return this.enabledSingleAction && - (this.issue > 0 || this.isSingleActionWithoutIssue) && - this.actions.indexOf(this.currentSingleAction) > -1; - } - get isSingleActionWithoutIssue() { - return this.actionsWithoutIssue.indexOf(this.currentSingleAction) > -1; - } - get throwError() { - return this.actionsThrowError.indexOf(this.currentSingleAction) > -1; - } - constructor(currentSingleAction, issue, version, title, changelog) { - this.actions = [ - constants_1.ACTIONS.DEPLOYED, - constants_1.ACTIONS.COMPILE_VECTOR_SERVER, - constants_1.ACTIONS.VECTOR, - constants_1.ACTIONS.VECTOR_LOCAL, - constants_1.ACTIONS.VECTOR_REMOVAL, - constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, - constants_1.ACTIONS.CREATE_TAG, - constants_1.ACTIONS.CREATE_RELEASE, - ]; - /** - * Actions that throw an error if the last step failed - */ - this.actionsThrowError = [ - constants_1.ACTIONS.VECTOR, - constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, - constants_1.ACTIONS.CREATE_RELEASE, - constants_1.ACTIONS.DEPLOYED, - constants_1.ACTIONS.CREATE_TAG, - ]; - /** - * Actions that do not require an issue - */ - this.actionsWithoutIssue = [ - constants_1.ACTIONS.VECTOR, - constants_1.ACTIONS.VECTOR_LOCAL, - constants_1.ACTIONS.COMPILE_VECTOR_SERVER, - ]; - this.isIssue = false; - this.isPullRequest = false; - this.isPush = false; - /** - * Properties - */ - this.issue = -1; - this.version = ''; - this.title = ''; - this.changelog = ''; - this.version = version; - this.title = title; - this.changelog = changelog; - if (!this.isSingleActionWithoutIssue) { - try { - this.issue = parseInt(issue); - } - catch (error) { - (0, logger_1.logError)(`Issue ${issue} is not a number.`); - (0, logger_1.logError)(error); - } - } - else { - this.issue = 0; - } - this.currentSingleAction = currentSingleAction; + // 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) } -} -exports.SingleAction = SingleAction; + // 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 + } -/***/ 23835: -/***/ ((__unused_webpack_module, exports) => { + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) -"use strict"; + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SizeThreshold = void 0; -class SizeThreshold { - constructor(lines, files, commits) { - this.lines = lines; - this.files = files; - this.commits = commits; - } -} -exports.SizeThreshold = SizeThreshold; + // 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)) -/***/ 98237: -/***/ ((__unused_webpack_module, exports) => { + // 2. If n < 0, then return -1 Ɨ r. + if (n < 0) { + return -1 * r + } -"use strict"; + // 3. Otherwise, return r. + return r +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SizeThresholds = void 0; -class SizeThresholds { - constructor(xxl, xl, l, m, s, xs) { - this.xxl = xxl; - this.xl = xl; - this.l = l; - this.m = m; - this.s = s; - this.xs = xs; +// 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.` + }) } -} -exports.SizeThresholds = SizeThresholds; + // 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.' + }) + } -/***/ 149: -/***/ ((__unused_webpack_module, exports) => { + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() -"use strict"; + if (done) { + break + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SupabaseConfig = void 0; -class SupabaseConfig { - constructor(url, key) { - this.url = url; - this.key = key; - } - getUrl() { - return this.url; - } - getKey() { - return this.key; + seq.push(converter(value)) } + + return seq + } } -exports.SupabaseConfig = SupabaseConfig; +// 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) -/***/ 53421: -/***/ ((__unused_webpack_module, exports) => { + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) -"use strict"; + // 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]) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Tokens = void 0; -class Tokens { - constructor(token, classicToken) { - this.token = token; - this.classicToken = classicToken; + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result } -} -exports.Tokens = Tokens; + // 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) -/***/ 89471: -/***/ ((__unused_webpack_module, exports) => { + // 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) -"use strict"; + // 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]) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Welcome = void 0; -class Welcome { - constructor(title, messages) { - this.title = title; - this.messages = messages; + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } } + + // 5. Return result. + return result + } } -exports.Welcome = Welcome; +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 = {} -/***/ 6845: -/***/ ((__unused_webpack_module, exports) => { + 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.` + }) + } -"use strict"; + for (const options of converters) { + const { key, defaultValue, required, converter } = options -// types.ts (o donde quieras definir tus modelos) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WorkflowRun = void 0; -class WorkflowRun { - // puedes agregar mĆ”s campos si los usas - constructor(data) { - this.id = data.id; - this.name = data.name; - this.head_branch = data.head_branch; - this.head_sha = data.head_sha; - this.run_number = data.run_number; - this.event = data.event; - this.status = data.status; - this.conclusion = data.conclusion; - this.created_at = data.created_at; - this.updated_at = data.updated_at; - this.url = data.url; - this.html_url = data.html_url; + 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 + } } - isActive() { - return this.status === "in_progress" || this.status === "queued"; + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V } + + return converter(V) + } } -exports.WorkflowRun = WorkflowRun; +// 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.') + } -/***/ 38553: -/***/ ((__unused_webpack_module, exports) => { + // 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) +} -"use strict"; +// 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) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Workflows = void 0; -class Workflows { - constructor(release, hotfix) { - this.release = release; - this.hotfix = hotfix; + // 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.` + ) } -} -exports.Workflows = Workflows; + } + // 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 -/***/ 68307: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// 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) -"use strict"; + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AiRepository = void 0; -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class AiRepository { - constructor() { - this.ask = async (ai, prompt) => { - const model = ai.getOpenRouterModel(); - const apiKey = ai.getOpenRouterApiKey(); - const providerRouting = ai.getProviderRouting(); - if (!model || !apiKey) { - (0, logger_1.logError)('Missing required AI configuration'); - return undefined; - } - (0, logger_1.logDebugInfo)(`šŸ”Ž Model: ${model}`); - (0, logger_1.logDebugInfo)(`šŸ”Ž API Key: ***`); - (0, logger_1.logDebugInfo)(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); - const url = `https://openrouter.ai/api/v1/chat/completions`; - try { - // logDebugInfo(`Sending prompt to ${model}: ${prompt}`); - const requestBody = { - model: model, - messages: [ - { role: 'user', content: prompt }, - ], - }; - // Add provider routing configuration if it exists and has properties - if (Object.keys(providerRouting).length > 0) { - requestBody.provider = providerRouting; - } - const response = await fetch(url, { - method: 'POST', - headers: { - Authorization: `Bearer ${apiKey}`, - 'HTTP-Referer': constants_1.REPO_URL, - 'X-Title': constants_1.TITLE, - 'Content-Type': 'application/json', - }, - body: JSON.stringify(requestBody), - }); - if (!response.ok) { - const errorText = await response.text(); - console.error('API Response:', errorText); - (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); - return undefined; - } - const data = await response.json(); - if (!data.choices || data.choices.length === 0) { - (0, logger_1.logError)('No response content received from API'); - return undefined; - } - (0, logger_1.logDebugInfo)(`Successfully received response from ${model}`); - return data.choices[0].message.content; - } - catch (error) { - (0, logger_1.logError)(`Error querying ${model}: ${error}`); - return undefined; - } - }; - this.askJson = async (ai, prompt) => { - const result = await this.ask(ai, prompt); - if (!result) { - return undefined; - } - // Clean the response by removing ```json markers if present - const cleanedResult = result - .replace(/^```json\n?/, '') // Remove ```json at the start - .replace(/\n?```$/, '') // Remove ``` at the end - .trim(); - return JSON.parse(cleanedResult); - }; - } +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V } -exports.AiRepository = AiRepository; +// 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 +} -/***/ 37701: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +// 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') -"use strict"; + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BranchRepository = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const exec = __importStar(__nccwpck_require__(71514)); -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const version_utils_1 = __nccwpck_require__(29887); -const result_1 = __nccwpck_require__(27305); -class BranchRepository { - constructor() { - this.fetchRemoteBranches = async () => { - try { - (0, logger_1.logDebugInfo)('Fetching tags and forcing fetch...'); - await exec.exec('git', ['fetch', '--tags', '--force']); - (0, logger_1.logDebugInfo)('Fetching all remote branches with verbose output...'); - await exec.exec('git', ['fetch', '--all', '-v']); - (0, logger_1.logDebugInfo)('Successfully fetched all remote branches.'); - } - catch (error) { - core.setFailed(`Error fetching remote branches: ${error}`); - } - }; - this.getLatestTag = async () => { - try { - (0, logger_1.logDebugInfo)('Fetching the latest tag...'); - await exec.exec('git', ['fetch', '--tags']); - const tags = []; - await exec.exec('git', ['tag', '--sort=-creatordate'], { - listeners: { - stdout: (data) => { - tags.push(...data.toString().split('\n').map((v, i, a) => { - return v.replace('v', ''); - })); - }, - }, - }); - const validTags = tags.filter(tag => /\d+\.\d+\.\d+$/.test(tag)); - if (validTags.length > 0) { - const latestTag = (0, version_utils_1.getLatestVersion)(validTags); - (0, logger_1.logDebugInfo)(`Latest tag: ${latestTag}`); - return latestTag; - } - else { - (0, logger_1.logDebugInfo)('No valid tags found.'); - return undefined; - } - } - catch (error) { - core.setFailed(`Error fetching the latest tag: ${error}`); - return undefined; - } - }; - this.getCommitTag = async (latestTag) => { - try { - if (!latestTag) { - core.setFailed('No LATEST_TAG found in the environment'); - return; - } - let tagVersion; - if (latestTag.startsWith('v')) { - tagVersion = latestTag; - } - else { - tagVersion = `v${latestTag}`; - } - (0, logger_1.logDebugInfo)(`Fetching commit hash for the tag: ${tagVersion}`); - let commitOid = ''; - await exec.exec('git', ['rev-list', '-n', '1', tagVersion], { - listeners: { - stdout: (data) => { - commitOid = data.toString().trim(); - }, - }, - }); - if (commitOid) { - (0, logger_1.logDebugInfo)(`Commit tag: ${commitOid}`); - return commitOid; - } - else { - core.setFailed('No commit found for the tag'); - } - } - catch (error) { - core.setFailed(`Error fetching the commit hash: ${error}`); - } - return undefined; - }; - /** - * Returns replaced branch (if any). - * - * @param param - * @param repository - * @param owner - * @param token - * @param issueNumber - * @param issueTitle - * @param branchType - * @param developmentBranch - * @param hotfixBranch - * @param isHotfix - */ - this.manageBranches = async (param, owner, repository, issueNumber, issueTitle, branchType, developmentBranch, hotfixBranch, isHotfix, token) => { - const result = []; - try { - (0, logger_1.logDebugInfo)(`Managing branches`); - const branches = await this.getListOfBranches(owner, repository, token); - (0, logger_1.logDebugInfo)(JSON.stringify(branches, null, 2)); - if (hotfixBranch === undefined && isHotfix) { - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Tried to prepare the hotfix branch of the issue, but hotfix branch was not found.`, - ], - })); - return result; - } - const octokit = github.getOctokit(token); - const sanitizedTitle = this.formatBranchName(issueTitle, issueNumber); - const newBranchName = `${branchType}/${issueNumber}-${sanitizedTitle}`; - if (branches.indexOf(newBranchName) > -1) { - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: false, - })); - return result; - } - const branchTypes = [ - param.branches.featureTree, - param.branches.bugfixTree, - param.branches.docsTree, - param.branches.choreTree, - ]; - /** - * Default base branch name. (ex. [develop]) - */ - let baseBranchName = developmentBranch; - if (!isHotfix) { - /** - * Check if it is a branch switch: feature/123-bla <-> bugfix/123-bla - */ - (0, logger_1.logDebugInfo)(`Searching for branches related to issue #${issueNumber}...`); - const { data } = await octokit.rest.repos.listBranches({ - owner: owner, - repo: repository, - }); - for (const type of branchTypes) { - const prefix = `${type}/${issueNumber}-`; - try { - const matchingBranch = data.find(branch => branch.name.indexOf(prefix) > -1); - if (matchingBranch) { - baseBranchName = matchingBranch.name; - (0, logger_1.logDebugInfo)(`Found previous issue branch: ${baseBranchName}`); - // TODO replacedBranchName = baseBranchName - break; - } - } - catch (error) { - (0, logger_1.logError)(`Error while listing branches: ${error}`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Error while listing branches.`, - ], - error: error, - })); - } - } - } - else { - baseBranchName = hotfixBranch ?? developmentBranch; - } - param.currentConfiguration.parentBranch = baseBranchName; - (0, logger_1.logDebugInfo)(`============================================================================================`); - (0, logger_1.logDebugInfo)(`Base branch: ${baseBranchName}`); - (0, logger_1.logDebugInfo)(`New branch: ${newBranchName}`); - result.push(...await this.createLinkedBranch(owner, repository, baseBranchName, newBranchName, issueNumber, undefined, token)); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Tried to prepare the hotfix to the issue, but there was a problem.`, - ], - error: error, - })); - } - return result; - }; - this.formatBranchName = (issueTitle, issueNumber) => { - let sanitizedTitle = issueTitle.toLowerCase() - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - sanitizedTitle = sanitizedTitle.replace(/[^a-z0-9 ]/g, '').replace(/ /g, '-'); - const issuePrefix = `${issueNumber}-`; - if (sanitizedTitle.startsWith(issuePrefix)) { - sanitizedTitle = sanitizedTitle.substring(issuePrefix.length); - } - sanitizedTitle = sanitizedTitle.replace(/-+/g, '-'); - sanitizedTitle = sanitizedTitle.replace(/^-|-$/g, ''); - return sanitizedTitle; - }; - this.createLinkedBranch = async (owner, repo, baseBranchName, newBranchName, issueNumber, oid, token) => { - const result = []; - try { - (0, logger_1.logDebugInfo)(`Creating linked branch ${newBranchName} from ${oid ?? baseBranchName}`); - let ref = `heads/${baseBranchName}`; - if (baseBranchName.indexOf('tags/') > -1) { - ref = baseBranchName; - } - const octokit = github.getOctokit(token); - const { repository } = await octokit.graphql(` - query($repo: String!, $owner: String!, $issueNumber: Int!) { - repository(name: $repo, owner: $owner) { - id - issue(number: $issueNumber) { - id - } - ref(qualifiedName: "refs/${ref}") { - target { - ... on Commit { - oid - } - } - } - } - } - `, { - repo: repo, - owner: owner, - issueNumber: issueNumber - }); - (0, logger_1.logDebugInfo)(`Repository information retrieved: ${JSON.stringify(repository?.ref)}`); - const repositoryId = repository?.id ?? undefined; - const issueId = repository?.issue?.id ?? undefined; - const branchOid = oid ?? repository?.ref?.target?.oid ?? undefined; - if (repositoryId === undefined || issueNumber === undefined || branchOid === undefined) { - (0, logger_1.logError)(`Error searching repository "${baseBranchName}": id: ${repositoryId}, oid: ${branchOid}), issue #${issueNumber}`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Error linking branch ${newBranchName} to issue: Repository not found.`, - ], - })); - return result; - } - (0, logger_1.logDebugInfo)(`Linking branch "${newBranchName}" (oid: ${branchOid}) to issue #${issueNumber}`); - const mutationResponse = await octokit.graphql(` - mutation($issueId: ID!, $name: String!, $repositoryId: ID!, $oid: GitObjectID!) { - createLinkedBranch(input: { - issueId: $issueId, - name: $name, - repositoryId: $repositoryId, - oid: $oid, - }) { - linkedBranch { - id - ref { - name - } - } - } - } - `, { - issueId: issueId, - name: `/${newBranchName}`, - repositoryId: repositoryId, - oid: branchOid, - }); - (0, logger_1.logDebugInfo)(`Linked branch: ${JSON.stringify(mutationResponse.createLinkedBranch?.linkedBranch)}`); - const baseBranchUrl = `https://github.com/${owner}/${repo}/tree/${baseBranchName}`; - const newBranchUrl = `https://github.com/${owner}/${repo}/tree/${newBranchName}`; - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: true, - payload: { - baseBranchName: baseBranchName, - baseBranchUrl: baseBranchUrl, - newBranchName: newBranchName, - newBranchUrl: newBranchUrl, - }, - })); - } - catch (error) { - (0, logger_1.logError)(`Error Linking branch "${error}"`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Tried to link branch to the issue, but there was a problem.`, - ], - error: error, - })); - } - return result; - }; - this.removeBranch = async (owner, repository, branch, token) => { - const octokit = github.getOctokit(token); - const ref = `heads/${branch}`; - try { - const { data } = await octokit.rest.git.getRef({ - owner: owner, - repo: repository, - ref, - }); - (0, logger_1.logDebugInfo)(`Branch found: ${data.ref}`); - await octokit.rest.git.deleteRef({ - owner: owner, - repo: repository, - ref, - }); - (0, logger_1.logDebugInfo)(`Successfully deleted branch: ${branch}`); - return true; - } - catch (error) { - (0, logger_1.logError)(`Error processing branch ${branch}: ${error}`); - throw error; - } - }; - this.getListOfBranches = async (owner, repository, token) => { - const octokit = github.getOctokit(token); - const allBranches = []; - let page = 1; - while (true) { - const { data } = await octokit.rest.repos.listBranches({ - owner: owner, - repo: repository, - per_page: 100, - page: page, - }); - if (data.length === 0) { - break; - } - allBranches.push(...data.map(branch => branch.name)); - page++; - } - return allBranches; - }; - this.executeWorkflow = async (owner, repository, branch, workflow, inputs, token) => { - const octokit = github.getOctokit(token); - return octokit.rest.actions.createWorkflowDispatch({ - owner: owner, - repo: repository, - workflow_id: workflow, - ref: branch, - inputs: inputs - }); - }; - this.mergeBranch = async (owner, repository, head, base, timeout, token) => { - const result = []; - try { - const octokit = github.getOctokit(token); - (0, logger_1.logDebugInfo)(`Creating merge from ${head} into ${base}`); - // Build PR body with commit list - const prBody = `šŸš€ Automated Merge +// 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') -This PR merges **${head}** into **${base}**. + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} -**Commits included:**`; - // We need PAT for creating PR to ensure it can trigger workflows - const { data: pullRequest } = await octokit.rest.pulls.create({ - owner: owner, - repo: repository, - head: head, - base: base, - title: `Merge ${head} into ${base}`, - body: prBody, - }); - (0, logger_1.logDebugInfo)(`Pull request #${pullRequest.number} created, getting commits...`); - // Get all commits in the PR - const { data: commits } = await octokit.rest.pulls.listCommits({ - owner: owner, - repo: repository, - pull_number: pullRequest.number - }); - const commitMessages = commits.map(commit => commit.commit.message); - (0, logger_1.logDebugInfo)(`Found ${commitMessages.length} commits in PR`); - // Update PR with commit list and footer - await octokit.rest.pulls.update({ - owner: owner, - repo: repository, - pull_number: pullRequest.number, - body: prBody + '\n' + commitMessages.map(msg => `- ${msg}`).join('\n') + - '\n\nThis PR was automatically created by [`git-board-flow`](https://github.com/landamessenger/git-board-flow).' - }); - const iteration = 10; - if (timeout > iteration) { - // Wait for checks to complete - can use regular token for reading checks - let checksCompleted = false; - let attempts = 0; - const maxAttempts = timeout > iteration ? Math.floor(timeout / iteration) : iteration; - while (!checksCompleted && attempts < maxAttempts) { - const { data: checkRuns } = await octokit.rest.checks.listForRef({ - owner: owner, - repo: repository, - ref: head, - }); - // Get commit status checks for the PR head commit - const { data: commitStatus } = await octokit.rest.repos.getCombinedStatusForRef({ - owner: owner, - repo: repository, - ref: head - }); - (0, logger_1.logDebugInfo)(`Combined status state: ${commitStatus.state}`); - (0, logger_1.logDebugInfo)(`Number of check runs: ${checkRuns.check_runs.length}`); - // If there are check runs, prioritize those over status checks - if (checkRuns.check_runs.length > 0) { - const pendingCheckRuns = checkRuns.check_runs.filter(check => check.status !== 'completed'); - if (pendingCheckRuns.length === 0) { - checksCompleted = true; - (0, logger_1.logDebugInfo)('All check runs have completed.'); - // Verify if all checks passed - const failedChecks = checkRuns.check_runs.filter(check => check.conclusion === 'failure'); - if (failedChecks.length > 0) { - throw new Error(`Checks failed: ${failedChecks.map(check => check.name).join(', ')}`); - } - } - else { - (0, logger_1.logDebugInfo)(`Waiting for ${pendingCheckRuns.length} check runs to complete:`); - pendingCheckRuns.forEach(check => { - (0, logger_1.logDebugInfo)(` - ${check.name} (Status: ${check.status})`); - }); - await new Promise(resolve => setTimeout(resolve, iteration * 1000)); - attempts++; - continue; - } - } - else { - // Fall back to status checks if no check runs exist - const pendingChecks = commitStatus.statuses.filter(status => { - (0, logger_1.logDebugInfo)(`Status check: ${status.context} (State: ${status.state})`); - return status.state === 'pending'; - }); - if (pendingChecks.length === 0) { - checksCompleted = true; - (0, logger_1.logDebugInfo)('All status checks have completed.'); - } - else { - (0, logger_1.logDebugInfo)(`Waiting for ${pendingChecks.length} status checks to complete:`); - pendingChecks.forEach(check => { - (0, logger_1.logDebugInfo)(` - ${check.context} (State: ${check.state})`); - }); - await new Promise(resolve => setTimeout(resolve, iteration * 1000)); - attempts++; - } - } - } - if (!checksCompleted) { - throw new Error('Timed out waiting for checks to complete'); - } - } - // Need PAT for merging to ensure it can trigger subsequent workflows - await octokit.rest.pulls.merge({ - owner: owner, - repo: repository, - pull_number: pullRequest.number, - merge_method: 'merge', - commit_title: `Merge ${head} into ${base}. Forced merge with PAT token.`, - }); - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: true, - steps: [ - `The branch \`${head}\` was merged into \`${base}\`.`, - ], - })); - } - catch (error) { - (0, logger_1.logError)(`Error in PR workflow: ${error}`); - // If the PR workflow fails, we try to merge directly - need PAT for direct merge to ensure it can trigger workflows - try { - const octokit = github.getOctokit(token); - await octokit.rest.repos.merge({ - owner: owner, - repo: repository, - base: base, - head: head, - commit_message: `Forced merge of ${head} into ${base}. Automated merge with PAT token.`, - }); - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: true, - steps: [ - `The branch \`${head}\` was merged into \`${base}\` using direct merge.`, - ], - })); - return result; - } - catch (directMergeError) { - (0, logger_1.logError)(`Error in direct merge attempt: ${directMergeError}`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Failed to merge branch \`${head}\` into \`${base}\`.`, - ], - })); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - error: error, - })); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - error: directMergeError, - })); - } - } - return result; - }; - this.getChanges = async (owner, repository, head, base, token) => { - const octokit = github.getOctokit(token); - try { - (0, logger_1.logDebugInfo)(`Comparing branches: ${head} with ${base}`); - let headRef = `heads/${head}`; - if (head.indexOf('tags/') > -1) { - headRef = head; - } - let baseRef = `heads/${base}`; - if (base.indexOf('tags/') > -1) { - baseRef = base; - } - const { data: comparison } = await octokit.rest.repos.compareCommits({ - owner: owner, - repo: repository, - base: baseRef, - head: headRef, - }); - return { - aheadBy: comparison.ahead_by, - behindBy: comparison.behind_by, - totalCommits: comparison.total_commits, - files: (comparison.files || []).map(file => ({ - filename: file.filename, - status: file.status, - additions: file.additions, - deletions: file.deletions, - changes: file.changes, - blobUrl: file.blob_url, - rawUrl: file.raw_url, - contentsUrl: file.contents_url, - patch: file.patch - })), - commits: comparison.commits.map(commit => ({ - sha: commit.sha, - message: commit.commit.message, - author: commit.commit.author || { name: 'Unknown', email: 'unknown@example.com', date: new Date().toISOString() }, - date: commit.commit.author?.date || new Date().toISOString() - })) - }; - } - catch (error) { - (0, logger_1.logError)(`Error comparing branches: ${error}`); - throw error; - } - }; - this.getSizeCategoryAndReason = async (owner, repository, head, base, sizeThresholds, labels, token) => { - try { - const headBranchChanges = await this.getChanges(owner, repository, head, base, token); - const totalChanges = headBranchChanges.files.reduce((sum, file) => sum + file.changes, 0); - const totalFiles = headBranchChanges.files.length; - const totalCommits = headBranchChanges.totalCommits; - let sizeCategory; - let githubSize; - let sizeReason; - if (totalChanges > sizeThresholds.xxl.lines || totalFiles > sizeThresholds.xxl.files || totalCommits > sizeThresholds.xxl.commits) { - sizeCategory = labels.sizeXxl; - githubSize = `XL`; - sizeReason = totalChanges > sizeThresholds.xxl.lines ? `More than ${sizeThresholds.xxl.lines} lines changed` : - totalFiles > sizeThresholds.xxl.files ? `More than ${sizeThresholds.xxl.files} files modified` : - `More than ${sizeThresholds.xxl.commits} commits`; - } - else if (totalChanges > sizeThresholds.xl.lines || totalFiles > sizeThresholds.xl.files || totalCommits > sizeThresholds.xl.commits) { - sizeCategory = labels.sizeXl; - githubSize = `XL`; - sizeReason = totalChanges > sizeThresholds.xl.lines ? `More than ${sizeThresholds.xl.lines} lines changed` : - totalFiles > sizeThresholds.xl.files ? `More than ${sizeThresholds.xl.files} files modified` : - `More than ${sizeThresholds.xl.commits} commits`; - } - else if (totalChanges > sizeThresholds.l.lines || totalFiles > sizeThresholds.l.files || totalCommits > sizeThresholds.l.commits) { - sizeCategory = labels.sizeL; - githubSize = `L`; - sizeReason = totalChanges > sizeThresholds.l.lines ? `More than ${sizeThresholds.l.lines} lines changed` : - totalFiles > sizeThresholds.l.files ? `More than ${sizeThresholds.l.files} files modified` : - `More than ${sizeThresholds.l.commits} commits`; - } - else if (totalChanges > sizeThresholds.m.lines || totalFiles > sizeThresholds.m.files || totalCommits > sizeThresholds.m.commits) { - sizeCategory = labels.sizeM; - githubSize = `M`; - sizeReason = totalChanges > sizeThresholds.m.lines ? `More than ${sizeThresholds.m.lines} lines changed` : - totalFiles > sizeThresholds.m.files ? `More than ${sizeThresholds.m.files} files modified` : - `More than ${sizeThresholds.m.commits} commits`; - } - else if (totalChanges > sizeThresholds.s.lines || totalFiles > sizeThresholds.s.files || totalCommits > sizeThresholds.s.commits) { - sizeCategory = labels.sizeS; - githubSize = `S`; - sizeReason = totalChanges > sizeThresholds.s.lines ? `More than ${sizeThresholds.s.lines} lines changed` : - totalFiles > sizeThresholds.s.files ? `More than ${sizeThresholds.s.files} files modified` : - `More than ${sizeThresholds.s.commits} commits`; - } - else { - sizeCategory = labels.sizeXs; - githubSize = `XS`; - sizeReason = `Small changes (${totalChanges} lines, ${totalFiles} files)`; - } - return { - size: sizeCategory, - githubSize: githubSize, - reason: sizeReason - }; - } - catch (error) { - (0, logger_1.logError)(`Error comparing branches: ${error}`); - throw error; - } - }; - } +// 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 +} + + +/***/ }), + +/***/ 4854: +/***/ ((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 } -exports.BranchRepository = BranchRepository; /***/ }), -/***/ 19097: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 1446: +/***/ ((module, __unused_webpack_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 })); -exports.DockerRepository = void 0; -const dockerode_1 = __importDefault(__nccwpck_require__(14571)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const axios_1 = __importDefault(__nccwpck_require__(88757)); -const logger_1 = __nccwpck_require__(38836); -const child_process_1 = __nccwpck_require__(32081); -class DockerRepository { - constructor() { - // ============================== - // šŸ”§ Core Docker Lifecycle - // ============================== - this.prepareLocalVectorServer = async (param) => { - (0, logger_1.logDebugInfo)('🐳 🟔 Preparing local vector server...'); - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - try { - // Authenticate with registry - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - // Check if image already exists locally - const localImageExists = await this.imageExists(param); - if (localImageExists) { - (0, logger_1.logDebugInfo)(`🐳 🟢 Local image ${imageName} already exists, skipping pull`); - return; - } - // Check if multi-architecture image exists in registry - const registryImageExists = await this.checkMultiArchImageInRegistry(param); - if (!registryImageExists) { - throw new Error(`Multi-architecture image not found in registry: ${registryImageName}. Please build the image first using PrepareAIContainerUseCase.`); - } - // Pull the multi-architecture image from registry - (0, logger_1.logDebugInfo)(`🐳 🟔 Pulling multi-architecture image from registry: ${registryImageName}`); - try { - (0, child_process_1.execSync)(`docker pull ${registryImageName}`, { - stdio: 'inherit', - env: { ...process.env, DOCKER_BUILDKIT: '1' } - }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Successfully pulled multi-architecture image: ${registryImageName}`); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Failed to pull image: ${error}`); - throw error; - } - // Tag the pulled image with local name for consistency - (0, child_process_1.execSync)(`docker tag ${registryImageName} ${imageName}`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-architecture image pulled and tagged successfully: ${imageName}`); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Failed to prepare local vector server: ${error}`); - throw error; - } - }; - this.checkVersionExistsInRegistry = async (param) => { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - try { - (0, logger_1.logDebugInfo)(`🐳 🟔 Checking if version already exists in registry: ${registryImageName}`); - // Try to inspect the manifest to check if version exists - const output = (0, child_process_1.execSync)(`docker manifest inspect ${registryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - // Check if the manifest contains both architectures (multi-arch image) - const hasAmd64 = output.includes('"architecture": "amd64"'); - const hasArm64 = output.includes('"architecture": "arm64"'); - const versionExists = hasAmd64 && hasArm64; - (0, logger_1.logDebugInfo)(`🐳 🟔 Version ${imageName} exists in registry: ${versionExists}`); - return versionExists; - } - catch (error) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Version ${imageName} not found in registry: ${error}`); - return false; - } - }; - this.startContainer = async (param) => { - (0, logger_1.logDebugInfo)('🐳 🟔 Starting Docker container...'); - const isRunning = await this.isContainerRunning(param); - if (isRunning) { - (0, logger_1.logDebugInfo)('🐳 🟢 Docker container is ready'); - return; - } - try { - /* - if (this.shouldUsePrebuiltImage()) { - const imageExists = await this.imageExists(param); - if (!imageExists) { - const pulled = await this.pullPrebuiltImage(param); - if (!pulled) throw new Error('Prebuilt image not available'); - } - } else if (this.shouldUseLocalImage()) { - const imageExists = await this.imageExists(param); - if (!imageExists) await this.buildImage(param); - }*/ - await this.runContainer(param); - (0, logger_1.logDebugInfo)('🐳 🟢 Container started successfully'); - } - catch (error) { - (0, logger_1.logError)('Error starting container: ' + error); - throw error; - } - }; - this.runContainer = async (param) => { - const container = await this.getContainer(param); - const info = await container.inspect(); - if (info.State.Status !== 'running') - await container.start(); - await this.waitForContainer(param); - }; - this.imageExists = async (param) => { - const images = await this.docker.listImages(); - return images.some(img => img.RepoTags && img.RepoTags.includes(this.getImageNameWithTag(param))); - }; - this.pullPrebuiltImage = async (param) => { - try { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - const stream = await this.docker.pull(registryImageName); - await new Promise((resolve, reject) => { - this.docker.modem.followProgress(stream, (err) => { - if (err) - reject(err); - else - resolve(true); - }); - }); - return true; - } - catch { - return false; - } - }; - // ============================== - // 🧱 Build Image - // ============================== - this.buildImage = async (param) => { - // const imageName = this.getImageNameWithTag(param); - // const archType = this.getArchitectureType(); - // Check if Docker Buildx is available for multi-architecture builds - const buildxAvailable = await this.checkDockerBuildxAvailable(); - if (buildxAvailable) { - await this.buildMultiArchImage(param); - } - /* else { - logDebugInfo(`🐳 🟔 Building single-architecture Docker image: ${imageName} for architecture: ${archType}`); - await this.buildSingleArchImage(param, imageName, archType); - }*/ - (0, logger_1.logDebugInfo)('🐳 🟢 Docker image built successfully'); - }; - /*private async buildSingleArchImage(param: Execution, imageName: string, archType: string): Promise { - const stream = await this.docker.buildImage({ - context: this.dockerDir, - src: ['Dockerfile', 'requirements.txt', 'main.py'], - }, { - t: imageName, - dockerfile: 'Dockerfile', - buildargs: {}, - nocache: false, - platform: `linux/${archType}`, - }); - - await new Promise((resolve, reject) => { - this.docker.modem.followProgress(stream, (err: any, res: any) => { - if (err) reject(err); - else resolve(res); - }, (event: any) => { - if (event.stream) logDebugInfo(`🐳 🟔 ${event.stream.trim()}`); - }); - }); - }*/ - // ============================== - // 🧩 Manifest / Registry Handling - // ============================== - /*checkImageInRegistry = async (param: Execution): Promise => { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - const archType = this.getArchitectureType(); - const dockerPlatform = `linux/${archType}`; - - try { - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - const manifestProcess = spawn('docker', ['manifest', 'inspect', registryImageName]); - - const output = await new Promise((resolve) => { - let data = ''; - manifestProcess.stdout.on('data', (chunk) => data += chunk.toString()); - manifestProcess.on('close', () => resolve(data)); - }); - - logDebugInfo(`🐳 🟔 Manifest output: ${output}`); - - if (output.includes(`"${archType}"`)) { - logDebugInfo(`🐳 🟢 Image already has platform ${dockerPlatform}`); - return true; - } else if (output.includes('"architecture"')) { - logDebugInfo(`🐳 🟔 Image exists but missing ${dockerPlatform}`); - return false; - } - return false; - } catch { - logDebugInfo(`🐳 🟔 No manifest found for ${registryImageName}`); - return false; - } - }*/ - /* - pushImageToRegistry = async (param: Execution, imageName: string): Promise => { - const buildxAvailable = await this.checkDockerBuildxAvailable(); - - if (buildxAvailable) { - // For multi-architecture builds, the image is already pushed during build - logDebugInfo('🐳 🟢 Multi-architecture image already pushed during build process'); - return; - } - - // Fallback to single-architecture push for systems without Buildx - const archType = this.getArchitectureType(); - const dockerPlatform = `linux/${archType}`; - const registryImageName = `ghcr.io/${param.owner}/${imageName}:latest`; - - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - - // Tag + Push architecture-specific image - execSync(`docker tag ${imageName}:latest ${registryImageName}`, { stdio: 'inherit' }); - execSync(`docker push ${registryImageName}`, { stdio: 'inherit' }); - - // Merge with existing manifest if necessary - try { - const manifestExists = await this.checkImageInRegistry(param); - if (manifestExists) { - logDebugInfo(`🐳 🟔 Amending existing manifest with ${dockerPlatform}...`); - execSync(`docker manifest create ${registryImageName} --amend ${registryImageName}`, { stdio: 'inherit' }); - } else { - logDebugInfo(`🐳 🟔 Creating new manifest list for ${dockerPlatform}...`); - execSync(`docker manifest create ${registryImageName} ${registryImageName}`, { stdio: 'inherit' }); - } - - execSync(`docker manifest push ${registryImageName}`, { stdio: 'inherit' }); - logDebugInfo(`🐳 🟢 Multi-arch manifest updated successfully for ${dockerPlatform}`); - } catch (err) { - logError(`🐳 šŸ”“ Manifest merge failed: ${err}`); - } - }*/ - this.authenticateWithRegistry = async (organizationName, token) => { - try { - (0, logger_1.logDebugInfo)(`🐳 🟔 Authenticating with GitHub Container Registry as ${organizationName}`); - (0, child_process_1.execSync)(`echo ${token} | docker login ghcr.io -u ${organizationName} --password-stdin`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Authenticated successfully`); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Docker login error: ${error.message}`); - throw error; - } - }; - this.getEmbedding = async (param, textInstructionsPairs) => { - try { - const request = { - instructions: textInstructionsPairs.map(pair => pair[0]), - texts: textInstructionsPairs.map(pair => pair[1]) - }; - const response = await axios_1.default.post(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/embed`, request, { - headers: { - 'Content-Type': 'application/json', - }, - family: 4 - }); - const data = response.data; - return data.embeddings; - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Error getting embedding: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getSystemInfo = async (param) => { - const response = await axios_1.default.get(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/system-info`, { - family: 4 - }); - return response.data; - }; - this.stopContainer = async (param) => { - (0, logger_1.logDebugInfo)('🐳 🟠 Stopping Docker container...'); - if (!this.isContainerRunning(param)) - return; - const containerId = await this.getContainerIdByName(param); - if (!containerId) - return; - try { - const container = this.docker.getContainer(containerId); - await container.stop(); - await container.remove(); - (0, logger_1.logDebugInfo)('🐳 ⚪ Docker container stopped'); - // Clean up dangling images after stopping (only on self-hosted runners) - if (this.isSelfHostedRunner()) { - await this.cleanupDanglingImages(); - await this.cleanupBuildxBuilder(); - } - } - catch (error) { - (0, logger_1.logError)('🐳 šŸ”“ Error stopping container: ' + error); - } - }; - this.cleanupDanglingImages = async () => { - try { - const images = await this.docker.listImages({ filters: { dangling: ['true'] } }); - if (images.length > 0) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Found ${images.length} dangling images, cleaning up...`); - let removedCount = 0; - for (const image of images) { - try { - // Force remove to handle different Docker managers (OrbStack, Colima, Docker Desktop) - await this.docker.getImage(image.Id).remove({ force: true }); - removedCount++; - (0, logger_1.logDebugInfo)(`🐳 🟔 Removed dangling image: ${image.Id.substring(0, 12)}`); - } - catch (error) { - (0, logger_1.logDebugError)(`Error removing dangling image ${image.Id}: ${error}`); - } - } - (0, logger_1.logDebugInfo)(`🐳 🟢 Dangling images cleanup completed: ${removedCount}/${images.length} removed`); - } - } - catch (error) { - (0, logger_1.logDebugError)('Error cleaning up dangling images: ' + error); - } - }; - this.cleanupBuildxBuilder = async () => { - try { - const builderName = 'git-board-flow-multiarch'; - const listCommand = ['docker', 'buildx', 'ls']; - const output = (0, child_process_1.execSync)(listCommand.join(' '), { encoding: 'utf8', stdio: 'pipe' }); - if (output.includes(builderName)) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Cleaning up Buildx builder '${builderName}'...`); - (0, child_process_1.execSync)(`docker buildx rm ${builderName}`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Buildx builder '${builderName}' removed successfully`); - } - } - catch (error) { - (0, logger_1.logDebugError)(`Error cleaning up Buildx builder: ${error}`); - } - }; - this.docker = new dockerode_1.default(); - this.dockerDir = path_1.default.join(process.cwd(), 'docker'); - } - isGitHubActions() { - return process.env.GITHUB_ACTIONS === 'true'; - } - isSelfHostedRunner() { - return process.env.RUNNER_TEMP?.includes('actions-runner') || - process.env.GITHUB_RUN_ID === undefined || - process.env.GITHUB_HOSTED === 'false'; - } - shouldUsePrebuiltImage() { - return this.isGitHubActions() && !this.isSelfHostedRunner(); - } - shouldUseLocalImage() { - return !this.isGitHubActions() || this.isSelfHostedRunner(); - } - getArchitectureType() { - const platform = process.platform; - const arch = process.arch; - if (platform === 'darwin' && arch === 'arm64') - return 'arm64'; - if (platform === 'darwin' && arch === 'x64') - return 'amd64'; - if (platform === 'linux' && arch === 'x64') - return 'amd64'; - if (platform === 'linux' && arch === 'arm64') - return 'arm64'; - if (platform === 'linux' && arch === 'arm') - return 'armv7'; - if (platform === 'win32' && arch === 'x64') - return 'amd64'; - (0, logger_1.logDebugInfo)(`🐳 🟔 Unknown architecture: ${platform}/${arch}, defaulting to amd64`); - return 'amd64'; - } - async checkMultiArchImageInRegistry(param) { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - try { - (0, logger_1.logDebugInfo)(`🐳 🟔 Checking multi-architecture image in registry: ${registryImageName}`); - // Try to inspect the manifest to check if multi-arch image exists - const output = (0, child_process_1.execSync)(`docker manifest inspect ${registryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - (0, logger_1.logDebugInfo)(`🐳 🟔 Manifest output: ${output.substring(0, 500)}...`); - // Check if the manifest contains both architectures - const hasAmd64 = output.includes('"architecture": "amd64"'); - const hasArm64 = output.includes('"architecture": "arm64"'); - (0, logger_1.logDebugInfo)(`🐳 🟔 Registry image check - AMD64: ${hasAmd64}, ARM64: ${hasArm64}`); - return hasAmd64 && hasArm64; - } - catch (error) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Multi-architecture image not found in registry: ${registryImageName} - ${error}`); - // If specific version not found, try latest tag as fallback - if (!imageName.includes('latest')) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Trying latest tag as fallback...`); - const latestImageName = `${this.getImageName(param)}:latest`; - const latestRegistryImageName = `ghcr.io/${param.owner}/${latestImageName}`; - try { - const latestOutput = (0, child_process_1.execSync)(`docker manifest inspect ${latestRegistryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - const hasAmd64Latest = latestOutput.includes('"architecture": "amd64"'); - const hasArm64Latest = latestOutput.includes('"architecture": "arm64"'); - if (hasAmd64Latest && hasArm64Latest) { - (0, logger_1.logDebugInfo)(`🐳 🟢 Found latest multi-architecture image, will use that instead`); - return true; - } - } - catch { - (0, logger_1.logDebugInfo)(`🐳 🟔 Latest image also not found in registry`); - } - } - return false; - } + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = __nccwpck_require__(7530) +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = __nccwpck_require__(9054) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) + +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) } - getImageName(param) { - return param.dockerConfig.getContainerName(); + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null } - getImageNameWithTag(param) { - const version = this.generateImageVersion(param); - return `${this.getImageName(param)}:${version}`; + } + + 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) } - generateImageVersion(param) { - if (param.singleAction.version.length > 0) { - return `v${param.singleAction.version}`; - } - // Fallback to latest - return 'latest'; + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null } - generateImageTags(param) { - const baseImageName = this.getImageName(param); - const tags = []; - // Always include the specific version - const version = this.generateImageVersion(param); - tags.push(`${baseImageName}:${version}`); - tags.push(`${baseImageName}:latest`); - return tags; + } + + 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) } - async checkDockerBuildxAvailable() { - try { - // Check if Docker Buildx is installed - (0, child_process_1.execSync)('docker buildx version', { stdio: 'pipe' }); - // Check if we can create a multi-platform builder - try { - const testBuilderName = 'test-multiarch-builder'; - (0, child_process_1.execSync)(`docker buildx create --name ${testBuilderName} --driver docker-container --platform linux/amd64,linux/arm64`, { stdio: 'pipe' }); - (0, child_process_1.execSync)(`docker buildx rm ${testBuilderName}`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)('🐳 🟢 Docker Buildx supports multi-platform builds'); - return true; - } - catch { - (0, logger_1.logDebugInfo)('🐳 🟔 Docker Buildx available but multi-platform not supported, will create custom builder'); - return true; // Still return true, we'll handle the builder creation in buildMultiArchImage - } - } - catch { - (0, logger_1.logDebugInfo)('🐳 🟔 Docker Buildx not available, falling back to single-architecture build'); - return false; - } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null } - async buildMultiArchImage(param) { - const imageTags = this.generateImageTags(param); - const registryImageTags = imageTags.map(tag => `ghcr.io/${param.owner}/${tag}`); - (0, logger_1.logDebugInfo)(`🐳 🟔 Building multi-architecture Docker image with tags: ${imageTags.join(', ')}`); - (0, logger_1.logDebugInfo)(`🐳 🟔 Registry tags: ${registryImageTags.join(', ')}`); - // Authenticate with registry before building - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - // Create or use a multi-platform builder - const builderName = 'git-board-flow-multiarch'; - await this.ensureMultiPlatformBuilder(builderName); - // Build and push multi-architecture image using Docker Buildx - const buildCommand = [ - 'docker', 'buildx', 'build', - '--builder', builderName, - '--platform', 'linux/amd64,linux/arm64', - ...registryImageTags.flatMap(tag => ['--tag', tag]), - '--push', - '--file', path_1.default.join(this.dockerDir, 'Dockerfile'), - this.dockerDir - ]; - (0, logger_1.logDebugInfo)(`🐳 🟔 Executing: ${buildCommand.join(' ')}`); - try { - (0, child_process_1.execSync)(buildCommand.join(' '), { - stdio: 'inherit', - env: { ...process.env, DOCKER_BUILDKIT: '1' } - }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-architecture image built and pushed successfully with tags: ${imageTags.join(', ')}`); - await this.cleanupDanglingImages(); - await this.cleanupBuildxBuilder(); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Multi-architecture build failed: ${error}`); - throw error; - } + } + + 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) } - async ensureMultiPlatformBuilder(builderName) { - try { - // Check if builder already exists - const listCommand = ['docker', 'buildx', 'ls']; - const output = (0, child_process_1.execSync)(listCommand.join(' '), { encoding: 'utf8', stdio: 'pipe' }); - if (output.includes(builderName)) { - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-platform builder '${builderName}' already exists`); - return; - } - // Create new multi-platform builder - (0, logger_1.logDebugInfo)(`🐳 🟔 Creating multi-platform builder '${builderName}'...`); - const createCommand = [ - 'docker', 'buildx', 'create', - '--name', builderName, - '--driver', 'docker-container', - '--platform', 'linux/amd64,linux/arm64' - ]; - (0, child_process_1.execSync)(createCommand.join(' '), { stdio: 'inherit' }); - // Start the builder - const startCommand = ['docker', 'buildx', 'inspect', '--bootstrap', builderName]; - (0, child_process_1.execSync)(startCommand.join(' '), { stdio: 'inherit' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-platform builder '${builderName}' created and started successfully`); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Failed to create multi-platform builder: ${error}`); - throw error; - } + + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null } - // ============================== - // 🧼 Misc Helpers - // ============================== - async getContainer(param) { - const containerId = await this.getContainerIdByName(param); - const imageName = this.getImageNameWithTag(param); - if (containerId) - return this.docker.getContainer(containerId); - return this.docker.createContainer({ - Image: imageName, - ExposedPorts: { [`${param.dockerConfig.getPort()}/tcp`]: {} }, - HostConfig: { - PortBindings: { [`${param.dockerConfig.getPort()}/tcp`]: [{ HostPort: param.dockerConfig.getPort().toString() }] }, - }, - name: this.getImageName(param), - }); + } + + 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) } - async waitForContainer(param) { - const maxAttempts = 30; - const interval = 2000; - for (let i = 0; i < maxAttempts; i++) { - try { - const res = await axios_1.default.get(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/health`); - if (res.data.status === 'ready') - return; - } - catch { } - await new Promise(r => setTimeout(r, interval)); - } - throw new Error('Container did not become ready'); + + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null } - async getContainerIdByName(param) { - const containers = await this.docker.listContainers({ all: true }); - const found = containers.find(c => c.Names.includes(`/${this.getImageName(param)}`)); - return found?.Id || ''; + } + + 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) } - async isContainerRunning(param) { - const containers = await this.docker.listContainers({ all: true }); - const container = containers.find(c => c.Names.includes(`/${this.getImageName(param)}`)); - return container?.State === 'running'; + + 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 } -exports.DockerRepository = DockerRepository; /***/ }), -/***/ 81503: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 5504: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FileRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const chunked_file_1 = __nccwpck_require__(2469); -const crypto_1 = __nccwpck_require__(6113); -class FileRepository { - constructor() { - this.getFileContent = async (owner, repository, path, token, branch) => { - const octokit = github.getOctokit(token); - try { - const { data } = await octokit.rest.repos.getContent({ - owner, - repo: repository, - path, - ref: branch - }); - if ('content' in data) { - return Buffer.from(data.content, 'base64').toString(); - } - return ''; - } - catch (error) { - (0, logger_1.logError)(`Error getting file content: ${error}.`); - return ''; - } - }; - this.getRepositoryContent = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { - const octokit = github.getOctokit(token); - const fileContents = new Map(); - try { - const getContentRecursively = async (path = '') => { - const { data } = await octokit.rest.repos.getContent({ - owner, - repo: repository, - path, - ref: branch - }); - if (Array.isArray(data)) { - const promises = []; - for (const item of data) { - if (item.type === 'file') { - if (this.isMediaOrPdfFile(item.path) || this.shouldIgnoreFile(item.path, ignoreFiles)) { - ignoredFiles(item.path); - continue; - } - progress(item.path); - const filePromise = (async () => { - const content = await this.getFileContent(owner, repository, item.path, token, branch); - fileContents.set(item.path, content); - })(); - promises.push(filePromise); - } - else if (item.type === 'dir') { - promises.push(getContentRecursively(item.path)); - } - } - await Promise.all(promises); - } - }; - await getContentRecursively(); - return fileContents; - } - catch (error) { - (0, logger_1.logError)(`Error getting repository content: ${error}.`); - return new Map(); - } - }; - this.getChunkedRepositoryContent = async (owner, repository, branch, chunkSize, token, ignoreFiles, progress, ignoredFiles) => { - const fileContents = await this.getRepositoryContent(owner, repository, token, branch, ignoreFiles, progress, ignoredFiles); - const chunkedFilesMap = new Map(); - for (const [path, content] of fileContents.entries()) { - const shasum = this.calculateShasum(content); - chunkedFilesMap.set(path, [ - ...this.getChunksByLines(path, content, shasum, chunkSize), - ...this.getChunksByBlocks(path, content, shasum, chunkSize), - ]); - } - return chunkedFilesMap; - }; - this.getChunksByLines = (path, content, shasum, chunkSize) => { - const chunkedFiles = []; - const lines = content.split('\n'); - const chunks = []; - let currentChunk = []; - for (const line of lines) { - if (this.shouldIgnoreLine(line)) { - continue; - } - currentChunk.push(line.trim()); - if (currentChunk.length >= chunkSize) { - chunks.push([...currentChunk]); - currentChunk = []; - } - } - // Add the last chunk if it's not empty - if (currentChunk.length > 0) { - chunks.push(currentChunk); - } - // Create ChunkedFile objects for each chunk - chunks.forEach((chunkLines, index) => { - const chunkContent = chunkLines.join('\n'); - chunkedFiles.push(new chunked_file_1.ChunkedFile(path, index, 'line', chunkContent, shasum, chunkLines)); - }); - return chunkedFiles; - }; - this.getChunksByBlocks = (path, content, shasum, chunkSize) => { - const chunkedFiles = []; - const blocks = this.extractCodeBlocks(content); - const chunks = []; - let currentChunk = []; - for (const block of blocks) { - currentChunk.push(block.content); - if (currentChunk.length >= chunkSize) { - chunks.push([...currentChunk]); - currentChunk = []; - } - } - // Add the last chunk if it's not empty - if (currentChunk.length > 0) { - chunks.push(currentChunk); - } - // Create ChunkedFile objects for each chunk - chunks.forEach((chunkLines, index) => { - const chunkContent = chunkLines.join('\n'); - chunkedFiles.push(new chunked_file_1.ChunkedFile(path, index, 'block', chunkContent, shasum, chunkLines)); - }); - return chunkedFiles; - }; - this.extractCodeBlocks = (code) => { - const lines = code.split('\n'); - const blocks = []; - let currentBlock; - let braceDepth = 0; - let indentLevel = 0; - const startBlock = (type, name, line, lineNumber) => { - currentBlock = { - type, - name, - content: line + '\n', - startLine: lineNumber, - endLine: lineNumber, - }; - braceDepth = (line.match(/{/g) || []).length - (line.match(/}/g) || []).length; - indentLevel = line.match(/^(\s*)/)?.[1].length ?? 0; - }; - const endBlock = (lineNumber) => { - if (currentBlock) { - currentBlock.endLine = lineNumber; - blocks.push(currentBlock); - currentBlock = undefined; - } - }; - lines.forEach((line, idx) => { - const trimmed = line.trim(); - const lineNumber = idx + 1; - // Detect class or function headers - const functionMatch = trimmed.match(/(?:function|def|fn|async|const|let)\s+(\w+)/); - const classMatch = trimmed.match(/class\s+(\w+)/); - if (!currentBlock && functionMatch) { - startBlock('function', functionMatch[1], line, lineNumber); - } - else if (!currentBlock && classMatch) { - startBlock('class', classMatch[1], line, lineNumber); - } - else if (currentBlock) { - currentBlock.content += line + '\n'; - // Update brace depth - braceDepth += (line.match(/{/g) || []).length; - braceDepth -= (line.match(/}/g) || []).length; - // Or detect dedentation (for Python-style) - const currentIndent = line.match(/^(\s*)/)?.[1].length ?? 0; - const dedented = currentIndent < indentLevel; - if (braceDepth <= 0 && trimmed.endsWith('}') || dedented) { - endBlock(lineNumber); - } - } - }); - // Catch any unfinished block - if (currentBlock) { - currentBlock.endLine = lines.length; - blocks.push(currentBlock); - } - return blocks; - }; - this.shouldIgnoreLine = (line) => { - const trimmed = line.trim(); - return (trimmed === '' || - /^[}\]);]+;?$/.test(trimmed) || - /^import\s.+from\s.+;?$/.test(trimmed) || - /^(return|break|continue|pass);?$/.test(trimmed) || - /^\/\/[-=]*$/.test(trimmed) || // comentarios de separación - /^\/\/\s*(TODO|FIXME)?\s*$/i.test(trimmed) || - /^[\]],?;?$/.test(trimmed) || - /^try\s*{$/.test(trimmed) || - /^}\s*else\s*{$/.test(trimmed) || - /^`;?$/.test(trimmed) || - /^\/\*\*$/.test(trimmed) || - /^\*\/$/.test(trimmed)); - }; - this.getFileTree = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { - const fileContents = await this.getRepositoryContent(owner, repository, token, branch, ignoreFiles, progress, ignoredFiles); - // Create root nodes for both trees - const rootWithContent = { - name: repository, - type: 'directory', - path: '', - children: [] - }; - const rootWithoutContent = { - name: repository, - type: 'directory', - path: '', - children: [] - }; - // Process each file path to build both trees - for (const [filePath, content] of fileContents.entries()) { - const parts = filePath.split('/'); - let currentLevelWithContent = rootWithContent; - let currentLevelWithoutContent = rootWithoutContent; - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - const isLastPart = i === parts.length - 1; - const currentPath = parts.slice(0, i + 1).join('/'); - // Find or create the node in the content tree - let nodeWithContent = currentLevelWithContent.children?.find(n => n.name === part); - if (!nodeWithContent) { - nodeWithContent = { - name: part, - type: isLastPart ? 'file' : 'directory', - path: currentPath, - children: isLastPart ? undefined : [], - content: isLastPart ? content : undefined - }; - if (!currentLevelWithContent.children) { - currentLevelWithContent.children = []; - } - currentLevelWithContent.children.push(nodeWithContent); - } - // Find or create the node in the no-content tree - let nodeWithoutContent = currentLevelWithoutContent.children?.find(n => n.name === part); - if (!nodeWithoutContent) { - nodeWithoutContent = { - name: part, - type: isLastPart ? 'file' : 'directory', - path: currentPath, - children: isLastPart ? undefined : [] - }; - if (!currentLevelWithoutContent.children) { - currentLevelWithoutContent.children = []; - } - currentLevelWithoutContent.children.push(nodeWithoutContent); - } - if (!isLastPart) { - currentLevelWithContent = nodeWithContent; - currentLevelWithoutContent = nodeWithoutContent; - } - } - } - return { - withContent: rootWithContent, - withoutContent: rootWithoutContent - }; - }; - } - isMediaOrPdfFile(path) { - const mediaExtensions = [ - // Image formats - '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico', - // Audio formats - '.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', - // Video formats - '.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', - // PDF - '.pdf' - ]; - const extension = path.toLowerCase().substring(path.lastIndexOf('.')); - return mediaExtensions.includes(extension); - } - shouldIgnoreFile(filename, ignorePatterns) { - // First check for .DS_Store - if (filename.endsWith('.DS_Store')) { - return true; - } - return ignorePatterns.some(pattern => { - // Convert glob pattern to regex - const regexPattern = pattern - .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) - .replace(/\*/g, '.*') // Convert * to match anything - .replace(/\//g, '\\/'); // Escape forward slashes - // Allow pattern ending on /* to ignore also subdirectories and files inside - if (pattern.endsWith("/*")) { - return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); - } - const regex = new RegExp(`^${regexPattern}$`); - return regex.test(filename); - }); - } - shuffleArray(array) { - return [...array].sort(() => Math.random() - 0.5); - } - calculateShasum(content) { - return (0, crypto_1.createHash)('sha256').update(content).digest('hex'); + +const { webidl } = __nccwpck_require__(1744) + +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 } -exports.FileRepository = FileRepository; /***/ }), -/***/ 40057: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 9054: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueRepository = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const milestone_1 = __nccwpck_require__(52298); -class IssueRepository { - constructor() { - this.updateTitleIssueFormat = async (owner, repository, version, issueTitle, issueNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { - try { - const octokit = github.getOctokit(token); - let emoji = 'šŸ¤–'; - const branched = branchManagementAlways || labels.containsBranchedLabel; - if (labels.isHotfix && branched) { - emoji = `šŸ”„${branchManagementEmoji}`; - } - else if (labels.isRelease && branched) { - emoji = `šŸš€${branchManagementEmoji}`; - } - else if ((labels.isBugfix || labels.isBug) && branched) { - emoji = `šŸ›${branchManagementEmoji}`; - } - else if ((labels.isFeature || labels.isEnhancement) && branched) { - emoji = `✨${branchManagementEmoji}`; - } - else if ((labels.isDocs || labels.isDocumentation) && branched) { - emoji = `šŸ“${branchManagementEmoji}`; - } - else if ((labels.isChore || labels.isMaintenance) && branched) { - emoji = `šŸ”§${branchManagementEmoji}`; - } - else if (labels.isHotfix) { - emoji = 'šŸ”„'; - } - else if (labels.isRelease) { - emoji = 'šŸš€'; - } - else if ((labels.isDocs || labels.isDocumentation)) { - emoji = 'šŸ“'; - } - else if (labels.isChore || labels.isMaintenance) { - emoji = 'šŸ”§'; - } - else if (labels.isBugfix || labels.isBug) { - emoji = 'šŸ›'; - } - else if (labels.isFeature || labels.isEnhancement) { - emoji = '✨'; - } - else if (labels.isHelp) { - emoji = 'šŸ†˜'; - } - else if (labels.isQuestion) { - emoji = 'ā“'; - } - let sanitizedTitle = issueTitle - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - let formattedTitle = `${emoji} - ${sanitizedTitle}`; - if (version.length > 0) { - formattedTitle = `${emoji} - ${version} - ${sanitizedTitle}`; - } - if (formattedTitle !== issueTitle) { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - title: formattedTitle, - }); - (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); - return formattedTitle; - } - return undefined; - } - catch (error) { - core.setFailed(`Failed to check or update issue title: ${error}`); - return undefined; - } - }; - this.updateTitlePullRequestFormat = async (owner, repository, pullRequestTitle, issueTitle, issueNumber, pullRequestNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { - try { - const octokit = github.getOctokit(token); - let emoji = 'šŸ¤–'; - const branched = branchManagementAlways || labels.containsBranchedLabel; - if (labels.isHotfix && branched) { - emoji = `šŸ”„${branchManagementEmoji}`; - } - else if (labels.isRelease && branched) { - emoji = `šŸš€${branchManagementEmoji}`; - } - else if ((labels.isBugfix || labels.isBug) && branched) { - emoji = `šŸ›${branchManagementEmoji}`; - } - else if ((labels.isFeature || labels.isEnhancement) && branched) { - emoji = `✨${branchManagementEmoji}`; - } - else if ((labels.isDocs || labels.isDocumentation) && branched) { - emoji = `šŸ“${branchManagementEmoji}`; - } - else if ((labels.isChore || labels.isMaintenance) && branched) { - emoji = `šŸ”§${branchManagementEmoji}`; - } - else if (labels.isHotfix) { - emoji = 'šŸ”„'; - } - else if (labels.isRelease) { - emoji = 'šŸš€'; - } - else if (labels.isBugfix || labels.isBug) { - emoji = 'šŸ›'; - } - else if (labels.isFeature || labels.isEnhancement) { - emoji = '✨'; - } - else if (labels.isDocs || labels.isDocumentation) { - emoji = 'šŸ“'; - } - else if (labels.isChore || labels.isMaintenance) { - emoji = 'šŸ”§'; - } - else if (labels.isHelp) { - emoji = 'šŸ†˜'; - } - else if (labels.isQuestion) { - emoji = 'ā“'; - } - let sanitizedTitle = issueTitle - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 ]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - const formattedTitle = `[#${issueNumber}] ${emoji} - ${sanitizedTitle}`; - if (formattedTitle !== pullRequestTitle) { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: pullRequestNumber, - title: formattedTitle, - }); - (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); - return formattedTitle; - } - return undefined; - } - catch (error) { - core.setFailed(`Failed to check or update issue title: ${error}`); - return undefined; - } - }; - this.cleanTitle = async (owner, repository, issueTitle, issueNumber, token) => { - try { - const octokit = github.getOctokit(token); - let sanitizedTitle = issueTitle - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 ]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - if (sanitizedTitle !== issueTitle) { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - title: sanitizedTitle, - }); - (0, logger_1.logDebugInfo)(`Issue title updated to: ${sanitizedTitle}`); - return sanitizedTitle; - } - return undefined; - } - catch (error) { - core.setFailed(`Failed to check or update issue title: ${error}`); - return undefined; - } - }; - this.updateDescription = async (owner, repo, issueNumber, description, token) => { - const octokit = github.getOctokit(token); - try { - await octokit.rest.issues.update({ - owner, - repo, - issue_number: issueNumber, - body: description, - }); - } - catch (error) { - (0, logger_1.logError)(`Error updating issue description: ${error}`); - throw error; - } - }; - this.getDescription = async (owner, repo, issueNumber, token) => { - if (issueNumber === -1) { - return undefined; - } - const octokit = github.getOctokit(token); - try { - const { data: issue } = await octokit.rest.issues.get({ - owner, - repo, - issue_number: issueNumber, - }); - return issue.body ?? ''; - } - catch (error) { - (0, logger_1.logError)(`Error reading issue #${issueNumber} description: ${error}`); - return undefined; - } - }; - this.getId = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const issueQuery = ` - query($repo: String!, $owner: String!, $issueNumber: Int!) { - repository(name: $repo, owner: $owner) { - issue(number: $issueNumber) { - id - } - } - } - `; - const issueResult = await octokit.graphql(issueQuery, { - owner: owner, - repo: repository, - issueNumber, - }); - const issueId = issueResult.repository.issue.id; - (0, logger_1.logDebugInfo)(`Fetched issue ID: ${issueId}`); - return issueId; - }; - this.getMilestone = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - if (issue.milestone) { - return new milestone_1.Milestone(issue.milestone.id, issue.milestone.title, issue.milestone.description ?? ''); - } - else { - return undefined; - } - }; - this.getTitle = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - return issue.title; - } - catch (error) { - (0, logger_1.logError)(`Failed to fetch the issue title: ${error}`); - return undefined; - } - }; - this.getLabels = async (owner, repository, issueNumber, token) => { - if (issueNumber === -1) { - return []; - } - const octokit = github.getOctokit(token); - const { data: labels } = await octokit.rest.issues.listLabelsOnIssue({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - return labels.map(label => label.name); - }; - this.setLabels = async (owner, repository, issueNumber, labels, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.issues.setLabels({ - owner: owner, - repo: repository, - issue_number: issueNumber, - labels: labels, - }); - }; - this.isIssue = async (owner, repository, issueNumber, token) => { - const isPullRequest = await this.isPullRequest(owner, repository, issueNumber, token); - return !isPullRequest; - }; - this.isPullRequest = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - return !!data.pull_request; - }; - this.getHeadBranch = async (owner, repository, issueNumber, token) => { - const isPr = await this.isPullRequest(owner, repository, issueNumber, token); - if (!isPr) { - return undefined; - } - const octokit = github.getOctokit(token); - const pullRequest = await octokit.rest.pulls.get({ - owner, - repo: repository, - pull_number: issueNumber, - }); - return pullRequest.data.head.ref; - }; - this.addComment = async (owner, repository, issueNumber, comment, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.issues.createComment({ - owner: owner, - repo: repository, - issue_number: issueNumber, - body: comment, - }); - (0, logger_1.logDebugInfo)(`Comment added to Issue ${issueNumber}.`); - }; - this.updateComment = async (owner, repository, issueNumber, commentId, comment, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.issues.updateComment({ - owner: owner, - repo: repository, - comment_id: commentId, - body: comment, - }); - (0, logger_1.logDebugInfo)(`Comment ${commentId} updated in Issue ${issueNumber}.`); - }; - this.closeIssue = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); - if (issue.state === 'open') { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - state: 'closed', - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been closed.`); - return true; - } - else { - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already closed.`); - return false; - } - }; - this.openIssue = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); - if (issue.state === 'closed') { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - state: 'open', - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been re-opened.`); - return true; - } - else { - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already opened.`); - return false; - } - }; - this.getCurrentAssignees = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data: issue } = await octokit.rest.issues.get({ - owner, - repo: repository, - issue_number: issueNumber, - }); - const assignees = issue.assignees; - if (assignees === undefined || assignees === null) { - return []; - } - return assignees.map((assignee) => assignee.login); - } - catch (error) { - (0, logger_1.logError)(`Error getting members of issue: ${error}.`); - return []; - } - }; - this.assignMembersToIssue = async (owner, repository, issueNumber, members, token) => { - const octokit = github.getOctokit(token); - try { - if (members.length === 0) { - (0, logger_1.logDebugInfo)(`No members provided for assignment. Skipping operation.`); - return []; - } - const { data: updatedIssue } = await octokit.rest.issues.addAssignees({ - owner, - repo: repository, - issue_number: issueNumber, - assignees: members, - }); - const updatedAssignees = updatedIssue.assignees || []; - return updatedAssignees.map((assignee) => assignee.login); - } - catch (error) { - (0, logger_1.logError)(`Error assigning members to issue: ${error}.`); - return []; - } - }; - this.getIssueDescription = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner, - repo: repository, - issue_number: issueNumber, - }); - return issue.body ?? ''; - }; - this.setIssueType = async (owner, repository, issueNumber, labels, issueTypes, token) => { + +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') +} + + +/***/ }), + +/***/ 7530: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = __nccwpck_require__(9054) +const { ProgressEvent } = __nccwpck_require__(5504) +const { getEncoding } = __nccwpck_require__(4854) +const { DOMException } = __nccwpck_require__(1037) +const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(685) +const { types } = __nccwpck_require__(3837) +const { StringDecoder } = __nccwpck_require__(1576) +const { btoa } = __nccwpck_require__(4300) + +/** @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 { - let issueType = issueTypes.task; - let issueTypeDescription = issueTypes.taskDescription; - let issueTypeColor = issueTypes.taskColor; - if (labels.isHotfix) { - issueType = issueTypes.hotfix; - issueTypeDescription = issueTypes.hotfixDescription; - issueTypeColor = issueTypes.hotfixColor; - } - else if (labels.isRelease) { - issueType = issueTypes.release; - issueTypeDescription = issueTypes.releaseDescription; - issueTypeColor = issueTypes.releaseColor; - } - else if ((labels.isDocs || labels.isDocumentation)) { - issueType = issueTypes.documentation; - issueTypeDescription = issueTypes.documentationDescription; - issueTypeColor = issueTypes.documentationColor; - } - else if (labels.isChore || labels.isMaintenance) { - issueType = issueTypes.maintenance; - issueTypeDescription = issueTypes.maintenanceDescription; - issueTypeColor = issueTypes.maintenanceColor; - } - else if (labels.isBugfix || labels.isBug) { - issueType = issueTypes.bug; - issueTypeDescription = issueTypes.bugDescription; - issueTypeColor = issueTypes.bugColor; - } - else if (labels.isFeature || labels.isEnhancement) { - issueType = issueTypes.feature; - issueTypeDescription = issueTypes.featureDescription; - issueTypeColor = issueTypes.featureColor; - } - else if (labels.isHelp) { - issueType = issueTypes.help; - issueTypeDescription = issueTypes.helpDescription; - issueTypeColor = issueTypes.helpColor; - } - else if (labels.isQuestion) { - issueType = issueTypes.question; - issueTypeDescription = issueTypes.questionDescription; - issueTypeColor = issueTypes.questionColor; - } - const octokit = github.getOctokit(token); - (0, logger_1.logDebugInfo)(`Setting issue type for issue ${issueNumber} to ${issueType}`); - (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); - (0, logger_1.logDebugInfo)(`Issue Type: ${issueType}`); - (0, logger_1.logDebugInfo)(`Issue Type Description: ${issueTypeDescription}`); - (0, logger_1.logDebugInfo)(`Issue Type Color: ${issueTypeColor}`); - // Try to update the issue with the issue type using GraphQL - const issueId = await this.getId(owner, repository, issueNumber, token); - // First, try to find existing issue types in the organization - const { organization } = await octokit.graphql(` - query ($owner: String!) { - organization(login: $owner) { - id - issueTypes(first: 20) { - nodes { - id - name - } - } - } - } - `, { owner }); - (0, logger_1.logDebugInfo)(`Organization ID: ${organization.id}`); - (0, logger_1.logDebugInfo)(`Organization issue types: ${JSON.stringify(organization.issueTypes.nodes)}`); - // Check if the issue type already exists - const existingType = organization.issueTypes.nodes.find((type) => type.name.toLowerCase() === issueType.toLowerCase()); - let issueTypeId; - if (existingType) { - issueTypeId = existingType.id; - (0, logger_1.logDebugInfo)(`Found existing issue type "${issueType}" with ID: ${issueTypeId}`); - } - else { - // Try to create the issue type using GraphQL - try { - (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); - const createResult = await octokit.graphql(` - mutation ($ownerId: ID!, $name: String!, $description: String!, $color: IssueTypeColor!, $isEnabled: Boolean!) { - createIssueType(input: { - ownerId: $ownerId, - name: $name, - description: $description, - color: $color, - isEnabled: $isEnabled - }) { - issueType { - id - } - } - } - `, { - ownerId: organization.id, - name: issueType, - description: issueTypeDescription, - color: issueTypeColor.toUpperCase(), - isEnabled: true, - }); - issueTypeId = createResult.createIssueType.issueType.id; - (0, logger_1.logDebugInfo)(`Created new issue type "${issueType}" with ID: ${issueTypeId}`); - } - catch (createError) { - (0, logger_1.logError)(`Failed to create issue type "${issueType}": ${createError}`); - // If creation fails, we'll fall back to using labels - (0, logger_1.logDebugInfo)(`Falling back to using labels for issue type classification`); - return; - } - } - // Update the issue with the issue type using GraphQL - await octokit.graphql(` - mutation ($issueId: ID!, $issueTypeId: ID!) { - updateIssueIssueType(input: { - issueId: $issueId, - issueTypeId: $issueTypeId - }) { - issue { - id - issueType { - id - name - } - } - } - } - `, { - issueId, - issueTypeId, - }); - (0, logger_1.logDebugInfo)(`Successfully updated issue type to ${issueType}`); + 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) } - catch (error) { - (0, logger_1.logError)(`Failed to update issue type: ${error}`); - // Don't throw the error to prevent breaking the main flow - // The issue will still be processed with labels - (0, logger_1.logDebugInfo)(`Continuing with issue processing despite issue type update failure`); - throw error; + + // 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 +} + + +/***/ }), + +/***/ 1892: +/***/ ((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__(8045) +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 +} + + +/***/ }), + +/***/ 6930: +/***/ ((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) + } +} + + +/***/ }), + +/***/ 2860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const util = __nccwpck_require__(3983) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const EE = __nccwpck_require__(2361) + +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) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false +} + +// 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 + + +/***/ }), + +/***/ 2286: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const assert = __nccwpck_require__(9491) + +const { kRetryHandlerDefaultRetry } = __nccwpck_require__(2785) +const { RequestRetryError } = __nccwpck_require__(8045) +const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3983) + +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 + + +/***/ }), + +/***/ 8861: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const RedirectHandler = __nccwpck_require__(2860) + +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 + + +/***/ }), + +/***/ 953: +/***/ ((__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__(1891); +// 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 + +/***/ }), + +/***/ 1145: +/***/ ((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=' + + +/***/ }), + +/***/ 5627: +/***/ ((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==' + + +/***/ }), + +/***/ 1891: +/***/ ((__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 + +/***/ }), + +/***/ 6771: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kClients } = __nccwpck_require__(2785) +const Agent = __nccwpck_require__(7890) +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = __nccwpck_require__(4347) +const MockClient = __nccwpck_require__(8687) +const MockPool = __nccwpck_require__(6193) +const { matchValue, buildMockOptions } = __nccwpck_require__(9323) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8045) +const Dispatcher = __nccwpck_require__(412) +const Pluralizer = __nccwpck_require__(8891) +const PendingInterceptorsFormatter = __nccwpck_require__(6823) + +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 + + +/***/ }), + +/***/ 8687: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { promisify } = __nccwpck_require__(3837) +const Client = __nccwpck_require__(3598) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) + +/** + * 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 + + +/***/ }), + +/***/ 888: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { UndiciError } = __nccwpck_require__(8045) + +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 +} + + +/***/ }), + +/***/ 410: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = __nccwpck_require__(4347) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { buildURL } = __nccwpck_require__(3983) + +/** + * 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 + + +/***/ }), + +/***/ 6193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { promisify } = __nccwpck_require__(3837) +const Pool = __nccwpck_require__(4634) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) + +/** + * 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 + + +/***/ }), + +/***/ 4347: +/***/ ((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') +} + + +/***/ }), + +/***/ 9323: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { MockNotMatchedError } = __nccwpck_require__(888) +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = __nccwpck_require__(4347) +const { buildURL, nop } = __nccwpck_require__(3983) +const { STATUS_CODES } = __nccwpck_require__(3685) +const { + types: { + isPromise + } +} = __nccwpck_require__(3837) + +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 +} + + +/***/ }), + +/***/ 6823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Transform } = __nccwpck_require__(2781) +const { Console } = __nccwpck_require__(6206) + +/** + * 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() + } +} + + +/***/ }), + +/***/ 8891: +/***/ ((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 } + } +} + + +/***/ }), + +/***/ 8266: +/***/ ((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; + } } -exports.IssueRepository = IssueRepository; + +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; + } +}; /***/ }), -/***/ 67917: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 3198: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + +const DispatcherBase = __nccwpck_require__(4839) +const FixedQueue = __nccwpck_require__(8266) +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(2785) +const PoolStats = __nccwpck_require__(9689) + +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]) + } } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProjectRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const project_detail_1 = __nccwpck_require__(93765); -class ProjectRepository { - constructor() { - this.priorityLabel = "Priority"; - this.sizeLabel = "Size"; - this.statusLabel = "Status"; - /** - * Retrieves detailed information about a GitHub project - * @param projectId - The project number/ID - * @param token - GitHub authentication token - * @returns Promise - The project details - * @throws {Error} If the project is not found or if there are authentication/network issues - */ - this.getProjectDetail = async (projectId, token) => { - try { - // Validate projectId is a valid number - const projectNumber = parseInt(projectId, 10); - if (isNaN(projectNumber)) { - throw new Error(`Invalid project ID: ${projectId}. Must be a valid number.`); - } - const octokit = github.getOctokit(token); - const { data: owner } = await octokit.rest.users.getByUsername({ - username: github.context.repo.owner - }).catch(error => { - throw new Error(`Failed to get owner information: ${error.message}`); - }); - const ownerType = owner.type === 'Organization' ? 'orgs' : 'users'; - const projectUrl = `https://github.com/${ownerType}/${github.context.repo.owner}/projects/${projectId}`; - const ownerQueryField = ownerType === 'orgs' ? 'organization' : 'user'; - const queryProject = ` - query($ownerName: String!, $projectNumber: Int!) { - ${ownerQueryField}(login: $ownerName) { - projectV2(number: $projectNumber) { - id - title - url - } - } - } - `; - const projectResult = await octokit.graphql(queryProject, { - ownerName: github.context.repo.owner, - projectNumber: projectNumber, - }).catch(error => { - throw new Error(`Failed to fetch project data: ${error.message}`); - }); - const projectData = projectResult[ownerQueryField]?.projectV2; - if (!projectData) { - throw new Error(`Project not found: ${projectUrl}`); - } - (0, logger_1.logDebugInfo)(`Project ID: ${projectData.id}`); - (0, logger_1.logDebugInfo)(`Project Title: ${projectData.title}`); - (0, logger_1.logDebugInfo)(`Project URL: ${projectData.url}`); - return new project_detail_1.ProjectDetail({ - id: projectData.id, - title: projectData.title, - url: projectData.url, - type: ownerQueryField, - owner: github.context.repo.owner, - number: projectNumber, - }); - } - catch (error) { - const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; - (0, logger_1.logError)(`Error in getProjectDetail: ${errorMessage}`); - throw error; - } - }; - this.getContentId = async (project, owner, repo, issueOrPullRequestNumber, token) => { - const octokit = github.getOctokit(token); - // Search for the issue or pull request ID in the repository - const issueOrPrQuery = ` - query($owner: String!, $repo: String!, $number: Int!) { - repository(owner: $owner, name: $repo) { - issueOrPullRequest: issueOrPullRequest(number: $number) { - ... on Issue { - id - } - ... on PullRequest { - id - } - } + + 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]) } - }`; - const issueOrPrResult = await octokit.graphql(issueOrPrQuery, { - owner, - repo, - number: issueOrPullRequestNumber - }); - if (!issueOrPrResult.repository.issueOrPullRequest) { - console.error(`Issue or PR #${issueOrPullRequestNumber} not found.`); - return undefined; - } - const contentId = issueOrPrResult.repository.issueOrPullRequest.id; - // Search for the item ID in the project with pagination - let cursor = null; - let projectItemId = undefined; - do { - const projectQuery = ` - query($projectId: ID!, $cursor: String) { - node(id: $projectId) { - ... on ProjectV2 { - items(first: 100, after: $cursor) { - pageInfo { - hasNextPage - endCursor - } - nodes { - id - content { - ... on Issue { - id - } - ... on PullRequest { - id - } - } - } - } - } - } - }`; - const projectResult = await octokit.graphql(projectQuery, { - projectId: project.id, - cursor - }); - const items = projectResult.node.items.nodes; - const foundItem = items.find((item) => item.content?.id === contentId); - if (foundItem) { - projectItemId = foundItem.id; - break; - } - cursor = projectResult.node.items.pageInfo.hasNextPage - ? projectResult.node.items.pageInfo.endCursor - : null; - } while (cursor); - return projectItemId; - }; - this.isContentLinked = async (project, contentId, token) => { - const octokit = github.getOctokit(token); - let hasNextPage = true; - let endCursor = null; - let allItems = []; - while (hasNextPage) { - const query = ` - query($projectId: ID!, $after: String) { - node(id: $projectId) { - ... on ProjectV2 { - items(first: 100, after: $after) { - nodes { - content { - ... on PullRequest { - id - } - ... on Issue { - id - } - } - } - pageInfo { - hasNextPage - endCursor - } - } + }) + } + + 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 +} + + +/***/ }), + +/***/ 9689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(2785) +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__(3198) +const Client = __nccwpck_require__(3598) +const { + InvalidArgumentError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const buildConnector = __nccwpck_require__(2067) + +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 + + this.on('connectionError', (origin, targets, error) => { + // If a connection error occurs, we remove the client from the pool, + // and emit a connectionError event. They will not be re-used. + // Fixes https://github.com/nodejs/undici/issues/3895 + for (const target of targets) { + // Do not use kRemoveClient here, as it will close the client, + // but the client cannot be closed in this state. + const idx = this[kClients].indexOf(target) + if (idx !== -1) { + this[kClients].splice(idx, 1) } } + }) + } + + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher } - `; - // logDebugInfo(`Query: ${query}`); - // logDebugInfo(`Project ID: ${project.id}`); - // logDebugInfo(`Content ID: ${contentId}`); - // logDebugInfo(`After cursor: ${endCursor}`); - const result = await octokit.graphql(query, { - projectId: project.id, - after: endCursor, - }); - // logDebugInfo(`Result: ${JSON.stringify(result, null, 2)}`); - const items = result.node.items.nodes; - allItems = allItems.concat(items); - hasNextPage = result.node.items.pageInfo.hasNextPage; - endCursor = result.node.items.pageInfo.endCursor; - } - return allItems.some((item) => item.content && item.content.id === contentId); - }; - this.linkContentId = async (project, contentId, token) => { - const alreadyLinked = await this.isContentLinked(project, contentId, token); - if (alreadyLinked) { - (0, logger_1.logDebugInfo)(`Content ${contentId} is already linked to project ${project.id}.`); - return false; - } - const octokit = github.getOctokit(token); - const linkMutation = ` - mutation($projectId: ID!, $contentId: ID!) { - addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) { - item { - id - } - } - } - `; - const linkResult = await octokit.graphql(linkMutation, { - projectId: project.id, - contentId: contentId, - }); - (0, logger_1.logDebugInfo)(`Linked ${contentId} with id ${linkResult.addProjectV2ItemById.item.id} to project ${project.id}`); - return true; - }; - this.setSingleSelectFieldValue = async (project, owner, repo, issueOrPullRequestNumber, fieldName, fieldValue, token) => { - const contentId = await this.getContentId(project, owner, repo, issueOrPullRequestNumber, token); - if (!contentId) { - (0, logger_1.logError)(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); - throw new Error(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); - } - (0, logger_1.logDebugInfo)(`Content ID: ${contentId}`); - const octokit = github.getOctokit(token); - // Get the field ID and current value - const fieldQuery = ` - query($projectId: ID!, $after: String) { - node(id: $projectId) { - ... on ProjectV2 { - fields(first: 20) { - nodes { - ... on ProjectV2SingleSelectField { - id - name - options { - id - name - } - } - } - } - items(first: 100, after: $after) { - pageInfo { - hasNextPage - endCursor - } - nodes { - id - fieldValues(first: 20) { - nodes { - ... on ProjectV2ItemFieldSingleSelectValue { - field { - ... on ProjectV2SingleSelectField { - name - } - } - optionId - } - } - } - } - } - } - } - }`; - let hasNextPage = true; - let endCursor = null; - let currentItem = null; - // Get the field and option information from the first page - const initialFieldResult = await octokit.graphql(fieldQuery, { - projectId: project.id, - after: null - }); - const targetField = initialFieldResult.node.fields.nodes.find((f) => f.name === fieldName); - (0, logger_1.logDebugInfo)(`Target field: ${JSON.stringify(targetField, null, 2)}`); - if (!targetField) { - (0, logger_1.logError)(`Field '${fieldName}' not found or is not a single-select field.`); - throw new Error(`Field '${fieldName}' not found or is not a single-select field.`); - } - const targetOption = targetField.options.find((opt) => opt.name === fieldValue); - (0, logger_1.logDebugInfo)(`Target option: ${JSON.stringify(targetOption, null, 2)}`); - if (!targetOption) { - (0, logger_1.logError)(`Option '${fieldValue}' not found for field '${fieldName}'.`); - throw new Error(`Option '${fieldValue}' not found for field '${fieldName}'.`); - } - // Now search for the item through all pages - while (hasNextPage) { - const fieldResult = await octokit.graphql(fieldQuery, { - projectId: project.id, - after: endCursor - }); - // logDebugInfo(`Field result: ${JSON.stringify(fieldResult, null, 2)}`); - // Check current value in current page - currentItem = fieldResult.node.items.nodes.find((item) => item.id === contentId); - if (currentItem) { - // logDebugInfo(`Current item: ${JSON.stringify(currentItem, null, 2)}`); - const currentFieldValue = currentItem.fieldValues.nodes.find((value) => value.field?.name === fieldName); - if (currentFieldValue && currentFieldValue.optionId === targetOption.id) { - (0, logger_1.logDebugInfo)(`Field '${fieldName}' is already set to '${fieldValue}'. No update needed.`); - return false; - } - break; // Found the item, no need to continue pagination - } - hasNextPage = fieldResult.node.items.pageInfo.hasNextPage; - endCursor = fieldResult.node.items.pageInfo.endCursor; - } - (0, logger_1.logDebugInfo)(`Target field ID: ${targetField.id}`); - (0, logger_1.logDebugInfo)(`Target option ID: ${targetOption.id}`); - const mutation = ` - mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { - updateProjectV2ItemFieldValue( - input: { - projectId: $projectId, - itemId: $itemId, - fieldId: $fieldId, - value: { singleSelectOptionId: $optionId } - } - ) { - projectV2Item { - id - } - } - }`; - const mutationResult = await octokit.graphql(mutation, { - projectId: project.id, - itemId: contentId, - fieldId: targetField.id, - optionId: targetOption.id - }); - return !!mutationResult.updateProjectV2ItemFieldValue.projectV2Item; - }; - this.setTaskPriority = async (project, owner, repo, issueOrPullRequestNumber, priorityLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.priorityLabel, priorityLabel, token); - this.setTaskSize = async (project, owner, repo, issueOrPullRequestNumber, sizeLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.sizeLabel, sizeLabel, token); - this.moveIssueToColumn = async (project, owner, repo, issueOrPullRequestNumber, columnName, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.statusLabel, columnName, token); - this.getRandomMembers = async (organization, membersToAdd, currentMembers, token) => { - if (membersToAdd === 0) { - return []; - } - const octokit = github.getOctokit(token); - try { - const { data: teams } = await octokit.rest.teams.list({ - org: organization, - }); - if (teams.length === 0) { - (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); - return []; - } - const membersSet = new Set(); - for (const team of teams) { - (0, logger_1.logDebugInfo)(`Checking team: ${team.slug}`); - const { data: members } = await octokit.rest.teams.listMembersInOrg({ - org: organization, - team_slug: team.slug, - }); - (0, logger_1.logDebugInfo)(`Members: ${members.length}`); - members.forEach((member) => membersSet.add(member.login)); - } - const allMembers = Array.from(membersSet); - const availableMembers = allMembers.filter((member) => !currentMembers.includes(member)); - if (availableMembers.length === 0) { - (0, logger_1.logDebugInfo)(`No available members to assign for organization ${organization}.`); - return []; - } - if (membersToAdd >= availableMembers.length) { - (0, logger_1.logDebugInfo)(`Requested size (${membersToAdd}) exceeds available members (${availableMembers.length}). Returning all available members.`); - return availableMembers; - } - const shuffled = availableMembers.sort(() => Math.random() - 0.5); - return shuffled.slice(0, membersToAdd); - } - catch (error) { - (0, logger_1.logError)(`Error getting random members: ${error}.`); - } - return []; - }; - this.getAllMembers = async (organization, token) => { - const octokit = github.getOctokit(token); - try { - const { data: teams } = await octokit.rest.teams.list({ - org: organization, - }); - if (teams.length === 0) { - (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); - return []; - } - const membersSet = new Set(); - for (const team of teams) { - const { data: members } = await octokit.rest.teams.listMembersInOrg({ - org: organization, - team_slug: team.slug, - }); - members.forEach((member) => membersSet.add(member.login)); - } - return Array.from(membersSet); - } - catch (error) { - (0, logger_1.logError)(`Error getting all members: ${error}.`); - } - return []; - }; - this.getUserFromToken = async (token) => { - const octokit = github.getOctokit(token); - const { data: user } = await octokit.rest.users.getAuthenticated(); - return user.login; - }; - this.findTag = async (owner, repo, tag, token) => { - const octokit = github.getOctokit(token); - try { - const { data: foundTag } = await octokit.rest.git.getRef({ - owner, - repo, - ref: `tags/${tag}`, - }); - return foundTag; - } - catch (err) { - return undefined; - } - }; - this.getTagSHA = async (owner, repo, tag, token) => { - const foundTag = await this.findTag(owner, repo, tag, token); - if (!foundTag) { - (0, logger_1.logError)(`The '${tag}' tag does not exist in the remote repository`); - return undefined; - } - return foundTag.object.sha; - }; - this.updateTag = async (owner, repo, sourceTag, targetTag, token) => { - const sourceTagSHA = await this.getTagSHA(owner, repo, sourceTag, token); - if (!sourceTagSHA) { - (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); - return; - } - const foundTargetTag = await this.findTag(owner, repo, targetTag, token); - const refName = `tags/${targetTag}`; - const octokit = github.getOctokit(token); - if (foundTargetTag) { - (0, logger_1.logDebugInfo)(`Updating the '${targetTag}' tag to point to the '${sourceTag}' tag`); - await octokit.rest.git.updateRef({ - owner, - repo, - ref: refName, - sha: sourceTagSHA, - force: true, - }); - } - else { - (0, logger_1.logDebugInfo)(`Creating the '${targetTag}' tag from the '${sourceTag}' tag`); - await octokit.rest.git.createRef({ - owner, - repo, - ref: `refs/${refName}`, - sha: sourceTagSHA, - }); - } - }; - this.updateRelease = async (owner, repo, sourceTag, targetTag, token) => { - // Get the release associated with sourceTag - const octokit = github.getOctokit(token); - const { data: sourceRelease } = await octokit.rest.repos.getReleaseByTag({ - owner, - repo, - tag: sourceTag, - }); - if (!sourceRelease.name || !sourceRelease.body) { - (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); - return undefined; - } - (0, logger_1.logDebugInfo)(`Found release for sourceTag '${sourceTag}': ${sourceRelease.name}`); - // Check if there is a release for targetTag - const { data: releases } = await octokit.rest.repos.listReleases({ - owner, - repo, - }); - const targetRelease = releases.find(r => r.tag_name === targetTag); - let targetReleaseId; - if (targetRelease) { - (0, logger_1.logDebugInfo)(`Updating release for targetTag '${targetTag}'`); - // Update the target release with the content from the source release - await octokit.rest.repos.updateRelease({ - owner, - repo, - release_id: targetRelease.id, - name: sourceRelease.name, - body: sourceRelease.body, - draft: sourceRelease.draft, - prerelease: sourceRelease.prerelease, - }); - targetReleaseId = targetRelease.id; - } - else { - console.log(`Creating new release for targetTag '${targetTag}'`); - // Create a new release for targetTag if it doesn't exist - const { data: newRelease } = await octokit.rest.repos.createRelease({ - owner, - repo, - tag_name: targetTag, - name: sourceRelease.name, - body: sourceRelease.body, - draft: sourceRelease.draft, - prerelease: sourceRelease.prerelease, - }); - targetReleaseId = newRelease.id; - } - (0, logger_1.logInfo)(`Updated release for targetTag '${targetTag}'`); - return targetReleaseId.toString(); - }; - this.createRelease = async (owner, repo, version, title, changelog, token) => { - try { - const octokit = github.getOctokit(token); - const { data: release } = await octokit.rest.repos.createRelease({ - owner, - repo, - tag_name: `v${version}`, - name: `v${version} - ${title}`, - body: changelog, - draft: false, - prerelease: false, - }); - return release.html_url; - } - catch (error) { - (0, logger_1.logError)(`Error creating release: ${error}`); - return undefined; - } - }; - this.createTag = async (owner, repo, branch, tag, token) => { - const octokit = github.getOctokit(token); - try { - // Check if tag already exists - const existingTag = await this.findTag(owner, repo, tag, token); - if (existingTag) { - (0, logger_1.logInfo)(`Tag '${tag}' already exists in repository ${owner}/${repo}`); - return existingTag.object.sha; - } - // Get the latest commit SHA from the specified branch - const { data: ref } = await octokit.rest.git.getRef({ - owner, - repo, - ref: `heads/${branch}`, - }); - // Create the tag - await octokit.rest.git.createRef({ - owner, - repo, - ref: `refs/tags/${tag}`, - sha: ref.object.sha, - }); - (0, logger_1.logInfo)(`Created tag '${tag}' in repository ${owner}/${repo} from branch '${branch}'`); - return ref.object.sha; - } - catch (error) { - (0, logger_1.logError)(`Error creating tag '${tag}': ${JSON.stringify(error, null, 2)}`); - return undefined; + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher + } +} + +module.exports = Pool + + +/***/ }), + +/***/ 7858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(2785) +const { URL } = __nccwpck_require__(7310) +const Agent = __nccwpck_require__(7890) +const Pool = __nccwpck_require__(4634) +const DispatcherBase = __nccwpck_require__(4839) +const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) + +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') + } } -exports.ProjectRepository = ProjectRepository; + +module.exports = ProxyAgent /***/ }), -/***/ 20634: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 9459: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + +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) } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequestRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -class PullRequestRepository { - constructor() { - this.isLinked = async (pullRequestUrl) => { - const htmlContent = await fetch(pullRequestUrl).then(res => res.text()); - return !htmlContent.includes('has_github_issues=false'); - }; - this.updateBaseBranch = async (owner, repository, pullRequestNumber, branch, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.pulls.update({ - owner: owner, - repo: repository, - pull_number: pullRequestNumber, - base: branch, - }); - (0, logger_1.logDebugInfo)(`Changed base branch to ${branch}`); - }; - this.updateDescription = async (owner, repository, pullRequestNumber, description, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.pulls.update({ - owner: owner, - repo: repository, - pull_number: pullRequestNumber, - body: description, - }); - (0, logger_1.logDebugInfo)(`Updated PR #${pullRequestNumber} description with: ${description}`); - }; - this.getCurrentReviewers = async (owner, repository, pullNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data } = await octokit.rest.pulls.listRequestedReviewers({ - owner, - repo: repository, - pull_number: pullNumber, - }); - return data.users.map((user) => user.login); - } - catch (error) { - (0, logger_1.logError)(`Error getting reviewers of PR: ${error}.`); - return []; - } - }; - this.addReviewersToPullRequest = async (owner, repository, pullNumber, reviewers, token) => { - const octokit = github.getOctokit(token); - try { - if (reviewers.length === 0) { - (0, logger_1.logDebugInfo)(`No reviewers provided for addition. Skipping operation.`); - return []; - } - const { data } = await octokit.rest.pulls.requestReviewers({ - owner, - repo: repository, - pull_number: pullNumber, - reviewers: reviewers, - }); - const addedReviewers = data.requested_reviewers || []; - return addedReviewers.map((reviewer) => reviewer.login); - } - catch (error) { - (0, logger_1.logError)(`Error adding reviewers to pull request: ${error}.`); - return []; - } - }; - this.getChangedFiles = async (owner, repository, pullNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data } = await octokit.rest.pulls.listFiles({ - owner, - repo: repository, - pull_number: pullNumber, - }); - return data.map((file) => ({ - filename: file.filename, - status: file.status - })); - } - catch (error) { - (0, logger_1.logError)(`Error getting changed files from pull request: ${error}.`); - return []; - } - }; - this.getPullRequestChanges = async (owner, repository, pullNumber, token) => { - const octokit = github.getOctokit(token); - const allFiles = []; - try { - for await (const response of octokit.paginate.iterator(octokit.rest.pulls.listFiles, { - owner, - repo: repository, - pull_number: pullNumber, - per_page: 100 - })) { - const filesData = response.data; - allFiles.push(...filesData.map((file) => ({ - filename: file.filename, - status: file.status, - additions: file.additions, - deletions: file.deletions, - patch: file.patch || '' - }))); - } - return allFiles; - } - catch (error) { - (0, logger_1.logError)(`Error getting pull request changes: ${error}.`); - return []; - } - }; + + 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) + } + } +} + + +/***/ }), + +/***/ 5354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const diagnosticsChannel = __nccwpck_require__(7643) +const { uid, states } = __nccwpck_require__(9188) +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = __nccwpck_require__(7578) +const { fireEvent, failWebsocketConnection } = __nccwpck_require__(5515) +const { CloseEvent } = __nccwpck_require__(2611) +const { makeRequest } = __nccwpck_require__(8359) +const { fetching } = __nccwpck_require__(4881) +const { Headers } = __nccwpck_require__(554) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { kHeadersList } = __nccwpck_require__(2785) + +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 } -exports.PullRequestRepository = PullRequestRepository; +/** + * @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 -/***/ 79829: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 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] -"use strict"; + let code = 1005 + let reason = '' -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SupabaseRepository = void 0; -const supabase_js_1 = __nccwpck_require__(91206); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -const chunked_file_chunk_1 = __nccwpck_require__(64370); -class SupabaseRepository { - constructor(config) { - this.CHUNKS_TABLE = 'chunks'; - this.MAX_BATCH_SIZE = 500; - this.DEFAULT_TIMEOUT = 30000; // 30 seconds - this.setChunkedFile = async (owner, repository, branch, chunkedFile) => { - try { - const insertPromises = chunkedFile.chunks.map(async (chunk, index) => { - const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .insert({ - owner, - repository, - branch, - path: chunkedFile.path, - type: chunkedFile.type, - index: chunkedFile.index, - chunk_index: index, - content: chunk, - shasum: chunkedFile.shasum, - vector: chunkedFile.vector[index], - updated_at: new Date().toISOString() - }); - if (error) { - chunkedFile.vector = []; - (0, logger_1.logError)(`Error inserting index ${chunkedFile.index} chunk ${index} for file ${chunkedFile.path}: ${JSON.stringify(chunkedFile, null, 2)}`); - (0, logger_1.logError)(`Inserting error: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }); - await Promise.all(insertPromises); - } - catch (error) { - (0, logger_1.logError)(`Error setting chunked file ${chunkedFile.path}: ${JSON.stringify(error, null, 2)}`); - // throw error; - } - }; - this.removeChunksByShasum = async (owner, repository, branch, shasum) => { - try { - const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .delete() - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('shasum', shasum); - if (error) { - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error removing chunks by shasum: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getChunkedFileByShasum = async (owner, repository, branch, type, shasum) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('type', type) - .eq('shasum', shasum) - .order('chunk_index'); - if (error) { - (0, logger_1.logError)(`Supabase error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - if (!data) { - return []; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.content, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - }; - this.getChunks = async (owner, repository, branch, path, type, index) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('path', path) - .eq('type', type) - .eq('index', index) - .order('chunk_index'); - if (error) { - (0, logger_1.logError)(`Supabase error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - if (!data) { - return []; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.chunk, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - }; - this.getChunksByShasum = async (owner, repository, branch, shasum) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('shasum', shasum) - .order('chunk_index'); - if (error) { - throw error; - } - if (!data) { - return []; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.chunk, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.updateVector = async (owner, repository, branch, path, index, chunkIndex, vector) => { - try { - const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .update({ vector }) - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('path', path) - .eq('index', index) - .eq('chunk_index', chunkIndex); - if (error) { - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error updating vector: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.matchChunks = async (owner, repository, branch, type, queryEmbedding, matchCount = 5) => { - try { - const { data, error } = await this.supabase - .rpc('match_chunks', { - owner_param: owner, - repository_param: repository, - branch_param: branch, - type_param: type, - query_embedding: queryEmbedding, - match_count: matchCount - }); - if (error) { - (0, logger_1.logError)(`Error matching chunks: ${JSON.stringify(error, null, 2)}`); - throw error; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.content, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error matching chunks: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.duplicateChunksByBranch = async (owner, repository, sourceBranch, targetBranch) => { - const count = await this.countBranchEntries(owner, repository, sourceBranch); - (0, logger_1.logDebugInfo)(`Counting chunks in branch ${sourceBranch}: ${count}`); - if (count < 10000) { - await this.duplicateBranchEntries(owner, repository, sourceBranch, targetBranch); - } - else { - const filePaths = await this.getDistinctPaths(owner, repository, sourceBranch); - (0, logger_1.logDebugInfo)(`Counting files in branch ${sourceBranch}: ${filePaths.length}`); - for (const path of filePaths) { - await this.duplicateFileEntries(owner, repository, sourceBranch, path, targetBranch); - } - } - }; - this.removeChunksByBranch = async (owner, repository, branch) => { - const count = await this.countBranchEntries(owner, repository, branch); - (0, logger_1.logDebugInfo)(`Counting chunks in branch ${branch}: ${count}`); - if (count < 10000) { - await this.deleteBranchEntries(owner, repository, branch); - } - else { - const filePaths = await this.getDistinctPaths(owner, repository, branch); - (0, logger_1.logDebugInfo)(`Counting files in branch ${branch}: ${filePaths.length}`); - for (const path of filePaths) { - await this.removeChunksByPath(owner, repository, branch, path); - } - } - (0, logger_1.logDebugInfo)(`Checking if all chunks are deleted from branch ${branch}`); - // Retry logic to ensure all chunks are deleted - const maxRetries = 5; - const retryDelay = 10000; // 1 second - let retryCount = 0; - while (retryCount < maxRetries) { - const { data: chunks, error: chunksError } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch); - if (chunksError) { - (0, logger_1.logError)(`Error checking chunks by branch: ${JSON.stringify(chunksError, null, 2)}`); - throw chunksError; - } - if (!chunks || chunks.length === 0) { - // No chunks found, deletion successful - (0, logger_1.logDebugInfo)(`Removed all chunks from branch ${branch}`); - return; - } - retryCount++; - if (retryCount < maxRetries) { - (0, logger_1.logDebugInfo)(`Chunks still present for branch ${branch}, retrying in ${retryDelay}ms (attempt ${retryCount}/${maxRetries})`); - await new Promise(resolve => setTimeout(resolve, retryDelay)); - } - } - // If we reach here, we've exhausted all retries and chunks still exist - (0, logger_1.logError)(`There are still chunks left for this branch after ${maxRetries} attempts: ${branch}`); - throw new Error(`There are still chunks left for this branch after ${maxRetries} attempts: ${branch}`); - }; - this.getDistinctPaths = async (owner, repository, branch) => { - try { - const { data, error } = await this.supabase - .rpc('get_distinct_paths', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - if (error) { - (0, logger_1.logError)(`Error getting distinct paths for ${owner}/${repository}/${branch}: ${JSON.stringify(error, null, 2)}`); - return []; - } - if (!data) { - (0, logger_1.logInfo)(`No data found for ${owner}/${repository}/${branch}`); - return []; - } - const paths = data.map((doc) => doc.path); - return paths; - } - catch (error) { - (0, logger_1.logError)(`Unexpected error getting distinct paths for ${owner}/${repository}/${branch}: ${JSON.stringify(error, null, 2)}`); - if (error instanceof Error) { - (0, logger_1.logError)(`Error details: ${error.message}`); - (0, logger_1.logError)(`Error stack: ${error.stack}`); - } - return []; - } - }; - this.removeChunksByPath = async (owner, repository, branch, path) => { - const { error } = await this.supabase - .rpc('delete_branch_path_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch, - path_param: path - }); - (0, logger_1.logDebugInfo)(`Removed chunks: ${path} [${branch}]`); - if (error) { - (0, logger_1.logError)(`Error removing chunks by path: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getShasumByPath = async (owner, repository, branch, path) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('path', path) - .order('index') - .order('chunk_index') - .limit(1); - if (error) { - (0, logger_1.logError)(`Supabase error getting chunks by path: ${JSON.stringify(error, null, 2)}`); - return undefined; - } - if (!data) { - return undefined; - } - return data[0].shasum; - } - catch (error) { - // logError(`Error getting shasum by path: ${JSON.stringify(error, null, 2)}`); - return undefined; - } - }; - this.countBranchEntries = async (owner, repository, branch) => { - try { - const { data, error } = await this.supabase - .rpc('count_branch_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - if (error) { - (0, logger_1.logError)(`Error counting branch entries: ${JSON.stringify(error, null, 2)}`); - return 0; - } - return data || 0; - } - catch (error) { - (0, logger_1.logError)(`Error counting branch entries: ${JSON.stringify(error, null, 2)}`); - return 0; - } - }; - this.duplicateFileEntries = async (owner, repository, sourceBranch, path, targetBranch) => { - try { - (0, logger_1.logDebugInfo)(`Duplicating file entries: ${path} [${sourceBranch}] -> [${targetBranch}]`); - const { error } = await this.supabase - .rpc('duplicate_file_entries', { - owner_param: owner, - repository_param: repository, - source_branch_param: sourceBranch, - path_param: path, - target_branch_param: targetBranch - }); - if (error) { - (0, logger_1.logError)(`Error duplicating file entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error duplicating file entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.duplicateBranchEntries = async (owner, repository, sourceBranch, targetBranch) => { - try { - (0, logger_1.logDebugInfo)(`Duplicating branch entries for ${owner}/${repository}/${sourceBranch} to ${targetBranch}`); - const { error } = await this.supabase - .rpc('duplicate_branch_entries', { - owner_param: owner, - repository_param: repository, - source_branch_param: sourceBranch, - target_branch_param: targetBranch - }); - if (error) { - (0, logger_1.logError)(`Error duplicating branch entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error duplicating branch entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.deleteBranchEntries = async (owner, repository, branch) => { - const { error } = await this.supabase - .rpc('delete_branch_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - if (error) { - (0, logger_1.logError)(`Error removing chunks from branch: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getVectorOfChunkContent = async (owner, repository, content) => { - try { - const { data, error } = await this.supabase - .rpc('get_vector_of_chunk_content', { - owner_param: owner, - repository_param: repository, - content_param: content - }); - if (error) { - (0, logger_1.logError)(`Error getting vector of chunk content: ${JSON.stringify(error, null, 2)}`); - throw error; - } - // If no data is found, return empty array - if (!data) { - return []; - } - return data; - } - catch (error) { - (0, logger_1.logError)(`Error getting vector of chunk content: ${JSON.stringify(error, null, 2)}`); - return []; - } - }; - const customFetch = async (input, init) => { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.DEFAULT_TIMEOUT); - try { - const response = await fetch(input, { - ...init, - signal: controller.signal - }); - return response; - } - finally { - clearTimeout(timeoutId); - } - }; - this.supabase = (0, supabase_js_1.createClient)(config.getUrl(), config.getKey(), { - global: { - headers: { - 'X-Client-Info': constants_1.COMMAND - }, - fetch: customFetch - }, - db: { - schema: 'public' - }, - auth: { - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true - } - }); - } + 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 } -exports.SupabaseRepository = SupabaseRepository; /***/ }), -/***/ 90779: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 9188: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WorkflowRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const workflow_run_1 = __nccwpck_require__(6845); -const constants_1 = __nccwpck_require__(8593); -class WorkflowRepository { - constructor() { - this.getWorkflows = async (params) => { - const octokit = github.getOctokit(params.tokens.token); - const workflows = await octokit.rest.actions.listWorkflowRunsForRepo({ - owner: params.owner, - repo: params.repo, - }); - return workflows.data.workflow_runs.map(w => new workflow_run_1.WorkflowRun({ - id: w.id, - name: w.name ?? 'unknown', - head_branch: w.head_branch, - head_sha: w.head_sha, - run_number: w.run_number, - event: w.event, - status: w.status ?? 'unknown', - conclusion: w.conclusion ?? null, - created_at: w.created_at, - updated_at: w.updated_at, - url: w.url, - html_url: w.html_url, - })); - }; - this.getActivePreviousRuns = async (params) => { - const workflows = await this.getWorkflows(params); - const runId = parseInt(process.env.GITHUB_RUN_ID, 10); - const workflowName = process.env.GITHUB_WORKFLOW; - return workflows.filter((run) => { - const isSameWorkflow = run.name === workflowName; - const isPrevious = run.id < runId; - const isActive = constants_1.WORKFLOW_ACTIVE_STATUSES.includes(run.status); - return isSameWorkflow && isPrevious && isActive; - }); - }; - } + +// 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 } -exports.WorkflowRepository = WorkflowRepository; /***/ }), -/***/ 26365: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ContentInterface = void 0; -const logger_1 = __nccwpck_require__(38836); -class ContentInterface { - constructor() { - this.getContent = (description) => { - try { - if (description === undefined) { - return undefined; - } - if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { - return undefined; - } - return description.split(this.startPattern)[1].split(this.endPattern)[0]; - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; - } - }; - this._addContent = (description, content) => { - if (description.indexOf(this.startPattern) === -1 && description.indexOf(this.endPattern) === -1) { - const newContent = `${this.startPattern}\n${content}\n${this.endPattern}`; - return `${description}\n\n${newContent}`; - } - else { - return undefined; - } - }; - this._updateContent = (description, content) => { - if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { - (0, logger_1.logError)(`The content has a problem with open-close tags: ${this.startPattern} / ${this.endPattern}`); - return undefined; - } - const start = description.split(this.startPattern)[0]; - const mid = `${this.startPattern}\n${content}\n${this.endPattern}`; - const end = description.split(this.endPattern)[1]; - return `${start}${mid}${end}`; - }; - this.updateContent = (description, content) => { - try { - if (description === undefined || content === undefined) { - return undefined; - } - const addedContent = this._addContent(description, content); - if (addedContent !== undefined) { - return addedContent; - } - return this._updateContent(description, content); - } - catch (error) { - (0, logger_1.logError)(`Error updating issue description: ${error}`); - return undefined; - } - }; - } - get _id() { - return `git-board-flow-${this.id}`; - } - get startPattern() { - if (this.visibleContent) { - return ``; - } - return ``; - } - return `${this._id}-end -->`; - } -} -exports.ContentInterface = ContentInterface; +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const { MessagePort } = __nccwpck_require__(1267) -/***/ }), +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit -/***/ 9913: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) -"use strict"; + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.MessageEventInit(eventInitDict) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueContentInterface = void 0; -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -const content_interface_1 = __nccwpck_require__(26365); -class IssueContentInterface extends content_interface_1.ContentInterface { - constructor() { - super(...arguments); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.internalGetter = async (execution) => { - try { - let number = -1; - if (execution.isSingleAction) { - number = execution.issueNumber; - } - else if (execution.isIssue) { - number = execution.issue.number; - } - else if (execution.isPullRequest) { - number = execution.pullRequest.number; - } - else if (execution.isPush) { - number = execution.issueNumber; - } - else { - return undefined; - } - const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); - return this.getContent(description); - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; - } - }; - this.internalUpdate = async (execution, content) => { - try { - let number = -1; - if (execution.isSingleAction) { - if (execution.isIssue) { - number = execution.issue.number; - } - else if (execution.isPullRequest) { - number = execution.pullRequest.number; - } - else if (execution.isPush) { - number = execution.issueNumber; - } - else { - number = execution.singleAction.issue; - } - } - else if (execution.isIssue) { - number = execution.issue.number; - } - else if (execution.isPullRequest) { - number = execution.pullRequest.number; - } - else if (execution.isPush) { - number = execution.issueNumber; - } - else { - return undefined; - } - const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); - const updated = this.updateContent(description, content); - if (updated === undefined) { - return undefined; - } - await this.issueRepository.updateDescription(execution.owner, execution.repo, number, updated, execution.tokens.token); - return updated; - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; - } - }; - } -} -exports.IssueContentInterface = IssueContentInterface; + super(type, eventInitDict) + this.#eventInit = eventInitDict + } -/***/ }), + get data () { + webidl.brandCheck(this, MessageEvent) -/***/ 34509: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this.#eventInit.data + } -"use strict"; + get origin () { + webidl.brandCheck(this, MessageEvent) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ConfigurationHandler = void 0; -const config_1 = __nccwpck_require__(41106); -const logger_1 = __nccwpck_require__(38836); -const issue_content_interface_1 = __nccwpck_require__(9913); -class ConfigurationHandler extends issue_content_interface_1.IssueContentInterface { - constructor() { - super(...arguments); - this.update = async (execution) => { - try { - return await this.internalUpdate(execution, JSON.stringify(execution.currentConfiguration, null, 4)); - } - catch (error) { - (0, logger_1.logError)(`Error updating issue description: ${error}`); - return undefined; - } - }; - this.get = async (execution) => { - try { - const config = await this.internalGetter(execution); - if (config === undefined) { - return undefined; - } - const branchConfig = JSON.parse(config); - return new config_1.Config(branchConfig); - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; - } - }; - } - get id() { - return 'configuration'; - } - get visibleContent() { - return false; + 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 + }) + } } -exports.ConfigurationHandler = ConfigurationHandler; +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit -/***/ }), + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) -/***/ 2430: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) -"use strict"; + super(type, eventInitDict) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CreateReleaseUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class CreateReleaseUseCase { - constructor() { - this.taskId = 'CreateReleaseUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - if (param.singleAction.version.length === 0) { - (0, logger_1.logError)(`Version is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` - ], - })); - return result; - } - else if (param.singleAction.title.length === 0) { - (0, logger_1.logError)(`Title is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE} is not set.` - ], - })); - } - else if (param.singleAction.changelog.length === 0) { - (0, logger_1.logError)(`Changelog is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG} is not set.` - ], - })); - } - try { - const releaseUrl = await this.projectRepository.createRelease(param.owner, param.repo, param.singleAction.version, param.singleAction.title, param.singleAction.changelog, param.tokens.token); - if (releaseUrl) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Created release \`${releaseUrl}\`.`], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Failed to create release.` - ], - })); - } - } - catch (error) { - (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Failed to create release.`], - errors: [ - JSON.stringify(error) - ], - })); - } - return result; - } + 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 + } } -exports.CreateReleaseUseCase = CreateReleaseUseCase; +// 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) -/***/ 45279: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) -"use strict"; + this.#eventInit = eventInitDict + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CreateTagUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class CreateTagUseCase { - constructor() { - this.taskId = 'CreateTagUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - if (param.singleAction.version.length === 0) { - (0, logger_1.logError)(`Version is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` - ], - })); - return result; - } - else if (param.currentConfiguration.releaseBranch === undefined) { - (0, logger_1.logError)(`Working branch not found in configuration.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Release branch not found in issue configuration.` - ], - })); - return result; - } - try { - const sha1Tag = await this.projectRepository.createTag(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.singleAction.version, param.tokens.token); - if (sha1Tag) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Tag ${param.singleAction.version} is ready: ${sha1Tag}`], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Failed to create tag ${param.singleAction.version}.` - ], - })); - } - } - catch (error) { - (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Failed to create tag ${param.singleAction.version}.`], - errors: [ - JSON.stringify(error) - ], - })); - } - return result; - } + 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 + } } -exports.CreateTagUseCase = CreateTagUseCase; +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) -/***/ 98293: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) -"use strict"; +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 + } +] -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DeployedActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class DeployedActionUseCase { - constructor() { - this.taskId = 'DeployedActionUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.branchRepository = new branch_repository_1.BranchRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (!param.labels.isDeploy) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to set label \`${param.labels.deployed}\` but there was no \`${param.labels.deploy}\` label.`, - ], - })); - return result; - } - if (param.labels.isDeployed) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to set label \`${param.labels.deployed}\` but it was already set.`, - ], - })); - return result; - } - const labelNames = param.labels.currentIssueLabels.filter(name => name !== param.labels.deploy); - labelNames.push(param.labels.deployed); - await this.issueRepository.setLabels(param.owner, param.repo, param.singleAction.issue, labelNames, param.tokens.token); - (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.singleAction.issue}:`); - (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Label \`${param.labels.deployed}\` added after a success deploy.`, - ], - })); - if (param.currentConfiguration.releaseBranch) { - const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDefaultResult); - const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDevelopResult); - } - else if (param.currentConfiguration.hotfixBranch) { - const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.hotfixBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDefaultResult); - const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.branches.defaultBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDevelopResult); - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to assign members to issue.`], - error: error, - })); - } - return result; +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 [] } -} -exports.DeployedActionUseCase = DeployedActionUseCase; - - -/***/ }), + } +]) -/***/ 67336: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +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: '' + } +]) -"use strict"; +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 + } +]) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PrepareAIContainerUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const docker_repository_1 = __nccwpck_require__(19097); -const logger_1 = __nccwpck_require__(38836); -class PrepareAIContainerUseCase { - constructor() { - this.taskId = 'PrepareAIContainerUseCase'; - this.dockerRepository = new docker_repository_1.DockerRepository(); - /*private async buildAndPushImage(param: Execution): Promise { - const imageName = this.dockerRepository.getImageName(param); - - const localExists = await this.dockerRepository.imageExists(param); - if (!localExists) { - logDebugInfo('🐳 🟔 Local image not found, building...'); - await this.dockerRepository.buildImage(param); - } else { - logDebugInfo('🐳 🟢 Local image already exists, skipping build'); - } - - logInfo('🐳 🟔 Pushing image to registry...'); - // await this.dockerRepository.pushImageToRegistry(param, imageName); - }*/ - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - const version = param.singleAction.version; - if (version.length === 0) { - (0, logger_1.logError)(`No version specified, skipping version check`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`No version specified, skipping build`], - })); - return results; - } - const imageName = this.dockerRepository.getImageNameWithTag(param); - (0, logger_1.logInfo)(`🐳 🟔 Checking if v${version} already exists in registry...`); - (0, logger_1.logInfo)(`🐳 🟔 Image: ${imageName}`); - const versionExists = await this.dockerRepository.checkVersionExistsInRegistry(param); - if (versionExists) { - (0, logger_1.logInfo)(`🐳 🟢 v${version} already exists in registry, skipping build`); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`v${version} already exists in registry: ${imageName}`], - })); - return results; - } - else { - (0, logger_1.logInfo)(`🐳 🟔 v${version} not found in registry, proceeding with build...`); - } - (0, logger_1.logInfo)('🐳 🟔 Building and pushing new image...'); - await this.dockerRepository.buildImage(param); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Image built and pushed successfully: ${this.dockerRepository.getImageName(param)}`], - })); - } - catch (error) { - (0, logger_1.logError)(`Error in ${this.taskId}: ${error}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Error preparing AI container: ${error}`], - })); - } - return results; - } +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent } -exports.PrepareAIContainerUseCase = PrepareAIContainerUseCase; /***/ }), -/***/ 19029: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5444: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PublishGithubActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class PublishGithubActionUseCase { - constructor() { - this.taskId = 'PublishGithubActionUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - if (param.singleAction.version.length === 0) { - (0, logger_1.logError)(`Version is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` - ], - })); - return result; - } - const sourceTag = `v${param.singleAction.version}`; - const targetTag = sourceTag.split('.')[0]; - try { - await this.projectRepository.updateTag(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); - const releaseId = await this.projectRepository.updateRelease(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); - if (releaseId) { - (0, logger_1.logInfo)(`Updated release \`${targetTag}\` from \`${sourceTag}\`: ${releaseId}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Updated release \`${targetTag}\` from \`${sourceTag}\`.`], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Failed to update release \`${targetTag}\` from \`${sourceTag}\`.` - ], - })); - } - } - catch (error) { - (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Failed to update release \`${targetTag}\` from \`${sourceTag}\`.`], - errors: [ - JSON.stringify(error) - ], - })); - } - return result; - } -} -exports.PublishGithubActionUseCase = PublishGithubActionUseCase; +const { maxUnsigned16Bit } = __nccwpck_require__(9188) -/***/ }), +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6113) +} catch { -/***/ 17757: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +} -"use strict"; +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = crypto.randomBytes(4) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VectorActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const docker_repository_1 = __nccwpck_require__(19097); -const file_repository_1 = __nccwpck_require__(81503); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -class VectorActionUseCase { - constructor() { - this.taskId = 'VectorActionUseCase'; - this.dockerRepository = new docker_repository_1.DockerRepository(); - this.fileRepository = new file_repository_1.FileRepository(); - this.CODE_INSTRUCTION_BLOCK = "Represent the code for semantic search"; - this.CODE_INSTRUCTION_LINE = "Represent each line of code for retrieval"; - this.checkChunksInSupabase = async (param, branch, chunkedFilesMap) => { - const results = []; - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - const remotePaths = await supabaseRepository.getDistinctPaths(param.owner, param.repo, branch); - // Get all local paths from chunkedFiles - const localPaths = new Set(Array.from(chunkedFilesMap.keys())); - // Find paths that exist in Supabase but not in the current branch - const pathsToRemove = remotePaths.filter(path => !localPaths.has(path)); - if (pathsToRemove.length > 0 && remotePaths.length > 0) { - (0, logger_1.logInfo)(`šŸ“¦ Found ${pathsToRemove.length} paths to remove from AI index as they no longer exist in the branch ${branch}.`); - for (const path of pathsToRemove) { - try { - await supabaseRepository.removeChunksByPath(param.owner, param.repo, branch, path); - (0, logger_1.logInfo)(`šŸ“¦ āœ… Removed chunks for path: ${path}`); - } - catch (error) { - (0, logger_1.logError)(`šŸ“¦ āŒ Error removing chunks for path ${path}: ${JSON.stringify(error, null, 2)}`); - } - } - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Removed ${pathsToRemove.length} paths from AI index as they no longer exist in \`${branch}\`.`, - ], - })); - } - else { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - return results; - }; - this.uploadChunksToSupabase = async (param, branch, chunkedFilesMap) => { - const results = []; - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - const processedChunkedFiles = []; - const startTime = Date.now(); - const chunkedPaths = Array.from(chunkedFilesMap.keys()); - for (let i = 0; i < chunkedPaths.length; i++) { - const path = chunkedPaths[i]; - const chunkedFiles = chunkedFilesMap.get(path) || []; - const progress = ((i + 1) / chunkedPaths.length) * 100; - const currentTime = Date.now(); - const elapsedTime = (currentTime - startTime) / 1000; // in seconds - const estimatedTotalTime = (elapsedTime / (i + 1)) * chunkedPaths.length; - const remainingTime = estimatedTotalTime - elapsedTime; - (0, logger_1.logSingleLine)(`šŸ”˜ ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Checking [${path}]`); - const remoteShasum = await supabaseRepository.getShasumByPath(param.owner, param.repo, branch, path); - if (remoteShasum) { - if (remoteShasum === chunkedFiles[0].shasum) { - (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File indexed [${path}]`); - continue; - } - else if (remoteShasum !== chunkedFiles[0].shasum) { - (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File has changes and must be reindexed [${path}]`); - await supabaseRepository.removeChunksByPath(param.owner, param.repo, branch, path); - } - } - // Process chunks in parallel with concurrency limit - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const maxWorkers = systemInfo.parameters.max_workers; - const chunkPromises = []; - let activeWorkers = 0; - for (let j = 0; j < chunkedFiles.length; j++) { - const chunkedFile = chunkedFiles[j]; - const chunkProgress = ((j + 1) / chunkedFiles.length) * 100; - // Wait if we have reached the limit of workers - while (activeWorkers >= maxWorkers) { - await Promise.race(chunkPromises); - activeWorkers = chunkPromises.filter(p => !p).length; - } - const processChunk = async () => { - try { - (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Vectorizing [${chunkedFile.path}]`); - const existingVectors = []; - const existingChunks = []; - const chunksToProcess = []; - for (const chunk of chunkedFile.chunks) { - const vector = await supabaseRepository.getVectorOfChunkContent(param.owner, param.repo, chunk); - if (vector.length > 0) { - existingVectors.push(vector); - existingChunks.push(chunk); - } - else { - chunksToProcess.push(chunk); - } - } - const cachedPercentage = (existingChunks.length / chunkedFile.chunks.length) * 100; - (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Vectorizing [${chunkedFile.path}] - ${cachedPercentage.toFixed(1)}% cached`); - let embeddings = []; - let chunks = []; - if (chunksToProcess.length > 0) { - const newEmbeddings = await this.dockerRepository.getEmbedding(param, chunksToProcess.map(chunk => [chunkedFile.type === 'block' ? this.CODE_INSTRUCTION_BLOCK : this.CODE_INSTRUCTION_LINE, chunk])); - embeddings = [...existingVectors, ...newEmbeddings]; - chunks = [...existingChunks, ...chunksToProcess]; - } - else { - embeddings = existingVectors; - chunks = existingChunks; - } - chunkedFile.vector = embeddings; - chunkedFile.chunks = chunks; - (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Storing [${chunkedFile.path}]`); - await supabaseRepository.setChunkedFile(param.owner, param.repo, branch, chunkedFile); - processedChunkedFiles.push(chunkedFile); - } - catch (error) { - (0, logger_1.logError)(`Error processing chunk ${j + 1} of file ${path}: ${JSON.stringify(error, null, 2)}`); - } - }; - const chunkPromise = processChunk(); - chunkPromises.push(chunkPromise); - activeWorkers++; - chunkPromise.finally(() => { - activeWorkers--; - }); - } - // Wait for all chunks of the current file to be processed - await Promise.all(chunkPromises); - } - const totalDurationSeconds = (Date.now() - startTime) / 1000; - (0, logger_1.logInfo)(`šŸ“¦ šŸš€ All chunked files stored ${param.owner}/${param.repo}/${branch}. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, true); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `All chunked files up to date in AI index for \`${branch}\`. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, - ], - })); - return results; - }; - this.duplicateChunksToBranch = async (param, sourceBranch, targetBranch) => { - const results = []; - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - try { - (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Clearing possible existing chunks from ${targetBranch} for ${param.owner}/${param.repo}.`); - await supabaseRepository.removeChunksByBranch(param.owner, param.repo, targetBranch); - (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Duplicating chunks from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`); - await supabaseRepository.duplicateChunksByBranch(param.owner, param.repo, sourceBranch, targetBranch); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Duplicated chunks from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`, - ], - })); - } - catch (error) { - (0, logger_1.logError)(`šŸ“¦ -> šŸ“¦ āŒ Error duplicating chunks from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Error duplicating chunks from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`, - ], - })); - } - return results; - }; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - await this.dockerRepository.prepareLocalVectorServer(param); - const branch = param.commit.branch || param.branches.main; - let duplicationBranch = undefined; - if (branch === param.branches.main && param.singleAction.isVectorLocalAction) { - (0, logger_1.logInfo)(`šŸ“¦ Chunks from [${param.branches.main}] will be duplicated to [${param.branches.development}] for ${param.owner}/${param.repo}.`); - duplicationBranch = param.branches.development; - } - await this.dockerRepository.startContainer(param); - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const chunkSize = systemInfo.parameters.chunk_size; - const maxWorkers = systemInfo.parameters.max_workers; - (0, logger_1.logInfo)(`šŸ§‘ā€šŸ­ Max workers: ${maxWorkers}`); - (0, logger_1.logInfo)(`🚚 Chunk size: ${chunkSize}`); - (0, logger_1.logInfo)(`šŸ“¦ Getting chunks on ${param.owner}/${param.repo}/${branch}`); - const chunkedFilesMap = await this.fileRepository.getChunkedRepositoryContent(param.owner, param.repo, branch, chunkSize, param.tokens.token, param.ai.getAiIgnoreFiles(), (fileName) => { - (0, logger_1.logSingleLine)(`Checking file ${fileName}`); - }, (fileName) => { - (0, logger_1.logSingleLine)(`Ignoring file ${fileName}`); - }); - (0, logger_1.logInfo)(`šŸ“¦ āœ… Files to index: ${chunkedFilesMap.size}`, true); - results.push(...await this.checkChunksInSupabase(param, branch, chunkedFilesMap)); - results.push(...await this.uploadChunksToSupabase(param, branch, chunkedFilesMap)); - if (duplicationBranch) { - results.push(...await this.duplicateChunksToBranch(param, branch, duplicationBranch)); - } - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Vector action executed successfully.`, - ], - })); - } - catch (error) { - (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`, - ], - })); - } - finally { - await this.dockerRepository.stopContainer(param); - } - return results; + 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 } -} -exports.VectorActionUseCase = VectorActionUseCase; + 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 -/***/ 85016: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + /*! 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] -"use strict"; + buffer[1] = payloadLength -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CommitUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -const notify_new_commit_on_issue_use_case_1 = __nccwpck_require__(99054); -const check_changes_issue_size_use_case_1 = __nccwpck_require__(15863); -class CommitUseCase { - constructor() { - this.taskId = 'CommitUseCase'; + 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) } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - if (param.commit.commits.length === 0) { - (0, logger_1.logDebugInfo)('No commits found in this push.'); - return results; - } - (0, logger_1.logDebugInfo)(`Branch: ${param.commit.branch}`); - (0, logger_1.logDebugInfo)(`Commits detected: ${param.commit.commits.length}`); - (0, logger_1.logDebugInfo)(`Issue number: ${param.issueNumber}`); - results.push(...(await new notify_new_commit_on_issue_use_case_1.NotifyNewCommitOnIssueUseCase().invoke(param))); - results.push(...(await new check_changes_issue_size_use_case_1.CheckChangesIssueSizeUseCase().invoke(param))); - } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error processing the commits.`, - ], - error: error, - })); - } - return results; + + 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 } -exports.CommitUseCase = CommitUseCase; /***/ }), -/***/ 50854: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1688: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueCommentUseCase = void 0; -const logger_1 = __nccwpck_require__(38836); -const ask_ai_use_case_1 = __nccwpck_require__(52268); -const check_issue_comment_language_use_case_1 = __nccwpck_require__(90465); -class IssueCommentUseCase { - constructor() { - this.taskId = 'IssueCommentUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - results.push(...await new check_issue_comment_language_use_case_1.CheckIssueCommentLanguageUseCase().invoke(param)); - results.push(...await new ask_ai_use_case_1.AskActionUseCase().invoke(param)); - return results; - } -} -exports.IssueCommentUseCase = IssueCommentUseCase; +const { Writable } = __nccwpck_require__(2781) +const diagnosticsChannel = __nccwpck_require__(7643) +const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(9188) +const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(7578) +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(5515) +const { WebsocketFrameSend } = __nccwpck_require__(5444) -/***/ }), +// 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 -/***/ 58675: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +const channels = {} +channels.ping = diagnosticsChannel.channel('undici:websocket:ping') +channels.pong = diagnosticsChannel.channel('undici:websocket:pong') -"use strict"; +class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueUseCase = void 0; -const logger_1 = __nccwpck_require__(38836); -const check_permissions_use_case_1 = __nccwpck_require__(58749); -const update_title_use_case_1 = __nccwpck_require__(65107); -const assign_members_to_issue_use_case_1 = __nccwpck_require__(53115); -const check_priority_issue_size_use_case_1 = __nccwpck_require__(151); -const close_not_allowed_issue_use_case_1 = __nccwpck_require__(97826); -const label_deploy_added_use_case_1 = __nccwpck_require__(75678); -const label_deployed_added_use_case_1 = __nccwpck_require__(8388); -const link_issue_project_use_case_1 = __nccwpck_require__(67528); -const prepare_branches_use_case_1 = __nccwpck_require__(84423); -const remove_issue_branches_use_case_1 = __nccwpck_require__(92354); -const remove_not_needed_branches_use_case_1 = __nccwpck_require__(90773); -const update_issue_type_use_case_1 = __nccwpck_require__(81652); -class IssueUseCase { - constructor() { - this.taskId = 'IssueUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - const permissionResult = await new check_permissions_use_case_1.CheckPermissionsUseCase().invoke(param); - const lastAction = permissionResult[permissionResult.length - 1]; - if (!lastAction.success && lastAction.executed) { - results.push(...permissionResult); - results.push(...await new close_not_allowed_issue_use_case_1.CloseNotAllowedIssueUseCase().invoke(param)); - return results; - } - if (param.cleanIssueBranches) { - results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); + #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() } - /** - * Assignees - */ - results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); - /** - * Update title - */ - results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); - /** - * Update issue type - */ - results.push(...await new update_issue_type_use_case_1.UpdateIssueTypeUseCase().invoke(param)); - /** - * Link issue to project - */ - results.push(...await new link_issue_project_use_case_1.LinkIssueProjectUseCase().invoke(param)); - /** - * Check priority issue size - */ - results.push(...await new check_priority_issue_size_use_case_1.CheckPriorityIssueSizeUseCase().invoke(param)); - /** - * Prepare branches - */ - if (param.isBranched) { - results.push(...await new prepare_branches_use_case_1.PrepareBranchesUseCase().invoke(param)); + + 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 } - else { - results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); + + 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 } - /** - * Remove unnecessary branches - */ - results.push(...await new remove_not_needed_branches_use_case_1.RemoveNotNeededBranchesUseCase().invoke(param)); - /** - * Check if deploy label was added - */ - results.push(...await new label_deploy_added_use_case_1.DeployAddedUseCase().invoke(param)); - /** - * Check if deployed label was added - */ - results.push(...await new label_deployed_added_use_case_1.DeployedAddedUseCase().invoke(param)); - return results; - } -} -exports.IssueUseCase = IssueUseCase; + 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) -/***/ 67883: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.#info.closeInfo = this.parseCloseBody(false, body) -"use strict"; + 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) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequestReviewCommentUseCase = void 0; -const logger_1 = __nccwpck_require__(38836); -const check_pull_request_comment_language_use_case_1 = __nccwpck_require__(87112); -class PullRequestReviewCommentUseCase { - constructor() { - this.taskId = 'PullRequestReviewCommentUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - results.push(...await new check_pull_request_comment_language_use_case_1.CheckPullRequestCommentLanguageUseCase().invoke(param)); - return results; - } -} -exports.PullRequestReviewCommentUseCase = PullRequestReviewCommentUseCase; + 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() -/***/ 53478: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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" -"use strict"; + const body = this.consume(payloadLength) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequestUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -const update_title_use_case_1 = __nccwpck_require__(65107); -const assign_members_to_issue_use_case_1 = __nccwpck_require__(53115); -const assign_reviewers_to_issue_use_case_1 = __nccwpck_require__(46275); -const close_issue_after_merging_use_case_1 = __nccwpck_require__(35137); -const check_changes_pull_request_size_use_case_1 = __nccwpck_require__(38129); -const check_priority_pull_request_size_use_case_1 = __nccwpck_require__(67383); -const link_pull_request_issue_use_case_1 = __nccwpck_require__(22175); -const link_pull_request_project_use_case_1 = __nccwpck_require__(64311); -const update_pull_request_description_use_case_1 = __nccwpck_require__(50158); -class PullRequestUseCase { - constructor() { - this.taskId = 'PullRequestUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - (0, logger_1.logDebugInfo)(`PR action ${param.pullRequest.action}`); - (0, logger_1.logDebugInfo)(`PR isOpened ${param.pullRequest.isOpened}`); - (0, logger_1.logDebugInfo)(`PR isMerged ${param.pullRequest.isMerged}`); - (0, logger_1.logDebugInfo)(`PR isClosed ${param.pullRequest.isClosed}`); - if (param.pullRequest.isOpened) { - /** - * Update title - */ - results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); - /** - * Assignees - */ - results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); - /** - * Reviewers - */ - results.push(...await new assign_reviewers_to_issue_use_case_1.AssignReviewersToIssueUseCase().invoke(param)); - /** - * Link Pull Request to projects - */ - results.push(...await new link_pull_request_project_use_case_1.LinkPullRequestProjectUseCase().invoke(param)); - /** - * Link Pull Request to issue - */ - results.push(...await new link_pull_request_issue_use_case_1.LinkPullRequestIssueUseCase().invoke(param)); - /** - * Check priority pull request size - */ - results.push(...await new check_priority_pull_request_size_use_case_1.CheckPriorityPullRequestSizeUseCase().invoke(param)); - /** - * Check changes size - */ - results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); - if (param.ai.getAiPullRequestDescription()) { - /** - * Update pull request description - */ - results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); - } - } - else if (param.pullRequest.isSynchronize) { - /** - * Check changes size - */ - results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); - /** - * Pushed changes to the pull request - */ - if (param.ai.getAiPullRequestDescription()) { - /** - * Update pull request description - */ - results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); - } - } - else if (param.pullRequest.isClosed && param.pullRequest.isMerged) { - /** - * Close issue if needed - */ - results.push(...await new close_issue_after_merging_use_case_1.CloseIssueAfterMergingUseCase().invoke(param)); + 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 + } } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error linking projects/issues with pull request.`, - ], - error: error, - })); + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() } - return results; + + 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 + } } -} -exports.PullRequestUseCase = PullRequestUseCase; + this.#byteOffset -= n -/***/ }), - -/***/ 6479: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return buffer + } -"use strict"; + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SingleActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -const deployed_action_use_case_1 = __nccwpck_require__(98293); -const vector_action_use_case_1 = __nccwpck_require__(17757); -const prepare_ai_container_use_case_1 = __nccwpck_require__(67336); -const publish_github_action_use_case_1 = __nccwpck_require__(19029); -const create_release_use_case_1 = __nccwpck_require__(2430); -const create_tag_use_case_1 = __nccwpck_require__(45279); -class SingleActionUseCase { - constructor() { - this.taskId = 'SingleActionUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - if (!param.singleAction.validSingleAction) { - (0, logger_1.logDebugInfo)(`Not a valid single action: ${param.singleAction.currentSingleAction}`); - return results; - } - if (param.singleAction.isCompileVectorServerAction) { - results.push(...await new prepare_ai_container_use_case_1.PrepareAIContainerUseCase().invoke(param)); - } - else if (param.singleAction.isVectorAction) { - // results.push(...await new PrepareLocalVectorServerUseCase().invoke(param)); - results.push(...await new vector_action_use_case_1.VectorActionUseCase().invoke(param)); - } - else if (param.singleAction.isDeployedAction) { - results.push(...await new deployed_action_use_case_1.DeployedActionUseCase().invoke(param)); - } - else if (param.singleAction.isPublishGithubAction) { - results.push(...await new publish_github_action_use_case_1.PublishGithubActionUseCase().invoke(param)); - } - else if (param.singleAction.isCreateReleaseAction) { - results.push(...await new create_release_use_case_1.CreateReleaseUseCase().invoke(param)); - } - else if (param.singleAction.isCreateTagAction) { - results.push(...await new create_tag_use_case_1.CreateTagUseCase().invoke(param)); - } - } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error executing single action: ${param.singleAction.currentSingleAction}.`, - ], - error: error, - })); - } - return results; + 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) } -} -exports.SingleActionUseCase = SingleActionUseCase; + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } -/***/ }), + return { code } + } -/***/ 15863: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) -"use strict"; + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckChangesIssueSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckChangesIssueSizeUseCase { - constructor() { - this.taskId = 'CheckChangesIssueSizeUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); + if (code !== undefined && !isValidStatusCode(code)) { + return null } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.currentConfiguration.parentBranch === undefined) { - (0, logger_1.logDebugInfo)(`Parent branch is undefined.`); - return result; - } - const headBranch = param.commit.branch; - const baseBranch = param.currentConfiguration.parentBranch; - const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, headBranch, baseBranch, param.sizeThresholds, param.labels, param.tokens.token); - (0, logger_1.logDebugInfo)(`Size: ${size}`); - (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); - (0, logger_1.logDebugInfo)(`Reason: ${reason}`); - (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnIssue}`); - if (param.labels.sizedLabelOnIssue !== size) { - const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); - labelNames.push(size); - await this.issueRepository.setLabels(param.owner, param.repo, param.issueNumber, labelNames, param.tokens.token); - for (const project of param.project.getProjects()) { - await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.issueNumber, githubSize, param.tokens.token); - } - (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.issueNumber}:`); - (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `${reason}, so the issue was resized to ${size}.`, - ], - })); - } - else { - (0, logger_1.logDebugInfo)(`The issue is already at the correct size.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the size of the changes, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + + 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 } -exports.CheckChangesIssueSizeUseCase = CheckChangesIssueSizeUseCase; /***/ }), -/***/ 99054: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7578: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.NotifyNewCommitOnIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const list_utils_1 = __nccwpck_require__(14990); -const logger_1 = __nccwpck_require__(38836); -const execute_script_use_case_1 = __nccwpck_require__(155); -class NotifyNewCommitOnIssueUseCase { - constructor() { - this.taskId = 'NotifyNewCommitOnIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.mergeBranchPattern = 'Merge branch '; - this.ghAction = 'gh-action: '; - this.separator = '------------------------------------------------------'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const branchName = param.commit.branch; - let commitPrefix = ''; - if (param.commitPrefixBuilder.length > 0) { - param.commitPrefixBuilderParams = { - branchName: branchName, - }; - const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); - const prefixResult = await executor.invoke(param); - commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; - (0, logger_1.logDebugInfo)(`Commit prefix: ${commitPrefix}`); - } - let title = ''; - let image = ''; - if (param.release.active) { - title = 'šŸš€ Release News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitReleaseGifs); - } - else if (param.hotfix.active) { - title = 'šŸ”„šŸ› Hotfix News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitHotfixGifs); - } - else if (param.isBugfix) { - title = 'šŸ› Bugfix News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitBugfixGifs); - } - else if (param.isFeature) { - title = '✨ Feature News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitFeatureGifs); - } - else if (param.isDocs) { - title = 'šŸ“ Documentation News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitDocsGifs); - } - else if (param.isChore) { - title = 'šŸ”§ Chore News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitChoreGifs); - } - else { - title = 'šŸŖ„ Automatic News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitAutomaticActions); - } - let commentBody = ` -# ${title} -**Changes on branch \`${param.commit.branch}\`:** +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') +} -`; - let shouldWarn = false; - for (const commit of param.commit.commits) { - commentBody += ` -${this.separator} -- ${commit.id} by **${commit.author.name}** (@${commit.author.username}) -\`\`\` -${commit.message.replaceAll(`${commitPrefix}: `, '')} -\`\`\` +/***/ }), -`; - if ((commit.message.indexOf(commitPrefix) !== 0 && commitPrefix.length > 0) - && commit.message.indexOf(this.mergeBranchPattern) !== 0 - && commit.message.indexOf(this.ghAction) !== 0) { - shouldWarn = true; - } - } - if (shouldWarn && commitPrefix.length > 0) { - commentBody += ` -${this.separator} -## āš ļø Attention +/***/ 5515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -One or more commits didn't start with the prefix **${commitPrefix}**. +"use strict"; -\`\`\` -${commitPrefix}: created hello-world app -\`\`\` -`; - } - if (image && param.images.imagesOnCommit) { - commentBody += ` -${this.separator} -![image](${image}) -`; - } - if (param.issue.reopenOnPush) { - const opened = await this.issueRepository.openIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (opened) { - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was re-opened after pushing new commits to the branch \`${branchName}\`.`, param.tokens.token); - } - } - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, commentBody, param.tokens.token); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to notify the new commit on the issue, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; - } +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(7578) +const { states, opcodes } = __nccwpck_require__(9188) +const { MessageEvent, ErrorEvent } = __nccwpck_require__(2611) + +/* 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 } -exports.NotifyNewCommitOnIssueUseCase = NotifyNewCommitOnIssueUseCase; +/** + * @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 +} -/***/ 52268: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * @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. -"use strict"; + // 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 -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AskActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const docker_repository_1 = __nccwpck_require__(19097); -const file_repository_1 = __nccwpck_require__(81503); -const issue_repository_1 = __nccwpck_require__(40057); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -class AskActionUseCase { - constructor() { - this.taskId = 'AskActionUseCase'; - this.dockerRepository = new docker_repository_1.DockerRepository(); - this.fileRepository = new file_repository_1.FileRepository(); - this.aiRepository = new ai_repository_1.AiRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.CODE_INSTRUCTION_ASK = "Represent the question for retrieving relevant code snippets"; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - /** - * Check if the user from the token is found. - */ - if (!param.tokenUser) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - errors: [ - `User from token not found.`, - ], - })); - return results; - } - let description = ''; - let commentBody = ''; - /** - * Get the comment body. - */ - if (param.issue.isIssueComment) { - (0, logger_1.logInfo)(`šŸ”Ž Issue comment body: ${param.issue.commentBody}`); - commentBody = param.issue.commentBody; - description = await this.issueRepository.getDescription(param.owner, param.repo, param.issueNumber, param.tokens.token) ?? ''; - } - else if (param.pullRequest.isPullRequestReviewComment) { - (0, logger_1.logInfo)(`šŸ”Ž Pull request review comment body: ${param.pullRequest.commentBody}`); - commentBody = param.pullRequest.commentBody; - description = await this.issueRepository.getDescription(param.owner, param.repo, param.issueNumber, param.tokens.token) ?? ''; - } - else { - (0, logger_1.logError)(`Not a valid comment body.`); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; - } - if (commentBody.length === 0 || !commentBody.includes(`@${param.tokenUser}`)) { - (0, logger_1.logInfo)(`šŸ”Ž Comment body is empty or does not include @${param.tokenUser}`); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; - } - else { - commentBody = commentBody.replace(param.tokenUser, '').trim(); - } - (0, logger_1.logInfo)(`šŸ”Ž Comment body: ${commentBody}`); - if (param.ai.getOpenRouterModel().length === 0 || param.ai.getOpenRouterApiKey().length === 0) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - errors: [ - `OpenRouter model or API key not found.`, - ], - })); - return results; - } - /** - * Check if the supabase config is found. - */ - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - await this.dockerRepository.startContainer(param); - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const chunkSize = systemInfo.parameters.chunk_size; - const maxWorkers = systemInfo.parameters.max_workers; - (0, logger_1.logInfo)(`šŸ§‘ā€šŸ­ Max workers: ${maxWorkers}`); - (0, logger_1.logInfo)(`🚚 Chunk size: ${chunkSize}`); - (0, logger_1.logInfo)(`šŸ“¦ Getting chunked files for ${param.owner}/${param.repo}/${param.commit.branch}`); - const startTime = Date.now(); - const embeddings = await this.dockerRepository.getEmbedding(param, [ - [this.CODE_INSTRUCTION_ASK, commentBody] - ]); - // logInfo(`šŸ”Ž Embeddings: ${JSON.stringify(embeddings, null, 2)}`); - const types = [ - 'line', - 'block' - ]; - const chunks = []; - for (const type of types) { - (0, logger_1.logInfo)(`šŸ“¦ šŸ”Ž Matching chunks for ${param.owner}/${param.repo}/${param.commit.branch}`); - const foundChunks = await supabaseRepository.matchChunks(param.owner, param.repo, param.commit.branch, type, embeddings[0], 5); - for (const chunk of foundChunks) { - (0, logger_1.logDebugInfo)(`šŸ“¦ šŸ”Ž Chunk type: ${type} - ${chunk.path}`); - } - chunks.push(...foundChunks); - } - const { withContent, withoutContent } = await this.fileRepository.getFileTree(param.owner, param.repo, param.tokens.token, param.commit.branch, param.ai.getAiIgnoreFiles(), (fileName) => { - (0, logger_1.logSingleLine)(`Checking file ${fileName}`); - }, (fileName) => { - (0, logger_1.logSingleLine)(`Ignoring file ${fileName}`); - }); - let workComplete = false; - let relatedFiles = new Map(); - let finalResponse = ''; - while (!workComplete) { - const prompt = ` - # Copilot - - You are a highly skilled code analysis assistant, currently working on a GitHub issue. Your role is to assist the developer by answering any related questions they may have. I will provide you with: - 1. The issue description - 2. A user's question about a codebase - 3. A file tree representing the structure of the project - 4. The most relevant code snippets from the codebase related to their query - - ## Your tasks - - - Analyze the code snippets in the context of the user's question. - - If the provided code snippets are not directly relevant to the question, analyze the file tree structure to identify potential relevant files and directories. - - Use the file tree to provide additional context if needed (e.g., to understand module relationships). - - Strive to find the most appropriate and complete solution to the user's question. - - When in doubt or if you need more context to provide a confident answer, request additional files. - - Provide your answer **only** in a JSON format, following this structure: - - { - "text_response": "Your detailed analysis or answer here.", - "action": "none" | "analyze_files", - "related_files": ["optional", "list", "of", "files"], - "complete": true | false - } + // 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) +} - ## Important guidelines for text_response +/** + * @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 + } - - Start your response directly with the answer or analysis, without introductory phrases like "Based on the provided code snippets..." or "Based on the file tree..." - - Be concise and direct in your response - - Focus on providing the information requested without unnecessary context or explanations - - If you need more information, state it directly without prefacing phrases + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent - ## Explanation + 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 + } + } - - If the provided code snippets and file tree are sufficient to confidently answer the question, set "complete": true and "action": "none". - - If you have any doubts or need more context to provide a complete and accurate answer, set "complete": false, "action": "analyze_files", and list the related file paths you need to investigate further in "related_files". - - If the current code snippets are not relevant to the question, analyze the file tree structure to identify potentially relevant files and request them. - - Do not invent file paths; only request files that logically relate to the question based on the information available. - - Always provide a "text_response" with your reasoning, even if requesting more files. - - When requesting additional files, explain in the text_response why you need those specific files to provide a better answer. + // 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 + }) +} - ## Important +/** + * @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 + } - - **Respond only with the JSON object**, without any extra commentary or text outside of the JSON. - - Prioritize accuracy and completeness over speed - it's better to request more files than to provide an incomplete or uncertain answer. - - If the current code snippets are not helpful, use the file tree structure to guide your search for relevant files. + for (const char of protocol) { + const code = char.charCodeAt(0) - ## Information provided + 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 + } + } - ### Issue description + return true +} - \`\`\` - ${description} - \`\`\` +/** + * @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" + ) + } - ### User's question + return code >= 3000 && code <= 4999 +} - \`\`\` - ${commentBody} - \`\`\` +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws - ### File tree + controller.abort() - \`\`\`json - ${JSON.stringify(withoutContent, null, 2)} - \`\`\` + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() + } - ### Relevant code snippets + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) + } +} - ${relatedFiles.size > 0 - ? Array.from(relatedFiles.entries()).map(([path, content]) => `\nFile: ${path}\nCode:\n${content}`).join('\n') - : chunks.map(chunk => `\nFile: ${chunk.path}\nCode:\n${chunk.chunk}`).join('\n')} - `; - const jsonResponse = await this.aiRepository.askJson(param.ai, prompt); - if (!jsonResponse) { - (0, logger_1.logError)(`No result from AI.`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error in ${this.taskId}: No result from AI.`, - ], - })); - return results; - } - (0, logger_1.logInfo)(`šŸ”Ž Result: ${JSON.stringify(jsonResponse, null, 2)}`); - workComplete = jsonResponse.complete; - if (jsonResponse.action === 'analyze_files') { - relatedFiles = this.getRelatedFiles(jsonResponse.related_files, withContent); - } - else if (jsonResponse.action === 'none') { - finalResponse = jsonResponse.text_response; - } - } - const totalDurationSeconds = (Date.now() - startTime) / 1000; - (0, logger_1.logInfo)(`šŸ“¦ šŸ”Ž Matched chunks for ${param.owner}/${param.repo}/${param.commit.branch}:\n Total duration: ${Math.ceil(totalDurationSeconds)} seconds`); - let number = 0; - if (param.issue.isIssueComment) { - number = param.issueNumber; - } - else if (param.pullRequest.isPullRequestReviewComment) { - number = param.pullRequest.number; - } - await this.issueRepository.addComment(param.owner, param.repo, number, finalResponse, param.tokens.token); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - catch (error) { - (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`, - ], - })); - } - finally { - await this.dockerRepository.stopContainer(param); - } - return results; - } - getRelatedFiles(relatedFiles, tree) { - const result = new Map(); - const findFile = (node, targetPath) => { - if (node.path === targetPath) { - return node; - } - if (node.children) { - for (const child of node.children) { - const found = findFile(child, targetPath); - if (found) { - return found; - } - } - } - return null; - }; - for (const filePath of relatedFiles) { - const fileNode = findFile(tree, filePath); - if (fileNode && fileNode.type === 'file' && fileNode.content) { - result.set(filePath, fileNode.content); - } - } - return result; - } +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived } -exports.AskActionUseCase = AskActionUseCase; /***/ }), -/***/ 58749: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4284: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckPermissionsUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckPermissionsUseCase { - constructor() { - this.taskId = 'CheckPermissionsUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - /** - * If a release/hotfix issue was opened, check if author is a member of the project. - */ - if (param.isIssue && !param.issue.opened) { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue state is not 'opened'.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - else if (param.isPullRequest && !param.pullRequest.opened) { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Pull request state is not 'opened'.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - try { - const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); - const creator = param.isIssue ? param.issue.creator : param.pullRequest.creator; - const creatorIsTeamMember = creator.length > 0 - && currentProjectMembers.indexOf(creator) > -1; - if (param.labels.isMandatoryBranchedLabel) { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); - if (creatorIsTeamMember) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`@${param.issue.creator} was not authorized to create **[${param.labels.currentIssueLabels.join(',')}]** issues.`], - })); - } - } - else { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; - } -} -exports.CheckPermissionsUseCase = CheckPermissionsUseCase; +const { webidl } = __nccwpck_require__(1744) +const { DOMException } = __nccwpck_require__(1037) +const { URLSerializer } = __nccwpck_require__(685) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(9188) +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = __nccwpck_require__(7578) +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(5515) +const { establishWebSocketConnection } = __nccwpck_require__(5354) +const { WebsocketFrameSend } = __nccwpck_require__(5444) +const { ByteParser } = __nccwpck_require__(1688) +const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3983) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { types } = __nccwpck_require__(3837) -/***/ }), +let experimentalWarned = false -/***/ 155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } -"use strict"; + #bufferedAmount = 0 + #protocol = '' + #extensions = '' -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CommitPrefixBuilderUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -class CommitPrefixBuilderUseCase { - constructor() { - this.taskId = 'CommitPrefixBuilderUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const branchName = param.commitPrefixBuilderParams.branchName; - const transforms = param.commitPrefixBuilder; // Now it's a list of transforms - const commitPrefix = this.applyTransforms(branchName, transforms); - (0, logger_1.logDebugInfo)(`Commit prefix generated: ${commitPrefix}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [], - payload: { - scriptResult: commitPrefix - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [], - error: error, - })); - } - return result; - } - applyTransforms(branchName, transforms) { - // Parse the list of transformations - const transformList = transforms.split(',').map(t => t.trim()); - let result = branchName; - // Apply each transformation sequentially - for (const transform of transformList) { - result = this.applyTransform(result, transform); - } - return result; - } - applyTransform(input, transform) { - switch (transform) { - case "replace-slash": - return input.replace("/", "-"); - case "replace-all": - return input.replace(/[^a-zA-Z0-9-]/g, "-"); - case "lowercase": - return input.toLowerCase(); - case "uppercase": - return input.toUpperCase(); - case "kebab-case": - return input - .replace(/[^a-zA-Z0-9-]/g, "-") - .replace(/-+/g, "-") - .replace(/^-|-$/g, "") - .toLowerCase(); - case "snake-case": - return input - .replace(/[^a-zA-Z0-9-]/g, "_") - .replace(/_+/g, "_") - .replace(/^_|_$/g, "") - .toLowerCase(); - case "camel-case": - return input - .replace(/[^a-zA-Z0-9-]/g, "-") - .split("-") - .map((word, index) => index === 0 ? word.toLowerCase() : - word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) - .join(""); - case "trim": - return input.trim(); - case "remove-numbers": - return input.replace(/\d+/g, ""); - case "remove-special": - return input.replace(/[^a-zA-Z0-9]/g, ""); - case "remove-spaces": - return input.replace(/\s+/g, ""); - case "remove-dashes": - return input.replace(/-+/g, ""); - case "remove-underscores": - return input.replace(/_+/g, ""); - case "clean-dashes": - return input.replace(/-+/g, "-").replace(/^-|-$/g, ""); - case "clean-underscores": - return input.replace(/_+/g, "_").replace(/^_|_$/g, ""); - case "prefix": - return `prefix-${input}`; - case "suffix": - return `${input}-suffix`; - default: - // If not recognized, return without changes - (0, logger_1.logDebugInfo)(`Unknown transform: ${transform}, skipping...`); - return input; - } + /** + * @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' + }) } -} -exports.CommitPrefixBuilderUseCase = CommitPrefixBuilderUseCase; + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) -/***/ }), + url = webidl.converters.USVString(url) + protocols = options.protocols -/***/ 8243: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin() -"use strict"; + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GetHotfixVersionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class GetHotfixVersionUseCase { - constructor() { - this.taskId = 'GetHotfixVersionUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - let number = -1; - if (param.isSingleAction) { - number = param.singleAction.issue; - } - else if (param.isIssue) { - number = param.issue.number; - } - else if (param.isPullRequest) { - number = param.pullRequest.number; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem identifying the issue.`], - })); - return result; - } - const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); - if (description === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem getting the description.`], - })); - return result; - } - const baseVersion = (0, content_utils_1.extractVersion)('Base Version', description); - const hotfixVersion = (0, content_utils_1.extractVersion)('Hotfix Version', description); - if (baseVersion === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the base version but there was a problem identifying the version.`], - })); - return result; - } - else if (hotfixVersion === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the hotfix version but there was a problem identifying the version.`], - })); - return result; - } - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - payload: { - baseVersion: baseVersion, - hotfixVersion: hotfixVersion, - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') } -} -exports.GetHotfixVersionUseCase = GetHotfixVersionUseCase; + // 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' + ) + } -/***/ 35966: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 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') + } -"use strict"; + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GetReleaseTypeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class GetReleaseTypeUseCase { - constructor() { - this.taskId = 'GetReleaseTypeUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); + // 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') } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - let number = -1; - if (param.isSingleAction) { - number = param.singleAction.issue; - } - else if (param.isIssue) { - number = param.issue.number; - } - else if (param.isPullRequest) { - number = param.pullRequest.number; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the release type but there was a problem identifying the issue.`], - })); - return result; - } - const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); - if (description === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the release type but there was a problem getting the description.`], - })); - return result; - } - const releaseType = (0, content_utils_1.extractReleaseType)('Release Type', description); - if (releaseType === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the release type but there was a problem identifying the type.`], - })); - return result; - } - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - payload: { - releaseType: releaseType, - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } -} -exports.GetReleaseTypeUseCase = GetReleaseTypeUseCase; + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) -/***/ }), + // 11. Let client be this's relevant settings object. -/***/ 3827: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 12. Run this step in parallel: -"use strict"; + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GetReleaseVersionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class GetReleaseVersionUseCase { - constructor() { - this.taskId = 'GetReleaseVersionUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - let number = -1; - if (param.isSingleAction) { - number = param.singleAction.issue; - } - else if (param.isIssue) { - number = param.issue.number; - } - else if (param.isPullRequest) { - number = param.pullRequest.number; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem identifying the issue.`], - })); - return result; - } - const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); - if (description === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem getting the description.`], - })); - return result; - } - const releaseVersion = (0, content_utils_1.extractVersion)('Release Version', description); - if (releaseVersion === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - })); - return result; - } - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - payload: { - releaseVersion: releaseVersion, - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; - } -} -exports.GetReleaseVersionUseCase = GetReleaseVersionUseCase; + // 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. -/***/ 65107: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } -"use strict"; + /** + * @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) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UpdateTitleUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class UpdateTitleUseCase { - constructor() { - this.taskId = 'UpdateTitleUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.isIssue) { - if (param.emoji.emojiLabeledTitle) { - let _title = await this.issueRepository.getTitle(param.owner, param.repo, param.issue.number, param.tokens.token) ?? param.issue.title; - let _version = ''; - if (param.release.active) { - _version = param.release.version ?? 'Unknown Version'; - } - else if (param.hotfix.active) { - _version = param.hotfix.version ?? 'Unknown Version'; - } - const title = await this.issueRepository.updateTitleIssueFormat(param.owner, param.repo, _version, _title, param.issue.number, param.issue.branchManagementAlways, param.emoji.branchManagementEmoji, param.labels, param.tokens.token); - if (title) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The issue's title was updated from \`${_title}\` to \`${title}\`.`, - ] - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - else if (param.isPullRequest) { - if (param.emoji.emojiLabeledTitle) { - const issueTitle = await this.issueRepository.getTitle(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (issueTitle === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update title, but there was a problem.`, - ], - })); - return result; - } - const title = await this.issueRepository.updateTitlePullRequestFormat(param.owner, param.repo, param.pullRequest.title, issueTitle, param.issueNumber, param.pullRequest.number, false, '', param.labels, param.tokens.token); - if (title) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The pull request's title was updated from \`${param.pullRequest.title}\` to \`${title}\`.`, - ] - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update title, but there was a problem.`, - ], - error: error, - })); - } - return result; + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }) } -} -exports.UpdateTitleUseCase = UpdateTitleUseCase; + 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') + } + } -/***/ 53115: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + let reasonByteLength = 0 -"use strict"; + // 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) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AssignMemberToIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class AssignMemberToIssueUseCase { - constructor() { - this.taskId = 'AssignMemberToIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const desiredAssigneesCount = param.isIssue ? - param.issue.desiredAssigneesCount : param.pullRequest.desiredAssigneesCount; - const number = param.isIssue ? param.issue.number : param.pullRequest.number; - const result = []; - try { - (0, logger_1.logDebugInfo)(`#${number} needs ${desiredAssigneesCount} assignees.`); - const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); - const currentMembers = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); - let remainingAssignees = desiredAssigneesCount - currentMembers.length; - const pullRequestCreatorIsTeamMember = param.isPullRequest - && param.pullRequest.creator.length > 0 - && currentProjectMembers.indexOf(param.pullRequest.creator) > -1 - && !currentMembers.includes(param.pullRequest.creator); - const issueCreatorIsTeamMember = param.isIssue - && param.issue.creator.length > 0 - && currentProjectMembers.indexOf(param.issue.creator) > -1 - && !currentMembers.includes(param.issue.creator); - /** - * Assign PR creator if applicable - */ - if (pullRequestCreatorIsTeamMember) { - const creator = param.pullRequest.creator; - await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); - (0, logger_1.logDebugInfo)(`Assigned PR creator @${creator} to #${number}.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`The pull request was assigned to @${creator} (creator).`], - })); - remainingAssignees--; // Reduce the count of required assignees - } - else if (issueCreatorIsTeamMember) { - const creator = param.issue.creator; - await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); - (0, logger_1.logDebugInfo)(`Assigned Issue creator @${creator} to #${number}.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`The issue was assigned to @${creator} (creator).`], - })); - remainingAssignees--; // Reduce the count of required assignees - } - /** - * Exit if no more assignees are needed - */ - if (remainingAssignees <= 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return result; - } - /** - * Assign remaining members randomly - */ - const members = await this.projectRepository.getRandomMembers(param.owner, remainingAssignees, currentMembers, param.tokens.token); - if (members.length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to assign members to issue, but no one was found.`], - })); - return result; - } - const membersAdded = await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, members, param.tokens.token); - for (const member of membersAdded) { - if (members.includes(member)) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - param.isIssue ? `The issue was assigned to @${member}.` : `The pull request was assigned to @${member}.`, - ], - })); - } - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to assign members to issue.`], - error: error, - })); + + // 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 } - return result; - } -} -exports.AssignMemberToIssueUseCase = AssignMemberToIssueUseCase; + }) + // 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) -/***/ 46275: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) -"use strict"; + data = webidl.converters.WebSocketSendData(data) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AssignReviewersToIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const pull_request_repository_1 = __nccwpck_require__(20634); -const logger_1 = __nccwpck_require__(38836); -class AssignReviewersToIssueUseCase { - constructor() { - this.taskId = 'AssignReviewersToIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); + // 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') } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const desiredReviewersCount = param.pullRequest.desiredReviewersCount; - const number = param.pullRequest.number; - const result = []; - try { - (0, logger_1.logDebugInfo)(`#${number} needs ${desiredReviewersCount} reviewers.`); - const currentReviewers = await this.pullRequestRepository.getCurrentReviewers(param.owner, param.repo, number, param.tokens.token); - const currentAssignees = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); - if (currentReviewers.length >= desiredReviewersCount) { - /** - * No more assignees needed - */ - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return result; - } - const missingReviewers = desiredReviewersCount - currentReviewers.length; - (0, logger_1.logDebugInfo)(`#${number} needs ${missingReviewers} more reviewers.`); - const excludeForReview = []; - excludeForReview.push(param.pullRequest.creator); - excludeForReview.push(...currentReviewers); - excludeForReview.push(...currentAssignees); - const members = await this.projectRepository.getRandomMembers(param.owner, missingReviewers, excludeForReview, param.tokens.token); - if (members.length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to assign members as reviewers to pull request, but no one was found.`, - ], - })); - return result; - } - const reviewersAdded = await this.pullRequestRepository.addReviewersToPullRequest(param.owner, param.repo, number, members, param.tokens.token); - for (const member of reviewersAdded) { - if (members.indexOf(member) > -1) - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `@${member} was requested to review the pull request.`, - ], - })); - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to assign members to issue.`, - ], - error: error, - })); - } - return result; + + // 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 } -} -exports.AssignReviewersToIssueUseCase = AssignReviewersToIssueUseCase; + /** @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. -/***/ 151: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) -"use strict"; + 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. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckPriorityIssueSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckPriorityIssueSizeUseCase { - constructor() { - this.taskId = 'CheckPriorityIssueSizeUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const priority = param.labels.priorityLabelOnIssue; - if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - let priorityLabel = ``; - if (priority === param.labels.priorityHigh) { - priorityLabel = `P0`; - } - else if (priority === param.labels.priorityMedium) { - priorityLabel = `P1`; - } - else if (priority === param.labels.priorityLow) { - priorityLabel = `P2`; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - (0, logger_1.logDebugInfo)(`Priority: ${priority}`); - (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); - for (const project of param.project.getProjects()) { - const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.issueNumber, priorityLabel, param.tokens.token); - if (success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, - ], - })); - } - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the priority of the issue, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; - } -} -exports.CheckPriorityIssueSizeUseCase = CheckPriorityIssueSizeUseCase; + 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. -/***/ 35137: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const frame = new WebsocketFrameSend() -"use strict"; + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloseIssueAfterMergingUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -class CloseIssueAfterMergingUseCase { - constructor() { - this.taskId = 'CloseIssueAfterMergingUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.removeBranches = async (supabaseRepository, param, branch) => { - const result = []; - if (!supabaseRepository) { - return result; - } - try { - await supabaseRepository.removeChunksByBranch(param.owner, param.repo, branch); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `AI index was removed from \`${branch}\`.`, - ] - })); - } - catch (error) { - (0, logger_1.logError)(`Error removing chunks: ${JSON.stringify(error, null, 2)}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `There was an error removing the AI index from \`${branch}\`.`, - ], - errors: [ - JSON.stringify(error, null, 2), - ], - })); - } - return result; - }; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - let supabaseRepository = undefined; - if (param.supabaseConfig) { - supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - } - const result = []; - try { - const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (closed) { - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was closed after merging #${param.pullRequest.number}.`, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `#${param.issueNumber} was automatically closed after merging this pull request.` - ] - })); - result.push(...await this.removeBranches(supabaseRepository, param, param.pullRequest.head.replace('refs/heads/', ''))); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to close issue #${param.issueNumber}, but there was a problem.`, - ], - error: error, - })); - } - return result; + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) } -} -exports.CloseIssueAfterMergingUseCase = CloseIssueAfterMergingUseCase; + } + get readyState () { + webidl.brandCheck(this, WebSocket) -/***/ }), + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } -/***/ 97826: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) -"use strict"; + return this.#bufferedAmount + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloseNotAllowedIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class CloseNotAllowedIssueUseCase { - constructor() { - this.taskId = 'CloseNotAllowedIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (closed) { - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue has been closed because the author is not a member of the project. The user may be banned if the fact is repeated.`, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `#${param.issueNumber} was automatically closed because the author is not a member of the project.` - ] - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to close issue #${param.issueNumber}, but there was a problem.`, - ], - error: error, - })); - } - return result; - } -} -exports.CloseNotAllowedIssueUseCase = CloseNotAllowedIssueUseCase; + 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) -/***/ 75678: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this.#extensions + } -"use strict"; + get protocol () { + webidl.brandCheck(this, WebSocket) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DeployAddedUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class DeployAddedUseCase { - constructor() { - this.taskId = 'DeployAddedUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.issue.labeled && param.issue.labelAdded === param.labels.deploy) { - (0, logger_1.logDebugInfo)(`Deploying requested.`); - if (param.release.active && param.release.branch !== undefined) { - const sanitizedTitle = param.issue.title - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - const description = param.issue.body?.match(/### Changelog\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; - const escapedDescription = description.replace(/\n/g, '\\n'); - const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; - const parameters = { - version: param.release.version, - title: sanitizedTitle, - changelog: escapedDescription, - issue: `${param.issue.number}`, - }; - await this.branchRepository.executeWorkflow(param.owner, param.repo, param.release.branch, param.workflows.release, parameters, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Executed release workflow [**${param.workflows.release}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.release}) on [**${param.release.branch}**](${releaseUrl}). + return this.#protocol + } -${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}` - ] - })); - } - else if (param.hotfix.active && param.hotfix.branch !== undefined) { - const sanitizedTitle = param.issue.title - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - const description = param.issue.body?.match(/### Hotfix Solution\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; - const escapedDescription = description.replace(/\n/g, '\\n'); - const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; - const parameters = { - version: param.hotfix.version, - title: sanitizedTitle, - changelog: escapedDescription, - issue: param.issue.number, - }; - await this.branchRepository.executeWorkflow(param.owner, param.repo, param.hotfix.branch, param.workflows.release, parameters, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Executed hotfix workflow [**${param.workflows.hotfix}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.hotfix}) on [**${param.hotfix.branch}**](${hotfixUrl}). + get onopen () { + webidl.brandCheck(this, WebSocket) -${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}\`` - ] - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to work with workflows, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) } -} -exports.DeployAddedUseCase = DeployAddedUseCase; + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } -/***/ }), + get onerror () { + webidl.brandCheck(this, WebSocket) -/***/ 8388: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this.#events.error + } -"use strict"; + set onerror (fn) { + webidl.brandCheck(this, WebSocket) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DeployedAddedUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -class DeployedAddedUseCase { - constructor() { - this.taskId = 'DeployedAddedUseCase'; + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.issue.labeled && param.issue.labelAdded === param.labels.deployed) { - (0, logger_1.logDebugInfo)(`Deploy complete.`); - if (param.release.active && param.release.branch !== undefined) { - const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Deploy complete from [${param.release.branch}](${releaseUrl})` - ] - })); - } - else if (param.hotfix.active && param.hotfix.branch !== undefined) { - const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Deploy complete from [${param.hotfix.branch}](${hotfixUrl})` - ] - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to complete the deployment, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + + 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) } -} -exports.DeployedAddedUseCase = DeployedAddedUseCase; + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } -/***/ }), + get onmessage () { + webidl.brandCheck(this, WebSocket) -/***/ 67528: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this.#events.message + } -"use strict"; + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LinkIssueProjectUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class LinkIssueProjectUseCase { - constructor() { - this.taskId = 'LinkIssueProjectUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - const columnName = param.project.getProjectColumnIssueCreated(); - try { - for (const project of param.project.getProjects()) { - const issueId = await this.issueRepository.getId(param.owner, param.repo, param.issue.number, param.tokens.token); - let actionDone = await this.projectRepository.linkContentId(project, issueId, param.tokens.token); - if (actionDone) { - /** - * Wait for 10 seconds to ensure the issue is linked to the project - */ - await new Promise(resolve => setTimeout(resolve, 10000)); - actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issue.number, columnName, param.tokens.token); - if (actionDone) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The issue was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, - ] - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - steps: [] - })); - } - } - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to link issue to project, but there was a problem.`, - ], - error: error, - })); - } - return result; + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) } -} -exports.LinkIssueProjectUseCase = LinkIssueProjectUseCase; + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } -/***/ }), + get binaryType () { + webidl.brandCheck(this, WebSocket) -/***/ 98203: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this[kBinaryType] + } -"use strict"; + set binaryType (type) { + webidl.brandCheck(this, WebSocket) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MoveIssueToInProgressUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class MoveIssueToInProgressUseCase { - constructor() { - this.taskId = 'MoveIssueToInProgressUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - const columnName = param.project.getProjectColumnIssueInProgress(); - try { - for (const project of param.project.getProjects()) { - const success = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issueNumber, columnName, param.tokens.token); - if (success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Moved issue to \`${columnName}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, - ], - })); - } - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to move the issue to \`${columnName}\`, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type } -} -exports.MoveIssueToInProgressUseCase = MoveIssueToInProgressUseCase; + } + /** + * @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() + }) -/***/ 84423: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + response.socket.ws = this + this[kByteParser] = parser -"use strict"; + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN -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]; } }; + // 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 } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PrepareBranchesUseCase = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -const execute_script_use_case_1 = __nccwpck_require__(155); -const move_issue_to_in_progress_1 = __nccwpck_require__(98203); -class PrepareBranchesUseCase { - constructor() { - this.taskId = 'PrepareBranchesUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - this.duplicateChunksByBranch = async (supabaseRepository, param, sourceBranch, targetBranch) => { - const result = []; - if (!supabaseRepository) { - return result; - } - try { - await supabaseRepository.duplicateChunksByBranch(param.owner, param.repo, sourceBranch, targetBranch); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `AI index was duplicated from \`${sourceBranch}\` to \`${targetBranch}\`.`, - ] - })); - } - catch (error) { - (0, logger_1.logError)(`Error duplicating chunks: ${JSON.stringify(error, null, 2)}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `There was an error duplicating the AI index from \`${sourceBranch}\` to \`${targetBranch}\`.`, - ], - errors: [ - JSON.stringify(error, null, 2), - ], - })); - } - return result; - }; + + // 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 } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - let supabaseRepository = undefined; - if (param.supabaseConfig) { - supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - } - const result = []; - try { - const issueTitle = param.issue.title; - if (!param.labels.isMandatoryBranchedLabel && issueTitle.length === 0) { - core.setFailed('Issue title not available.'); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - reminders: [ - `Tried to check the title but no one was found.` - ] - })); - return result; - } - /** - * Fetch all branches/tags - */ - await this.branchRepository.fetchRemoteBranches(); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `Take a coffee break while you work ā˜•.` - ] - })); - const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); - (0, logger_1.logDebugInfo)('Available branches:'); - branches.forEach(branch => { - (0, logger_1.logDebugInfo)(`- ${branch}`); - }); - if (param.hotfix.active) { - if (param.hotfix.baseVersion !== undefined && param.hotfix.version !== undefined && param.hotfix.branch !== undefined && param.hotfix.baseBranch !== undefined) { - const branchOid = await this.branchRepository.getCommitTag(param.hotfix.baseVersion); - const tagUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.baseBranch}`; - const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; - (0, logger_1.logDebugInfo)(`Tag branch: ${param.hotfix.baseBranch}`); - (0, logger_1.logDebugInfo)(`Hotfix branch: ${param.hotfix.branch}`); - param.currentConfiguration.parentBranch = param.hotfix.baseBranch; - param.currentConfiguration.hotfixBranch = param.hotfix.branch; - param.currentConfiguration.workingBranch = param.hotfix.branch; - if (branches.indexOf(param.hotfix.branch) === -1) { - const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.hotfix.baseBranch, param.hotfix.branch, param.issueNumber, branchOid, param.tokens.token); - if (linkResult[linkResult.length - 1].success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The tag [**${param.hotfix.baseBranch}**](${tagUrl}) was used to create the branch [**${param.hotfix.branch}**](${hotfixUrl})`, - ], - })); - (0, logger_1.logDebugInfo)(`Hotfix branch successfully linked to issue: ${JSON.stringify(linkResult)}`); - result.push(...await this.duplicateChunksByBranch(supabaseRepository, param, param.branches.main, param.hotfix.branch)); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch [**${param.hotfix.branch}**](${hotfixUrl}) already exists and will not be created from the tag [**${param.hotfix.baseBranch}**](${tagUrl}).`, - ], - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to create a hotfix but no tag was found.`, - ] - })); - return result; - } - } - else if (param.release.active) { - if (param.release.version !== undefined && param.release.branch !== undefined) { - param.currentConfiguration.releaseBranch = param.release.branch; - param.currentConfiguration.workingBranch = param.release.branch; - (0, logger_1.logDebugInfo)(`Release branch: ${param.release.branch}`); - param.currentConfiguration.parentBranch = param.branches.development; - const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; - const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; - const mainUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.defaultBranch}`; - if (branches.indexOf(param.release.branch) === -1) { - const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.branches.development, param.release.branch, param.issueNumber, undefined, param.tokens.token); - const lastAction = linkResult[linkResult.length - 1]; - const reminders = []; - if (lastAction.success) { - const branchName = lastAction.payload.newBranchName; - let commitPrefix = ''; - if (param.commitPrefixBuilder.length > 0) { - param.commitPrefixBuilderParams = { - branchName: branchName, - }; - const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); - const prefixResult = await executor.invoke(param); - commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; - } - reminders.push(`Before deploying, apply any change needed in [**${param.release.branch}**](${releaseUrl}): -> \`\`\`bash -> git fetch -v && git checkout ${param.release.branch} -> \`\`\` -> -> Version files, changelogs..`); - if (commitPrefix.length > 0) { - reminders.push(`Commit the needed changes with this prefix: -> \`\`\` ->${commitPrefix} -> \`\`\``); - } - reminders.push(...[ - `Create the tag version in [**${param.release.branch}**](${releaseUrl}). -> Avoid using \`git merge --squash\`, otherwise the created tag will be lost.`, - `Add the **${param.labels.deploy}** label to run the \`${param.workflows.release}\` workflow.`, - `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). -> **Quick actions:** -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, - ]); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch [**${param.branches.development}**](${developmentUrl}) was used to create the branch [**${param.release.branch}**](${releaseUrl})`, - ], - reminders: reminders, - })); - (0, logger_1.logDebugInfo)(`Release branch successfully linked to issue: ${JSON.stringify(linkResult)}`); - result.push(...await this.duplicateChunksByBranch(supabaseRepository, param, param.branches.development, param.release.branch)); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). -> **Quick actions:** -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, - ], - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to create a release but no release version was found.`, - ] - })); - } - return result; - } - (0, logger_1.logDebugInfo)(`Branch type: ${param.managementBranch}`); - const branchesResult = await this.branchRepository.manageBranches(param, param.owner, param.repo, param.issueNumber, issueTitle, param.managementBranch, param.branches.development, param.hotfix?.branch, param.hotfix.active, param.tokens.token); - result.push(...branchesResult); - const lastAction = branchesResult[branchesResult.length - 1]; - if (lastAction.success && lastAction.executed) { - const branchName = lastAction.payload.newBranchName; - param.currentConfiguration.workingBranch = branchName; - let commitPrefix = ''; - if (param.commitPrefixBuilder.length > 0) { - param.commitPrefixBuilderParams = { - branchName: branchName, - }; - const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); - const prefixResult = await executor.invoke(param); - commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; - } - const rename = lastAction.payload.baseBranchName.indexOf(`${param.branches.featureTree}/`) > -1 - || lastAction.payload.baseBranchName.indexOf(`${param.branches.bugfixTree}/`) > -1; - let step; - let reminder; - if (rename) { - const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; - step = `The branch **${lastAction.payload.baseBranchName}** was renamed to [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; - reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${param.branches.development}\`](${developmentUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${lastAction.payload.newBranchName}?expand=1)`; - } - else { - step = `The branch [**${lastAction.payload.baseBranchName}**](${lastAction.payload.baseBranchUrl}) was used to create [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; - reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${lastAction.payload.baseBranchName}...${lastAction.payload.newBranchName}?expand=1)`; - } - const reminders = []; - reminders.push(`Check out the branch: -> \`\`\`bash -> git fetch -v && git checkout ${lastAction.payload.newBranchName} -> \`\`\``); - if (commitPrefix.length > 0) { - reminders.push(`Commit the needed changes with this prefix: -> \`\`\` ->${commitPrefix} -> \`\`\``); - } - reminders.push(reminder); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - step, - ], - reminders: reminders, - })); - if (param.hotfix.active) { - const mainBranchUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.main}`; - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `After merging into [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}), open a Pull Request from [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}) to [\`${param.branches.main}\`](${mainBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${lastAction.payload.baseBranchName}?expand=1)`, - `After merging into [\`${param.branches.main}\`](${mainBranchUrl}), create the tag \`${param.hotfix.version}\`.`, - ] - })); - } - result.push(...await this.duplicateChunksByBranch(supabaseRepository, param, param.branches.development, lastAction.payload.newBranchName)); - await new Promise(resolve => setTimeout(resolve, 10000)); - result.push(...await new move_issue_to_in_progress_1.MoveIssueToInProgressUseCase().invoke(param)); - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to prepare the hotfix branch to the issue, but there was a problem.`, - ], - error: error, - })); - } - return result; + + // 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 } -exports.PrepareBranchesUseCase = PrepareBranchesUseCase; /***/ }), -/***/ 92354: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5030: +/***/ ((__unused_webpack_module, exports) => { "use strict"; + Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RemoveIssueBranchesUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const logger_1 = __nccwpck_require__(38836); -/** - * Remove any branch created for this issue - */ -class RemoveIssueBranchesUseCase { - constructor() { - this.taskId = 'RemoveIssueBranchesUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); + +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + + if (typeof process === "object" && process.version !== undefined) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + + return ""; +} + +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 2940: +/***/ ((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] } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; - const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); - for (const type of branchTypes) { - (0, logger_1.logDebugInfo)(`Checking branch type ${type}`); - let branchName = ''; - const prefix = `${type}/${param.issueNumber}-`; - (0, logger_1.logDebugInfo)(`Checking prefix ${prefix}`); - const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); - if (!matchingBranch) - continue; - branchName = matchingBranch; - const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); - if (removed) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch \`${branchName}\` was removed.`, - ], - })); - if (param.previousConfiguration?.branchType === param.branches.hotfixTree) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `Determine if the \`${param.branches.hotfixTree}\` branch is no longer required and can be removed.`, - ], - })); - } - } - } - } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update issue's title, but there was a problem.`, - ], - error: error, - })); - } - return results; + 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 + } } -exports.RemoveIssueBranchesUseCase = RemoveIssueBranchesUseCase; /***/ }), -/***/ 90773: +/***/ 3752: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -143525,402 +59638,564 @@ var __importStar = (this && this.__importStar) || (function () { return result; }; })(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RemoveNotNeededBranchesUseCase = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const logger_1 = __nccwpck_require__(38836); -class RemoveNotNeededBranchesUseCase { - constructor() { - this.taskId = 'RemoveNotNeededBranchesUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const issueTitle = param.issue.title; - if (issueTitle.length === 0) { - core.setFailed('Issue title not available.'); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Tried to remove not needed branches related to the issue, but the issue title was not found.`, - ], - })); - return result; - } - const sanitizedTitle = this.branchRepository.formatBranchName(issueTitle, param.issueNumber); - const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); - const finalBranch = `${param.managementBranch}/${param.issueNumber}-${sanitizedTitle}`; - const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; - for (const type of branchTypes) { - let branchName = `${type}/${param.issueNumber}-${sanitizedTitle}`; - const prefix = `${type}/${param.issueNumber}-`; - if (type !== param.managementBranch) { - const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); - if (!matchingBranch) { - continue; - } - branchName = matchingBranch; - const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); - if (removed) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch \`${branchName}\` was removed.`, - ], - })); - } - else { - (0, logger_1.logError)(`Error deleting ${branchName}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to remove not needed branch \`${branchName}\`, but there was a problem.`, - ], - })); - } - } - else { - for (const branch of branches) { - if (branch.indexOf(prefix) > -1 && branch !== finalBranch) { - const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branch, param.tokens.token); - if (removed) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch \`${branch}\` was removed.`, - ], - })); - } - else { - (0, logger_1.logError)(`Error deleting ${branch}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to remove not needed branch \`${branch}\`, but there was a problem.`, - ], - })); - } - } - } - } - } - } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to remove not needed branches related to the issue, but there was a problem.`, - ], - error: error, - })); - } - return result; - } -} -exports.RemoveNotNeededBranchesUseCase = RemoveNotNeededBranchesUseCase; - - -/***/ }), - -/***/ 81652: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UpdateIssueTypeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class UpdateIssueTypeUseCase { - constructor() { - this.taskId = 'UpdateIssueTypeUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); +exports.mainRun = mainRun; +const core = __importStar(__nccwpck_require__(2186)); +const commit_use_case_1 = __nccwpck_require__(5016); +const issue_comment_use_case_1 = __nccwpck_require__(854); +const issue_use_case_1 = __nccwpck_require__(8675); +const pull_request_review_comment_use_case_1 = __nccwpck_require__(7883); +const pull_request_use_case_1 = __nccwpck_require__(5041); +const single_action_use_case_1 = __nccwpck_require__(6479); +const logger_1 = __nccwpck_require__(8836); +const constants_1 = __nccwpck_require__(8593); +const chalk_1 = __importDefault(__nccwpck_require__(7037)); +const boxen_1 = __importDefault(__nccwpck_require__(6192)); +const queue_utils_1 = __nccwpck_require__(9800); +async function mainRun(execution) { + const results = []; + await execution.setup(); + if (!execution.welcome) { + /** + * Wait for previous runs to finish + */ + await (0, queue_utils_1.waitForPreviousRuns)(execution).catch((err) => { + (0, logger_1.logError)(`Error waiting for previous runs: ${err}`); + process.exit(1); + }); } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - await this.issueRepository.setIssueType(param.owner, param.repo, param.issueNumber, param.labels, param.issueTypes, param.tokens.token); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update issue type, but there was a problem.`, - ], - error: error, - })); + if (execution.runnedByToken) { + if (execution.isSingleAction && execution.singleAction.validSingleAction) { + (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Executing single action.`); + results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); + return results; } - return result; - } -} -exports.UpdateIssueTypeUseCase = UpdateIssueTypeUseCase; - - -/***/ }), - -/***/ 90465: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckIssueCommentLanguageUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class CheckIssueCommentLanguageUseCase { - constructor() { - this.taskId = 'CheckIssueCommentLanguageUseCase'; - this.aiRepository = new ai_repository_1.AiRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.translatedKey = ``; + (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Ignoring.`); + return results; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - const commentBody = param.issue.commentBody; - if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; + if (execution.issueNumber === -1) { + if (execution.isSingleAction && execution.singleAction.isSingleActionWithoutIssue) { + results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); } - const locale = param.locale.issue; - let prompt = ` - You are a helpful assistant that checks if the text is written in ${locale}. - - Instructions: - 1. Analyze the provided text - 2. If the text is written in ${locale}, respond with exactly "done" - 3. If the text is written in any other language, respond with exactly "must_translate" - 4. Do not provide any explanation or additional text - - The text is: ${commentBody} - `; - let result = await this.aiRepository.ask(param.ai, prompt); - if (result === "done") { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return results; + else { + (0, logger_1.logInfo)(`Issue number not found. Skipping.`); } - prompt = ` -You are a helpful assistant that translates the text to ${locale}. - -Instructions: -1. Translate the text to ${locale} -2. Do not provide any explanation or additional text -3. Return the translated text only - -The text is: ${commentBody} - `; - result = await this.aiRepository.ask(param.ai, prompt); - const translatedCommentBody = `${result} -> ${commentBody} -${this.translatedKey} -`; - await this.issueRepository.updateComment(param.owner, param.repo, param.issue.number, param.issue.commentId, translatedCommentBody, param.tokens.token); return results; } -} -exports.CheckIssueCommentLanguageUseCase = CheckIssueCommentLanguageUseCase; - - -/***/ }), - -/***/ 38129: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckChangesPullRequestSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckChangesPullRequestSizeUseCase { - constructor() { - this.taskId = 'CheckChangesPullRequestSizeUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); + if (execution.welcome) { + (0, logger_1.logInfo)((0, boxen_1.default)(chalk_1.default.cyan(execution.welcome.title) + '\n' + + execution.welcome.messages.map(message => chalk_1.default.gray(message)).join('\n'), { + padding: 1, + margin: 1, + borderStyle: 'round', + borderColor: 'cyan', + title: constants_1.TITLE, + titleAlignment: 'center' + })); } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, param.pullRequest.head, param.pullRequest.base, param.sizeThresholds, param.labels, param.tokens.token); - (0, logger_1.logDebugInfo)(`Size: ${size}`); - (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); - (0, logger_1.logDebugInfo)(`Reason: ${reason}`); - (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnPullRequest}`); - if (param.labels.sizedLabelOnPullRequest !== size) { - /** - * Even if this is for pull reuqets, we are getting the issue labels for having a mirror of the issue labels on the pull request. - */ - const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); - labelNames.push(size); - await this.issueRepository.setLabels(param.owner, param.repo, param.pullRequest.number, labelNames, param.tokens.token); - for (const project of param.project.getProjects()) { - await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.pullRequest.number, githubSize, param.tokens.token); - } - (0, logger_1.logDebugInfo)(`Updated labels on pull request #${param.pullRequest.number}:`); - (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `${reason}, so the pull request was resized to ${size}.`, - ], - })); + try { + if (execution.isSingleAction) { + results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); + } + else if (execution.isIssue) { + if (execution.issue.isIssueComment) { + results.push(...await new issue_comment_use_case_1.IssueCommentUseCase().invoke(execution)); } else { - (0, logger_1.logDebugInfo)(`The pull request is already at the correct size.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); + results.push(...await new issue_use_case_1.IssueUseCase().invoke(execution)); + } + } + else if (execution.isPullRequest) { + if (execution.pullRequest.isPullRequestReviewComment) { + results.push(...await new pull_request_review_comment_use_case_1.PullRequestReviewCommentUseCase().invoke(execution)); + } + else { + results.push(...await new pull_request_use_case_1.PullRequestUseCase().invoke(execution)); } } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the size of the changes, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); + else if (execution.isPush) { + results.push(...await new commit_use_case_1.CommitUseCase().invoke(execution)); } - return result; + else { + core.setFailed(`Action not handled.`); + } + return results; + } + catch (error) { + core.setFailed(error.message); + return []; } } -exports.CheckChangesPullRequestSizeUseCase = CheckChangesPullRequestSizeUseCase; /***/ }), -/***/ 67383: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7002: +/***/ (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 })); -exports.CheckPriorityPullRequestSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckPriorityPullRequestSizeUseCase { - constructor() { - this.taskId = 'CheckPriorityPullRequestSizeUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); +exports.runLocalAction = runLocalAction; +const chalk_1 = __importDefault(__nccwpck_require__(7037)); +const ai_1 = __nccwpck_require__(4470); +const branches_1 = __nccwpck_require__(5308); +const emoji_1 = __nccwpck_require__(9463); +const execution_1 = __nccwpck_require__(7550); +const hotfix_1 = __nccwpck_require__(7341); +const images_1 = __nccwpck_require__(1721); +const issue_1 = __nccwpck_require__(2632); +const issue_types_1 = __nccwpck_require__(1975); +const labels_1 = __nccwpck_require__(818); +const locale_1 = __nccwpck_require__(2152); +const projects_1 = __nccwpck_require__(1938); +const pull_request_1 = __nccwpck_require__(4179); +const release_1 = __nccwpck_require__(2551); +const single_action_1 = __nccwpck_require__(8024); +const size_threshold_1 = __nccwpck_require__(3835); +const size_thresholds_1 = __nccwpck_require__(8237); +const supabase_config_1 = __nccwpck_require__(149); +const tokens_1 = __nccwpck_require__(3421); +const welcome_1 = __nccwpck_require__(9471); +const workflows_1 = __nccwpck_require__(8553); +const project_repository_1 = __nccwpck_require__(7917); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +const yml_utils_1 = __nccwpck_require__(8198); +const common_action_1 = __nccwpck_require__(3752); +const boxen_1 = __importDefault(__nccwpck_require__(6192)); +async function runLocalAction(additionalParams) { + const projectRepository = new project_repository_1.ProjectRepository(); + const actionInputs = (0, yml_utils_1.getActionInputsWithDefaults)(); + /** + * Debug + */ + const debug = (additionalParams[constants_1.INPUT_KEYS.DEBUG] ?? actionInputs[constants_1.INPUT_KEYS.DEBUG]) == 'true'; + /** + * Welcome + */ + const welcomeTitle = additionalParams[constants_1.INPUT_KEYS.WELCOME_TITLE] ?? actionInputs[constants_1.INPUT_KEYS.WELCOME_TITLE]; + const welcomeMessages = additionalParams[constants_1.INPUT_KEYS.WELCOME_MESSAGES] ?? actionInputs[constants_1.INPUT_KEYS.WELCOME_MESSAGES]; + /** + * Single action + */ + const singleAction = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION]; + const singleActionIssue = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]; + const singleActionVersion = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION]; + const singleActionTitle = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE]; + const singleActionChangelog = additionalParams[constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG] ?? actionInputs[constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG]; + /** + * Tokens + */ + const token = additionalParams[constants_1.INPUT_KEYS.TOKEN] ?? actionInputs[constants_1.INPUT_KEYS.TOKEN]; + /** + * AI + */ + const openrouterApiKey = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_API_KEY] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_API_KEY]; + const openrouterModel = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_MODEL] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_MODEL]; + const aiPullRequestDescription = (additionalParams[constants_1.INPUT_KEYS.AI_PULL_REQUEST_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.AI_PULL_REQUEST_DESCRIPTION]) === 'true'; + const aiMembersOnly = (additionalParams[constants_1.INPUT_KEYS.AI_MEMBERS_ONLY] ?? actionInputs[constants_1.INPUT_KEYS.AI_MEMBERS_ONLY]) === 'true'; + const aiIncludeReasoning = (additionalParams[constants_1.INPUT_KEYS.AI_INCLUDE_REASONING] ?? actionInputs[constants_1.INPUT_KEYS.AI_INCLUDE_REASONING]) === 'true'; + const aiIgnoreFilesInput = additionalParams[constants_1.INPUT_KEYS.AI_IGNORE_FILES] ?? actionInputs[constants_1.INPUT_KEYS.AI_IGNORE_FILES]; + const aiIgnoreFiles = aiIgnoreFilesInput + .split(',') + .map(path => path.trim()) + .filter(path => path.length > 0); + // Provider routing configuration + const openRouterProviderOrderInput = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER]; + const openRouterProviderOrder = openRouterProviderOrderInput + .split(',') + .map(provider => provider.trim()) + .filter(provider => provider.length > 0); + const openRouterProviderAllowFallbacks = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS]) === 'true'; + const openRouterProviderRequireParameters = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS]) === 'true'; + const openRouterProviderDataCollection = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION]); + const openRouterProviderIgnoreInput = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE]; + const openRouterProviderIgnore = openRouterProviderIgnoreInput + .split(',') + .map(provider => provider.trim()) + .filter(provider => provider.length > 0); + const openRouterProviderQuantizationsInput = additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS]; + const openRouterProviderQuantizations = openRouterProviderQuantizationsInput + .split(',') + .map(level => level.trim()) + .filter(level => level.length > 0); + const openRouterProviderSort = (additionalParams[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT] ?? actionInputs[constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT]); + const providerRouting = { + ...(openRouterProviderOrder.length > 0 && { order: openRouterProviderOrder }), + ...(openRouterProviderAllowFallbacks !== undefined && { allow_fallbacks: openRouterProviderAllowFallbacks }), + ...(openRouterProviderRequireParameters !== undefined && { require_parameters: openRouterProviderRequireParameters }), + ...(openRouterProviderDataCollection && { data_collection: openRouterProviderDataCollection }), + ...(openRouterProviderIgnore.length > 0 && { ignore: openRouterProviderIgnore }), + ...(openRouterProviderQuantizations.length > 0 && { quantizations: openRouterProviderQuantizations }), + ...(openRouterProviderSort && { sort: openRouterProviderSort }) + }; + /** + * Projects Details + */ + const projectIdsInput = additionalParams[constants_1.INPUT_KEYS.PROJECT_IDS] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_IDS]; + const projectIds = projectIdsInput + .split(',') + .map(id => id.trim()) + .filter(id => id.length > 0); + const projects = []; + for (const projectId of projectIds) { + const detail = await projectRepository.getProjectDetail(projectId, token); + projects.push(detail); } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const priority = param.labels.priorityLabelOnIssue; - if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - let priorityLabel = ``; - if (priority === param.labels.priorityHigh) { - priorityLabel = `P0`; - } - else if (priority === param.labels.priorityMedium) { - priorityLabel = `P1`; - } - else if (priority === param.labels.priorityLow) { - priorityLabel = `P2`; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - (0, logger_1.logDebugInfo)(`Priority: ${priority}`); - (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); - for (const project of param.project.getProjects()) { - const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.pullRequest.number, priorityLabel, param.tokens.token); - if (success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, - ], - })); - } - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the priority of the issue, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + const projectColumnIssueCreated = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_CREATED] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_CREATED]; + const projectColumnPullRequestCreated = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_CREATED] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_CREATED]; + const projectColumnIssueInProgress = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_IN_PROGRESS] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_IN_PROGRESS]; + const projectColumnPullRequestInProgress = additionalParams[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS] ?? actionInputs[constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS]; + /** + * Images + */ + const imagesOnIssue = (additionalParams[constants_1.INPUT_KEYS.IMAGES_ON_ISSUE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ON_ISSUE]) === 'true'; + const imagesOnPullRequest = (additionalParams[constants_1.INPUT_KEYS.IMAGES_ON_PULL_REQUEST] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ON_PULL_REQUEST]) === 'true'; + const imagesOnCommit = (additionalParams[constants_1.INPUT_KEYS.IMAGES_ON_COMMIT] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ON_COMMIT]) === 'true'; + const imagesIssueAutomaticInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_AUTOMATIC] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_AUTOMATIC]; + const imagesIssueAutomatic = imagesIssueAutomaticInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueAutomatic.length === 0) { + imagesIssueAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.automatic); + } + const imagesIssueFeatureInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_FEATURE]; + const imagesIssueFeature = imagesIssueFeatureInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueFeature.length === 0) { + imagesIssueFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.feature); + } + const imagesIssueBugfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_BUGFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_BUGFIX]; + const imagesIssueBugfix = imagesIssueBugfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueBugfix.length === 0) { + imagesIssueBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.bugfix); + } + const imagesIssueDocsInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_DOCS] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_DOCS]; + const imagesIssueDocs = imagesIssueDocsInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueDocs.length === 0) { + imagesIssueDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.docs); + } + const imagesIssueChoreInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_CHORE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_CHORE]; + const imagesIssueChore = imagesIssueChoreInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueChore.length === 0) { + imagesIssueChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.chore); + } + const imagesIssueReleaseInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_RELEASE]; + const imagesIssueRelease = imagesIssueReleaseInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueRelease.length === 0) { + imagesIssueRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.release); + } + const imagesIssueHotfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_ISSUE_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_ISSUE_HOTFIX]; + const imagesIssueHotfix = imagesIssueHotfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueHotfix.length === 0) { + imagesIssueHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.hotfix); + } + const imagesPullRequestAutomaticInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_AUTOMATIC] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_AUTOMATIC]; + const imagesPullRequestAutomatic = imagesPullRequestAutomaticInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestAutomatic.length === 0) { + imagesPullRequestAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.automatic); + } + const imagesPullRequestFeatureInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_FEATURE]; + const imagesPullRequestFeature = imagesPullRequestFeatureInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestFeature.length === 0) { + imagesPullRequestFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.feature); + } + const imagesPullRequestBugfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_BUGFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_BUGFIX]; + const imagesPullRequestBugfix = imagesPullRequestBugfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestBugfix.length === 0) { + imagesPullRequestBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.bugfix); + } + const imagesPullRequestReleaseInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_RELEASE]; + const imagesPullRequestRelease = imagesPullRequestReleaseInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestRelease.length === 0) { + imagesPullRequestRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.release); + } + const imagesPullRequestHotfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_HOTFIX]; + const imagesPullRequestHotfix = imagesPullRequestHotfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestHotfix.length === 0) { + imagesPullRequestHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.hotfix); + } + const imagesPullRequestDocsInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_DOCS] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_DOCS]; + const imagesPullRequestDocs = imagesPullRequestDocsInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestDocs.length === 0) { + imagesPullRequestDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.docs); + } + const imagesPullRequestChoreInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_CHORE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_CHORE]; + const imagesPullRequestChore = imagesPullRequestChoreInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestChore.length === 0) { + imagesPullRequestChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.chore); + } + const imagesCommitAutomaticInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_AUTOMATIC] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_AUTOMATIC]; + const imagesCommitAutomatic = imagesCommitAutomaticInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitAutomatic.length === 0) { + imagesCommitAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.automatic); + } + const imagesCommitFeatureInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_FEATURE]; + const imagesCommitFeature = imagesCommitFeatureInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitFeature.length === 0) { + imagesCommitFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.feature); + } + const imagesCommitBugfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_BUGFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_BUGFIX]; + const imagesCommitBugfix = imagesCommitBugfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitBugfix.length === 0) { + imagesCommitBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.bugfix); + } + const imagesCommitReleaseInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_RELEASE]; + const imagesCommitRelease = imagesCommitReleaseInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitRelease.length === 0) { + imagesCommitRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.release); + } + const imagesCommitHotfixInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_HOTFIX]; + const imagesCommitHotfix = imagesCommitHotfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitHotfix.length === 0) { + imagesCommitHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.hotfix); + } + const imagesCommitDocsInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_DOCS] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_DOCS]; + const imagesCommitDocs = imagesCommitDocsInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitDocs.length === 0) { + imagesCommitDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.docs); + } + const imagesCommitChoreInput = additionalParams[constants_1.INPUT_KEYS.IMAGES_COMMIT_CHORE] ?? actionInputs[constants_1.INPUT_KEYS.IMAGES_COMMIT_CHORE]; + const imagesCommitChore = imagesCommitChoreInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitChore.length === 0) { + imagesCommitChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.chore); + } + /** + * Workflows + */ + const releaseWorkflow = additionalParams[constants_1.INPUT_KEYS.RELEASE_WORKFLOW] ?? actionInputs[constants_1.INPUT_KEYS.RELEASE_WORKFLOW]; + const hotfixWorkflow = additionalParams[constants_1.INPUT_KEYS.HOTFIX_WORKFLOW] ?? actionInputs[constants_1.INPUT_KEYS.HOTFIX_WORKFLOW]; + /** + * Emoji-title + */ + const titleEmoji = (additionalParams[constants_1.INPUT_KEYS.EMOJI_LABELED_TITLE] ?? actionInputs[constants_1.INPUT_KEYS.EMOJI_LABELED_TITLE]) === 'true'; + const branchManagementEmoji = additionalParams[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_EMOJI] ?? actionInputs[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_EMOJI]; + /** + * Labels + */ + const branchManagementLauncherLabel = additionalParams[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_LAUNCHER_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_LAUNCHER_LABEL]; + const bugfixLabel = additionalParams[constants_1.INPUT_KEYS.BUGFIX_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.BUGFIX_LABEL]; + const bugLabel = additionalParams[constants_1.INPUT_KEYS.BUG_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.BUG_LABEL]; + const hotfixLabel = additionalParams[constants_1.INPUT_KEYS.HOTFIX_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.HOTFIX_LABEL]; + const enhancementLabel = additionalParams[constants_1.INPUT_KEYS.ENHANCEMENT_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.ENHANCEMENT_LABEL]; + const featureLabel = additionalParams[constants_1.INPUT_KEYS.FEATURE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.FEATURE_LABEL]; + const releaseLabel = additionalParams[constants_1.INPUT_KEYS.RELEASE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.RELEASE_LABEL]; + const questionLabel = additionalParams[constants_1.INPUT_KEYS.QUESTION_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.QUESTION_LABEL]; + const helpLabel = additionalParams[constants_1.INPUT_KEYS.HELP_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.HELP_LABEL]; + const deployLabel = additionalParams[constants_1.INPUT_KEYS.DEPLOY_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DEPLOY_LABEL]; + const deployedLabel = additionalParams[constants_1.INPUT_KEYS.DEPLOYED_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DEPLOYED_LABEL]; + const docsLabel = additionalParams[constants_1.INPUT_KEYS.DOCS_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DOCS_LABEL]; + const documentationLabel = additionalParams[constants_1.INPUT_KEYS.DOCUMENTATION_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.DOCUMENTATION_LABEL]; + const choreLabel = additionalParams[constants_1.INPUT_KEYS.CHORE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.CHORE_LABEL]; + const maintenanceLabel = additionalParams[constants_1.INPUT_KEYS.MAINTENANCE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.MAINTENANCE_LABEL]; + const priorityHighLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_HIGH_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_HIGH_LABEL]; + const priorityMediumLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_MEDIUM_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_MEDIUM_LABEL]; + const priorityLowLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_LOW_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_LOW_LABEL]; + const priorityNoneLabel = additionalParams[constants_1.INPUT_KEYS.PRIORITY_NONE_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.PRIORITY_NONE_LABEL]; + const sizeXxlLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_LABEL]; + const sizeXlLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_XL_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_LABEL]; + const sizeLLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_L_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_LABEL]; + const sizeMLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_M_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_LABEL]; + const sizeSLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_S_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_LABEL]; + const sizeXsLabel = additionalParams[constants_1.INPUT_KEYS.SIZE_XS_LABEL] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_LABEL]; + /** + * Issue Types + */ + const issueTypeBug = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG]; + const issueTypeBugDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_DESCRIPTION]; + const issueTypeBugColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_COLOR]; + const issueTypeHotfix = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX]; + const issueTypeHotfixDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_DESCRIPTION]; + const issueTypeHotfixColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_COLOR]; + const issueTypeFeature = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE]; + const issueTypeFeatureDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_DESCRIPTION]; + const issueTypeFeatureColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_COLOR]; + const issueTypeDocumentation = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION]; + const issueTypeDocumentationDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_DESCRIPTION]; + const issueTypeDocumentationColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_COLOR]; + const issueTypeMaintenance = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE]; + const issueTypeMaintenanceDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_DESCRIPTION]; + const issueTypeMaintenanceColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_COLOR]; + const issueTypeRelease = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE]; + const issueTypeReleaseDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_DESCRIPTION]; + const issueTypeReleaseColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_COLOR]; + const issueTypeQuestion = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION]; + const issueTypeQuestionDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_DESCRIPTION]; + const issueTypeQuestionColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_COLOR]; + const issueTypeHelp = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP]; + const issueTypeHelpDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_DESCRIPTION]; + const issueTypeHelpColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_COLOR]; + const issueTypeTask = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK]; + const issueTypeTaskDescription = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_DESCRIPTION] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_DESCRIPTION]; + const issueTypeTaskColor = additionalParams[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_COLOR] ?? actionInputs[constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_COLOR]; + /** + * Locale + */ + const issueLocale = additionalParams[constants_1.INPUT_KEYS.ISSUES_LOCALE] ?? actionInputs[constants_1.INPUT_KEYS.ISSUES_LOCALE] ?? locale_1.Locale.DEFAULT; + const pullRequestLocale = additionalParams[constants_1.INPUT_KEYS.PULL_REQUESTS_LOCALE] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUESTS_LOCALE] ?? locale_1.Locale.DEFAULT; + /** + * Size Thresholds + */ + const sizeXxlThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_LINES]) ?? 1000; + const sizeXxlThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_FILES]) ?? 20; + const sizeXxlThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_COMMITS]) ?? 10; + const sizeXlThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_LINES]) ?? 500; + const sizeXlThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_FILES]) ?? 10; + const sizeXlThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_COMMITS]) ?? 5; + const sizeLThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_LINES]) ?? 250; + const sizeLThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_FILES]) ?? 5; + const sizeLThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_COMMITS]) ?? 3; + const sizeMThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_LINES]) ?? 100; + const sizeMThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_FILES]) ?? 3; + const sizeMThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_COMMITS]) ?? 2; + const sizeSThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_LINES]) ?? 50; + const sizeSThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_FILES]) ?? 2; + const sizeSThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_COMMITS]) ?? 1; + const sizeXsThresholdLines = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_LINES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_LINES]) ?? 25; + const sizeXsThresholdFiles = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_FILES] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_FILES]) ?? 1; + const sizeXsThresholdCommits = parseInt(additionalParams[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_COMMITS] ?? actionInputs[constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_COMMITS]) ?? 1; + /** + * Branches + */ + const mainBranch = additionalParams[constants_1.INPUT_KEYS.MAIN_BRANCH] ?? actionInputs[constants_1.INPUT_KEYS.MAIN_BRANCH]; + const developmentBranch = additionalParams[constants_1.INPUT_KEYS.DEVELOPMENT_BRANCH] ?? actionInputs[constants_1.INPUT_KEYS.DEVELOPMENT_BRANCH]; + const featureTree = additionalParams[constants_1.INPUT_KEYS.FEATURE_TREE] ?? actionInputs[constants_1.INPUT_KEYS.FEATURE_TREE]; + const bugfixTree = additionalParams[constants_1.INPUT_KEYS.BUGFIX_TREE] ?? actionInputs[constants_1.INPUT_KEYS.BUGFIX_TREE]; + const hotfixTree = additionalParams[constants_1.INPUT_KEYS.HOTFIX_TREE] ?? actionInputs[constants_1.INPUT_KEYS.HOTFIX_TREE]; + const releaseTree = additionalParams[constants_1.INPUT_KEYS.RELEASE_TREE] ?? actionInputs[constants_1.INPUT_KEYS.RELEASE_TREE]; + const docsTree = additionalParams[constants_1.INPUT_KEYS.DOCS_TREE] ?? actionInputs[constants_1.INPUT_KEYS.DOCS_TREE]; + const choreTree = additionalParams[constants_1.INPUT_KEYS.CHORE_TREE] ?? actionInputs[constants_1.INPUT_KEYS.CHORE_TREE]; + /** + * Prefix builder + */ + let commitPrefixBuilder = additionalParams[constants_1.INPUT_KEYS.COMMIT_PREFIX_TRANSFORMS] ?? actionInputs[constants_1.INPUT_KEYS.COMMIT_PREFIX_TRANSFORMS] ?? ''; + if (commitPrefixBuilder.length === 0) { + commitPrefixBuilder = 'replace-slash'; + } + /** + * Issue + */ + const branchManagementAlways = (additionalParams[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_ALWAYS] ?? actionInputs[constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_ALWAYS]) === 'true'; + const reopenIssueOnPush = (additionalParams[constants_1.INPUT_KEYS.REOPEN_ISSUE_ON_PUSH] ?? actionInputs[constants_1.INPUT_KEYS.REOPEN_ISSUE_ON_PUSH]) === 'true'; + const issueDesiredAssigneesCount = parseInt(additionalParams[constants_1.INPUT_KEYS.DESIRED_ASSIGNEES_COUNT] ?? actionInputs[constants_1.INPUT_KEYS.DESIRED_ASSIGNEES_COUNT]) ?? 0; + /** + * Pull Request + */ + const pullRequestDesiredAssigneesCount = parseInt(additionalParams[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_ASSIGNEES_COUNT] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_ASSIGNEES_COUNT]) ?? 0; + const pullRequestDesiredReviewersCount = parseInt(additionalParams[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_REVIEWERS_COUNT] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_REVIEWERS_COUNT]) ?? 0; + const pullRequestMergeTimeout = parseInt(additionalParams[constants_1.INPUT_KEYS.PULL_REQUEST_MERGE_TIMEOUT] ?? actionInputs[constants_1.INPUT_KEYS.PULL_REQUEST_MERGE_TIMEOUT]) ?? 0; + /** + * Supabase + */ + const supabaseUrl = additionalParams[constants_1.INPUT_KEYS.SUPABASE_URL] ?? actionInputs[constants_1.INPUT_KEYS.SUPABASE_URL]; + const supabaseKey = additionalParams[constants_1.INPUT_KEYS.SUPABASE_KEY] ?? actionInputs[constants_1.INPUT_KEYS.SUPABASE_KEY]; + let supabaseConfig = undefined; + if (supabaseUrl.length > 0 && supabaseKey.length > 0) { + supabaseConfig = new supabase_config_1.SupabaseConfig(supabaseUrl, supabaseKey); + } + const execution = new execution_1.Execution(debug, new single_action_1.SingleAction(singleAction, singleActionIssue, singleActionVersion, singleActionTitle, singleActionChangelog), commitPrefixBuilder, new issue_1.Issue(branchManagementAlways, reopenIssueOnPush, issueDesiredAssigneesCount, additionalParams), new pull_request_1.PullRequest(pullRequestDesiredAssigneesCount, pullRequestDesiredReviewersCount, pullRequestMergeTimeout, additionalParams), new emoji_1.Emoji(titleEmoji, branchManagementEmoji), new images_1.Images(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, imagesIssueAutomatic, imagesIssueFeature, imagesIssueBugfix, imagesIssueDocs, imagesIssueChore, imagesIssueRelease, imagesIssueHotfix, imagesPullRequestAutomatic, imagesPullRequestFeature, imagesPullRequestBugfix, imagesPullRequestRelease, imagesPullRequestHotfix, imagesPullRequestDocs, imagesPullRequestChore, imagesCommitAutomatic, imagesCommitFeature, imagesCommitBugfix, imagesCommitRelease, imagesCommitHotfix, imagesCommitDocs, imagesCommitChore), new tokens_1.Tokens(token), new ai_1.Ai(openrouterApiKey, openrouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, Object.keys(providerRouting).length > 0 ? providerRouting : undefined), new labels_1.Labels(branchManagementLauncherLabel, bugLabel, bugfixLabel, hotfixLabel, enhancementLabel, featureLabel, releaseLabel, questionLabel, helpLabel, deployLabel, deployedLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel, priorityHighLabel, priorityMediumLabel, priorityLowLabel, priorityNoneLabel, sizeXxlLabel, sizeXlLabel, sizeLLabel, sizeMLabel, sizeSLabel, sizeXsLabel), new issue_types_1.IssueTypes(issueTypeTask, issueTypeTaskDescription, issueTypeTaskColor, issueTypeBug, issueTypeBugDescription, issueTypeBugColor, issueTypeFeature, issueTypeFeatureDescription, issueTypeFeatureColor, issueTypeDocumentation, issueTypeDocumentationDescription, issueTypeDocumentationColor, issueTypeMaintenance, issueTypeMaintenanceDescription, issueTypeMaintenanceColor, issueTypeHotfix, issueTypeHotfixDescription, issueTypeHotfixColor, issueTypeRelease, issueTypeReleaseDescription, issueTypeReleaseColor, issueTypeQuestion, issueTypeQuestionDescription, issueTypeQuestionColor, issueTypeHelp, issueTypeHelpDescription, issueTypeHelpColor), new locale_1.Locale(issueLocale, pullRequestLocale), new size_thresholds_1.SizeThresholds(new size_threshold_1.SizeThreshold(sizeXxlThresholdLines, sizeXxlThresholdFiles, sizeXxlThresholdCommits), new size_threshold_1.SizeThreshold(sizeXlThresholdLines, sizeXlThresholdFiles, sizeXlThresholdCommits), new size_threshold_1.SizeThreshold(sizeLThresholdLines, sizeLThresholdFiles, sizeLThresholdCommits), new size_threshold_1.SizeThreshold(sizeMThresholdLines, sizeMThresholdFiles, sizeMThresholdCommits), new size_threshold_1.SizeThreshold(sizeSThresholdLines, sizeSThresholdFiles, sizeSThresholdCommits), new size_threshold_1.SizeThreshold(sizeXsThresholdLines, sizeXsThresholdFiles, sizeXsThresholdCommits)), new branches_1.Branches(mainBranch, developmentBranch, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree), new release_1.Release(), new hotfix_1.Hotfix(), new workflows_1.Workflows(releaseWorkflow, hotfixWorkflow), new projects_1.Projects(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress), supabaseConfig, new welcome_1.Welcome(welcomeTitle, welcomeMessages), additionalParams); + const results = await (0, common_action_1.mainRun)(execution); + let content = ''; + const stepsContent = results + .filter(result => result.executed && result.steps.length > 0) + .map(result => chalk_1.default.gray(result.steps.join('\n'))).join('\n'); + if (stepsContent.length > 0) { + content += '\n' + chalk_1.default.cyan('Steps:') + '\n' + stepsContent; + } + const errorsContent = results + .filter(result => !result.executed && result.errors.length > 0) + .map(result => chalk_1.default.gray(result.errors.join('\n'))).join('\n'); + if (errorsContent.length > 0) { + content += '\n' + chalk_1.default.red('Errors:') + '\n' + errorsContent; + } + const reminderContent = results + .filter(result => result.executed && result.reminders.length > 0) + .map(result => chalk_1.default.gray(result.reminders.join('\n'))).join('\n'); + if (reminderContent.length > 0) { + content += '\n' + chalk_1.default.cyan('Reminder:') + '\n' + reminderContent; } + (0, logger_1.logInfo)('\n'); + (0, logger_1.logInfo)((0, boxen_1.default)(content, { + padding: 1, + margin: 1, + borderStyle: 'round', + borderColor: 'cyan', + title: constants_1.TITLE, + titleAlignment: 'center' + })); } -exports.CheckPriorityPullRequestSizeUseCase = CheckPriorityPullRequestSizeUseCase; /***/ }), -/***/ 22175: +/***/ 6733: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -143959,1189 +60234,824 @@ var __importStar = (this && this.__importStar) || (function () { }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LinkPullRequestIssueUseCase = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const result_1 = __nccwpck_require__(27305); -const pull_request_repository_1 = __nccwpck_require__(20634); -const logger_1 = __nccwpck_require__(38836); -class LinkPullRequestIssueUseCase { - constructor() { - this.taskId = 'LinkPullRequestIssueUseCase'; - this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const isLinked = await this.pullRequestRepository.isLinked(github.context.payload.pull_request?.html_url ?? ''); - if (!isLinked) { - /** - * Set the primary/default branch - */ - await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.branches.defaultBranch, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The base branch was temporarily updated to \`${param.branches.defaultBranch}\`.`, - ], - })); - /** - * Update PR's description. - */ - let prBody = param.pullRequest.body; - let updatedBody = `${prBody}\n\nResolves #${param.issueNumber}`; - await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The description was temporarily modified to include a reference to issue **#${param.issueNumber}**.`, - ], - })); - /** - * Await 20 seconds - */ - await new Promise(resolve => setTimeout(resolve, 20 * 1000)); - /** - * Restore the original branch - */ - await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.pullRequest.base, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The base branch was reverted to its original value: \`${param.pullRequest.base}\`.`, - ], - })); - /** - * Restore comment on description - */ - prBody = param.pullRequest.body; - updatedBody = prBody.replace(`\n\nResolves #${param.issueNumber}`, ""); - await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The temporary issue reference **#${param.issueNumber}** was removed from the description.`, - ], - })); - return result; - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to link pull request to project, but there was a problem.`, - ], - error: error, - })); +const child_process_1 = __nccwpck_require__(2081); +const commander_1 = __nccwpck_require__(4379); +const dotenv = __importStar(__nccwpck_require__(2437)); +const local_action_1 = __nccwpck_require__(7002); +const issue_repository_1 = __nccwpck_require__(57); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +// Load environment variables from .env file +dotenv.config(); +const program = new commander_1.Command(); +// Function to get git repository info +function getGitInfo() { + try { + const remoteUrl = (0, child_process_1.execSync)('git config --get remote.origin.url').toString().trim(); + const match = remoteUrl.match(/github\.com[/:]([^/]+)\/([^/]+)(?:\.git)?$/); + if (!match) { + return { error: constants_1.ERRORS.GIT_REPOSITORY_NOT_FOUND }; } - return result; - } -} -exports.LinkPullRequestIssueUseCase = LinkPullRequestIssueUseCase; - - -/***/ }), - -/***/ 64311: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LinkPullRequestProjectUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class LinkPullRequestProjectUseCase { - constructor() { - this.taskId = 'LinkPullRequestProjectUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); + return { + owner: match[1], + repo: match[2].replace('.git', '') + }; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - const columnName = param.project.getProjectColumnPullRequestCreated(); - try { - for (const project of param.project.getProjects()) { - let actionDone = await this.projectRepository.linkContentId(project, param.pullRequest.id, param.tokens.token); - if (actionDone) { - /** - * Wait for 10 seconds to ensure the pull request is linked to the project - */ - await new Promise(resolve => setTimeout(resolve, 10000)); - actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.pullRequest.number, columnName, param.tokens.token); - if (actionDone) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The pull request was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, - ], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `The pull request was linked to [**${project?.title}**](${project?.url}) but there was an error moving it to the column \`${columnName}\`.`, - ], - })); - } - } - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to link pull request to project, but there was a problem.`, - ], - error: error, - })); - } - return result; + catch (error) { + return { error: constants_1.ERRORS.GIT_REPOSITORY_NOT_FOUND }; } } -exports.LinkPullRequestProjectUseCase = LinkPullRequestProjectUseCase; - - -/***/ }), - -/***/ 50158: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UpdatePullRequestDescriptionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const file_repository_1 = __nccwpck_require__(81503); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const pull_request_repository_1 = __nccwpck_require__(20634); -const logger_1 = __nccwpck_require__(38836); -class UpdatePullRequestDescriptionUseCase { - constructor() { - this.taskId = 'UpdatePullRequestDescriptionUseCase'; - this.aiRepository = new ai_repository_1.AiRepository(); - this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); - this.fileRepository = new file_repository_1.FileRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); +program + .command('build-ai') + .description(`${constants_1.TITLE} - Build AI container and execute AI cache indexing`) + .option('-d, --debug', 'Debug mode', false) + .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) + .action(async (options) => { + const gitInfo = getGitInfo(); + if ('error' in gitInfo) { + console.log(gitInfo.error); + return; } - async invoke(param) { - (0, logger_1.logDebugInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const prNumber = param.pullRequest.number; - const issueDescription = await this.issueRepository.getIssueDescription(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (issueDescription.length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - steps: [ - `No issue description found. Skipping update pull request description.` - ] - })); - return result; - } - const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); - const pullRequestCreatorIsTeamMember = param.pullRequest.creator.length > 0 - && currentProjectMembers.indexOf(param.pullRequest.creator) > -1; - if (!pullRequestCreatorIsTeamMember && param.ai.getAiMembersOnly()) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - steps: [ - `The pull request creator @${param.pullRequest.creator} is not a team member and \`AI members only\` is enabled. Skipping update pull request description.` - ] - })); - return result; - } - const changes = await this.pullRequestRepository.getPullRequestChanges(param.owner, param.repo, prNumber, param.tokens.token); - const changesDescription = await this.processChanges(changes, param.ai, param.owner, param.repo, param.tokens.token, param.pullRequest.base); - const descriptionPrompt = `this an issue descrition. -define a description for the pull request which closes the issue and avoid the use of titles (#, ##, ###). -just a text description:\n\n -${issueDescription}`; - const currentDescription = await this.aiRepository.ask(param.ai, descriptionPrompt); - // Update pull request description - await this.pullRequestRepository.updateDescription(param.owner, param.repo, prNumber, ` -#${param.issueNumber} - -## What does this PR do? - -${currentDescription} - -${changesDescription} -`, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The description has been updated with AI-generated content.` - ] - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error updating pull request description: ${error}` - ] - })); - } - return result; + const params = { + [constants_1.INPUT_KEYS.DEBUG]: options.debug.toString(), + [constants_1.INPUT_KEYS.SINGLE_ACTION]: constants_1.ACTIONS.AI_CACHE_LOCAL, + [constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]: 1, + [constants_1.INPUT_KEYS.SUPABASE_URL]: process.env.SUPABASE_URL, + [constants_1.INPUT_KEYS.SUPABASE_KEY]: process.env.SUPABASE_KEY, + [constants_1.INPUT_KEYS.OPENROUTER_API_KEY]: process.env.OPENROUTER_API_KEY, + [constants_1.INPUT_KEYS.OPENROUTER_MODEL]: process.env.OPENROUTER_MODEL, + [constants_1.INPUT_KEYS.TOKEN]: options.token || process.env.PERSONAL_ACCESS_TOKEN, + [constants_1.INPUT_KEYS.AI_IGNORE_FILES]: 'build/*', + repo: { + owner: gitInfo.owner, + repo: gitInfo.repo, + }, + issue: { + number: 1, + }, + }; + params[constants_1.INPUT_KEYS.WELCOME_TITLE] = 'šŸš€ AI Container Build'; + params[constants_1.INPUT_KEYS.WELCOME_MESSAGES] = [ + `Building AI container for ${gitInfo.owner}/${gitInfo.repo}...`, + ]; + await (0, local_action_1.runLocalAction)(params); +}); +/** + * Run the thinking AI scenario for deep code analysis and proposals. + */ +program + .command('think') + .description(`${constants_1.TITLE} - Deep code analysis and change proposals using AI reasoning`) + .option('-i, --issue ', 'Issue number to process (optional)', '1') + .option('-b, --branch ', 'Branch name', 'master') + .option('-d, --debug', 'Debug mode', false) + .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) + .option('-q, --question ', 'Question or prompt for analysis', '') + .option('--openrouter-api-key ', 'OpenRouter API key', '') + .option('--openrouter-model ', 'OpenRouter model', '') + .option('--openrouter-provider-order ', 'OpenRouter provider', '') + .option('--openrouter-provider-allow-fallbacks ', 'OpenRouter fallback', '') + .option('--openrouter-provider-require-parameters ', 'OpenRouter require', '') + .option('--openrouter-provider-data-collection ', 'OpenRouter collection', '') + .option('--openrouter-provider-ignore ', 'OpenRouter ignore', '') + .option('--openrouter-provider-quantizations ', 'OpenRouter quantizations', '') + .option('--openrouter-provider-sort ', 'OpenRouter sort', '') + .option('--ai-ignore-files ', 'AI ignore files', 'node_modules/*,build/*') + .option('--include-reasoning ', 'Include reasoning', 'false') + .action(async (options) => { + const gitInfo = getGitInfo(); + if ('error' in gitInfo) { + console.log(gitInfo.error); + return; } - shouldIgnoreFile(filename, ignorePatterns) { - return ignorePatterns.some(pattern => { - // Convert glob pattern to regex - const regexPattern = pattern - .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) - .replace(/\*/g, '.*') // Convert * to match anything - .replace(/\//g, '\\/'); // Escape forward slashes - // Allow pattern ending on /* to ignore also subdirectories and files inside - if (pattern.endsWith("/*")) { - return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); - } - const regex = new RegExp(`^${regexPattern}$`); - return regex.test(filename); - }); + // Helper function to clean CLI arguments that may have '=' prefix + const cleanArg = (value) => { + if (!value) + return ''; + const str = String(value); + return str.startsWith('=') ? str.substring(1) : str; + }; + const questionParts = (options.question || []).map(cleanArg); + const question = questionParts.join(' '); + if (!question || question.length === 0) { + console.log('āŒ Please provide a question or prompt using -q or --question'); + return; } - mergePatchSummaries(summaries) { - const mergedMap = new Map(); - for (const summary of summaries) { - const existing = mergedMap.get(summary.filePath); - if (existing) { - // Merge with existing summary - existing.summary = `${existing.summary}\n${summary.summary}`; - existing.changes = [...new Set([...existing.changes, ...summary.changes])]; - } - else { - // Create new entry - mergedMap.set(summary.filePath, { - filePath: summary.filePath, - summary: summary.summary, - changes: [...summary.changes] - }); - } + const branch = cleanArg(options.branch); + const issueNumber = cleanArg(options.issue); + const params = { + [constants_1.INPUT_KEYS.DEBUG]: options.debug.toString(), + [constants_1.INPUT_KEYS.SINGLE_ACTION]: constants_1.ACTIONS.THINK, + [constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]: parseInt(issueNumber) || 1, + [constants_1.INPUT_KEYS.SUPABASE_URL]: options?.supabaseUrl?.length > 0 ? options.supabaseUrl : process.env.SUPABASE_URL, + [constants_1.INPUT_KEYS.SUPABASE_KEY]: options?.supabaseKey?.length > 0 ? options.supabaseKey : process.env.SUPABASE_KEY, + [constants_1.INPUT_KEYS.TOKEN]: options?.token?.length > 0 ? options.token : process.env.PERSONAL_ACCESS_TOKEN, + [constants_1.INPUT_KEYS.OPENROUTER_API_KEY]: options?.openrouterApiKey?.length > 0 ? options.openrouterApiKey : process.env.OPENROUTER_API_KEY, + [constants_1.INPUT_KEYS.OPENROUTER_MODEL]: options?.openrouterModel?.length > 0 ? options.openrouterModel : process.env.OPENROUTER_MODEL, + [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER]: options?.openrouterProviderOrder?.length > 0 ? options.openrouterProviderOrder : process.env.OPENROUTER_PROVIDER_ORDER, + [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS]: options?.openrouterProviderAllowFallbacks?.length > 0 ? options.openrouterProviderAllowFallbacks : process.env.OPENROUTER_PROVIDER_ALLOW_FALLBACKS, + [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS]: options?.openrouterProviderRequireParameters?.length > 0 ? options.openrouterProviderRequireParameters : process.env.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS, + [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION]: options?.openrouterProviderDataCollection?.length > 0 ? options.openrouterProviderDataCollection : process.env.OPENROUTER_PROVIDER_DATA_COLLECTION, + [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE]: options?.openrouterProviderIgnore?.length > 0 ? options.openrouterProviderIgnore : process.env.OPENROUTER_PROVIDER_IGNORE, + [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS]: options?.openrouterProviderQuantizations?.length > 0 ? options.openrouterProviderQuantizations : process.env.OPENROUTER_PROVIDER_QUANTIZATIONS, + [constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT]: options?.openrouterProviderSort?.length > 0 ? options.openrouterProviderSort : process.env.OPENROUTER_PROVIDER_SORT, + [constants_1.INPUT_KEYS.AI_IGNORE_FILES]: options?.aiIgnoreFiles?.length > 0 ? options.aiIgnoreFiles : process.env.AI_IGNORE_FILES, + [constants_1.INPUT_KEYS.AI_INCLUDE_REASONING]: options?.includeReasoning?.length > 0 ? options.includeReasoning : process.env.AI_INCLUDE_REASONING, + repo: { + owner: gitInfo.owner, + repo: gitInfo.repo, + }, + commits: { + ref: `refs/heads/${branch}`, + }, + }; + // Set up issue context if provided + const parsedIssueNumber = parseInt(issueNumber); + if (issueNumber && parsedIssueNumber > 0) { + const issueRepository = new issue_repository_1.IssueRepository(); + const isIssue = await issueRepository.isIssue(gitInfo.owner, gitInfo.repo, parsedIssueNumber, params[constants_1.INPUT_KEYS.TOKEN] ?? ''); + if (isIssue) { + params.eventName = 'issue'; + params.issue = { + number: parsedIssueNumber, + }; + params.comment = { + body: question, + }; } - return Array.from(mergedMap.values()); } - groupFilesByDirectory(files) { - const groups = { - root: [] + else { + // If no issue provided, set up as issue with question as body + params.eventName = 'issue'; + params.issue = { + number: 1, + }; + params.comment = { + body: question, }; - files.forEach(file => { - const pathParts = file.filePath.split('/'); - if (pathParts.length > 1) { - const directory = pathParts.slice(0, -1).join('/'); - if (!groups[directory]) { - groups[directory] = []; - } - groups[directory].push(file); - } - else { - groups.root.push(file); - } - }); - return groups; - } - formatFileChanges(file) { - let output = `#### \`${file.filePath}\`\n\n`; - output += `${file.summary}\n\n`; - if (file.changes.length > 0) { - output += '**Changes:**\n'; - output += file.changes.map(change => `- ${change}`).join('\n'); - } - output += `\n\n--- \n\n`; - return output; - } - async processFile(change, ai, owner, repo, token, baseBranch) { - if (!change.patch) { - return []; - } - // Get the original file content - const originalContent = await this.fileRepository.getFileContent(owner, repo, change.filename, token, baseBranch); - const filePrompt = `Analyze the following code changes and provide a summary in JSON format. - -### **Guidelines**: -- Output must be a **valid JSON** object. -- Provide a high-level summary of the changes. -- List the key changes in detail. -- Pay attention to the file names, don't make mistakes with uppercase, lowercase, or underscores. -- Be careful when composing the response JSON, don't make mistakes with unnecessary commas. - -### **Output Format Example**: -\`\`\`json -{ - "filePath": "src/utils/logger.ts", - "summary": "Refactored logging system for better error handling.", - "changes": [ - "Replaced \`console.error\` with \`logError\`.", - "Added support for async logging.", - "Removed unused function \`debugLog\`." - ] -} -\`\`\` - -### **Metadata**: -- **Filename:** ${change.filename} -- **Status:** ${change.status} -- **Changes:** +${change.additions} / -${change.deletions} - -### **Original File Content**: -\`\`\` -${originalContent} -\`\`\` - -### **Patch**: -${change.patch}`; - const response = await this.aiRepository.ask(ai, filePrompt); - if (!response) { - return []; - } - try { - const cleanResponse = response.replace(/^```json\n?/, '').replace(/\n?```$/, '').trim(); - const patchSummary = JSON.parse(cleanResponse); - return [patchSummary]; - } - catch (error) { - (0, logger_1.logDebugError)(`Response: ${response}`); - (0, logger_1.logError)(`Error parsing JSON response: ${error}`); - return []; - } } - async processChanges(changes, ai, owner, repo, token, baseBranch) { - (0, logger_1.logDebugInfo)(`Processing ${changes.length} changes`); - const processFilePromises = changes.map(async (change) => { - try { - (0, logger_1.logDebugInfo)(`Processing changes for file ${change.filename}`); - const shouldIgnoreFile = this.shouldIgnoreFile(change.filename, ai.getAiIgnoreFiles()); - if (shouldIgnoreFile) { - (0, logger_1.logDebugInfo)(`File ${change.filename} should be ignored`); - return []; - } - return await this.processFile(change, ai, owner, repo, token, baseBranch); - } - catch (error) { - (0, logger_1.logError)(error); - throw new Error(`Error processing file ${change.filename}: ${error}`); - } - }); - const fileDescriptions = (await Promise.all(processFilePromises)).flat(); - // Merge PatchSummary objects for the same file - const mergedFileDescriptions = this.mergePatchSummaries(fileDescriptions); - // Group files by directory - const groupedFiles = this.groupFilesByDirectory(mergedFileDescriptions); - // Generate a structured description - let description = ''; - // Add summary section if there are files - if (mergedFileDescriptions.length > 0) { - description += '## Summary of Changes\n\n'; - description += mergedFileDescriptions.map(file => `- **${file.filePath}**: ${file.summary}`).join('\n'); - description += '\n\n'; - } - // Add detailed changes section - description += '## Detailed Changes\n\n'; - // Process each directory group - for (const [directory, files] of Object.entries(groupedFiles)) { - if (directory === 'root') { - // Files in root directory - description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; - } - else { - // Files in subdirectories - description += `### ${directory}\n\n`; - description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; - } - } - return description; + params[constants_1.INPUT_KEYS.WELCOME_TITLE] = 'šŸ¤” AI Reasoning Analysis'; + params[constants_1.INPUT_KEYS.WELCOME_MESSAGES] = [ + `Starting deep code analysis for ${gitInfo.owner}/${gitInfo.repo}/${branch}...`, + `Question: ${question.substring(0, 100)}${question.length > 100 ? '...' : ''}`, + ]; + (0, logger_1.logInfo)(JSON.stringify(params, null, 2)); + (0, local_action_1.runLocalAction)(params); +}); +program.parse(process.argv); + + +/***/ }), + +/***/ 4470: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Ai = void 0; +class Ai { + constructor(openRouterApiKey, openRouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, providerRouting) { + this.openRouterApiKey = openRouterApiKey; + this.openRouterModel = openRouterModel; + this.aiPullRequestDescription = aiPullRequestDescription; + this.aiMembersOnly = aiMembersOnly; + this.aiIgnoreFiles = aiIgnoreFiles; + this.aiIncludeReasoning = aiIncludeReasoning; + this.providerRouting = providerRouting || {}; + } + getOpenRouterApiKey() { + return this.openRouterApiKey; + } + getAiPullRequestDescription() { + return this.aiPullRequestDescription; + } + getAiMembersOnly() { + return this.aiMembersOnly; + } + getAiIgnoreFiles() { + return this.aiIgnoreFiles; + } + getAiIncludeReasoning() { + return this.aiIncludeReasoning; + } + getOpenRouterModel() { + return this.openRouterModel; + } + getProviderRouting() { + return this.providerRouting; } } -exports.UpdatePullRequestDescriptionUseCase = UpdatePullRequestDescriptionUseCase; +exports.Ai = Ai; /***/ }), -/***/ 87112: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5968: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckPullRequestCommentLanguageUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class CheckPullRequestCommentLanguageUseCase { - constructor() { - this.taskId = 'CheckPullRequestCommentLanguageUseCase'; - this.aiRepository = new ai_repository_1.AiRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.translatedKey = ``; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - const commentBody = param.pullRequest.commentBody; - if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; - } - const locale = param.locale.pullRequest; - let prompt = ` - You are a helpful assistant that checks if the text is written in ${locale}. - - Instructions: - 1. Analyze the provided text - 2. If the text is written in ${locale}, respond with exactly "done" - 3. If the text is written in any other language, respond with exactly "must_translate" - 4. Do not provide any explanation or additional text - - The text is: ${commentBody} - `; - let result = await this.aiRepository.ask(param.ai, prompt); - if (result === "done") { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return results; +exports.AI_RESPONSE_JSON_SCHEMA = void 0; +/** + * JSON Schema for AiResponse interface + * This schema is used to enforce structured JSON responses from the AI + */ +exports.AI_RESPONSE_JSON_SCHEMA = { + type: "object", + properties: { + text_response: { + type: "string", + description: "The detailed analysis or answer to the user's question" + }, + action: { + type: "string", + enum: ["none", "analyze_files"], + description: "The action to take: 'none' if no additional files are needed, 'analyze_files' if more files are required" + }, + related_files: { + type: "array", + items: { + type: "string" + }, + description: "List of file paths that need to be analyzed if action is 'analyze_files'" + }, + complete: { + type: "boolean", + description: "Whether the response is complete and no further analysis is needed" } - prompt = ` -You are a helpful assistant that translates the text to ${locale}. + }, + required: ["text_response", "action", "related_files", "complete"], + additionalProperties: false +}; -Instructions: -1. Translate the text to ${locale} -2. Do not provide any explanation or additional text -3. Return the translated text only -The text is: ${commentBody} - `; - result = await this.aiRepository.ask(param.ai, prompt); - const translatedCommentBody = `${result} -> ${commentBody} -${this.translatedKey} -`; - await this.issueRepository.updateComment(param.owner, param.repo, param.pullRequest.number, param.pullRequest.commentId, translatedCommentBody, param.tokens.token); - return results; +/***/ }), + +/***/ 2141: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BranchConfiguration = void 0; +class BranchConfiguration { + constructor(data) { + this.name = data['name'] ?? ''; + this.oid = data['oid'] ?? ''; + this.children = []; + if (data['children'] !== undefined && data['children'].length > 0) { + for (let child of data['children']) { + this.children.push(new BranchConfiguration(child)); + } + } } } -exports.CheckPullRequestCommentLanguageUseCase = CheckPullRequestCommentLanguageUseCase; +exports.BranchConfiguration = BranchConfiguration; /***/ }), -/***/ 8593: -/***/ ((__unused_webpack_module, exports) => { +/***/ 5308: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ACTIONS = exports.ERRORS = exports.INPUT_KEYS = exports.WORKFLOW_ACTIVE_STATUSES = exports.WORKFLOW_STATUS = exports.DEFAULT_IMAGE_CONFIG = exports.REPO_URL = exports.TITLE = exports.COMMAND = void 0; -exports.COMMAND = 'git-board-flow'; -exports.TITLE = 'Git Board Flow'; -exports.REPO_URL = 'https://github.com/landamessenger/git-board-flow'; -exports.DEFAULT_IMAGE_CONFIG = { - issue: { - automatic: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp" - ], - feature: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", - ], - bugfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" - ], - hotfix: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" - ], - release: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", - ], - docs: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", - ], - chore: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", - ], - }, - pullRequest: { - automatic: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - ], - feature: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", - ], - bugfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", - ], - hotfix: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", - ], - release: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", - ], - docs: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", - ], - chore: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", - ], - }, - commit: { - automatic: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - feature: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - bugfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - hotfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - release: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - docs: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - chore: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ] +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]; } }; } -}; -exports.WORKFLOW_STATUS = { - IN_PROGRESS: 'in_progress', - QUEUED: 'queued', - COMPLETED: 'completed', - FAILED: 'failed', - CANCELLED: 'cancelled', - SKIPPED: 'skipped', - TIMED_OUT: 'timed_out', -}; -exports.WORKFLOW_ACTIVE_STATUSES = [exports.WORKFLOW_STATUS.IN_PROGRESS, exports.WORKFLOW_STATUS.QUEUED]; -exports.INPUT_KEYS = { - // Debug - DEBUG: 'debug', - // Welcome - WELCOME_TITLE: 'welcome-title', - WELCOME_MESSAGES: 'welcome-messages', - // Docker - DOCKER_CONTAINER_NAME: 'docker-container-name', - DOCKER_DOMAIN: 'docker-domain', - DOCKER_PORT: 'docker-port', - DOCKER_CACHE_OS: 'docker-cache-os', - DOCKER_CACHE_ARCH: 'docker-cache-arch', - // Single action - SINGLE_ACTION: 'single-action', - SINGLE_ACTION_ISSUE: 'single-action-issue', - SINGLE_ACTION_VERSION: 'single-action-version', - SINGLE_ACTION_TITLE: 'single-action-title', - SINGLE_ACTION_CHANGELOG: 'single-action-changelog', - // Tokens - TOKEN: 'token', - CLASSIC_TOKEN: 'classic-token', - // AI - OPENROUTER_API_KEY: 'openrouter-api-key', - OPENROUTER_MODEL: 'openrouter-model', - AI_PULL_REQUEST_DESCRIPTION: 'ai-pull-request-description', - AI_MEMBERS_ONLY: 'ai-members-only', - AI_IGNORE_FILES: 'ai-ignore-files', - AI_INCLUDE_REASONING: 'ai-include-reasoning', - OPENROUTER_PROVIDER_ORDER: 'openrouter-provider-order', - OPENROUTER_PROVIDER_ALLOW_FALLBACKS: 'openrouter-provider-allow-fallbacks', - OPENROUTER_PROVIDER_REQUIRE_PARAMETERS: 'openrouter-provider-require-parameters', - OPENROUTER_PROVIDER_DATA_COLLECTION: 'openrouter-provider-data-collection', - OPENROUTER_PROVIDER_IGNORE: 'openrouter-provider-ignore', - OPENROUTER_PROVIDER_QUANTIZATIONS: 'openrouter-provider-quantizations', - OPENROUTER_PROVIDER_SORT: 'openrouter-provider-sort', - // Projects - PROJECT_IDS: 'project-ids', - PROJECT_COLUMN_ISSUE_CREATED: 'project-column-issue-created', - PROJECT_COLUMN_PULL_REQUEST_CREATED: 'project-column-pull-request-created', - PROJECT_COLUMN_ISSUE_IN_PROGRESS: 'project-column-issue-in-progress', - PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS: 'project-column-pull-request-in-progress', - // Images - IMAGES_ON_ISSUE: 'images-on-issue', - IMAGES_ON_PULL_REQUEST: 'images-on-pull-request', - IMAGES_ON_COMMIT: 'images-on-commit', - IMAGES_ISSUE_AUTOMATIC: 'images-issue-automatic', - IMAGES_ISSUE_FEATURE: 'images-issue-feature', - IMAGES_ISSUE_BUGFIX: 'images-issue-bugfix', - IMAGES_ISSUE_DOCS: 'images-issue-docs', - IMAGES_ISSUE_CHORE: 'images-issue-chore', - IMAGES_ISSUE_RELEASE: 'images-issue-release', - IMAGES_ISSUE_HOTFIX: 'images-issue-hotfix', - IMAGES_PULL_REQUEST_AUTOMATIC: 'images-pull-request-automatic', - IMAGES_PULL_REQUEST_FEATURE: 'images-pull-request-feature', - IMAGES_PULL_REQUEST_BUGFIX: 'images-pull-request-bugfix', - IMAGES_PULL_REQUEST_RELEASE: 'images-pull-request-release', - IMAGES_PULL_REQUEST_HOTFIX: 'images-pull-request-hotfix', - IMAGES_PULL_REQUEST_DOCS: 'images-pull-request-docs', - IMAGES_PULL_REQUEST_CHORE: 'images-pull-request-chore', - IMAGES_COMMIT_AUTOMATIC: 'images-commit-automatic', - IMAGES_COMMIT_FEATURE: 'images-commit-feature', - IMAGES_COMMIT_BUGFIX: 'images-commit-bugfix', - IMAGES_COMMIT_RELEASE: 'images-commit-release', - IMAGES_COMMIT_HOTFIX: 'images-commit-hotfix', - IMAGES_COMMIT_DOCS: 'images-commit-docs', - IMAGES_COMMIT_CHORE: 'images-commit-chore', - // Workflows - RELEASE_WORKFLOW: 'release-workflow', - HOTFIX_WORKFLOW: 'hotfix-workflow', - // Emoji - EMOJI_LABELED_TITLE: 'emoji-labeled-title', - BRANCH_MANAGEMENT_EMOJI: 'branch-management-emoji', - // Labels - BRANCH_MANAGEMENT_LAUNCHER_LABEL: 'branch-management-launcher-label', - BUGFIX_LABEL: 'bugfix-label', - BUG_LABEL: 'bug-label', - HOTFIX_LABEL: 'hotfix-label', - ENHANCEMENT_LABEL: 'enhancement-label', - FEATURE_LABEL: 'feature-label', - RELEASE_LABEL: 'release-label', - QUESTION_LABEL: 'question-label', - HELP_LABEL: 'help-label', - DEPLOY_LABEL: 'deploy-label', - DEPLOYED_LABEL: 'deployed-label', - DOCS_LABEL: 'docs-label', - DOCUMENTATION_LABEL: 'documentation-label', - CHORE_LABEL: 'chore-label', - MAINTENANCE_LABEL: 'maintenance-label', - PRIORITY_HIGH_LABEL: 'priority-high-label', - PRIORITY_MEDIUM_LABEL: 'priority-medium-label', - PRIORITY_LOW_LABEL: 'priority-low-label', - PRIORITY_NONE_LABEL: 'priority-none-label', - SIZE_XXL_LABEL: 'size-xxl-label', - SIZE_XL_LABEL: 'size-xl-label', - SIZE_L_LABEL: 'size-l-label', - SIZE_M_LABEL: 'size-m-label', - SIZE_S_LABEL: 'size-s-label', - SIZE_XS_LABEL: 'size-xs-label', - // Issue Types - ISSUE_TYPE_BUG: 'issue-type-bug', - ISSUE_TYPE_BUG_DESCRIPTION: 'issue-type-bug-description', - ISSUE_TYPE_BUG_COLOR: 'issue-type-bug-color', - ISSUE_TYPE_HOTFIX: 'issue-type-hotfix', - ISSUE_TYPE_HOTFIX_DESCRIPTION: 'issue-type-hotfix-description', - ISSUE_TYPE_HOTFIX_COLOR: 'issue-type-hotfix-color', - ISSUE_TYPE_FEATURE: 'issue-type-feature', - ISSUE_TYPE_FEATURE_DESCRIPTION: 'issue-type-feature-description', - ISSUE_TYPE_FEATURE_COLOR: 'issue-type-feature-color', - ISSUE_TYPE_DOCUMENTATION: 'issue-type-documentation', - ISSUE_TYPE_DOCUMENTATION_DESCRIPTION: 'issue-type-documentation-description', - ISSUE_TYPE_DOCUMENTATION_COLOR: 'issue-type-documentation-color', - ISSUE_TYPE_MAINTENANCE: 'issue-type-maintenance', - ISSUE_TYPE_MAINTENANCE_DESCRIPTION: 'issue-type-maintenance-description', - ISSUE_TYPE_MAINTENANCE_COLOR: 'issue-type-maintenance-color', - ISSUE_TYPE_RELEASE: 'issue-type-release', - ISSUE_TYPE_RELEASE_DESCRIPTION: 'issue-type-release-description', - ISSUE_TYPE_RELEASE_COLOR: 'issue-type-release-color', - ISSUE_TYPE_QUESTION: 'issue-type-question', - ISSUE_TYPE_QUESTION_DESCRIPTION: 'issue-type-question-description', - ISSUE_TYPE_QUESTION_COLOR: 'issue-type-question-color', - ISSUE_TYPE_HELP: 'issue-type-help', - ISSUE_TYPE_HELP_DESCRIPTION: 'issue-type-help-description', - ISSUE_TYPE_HELP_COLOR: 'issue-type-help-color', - ISSUE_TYPE_TASK: 'issue-type-task', - ISSUE_TYPE_TASK_DESCRIPTION: 'issue-type-task-description', - ISSUE_TYPE_TASK_COLOR: 'issue-type-task-color', - // Locale - ISSUES_LOCALE: 'issues-locale', - PULL_REQUESTS_LOCALE: 'pull-requests-locale', - // Size Thresholds - SIZE_XXL_THRESHOLD_LINES: 'size-xxl-threshold-lines', - SIZE_XXL_THRESHOLD_FILES: 'size-xxl-threshold-files', - SIZE_XXL_THRESHOLD_COMMITS: 'size-xxl-threshold-commits', - SIZE_XL_THRESHOLD_LINES: 'size-xl-threshold-lines', - SIZE_XL_THRESHOLD_FILES: 'size-xl-threshold-files', - SIZE_XL_THRESHOLD_COMMITS: 'size-xl-threshold-commits', - SIZE_L_THRESHOLD_LINES: 'size-l-threshold-lines', - SIZE_L_THRESHOLD_FILES: 'size-l-threshold-files', - SIZE_L_THRESHOLD_COMMITS: 'size-l-threshold-commits', - SIZE_M_THRESHOLD_LINES: 'size-m-threshold-lines', - SIZE_M_THRESHOLD_FILES: 'size-m-threshold-files', - SIZE_M_THRESHOLD_COMMITS: 'size-m-threshold-commits', - SIZE_S_THRESHOLD_LINES: 'size-s-threshold-lines', - SIZE_S_THRESHOLD_FILES: 'size-s-threshold-files', - SIZE_S_THRESHOLD_COMMITS: 'size-s-threshold-commits', - SIZE_XS_THRESHOLD_LINES: 'size-xs-threshold-lines', - SIZE_XS_THRESHOLD_FILES: 'size-xs-threshold-files', - SIZE_XS_THRESHOLD_COMMITS: 'size-xs-threshold-commits', - // Branches - MAIN_BRANCH: 'main-branch', - DEVELOPMENT_BRANCH: 'development-branch', - FEATURE_TREE: 'feature-tree', - BUGFIX_TREE: 'bugfix-tree', - HOTFIX_TREE: 'hotfix-tree', - RELEASE_TREE: 'release-tree', - DOCS_TREE: 'docs-tree', - CHORE_TREE: 'chore-tree', - // Commit - COMMIT_PREFIX_TRANSFORMS: 'commit-prefix-transforms', - // Issue - BRANCH_MANAGEMENT_ALWAYS: 'branch-management-always', - REOPEN_ISSUE_ON_PUSH: 'reopen-issue-on-push', - DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', - // Pull Request - PULL_REQUEST_DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', - PULL_REQUEST_DESIRED_REVIEWERS_COUNT: 'desired-reviewers-count', - PULL_REQUEST_MERGE_TIMEOUT: 'merge-timeout', - // Supabase - SUPABASE_URL: 'supabase-url', - SUPABASE_KEY: 'supabase-key' -}; -exports.ERRORS = { - GIT_REPOSITORY_NOT_FOUND: 'āŒ Git repository not found' -}; -exports.ACTIONS = { - DEPLOYED: 'deployed_action', - COMPILE_VECTOR_SERVER: 'compile_vector_server', - VECTOR: 'vector_action', - VECTOR_LOCAL: 'vector_local', - VECTOR_REMOVAL: 'vector_removal', - PUBLISH_GITHUB_ACTION: 'publish_github_action', - CREATE_RELEASE: 'create_release', - CREATE_TAG: 'create_tag', -}; + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Branches = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class Branches { + get defaultBranch() { + return github.context.payload.repository?.default_branch ?? ''; + } + constructor(main, development, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree) { + this.main = main; + this.development = development; + this.featureTree = featureTree; + this.bugfixTree = bugfixTree; + this.hotfixTree = hotfixTree; + this.releaseTree = releaseTree; + this.docsTree = docsTree; + this.choreTree = choreTree; + } +} +exports.Branches = Branches; /***/ }), -/***/ 17873: -/***/ ((__unused_webpack_module, exports) => { +/***/ 3993: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.injectJsonAsMarkdownBlock = exports.extractReleaseType = exports.extractVersion = void 0; -const extractVersion = (pattern, text) => { - const versionPattern = new RegExp(`###\\s*${pattern}\\s+(\\d+\\.\\d+\\.\\d+)`, 'i'); - const match = text.match(versionPattern); - return match ? match[1] : undefined; -}; -exports.extractVersion = extractVersion; -const extractReleaseType = (pattern, text) => { - const releaseTypePattern = new RegExp(`###\\s*${pattern}\\s+(Patch|Minor|Major)`, 'i'); - const match = text.match(releaseTypePattern); - return match ? match[1] : undefined; -}; -exports.extractReleaseType = extractReleaseType; -const injectJsonAsMarkdownBlock = (title, json) => { - const formattedJson = JSON.stringify(json, null, 4) // Pretty-print the JSON with 4 spaces. - .split('\n') // Split into lines. - .map(line => `> ${line}`) // Prefix each line with '> '. - .join('\n'); // Join lines back into a string. - return `> **${title}**\n>\n> \`\`\`json\n${formattedJson}\n> \`\`\``; -}; -exports.injectJsonAsMarkdownBlock = injectJsonAsMarkdownBlock; +exports.Commit = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class Commit { + constructor(inputs = undefined) { + this.inputs = undefined; + this.inputs = inputs; + } + get branchReference() { + return this.inputs?.commits?.ref ?? github.context.payload.ref ?? ''; + } + get branch() { + return this.branchReference.replace('refs/heads/', ''); + } + get commits() { + return github.context.payload.commits || []; + } +} +exports.Commit = Commit; /***/ }), -/***/ 31479: -/***/ ((__unused_webpack_module, exports) => { +/***/ 1106: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.typesForIssue = exports.branchesForManagement = void 0; -const branchesForManagement = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { - if (labels.includes(hotfixLabel)) - return params.branches.bugfixTree; - if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) - return params.branches.bugfixTree; - if (labels.includes(releaseLabel)) - return params.branches.releaseTree; - if (labels.includes(docsLabel) || labels.includes(documentationLabel)) - return params.branches.docsTree; - if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) - return params.branches.choreTree; - if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) - return params.branches.featureTree; - return params.branches.featureTree; -}; -exports.branchesForManagement = branchesForManagement; -const typesForIssue = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { - if (labels.includes(hotfixLabel)) - return params.branches.hotfixTree; - if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) - return params.branches.bugfixTree; - if (labels.includes(releaseLabel)) - return params.branches.releaseTree; - if (labels.includes(docsLabel) || labels.includes(documentationLabel)) - return params.branches.docsTree; - if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) - return params.branches.choreTree; - if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) - return params.branches.featureTree; - return params.branches.featureTree; -}; -exports.typesForIssue = typesForIssue; +exports.Config = void 0; +const branch_configuration_1 = __nccwpck_require__(2141); +class Config { + constructor(data) { + this.results = []; + this.branchType = data['branchType'] ?? ''; + this.hotfixOriginBranch = data['hotfixOriginBranch']; + this.hotfixBranch = data['hotfixBranch']; + this.releaseBranch = data['releaseBranch']; + this.parentBranch = data['parentBranch']; + this.workingBranch = data['workingBranch']; + if (data['branchConfiguration'] !== undefined) { + this.branchConfiguration = new branch_configuration_1.BranchConfiguration(data['branchConfiguration']); + } + } +} +exports.Config = Config; /***/ }), -/***/ 14990: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 9463: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRandomElement = void 0; -const chance_1 = __importDefault(__nccwpck_require__(82983)); -const chance = new chance_1.default(); -const getRandomElement = (list) => { - // Return undefined for empty lists - if (!list?.length) { - return undefined; - } - // Return first element for single item lists - if (list.length === 1) { - return list[0]; +exports.Emoji = void 0; +class Emoji { + constructor(emojiLabeledTitle, branchManagementEmoji) { + this.emojiLabeledTitle = emojiLabeledTitle; + this.branchManagementEmoji = branchManagementEmoji; } - // Use chance to get a random index - const randomIndex = chance.integer({ min: 0, max: list.length - 1 }); - return list[randomIndex]; -}; -exports.getRandomElement = getRandomElement; +} +exports.Emoji = Emoji; /***/ }), -/***/ 38836: +/***/ 7550: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setGlobalLoggerDebug = setGlobalLoggerDebug; -exports.logInfo = logInfo; -exports.logWarning = logWarning; -exports.logError = logError; -exports.logDebugInfo = logDebugInfo; -exports.logDebugWarning = logDebugWarning; -exports.logDebugError = logDebugError; -exports.logSingleLine = logSingleLine; -const readline_1 = __importDefault(__nccwpck_require__(14521)); -let loggerDebug = false; -let loggerRemote = false; -function setGlobalLoggerDebug(debug, isRemote = false) { - loggerDebug = debug; - loggerRemote = isRemote; -} -function logInfo(message, previousWasSingleLine = false) { - if (previousWasSingleLine && !loggerRemote) { - console.log(); +exports.Execution = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const configuration_handler_1 = __nccwpck_require__(4509); +const get_hotfix_version_use_case_1 = __nccwpck_require__(8243); +const get_release_type_use_case_1 = __nccwpck_require__(5966); +const get_release_version_use_case_1 = __nccwpck_require__(3827); +const constants_1 = __nccwpck_require__(8593); +const label_utils_1 = __nccwpck_require__(1479); +const logger_1 = __nccwpck_require__(8836); +const title_utils_1 = __nccwpck_require__(6676); +const version_utils_1 = __nccwpck_require__(9887); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const commit_1 = __nccwpck_require__(3993); +const config_1 = __nccwpck_require__(1106); +class Execution { + get eventName() { + return this.inputs?.eventName ?? github.context.eventName; } - console.log(message); -} -function logWarning(message) { - console.warn(message); -} -function logError(message) { - console.error(message.toString()); -} -function logDebugInfo(message, previousWasSingleLine = false) { - if (loggerDebug) { - logInfo(message, previousWasSingleLine); + get actor() { + return this.inputs?.actor ?? github.context.actor; } -} -function logDebugWarning(message) { - if (loggerDebug) { - logWarning(message); + get isSingleAction() { + return this.singleAction.enabledSingleAction; } -} -function logDebugError(message) { - if (loggerDebug) { - logError(message.toString()); + get isIssue() { + return this.issue.isIssue || this.issue.isIssueComment || this.singleAction.isIssue; } -} -function logSingleLine(message) { - if (loggerRemote) { - console.log(message); - return; + get isPullRequest() { + return this.pullRequest.isPullRequest || this.pullRequest.isPullRequestReviewComment || this.singleAction.isPullRequest; + } + get isPush() { + return this.eventName === 'push'; + } + get repo() { + return this.inputs?.repo?.repo ?? github.context.repo.repo; + } + get owner() { + return this.inputs?.repo?.owner ?? github.context.repo.owner; + } + get isFeature() { + return this.issueType === this.branches.featureTree; + } + get isBugfix() { + return this.issueType === this.branches.bugfixTree; + } + get isDocs() { + return this.issueType === this.branches.docsTree; + } + get isChore() { + return this.issueType === this.branches.choreTree; + } + get isBranched() { + return this.issue.branchManagementAlways || + this.labels.containsBranchedLabel || + this.labels.isMandatoryBranchedLabel; + } + get issueNotBranched() { + return this.isIssue && !this.isBranched; + } + get managementBranch() { + return (0, label_utils_1.branchesForManagement)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); + } + get issueType() { + return (0, label_utils_1.typesForIssue)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); + } + get cleanIssueBranches() { + return this.isIssue + && this.previousConfiguration !== undefined + && this.previousConfiguration?.branchType != this.currentConfiguration.branchType; + } + get commit() { + return new commit_1.Commit(this.inputs); + } + get runnedByToken() { + return this.tokenUser === this.actor; + } + constructor(debug, singleAction, commitPrefixBuilder, issue, pullRequest, emoji, giphy, tokens, ai, labels, issueTypes, locale, sizeThresholds, branches, release, hotfix, workflows, project, supabaseConfig, welcome, inputs) { + this.debug = false; + /** + * Every usage of this field should be checked. + * PRs with no issue ID in the head branch won't have it. + * + * master <- develop + */ + this.issueNumber = -1; + this.commitPrefixBuilderParams = {}; + this.setup = async () => { + (0, logger_1.setGlobalLoggerDebug)(this.debug, this.inputs === undefined); + const issueRepository = new issue_repository_1.IssueRepository(); + const projectRepository = new project_repository_1.ProjectRepository(); + this.tokenUser = await projectRepository.getUserFromToken(this.tokens.token); + if (!this.tokenUser) { + throw new Error('Failed to get user from token'); + } + /** + * Set the issue number + */ + if (this.isSingleAction) { + /** + * Single actions can run as isolated processes or as part of a workflow. + * In the case of a workflow, the issue number is got from the workflow. + * In the case of a single action, the issue number is set. + */ + if (this.inputs?.[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]) { + this.issueNumber = this.inputs[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]; + this.singleAction.issue = this.issueNumber; + } + else if (this.isIssue) { + this.singleAction.isIssue = true; + this.issueNumber = this.issue.number; + this.singleAction.issue = this.issueNumber; + } + else if (this.isPullRequest) { + this.singleAction.isPullRequest = true; + this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); + this.singleAction.issue = this.issueNumber; + } + else if (this.isPush) { + this.singleAction.isPush = true; + this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); + this.singleAction.issue = this.issueNumber; + } + else { + this.singleAction.isPullRequest = await issueRepository.isPullRequest(this.owner, this.repo, this.singleAction.issue, this.tokens.token); + this.singleAction.isIssue = await issueRepository.isIssue(this.owner, this.repo, this.singleAction.issue, this.tokens.token); + if (this.singleAction.isIssue) { + this.issueNumber = this.singleAction.issue; + } + else if (this.singleAction.isPullRequest) { + const head = await issueRepository.getHeadBranch(this.owner, this.repo, this.singleAction.issue, this.tokens.token); + if (head === undefined) { + return; + } + this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(head); + } + } + } + else if (this.isIssue) { + this.issueNumber = this.issue.number; + } + else if (this.isPullRequest) { + this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); + } + else if (this.isPush) { + this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); + } + this.previousConfiguration = await new configuration_handler_1.ConfigurationHandler().get(this); + /** + * Get labels of issue + */ + this.labels.currentIssueLabels = await issueRepository.getLabels(this.owner, this.repo, this.issueNumber, this.tokens.token); + /** + * Contains release label + */ + this.release.active = this.labels.isRelease; + this.hotfix.active = this.labels.isHotfix; + /** + * Get previous state + */ + if (this.release.active) { + const previousReleaseBranch = this.previousConfiguration?.releaseBranch; + if (previousReleaseBranch) { + this.release.version = previousReleaseBranch.split('/')[1] ?? ''; + this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; + this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; + this.currentConfiguration.releaseBranch = this.release.branch; + } + } + else if (this.hotfix.active) { + const previousHotfixOriginBranch = this.previousConfiguration?.hotfixOriginBranch; + if (previousHotfixOriginBranch) { + this.hotfix.baseVersion = previousHotfixOriginBranch.split('/v')[1] ?? ''; + this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; + this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; + this.currentConfiguration.parentBranch = this.hotfix.baseBranch; + } + const previousHotfixBranch = this.previousConfiguration?.hotfixBranch; + if (previousHotfixBranch) { + this.hotfix.version = previousHotfixBranch.split('/')[1] ?? ''; + this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; + this.currentConfiguration.hotfixBranch = this.hotfix.branch; + } + } + else { + this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; + } + if (this.isSingleAction) { + /** + * Nothing to do here (for now) + */ + } + else if (this.isIssue) { + const branchRepository = new branch_repository_1.BranchRepository(); + if (this.release.active && this.release.version === undefined) { + const versionResult = await new get_release_version_use_case_1.GetReleaseVersionUseCase().invoke(this); + const versionInfo = versionResult[versionResult.length - 1]; + if (versionInfo.executed && versionInfo.success) { + this.release.version = versionInfo.payload['releaseVersion']; + } + else { + const typeResult = await new get_release_type_use_case_1.GetReleaseTypeUseCase().invoke(this); + const typeInfo = typeResult[typeResult.length - 1]; + if (typeInfo.executed && typeInfo.success) { + this.release.type = typeInfo.payload['releaseType']; + if (this.release.type === undefined) { + return; + } + const lastTag = await branchRepository.getLatestTag(); + if (lastTag === undefined) { + return; + } + this.release.version = (0, version_utils_1.incrementVersion)(lastTag, this.release.type); + } + } + this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; + } + else if (this.hotfix.active && this.hotfix.version === undefined) { + const versionResult = await new get_hotfix_version_use_case_1.GetHotfixVersionUseCase().invoke(this); + const versionInfo = versionResult[versionResult.length - 1]; + if (versionInfo.executed && versionInfo.success) { + this.hotfix.baseVersion = versionInfo.payload['baseVersion']; + this.hotfix.version = versionInfo.payload['hotfixVersion']; + } + else { + this.hotfix.baseVersion = await branchRepository.getLatestTag(); + if (this.hotfix.baseVersion === undefined) { + return; + } + this.hotfix.version = (0, version_utils_1.incrementVersion)(this.hotfix.baseVersion, 'Patch'); + } + this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; + this.currentConfiguration.hotfixBranch = this.hotfix.branch; + this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; + this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; + } + } + else if (this.isPullRequest) { + this.labels.currentPullRequestLabels = await issueRepository.getLabels(this.owner, this.repo, this.pullRequest.number, this.tokens.token); + this.release.active = this.pullRequest.base.indexOf(`${this.branches.releaseTree}/`) > -1; + this.hotfix.active = this.pullRequest.base.indexOf(`${this.branches.hotfixTree}/`) > -1; + } + this.currentConfiguration.branchType = this.issueType; + (0, logger_1.logDebugInfo)(`Current configuration: ${JSON.stringify(this.currentConfiguration, null, 2)}`); + }; + this.debug = debug; + this.singleAction = singleAction; + this.commitPrefixBuilder = commitPrefixBuilder; + this.issue = issue; + this.pullRequest = pullRequest; + this.images = giphy; + this.tokens = tokens; + this.ai = ai; + this.emoji = emoji; + this.labels = labels; + this.issueTypes = issueTypes; + this.locale = locale; + this.sizeThresholds = sizeThresholds; + this.branches = branches; + this.release = release; + this.hotfix = hotfix; + this.project = project; + this.workflows = workflows; + this.currentConfiguration = new config_1.Config({}); + this.supabaseConfig = supabaseConfig; + this.inputs = inputs; + this.welcome = welcome; } - readline_1.default.clearLine(process.stdout, 0); - readline_1.default.cursorTo(process.stdout, 0); - process.stdout.write(message); } +exports.Execution = Execution; /***/ }), -/***/ 99800: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.waitForPreviousRuns = void 0; -const workflow_repository_1 = __nccwpck_require__(90779); -const logger_1 = __nccwpck_require__(38836); -const waitForPreviousRuns = async (params) => { - let attempts = 0; - while (attempts < 2000) { - const workflowRepository = new workflow_repository_1.WorkflowRepository(); - const activeRuns = await workflowRepository.getActivePreviousRuns(params); - if (activeRuns.length === 0) { - (0, logger_1.logDebugInfo)("āœ… No previous runs active. Continuing..."); - return; - } - (0, logger_1.logDebugInfo)(`ā³ Found ${activeRuns.length} previous run(s) still active. Waiting 2s...`); - await new Promise((res) => setTimeout(res, 2000)); - attempts++; - } - throw new Error("Timeout waiting for previous runs to finish."); -}; -exports.waitForPreviousRuns = waitForPreviousRuns; - - -/***/ }), - -/***/ 26676: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7341: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.extractVersionFromBranch = exports.extractIssueNumberFromPush = exports.extractIssueNumberFromBranch = void 0; -const logger_1 = __nccwpck_require__(38836); -const extractIssueNumberFromBranch = (branchName) => { - const match = branchName?.match(/[a-zA-Z]+\/([0-9]+)-.*/); - if (match) { - return parseInt(match[1]); - } - else { - (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); - return -1; - } -}; -exports.extractIssueNumberFromBranch = extractIssueNumberFromBranch; -const extractIssueNumberFromPush = (branchName) => { - const issueNumberMatch = branchName.match(/^[^/]+\/(\d+)-/); - if (!issueNumberMatch) { - (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); - return -1; - } - const issueNumber = parseInt(issueNumberMatch[1], 10); - (0, logger_1.logDebugInfo)(`Linked Issue: #${issueNumber}`); - return issueNumber; -}; -exports.extractIssueNumberFromPush = extractIssueNumberFromPush; -const extractVersionFromBranch = (branchName) => { - const match = branchName?.match(/^[^\/]+\/(\d+\.\d+\.\d+)$/); - if (match) { - return match[1]; - } - else { - (0, logger_1.logDebugInfo)('No version found in the branch name.'); - return undefined; +exports.Hotfix = void 0; +class Hotfix { + constructor() { + this.active = false; } -}; -exports.extractVersionFromBranch = extractVersionFromBranch; +} +exports.Hotfix = Hotfix; /***/ }), -/***/ 29887: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1721: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getLatestVersion = exports.incrementVersion = void 0; -const logger_1 = __nccwpck_require__(38836); -const incrementVersion = (version, releaseType) => { - (0, logger_1.logDebugInfo)(`Incrementing version ${version}.`); - const versionParts = version.split('.').map(Number); - if (versionParts.length !== 3) { - throw new Error('Invalid version format'); - } - const [major, minor, patch] = versionParts; - switch (releaseType) { - case 'Major': - // Increment the major version and reset minor and patch - return `${major + 1}.0.0`; - case 'Minor': - // Increment the minor version and reset patch - return `${major}.${minor + 1}.0`; - case 'Patch': - // Increment the patch version - return `${major}.${minor}.${patch + 1}`; - default: - throw new Error('Unknown release type'); +exports.Images = void 0; +class Images { + constructor(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, cleanUpGifs, featureGifs, bugfixGifs, docsGifs, choreGifs, releaseGifs, hotfixGifs, prLinkGifs, prFeatureGifs, prBugfixGifs, prReleaseGifs, prHotfixGifs, prDocsGifs, prChoreGifs, commitAutomaticActions, commitFeatureGifs, commitBugfixGifs, commitReleaseGifs, commitHotfixGifs, commitDocsGifs, commitChoreGifs) { + this.imagesOnIssue = imagesOnIssue; + this.imagesOnPullRequest = imagesOnPullRequest; + this.imagesOnCommit = imagesOnCommit; + this.issueAutomaticActions = cleanUpGifs; + this.issueFeatureGifs = featureGifs; + this.issueBugfixGifs = bugfixGifs; + this.issueReleaseGifs = releaseGifs; + this.issueHotfixGifs = hotfixGifs; + this.issueDocsGifs = docsGifs; + this.issueChoreGifs = choreGifs; + this.pullRequestAutomaticActions = prLinkGifs; + this.pullRequestFeatureGifs = prFeatureGifs; + this.pullRequestBugfixGifs = prBugfixGifs; + this.pullRequestReleaseGifs = prReleaseGifs; + this.pullRequestHotfixGifs = prHotfixGifs; + this.pullRequestDocsGifs = prDocsGifs; + this.pullRequestChoreGifs = prChoreGifs; + this.commitAutomaticActions = commitAutomaticActions; + this.commitFeatureGifs = commitFeatureGifs; + this.commitBugfixGifs = commitBugfixGifs; + this.commitReleaseGifs = commitReleaseGifs; + this.commitHotfixGifs = commitHotfixGifs; + this.commitDocsGifs = commitDocsGifs; + this.commitChoreGifs = commitChoreGifs; } -}; -exports.incrementVersion = incrementVersion; -const getLatestVersion = (versions) => { - return versions - .map(version => version.split('.').map(num => parseInt(num, 10))) - .sort((a, b) => { - for (let i = 0; i < 3; i++) { - if (a[i] > b[i]) - return 1; - if (a[i] < b[i]) - return -1; - } - return 0; - }) - .map(version => version.join('.')) - .pop(); -}; -exports.getLatestVersion = getLatestVersion; +} +exports.Images = Images; /***/ }), -/***/ 48198: +/***/ 2632: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -145180,12598 +61090,16603 @@ var __importStar = (this && this.__importStar) || (function () { }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.loadActionYaml = loadActionYaml; -exports.getActionInputs = getActionInputs; -exports.getActionInputsWithDefaults = getActionInputsWithDefaults; -const fs = __importStar(__nccwpck_require__(57147)); -const path = __importStar(__nccwpck_require__(71017)); -const yaml = __importStar(__nccwpck_require__(21917)); -function loadActionYaml() { - const actionYamlPath = path.join(process.cwd(), 'action.yml'); - const yamlContent = fs.readFileSync(actionYamlPath, 'utf8'); - return yaml.load(yamlContent); -} -function getActionInputs() { - const actionYaml = loadActionYaml(); - return actionYaml.inputs; -} -function getActionInputsWithDefaults() { - const inputs = getActionInputs(); - const inputsWithDefaults = {}; - for (const [key, value] of Object.entries(inputs)) { - inputsWithDefaults[key] = value.default; +exports.Issue = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class Issue { + get title() { + return this.inputs?.issue?.title ?? github.context.payload.issue?.title ?? ''; + } + get number() { + return this.inputs?.issue?.number ?? github.context.payload.issue?.number ?? -1; + } + get creator() { + return this.inputs?.issue?.user?.login ?? github.context.payload.issue?.user.login ?? ''; + } + get url() { + return this.inputs?.issue?.html_url ?? github.context.payload.issue?.html_url ?? ''; + } + get body() { + return this.inputs?.issue?.body ?? github.context.payload.issue?.body ?? ''; + } + get opened() { + return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); + } + get labeled() { + return (this.inputs?.action ?? github.context.payload.action) === 'labeled'; + } + get labelAdded() { + return this.inputs?.label?.name ?? github.context.payload.label?.name ?? ''; + } + get isIssue() { + return (this.inputs?.eventName ?? github.context.eventName) === 'issues'; + } + get isIssueComment() { + return (this.inputs?.eventName ?? github.context.eventName) === 'issue_comment'; + } + get commentId() { + return this.inputs?.comment?.id ?? github.context.payload.comment?.id ?? -1; + } + get commentBody() { + return this.inputs?.comment?.body ?? github.context.payload.comment?.body ?? ''; + } + get commentAuthor() { + return this.inputs?.comment?.user?.login ?? github.context.payload.comment?.user.login ?? ''; + } + get commentUrl() { + return this.inputs?.comment?.html_url ?? github.context.payload.comment?.html_url ?? ''; + } + constructor(branchManagementAlways, reopenOnPush, desiredAssigneesCount, inputs = undefined) { + this.inputs = undefined; + this.branchManagementAlways = branchManagementAlways; + this.reopenOnPush = reopenOnPush; + this.desiredAssigneesCount = desiredAssigneesCount; + this.inputs = inputs; } - return inputsWithDefaults; } +exports.Issue = Issue; /***/ }), -/***/ 24240: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = require(__nccwpck_require__.ab + "build/Release/cpufeatures.node") - -/***/ }), - -/***/ 29041: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = require(__nccwpck_require__.ab + "lib/protocol/crypto/build/Release/sshcrypto.node") - -/***/ }), - -/***/ 30132: -/***/ ((module) => { - -module.exports = eval("require")("supports-color"); - - -/***/ }), - -/***/ 39491: -/***/ ((module) => { - -"use strict"; -module.exports = require("assert"); - -/***/ }), - -/***/ 50852: -/***/ ((module) => { - -"use strict"; -module.exports = require("async_hooks"); - -/***/ }), - -/***/ 14300: -/***/ ((module) => { - -"use strict"; -module.exports = require("buffer"); - -/***/ }), - -/***/ 32081: -/***/ ((module) => { - -"use strict"; -module.exports = require("child_process"); - -/***/ }), - -/***/ 96206: -/***/ ((module) => { - -"use strict"; -module.exports = require("console"); - -/***/ }), - -/***/ 22057: -/***/ ((module) => { - -"use strict"; -module.exports = require("constants"); - -/***/ }), - -/***/ 6113: -/***/ ((module) => { - -"use strict"; -module.exports = require("crypto"); - -/***/ }), - -/***/ 67643: -/***/ ((module) => { - -"use strict"; -module.exports = require("diagnostics_channel"); - -/***/ }), - -/***/ 9523: -/***/ ((module) => { - -"use strict"; -module.exports = require("dns"); - -/***/ }), - -/***/ 82361: -/***/ ((module) => { +/***/ 1975: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("events"); - -/***/ }), -/***/ 57147: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueTypes = void 0; +class IssueTypes { + constructor(task, taskDescription, taskColor, bug, bugDescription, bugColor, feature, featureDescription, featureColor, documentation, documentationDescription, documentationColor, maintenance, maintenanceDescription, maintenanceColor, hotfix, hotfixDescription, hotfixColor, release, releaseDescription, releaseColor, question, questionDescription, questionColor, help, helpDescription, helpColor) { + this.task = task; + this.taskDescription = taskDescription; + this.taskColor = taskColor; + this.bug = bug; + this.bugDescription = bugDescription; + this.bugColor = bugColor; + this.feature = feature; + this.featureDescription = featureDescription; + this.featureColor = featureColor; + this.documentation = documentation; + this.documentationDescription = documentationDescription; + this.documentationColor = documentationColor; + this.maintenance = maintenance; + this.maintenanceDescription = maintenanceDescription; + this.maintenanceColor = maintenanceColor; + this.hotfix = hotfix; + this.hotfixDescription = hotfixDescription; + this.hotfixColor = hotfixColor; + this.release = release; + this.releaseDescription = releaseDescription; + this.releaseColor = releaseColor; + this.question = question; + this.questionDescription = questionDescription; + this.questionColor = questionColor; + this.help = help; + this.helpDescription = helpDescription; + this.helpColor = helpColor; + } +} +exports.IssueTypes = IssueTypes; -"use strict"; -module.exports = require("fs"); /***/ }), -/***/ 13685: -/***/ ((module) => { +/***/ 818: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("http"); - -/***/ }), -/***/ 85158: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Labels = void 0; +class Labels { + get isMandatoryBranchedLabel() { + return this.isHotfix || this.isRelease; + } + get containsBranchedLabel() { + return this.currentIssueLabels.includes(this.branchManagementLauncherLabel); + } + get isDeploy() { + return this.currentIssueLabels.includes(this.deploy); + } + get isDeployed() { + return this.currentIssueLabels.includes(this.deployed); + } + get isHelp() { + return this.currentIssueLabels.includes(this.help); + } + get isQuestion() { + return this.currentIssueLabels.includes(this.question); + } + get isFeature() { + return this.currentIssueLabels.includes(this.feature); + } + get isEnhancement() { + return this.currentIssueLabels.includes(this.enhancement); + } + get isBugfix() { + return this.currentIssueLabels.includes(this.bugfix); + } + get isBug() { + return this.currentIssueLabels.includes(this.bug); + } + get isHotfix() { + return this.currentIssueLabels.includes(this.hotfix); + } + get isRelease() { + return this.currentIssueLabels.includes(this.release); + } + get isDocs() { + return this.currentIssueLabels.includes(this.docs); + } + get isDocumentation() { + return this.currentIssueLabels.includes(this.documentation); + } + get isChore() { + return this.currentIssueLabels.includes(this.chore); + } + get isMaintenance() { + return this.currentIssueLabels.includes(this.maintenance); + } + get sizeLabels() { + return [this.sizeXxl, this.sizeXl, this.sizeL, this.sizeM, this.sizeS, this.sizeXs]; + } + get sizedLabelOnIssue() { + if (this.currentIssueLabels.includes(this.sizeXxl)) { + return this.sizeXxl; + } + else if (this.currentIssueLabels.includes(this.sizeXl)) { + return this.sizeXl; + } + else if (this.currentIssueLabels.includes(this.sizeL)) { + return this.sizeL; + } + else if (this.currentIssueLabels.includes(this.sizeM)) { + return this.sizeM; + } + else if (this.currentIssueLabels.includes(this.sizeS)) { + return this.sizeS; + } + else if (this.currentIssueLabels.includes(this.sizeXs)) { + return this.sizeXs; + } + return undefined; + } + get sizedLabelOnPullRequest() { + if (this.currentPullRequestLabels.includes(this.sizeXxl)) { + return this.sizeXxl; + } + else if (this.currentPullRequestLabels.includes(this.sizeXl)) { + return this.sizeXl; + } + else if (this.currentPullRequestLabels.includes(this.sizeL)) { + return this.sizeL; + } + else if (this.currentPullRequestLabels.includes(this.sizeM)) { + return this.sizeM; + } + else if (this.currentPullRequestLabels.includes(this.sizeS)) { + return this.sizeS; + } + else if (this.currentPullRequestLabels.includes(this.sizeXs)) { + return this.sizeXs; + } + return undefined; + } + get isIssueSized() { + return this.sizedLabelOnIssue !== undefined; + } + get isPullRequestSized() { + return this.sizedLabelOnPullRequest !== undefined; + } + get priorityLabels() { + return [this.priorityHigh, this.priorityMedium, this.priorityLow, this.priorityNone]; + } + get priorityLabelOnIssue() { + if (this.currentIssueLabels.includes(this.priorityHigh)) { + return this.priorityHigh; + } + else if (this.currentIssueLabels.includes(this.priorityMedium)) { + return this.priorityMedium; + } + else if (this.currentIssueLabels.includes(this.priorityLow)) { + return this.priorityLow; + } + else if (this.currentIssueLabels.includes(this.priorityNone)) { + return this.priorityNone; + } + return undefined; + } + get priorityLabelOnIssueProcessable() { + return this.currentIssueLabels.includes(this.priorityHigh) || + this.currentIssueLabels.includes(this.priorityMedium) || + this.currentIssueLabels.includes(this.priorityLow); + } + get priorityLabelOnPullRequest() { + if (this.currentPullRequestLabels.includes(this.priorityHigh)) { + return this.priorityHigh; + } + else if (this.currentPullRequestLabels.includes(this.priorityMedium)) { + return this.priorityMedium; + } + else if (this.currentPullRequestLabels.includes(this.priorityLow)) { + return this.priorityLow; + } + else if (this.currentPullRequestLabels.includes(this.priorityNone)) { + return this.priorityNone; + } + return undefined; + } + get priorityLabelOnPullRequestProcessable() { + return this.currentPullRequestLabels.includes(this.priorityHigh) || + this.currentPullRequestLabels.includes(this.priorityMedium) || + this.currentPullRequestLabels.includes(this.priorityLow); + } + get isIssuePrioritized() { + return this.priorityLabelOnIssue !== undefined && this.priorityLabelOnIssue !== this.priorityNone; + } + get isPullRequestPrioritized() { + return this.priorityLabelOnPullRequest !== undefined && this.priorityLabelOnPullRequest !== this.priorityNone; + } + constructor(branchManagementLauncherLabel, bug, bugfix, hotfix, enhancement, feature, release, question, help, deploy, deployed, docs, documentation, chore, maintenance, priorityHigh, priorityMedium, priorityLow, priorityNone, sizeXxl, sizeXl, sizeL, sizeM, sizeS, sizeXs) { + this.currentIssueLabels = []; + this.currentPullRequestLabels = []; + this.branchManagementLauncherLabel = branchManagementLauncherLabel; + this.bug = bug; + this.bugfix = bugfix; + this.hotfix = hotfix; + this.enhancement = enhancement; + this.feature = feature; + this.release = release; + this.question = question; + this.help = help; + this.deploy = deploy; + this.deployed = deployed; + this.docs = docs; + this.documentation = documentation; + this.chore = chore; + this.maintenance = maintenance; + this.sizeXxl = sizeXxl; + this.sizeXl = sizeXl; + this.sizeL = sizeL; + this.sizeM = sizeM; + this.sizeS = sizeS; + this.sizeXs = sizeXs; + this.priorityHigh = priorityHigh; + this.priorityMedium = priorityMedium; + this.priorityLow = priorityLow; + this.priorityNone = priorityNone; + } +} +exports.Labels = Labels; -"use strict"; -module.exports = require("http2"); /***/ }), -/***/ 95687: -/***/ ((module) => { +/***/ 2152: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("https"); - -/***/ }), -/***/ 41808: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Locale = void 0; +class Locale { + constructor(issue, pullRequest) { + this.issue = issue; + this.pullRequest = pullRequest; + } +} +exports.Locale = Locale; +Locale.DEFAULT = 'en-US'; -"use strict"; -module.exports = require("net"); /***/ }), -/***/ 17718: -/***/ ((module) => { +/***/ 2298: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("node:child_process"); - -/***/ }), -/***/ 6005: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Milestone = void 0; +class Milestone { + constructor(id, title, description) { + this.id = id; + this.title = title; + this.description = description; + } +} +exports.Milestone = Milestone; -"use strict"; -module.exports = require("node:crypto"); /***/ }), -/***/ 15673: -/***/ ((module) => { +/***/ 3765: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("node:events"); -/***/ }), - -/***/ 87561: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProjectDetail = void 0; +class ProjectDetail { + constructor(data) { + this.id = data[`id`] ?? ''; + this.title = data[`title`] ?? ''; + this.type = data[`type`] ?? ''; + this.owner = data[`owner`] ?? ''; + this.url = data[`url`] ?? ''; + this.number = data[`number`] ?? -1; + } +} +exports.ProjectDetail = ProjectDetail; -"use strict"; -module.exports = require("node:fs"); /***/ }), -/***/ 49411: -/***/ ((module) => { +/***/ 1938: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("node:path"); - -/***/ }), -/***/ 97742: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Projects = void 0; +class Projects { + constructor(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress) { + this.projects = projects; + this.projectColumnIssueCreated = projectColumnIssueCreated; + this.projectColumnPullRequestCreated = projectColumnPullRequestCreated; + this.projectColumnIssueInProgress = projectColumnIssueInProgress; + this.projectColumnPullRequestInProgress = projectColumnPullRequestInProgress; + } + getProjects() { + return this.projects; + } + getProjectColumnIssueCreated() { + return this.projectColumnIssueCreated; + } + getProjectColumnPullRequestCreated() { + return this.projectColumnPullRequestCreated; + } + getProjectColumnIssueInProgress() { + return this.projectColumnIssueInProgress; + } + getProjectColumnPullRequestInProgress() { + return this.projectColumnPullRequestInProgress; + } +} +exports.Projects = Projects; -"use strict"; -module.exports = require("node:process"); /***/ }), -/***/ 84492: -/***/ ((module) => { +/***/ 4179: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -module.exports = require("node:stream"); - -/***/ }), -/***/ 47261: -/***/ ((module) => { +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullRequest = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class PullRequest { + get action() { + return this.inputs?.action ?? github.context.payload.action ?? ''; + } + get id() { + return this.inputs?.pull_request?.node_id ?? github.context.payload.pull_request?.node_id ?? ''; + } + get title() { + return this.inputs?.pull_request?.title ?? github.context.payload.pull_request?.title ?? ''; + } + get creator() { + return this.inputs?.pull_request?.user?.login ?? github.context.payload.pull_request?.user.login ?? ''; + } + get number() { + return this.inputs?.pull_request?.number ?? github.context.payload.pull_request?.number ?? -1; + } + get url() { + return this.inputs?.pull_request?.html_url ?? github.context.payload.pull_request?.html_url ?? ''; + } + get body() { + return this.inputs?.pull_request?.body ?? github.context.payload.pull_request?.body ?? ''; + } + get head() { + return this.inputs?.pull_request?.head?.ref ?? github.context.payload.pull_request?.head.ref ?? ''; + } + get base() { + return this.inputs?.pull_request?.base?.ref ?? github.context.payload.pull_request?.base.ref ?? ''; + } + get isMerged() { + return this.inputs?.pull_request?.merged ?? github.context.payload.pull_request?.merged ?? false; + } + get opened() { + return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); + } + get isOpened() { + return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'open' + && this.action !== 'closed'; + } + get isClosed() { + return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'closed' + || this.action === 'closed'; + } + get isSynchronize() { + return this.action === 'synchronize'; + } + get isPullRequest() { + return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request'; + } + get isPullRequestReviewComment() { + return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request_review_comment'; + } + get commentId() { + return this.inputs?.pull_request_review_comment?.id ?? github.context.payload.pull_request_review_comment?.id ?? -1; + } + get commentBody() { + return this.inputs?.pull_request_review_comment?.body ?? github.context.payload.pull_request_review_comment?.body ?? ''; + } + get commentAuthor() { + return this.inputs?.pull_request_review_comment?.user?.login ?? github.context.payload.pull_request_review_comment?.user.login ?? ''; + } + get commentUrl() { + return this.inputs?.pull_request_review_comment?.html_url ?? github.context.payload.pull_request_review_comment?.html_url ?? ''; + } + constructor(desiredAssigneesCount, desiredReviewersCount, mergeTimeout, inputs = undefined) { + this.inputs = undefined; + this.desiredAssigneesCount = desiredAssigneesCount; + this.desiredReviewersCount = desiredReviewersCount; + this.mergeTimeout = mergeTimeout; + this.inputs = inputs; + } +} +exports.PullRequest = PullRequest; -"use strict"; -module.exports = require("node:util"); /***/ }), -/***/ 22037: -/***/ ((module) => { +/***/ 2551: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("os"); -/***/ }), - -/***/ 71017: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Release = void 0; +class Release { + constructor() { + this.active = false; + } +} +exports.Release = Release; -"use strict"; -module.exports = require("path"); /***/ }), -/***/ 4074: -/***/ ((module) => { +/***/ 7305: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("perf_hooks"); - -/***/ }), -/***/ 77282: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Result = void 0; +class Result { + constructor(data) { + this.id = data['id'] ?? ''; + this.success = data['success'] ?? false; + this.executed = data['executed'] ?? false; + this.steps = data['steps'] ?? []; + this.errors = data['errors'] ?? []; + this.payload = data['payload']; + this.reminders = data['reminders'] ?? []; + } +} +exports.Result = Result; -"use strict"; -module.exports = require("process"); /***/ }), -/***/ 85477: -/***/ ((module) => { +/***/ 8024: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -module.exports = require("punycode"); - -/***/ }), -/***/ 63477: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SingleAction = void 0; +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class SingleAction { + get isDeployedAction() { + return this.currentSingleAction === constants_1.ACTIONS.DEPLOYED; + } + get isAiCacheAction() { + return this.currentSingleAction === constants_1.ACTIONS.AI_CACHE || this.currentSingleAction === constants_1.ACTIONS.AI_CACHE_LOCAL; + } + get isAiCacheLocalAction() { + return this.currentSingleAction === constants_1.ACTIONS.AI_CACHE_LOCAL; + } + get isPublishGithubAction() { + return this.currentSingleAction === constants_1.ACTIONS.PUBLISH_GITHUB_ACTION; + } + get isCreateReleaseAction() { + return this.currentSingleAction === constants_1.ACTIONS.CREATE_RELEASE; + } + get isCreateTagAction() { + return this.currentSingleAction === constants_1.ACTIONS.CREATE_TAG; + } + get isThinkAction() { + return this.currentSingleAction === constants_1.ACTIONS.THINK; + } + get enabledSingleAction() { + return this.currentSingleAction.length > 0; + } + get validSingleAction() { + return this.enabledSingleAction && + (this.issue > 0 || this.isSingleActionWithoutIssue) && + this.actions.indexOf(this.currentSingleAction) > -1; + } + get isSingleActionWithoutIssue() { + return this.actionsWithoutIssue.indexOf(this.currentSingleAction) > -1; + } + get throwError() { + return this.actionsThrowError.indexOf(this.currentSingleAction) > -1; + } + constructor(currentSingleAction, issue, version, title, changelog) { + this.actions = [ + constants_1.ACTIONS.DEPLOYED, + constants_1.ACTIONS.AI_CACHE, + constants_1.ACTIONS.AI_CACHE_LOCAL, + constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, + constants_1.ACTIONS.CREATE_TAG, + constants_1.ACTIONS.CREATE_RELEASE, + constants_1.ACTIONS.THINK, + ]; + /** + * Actions that throw an error if the last step failed + */ + this.actionsThrowError = [ + constants_1.ACTIONS.AI_CACHE, + constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, + constants_1.ACTIONS.CREATE_RELEASE, + constants_1.ACTIONS.DEPLOYED, + constants_1.ACTIONS.CREATE_TAG, + ]; + /** + * Actions that do not require an issue + */ + this.actionsWithoutIssue = [ + constants_1.ACTIONS.AI_CACHE, + constants_1.ACTIONS.AI_CACHE_LOCAL, + constants_1.ACTIONS.THINK, + ]; + this.isIssue = false; + this.isPullRequest = false; + this.isPush = false; + /** + * Properties + */ + this.issue = -1; + this.version = ''; + this.title = ''; + this.changelog = ''; + this.version = version; + this.title = title; + this.changelog = changelog; + if (!this.isSingleActionWithoutIssue) { + try { + this.issue = parseInt(issue); + } + catch (error) { + (0, logger_1.logError)(`Issue ${issue} is not a number.`); + (0, logger_1.logError)(error); + } + } + else { + this.issue = 0; + } + this.currentSingleAction = currentSingleAction; + } +} +exports.SingleAction = SingleAction; -"use strict"; -module.exports = require("querystring"); /***/ }), -/***/ 14521: -/***/ ((module) => { +/***/ 3835: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("readline"); -/***/ }), - -/***/ 12781: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SizeThreshold = void 0; +class SizeThreshold { + constructor(lines, files, commits) { + this.lines = lines; + this.files = files; + this.commits = commits; + } +} +exports.SizeThreshold = SizeThreshold; -"use strict"; -module.exports = require("stream"); /***/ }), -/***/ 35356: -/***/ ((module) => { +/***/ 8237: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("stream/web"); - -/***/ }), -/***/ 71576: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SizeThresholds = void 0; +class SizeThresholds { + constructor(xxl, xl, l, m, s, xs) { + this.xxl = xxl; + this.xl = xl; + this.l = l; + this.m = m; + this.s = s; + this.xs = xs; + } +} +exports.SizeThresholds = SizeThresholds; -"use strict"; -module.exports = require("string_decoder"); /***/ }), -/***/ 39512: -/***/ ((module) => { +/***/ 149: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("timers"); -/***/ }), - -/***/ 24404: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SupabaseConfig = void 0; +class SupabaseConfig { + constructor(url, key) { + this.url = url; + this.key = key; + } + getUrl() { + return this.url; + } + getKey() { + return this.key; + } +} +exports.SupabaseConfig = SupabaseConfig; -"use strict"; -module.exports = require("tls"); /***/ }), -/***/ 76224: -/***/ ((module) => { +/***/ 7057: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("tty"); - -/***/ }), -/***/ 57310: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.THINK_RESPONSE_JSON_SCHEMA = void 0; +/** + * JSON Schema for ThinkResponse interface + * This schema is used for structured AI reasoning and analysis responses + */ +exports.THINK_RESPONSE_JSON_SCHEMA = { + type: "object", + properties: { + reasoning: { + type: "string", + description: "Current reasoning step or analysis of the problem" + }, + action: { + type: "string", + enum: ["search_files", "read_file", "analyze_code", "propose_changes", "complete", "update_todos"], + description: "Next action to take in the reasoning process" + }, + files_to_search: { + type: "array", + items: { + type: "string" + }, + description: "List of file paths or patterns to search for (when action is 'search_files')" + }, + files_to_read: { + type: "array", + items: { + type: "string" + }, + description: "List of specific file paths to read in full (when action is 'read_file')" + }, + analyzed_files: { + type: "array", + items: { + type: "object", + properties: { + path: { type: "string" }, + key_findings: { type: "string" }, + relevance: { type: "string", enum: ["high", "medium", "low"] } + }, + required: ["path", "key_findings", "relevance"] + }, + description: "Files that have been analyzed with their findings (when action is 'analyze_code')" + }, + proposed_changes: { + type: "array", + items: { + type: "object", + properties: { + file_path: { type: "string" }, + change_type: { type: "string", enum: ["create", "modify", "delete", "refactor"] }, + description: { type: "string" }, + suggested_code: { type: "string" }, + reasoning: { type: "string" } + }, + required: ["file_path", "change_type", "description", "reasoning"] + }, + description: "Proposed changes to the codebase (when action is 'propose_changes')" + }, + complete: { + type: "boolean", + description: "Whether the reasoning process is complete" + }, + final_analysis: { + type: "string", + description: "Final comprehensive analysis and recommendations (when complete is true)" + }, + todo_updates: { + type: "object", + description: "Updates to the TODO list (when action is 'update_todos' or alongside other actions)", + properties: { + create: { + type: "array", + items: { + type: "object", + properties: { + content: { type: "string" }, + status: { type: "string", enum: ["pending", "in_progress"] } + }, + required: ["content"] + }, + description: "New TODO items to create" + }, + update: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "string" }, + status: { type: "string", enum: ["pending", "in_progress", "completed", "cancelled"] }, + notes: { type: "string" } + }, + required: ["id"] + }, + description: "Updates to existing TODO items" + } + } + } + }, + required: ["reasoning", "action", "complete"], + additionalProperties: false +}; -"use strict"; -module.exports = require("url"); /***/ }), -/***/ 73837: -/***/ ((module) => { +/***/ 3421: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("util"); - -/***/ }), -/***/ 29830: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Tokens = void 0; +class Tokens { + constructor(token) { + this.token = token; + } +} +exports.Tokens = Tokens; -"use strict"; -module.exports = require("util/types"); /***/ }), -/***/ 71267: -/***/ ((module) => { +/***/ 9471: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -module.exports = require("worker_threads"); - -/***/ }), -/***/ 59796: -/***/ ((module) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Welcome = void 0; +class Welcome { + constructor(title, messages) { + this.title = title; + this.messages = messages; + } +} +exports.Welcome = Welcome; -"use strict"; -module.exports = require("zlib"); /***/ }), -/***/ 92960: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 6845: +/***/ ((__unused_webpack_module, exports) => { "use strict"; +// types.ts (o donde quieras definir tus modelos) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WorkflowRun = void 0; +class WorkflowRun { + // puedes agregar mĆ”s campos si los usas + constructor(data) { + this.id = data.id; + this.name = data.name; + this.head_branch = data.head_branch; + this.head_sha = data.head_sha; + this.run_number = data.run_number; + this.event = data.event; + this.status = data.status; + this.conclusion = data.conclusion; + this.created_at = data.created_at; + this.updated_at = data.updated_at; + this.url = data.url; + this.html_url = data.html_url; + } + isActive() { + return this.status === "in_progress" || this.status === "queued"; + } +} +exports.WorkflowRun = WorkflowRun; -const WritableStream = (__nccwpck_require__(84492).Writable) -const inherits = (__nccwpck_require__(47261).inherits) - -const StreamSearch = __nccwpck_require__(51142) - -const PartStream = __nccwpck_require__(81620) -const HeaderParser = __nccwpck_require__(92032) - -const DASH = 45 -const B_ONEDASH = Buffer.from('-') -const B_CRLF = Buffer.from('\r\n') -const EMPTY_FN = function () {} - -function Dicer (cfg) { - if (!(this instanceof Dicer)) { return new Dicer(cfg) } - WritableStream.call(this, cfg) - - if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - - if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - this._headerFirst = cfg.headerFirst +/***/ }), - this._dashes = 0 - this._parts = 0 - this._finished = false - this._realFinish = false - this._isPreamble = true - this._justMatched = false - this._firstWrite = true - this._inHeader = true - this._part = undefined - this._cb = undefined - this._ignoreData = false - this._partOpts = { highWaterMark: cfg.partHwm } - this._pause = false +/***/ 8553: +/***/ ((__unused_webpack_module, exports) => { - const self = this - this._hparser = new HeaderParser(cfg) - this._hparser.on('header', function (header) { - self._inHeader = false - self._part.emit('header', header) - }) -} -inherits(Dicer, WritableStream) +"use strict"; -Dicer.prototype.emit = function (ev) { - if (ev === 'finish' && !this._realFinish) { - if (!this._finished) { - const self = this - process.nextTick(function () { - self.emit('error', new Error('Unexpected end of multipart data')) - if (self._part && !self._ignoreData) { - const type = (self._isPreamble ? 'Preamble' : 'Part') - self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) - self._part.push(null) - process.nextTick(function () { - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - return - } - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Workflows = void 0; +class Workflows { + constructor(release, hotfix) { + this.release = release; + this.hotfix = hotfix; } - } else { WritableStream.prototype.emit.apply(this, arguments) } } +exports.Workflows = Workflows; -Dicer.prototype._write = function (data, encoding, cb) { - // ignore unexpected data (e.g. extra trailer data after finished) - if (!this._hparser && !this._bparser) { return cb() } - if (this._headerFirst && this._isPreamble) { - if (!this._part) { - this._part = new PartStream(this._partOpts) - if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } - } - const r = this._hparser.push(data) - if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } - } +/***/ }), - // allows for "easier" testing - if (this._firstWrite) { - this._bparser.push(B_CRLF) - this._firstWrite = false - } +/***/ 8307: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this._bparser.push(data) +"use strict"; - if (this._pause) { this._cb = cb } else { cb() } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AiRepository = void 0; +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +const ai_response_schema_1 = __nccwpck_require__(5968); +const think_response_schema_1 = __nccwpck_require__(7057); +class AiRepository { + constructor() { + this.ask = async (ai, prompt) => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + if (!model || !apiKey) { + (0, logger_1.logError)('Missing required AI configuration'); + return undefined; + } + (0, logger_1.logDebugInfo)(`šŸ”Ž Model: ${model}`); + (0, logger_1.logDebugInfo)(`šŸ”Ž API Key: ***`); + (0, logger_1.logDebugInfo)(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + const url = `https://openrouter.ai/api/v1/chat/completions`; + try { + (0, logger_1.logDebugInfo)(`Sending prompt to ${model}: ${prompt}`); + const requestBody = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + }; + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': constants_1.REPO_URL, + 'X-Title': constants_1.TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + const data = await response.json(); + if (!data.choices || data.choices.length === 0) { + (0, logger_1.logError)('No response content received from API'); + return undefined; + } + // logDebugInfo(`Successfully received response from ${model}`); + return data.choices[0].message.content; + } + catch (error) { + (0, logger_1.logError)(`Error querying ${model}: ${error}`); + return undefined; + } + }; + this.askJson = async (ai, prompt, schema, schemaName = "ai_response") => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + if (!model || !apiKey) { + (0, logger_1.logError)('Missing required AI configuration'); + return undefined; + } + // logDebugInfo(`šŸ”Ž Model: ${model}`); + // logDebugInfo(`šŸ”Ž API Key: ***`); + // logDebugInfo(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + const url = `https://openrouter.ai/api/v1/chat/completions`; + // Use provided schema or default to AI_RESPONSE_JSON_SCHEMA + const responseSchema = schema || ai_response_schema_1.AI_RESPONSE_JSON_SCHEMA; + try { + const requestBody = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + response_format: { + type: "json_schema", + json_schema: { + name: schemaName, + schema: responseSchema, + strict: true + } + } + }; + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': constants_1.REPO_URL, + 'X-Title': constants_1.TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + const data = await response.json(); + if (!data.choices || data.choices.length === 0) { + (0, logger_1.logError)('No response content received from API'); + return undefined; + } + // logDebugInfo(`Successfully received response from ${model}`); + const content = data.choices[0].message.content; + // logDebugInfo(`Response: ${content}`); + return JSON.parse(content); + } + catch (error) { + (0, logger_1.logError)(`Error querying ${model}: ${error}`); + return undefined; + } + }; + this.askThinkJson = async (ai, prompt) => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + if (!model || !apiKey) { + (0, logger_1.logError)('Missing required AI configuration'); + return undefined; + } + (0, logger_1.logDebugInfo)(`šŸ”Ž Model: ${model}`); + (0, logger_1.logDebugInfo)(`šŸ”Ž API Key: ***`); + (0, logger_1.logDebugInfo)(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + const url = `https://openrouter.ai/api/v1/chat/completions`; + try { + const requestBody = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + response_format: { + type: "json_schema", + json_schema: { + name: "think_response", + schema: think_response_schema_1.THINK_RESPONSE_JSON_SCHEMA, + strict: true + } + } + }; + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': constants_1.REPO_URL, + 'X-Title': constants_1.TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + const data = await response.json(); + if (!data.choices || data.choices.length === 0) { + (0, logger_1.logError)('No response content received from API'); + return undefined; + } + // logDebugInfo(`Successfully received response from ${model}`); + const content = data.choices[0].message.content; + // logDebugInfo(`Response: ${content}`); + return JSON.parse(content); + } + catch (error) { + (0, logger_1.logError)(`Error querying ${model}: ${error}`); + return undefined; + } + }; + } } +exports.AiRepository = AiRepository; -Dicer.prototype.reset = function () { - this._part = undefined - this._bparser = undefined - this._hparser = undefined -} -Dicer.prototype.setBoundary = function (boundary) { - const self = this - this._bparser = new StreamSearch('\r\n--' + boundary) - this._bparser.on('info', function (isMatch, data, start, end) { - self._oninfo(isMatch, data, start, end) - }) -} +/***/ }), -Dicer.prototype._ignore = function () { - if (this._part && !this._ignoreData) { - this._ignoreData = true - this._part.on('error', EMPTY_FN) - // we must perform some kind of read on the stream even though we are - // ignoring the data, otherwise node's Readable stream will not emit 'end' - // after pushing null to the stream - this._part.resume() - } -} +/***/ 7701: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -Dicer.prototype._oninfo = function (isMatch, data, start, end) { - let buf; const self = this; let i = 0; let r; let shouldWriteMore = true +"use strict"; - if (!this._part && this._justMatched && data) { - while (this._dashes < 2 && (start + i) < end) { - if (data[start + i] === DASH) { - ++i - ++this._dashes - } else { - if (this._dashes) { buf = B_ONEDASH } - this._dashes = 0 - break - } - } - if (this._dashes === 2) { - if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } - this.reset() - this._finished = true - // no more parts will be added - if (self._parts === 0) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } - } - if (this._dashes) { return } - } - if (this._justMatched) { this._justMatched = false } - if (!this._part) { - this._part = new PartStream(this._partOpts) - this._part._read = function (n) { - self._unpause() - } - if (this._isPreamble && this.listenerCount('preamble') !== 0) { - this.emit('preamble', this._part) - } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { - this.emit('part', this._part) - } else { - this._ignore() - } - if (!this._isPreamble) { this._inHeader = true } - } - if (data && start < end && !this._ignoreData) { - if (this._isPreamble || !this._inHeader) { - if (buf) { shouldWriteMore = this._part.push(buf) } - shouldWriteMore = this._part.push(data.slice(start, end)) - if (!shouldWriteMore) { this._pause = true } - } else if (!this._isPreamble && this._inHeader) { - if (buf) { this._hparser.push(buf) } - r = this._hparser.push(data.slice(start, end)) - if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } +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]; } }; } - } - if (isMatch) { - this._hparser.reset() - if (this._isPreamble) { this._isPreamble = false } else { - if (start !== end) { - ++this._parts - this._part.on('end', function () { - if (--self._parts === 0) { - if (self._finished) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } else { - self._unpause() + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BranchRepository = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const version_utils_1 = __nccwpck_require__(9887); +const result_1 = __nccwpck_require__(7305); +class BranchRepository { + constructor() { + this.fetchRemoteBranches = async () => { + try { + (0, logger_1.logDebugInfo)('Fetching tags and forcing fetch...'); + await exec.exec('git', ['fetch', '--tags', '--force']); + (0, logger_1.logDebugInfo)('Fetching all remote branches with verbose output...'); + await exec.exec('git', ['fetch', '--all', '-v']); + (0, logger_1.logDebugInfo)('Successfully fetched all remote branches.'); + } + catch (error) { + core.setFailed(`Error fetching remote branches: ${error}`); + } + }; + this.getLatestTag = async () => { + try { + (0, logger_1.logDebugInfo)('Fetching the latest tag...'); + await exec.exec('git', ['fetch', '--tags']); + const tags = []; + await exec.exec('git', ['tag', '--sort=-creatordate'], { + listeners: { + stdout: (data) => { + tags.push(...data.toString().split('\n').map((v, i, a) => { + return v.replace('v', ''); + })); + }, + }, + }); + const validTags = tags.filter(tag => /\d+\.\d+\.\d+$/.test(tag)); + if (validTags.length > 0) { + const latestTag = (0, version_utils_1.getLatestVersion)(validTags); + (0, logger_1.logDebugInfo)(`Latest tag: ${latestTag}`); + return latestTag; + } + else { + (0, logger_1.logDebugInfo)('No valid tags found.'); + return undefined; + } + } + catch (error) { + core.setFailed(`Error fetching the latest tag: ${error}`); + return undefined; + } + }; + this.getCommitTag = async (latestTag) => { + try { + if (!latestTag) { + core.setFailed('No LATEST_TAG found in the environment'); + return; + } + let tagVersion; + if (latestTag.startsWith('v')) { + tagVersion = latestTag; + } + else { + tagVersion = `v${latestTag}`; + } + (0, logger_1.logDebugInfo)(`Fetching commit hash for the tag: ${tagVersion}`); + let commitOid = ''; + await exec.exec('git', ['rev-list', '-n', '1', tagVersion], { + listeners: { + stdout: (data) => { + commitOid = data.toString().trim(); + }, + }, + }); + if (commitOid) { + (0, logger_1.logDebugInfo)(`Commit tag: ${commitOid}`); + return commitOid; + } + else { + core.setFailed('No commit found for the tag'); + } + } + catch (error) { + core.setFailed(`Error fetching the commit hash: ${error}`); + } + return undefined; + }; + /** + * Returns replaced branch (if any). + * + * @param param + * @param repository + * @param owner + * @param token + * @param issueNumber + * @param issueTitle + * @param branchType + * @param developmentBranch + * @param hotfixBranch + * @param isHotfix + */ + this.manageBranches = async (param, owner, repository, issueNumber, issueTitle, branchType, developmentBranch, hotfixBranch, isHotfix, token) => { + const result = []; + try { + (0, logger_1.logDebugInfo)(`Managing branches`); + const branches = await this.getListOfBranches(owner, repository, token); + (0, logger_1.logDebugInfo)(JSON.stringify(branches, null, 2)); + if (hotfixBranch === undefined && isHotfix) { + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Tried to prepare the hotfix branch of the issue, but hotfix branch was not found.`, + ], + })); + return result; + } + const octokit = github.getOctokit(token); + const sanitizedTitle = this.formatBranchName(issueTitle, issueNumber); + const newBranchName = `${branchType}/${issueNumber}-${sanitizedTitle}`; + if (branches.indexOf(newBranchName) > -1) { + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: false, + })); + return result; + } + const branchTypes = [ + param.branches.featureTree, + param.branches.bugfixTree, + param.branches.docsTree, + param.branches.choreTree, + ]; + /** + * Default base branch name. (ex. [develop]) + */ + let baseBranchName = developmentBranch; + if (!isHotfix) { + /** + * Check if it is a branch switch: feature/123-bla <-> bugfix/123-bla + */ + (0, logger_1.logDebugInfo)(`Searching for branches related to issue #${issueNumber}...`); + const { data } = await octokit.rest.repos.listBranches({ + owner: owner, + repo: repository, + }); + for (const type of branchTypes) { + const prefix = `${type}/${issueNumber}-`; + try { + const matchingBranch = data.find(branch => branch.name.indexOf(prefix) > -1); + if (matchingBranch) { + baseBranchName = matchingBranch.name; + (0, logger_1.logDebugInfo)(`Found previous issue branch: ${baseBranchName}`); + // TODO replacedBranchName = baseBranchName + break; + } + } + catch (error) { + (0, logger_1.logError)(`Error while listing branches: ${error}`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Error while listing branches.`, + ], + error: error, + })); + } + } + } + else { + baseBranchName = hotfixBranch ?? developmentBranch; + } + param.currentConfiguration.parentBranch = baseBranchName; + (0, logger_1.logDebugInfo)(`============================================================================================`); + (0, logger_1.logDebugInfo)(`Base branch: ${baseBranchName}`); + (0, logger_1.logDebugInfo)(`New branch: ${newBranchName}`); + result.push(...await this.createLinkedBranch(owner, repository, baseBranchName, newBranchName, issueNumber, undefined, token)); } - } - }) - } - } - this._part.push(null) - this._part = undefined - this._ignoreData = false - this._justMatched = true - this._dashes = 0 - } -} - -Dicer.prototype._unpause = function () { - if (!this._pause) { return } - - this._pause = false - if (this._cb) { - const cb = this._cb - this._cb = undefined - cb() - } -} - -module.exports = Dicer - - -/***/ }), - -/***/ 92032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const EventEmitter = (__nccwpck_require__(15673).EventEmitter) -const inherits = (__nccwpck_require__(47261).inherits) -const getLimit = __nccwpck_require__(21467) - -const StreamSearch = __nccwpck_require__(51142) - -const B_DCRLF = Buffer.from('\r\n\r\n') -const RE_CRLF = /\r\n/g -const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex - -function HeaderParser (cfg) { - EventEmitter.call(this) - - cfg = cfg || {} - const self = this - this.nread = 0 - this.maxed = false - this.npairs = 0 - this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) - this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) - this.buffer = '' - this.header = {} - this.finished = false - this.ss = new StreamSearch(B_DCRLF) - this.ss.on('info', function (isMatch, data, start, end) { - if (data && !self.maxed) { - if (self.nread + end - start >= self.maxHeaderSize) { - end = self.maxHeaderSize - self.nread + start - self.nread = self.maxHeaderSize - self.maxed = true - } else { self.nread += (end - start) } - - self.buffer += data.toString('binary', start, end) - } - if (isMatch) { self._finish() } - }) -} -inherits(HeaderParser, EventEmitter) - -HeaderParser.prototype.push = function (data) { - const r = this.ss.push(data) - if (this.finished) { return r } -} - -HeaderParser.prototype.reset = function () { - this.finished = false - this.buffer = '' - this.header = {} - this.ss.reset() -} - -HeaderParser.prototype._finish = function () { - if (this.buffer) { this._parseHeader() } - this.ss.matches = this.ss.maxMatches - const header = this.header - this.header = {} - this.buffer = '' - this.finished = true - this.nread = this.npairs = 0 - this.maxed = false - this.emit('header', header) -} - -HeaderParser.prototype._parseHeader = function () { - if (this.npairs === this.maxHeaderPairs) { return } - - const lines = this.buffer.split(RE_CRLF) - const len = lines.length - let m, h + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Tried to prepare the hotfix to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; + }; + this.formatBranchName = (issueTitle, issueNumber) => { + let sanitizedTitle = issueTitle.toLowerCase() + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + sanitizedTitle = sanitizedTitle.replace(/[^a-z0-9 ]/g, '').replace(/ /g, '-'); + const issuePrefix = `${issueNumber}-`; + if (sanitizedTitle.startsWith(issuePrefix)) { + sanitizedTitle = sanitizedTitle.substring(issuePrefix.length); + } + sanitizedTitle = sanitizedTitle.replace(/-+/g, '-'); + sanitizedTitle = sanitizedTitle.replace(/^-|-$/g, ''); + return sanitizedTitle; + }; + this.createLinkedBranch = async (owner, repo, baseBranchName, newBranchName, issueNumber, oid, token) => { + const result = []; + try { + (0, logger_1.logDebugInfo)(`Creating linked branch ${newBranchName} from ${oid ?? baseBranchName}`); + let ref = `heads/${baseBranchName}`; + if (baseBranchName.indexOf('tags/') > -1) { + ref = baseBranchName; + } + const octokit = github.getOctokit(token); + const { repository } = await octokit.graphql(` + query($repo: String!, $owner: String!, $issueNumber: Int!) { + repository(name: $repo, owner: $owner) { + id + issue(number: $issueNumber) { + id + } + ref(qualifiedName: "refs/${ref}") { + target { + ... on Commit { + oid + } + } + } + } + } + `, { + repo: repo, + owner: owner, + issueNumber: issueNumber + }); + (0, logger_1.logDebugInfo)(`Repository information retrieved: ${JSON.stringify(repository?.ref)}`); + const repositoryId = repository?.id ?? undefined; + const issueId = repository?.issue?.id ?? undefined; + const branchOid = oid ?? repository?.ref?.target?.oid ?? undefined; + if (repositoryId === undefined || issueNumber === undefined || branchOid === undefined) { + (0, logger_1.logError)(`Error searching repository "${baseBranchName}": id: ${repositoryId}, oid: ${branchOid}), issue #${issueNumber}`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Error linking branch ${newBranchName} to issue: Repository not found.`, + ], + })); + return result; + } + (0, logger_1.logDebugInfo)(`Linking branch "${newBranchName}" (oid: ${branchOid}) to issue #${issueNumber}`); + const mutationResponse = await octokit.graphql(` + mutation($issueId: ID!, $name: String!, $repositoryId: ID!, $oid: GitObjectID!) { + createLinkedBranch(input: { + issueId: $issueId, + name: $name, + repositoryId: $repositoryId, + oid: $oid, + }) { + linkedBranch { + id + ref { + name + } + } + } + } + `, { + issueId: issueId, + name: `/${newBranchName}`, + repositoryId: repositoryId, + oid: branchOid, + }); + (0, logger_1.logDebugInfo)(`Linked branch: ${JSON.stringify(mutationResponse.createLinkedBranch?.linkedBranch)}`); + const baseBranchUrl = `https://github.com/${owner}/${repo}/tree/${baseBranchName}`; + const newBranchUrl = `https://github.com/${owner}/${repo}/tree/${newBranchName}`; + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: true, + payload: { + baseBranchName: baseBranchName, + baseBranchUrl: baseBranchUrl, + newBranchName: newBranchName, + newBranchUrl: newBranchUrl, + }, + })); + } + catch (error) { + (0, logger_1.logError)(`Error Linking branch "${error}"`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Tried to link branch to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; + }; + this.removeBranch = async (owner, repository, branch, token) => { + const octokit = github.getOctokit(token); + const ref = `heads/${branch}`; + try { + const { data } = await octokit.rest.git.getRef({ + owner: owner, + repo: repository, + ref, + }); + (0, logger_1.logDebugInfo)(`Branch found: ${data.ref}`); + await octokit.rest.git.deleteRef({ + owner: owner, + repo: repository, + ref, + }); + (0, logger_1.logDebugInfo)(`Successfully deleted branch: ${branch}`); + return true; + } + catch (error) { + (0, logger_1.logError)(`Error processing branch ${branch}: ${error}`); + throw error; + } + }; + this.getListOfBranches = async (owner, repository, token) => { + const octokit = github.getOctokit(token); + const allBranches = []; + let page = 1; + while (true) { + const { data } = await octokit.rest.repos.listBranches({ + owner: owner, + repo: repository, + per_page: 100, + page: page, + }); + if (data.length === 0) { + break; + } + allBranches.push(...data.map(branch => branch.name)); + page++; + } + return allBranches; + }; + this.executeWorkflow = async (owner, repository, branch, workflow, inputs, token) => { + const octokit = github.getOctokit(token); + return octokit.rest.actions.createWorkflowDispatch({ + owner: owner, + repo: repository, + workflow_id: workflow, + ref: branch, + inputs: inputs + }); + }; + this.mergeBranch = async (owner, repository, head, base, timeout, token) => { + const result = []; + try { + const octokit = github.getOctokit(token); + (0, logger_1.logDebugInfo)(`Creating merge from ${head} into ${base}`); + // Build PR body with commit list + const prBody = `šŸš€ Automated Merge - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (lines[i].length === 0) { continue } - if (lines[i][0] === '\t' || lines[i][0] === ' ') { - // folded header content - // RFC2822 says to just remove the CRLF and not the whitespace following - // it, so we follow the RFC and include the leading whitespace ... - if (h) { - this.header[h][this.header[h].length - 1] += lines[i] - continue - } - } +This PR merges **${head}** into **${base}**. - const posColon = lines[i].indexOf(':') - if ( - posColon === -1 || - posColon === 0 - ) { - return +**Commits included:**`; + // We need PAT for creating PR to ensure it can trigger workflows + const { data: pullRequest } = await octokit.rest.pulls.create({ + owner: owner, + repo: repository, + head: head, + base: base, + title: `Merge ${head} into ${base}`, + body: prBody, + }); + (0, logger_1.logDebugInfo)(`Pull request #${pullRequest.number} created, getting commits...`); + // Get all commits in the PR + const { data: commits } = await octokit.rest.pulls.listCommits({ + owner: owner, + repo: repository, + pull_number: pullRequest.number + }); + const commitMessages = commits.map(commit => commit.commit.message); + (0, logger_1.logDebugInfo)(`Found ${commitMessages.length} commits in PR`); + // Update PR with commit list and footer + await octokit.rest.pulls.update({ + owner: owner, + repo: repository, + pull_number: pullRequest.number, + body: prBody + '\n' + commitMessages.map(msg => `- ${msg}`).join('\n') + + '\n\nThis PR was automatically created by [`git-board-flow`](https://github.com/landamessenger/git-board-flow).' + }); + const iteration = 10; + if (timeout > iteration) { + // Wait for checks to complete - can use regular token for reading checks + let checksCompleted = false; + let attempts = 0; + const maxAttempts = timeout > iteration ? Math.floor(timeout / iteration) : iteration; + while (!checksCompleted && attempts < maxAttempts) { + const { data: checkRuns } = await octokit.rest.checks.listForRef({ + owner: owner, + repo: repository, + ref: head, + }); + // Get commit status checks for the PR head commit + const { data: commitStatus } = await octokit.rest.repos.getCombinedStatusForRef({ + owner: owner, + repo: repository, + ref: head + }); + (0, logger_1.logDebugInfo)(`Combined status state: ${commitStatus.state}`); + (0, logger_1.logDebugInfo)(`Number of check runs: ${checkRuns.check_runs.length}`); + // If there are check runs, prioritize those over status checks + if (checkRuns.check_runs.length > 0) { + const pendingCheckRuns = checkRuns.check_runs.filter(check => check.status !== 'completed'); + if (pendingCheckRuns.length === 0) { + checksCompleted = true; + (0, logger_1.logDebugInfo)('All check runs have completed.'); + // Verify if all checks passed + const failedChecks = checkRuns.check_runs.filter(check => check.conclusion === 'failure'); + if (failedChecks.length > 0) { + throw new Error(`Checks failed: ${failedChecks.map(check => check.name).join(', ')}`); + } + } + else { + (0, logger_1.logDebugInfo)(`Waiting for ${pendingCheckRuns.length} check runs to complete:`); + pendingCheckRuns.forEach(check => { + (0, logger_1.logDebugInfo)(` - ${check.name} (Status: ${check.status})`); + }); + await new Promise(resolve => setTimeout(resolve, iteration * 1000)); + attempts++; + continue; + } + } + else { + // Fall back to status checks if no check runs exist + const pendingChecks = commitStatus.statuses.filter(status => { + (0, logger_1.logDebugInfo)(`Status check: ${status.context} (State: ${status.state})`); + return status.state === 'pending'; + }); + if (pendingChecks.length === 0) { + checksCompleted = true; + (0, logger_1.logDebugInfo)('All status checks have completed.'); + } + else { + (0, logger_1.logDebugInfo)(`Waiting for ${pendingChecks.length} status checks to complete:`); + pendingChecks.forEach(check => { + (0, logger_1.logDebugInfo)(` - ${check.context} (State: ${check.state})`); + }); + await new Promise(resolve => setTimeout(resolve, iteration * 1000)); + attempts++; + } + } + } + if (!checksCompleted) { + throw new Error('Timed out waiting for checks to complete'); + } + } + // Need PAT for merging to ensure it can trigger subsequent workflows + await octokit.rest.pulls.merge({ + owner: owner, + repo: repository, + pull_number: pullRequest.number, + merge_method: 'merge', + commit_title: `Merge ${head} into ${base}. Forced merge with PAT token.`, + }); + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: true, + steps: [ + `The branch \`${head}\` was merged into \`${base}\`.`, + ], + })); + } + catch (error) { + (0, logger_1.logError)(`Error in PR workflow: ${error}`); + // If the PR workflow fails, we try to merge directly - need PAT for direct merge to ensure it can trigger workflows + try { + const octokit = github.getOctokit(token); + await octokit.rest.repos.merge({ + owner: owner, + repo: repository, + base: base, + head: head, + commit_message: `Forced merge of ${head} into ${base}. Automated merge with PAT token.`, + }); + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: true, + steps: [ + `The branch \`${head}\` was merged into \`${base}\` using direct merge.`, + ], + })); + return result; + } + catch (directMergeError) { + (0, logger_1.logError)(`Error in direct merge attempt: ${directMergeError}`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Failed to merge branch \`${head}\` into \`${base}\`.`, + ], + })); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + error: error, + })); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + error: directMergeError, + })); + } + } + return result; + }; + this.getChanges = async (owner, repository, head, base, token) => { + const octokit = github.getOctokit(token); + try { + (0, logger_1.logDebugInfo)(`Comparing branches: ${head} with ${base}`); + let headRef = `heads/${head}`; + if (head.indexOf('tags/') > -1) { + headRef = head; + } + let baseRef = `heads/${base}`; + if (base.indexOf('tags/') > -1) { + baseRef = base; + } + const { data: comparison } = await octokit.rest.repos.compareCommits({ + owner: owner, + repo: repository, + base: baseRef, + head: headRef, + }); + return { + aheadBy: comparison.ahead_by, + behindBy: comparison.behind_by, + totalCommits: comparison.total_commits, + files: (comparison.files || []).map(file => ({ + filename: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + changes: file.changes, + blobUrl: file.blob_url, + rawUrl: file.raw_url, + contentsUrl: file.contents_url, + patch: file.patch + })), + commits: comparison.commits.map(commit => ({ + sha: commit.sha, + message: commit.commit.message, + author: commit.commit.author || { name: 'Unknown', email: 'unknown@example.com', date: new Date().toISOString() }, + date: commit.commit.author?.date || new Date().toISOString() + })) + }; + } + catch (error) { + (0, logger_1.logError)(`Error comparing branches: ${error}`); + throw error; + } + }; + this.getSizeCategoryAndReason = async (owner, repository, head, base, sizeThresholds, labels, token) => { + try { + const headBranchChanges = await this.getChanges(owner, repository, head, base, token); + const totalChanges = headBranchChanges.files.reduce((sum, file) => sum + file.changes, 0); + const totalFiles = headBranchChanges.files.length; + const totalCommits = headBranchChanges.totalCommits; + let sizeCategory; + let githubSize; + let sizeReason; + if (totalChanges > sizeThresholds.xxl.lines || totalFiles > sizeThresholds.xxl.files || totalCommits > sizeThresholds.xxl.commits) { + sizeCategory = labels.sizeXxl; + githubSize = `XL`; + sizeReason = totalChanges > sizeThresholds.xxl.lines ? `More than ${sizeThresholds.xxl.lines} lines changed` : + totalFiles > sizeThresholds.xxl.files ? `More than ${sizeThresholds.xxl.files} files modified` : + `More than ${sizeThresholds.xxl.commits} commits`; + } + else if (totalChanges > sizeThresholds.xl.lines || totalFiles > sizeThresholds.xl.files || totalCommits > sizeThresholds.xl.commits) { + sizeCategory = labels.sizeXl; + githubSize = `XL`; + sizeReason = totalChanges > sizeThresholds.xl.lines ? `More than ${sizeThresholds.xl.lines} lines changed` : + totalFiles > sizeThresholds.xl.files ? `More than ${sizeThresholds.xl.files} files modified` : + `More than ${sizeThresholds.xl.commits} commits`; + } + else if (totalChanges > sizeThresholds.l.lines || totalFiles > sizeThresholds.l.files || totalCommits > sizeThresholds.l.commits) { + sizeCategory = labels.sizeL; + githubSize = `L`; + sizeReason = totalChanges > sizeThresholds.l.lines ? `More than ${sizeThresholds.l.lines} lines changed` : + totalFiles > sizeThresholds.l.files ? `More than ${sizeThresholds.l.files} files modified` : + `More than ${sizeThresholds.l.commits} commits`; + } + else if (totalChanges > sizeThresholds.m.lines || totalFiles > sizeThresholds.m.files || totalCommits > sizeThresholds.m.commits) { + sizeCategory = labels.sizeM; + githubSize = `M`; + sizeReason = totalChanges > sizeThresholds.m.lines ? `More than ${sizeThresholds.m.lines} lines changed` : + totalFiles > sizeThresholds.m.files ? `More than ${sizeThresholds.m.files} files modified` : + `More than ${sizeThresholds.m.commits} commits`; + } + else if (totalChanges > sizeThresholds.s.lines || totalFiles > sizeThresholds.s.files || totalCommits > sizeThresholds.s.commits) { + sizeCategory = labels.sizeS; + githubSize = `S`; + sizeReason = totalChanges > sizeThresholds.s.lines ? `More than ${sizeThresholds.s.lines} lines changed` : + totalFiles > sizeThresholds.s.files ? `More than ${sizeThresholds.s.files} files modified` : + `More than ${sizeThresholds.s.commits} commits`; + } + else { + sizeCategory = labels.sizeXs; + githubSize = `XS`; + sizeReason = `Small changes (${totalChanges} lines, ${totalFiles} files)`; + } + return { + size: sizeCategory, + githubSize: githubSize, + reason: sizeReason + }; + } + catch (error) { + (0, logger_1.logError)(`Error comparing branches: ${error}`); + throw error; + } + }; } - m = RE_HDR.exec(lines[i]) - h = m[1].toLowerCase() - this.header[h] = this.header[h] || [] - this.header[h].push((m[2] || '')) - if (++this.npairs === this.maxHeaderPairs) { break } - } -} - -module.exports = HeaderParser - - -/***/ }), - -/***/ 81620: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const inherits = (__nccwpck_require__(47261).inherits) -const ReadableStream = (__nccwpck_require__(84492).Readable) - -function PartStream (opts) { - ReadableStream.call(this, opts) } -inherits(PartStream, ReadableStream) - -PartStream.prototype._read = function (n) {} - -module.exports = PartStream +exports.BranchRepository = BranchRepository; /***/ }), -/***/ 51142: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1503: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -/** - * Copyright Brian White. All rights reserved. - * - * @see https://github.com/mscdex/streamsearch - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - * - * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation - * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool - */ -const EventEmitter = (__nccwpck_require__(15673).EventEmitter) -const inherits = (__nccwpck_require__(47261).inherits) - -function SBMH (needle) { - if (typeof needle === 'string') { - needle = Buffer.from(needle) - } - - if (!Buffer.isBuffer(needle)) { - throw new TypeError('The needle has to be a String or a Buffer.') - } - - const needleLength = needle.length - - if (needleLength === 0) { - throw new Error('The needle cannot be an empty String/Buffer.') - } - - if (needleLength > 256) { - throw new Error('The needle cannot have a length bigger than 256.') - } - - this.maxMatches = Infinity - this.matches = 0 - - this._occ = new Array(256) - .fill(needleLength) // Initialize occurrence table. - this._lookbehind_size = 0 - this._needle = needle - this._bufpos = 0 - - this._lookbehind = Buffer.alloc(needleLength) - - // Populate occurrence table with analysis of the needle, - // ignoring last letter. - for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var - this._occ[needle[i]] = needleLength - 1 - i - } -} -inherits(SBMH, EventEmitter) - -SBMH.prototype.reset = function () { - this._lookbehind_size = 0 - this.matches = 0 - this._bufpos = 0 -} - -SBMH.prototype.push = function (chunk, pos) { - if (!Buffer.isBuffer(chunk)) { - chunk = Buffer.from(chunk, 'binary') - } - const chlen = chunk.length - this._bufpos = pos || 0 - let r - while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } - return r -} - -SBMH.prototype._sbmh_feed = function (data) { - const len = data.length - const needle = this._needle - const needleLength = needle.length - const lastNeedleChar = needle[needleLength - 1] - - // Positive: points to a position in `data` - // pos == 3 points to data[3] - // Negative: points to a position in the lookbehind buffer - // pos == -2 points to lookbehind[lookbehind_size - 2] - let pos = -this._lookbehind_size - let ch - - if (pos < 0) { - // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool - // search with character lookup code that considers both the - // lookbehind buffer and the current round's haystack data. - // - // Loop until - // there is a match. - // or until - // we've moved past the position that requires the - // lookbehind buffer. In this case we switch to the - // optimized loop. - // or until - // the character to look at lies outside the haystack. - while (pos < 0 && pos <= len - needleLength) { - ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - - if ( - ch === lastNeedleChar && - this._sbmh_memcmp(data, pos, needleLength - 1) - ) { - this._lookbehind_size = 0 - ++this.matches - this.emit('info', true) - - return (this._bufpos = pos + needleLength) - } - pos += this._occ[ch] +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]; } }; } - - // No match. - - if (pos < 0) { - // There's too few data for Boyer-Moore-Horspool to run, - // so let's use a different algorithm to skip as much as - // we can. - // Forward pos until - // the trailing part of lookbehind + data - // looks like the beginning of the needle - // or until - // pos == 0 - while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const crypto_1 = __nccwpck_require__(6113); +class FileRepository { + constructor() { + this.getFileContent = async (owner, repository, path, token, branch) => { + const octokit = github.getOctokit(token); + try { + const { data } = await octokit.rest.repos.getContent({ + owner, + repo: repository, + path, + ref: branch + }); + if ('content' in data) { + return Buffer.from(data.content, 'base64').toString(); + } + return ''; + } + catch (error) { + (0, logger_1.logError)(`Error getting file content: ${error}.`); + return ''; + } + }; + this.getRepositoryContent = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { + const octokit = github.getOctokit(token); + const fileContents = new Map(); + try { + const getContentRecursively = async (path = '') => { + const { data } = await octokit.rest.repos.getContent({ + owner, + repo: repository, + path, + ref: branch + }); + if (Array.isArray(data)) { + const promises = []; + for (const item of data) { + if (item.type === 'file') { + if (this.isMediaOrPdfFile(item.path) || this.shouldIgnoreFile(item.path, ignoreFiles)) { + ignoredFiles(item.path); + continue; + } + progress(item.path); + const filePromise = (async () => { + const content = await this.getFileContent(owner, repository, item.path, token, branch); + fileContents.set(item.path, content); + })(); + promises.push(filePromise); + } + else if (item.type === 'dir') { + promises.push(getContentRecursively(item.path)); + } + } + await Promise.all(promises); + } + }; + await getContentRecursively(); + return fileContents; + } + catch (error) { + (0, logger_1.logError)(`Error getting repository content: ${error}.`); + return new Map(); + } + }; + this.extractCodeBlocks = (code) => { + const lines = code.split('\n'); + const blocks = []; + let currentBlock; + let braceDepth = 0; + let indentLevel = 0; + const startBlock = (type, name, line, lineNumber) => { + currentBlock = { + type, + name, + content: line + '\n', + startLine: lineNumber, + endLine: lineNumber, + }; + braceDepth = (line.match(/{/g) || []).length - (line.match(/}/g) || []).length; + indentLevel = line.match(/^(\s*)/)?.[1].length ?? 0; + }; + const endBlock = (lineNumber) => { + if (currentBlock) { + currentBlock.endLine = lineNumber; + blocks.push(currentBlock); + currentBlock = undefined; + } + }; + lines.forEach((line, idx) => { + const trimmed = line.trim(); + const lineNumber = idx + 1; + // Detect class or function headers + const functionMatch = trimmed.match(/(?:function|def|fn|async|const|let)\s+(\w+)/); + const classMatch = trimmed.match(/class\s+(\w+)/); + if (!currentBlock && functionMatch) { + startBlock('function', functionMatch[1], line, lineNumber); + } + else if (!currentBlock && classMatch) { + startBlock('class', classMatch[1], line, lineNumber); + } + else if (currentBlock) { + currentBlock.content += line + '\n'; + // Update brace depth + braceDepth += (line.match(/{/g) || []).length; + braceDepth -= (line.match(/}/g) || []).length; + // Or detect dedentation (for Python-style) + const currentIndent = line.match(/^(\s*)/)?.[1].length ?? 0; + const dedented = currentIndent < indentLevel; + if (braceDepth <= 0 && trimmed.endsWith('}') || dedented) { + endBlock(lineNumber); + } + } + }); + // Catch any unfinished block + if (currentBlock) { + currentBlock.endLine = lines.length; + blocks.push(currentBlock); + } + return blocks; + }; + this.shouldIgnoreLine = (line) => { + const trimmed = line.trim(); + return (trimmed === '' || + /^[}\]);]+;?$/.test(trimmed) || + /^import\s.+from\s.+;?$/.test(trimmed) || + /^(return|break|continue|pass);?$/.test(trimmed) || + /^\/\/[-=]*$/.test(trimmed) || // comentarios de separación + /^\/\/\s*(TODO|FIXME)?\s*$/i.test(trimmed) || + /^[\]],?;?$/.test(trimmed) || + /^try\s*{$/.test(trimmed) || + /^}\s*else\s*{$/.test(trimmed) || + /^`;?$/.test(trimmed) || + /^\/\*\*$/.test(trimmed) || + /^\*\/$/.test(trimmed)); + }; + this.getFileTree = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { + const fileContents = await this.getRepositoryContent(owner, repository, token, branch, ignoreFiles, progress, ignoredFiles); + // Create root nodes for both trees + const rootWithContent = { + name: repository, + type: 'directory', + path: '', + children: [] + }; + const rootWithoutContent = { + name: repository, + type: 'directory', + path: '', + children: [] + }; + // Process each file path to build both trees + for (const [filePath, content] of fileContents.entries()) { + const parts = filePath.split('/'); + let currentLevelWithContent = rootWithContent; + let currentLevelWithoutContent = rootWithoutContent; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + const isLastPart = i === parts.length - 1; + const currentPath = parts.slice(0, i + 1).join('/'); + // Find or create the node in the content tree + let nodeWithContent = currentLevelWithContent.children?.find(n => n.name === part); + if (!nodeWithContent) { + nodeWithContent = { + name: part, + type: isLastPart ? 'file' : 'directory', + path: currentPath, + children: isLastPart ? undefined : [], + content: isLastPart ? content : undefined + }; + if (!currentLevelWithContent.children) { + currentLevelWithContent.children = []; + } + currentLevelWithContent.children.push(nodeWithContent); + } + // Find or create the node in the no-content tree + let nodeWithoutContent = currentLevelWithoutContent.children?.find(n => n.name === part); + if (!nodeWithoutContent) { + nodeWithoutContent = { + name: part, + type: isLastPart ? 'file' : 'directory', + path: currentPath, + children: isLastPart ? undefined : [] + }; + if (!currentLevelWithoutContent.children) { + currentLevelWithoutContent.children = []; + } + currentLevelWithoutContent.children.push(nodeWithoutContent); + } + if (!isLastPart) { + currentLevelWithContent = nodeWithContent; + currentLevelWithoutContent = nodeWithoutContent; + } + } + } + return { + withContent: rootWithContent, + withoutContent: rootWithoutContent + }; + }; } - - if (pos >= 0) { - // Discard lookbehind buffer. - this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) - this._lookbehind_size = 0 - } else { - // Cut off part of the lookbehind buffer that has - // been processed and append the entire haystack - // into it. - const bytesToCutOff = this._lookbehind_size + pos - if (bytesToCutOff > 0) { - // The cut off data is guaranteed not to contain the needle. - this.emit('info', false, this._lookbehind, 0, bytesToCutOff) - } - - this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, - this._lookbehind_size - bytesToCutOff) - this._lookbehind_size -= bytesToCutOff - - data.copy(this._lookbehind, this._lookbehind_size) - this._lookbehind_size += len - - this._bufpos = len - return len + isMediaOrPdfFile(path) { + const mediaExtensions = [ + // Image formats + '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico', + // Audio formats + '.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', + // Video formats + '.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', + // PDF + '.pdf' + ]; + const extension = path.toLowerCase().substring(path.lastIndexOf('.')); + return mediaExtensions.includes(extension); } - } - - pos += (pos >= 0) * this._bufpos - - // Lookbehind buffer is now empty. We only need to check if the - // needle is in the haystack. - if (data.indexOf(needle, pos) !== -1) { - pos = data.indexOf(needle, pos) - ++this.matches - if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - - return (this._bufpos = pos + needleLength) - } else { - pos = len - needleLength - } - - // There was no match. If there's trailing haystack data that we cannot - // match yet using the Boyer-Moore-Horspool algorithm (because the trailing - // data is less than the needle size) then match using a modified - // algorithm that starts matching from the beginning instead of the end. - // Whatever trailing data is left after running this algorithm is added to - // the lookbehind buffer. - while ( - pos < len && - ( - data[pos] !== needle[0] || - ( - (Buffer.compare( - data.subarray(pos, pos + len - pos), - needle.subarray(0, len - pos) - ) !== 0) - ) - ) - ) { - ++pos - } - if (pos < len) { - data.copy(this._lookbehind, 0, pos, pos + (len - pos)) - this._lookbehind_size = len - pos - } - - // Everything until pos is guaranteed not to contain needle data. - if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } - - this._bufpos = len - return len -} - -SBMH.prototype._sbmh_lookup_char = function (data, pos) { - return (pos < 0) - ? this._lookbehind[this._lookbehind_size + pos] - : data[pos] -} - -SBMH.prototype._sbmh_memcmp = function (data, pos, len) { - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } - } - return true -} - -module.exports = SBMH - - -/***/ }), - -/***/ 50727: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const WritableStream = (__nccwpck_require__(84492).Writable) -const { inherits } = __nccwpck_require__(47261) -const Dicer = __nccwpck_require__(92960) - -const MultipartParser = __nccwpck_require__(32183) -const UrlencodedParser = __nccwpck_require__(78306) -const parseParams = __nccwpck_require__(31854) - -function Busboy (opts) { - if (!(this instanceof Busboy)) { return new Busboy(opts) } - - if (typeof opts !== 'object') { - throw new TypeError('Busboy expected an options-Object.') - } - if (typeof opts.headers !== 'object') { - throw new TypeError('Busboy expected an options-Object with headers-attribute.') - } - if (typeof opts.headers['content-type'] !== 'string') { - throw new TypeError('Missing Content-Type-header.') - } - - const { - headers, - ...streamOptions - } = opts - - this.opts = { - autoDestroy: false, - ...streamOptions - } - WritableStream.call(this, this.opts) - - this._done = false - this._parser = this.getParserByHeaders(headers) - this._finished = false -} -inherits(Busboy, WritableStream) - -Busboy.prototype.emit = function (ev) { - if (ev === 'finish') { - if (!this._done) { - this._parser?.end() - return - } else if (this._finished) { - return + shouldIgnoreFile(filename, ignorePatterns) { + // First check for .DS_Store + if (filename.endsWith('.DS_Store')) { + return true; + } + return ignorePatterns.some(pattern => { + // Convert glob pattern to regex + const regexPattern = pattern + .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) + .replace(/\*/g, '.*') // Convert * to match anything + .replace(/\//g, '\\/'); // Escape forward slashes + // Allow pattern ending on /* to ignore also subdirectories and files inside + if (pattern.endsWith("/*")) { + return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); + } + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(filename); + }); + } + shuffleArray(array) { + return [...array].sort(() => Math.random() - 0.5); + } + calculateShasum(content) { + return (0, crypto_1.createHash)('sha256').update(content).digest('hex'); } - this._finished = true - } - WritableStream.prototype.emit.apply(this, arguments) -} - -Busboy.prototype.getParserByHeaders = function (headers) { - const parsed = parseParams(headers['content-type']) - - const cfg = { - defCharset: this.opts.defCharset, - fileHwm: this.opts.fileHwm, - headers, - highWaterMark: this.opts.highWaterMark, - isPartAFile: this.opts.isPartAFile, - limits: this.opts.limits, - parsedConType: parsed, - preservePath: this.opts.preservePath - } - - if (MultipartParser.detect.test(parsed[0])) { - return new MultipartParser(this, cfg) - } - if (UrlencodedParser.detect.test(parsed[0])) { - return new UrlencodedParser(this, cfg) - } - throw new Error('Unsupported Content-Type.') -} - -Busboy.prototype._write = function (chunk, encoding, cb) { - this._parser.write(chunk, cb) } - -module.exports = Busboy -module.exports["default"] = Busboy -module.exports.Busboy = Busboy - -module.exports.Dicer = Dicer +exports.FileRepository = FileRepository; /***/ }), -/***/ 32183: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 57: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -// TODO: -// * support 1 nested multipart level -// (see second multipart example here: -// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) -// * support limits.fieldNameSize -// -- this will require modifications to utils.parseParams - -const { Readable } = __nccwpck_require__(84492) -const { inherits } = __nccwpck_require__(47261) - -const Dicer = __nccwpck_require__(92960) - -const parseParams = __nccwpck_require__(31854) -const decodeText = __nccwpck_require__(84619) -const basename = __nccwpck_require__(48647) -const getLimit = __nccwpck_require__(21467) - -const RE_BOUNDARY = /^boundary$/i -const RE_FIELD = /^form-data$/i -const RE_CHARSET = /^charset$/i -const RE_FILENAME = /^filename$/i -const RE_NAME = /^name$/i - -Multipart.detect = /^multipart\/form-data/i -function Multipart (boy, cfg) { - let i - let len - const self = this - let boundary - const limits = cfg.limits - const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) - const parsedConType = cfg.parsedConType || [] - const defCharset = cfg.defCharset || 'utf8' - const preservePath = cfg.preservePath - const fileOpts = { highWaterMark: cfg.fileHwm } - - for (i = 0, len = parsedConType.length; i < len; ++i) { - if (Array.isArray(parsedConType[i]) && - RE_BOUNDARY.test(parsedConType[i][0])) { - boundary = parsedConType[i][1] - break - } - } - - function checkFinished () { - if (nends === 0 && finished && !boy._done) { - finished = false - self.end() - } - } - - if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - - const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) - const filesLimit = getLimit(limits, 'files', Infinity) - const fieldsLimit = getLimit(limits, 'fields', Infinity) - const partsLimit = getLimit(limits, 'parts', Infinity) - const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) - const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) - - let nfiles = 0 - let nfields = 0 - let nends = 0 - let curFile - let curField - let finished = false - - this._needDrain = false - this._pause = false - this._cb = undefined - this._nparts = 0 - this._boy = boy - - const parserCfg = { - boundary, - maxHeaderPairs: headerPairsLimit, - maxHeaderSize: headerSizeLimit, - partHwm: fileOpts.highWaterMark, - highWaterMark: cfg.highWaterMark - } - - this.parser = new Dicer(parserCfg) - this.parser.on('drain', function () { - self._needDrain = false - if (self._cb && !self._pause) { - const cb = self._cb - self._cb = undefined - cb() - } - }).on('part', function onPart (part) { - if (++self._nparts > partsLimit) { - self.parser.removeListener('part', onPart) - self.parser.on('part', skipPart) - boy.hitPartsLimit = true - boy.emit('partsLimit') - return skipPart(part) - } - - // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let - // us emit 'end' early since we know the part has ended if we are already - // seeing the next part - if (curField) { - const field = curField - field.emit('end') - field.removeAllListeners('end') +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]; } }; } - - part.on('header', function (header) { - let contype - let fieldname - let parsed - let charset - let encoding - let filename - let nsize = 0 - - if (header['content-type']) { - parsed = parseParams(header['content-type'][0]) - if (parsed[0]) { - contype = parsed[0].toLowerCase() - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_CHARSET.test(parsed[i][0])) { - charset = parsed[i][1].toLowerCase() - break + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueRepository = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const milestone_1 = __nccwpck_require__(2298); +class IssueRepository { + constructor() { + this.updateTitleIssueFormat = async (owner, repository, version, issueTitle, issueNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { + try { + const octokit = github.getOctokit(token); + let emoji = 'šŸ¤–'; + const branched = branchManagementAlways || labels.containsBranchedLabel; + if (labels.isHotfix && branched) { + emoji = `šŸ”„${branchManagementEmoji}`; + } + else if (labels.isRelease && branched) { + emoji = `šŸš€${branchManagementEmoji}`; + } + else if ((labels.isBugfix || labels.isBug) && branched) { + emoji = `šŸ›${branchManagementEmoji}`; + } + else if ((labels.isFeature || labels.isEnhancement) && branched) { + emoji = `✨${branchManagementEmoji}`; + } + else if ((labels.isDocs || labels.isDocumentation) && branched) { + emoji = `šŸ“${branchManagementEmoji}`; + } + else if ((labels.isChore || labels.isMaintenance) && branched) { + emoji = `šŸ”§${branchManagementEmoji}`; + } + else if (labels.isHotfix) { + emoji = 'šŸ”„'; + } + else if (labels.isRelease) { + emoji = 'šŸš€'; + } + else if ((labels.isDocs || labels.isDocumentation)) { + emoji = 'šŸ“'; + } + else if (labels.isChore || labels.isMaintenance) { + emoji = 'šŸ”§'; + } + else if (labels.isBugfix || labels.isBug) { + emoji = 'šŸ›'; + } + else if (labels.isFeature || labels.isEnhancement) { + emoji = '✨'; + } + else if (labels.isHelp) { + emoji = 'šŸ†˜'; + } + else if (labels.isQuestion) { + emoji = 'ā“'; + } + let sanitizedTitle = issueTitle + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + let formattedTitle = `${emoji} - ${sanitizedTitle}`; + if (version.length > 0) { + formattedTitle = `${emoji} - ${version} - ${sanitizedTitle}`; + } + if (formattedTitle !== issueTitle) { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + title: formattedTitle, + }); + (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); + return formattedTitle; + } + return undefined; + } + catch (error) { + core.setFailed(`Failed to check or update issue title: ${error}`); + return undefined; + } + }; + this.updateTitlePullRequestFormat = async (owner, repository, pullRequestTitle, issueTitle, issueNumber, pullRequestNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { + try { + const octokit = github.getOctokit(token); + let emoji = 'šŸ¤–'; + const branched = branchManagementAlways || labels.containsBranchedLabel; + if (labels.isHotfix && branched) { + emoji = `šŸ”„${branchManagementEmoji}`; + } + else if (labels.isRelease && branched) { + emoji = `šŸš€${branchManagementEmoji}`; + } + else if ((labels.isBugfix || labels.isBug) && branched) { + emoji = `šŸ›${branchManagementEmoji}`; + } + else if ((labels.isFeature || labels.isEnhancement) && branched) { + emoji = `✨${branchManagementEmoji}`; + } + else if ((labels.isDocs || labels.isDocumentation) && branched) { + emoji = `šŸ“${branchManagementEmoji}`; + } + else if ((labels.isChore || labels.isMaintenance) && branched) { + emoji = `šŸ”§${branchManagementEmoji}`; + } + else if (labels.isHotfix) { + emoji = 'šŸ”„'; + } + else if (labels.isRelease) { + emoji = 'šŸš€'; + } + else if (labels.isBugfix || labels.isBug) { + emoji = 'šŸ›'; + } + else if (labels.isFeature || labels.isEnhancement) { + emoji = '✨'; + } + else if (labels.isDocs || labels.isDocumentation) { + emoji = 'šŸ“'; + } + else if (labels.isChore || labels.isMaintenance) { + emoji = 'šŸ”§'; + } + else if (labels.isHelp) { + emoji = 'šŸ†˜'; + } + else if (labels.isQuestion) { + emoji = 'ā“'; + } + let sanitizedTitle = issueTitle + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 ]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + const formattedTitle = `[#${issueNumber}] ${emoji} - ${sanitizedTitle}`; + if (formattedTitle !== pullRequestTitle) { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: pullRequestNumber, + title: formattedTitle, + }); + (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); + return formattedTitle; + } + return undefined; + } + catch (error) { + core.setFailed(`Failed to check or update issue title: ${error}`); + return undefined; + } + }; + this.cleanTitle = async (owner, repository, issueTitle, issueNumber, token) => { + try { + const octokit = github.getOctokit(token); + let sanitizedTitle = issueTitle + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 ]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + if (sanitizedTitle !== issueTitle) { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + title: sanitizedTitle, + }); + (0, logger_1.logDebugInfo)(`Issue title updated to: ${sanitizedTitle}`); + return sanitizedTitle; + } + return undefined; + } + catch (error) { + core.setFailed(`Failed to check or update issue title: ${error}`); + return undefined; + } + }; + this.updateDescription = async (owner, repo, issueNumber, description, token) => { + const octokit = github.getOctokit(token); + try { + await octokit.rest.issues.update({ + owner, + repo, + issue_number: issueNumber, + body: description, + }); + } + catch (error) { + (0, logger_1.logError)(`Error updating issue description: ${error}`); + throw error; + } + }; + this.getDescription = async (owner, repo, issueNumber, token) => { + if (issueNumber === -1) { + return undefined; + } + const octokit = github.getOctokit(token); + try { + const { data: issue } = await octokit.rest.issues.get({ + owner, + repo, + issue_number: issueNumber, + }); + return issue.body ?? ''; + } + catch (error) { + (0, logger_1.logError)(`Error reading issue #${issueNumber} description: ${error}`); + return undefined; + } + }; + this.getId = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const issueQuery = ` + query($repo: String!, $owner: String!, $issueNumber: Int!) { + repository(name: $repo, owner: $owner) { + issue(number: $issueNumber) { + id + } } } - } - } - - if (contype === undefined) { contype = 'text/plain' } - if (charset === undefined) { charset = defCharset } - - if (header['content-disposition']) { - parsed = parseParams(header['content-disposition'][0]) - if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_NAME.test(parsed[i][0])) { - fieldname = parsed[i][1] - } else if (RE_FILENAME.test(parsed[i][0])) { - filename = parsed[i][1] - if (!preservePath) { filename = basename(filename) } - } - } - } else { return skipPart(part) } - - if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - - let onData, - onEnd - - if (isPartAFile(fieldname, contype, filename)) { - // file/binary field - if (nfiles === filesLimit) { - if (!boy.hitFilesLimit) { - boy.hitFilesLimit = true - boy.emit('filesLimit') - } - return skipPart(part) - } - - ++nfiles - - if (boy.listenerCount('file') === 0) { - self.parser._ignore() - return - } - - ++nends - const file = new FileStream(fileOpts) - curFile = file - file.on('end', function () { - --nends - self._pause = false - checkFinished() - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - }) - file._read = function (n) { - if (!self._pause) { return } - self._pause = false - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - } - boy.emit('file', fieldname, file, filename, encoding, contype) - - onData = function (data) { - if ((nsize += data.length) > fileSizeLimit) { - const extralen = fileSizeLimit - nsize + data.length - if (extralen > 0) { file.push(data.slice(0, extralen)) } - file.truncated = true - file.bytesRead = fileSizeLimit - part.removeAllListeners('data') - file.emit('limit') - return - } else if (!file.push(data)) { self._pause = true } - - file.bytesRead = nsize - } - - onEnd = function () { - curFile = undefined - file.push(null) - } - } else { - // non-file field - if (nfields === fieldsLimit) { - if (!boy.hitFieldsLimit) { - boy.hitFieldsLimit = true - boy.emit('fieldsLimit') - } - return skipPart(part) - } - - ++nfields - ++nends - let buffer = '' - let truncated = false - curField = part - - onData = function (data) { - if ((nsize += data.length) > fieldSizeLimit) { - const extralen = (fieldSizeLimit - (nsize - data.length)) - buffer += data.toString('binary', 0, extralen) - truncated = true - part.removeAllListeners('data') - } else { buffer += data.toString('binary') } - } - - onEnd = function () { - curField = undefined - if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } - boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) - --nends - checkFinished() - } - } - - /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become - broken. Streams2/streams3 is a huge black box of confusion, but - somehow overriding the sync state seems to fix things again (and still - seems to work for previous node versions). - */ - part._readableState.sync = false - - part.on('data', onData) - part.on('end', onEnd) - }).on('error', function (err) { - if (curFile) { curFile.emit('error', err) } - }) - }).on('error', function (err) { - boy.emit('error', err) - }).on('finish', function () { - finished = true - checkFinished() - }) -} - -Multipart.prototype.write = function (chunk, cb) { - const r = this.parser.write(chunk) - if (r && !this._pause) { - cb() - } else { - this._needDrain = !r - this._cb = cb - } -} - -Multipart.prototype.end = function () { - const self = this - - if (self.parser.writable) { - self.parser.end() - } else if (!self._boy._done) { - process.nextTick(function () { - self._boy._done = true - self._boy.emit('finish') - }) - } -} - -function skipPart (part) { - part.resume() -} - -function FileStream (opts) { - Readable.call(this, opts) - - this.bytesRead = 0 - - this.truncated = false + `; + const issueResult = await octokit.graphql(issueQuery, { + owner: owner, + repo: repository, + issueNumber, + }); + const issueId = issueResult.repository.issue.id; + (0, logger_1.logDebugInfo)(`Fetched issue ID: ${issueId}`); + return issueId; + }; + this.getMilestone = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + if (issue.milestone) { + return new milestone_1.Milestone(issue.milestone.id, issue.milestone.title, issue.milestone.description ?? ''); + } + else { + return undefined; + } + }; + this.getTitle = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + return issue.title; + } + catch (error) { + (0, logger_1.logError)(`Failed to fetch the issue title: ${error}`); + return undefined; + } + }; + this.getLabels = async (owner, repository, issueNumber, token) => { + if (issueNumber === -1) { + return []; + } + const octokit = github.getOctokit(token); + const { data: labels } = await octokit.rest.issues.listLabelsOnIssue({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + return labels.map(label => label.name); + }; + this.setLabels = async (owner, repository, issueNumber, labels, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.issues.setLabels({ + owner: owner, + repo: repository, + issue_number: issueNumber, + labels: labels, + }); + }; + this.isIssue = async (owner, repository, issueNumber, token) => { + const isPullRequest = await this.isPullRequest(owner, repository, issueNumber, token); + return !isPullRequest; + }; + this.isPullRequest = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + return !!data.pull_request; + }; + this.getHeadBranch = async (owner, repository, issueNumber, token) => { + const isPr = await this.isPullRequest(owner, repository, issueNumber, token); + if (!isPr) { + return undefined; + } + const octokit = github.getOctokit(token); + const pullRequest = await octokit.rest.pulls.get({ + owner, + repo: repository, + pull_number: issueNumber, + }); + return pullRequest.data.head.ref; + }; + this.addComment = async (owner, repository, issueNumber, comment, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.issues.createComment({ + owner: owner, + repo: repository, + issue_number: issueNumber, + body: comment, + }); + (0, logger_1.logDebugInfo)(`Comment added to Issue ${issueNumber}.`); + }; + this.updateComment = async (owner, repository, issueNumber, commentId, comment, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.issues.updateComment({ + owner: owner, + repo: repository, + comment_id: commentId, + body: comment, + }); + (0, logger_1.logDebugInfo)(`Comment ${commentId} updated in Issue ${issueNumber}.`); + }; + this.closeIssue = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); + if (issue.state === 'open') { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + state: 'closed', + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been closed.`); + return true; + } + else { + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already closed.`); + return false; + } + }; + this.openIssue = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); + if (issue.state === 'closed') { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + state: 'open', + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been re-opened.`); + return true; + } + else { + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already opened.`); + return false; + } + }; + this.getCurrentAssignees = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data: issue } = await octokit.rest.issues.get({ + owner, + repo: repository, + issue_number: issueNumber, + }); + const assignees = issue.assignees; + if (assignees === undefined || assignees === null) { + return []; + } + return assignees.map((assignee) => assignee.login); + } + catch (error) { + (0, logger_1.logError)(`Error getting members of issue: ${error}.`); + return []; + } + }; + this.assignMembersToIssue = async (owner, repository, issueNumber, members, token) => { + const octokit = github.getOctokit(token); + try { + if (members.length === 0) { + (0, logger_1.logDebugInfo)(`No members provided for assignment. Skipping operation.`); + return []; + } + const { data: updatedIssue } = await octokit.rest.issues.addAssignees({ + owner, + repo: repository, + issue_number: issueNumber, + assignees: members, + }); + const updatedAssignees = updatedIssue.assignees || []; + return updatedAssignees.map((assignee) => assignee.login); + } + catch (error) { + (0, logger_1.logError)(`Error assigning members to issue: ${error}.`); + return []; + } + }; + this.getIssueDescription = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner, + repo: repository, + issue_number: issueNumber, + }); + return issue.body ?? ''; + }; + this.setIssueType = async (owner, repository, issueNumber, labels, issueTypes, token) => { + try { + let issueType = issueTypes.task; + let issueTypeDescription = issueTypes.taskDescription; + let issueTypeColor = issueTypes.taskColor; + if (labels.isHotfix) { + issueType = issueTypes.hotfix; + issueTypeDescription = issueTypes.hotfixDescription; + issueTypeColor = issueTypes.hotfixColor; + } + else if (labels.isRelease) { + issueType = issueTypes.release; + issueTypeDescription = issueTypes.releaseDescription; + issueTypeColor = issueTypes.releaseColor; + } + else if ((labels.isDocs || labels.isDocumentation)) { + issueType = issueTypes.documentation; + issueTypeDescription = issueTypes.documentationDescription; + issueTypeColor = issueTypes.documentationColor; + } + else if (labels.isChore || labels.isMaintenance) { + issueType = issueTypes.maintenance; + issueTypeDescription = issueTypes.maintenanceDescription; + issueTypeColor = issueTypes.maintenanceColor; + } + else if (labels.isBugfix || labels.isBug) { + issueType = issueTypes.bug; + issueTypeDescription = issueTypes.bugDescription; + issueTypeColor = issueTypes.bugColor; + } + else if (labels.isFeature || labels.isEnhancement) { + issueType = issueTypes.feature; + issueTypeDescription = issueTypes.featureDescription; + issueTypeColor = issueTypes.featureColor; + } + else if (labels.isHelp) { + issueType = issueTypes.help; + issueTypeDescription = issueTypes.helpDescription; + issueTypeColor = issueTypes.helpColor; + } + else if (labels.isQuestion) { + issueType = issueTypes.question; + issueTypeDescription = issueTypes.questionDescription; + issueTypeColor = issueTypes.questionColor; + } + const octokit = github.getOctokit(token); + (0, logger_1.logDebugInfo)(`Setting issue type for issue ${issueNumber} to ${issueType}`); + (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); + (0, logger_1.logDebugInfo)(`Issue Type: ${issueType}`); + (0, logger_1.logDebugInfo)(`Issue Type Description: ${issueTypeDescription}`); + (0, logger_1.logDebugInfo)(`Issue Type Color: ${issueTypeColor}`); + // Try to update the issue with the issue type using GraphQL + const issueId = await this.getId(owner, repository, issueNumber, token); + // First, try to find existing issue types in the organization + const { organization } = await octokit.graphql(` + query ($owner: String!) { + organization(login: $owner) { + id + issueTypes(first: 20) { + nodes { + id + name + } + } + } + } + `, { owner }); + (0, logger_1.logDebugInfo)(`Organization ID: ${organization.id}`); + (0, logger_1.logDebugInfo)(`Organization issue types: ${JSON.stringify(organization.issueTypes.nodes)}`); + // Check if the issue type already exists + const existingType = organization.issueTypes.nodes.find((type) => type.name.toLowerCase() === issueType.toLowerCase()); + let issueTypeId; + if (existingType) { + issueTypeId = existingType.id; + (0, logger_1.logDebugInfo)(`Found existing issue type "${issueType}" with ID: ${issueTypeId}`); + } + else { + // Try to create the issue type using GraphQL + try { + (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); + const createResult = await octokit.graphql(` + mutation ($ownerId: ID!, $name: String!, $description: String!, $color: IssueTypeColor!, $isEnabled: Boolean!) { + createIssueType(input: { + ownerId: $ownerId, + name: $name, + description: $description, + color: $color, + isEnabled: $isEnabled + }) { + issueType { + id + } + } + } + `, { + ownerId: organization.id, + name: issueType, + description: issueTypeDescription, + color: issueTypeColor.toUpperCase(), + isEnabled: true, + }); + issueTypeId = createResult.createIssueType.issueType.id; + (0, logger_1.logDebugInfo)(`Created new issue type "${issueType}" with ID: ${issueTypeId}`); + } + catch (createError) { + (0, logger_1.logError)(`Failed to create issue type "${issueType}": ${createError}`); + // If creation fails, we'll fall back to using labels + (0, logger_1.logDebugInfo)(`Falling back to using labels for issue type classification`); + return; + } + } + // Update the issue with the issue type using GraphQL + await octokit.graphql(` + mutation ($issueId: ID!, $issueTypeId: ID!) { + updateIssueIssueType(input: { + issueId: $issueId, + issueTypeId: $issueTypeId + }) { + issue { + id + issueType { + id + name + } + } + } + } + `, { + issueId, + issueTypeId, + }); + (0, logger_1.logDebugInfo)(`Successfully updated issue type to ${issueType}`); + } + catch (error) { + (0, logger_1.logError)(`Failed to update issue type: ${error}`); + // Don't throw the error to prevent breaking the main flow + // The issue will still be processed with labels + (0, logger_1.logDebugInfo)(`Continuing with issue processing despite issue type update failure`); + throw error; + } + }; + } } - -inherits(FileStream, Readable) - -FileStream.prototype._read = function (n) {} - -module.exports = Multipart +exports.IssueRepository = IssueRepository; /***/ }), -/***/ 78306: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7917: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -const Decoder = __nccwpck_require__(27100) -const decodeText = __nccwpck_require__(84619) -const getLimit = __nccwpck_require__(21467) - -const RE_CHARSET = /^charset$/i - -UrlEncoded.detect = /^application\/x-www-form-urlencoded/i -function UrlEncoded (boy, cfg) { - const limits = cfg.limits - const parsedConType = cfg.parsedConType - this.boy = boy - - this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) - this.fieldsLimit = getLimit(limits, 'fields', Infinity) - - let charset - for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var - if (Array.isArray(parsedConType[i]) && - RE_CHARSET.test(parsedConType[i][0])) { - charset = parsedConType[i][1].toLowerCase() - break - } - } - - if (charset === undefined) { charset = cfg.defCharset || 'utf8' } - - this.decoder = new Decoder() - this.charset = charset - this._fields = 0 - this._state = 'key' - this._checkingBytes = true - this._bytesKey = 0 - this._bytesVal = 0 - this._key = '' - this._val = '' - this._keyTrunc = false - this._valTrunc = false - this._hitLimit = false -} - -UrlEncoded.prototype.write = function (data, cb) { - if (this._fields === this.fieldsLimit) { - if (!this.boy.hitFieldsLimit) { - this.boy.hitFieldsLimit = true - this.boy.emit('fieldsLimit') +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]; } }; } - return cb() - } - - let idxeq; let idxamp; let i; let p = 0; const len = data.length - - while (p < len) { - if (this._state === 'key') { - idxeq = idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x3D/* = */) { - idxeq = i - break - } else if (data[i] === 0x26/* & */) { - idxamp = i - break - } - if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesKey } - } - - if (idxeq !== undefined) { - // key with assignment - if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } - this._state = 'val' - - this._hitLimit = false - this._checkingBytes = true - this._val = '' - this._bytesVal = 0 - this._valTrunc = false - this.decoder.reset() - - p = idxeq + 1 - } else if (idxamp !== undefined) { - // key with no assignment - ++this._fields - let key; const keyTrunc = this._keyTrunc - if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - if (key.length) { - this.boy.emit('field', decodeText(key, 'binary', this.charset), - '', - keyTrunc, - false) - } - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._keyTrunc = true - } - } else { - if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } - p = len - } - } else { - idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x26/* & */) { - idxamp = i - break - } - if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesVal } - } - - if (idxamp !== undefined) { - ++this._fields - if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - this._state = 'key' - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._val === '' && this.fieldSizeLimit === 0) || - (this._bytesVal = this._val.length) === this.fieldSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._valTrunc = true + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProjectRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const project_detail_1 = __nccwpck_require__(3765); +class ProjectRepository { + constructor() { + this.priorityLabel = "Priority"; + this.sizeLabel = "Size"; + this.statusLabel = "Status"; + /** + * Retrieves detailed information about a GitHub project + * @param projectId - The project number/ID + * @param token - GitHub authentication token + * @returns Promise - The project details + * @throws {Error} If the project is not found or if there are authentication/network issues + */ + this.getProjectDetail = async (projectId, token) => { + try { + // Validate projectId is a valid number + const projectNumber = parseInt(projectId, 10); + if (isNaN(projectNumber)) { + throw new Error(`Invalid project ID: ${projectId}. Must be a valid number.`); + } + const octokit = github.getOctokit(token); + const { data: owner } = await octokit.rest.users.getByUsername({ + username: github.context.repo.owner + }).catch(error => { + throw new Error(`Failed to get owner information: ${error.message}`); + }); + const ownerType = owner.type === 'Organization' ? 'orgs' : 'users'; + const projectUrl = `https://github.com/${ownerType}/${github.context.repo.owner}/projects/${projectId}`; + const ownerQueryField = ownerType === 'orgs' ? 'organization' : 'user'; + const queryProject = ` + query($ownerName: String!, $projectNumber: Int!) { + ${ownerQueryField}(login: $ownerName) { + projectV2(number: $projectNumber) { + id + title + url + } + } + } + `; + const projectResult = await octokit.graphql(queryProject, { + ownerName: github.context.repo.owner, + projectNumber: projectNumber, + }).catch(error => { + throw new Error(`Failed to fetch project data: ${error.message}`); + }); + const projectData = projectResult[ownerQueryField]?.projectV2; + if (!projectData) { + throw new Error(`Project not found: ${projectUrl}`); + } + (0, logger_1.logDebugInfo)(`Project ID: ${projectData.id}`); + (0, logger_1.logDebugInfo)(`Project Title: ${projectData.title}`); + (0, logger_1.logDebugInfo)(`Project URL: ${projectData.url}`); + return new project_detail_1.ProjectDetail({ + id: projectData.id, + title: projectData.title, + url: projectData.url, + type: ownerQueryField, + owner: github.context.repo.owner, + number: projectNumber, + }); + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + (0, logger_1.logError)(`Error in getProjectDetail: ${errorMessage}`); + throw error; + } + }; + this.getContentId = async (project, owner, repo, issueOrPullRequestNumber, token) => { + const octokit = github.getOctokit(token); + // Search for the issue or pull request ID in the repository + const issueOrPrQuery = ` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issueOrPullRequest: issueOrPullRequest(number: $number) { + ... on Issue { + id + } + ... on PullRequest { + id + } + } } - } else { - if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } - p = len - } - } - } - cb() -} - -UrlEncoded.prototype.end = function () { - if (this.boy._done) { return } - - if (this._state === 'key' && this._key.length > 0) { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - '', - this._keyTrunc, - false) - } else if (this._state === 'val') { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - } - this.boy._done = true - this.boy.emit('finish') -} - -module.exports = UrlEncoded - - -/***/ }), - -/***/ 27100: -/***/ ((module) => { - -"use strict"; - - -const RE_PLUS = /\+/g - -const HEX = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -] - -function Decoder () { - this.buffer = undefined -} -Decoder.prototype.write = function (str) { - // Replace '+' with ' ' before decoding - str = str.replace(RE_PLUS, ' ') - let res = '' - let i = 0; let p = 0; const len = str.length - for (; i < len; ++i) { - if (this.buffer !== undefined) { - if (!HEX[str.charCodeAt(i)]) { - res += '%' + this.buffer - this.buffer = undefined - --i // retry character - } else { - this.buffer += str[i] - ++p - if (this.buffer.length === 2) { - res += String.fromCharCode(parseInt(this.buffer, 16)) - this.buffer = undefined + }`; + const issueOrPrResult = await octokit.graphql(issueOrPrQuery, { + owner, + repo, + number: issueOrPullRequestNumber + }); + if (!issueOrPrResult.repository.issueOrPullRequest) { + console.error(`Issue or PR #${issueOrPullRequestNumber} not found.`); + return undefined; + } + const contentId = issueOrPrResult.repository.issueOrPullRequest.id; + // Search for the item ID in the project with pagination + let cursor = null; + let projectItemId = undefined; + do { + const projectQuery = ` + query($projectId: ID!, $cursor: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $cursor) { + pageInfo { + hasNextPage + endCursor + } + nodes { + id + content { + ... on Issue { + id + } + ... on PullRequest { + id + } + } + } + } + } + } + }`; + const projectResult = await octokit.graphql(projectQuery, { + projectId: project.id, + cursor + }); + const items = projectResult.node.items.nodes; + const foundItem = items.find((item) => item.content?.id === contentId); + if (foundItem) { + projectItemId = foundItem.id; + break; + } + cursor = projectResult.node.items.pageInfo.hasNextPage + ? projectResult.node.items.pageInfo.endCursor + : null; + } while (cursor); + return projectItemId; + }; + this.isContentLinked = async (project, contentId, token) => { + const octokit = github.getOctokit(token); + let hasNextPage = true; + let endCursor = null; + let allItems = []; + while (hasNextPage) { + const query = ` + query($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + content { + ... on PullRequest { + id + } + ... on Issue { + id + } + } + } + pageInfo { + hasNextPage + endCursor + } + } } } - } else if (str[i] === '%') { - if (i > p) { - res += str.substring(p, i) - p = i - } - this.buffer = '' - ++p } - } - if (p < len && this.buffer === undefined) { res += str.substring(p) } - return res -} -Decoder.prototype.reset = function () { - this.buffer = undefined -} - -module.exports = Decoder - - -/***/ }), - -/***/ 48647: -/***/ ((module) => { - -"use strict"; - - -module.exports = function basename (path) { - if (typeof path !== 'string') { return '' } - for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var - switch (path.charCodeAt(i)) { - case 0x2F: // '/' - case 0x5C: // '\' - path = path.slice(i + 1) - return (path === '..' || path === '.' ? '' : path) + `; + // logDebugInfo(`Query: ${query}`); + // logDebugInfo(`Project ID: ${project.id}`); + // logDebugInfo(`Content ID: ${contentId}`); + // logDebugInfo(`After cursor: ${endCursor}`); + const result = await octokit.graphql(query, { + projectId: project.id, + after: endCursor, + }); + // logDebugInfo(`Result: ${JSON.stringify(result, null, 2)}`); + const items = result.node.items.nodes; + allItems = allItems.concat(items); + hasNextPage = result.node.items.pageInfo.hasNextPage; + endCursor = result.node.items.pageInfo.endCursor; + } + return allItems.some((item) => item.content && item.content.id === contentId); + }; + this.linkContentId = async (project, contentId, token) => { + const alreadyLinked = await this.isContentLinked(project, contentId, token); + if (alreadyLinked) { + (0, logger_1.logDebugInfo)(`Content ${contentId} is already linked to project ${project.id}.`); + return false; + } + const octokit = github.getOctokit(token); + const linkMutation = ` + mutation($projectId: ID!, $contentId: ID!) { + addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) { + item { + id + } + } + } + `; + const linkResult = await octokit.graphql(linkMutation, { + projectId: project.id, + contentId: contentId, + }); + (0, logger_1.logDebugInfo)(`Linked ${contentId} with id ${linkResult.addProjectV2ItemById.item.id} to project ${project.id}`); + return true; + }; + this.setSingleSelectFieldValue = async (project, owner, repo, issueOrPullRequestNumber, fieldName, fieldValue, token) => { + const contentId = await this.getContentId(project, owner, repo, issueOrPullRequestNumber, token); + if (!contentId) { + (0, logger_1.logError)(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); + throw new Error(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); + } + (0, logger_1.logDebugInfo)(`Content ID: ${contentId}`); + const octokit = github.getOctokit(token); + // Get the field ID and current value + const fieldQuery = ` + query($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + fields(first: 20) { + nodes { + ... on ProjectV2SingleSelectField { + id + name + options { + id + name + } + } + } + } + items(first: 100, after: $after) { + pageInfo { + hasNextPage + endCursor + } + nodes { + id + fieldValues(first: 20) { + nodes { + ... on ProjectV2ItemFieldSingleSelectValue { + field { + ... on ProjectV2SingleSelectField { + name + } + } + optionId + } + } + } + } + } + } + } + }`; + let hasNextPage = true; + let endCursor = null; + let currentItem = null; + // Get the field and option information from the first page + const initialFieldResult = await octokit.graphql(fieldQuery, { + projectId: project.id, + after: null + }); + const targetField = initialFieldResult.node.fields.nodes.find((f) => f.name === fieldName); + (0, logger_1.logDebugInfo)(`Target field: ${JSON.stringify(targetField, null, 2)}`); + if (!targetField) { + (0, logger_1.logError)(`Field '${fieldName}' not found or is not a single-select field.`); + throw new Error(`Field '${fieldName}' not found or is not a single-select field.`); + } + const targetOption = targetField.options.find((opt) => opt.name === fieldValue); + (0, logger_1.logDebugInfo)(`Target option: ${JSON.stringify(targetOption, null, 2)}`); + if (!targetOption) { + (0, logger_1.logError)(`Option '${fieldValue}' not found for field '${fieldName}'.`); + throw new Error(`Option '${fieldValue}' not found for field '${fieldName}'.`); + } + // Now search for the item through all pages + while (hasNextPage) { + const fieldResult = await octokit.graphql(fieldQuery, { + projectId: project.id, + after: endCursor + }); + // logDebugInfo(`Field result: ${JSON.stringify(fieldResult, null, 2)}`); + // Check current value in current page + currentItem = fieldResult.node.items.nodes.find((item) => item.id === contentId); + if (currentItem) { + // logDebugInfo(`Current item: ${JSON.stringify(currentItem, null, 2)}`); + const currentFieldValue = currentItem.fieldValues.nodes.find((value) => value.field?.name === fieldName); + if (currentFieldValue && currentFieldValue.optionId === targetOption.id) { + (0, logger_1.logDebugInfo)(`Field '${fieldName}' is already set to '${fieldValue}'. No update needed.`); + return false; + } + break; // Found the item, no need to continue pagination + } + hasNextPage = fieldResult.node.items.pageInfo.hasNextPage; + endCursor = fieldResult.node.items.pageInfo.endCursor; + } + (0, logger_1.logDebugInfo)(`Target field ID: ${targetField.id}`); + (0, logger_1.logDebugInfo)(`Target option ID: ${targetOption.id}`); + const mutation = ` + mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { + updateProjectV2ItemFieldValue( + input: { + projectId: $projectId, + itemId: $itemId, + fieldId: $fieldId, + value: { singleSelectOptionId: $optionId } + } + ) { + projectV2Item { + id + } + } + }`; + const mutationResult = await octokit.graphql(mutation, { + projectId: project.id, + itemId: contentId, + fieldId: targetField.id, + optionId: targetOption.id + }); + return !!mutationResult.updateProjectV2ItemFieldValue.projectV2Item; + }; + this.setTaskPriority = async (project, owner, repo, issueOrPullRequestNumber, priorityLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.priorityLabel, priorityLabel, token); + this.setTaskSize = async (project, owner, repo, issueOrPullRequestNumber, sizeLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.sizeLabel, sizeLabel, token); + this.moveIssueToColumn = async (project, owner, repo, issueOrPullRequestNumber, columnName, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.statusLabel, columnName, token); + this.getRandomMembers = async (organization, membersToAdd, currentMembers, token) => { + if (membersToAdd === 0) { + return []; + } + const octokit = github.getOctokit(token); + try { + const { data: teams } = await octokit.rest.teams.list({ + org: organization, + }); + if (teams.length === 0) { + (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); + return []; + } + const membersSet = new Set(); + for (const team of teams) { + (0, logger_1.logDebugInfo)(`Checking team: ${team.slug}`); + const { data: members } = await octokit.rest.teams.listMembersInOrg({ + org: organization, + team_slug: team.slug, + }); + (0, logger_1.logDebugInfo)(`Members: ${members.length}`); + members.forEach((member) => membersSet.add(member.login)); + } + const allMembers = Array.from(membersSet); + const availableMembers = allMembers.filter((member) => !currentMembers.includes(member)); + if (availableMembers.length === 0) { + (0, logger_1.logDebugInfo)(`No available members to assign for organization ${organization}.`); + return []; + } + if (membersToAdd >= availableMembers.length) { + (0, logger_1.logDebugInfo)(`Requested size (${membersToAdd}) exceeds available members (${availableMembers.length}). Returning all available members.`); + return availableMembers; + } + const shuffled = availableMembers.sort(() => Math.random() - 0.5); + return shuffled.slice(0, membersToAdd); + } + catch (error) { + (0, logger_1.logError)(`Error getting random members: ${error}.`); + } + return []; + }; + this.getAllMembers = async (organization, token) => { + const octokit = github.getOctokit(token); + try { + const { data: teams } = await octokit.rest.teams.list({ + org: organization, + }); + if (teams.length === 0) { + (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); + return []; + } + const membersSet = new Set(); + for (const team of teams) { + const { data: members } = await octokit.rest.teams.listMembersInOrg({ + org: organization, + team_slug: team.slug, + }); + members.forEach((member) => membersSet.add(member.login)); + } + return Array.from(membersSet); + } + catch (error) { + (0, logger_1.logError)(`Error getting all members: ${error}.`); + } + return []; + }; + this.getUserFromToken = async (token) => { + const octokit = github.getOctokit(token); + const { data: user } = await octokit.rest.users.getAuthenticated(); + return user.login; + }; + this.findTag = async (owner, repo, tag, token) => { + const octokit = github.getOctokit(token); + try { + const { data: foundTag } = await octokit.rest.git.getRef({ + owner, + repo, + ref: `tags/${tag}`, + }); + return foundTag; + } + catch (err) { + return undefined; + } + }; + this.getTagSHA = async (owner, repo, tag, token) => { + const foundTag = await this.findTag(owner, repo, tag, token); + if (!foundTag) { + (0, logger_1.logError)(`The '${tag}' tag does not exist in the remote repository`); + return undefined; + } + return foundTag.object.sha; + }; + this.updateTag = async (owner, repo, sourceTag, targetTag, token) => { + const sourceTagSHA = await this.getTagSHA(owner, repo, sourceTag, token); + if (!sourceTagSHA) { + (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); + return; + } + const foundTargetTag = await this.findTag(owner, repo, targetTag, token); + const refName = `tags/${targetTag}`; + const octokit = github.getOctokit(token); + if (foundTargetTag) { + (0, logger_1.logDebugInfo)(`Updating the '${targetTag}' tag to point to the '${sourceTag}' tag`); + await octokit.rest.git.updateRef({ + owner, + repo, + ref: refName, + sha: sourceTagSHA, + force: true, + }); + } + else { + (0, logger_1.logDebugInfo)(`Creating the '${targetTag}' tag from the '${sourceTag}' tag`); + await octokit.rest.git.createRef({ + owner, + repo, + ref: `refs/${refName}`, + sha: sourceTagSHA, + }); + } + }; + this.updateRelease = async (owner, repo, sourceTag, targetTag, token) => { + // Get the release associated with sourceTag + const octokit = github.getOctokit(token); + const { data: sourceRelease } = await octokit.rest.repos.getReleaseByTag({ + owner, + repo, + tag: sourceTag, + }); + if (!sourceRelease.name || !sourceRelease.body) { + (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); + return undefined; + } + (0, logger_1.logDebugInfo)(`Found release for sourceTag '${sourceTag}': ${sourceRelease.name}`); + // Check if there is a release for targetTag + const { data: releases } = await octokit.rest.repos.listReleases({ + owner, + repo, + }); + const targetRelease = releases.find(r => r.tag_name === targetTag); + let targetReleaseId; + if (targetRelease) { + (0, logger_1.logDebugInfo)(`Updating release for targetTag '${targetTag}'`); + // Update the target release with the content from the source release + await octokit.rest.repos.updateRelease({ + owner, + repo, + release_id: targetRelease.id, + name: sourceRelease.name, + body: sourceRelease.body, + draft: sourceRelease.draft, + prerelease: sourceRelease.prerelease, + }); + targetReleaseId = targetRelease.id; + } + else { + console.log(`Creating new release for targetTag '${targetTag}'`); + // Create a new release for targetTag if it doesn't exist + const { data: newRelease } = await octokit.rest.repos.createRelease({ + owner, + repo, + tag_name: targetTag, + name: sourceRelease.name, + body: sourceRelease.body, + draft: sourceRelease.draft, + prerelease: sourceRelease.prerelease, + }); + targetReleaseId = newRelease.id; + } + (0, logger_1.logInfo)(`Updated release for targetTag '${targetTag}'`); + return targetReleaseId.toString(); + }; + this.createRelease = async (owner, repo, version, title, changelog, token) => { + try { + const octokit = github.getOctokit(token); + const { data: release } = await octokit.rest.repos.createRelease({ + owner, + repo, + tag_name: `v${version}`, + name: `v${version} - ${title}`, + body: changelog, + draft: false, + prerelease: false, + }); + return release.html_url; + } + catch (error) { + (0, logger_1.logError)(`Error creating release: ${error}`); + return undefined; + } + }; + this.createTag = async (owner, repo, branch, tag, token) => { + const octokit = github.getOctokit(token); + try { + // Check if tag already exists + const existingTag = await this.findTag(owner, repo, tag, token); + if (existingTag) { + (0, logger_1.logInfo)(`Tag '${tag}' already exists in repository ${owner}/${repo}`); + return existingTag.object.sha; + } + // Get the latest commit SHA from the specified branch + const { data: ref } = await octokit.rest.git.getRef({ + owner, + repo, + ref: `heads/${branch}`, + }); + // Create the tag + await octokit.rest.git.createRef({ + owner, + repo, + ref: `refs/tags/${tag}`, + sha: ref.object.sha, + }); + (0, logger_1.logInfo)(`Created tag '${tag}' in repository ${owner}/${repo} from branch '${branch}'`); + return ref.object.sha; + } + catch (error) { + (0, logger_1.logError)(`Error creating tag '${tag}': ${JSON.stringify(error, null, 2)}`); + return undefined; + } + }; } - } - return (path === '..' || path === '.' ? '' : path) } +exports.ProjectRepository = ProjectRepository; /***/ }), -/***/ 84619: -/***/ (function(module) { +/***/ 634: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; - -// Node has always utf-8 -const utf8Decoder = new TextDecoder('utf-8') -const textDecoders = new Map([ - ['utf-8', utf8Decoder], - ['utf8', utf8Decoder] -]) - -function getDecoder (charset) { - let lc - while (true) { - switch (charset) { - case 'utf-8': - case 'utf8': - return decoders.utf8 - case 'latin1': - case 'ascii': // TODO: Make these a separate, strict decoder? - case 'us-ascii': - case 'iso-8859-1': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'windows-1252': - case 'iso_8859-1:1987': - case 'cp1252': - case 'x-cp1252': - return decoders.latin1 - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return decoders.utf16le - case 'base64': - return decoders.base64 - default: - if (lc === undefined) { - lc = true - charset = charset.toLowerCase() - continue - } - return decoders.other.bind(charset) - } - } -} - -const decoders = { - utf8: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.utf8Slice(0, data.length) - }, - - latin1: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - return data - } - return data.latin1Slice(0, data.length) - }, - - utf16le: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.ucs2Slice(0, data.length) - }, - - base64: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.base64Slice(0, data.length) - }, - - other: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) +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]; } }; } - - if (textDecoders.has(this.toString())) { - try { - return textDecoders.get(this).decode(data) - } catch {} + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullRequestRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +class PullRequestRepository { + constructor() { + this.isLinked = async (pullRequestUrl) => { + const htmlContent = await fetch(pullRequestUrl).then(res => res.text()); + return !htmlContent.includes('has_github_issues=false'); + }; + this.updateBaseBranch = async (owner, repository, pullRequestNumber, branch, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.pulls.update({ + owner: owner, + repo: repository, + pull_number: pullRequestNumber, + base: branch, + }); + (0, logger_1.logDebugInfo)(`Changed base branch to ${branch}`); + }; + this.updateDescription = async (owner, repository, pullRequestNumber, description, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.pulls.update({ + owner: owner, + repo: repository, + pull_number: pullRequestNumber, + body: description, + }); + (0, logger_1.logDebugInfo)(`Updated PR #${pullRequestNumber} description with: ${description}`); + }; + this.getCurrentReviewers = async (owner, repository, pullNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data } = await octokit.rest.pulls.listRequestedReviewers({ + owner, + repo: repository, + pull_number: pullNumber, + }); + return data.users.map((user) => user.login); + } + catch (error) { + (0, logger_1.logError)(`Error getting reviewers of PR: ${error}.`); + return []; + } + }; + this.addReviewersToPullRequest = async (owner, repository, pullNumber, reviewers, token) => { + const octokit = github.getOctokit(token); + try { + if (reviewers.length === 0) { + (0, logger_1.logDebugInfo)(`No reviewers provided for addition. Skipping operation.`); + return []; + } + const { data } = await octokit.rest.pulls.requestReviewers({ + owner, + repo: repository, + pull_number: pullNumber, + reviewers: reviewers, + }); + const addedReviewers = data.requested_reviewers || []; + return addedReviewers.map((reviewer) => reviewer.login); + } + catch (error) { + (0, logger_1.logError)(`Error adding reviewers to pull request: ${error}.`); + return []; + } + }; + this.getChangedFiles = async (owner, repository, pullNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data } = await octokit.rest.pulls.listFiles({ + owner, + repo: repository, + pull_number: pullNumber, + }); + return data.map((file) => ({ + filename: file.filename, + status: file.status + })); + } + catch (error) { + (0, logger_1.logError)(`Error getting changed files from pull request: ${error}.`); + return []; + } + }; + this.getPullRequestChanges = async (owner, repository, pullNumber, token) => { + const octokit = github.getOctokit(token); + const allFiles = []; + try { + for await (const response of octokit.paginate.iterator(octokit.rest.pulls.listFiles, { + owner, + repo: repository, + pull_number: pullNumber, + per_page: 100 + })) { + const filesData = response.data; + allFiles.push(...filesData.map((file) => ({ + filename: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + patch: file.patch || '' + }))); + } + return allFiles; + } + catch (error) { + (0, logger_1.logError)(`Error getting pull request changes: ${error}.`); + return []; + } + }; } - return typeof data === 'string' - ? data - : data.toString() - } -} - -function decodeText (text, sourceEncoding, destEncoding) { - if (text) { - return getDecoder(destEncoding)(text, sourceEncoding) - } - return text } - -module.exports = decodeText +exports.PullRequestRepository = PullRequestRepository; /***/ }), -/***/ 21467: -/***/ ((module) => { +/***/ 9829: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -module.exports = function getLimit (limits, name, defaultLimit) { - if ( - !limits || - limits[name] === undefined || - limits[name] === null - ) { return defaultLimit } - - if ( - typeof limits[name] !== 'number' || - isNaN(limits[name]) - ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - - return limits[name] +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SupabaseRepository = void 0; +const supabase_js_1 = __nccwpck_require__(1206); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class SupabaseRepository { + constructor(config) { + this.AI_FILE_CACHE_TABLE = 'ai_file_cache'; + this.MAX_BATCH_SIZE = 500; + this.DEFAULT_TIMEOUT = 30000; // 30 seconds + /** + * Set or update AI file cache entry + * If SHA hasn't changed, this will update the entry + */ + this.setAIFileCache = async (owner, repository, branch, fileInfo) => { + try { + const { error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .upsert({ + owner, + repository, + branch, + file_name: fileInfo.file_name, + path: fileInfo.path, + sha: fileInfo.sha, + description: fileInfo.description, + consumes: fileInfo.consumes, + consumed_by: fileInfo.consumed_by, + last_updated: new Date().toISOString() + }, { + onConflict: 'owner,repository,branch,path' + }); + if (error) { + (0, logger_1.logError)(`Error setting AI file cache for ${fileInfo.path}: ${JSON.stringify(error, null, 2)}`); + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error setting AI file cache ${fileInfo.path}: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Get AI file cache entry by path + */ + this.getAIFileCache = async (owner, repository, branch, filePath) => { + try { + const { data, error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .select('*') + .eq('owner', owner) + .eq('repository', repository) + .eq('branch', branch) + .eq('path', filePath) + .single(); + if (error) { + if (error.code === 'PGRST116') { + // No rows returned + return null; + } + (0, logger_1.logError)(`Error getting AI file cache: ${JSON.stringify(error, null, 2)}`); + return null; + } + return data; + } + catch (error) { + (0, logger_1.logError)(`Error getting AI file cache: ${JSON.stringify(error, null, 2)}`); + return null; + } + }; + /** + * Get all AI file cache entries for a branch + */ + this.getAIFileCachesByBranch = async (owner, repository, branch) => { + try { + const { data, error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .select('*') + .eq('owner', owner) + .eq('repository', repository) + .eq('branch', branch) + .order('path'); + if (error) { + (0, logger_1.logError)(`Error getting AI file caches by branch: ${JSON.stringify(error, null, 2)}`); + return []; + } + if (!data) { + return []; + } + return data; + } + catch (error) { + (0, logger_1.logError)(`Error getting AI file caches by branch: ${JSON.stringify(error, null, 2)}`); + return []; + } + }; + /** + * Remove AI file cache entry by path + */ + this.removeAIFileCacheByPath = async (owner, repository, branch, filePath) => { + try { + const { error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .delete() + .eq('owner', owner) + .eq('repository', repository) + .eq('branch', branch) + .eq('path', filePath); + if (error) { + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error removing AI file cache by path: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Duplicate AI file cache entries from one branch to another + */ + this.duplicateAIFileCacheByBranch = async (owner, repository, sourceBranch, targetBranch) => { + try { + const { error } = await this.supabase + .rpc('duplicate_ai_file_cache_by_branch', { + owner_param: owner, + repository_param: repository, + source_branch_param: sourceBranch, + target_branch_param: targetBranch + }); + if (error) { + (0, logger_1.logError)(`Error duplicating AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error duplicating AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Remove all AI file cache entries for a branch + */ + this.removeAIFileCacheByBranch = async (owner, repository, branch) => { + try { + const { error } = await this.supabase + .rpc('delete_ai_file_cache_by_branch', { + owner_param: owner, + repository_param: repository, + branch_param: branch + }); + if (error) { + (0, logger_1.logError)(`Error removing AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error removing AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Get SHA by path (for checking if file is cached) + */ + this.getShasumByPath = async (owner, repository, branch, path) => { + try { + const cached = await this.getAIFileCache(owner, repository, branch, path); + return cached?.sha; + } + catch (error) { + (0, logger_1.logError)(`Error getting SHA by path: ${JSON.stringify(error, null, 2)}`); + return undefined; + } + }; + /** + * Get distinct paths for a branch + */ + this.getDistinctPaths = async (owner, repository, branch) => { + try { + const cachedFiles = await this.getAIFileCachesByBranch(owner, repository, branch); + return cachedFiles.map(file => file.path); + } + catch (error) { + (0, logger_1.logError)(`Error getting distinct paths: ${JSON.stringify(error, null, 2)}`); + return []; + } + }; + const customFetch = async (input, init) => { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), this.DEFAULT_TIMEOUT); + try { + const response = await fetch(input, { + ...init, + signal: controller.signal + }); + return response; + } + finally { + clearTimeout(timeoutId); + } + }; + this.supabase = (0, supabase_js_1.createClient)(config.getUrl(), config.getKey(), { + global: { + headers: { + 'X-Client-Info': constants_1.COMMAND + }, + fetch: customFetch + }, + db: { + schema: 'public' + }, + auth: { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true + } + }); + } } +exports.SupabaseRepository = SupabaseRepository; /***/ }), -/***/ 31854: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 779: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -/* eslint-disable object-property-newline */ - - -const decodeText = __nccwpck_require__(84619) - -const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - -const EncodedLookup = { - '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', - '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', - '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', - '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', - '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', - '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', - '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', - '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', - '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', - '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', - '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', - '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', - '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', - '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', - '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', - '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', - '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', - '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', - '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', - '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', - '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', - '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', - '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', - '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', - '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', - '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', - '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', - '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', - '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', - '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', - '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', - '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', - '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', - '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', - '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', - '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', - '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', - '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', - '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', - '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', - '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', - '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', - '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', - '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', - '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', - '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', - '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', - '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', - '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', - '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', - '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', - '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', - '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', - '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', - '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', - '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', - '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', - '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', - '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', - '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', - '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', - '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', - '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', - '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', - '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', - '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', - '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', - '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', - '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', - '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', - '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', - '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', - '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', - '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', - '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', - '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', - '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', - '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', - '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', - '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', - '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', - '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', - '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', - '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', - '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', - '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', - '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', - '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', - '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', - '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', - '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', - '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', - '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', - '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', - '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', - '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', - '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' -} - -function encodedReplacer (match) { - return EncodedLookup[match] -} - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - const char = str[i] - if (char === '\\' && inquote) { - if (escaping) { escaping = false } else { - escaping = true - continue - } - } else if (char === '"') { - if (!escaping) { - if (inquote) { - inquote = false - state = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = STATE_KEY - if (charset) { - if (tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } - charset = '' - } else if (tmp.length) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } - tmp = '' - ++p - continue - } else if (!inquote && (char === ' ' || char === '\t')) { continue } +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WorkflowRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const workflow_run_1 = __nccwpck_require__(6845); +const constants_1 = __nccwpck_require__(8593); +class WorkflowRepository { + constructor() { + this.getWorkflows = async (params) => { + const octokit = github.getOctokit(params.tokens.token); + const workflows = await octokit.rest.actions.listWorkflowRunsForRepo({ + owner: params.owner, + repo: params.repo, + }); + return workflows.data.workflow_runs.map(w => new workflow_run_1.WorkflowRun({ + id: w.id, + name: w.name ?? 'unknown', + head_branch: w.head_branch, + head_sha: w.head_sha, + run_number: w.run_number, + event: w.event, + status: w.status ?? 'unknown', + conclusion: w.conclusion ?? null, + created_at: w.created_at, + updated_at: w.updated_at, + url: w.url, + html_url: w.html_url, + })); + }; + this.getActivePreviousRuns = async (params) => { + const workflows = await this.getWorkflows(params); + const runId = parseInt(process.env.GITHUB_RUN_ID, 10); + const workflowName = process.env.GITHUB_WORKFLOW; + return workflows.filter((run) => { + const isSameWorkflow = run.name === workflowName; + const isPrevious = run.id < runId; + const isActive = constants_1.WORKFLOW_ACTIVE_STATUSES.includes(run.status); + return isSameWorkflow && isPrevious && isActive; + }); + }; } - tmp += char - } - if (charset && tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } else if (tmp) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - - if (res[p] === undefined) { - if (tmp) { res[p] = tmp } - } else { res[p][1] = tmp } - - return res } - -module.exports = parseParams +exports.WorkflowRepository = WorkflowRepository; /***/ }), -/***/ 14379: +/***/ 6365: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const { Argument } = __nccwpck_require__(69414); -const { Command } = __nccwpck_require__(80552); -const { CommanderError, InvalidArgumentError } = __nccwpck_require__(12625); -const { Help } = __nccwpck_require__(5153); -const { Option } = __nccwpck_require__(66558); - -exports.program = new Command(); - -exports.createCommand = (name) => new Command(name); -exports.createOption = (flags, description) => new Option(flags, description); -exports.createArgument = (name, description) => new Argument(name, description); - -/** - * Expose classes - */ - -exports.Command = Command; -exports.Option = Option; -exports.Argument = Argument; -exports.Help = Help; +"use strict"; -exports.CommanderError = CommanderError; -exports.InvalidArgumentError = InvalidArgumentError; -exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ContentInterface = void 0; +const logger_1 = __nccwpck_require__(8836); +class ContentInterface { + constructor() { + this.getContent = (description) => { + try { + if (description === undefined) { + return undefined; + } + if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { + return undefined; + } + return description.split(this.startPattern)[1].split(this.endPattern)[0]; + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; + this._addContent = (description, content) => { + if (description.indexOf(this.startPattern) === -1 && description.indexOf(this.endPattern) === -1) { + const newContent = `${this.startPattern}\n${content}\n${this.endPattern}`; + return `${description}\n\n${newContent}`; + } + else { + return undefined; + } + }; + this._updateContent = (description, content) => { + if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { + (0, logger_1.logError)(`The content has a problem with open-close tags: ${this.startPattern} / ${this.endPattern}`); + return undefined; + } + const start = description.split(this.startPattern)[0]; + const mid = `${this.startPattern}\n${content}\n${this.endPattern}`; + const end = description.split(this.endPattern)[1]; + return `${start}${mid}${end}`; + }; + this.updateContent = (description, content) => { + try { + if (description === undefined || content === undefined) { + return undefined; + } + const addedContent = this._addContent(description, content); + if (addedContent !== undefined) { + return addedContent; + } + return this._updateContent(description, content); + } + catch (error) { + (0, logger_1.logError)(`Error updating issue description: ${error}`); + return undefined; + } + }; + } + get _id() { + return `git-board-flow-${this.id}`; + } + get startPattern() { + if (this.visibleContent) { + return ``; + } + return ``; + } + return `${this._id}-end -->`; + } +} +exports.ContentInterface = ContentInterface; /***/ }), -/***/ 69414: +/***/ 9913: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const { InvalidArgumentError } = __nccwpck_require__(12625); - -class Argument { - /** - * Initialize a new command argument with the given name and description. - * The default is that the argument is required, and you can explicitly - * indicate this with <> around the name. Put [] around the name for an optional argument. - * - * @param {string} name - * @param {string} [description] - */ - - constructor(name, description) { - this.description = description || ''; - this.variadic = false; - this.parseArg = undefined; - this.defaultValue = undefined; - this.defaultValueDescription = undefined; - this.argChoices = undefined; +"use strict"; - switch (name[0]) { - case '<': // e.g. - this.required = true; - this._name = name.slice(1, -1); - break; - case '[': // e.g. [optional] - this.required = false; - this._name = name.slice(1, -1); - break; - default: - this.required = true; - this._name = name; - break; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueContentInterface = void 0; +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +const content_interface_1 = __nccwpck_require__(6365); +class IssueContentInterface extends content_interface_1.ContentInterface { + constructor() { + super(...arguments); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.internalGetter = async (execution) => { + try { + let number = -1; + if (execution.isSingleAction) { + number = execution.issueNumber; + } + else if (execution.isIssue) { + number = execution.issue.number; + } + else if (execution.isPullRequest) { + number = execution.pullRequest.number; + } + else if (execution.isPush) { + number = execution.issueNumber; + } + else { + return undefined; + } + const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); + return this.getContent(description); + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; + this.internalUpdate = async (execution, content) => { + try { + let number = -1; + if (execution.isSingleAction) { + if (execution.isIssue) { + number = execution.issue.number; + } + else if (execution.isPullRequest) { + number = execution.pullRequest.number; + } + else if (execution.isPush) { + number = execution.issueNumber; + } + else { + number = execution.singleAction.issue; + } + } + else if (execution.isIssue) { + number = execution.issue.number; + } + else if (execution.isPullRequest) { + number = execution.pullRequest.number; + } + else if (execution.isPush) { + number = execution.issueNumber; + } + else { + return undefined; + } + const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); + const updated = this.updateContent(description, content); + if (updated === undefined) { + return undefined; + } + await this.issueRepository.updateDescription(execution.owner, execution.repo, number, updated, execution.tokens.token); + return updated; + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; } +} +exports.IssueContentInterface = IssueContentInterface; - if (this._name.length > 3 && this._name.slice(-3) === '...') { - this.variadic = true; - this._name = this._name.slice(0, -3); - } - } - /** - * Return argument name. - * - * @return {string} - */ +/***/ }), - name() { - return this._name; - } +/***/ 4509: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * @package - */ +"use strict"; - _concatValue(value, previous) { - if (previous === this.defaultValue || !Array.isArray(previous)) { - return [value]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConfigurationHandler = void 0; +const config_1 = __nccwpck_require__(1106); +const logger_1 = __nccwpck_require__(8836); +const issue_content_interface_1 = __nccwpck_require__(9913); +class ConfigurationHandler extends issue_content_interface_1.IssueContentInterface { + constructor() { + super(...arguments); + this.update = async (execution) => { + try { + return await this.internalUpdate(execution, JSON.stringify(execution.currentConfiguration, null, 4)); + } + catch (error) { + (0, logger_1.logError)(`Error updating issue description: ${error}`); + return undefined; + } + }; + this.get = async (execution) => { + try { + const config = await this.internalGetter(execution); + if (config === undefined) { + return undefined; + } + const branchConfig = JSON.parse(config); + return new config_1.Config(branchConfig); + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; } + get id() { + return 'configuration'; + } + get visibleContent() { + return false; + } +} +exports.ConfigurationHandler = ConfigurationHandler; - return previous.concat(value); - } - - /** - * Set the default value, and optionally supply the description to be displayed in the help. - * - * @param {*} value - * @param {string} [description] - * @return {Argument} - */ - - default(value, description) { - this.defaultValue = value; - this.defaultValueDescription = description; - return this; - } - /** - * Set the custom handler for processing CLI command arguments into argument values. - * - * @param {Function} [fn] - * @return {Argument} - */ +/***/ }), - argParser(fn) { - this.parseArg = fn; - return this; - } +/***/ 2430: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Only allow argument value to be one of choices. - * - * @param {string[]} values - * @return {Argument} - */ +"use strict"; - choices(values) { - this.argChoices = values.slice(); - this.parseArg = (arg, previous) => { - if (!this.argChoices.includes(arg)) { - throw new InvalidArgumentError( - `Allowed choices are ${this.argChoices.join(', ')}.`, - ); - } - if (this.variadic) { - return this._concatValue(arg, previous); - } - return arg; - }; - return this; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CreateReleaseUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class CreateReleaseUseCase { + constructor() { + this.taskId = 'CreateReleaseUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + if (param.singleAction.version.length === 0) { + (0, logger_1.logError)(`Version is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` + ], + })); + return result; + } + else if (param.singleAction.title.length === 0) { + (0, logger_1.logError)(`Title is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE} is not set.` + ], + })); + } + else if (param.singleAction.changelog.length === 0) { + (0, logger_1.logError)(`Changelog is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG} is not set.` + ], + })); + } + try { + const releaseUrl = await this.projectRepository.createRelease(param.owner, param.repo, param.singleAction.version, param.singleAction.title, param.singleAction.changelog, param.tokens.token); + if (releaseUrl) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`Created release \`${releaseUrl}\`.`], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Failed to create release.` + ], + })); + } + } + catch (error) { + (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Failed to create release.`], + errors: [ + JSON.stringify(error) + ], + })); + } + return result; + } +} +exports.CreateReleaseUseCase = CreateReleaseUseCase; - /** - * Make argument required. - * - * @returns {Argument} - */ - argRequired() { - this.required = true; - return this; - } - /** - * Make argument optional. - * - * @returns {Argument} - */ - argOptional() { - this.required = false; - return this; - } -} +/***/ }), -/** - * Takes an argument and returns its human readable equivalent for help usage. - * - * @param {Argument} arg - * @return {string} - * @private - */ +/***/ 5279: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function humanReadableArgName(arg) { - const nameOutput = arg.name() + (arg.variadic === true ? '...' : ''); +"use strict"; - return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CreateTagUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class CreateTagUseCase { + constructor() { + this.taskId = 'CreateTagUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + if (param.singleAction.version.length === 0) { + (0, logger_1.logError)(`Version is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` + ], + })); + return result; + } + else if (param.currentConfiguration.releaseBranch === undefined) { + (0, logger_1.logError)(`Working branch not found in configuration.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Release branch not found in issue configuration.` + ], + })); + return result; + } + try { + const sha1Tag = await this.projectRepository.createTag(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.singleAction.version, param.tokens.token); + if (sha1Tag) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`Tag ${param.singleAction.version} is ready: ${sha1Tag}`], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Failed to create tag ${param.singleAction.version}.` + ], + })); + } + } + catch (error) { + (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Failed to create tag ${param.singleAction.version}.`], + errors: [ + JSON.stringify(error) + ], + })); + } + return result; + } } - -exports.Argument = Argument; -exports.humanReadableArgName = humanReadableArgName; +exports.CreateTagUseCase = CreateTagUseCase; /***/ }), -/***/ 80552: +/***/ 8293: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const EventEmitter = (__nccwpck_require__(15673).EventEmitter); -const childProcess = __nccwpck_require__(17718); -const path = __nccwpck_require__(49411); -const fs = __nccwpck_require__(87561); -const process = __nccwpck_require__(97742); - -const { Argument, humanReadableArgName } = __nccwpck_require__(69414); -const { CommanderError } = __nccwpck_require__(12625); -const { Help } = __nccwpck_require__(5153); -const { Option, DualOptions } = __nccwpck_require__(66558); -const { suggestSimilar } = __nccwpck_require__(67592); - -class Command extends EventEmitter { - /** - * Initialize a new `Command`. - * - * @param {string} [name] - */ - - constructor(name) { - super(); - /** @type {Command[]} */ - this.commands = []; - /** @type {Option[]} */ - this.options = []; - this.parent = null; - this._allowUnknownOption = false; - this._allowExcessArguments = true; - /** @type {Argument[]} */ - this.registeredArguments = []; - this._args = this.registeredArguments; // deprecated old name - /** @type {string[]} */ - this.args = []; // cli args with options removed - this.rawArgs = []; - this.processedArgs = []; // like .args but after custom processing and collecting variadic - this._scriptPath = null; - this._name = name || ''; - this._optionValues = {}; - this._optionValueSources = {}; // default, env, cli etc - this._storeOptionsAsProperties = false; - this._actionHandler = null; - this._executableHandler = false; - this._executableFile = null; // custom name for executable - this._executableDir = null; // custom search directory for subcommands - this._defaultCommandName = null; - this._exitCallback = null; - this._aliases = []; - this._combineFlagAndOptionalValue = true; - this._description = ''; - this._summary = ''; - this._argsDescription = undefined; // legacy - this._enablePositionalOptions = false; - this._passThroughOptions = false; - this._lifeCycleHooks = {}; // a hash of arrays - /** @type {(boolean | string)} */ - this._showHelpAfterError = false; - this._showSuggestionAfterError = true; - - // see .configureOutput() for docs - this._outputConfiguration = { - writeOut: (str) => process.stdout.write(str), - writeErr: (str) => process.stderr.write(str), - getOutHelpWidth: () => - process.stdout.isTTY ? process.stdout.columns : undefined, - getErrHelpWidth: () => - process.stderr.isTTY ? process.stderr.columns : undefined, - outputError: (str, write) => write(str), - }; - - this._hidden = false; - /** @type {(Option | null | undefined)} */ - this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled. - this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited - /** @type {Command} */ - this._helpCommand = undefined; // lazy initialised, inherited - this._helpConfiguration = {}; - } +"use strict"; - /** - * Copy settings that are useful to have in common across root command and subcommands. - * - * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) - * - * @param {Command} sourceCommand - * @return {Command} `this` command for chaining - */ - copyInheritedSettings(sourceCommand) { - this._outputConfiguration = sourceCommand._outputConfiguration; - this._helpOption = sourceCommand._helpOption; - this._helpCommand = sourceCommand._helpCommand; - this._helpConfiguration = sourceCommand._helpConfiguration; - this._exitCallback = sourceCommand._exitCallback; - this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties; - this._combineFlagAndOptionalValue = - sourceCommand._combineFlagAndOptionalValue; - this._allowExcessArguments = sourceCommand._allowExcessArguments; - this._enablePositionalOptions = sourceCommand._enablePositionalOptions; - this._showHelpAfterError = sourceCommand._showHelpAfterError; - this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DeployedActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class DeployedActionUseCase { + constructor() { + this.taskId = 'DeployedActionUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.branchRepository = new branch_repository_1.BranchRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (!param.labels.isDeploy) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to set label \`${param.labels.deployed}\` but there was no \`${param.labels.deploy}\` label.`, + ], + })); + return result; + } + if (param.labels.isDeployed) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to set label \`${param.labels.deployed}\` but it was already set.`, + ], + })); + return result; + } + const labelNames = param.labels.currentIssueLabels.filter(name => name !== param.labels.deploy); + labelNames.push(param.labels.deployed); + await this.issueRepository.setLabels(param.owner, param.repo, param.singleAction.issue, labelNames, param.tokens.token); + (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.singleAction.issue}:`); + (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Label \`${param.labels.deployed}\` added after a success deploy.`, + ], + })); + if (param.currentConfiguration.releaseBranch) { + const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDefaultResult); + const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDevelopResult); + } + else if (param.currentConfiguration.hotfixBranch) { + const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.hotfixBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDefaultResult); + const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.branches.defaultBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDevelopResult); + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to assign members to issue.`], + error: error, + })); + } + return result; + } +} +exports.DeployedActionUseCase = DeployedActionUseCase; - return this; - } - /** - * @returns {Command[]} - * @private - */ +/***/ }), - _getCommandAndAncestors() { - const result = []; - // eslint-disable-next-line @typescript-eslint/no-this-alias - for (let command = this; command; command = command.parent) { - result.push(command); - } - return result; - } +/***/ 9029: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Define a command. - * - * There are two styles of command: pay attention to where to put the description. - * - * @example - * // Command implemented using action handler (description is supplied separately to `.command`) - * program - * .command('clone [destination]') - * .description('clone a repository into a newly created directory') - * .action((source, destination) => { - * console.log('clone command called'); - * }); - * - * // Command implemented using separate executable file (description is second parameter to `.command`) - * program - * .command('start ', 'start named service') - * .command('stop [service]', 'stop named service, or all if no name supplied'); - * - * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` - * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) - * @param {object} [execOpts] - configuration options (for executable) - * @return {Command} returns new command for action handler, or `this` for executable command - */ +"use strict"; - command(nameAndArgs, actionOptsOrExecDesc, execOpts) { - let desc = actionOptsOrExecDesc; - let opts = execOpts; - if (typeof desc === 'object' && desc !== null) { - opts = desc; - desc = null; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PublishGithubActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class PublishGithubActionUseCase { + constructor() { + this.taskId = 'PublishGithubActionUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); } - opts = opts || {}; - const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); - - const cmd = this.createCommand(name); - if (desc) { - cmd.description(desc); - cmd._executableHandler = true; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + if (param.singleAction.version.length === 0) { + (0, logger_1.logError)(`Version is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` + ], + })); + return result; + } + const sourceTag = `v${param.singleAction.version}`; + const targetTag = sourceTag.split('.')[0]; + try { + await this.projectRepository.updateTag(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); + const releaseId = await this.projectRepository.updateRelease(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); + if (releaseId) { + (0, logger_1.logInfo)(`Updated release \`${targetTag}\` from \`${sourceTag}\`: ${releaseId}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`Updated release \`${targetTag}\` from \`${sourceTag}\`.`], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Failed to update release \`${targetTag}\` from \`${sourceTag}\`.` + ], + })); + } + } + catch (error) { + (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Failed to update release \`${targetTag}\` from \`${sourceTag}\`.`], + errors: [ + JSON.stringify(error) + ], + })); + } + return result; } - if (opts.isDefault) this._defaultCommandName = cmd._name; - cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden - cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor - if (args) cmd.arguments(args); - this._registerCommand(cmd); - cmd.parent = this; - cmd.copyInheritedSettings(this); - - if (desc) return this; - return cmd; - } - - /** - * Factory routine to create a new unattached command. - * - * See .command() for creating an attached subcommand, which uses this routine to - * create the command. You can override createCommand to customise subcommands. - * - * @param {string} [name] - * @return {Command} new command - */ - - createCommand(name) { - return new Command(name); - } +} +exports.PublishGithubActionUseCase = PublishGithubActionUseCase; - /** - * You can customise the help with a subclass of Help by overriding createHelp, - * or by overriding Help properties using configureHelp(). - * - * @return {Help} - */ - createHelp() { - return Object.assign(new Help(), this.configureHelp()); - } +/***/ }), - /** - * You can customise the help by overriding Help properties using configureHelp(), - * or with a subclass of Help by overriding createHelp(). - * - * @param {object} [configuration] - configuration options - * @return {(Command | object)} `this` command for chaining, or stored configuration - */ +/***/ 7757: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - configureHelp(configuration) { - if (configuration === undefined) return this._helpConfiguration; +"use strict"; - this._helpConfiguration = configuration; - return this; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VectorActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const file_repository_1 = __nccwpck_require__(1503); +const supabase_repository_1 = __nccwpck_require__(9829); +const ai_repository_1 = __nccwpck_require__(8307); +const logger_1 = __nccwpck_require__(8836); +const file_import_analyzer_1 = __nccwpck_require__(5310); +const file_cache_manager_1 = __nccwpck_require__(1855); +const codebase_analyzer_1 = __nccwpck_require__(678); +const constants_1 = __nccwpck_require__(8593); +class VectorActionUseCase { + constructor() { + this.taskId = 'VectorActionUseCase'; + this.fileRepository = new file_repository_1.FileRepository(); + this.aiRepository = new ai_repository_1.AiRepository(); + this.fileImportAnalyzer = new file_import_analyzer_1.FileImportAnalyzer(); + this.fileCacheManager = new file_cache_manager_1.FileCacheManager(); + this.checkAICacheInSupabase = async (param, branch, repositoryFiles) => { + const results = []; + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + const remotePaths = await supabaseRepository.getDistinctPaths(param.owner, param.repo, branch); + // Get all local paths from repository files + const localPaths = new Set(Array.from(repositoryFiles.keys())); + // Find paths that exist in Supabase but not in the current branch + const pathsToRemove = remotePaths.filter(path => !localPaths.has(path)); + if (pathsToRemove.length > 0 && remotePaths.length > 0) { + (0, logger_1.logInfo)(`šŸ“¦ Found ${pathsToRemove.length} paths to remove from AI index as they no longer exist in the branch ${branch}.`); + for (const path of pathsToRemove) { + try { + await supabaseRepository.removeAIFileCacheByPath(param.owner, param.repo, branch, path); + (0, logger_1.logInfo)(`šŸ“¦ āœ… Removed AI cache for path: ${path}`); + } + catch (error) { + (0, logger_1.logError)(`šŸ“¦ āŒ Error removing AI cache for path ${path}: ${JSON.stringify(error, null, 2)}`); + } + } + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Removed ${pathsToRemove.length} paths from AI index as they no longer exist in \`${branch}\`.`, + ], + })); + } + else { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + return results; + }; + this.uploadAICacheToSupabase = async (param, branch, repositoryFiles) => { + const results = []; + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + const startTime = Date.now(); + const filePaths = Array.from(repositoryFiles.keys()); + // Step 1: Build relationship map once for all files + (0, logger_1.logInfo)(`šŸ“¦ Building relationship map from repository files...`); + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumesMap = relationshipMaps.consumes; + const consumedByMap = relationshipMaps.consumedBy; + (0, logger_1.logInfo)(`āœ… Relationship map built for ${repositoryFiles.size} files`); + for (let i = 0; i < filePaths.length; i++) { + const filePath = filePaths[i]; + const fileContent = repositoryFiles.get(filePath) || ''; + const progress = ((i + 1) / filePaths.length) * 100; + const currentTime = Date.now(); + const elapsedTime = (currentTime - startTime) / 1000; // in seconds + const estimatedTotalTime = (elapsedTime / (i + 1)) * filePaths.length; + const remainingTime = estimatedTotalTime - elapsedTime; + (0, logger_1.logSingleLine)(`šŸ”˜ ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Checking [${filePath}]`); + // Normalize path for consistent comparison + const normalizedPath = filePath.replace(/^\.\//, '').replace(/\\/g, '/').trim(); + // Calculate SHA for comparison + const currentSHA = this.fileCacheManager.calculateFileSHA(fileContent); + const remoteShasum = await supabaseRepository.getShasumByPath(param.owner, param.repo, branch, normalizedPath); + if (remoteShasum) { + if (remoteShasum === currentSHA) { + (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File indexed [${normalizedPath}]`); + continue; + } + else if (remoteShasum !== currentSHA) { + (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File has changes and must be reindexed [${normalizedPath}]`); + await supabaseRepository.removeAIFileCacheByPath(param.owner, param.repo, branch, normalizedPath); + } + } + else { + // File not in cache - will be processed below + (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File not in cache, will index [${normalizedPath}]`); + } + // Generate AI cache for this file + if (fileContent) { + try { + (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Generating AI cache [${filePath}]`); + // Step 2: Extract imports for this file (from pre-built map) + const consumes = consumesMap.get(filePath) || []; + const consumedBy = consumedByMap.get(filePath) || []; + // Step 3: Generate description using AI (with fallback) + let description = this.codebaseAnalyzer.generateBasicDescription(filePath); + try { + // Create schema for single file description + const FILE_DESCRIPTION_SCHEMA = { + "type": "object", + "description": "File description", + "properties": { + "description": { + "type": "string", + "description": "Description of what the file does." + } + }, + "required": ["description"], + "additionalProperties": false + }; + const descriptionPrompt = `${constants_1.PROMPTS.CODE_BASE_ANALYSIS}: - /** - * The default output goes to stdout and stderr. You can customise this for special - * applications. You can also customise the display of errors by overriding outputError. - * - * The configuration properties are all functions: - * - * // functions to change where being written, stdout and stderr - * writeOut(str) - * writeErr(str) - * // matching functions to specify width for wrapping help - * getOutHelpWidth() - * getErrHelpWidth() - * // functions based on what is being written out - * outputError(str, write) // used for displaying errors, and not used for displaying help - * - * @param {object} [configuration] - configuration options - * @return {(Command | object)} `this` command for chaining, or stored configuration - */ +\`\`\` +${fileContent} +\`\`\` - configureOutput(configuration) { - if (configuration === undefined) return this._outputConfiguration; +`; + const aiResponse = await this.aiRepository.askJson(param.ai, descriptionPrompt, FILE_DESCRIPTION_SCHEMA, "file_description"); + if (aiResponse && typeof aiResponse === 'object' && aiResponse.description) { + description = aiResponse.description.trim(); + } + } + catch (error) { + (0, logger_1.logError)(`Error generating AI description for ${filePath}, using fallback: ${error}`); + } + // Step 4: Save to Supabase (normalize path before saving) + const fileName = filePath.split('/').pop() || filePath; + const normalizedFilePath = filePath.replace(/^\.\//, '').replace(/\\/g, '/').trim(); + const normalizedConsumes = consumes.map(p => p.replace(/^\.\//, '').replace(/\\/g, '/').trim()); + const normalizedConsumedBy = consumedBy.map(p => p.replace(/^\.\//, '').replace(/\\/g, '/').trim()); + await supabaseRepository.setAIFileCache(param.owner, param.repo, branch, { + file_name: fileName, + path: normalizedFilePath, + sha: currentSHA, + description: description, + consumes: normalizedConsumes, + consumed_by: normalizedConsumedBy + }); + (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | AI cache saved [${filePath}]`); + } + catch (error) { + (0, logger_1.logError)(`Error generating AI cache for ${filePath}: ${JSON.stringify(error, null, 2)}`); + } + } + } + const totalDurationSeconds = (Date.now() - startTime) / 1000; + (0, logger_1.logInfo)(`šŸ“¦ šŸš€ All files stored in AI cache ${param.owner}/${param.repo}/${branch}. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, true); + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `All files up to date in AI cache for \`${branch}\`. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, + ], + })); + return results; + }; + this.duplicateAICacheToBranch = async (param, sourceBranch, targetBranch) => { + const results = []; + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + try { + (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Clearing possible existing AI cache from ${targetBranch} for ${param.owner}/${param.repo}.`); + await supabaseRepository.removeAIFileCacheByBranch(param.owner, param.repo, targetBranch); + (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Duplicating AI cache from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`); + await supabaseRepository.duplicateAIFileCacheByBranch(param.owner, param.repo, sourceBranch, targetBranch); + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Duplicated AI cache from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`, + ], + })); + } + catch (error) { + (0, logger_1.logError)(`šŸ“¦ -> šŸ“¦ āŒ Error duplicating AI cache from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Error duplicating AI cache from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`, + ], + })); + } + return results; + }; + // Initialize CodebaseAnalyzer with dependencies + this.codebaseAnalyzer = new codebase_analyzer_1.CodebaseAnalyzer(this.aiRepository, this.fileImportAnalyzer, this.fileCacheManager); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + // Check if AI configuration is available + if (!param.ai || !param.ai.getOpenRouterModel() || !param.ai.getOpenRouterApiKey()) { + (0, logger_1.logError)(`Missing required AI configuration. Please provide OPENROUTER_API_KEY and OPENROUTER_MODEL. ${JSON.stringify(param.ai, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Missing required AI configuration. Please provide OPENROUTER_API_KEY and OPENROUTER_MODEL.`, + ], + })); + return results; + } + const branch = param.commit.branch || param.branches.main; + let duplicationBranch = undefined; + if (branch === param.branches.main && param.singleAction.isAiCacheLocalAction) { + (0, logger_1.logInfo)(`šŸ“¦ AI cache from [${param.branches.main}] will be duplicated to [${param.branches.development}] for ${param.owner}/${param.repo}.`); + duplicationBranch = param.branches.development; + } + (0, logger_1.logInfo)(`šŸ“¦ Getting repository files on ${param.owner}/${param.repo}/${branch}`); + const repositoryFiles = await this.fileRepository.getRepositoryContent(param.owner, param.repo, param.tokens.token, branch, param.ai.getAiIgnoreFiles(), (fileName) => { + (0, logger_1.logSingleLine)(`Checking file ${fileName}`); + }, (fileName) => { + (0, logger_1.logSingleLine)(`Ignoring file ${fileName}`); + }); + (0, logger_1.logInfo)(`šŸ“¦ āœ… Files to index: ${repositoryFiles.size}`, true); + results.push(...await this.checkAICacheInSupabase(param, branch, repositoryFiles)); + results.push(...await this.uploadAICacheToSupabase(param, branch, repositoryFiles)); + if (duplicationBranch) { + results.push(...await this.duplicateAICacheToBranch(param, branch, duplicationBranch)); + } + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Vector action executed successfully.`, + ], + })); + } + catch (error) { + (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`, + ], + })); + } + return results; + } +} +exports.VectorActionUseCase = VectorActionUseCase; - Object.assign(this._outputConfiguration, configuration); - return this; - } - /** - * Display the help or a custom message after an error occurs. - * - * @param {(boolean|string)} [displayHelp] - * @return {Command} `this` command for chaining - */ - showHelpAfterError(displayHelp = true) { - if (typeof displayHelp !== 'string') displayHelp = !!displayHelp; - this._showHelpAfterError = displayHelp; - return this; - } +/***/ }), - /** - * Display suggestion of similar commands for unknown commands, or options for unknown options. - * - * @param {boolean} [displaySuggestion] - * @return {Command} `this` command for chaining - */ - showSuggestionAfterError(displaySuggestion = true) { - this._showSuggestionAfterError = !!displaySuggestion; - return this; - } +/***/ 5016: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Add a prepared subcommand. - * - * See .command() for creating an attached subcommand which inherits settings from its parent. - * - * @param {Command} cmd - new subcommand - * @param {object} [opts] - configuration options - * @return {Command} `this` command for chaining - */ +"use strict"; - addCommand(cmd, opts) { - if (!cmd._name) { - throw new Error(`Command passed to .addCommand() must have a name -- specify the name in Command constructor or using .name()`); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommitUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +const notify_new_commit_on_issue_use_case_1 = __nccwpck_require__(8020); +const check_changes_issue_size_use_case_1 = __nccwpck_require__(5863); +class CommitUseCase { + constructor() { + this.taskId = 'CommitUseCase'; } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + if (param.commit.commits.length === 0) { + (0, logger_1.logDebugInfo)('No commits found in this push.'); + return results; + } + (0, logger_1.logDebugInfo)(`Branch: ${param.commit.branch}`); + (0, logger_1.logDebugInfo)(`Commits detected: ${param.commit.commits.length}`); + (0, logger_1.logDebugInfo)(`Issue number: ${param.issueNumber}`); + results.push(...(await new notify_new_commit_on_issue_use_case_1.NotifyNewCommitOnIssueUseCase().invoke(param))); + results.push(...(await new check_changes_issue_size_use_case_1.CheckChangesIssueSizeUseCase().invoke(param))); + } + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error processing the commits.`, + ], + error: error, + })); + } + return results; + } +} +exports.CommitUseCase = CommitUseCase; - opts = opts || {}; - if (opts.isDefault) this._defaultCommandName = cmd._name; - if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation - - this._registerCommand(cmd); - cmd.parent = this; - cmd._checkForBrokenPassThrough(); - return this; - } +/***/ }), - /** - * Factory routine to create a new unattached argument. - * - * See .argument() for creating an attached argument, which uses this routine to - * create the argument. You can override createArgument to return a custom argument. - * - * @param {string} name - * @param {string} [description] - * @return {Argument} new argument - */ +/***/ 854: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - createArgument(name, description) { - return new Argument(name, description); - } +"use strict"; - /** - * Define argument syntax for command. - * - * The default is that the argument is required, and you can explicitly - * indicate this with <> around the name. Put [] around the name for an optional argument. - * - * @example - * program.argument(''); - * program.argument('[output-file]'); - * - * @param {string} name - * @param {string} [description] - * @param {(Function|*)} [fn] - custom argument processing function - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - */ - argument(name, description, fn, defaultValue) { - const argument = this.createArgument(name, description); - if (typeof fn === 'function') { - argument.default(defaultValue).argParser(fn); - } else { - argument.default(fn); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueCommentUseCase = void 0; +const logger_1 = __nccwpck_require__(8836); +const think_use_case_1 = __nccwpck_require__(3841); +const check_issue_comment_language_use_case_1 = __nccwpck_require__(465); +class IssueCommentUseCase { + constructor() { + this.taskId = 'IssueCommentUseCase'; } - this.addArgument(argument); - return this; - } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + results.push(...await new check_issue_comment_language_use_case_1.CheckIssueCommentLanguageUseCase().invoke(param)); + results.push(...await new think_use_case_1.ThinkUseCase().invoke(param)); + return results; + } +} +exports.IssueCommentUseCase = IssueCommentUseCase; - /** - * Define argument syntax for command, adding multiple at once (without descriptions). - * - * See also .argument(). - * - * @example - * program.arguments(' [env]'); - * - * @param {string} names - * @return {Command} `this` command for chaining - */ - arguments(names) { - names - .trim() - .split(/ +/) - .forEach((detail) => { - this.argument(detail); - }); - return this; - } +/***/ }), - /** - * Define argument syntax for command, adding a prepared argument. - * - * @param {Argument} argument - * @return {Command} `this` command for chaining - */ - addArgument(argument) { - const previousArgument = this.registeredArguments.slice(-1)[0]; - if (previousArgument && previousArgument.variadic) { - throw new Error( - `only the last argument can be variadic '${previousArgument.name()}'`, - ); - } - if ( - argument.required && - argument.defaultValue !== undefined && - argument.parseArg === undefined - ) { - throw new Error( - `a default value for a required argument is never used: '${argument.name()}'`, - ); - } - this.registeredArguments.push(argument); - return this; - } +/***/ 8675: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Customise or override default help command. By default a help command is automatically added if your command has subcommands. - * - * @example - * program.helpCommand('help [cmd]'); - * program.helpCommand('help [cmd]', 'show help'); - * program.helpCommand(false); // suppress default help command - * program.helpCommand(true); // add help command even if no subcommands - * - * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added - * @param {string} [description] - custom description - * @return {Command} `this` command for chaining - */ +"use strict"; - helpCommand(enableOrNameAndArgs, description) { - if (typeof enableOrNameAndArgs === 'boolean') { - this._addImplicitHelpCommand = enableOrNameAndArgs; - return this; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueUseCase = void 0; +const logger_1 = __nccwpck_require__(8836); +const check_permissions_use_case_1 = __nccwpck_require__(8749); +const update_title_use_case_1 = __nccwpck_require__(5107); +const assign_members_to_issue_use_case_1 = __nccwpck_require__(3115); +const check_priority_issue_size_use_case_1 = __nccwpck_require__(151); +const close_not_allowed_issue_use_case_1 = __nccwpck_require__(7826); +const label_deploy_added_use_case_1 = __nccwpck_require__(5678); +const label_deployed_added_use_case_1 = __nccwpck_require__(8388); +const link_issue_project_use_case_1 = __nccwpck_require__(7528); +const prepare_branches_use_case_1 = __nccwpck_require__(4423); +const remove_issue_branches_use_case_1 = __nccwpck_require__(2354); +const remove_not_needed_branches_use_case_1 = __nccwpck_require__(773); +const update_issue_type_use_case_1 = __nccwpck_require__(1652); +class IssueUseCase { + constructor() { + this.taskId = 'IssueUseCase'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + const permissionResult = await new check_permissions_use_case_1.CheckPermissionsUseCase().invoke(param); + const lastAction = permissionResult[permissionResult.length - 1]; + if (!lastAction.success && lastAction.executed) { + results.push(...permissionResult); + results.push(...await new close_not_allowed_issue_use_case_1.CloseNotAllowedIssueUseCase().invoke(param)); + return results; + } + if (param.cleanIssueBranches) { + results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); + } + /** + * Assignees + */ + results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); + /** + * Update title + */ + results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); + /** + * Update issue type + */ + results.push(...await new update_issue_type_use_case_1.UpdateIssueTypeUseCase().invoke(param)); + /** + * Link issue to project + */ + results.push(...await new link_issue_project_use_case_1.LinkIssueProjectUseCase().invoke(param)); + /** + * Check priority issue size + */ + results.push(...await new check_priority_issue_size_use_case_1.CheckPriorityIssueSizeUseCase().invoke(param)); + /** + * Prepare branches + */ + if (param.isBranched) { + results.push(...await new prepare_branches_use_case_1.PrepareBranchesUseCase().invoke(param)); + } + else { + results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); + } + /** + * Remove unnecessary branches + */ + results.push(...await new remove_not_needed_branches_use_case_1.RemoveNotNeededBranchesUseCase().invoke(param)); + /** + * Check if deploy label was added + */ + results.push(...await new label_deploy_added_use_case_1.DeployAddedUseCase().invoke(param)); + /** + * Check if deployed label was added + */ + results.push(...await new label_deployed_added_use_case_1.DeployedAddedUseCase().invoke(param)); + return results; } +} +exports.IssueUseCase = IssueUseCase; - enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]'; - const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/); - const helpDescription = description ?? 'display help for command'; - const helpCommand = this.createCommand(helpName); - helpCommand.helpOption(false); - if (helpArgs) helpCommand.arguments(helpArgs); - if (helpDescription) helpCommand.description(helpDescription); +/***/ }), - this._addImplicitHelpCommand = true; - this._helpCommand = helpCommand; +/***/ 7883: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this; - } +"use strict"; - /** - * Add prepared custom help command. - * - * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()` - * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only - * @return {Command} `this` command for chaining - */ - addHelpCommand(helpCommand, deprecatedDescription) { - // If not passed an object, call through to helpCommand for backwards compatibility, - // as addHelpCommand was originally used like helpCommand is now. - if (typeof helpCommand !== 'object') { - this.helpCommand(helpCommand, deprecatedDescription); - return this; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullRequestReviewCommentUseCase = void 0; +const logger_1 = __nccwpck_require__(8836); +const check_pull_request_comment_language_use_case_1 = __nccwpck_require__(7112); +class PullRequestReviewCommentUseCase { + constructor() { + this.taskId = 'PullRequestReviewCommentUseCase'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + results.push(...await new check_pull_request_comment_language_use_case_1.CheckPullRequestCommentLanguageUseCase().invoke(param)); + return results; } +} +exports.PullRequestReviewCommentUseCase = PullRequestReviewCommentUseCase; - this._addImplicitHelpCommand = true; - this._helpCommand = helpCommand; - return this; - } - /** - * Lazy create help command. - * - * @return {(Command|null)} - * @package - */ - _getHelpCommand() { - const hasImplicitHelpCommand = - this._addImplicitHelpCommand ?? - (this.commands.length && - !this._actionHandler && - !this._findCommand('help')); +/***/ }), - if (hasImplicitHelpCommand) { - if (this._helpCommand === undefined) { - this.helpCommand(undefined, undefined); // use default name and description - } - return this._helpCommand; - } - return null; - } +/***/ 5041: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Add hook for life cycle event. - * - * @param {string} event - * @param {Function} listener - * @return {Command} `this` command for chaining - */ +"use strict"; - hook(event, listener) { - const allowedValues = ['preSubcommand', 'preAction', 'postAction']; - if (!allowedValues.includes(event)) { - throw new Error(`Unexpected value for event passed to hook : '${event}'. -Expecting one of '${allowedValues.join("', '")}'`); - } - if (this._lifeCycleHooks[event]) { - this._lifeCycleHooks[event].push(listener); - } else { - this._lifeCycleHooks[event] = [listener]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullRequestUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +const update_title_use_case_1 = __nccwpck_require__(5107); +const assign_members_to_issue_use_case_1 = __nccwpck_require__(3115); +const assign_reviewers_to_issue_use_case_1 = __nccwpck_require__(6275); +const close_issue_after_merging_use_case_1 = __nccwpck_require__(5137); +const check_changes_pull_request_size_use_case_1 = __nccwpck_require__(8129); +const check_priority_pull_request_size_use_case_1 = __nccwpck_require__(7383); +const link_pull_request_issue_use_case_1 = __nccwpck_require__(2175); +const link_pull_request_project_use_case_1 = __nccwpck_require__(4311); +const update_pull_request_description_use_case_1 = __nccwpck_require__(158); +class PullRequestUseCase { + constructor() { + this.taskId = 'PullRequestUseCase'; } - return this; - } - - /** - * Register callback to use as replacement for calling process.exit. - * - * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing - * @return {Command} `this` command for chaining - */ - - exitOverride(fn) { - if (fn) { - this._exitCallback = fn; - } else { - this._exitCallback = (err) => { - if (err.code !== 'commander.executeSubCommandAsync') { - throw err; - } else { - // Async callback from spawn events, not useful to throw. + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + (0, logger_1.logDebugInfo)(`PR action ${param.pullRequest.action}`); + (0, logger_1.logDebugInfo)(`PR isOpened ${param.pullRequest.isOpened}`); + (0, logger_1.logDebugInfo)(`PR isMerged ${param.pullRequest.isMerged}`); + (0, logger_1.logDebugInfo)(`PR isClosed ${param.pullRequest.isClosed}`); + if (param.pullRequest.isOpened) { + /** + * Update title + */ + results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); + /** + * Assignees + */ + results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); + /** + * Reviewers + */ + results.push(...await new assign_reviewers_to_issue_use_case_1.AssignReviewersToIssueUseCase().invoke(param)); + /** + * Link Pull Request to projects + */ + results.push(...await new link_pull_request_project_use_case_1.LinkPullRequestProjectUseCase().invoke(param)); + /** + * Link Pull Request to issue + */ + results.push(...await new link_pull_request_issue_use_case_1.LinkPullRequestIssueUseCase().invoke(param)); + /** + * Check priority pull request size + */ + results.push(...await new check_priority_pull_request_size_use_case_1.CheckPriorityPullRequestSizeUseCase().invoke(param)); + /** + * Check changes size + */ + results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); + if (param.ai.getAiPullRequestDescription()) { + /** + * Update pull request description + */ + results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); + } + } + else if (param.pullRequest.isSynchronize) { + /** + * Check changes size + */ + results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); + /** + * Pushed changes to the pull request + */ + if (param.ai.getAiPullRequestDescription()) { + /** + * Update pull request description + */ + results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); + } + } + else if (param.pullRequest.isClosed && param.pullRequest.isMerged) { + /** + * Close issue if needed + */ + results.push(...await new close_issue_after_merging_use_case_1.CloseIssueAfterMergingUseCase().invoke(param)); + } + } + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error linking projects/issues with pull request.`, + ], + error: error, + })); } - }; - } - return this; - } - - /** - * Call process.exit, and _exitCallback if defined. - * - * @param {number} exitCode exit code for using with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - * @return never - * @private - */ - - _exit(exitCode, code, message) { - if (this._exitCallback) { - this._exitCallback(new CommanderError(exitCode, code, message)); - // Expecting this line is not reached. + return results; } - process.exit(exitCode); - } - - /** - * Register callback `fn` for the command. - * - * @example - * program - * .command('serve') - * .description('start service') - * .action(function() { - * // do work here - * }); - * - * @param {Function} fn - * @return {Command} `this` command for chaining - */ - - action(fn) { - const listener = (args) => { - // The .action callback takes an extra parameter which is the command or options. - const expectedArgsCount = this.registeredArguments.length; - const actionArgs = args.slice(0, expectedArgsCount); - if (this._storeOptionsAsProperties) { - actionArgs[expectedArgsCount] = this; // backwards compatible "options" - } else { - actionArgs[expectedArgsCount] = this.opts(); - } - actionArgs.push(this); +} +exports.PullRequestUseCase = PullRequestUseCase; - return fn.apply(this, actionArgs); - }; - this._actionHandler = listener; - return this; - } - /** - * Factory routine to create a new unattached option. - * - * See .option() for creating an attached option, which uses this routine to - * create the option. You can override createOption to return a custom option. - * - * @param {string} flags - * @param {string} [description] - * @return {Option} new option - */ +/***/ }), - createOption(flags, description) { - return new Option(flags, description); - } +/***/ 6479: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Wrap parseArgs to catch 'commander.invalidArgument'. - * - * @param {(Option | Argument)} target - * @param {string} value - * @param {*} previous - * @param {string} invalidArgumentMessage - * @private - */ +"use strict"; - _callParseArg(target, value, previous, invalidArgumentMessage) { - try { - return target.parseArg(value, previous); - } catch (err) { - if (err.code === 'commander.invalidArgument') { - const message = `${invalidArgumentMessage} ${err.message}`; - this.error(message, { exitCode: err.exitCode, code: err.code }); - } - throw err; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SingleActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +const deployed_action_use_case_1 = __nccwpck_require__(8293); +const vector_action_use_case_1 = __nccwpck_require__(7757); +const publish_github_action_use_case_1 = __nccwpck_require__(9029); +const create_release_use_case_1 = __nccwpck_require__(2430); +const create_tag_use_case_1 = __nccwpck_require__(5279); +const think_use_case_1 = __nccwpck_require__(3841); +class SingleActionUseCase { + constructor() { + this.taskId = 'SingleActionUseCase'; } - } - - /** - * Check for option flag conflicts. - * Register option if no conflicts found, or throw on conflict. - * - * @param {Option} option - * @private - */ - - _registerOption(option) { - const matchingOption = - (option.short && this._findOption(option.short)) || - (option.long && this._findOption(option.long)); - if (matchingOption) { - const matchingFlag = - option.long && this._findOption(option.long) - ? option.long - : option.short; - throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}' -- already used by option '${matchingOption.flags}'`); + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + if (!param.singleAction.validSingleAction) { + (0, logger_1.logDebugInfo)(`Not a valid single action: ${param.singleAction.currentSingleAction}`); + return results; + } + if (param.singleAction.isAiCacheAction) { + results.push(...await new vector_action_use_case_1.VectorActionUseCase().invoke(param)); + } + else if (param.singleAction.isDeployedAction) { + results.push(...await new deployed_action_use_case_1.DeployedActionUseCase().invoke(param)); + } + else if (param.singleAction.isPublishGithubAction) { + results.push(...await new publish_github_action_use_case_1.PublishGithubActionUseCase().invoke(param)); + } + else if (param.singleAction.isCreateReleaseAction) { + results.push(...await new create_release_use_case_1.CreateReleaseUseCase().invoke(param)); + } + else if (param.singleAction.isCreateTagAction) { + results.push(...await new create_tag_use_case_1.CreateTagUseCase().invoke(param)); + } + else if (param.singleAction.isThinkAction) { + results.push(...await new think_use_case_1.ThinkUseCase().invoke(param)); + } + } + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error executing single action: ${param.singleAction.currentSingleAction}.`, + ], + error: error, + })); + } + return results; } +} +exports.SingleActionUseCase = SingleActionUseCase; - this.options.push(option); - } - - /** - * Check for command name and alias conflicts with existing commands. - * Register command if no conflicts found, or throw on conflict. - * - * @param {Command} command - * @private - */ - - _registerCommand(command) { - const knownBy = (cmd) => { - return [cmd.name()].concat(cmd.aliases()); - }; - - const alreadyUsed = knownBy(command).find((name) => - this._findCommand(name), - ); - if (alreadyUsed) { - const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|'); - const newCmd = knownBy(command).join('|'); - throw new Error( - `cannot add command '${newCmd}' as already have command '${existingCmd}'`, - ); - } - this.commands.push(command); - } +/***/ }), - /** - * Add an option. - * - * @param {Option} option - * @return {Command} `this` command for chaining - */ - addOption(option) { - this._registerOption(option); +/***/ 5863: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const oname = option.name(); - const name = option.attributeName(); +"use strict"; - // store default value - if (option.negate) { - // --no-foo is special and defaults foo to true, unless a --foo option is already defined - const positiveLongFlag = option.long.replace(/^--no-/, '--'); - if (!this._findOption(positiveLongFlag)) { - this.setOptionValueWithSource( - name, - option.defaultValue === undefined ? true : option.defaultValue, - 'default', - ); - } - } else if (option.defaultValue !== undefined) { - this.setOptionValueWithSource(name, option.defaultValue, 'default'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckChangesIssueSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckChangesIssueSizeUseCase { + constructor() { + this.taskId = 'CheckChangesIssueSizeUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.currentConfiguration.parentBranch === undefined) { + (0, logger_1.logDebugInfo)(`Parent branch is undefined.`); + return result; + } + const headBranch = param.commit.branch; + const baseBranch = param.currentConfiguration.parentBranch; + const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, headBranch, baseBranch, param.sizeThresholds, param.labels, param.tokens.token); + (0, logger_1.logDebugInfo)(`Size: ${size}`); + (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); + (0, logger_1.logDebugInfo)(`Reason: ${reason}`); + (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnIssue}`); + if (param.labels.sizedLabelOnIssue !== size) { + const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); + labelNames.push(size); + await this.issueRepository.setLabels(param.owner, param.repo, param.issueNumber, labelNames, param.tokens.token); + for (const project of param.project.getProjects()) { + await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.issueNumber, githubSize, param.tokens.token); + } + (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.issueNumber}:`); + (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `${reason}, so the issue was resized to ${size}.`, + ], + })); + } + else { + (0, logger_1.logDebugInfo)(`The issue is already at the correct size.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the size of the changes, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } +} +exports.CheckChangesIssueSizeUseCase = CheckChangesIssueSizeUseCase; - // handler for cli and env supplied values - const handleOptionValue = (val, invalidValueMessage, valueSource) => { - // val is null for optional option used without an optional-argument. - // val is undefined for boolean and negated option. - if (val == null && option.presetArg !== undefined) { - val = option.presetArg; - } - // custom processing - const oldValue = this.getOptionValue(name); - if (val !== null && option.parseArg) { - val = this._callParseArg(option, val, oldValue, invalidValueMessage); - } else if (val !== null && option.variadic) { - val = option._concatValue(val, oldValue); - } +/***/ }), - // Fill-in appropriate missing values. Long winded but easy to follow. - if (val == null) { - if (option.negate) { - val = false; - } else if (option.isBoolean() || option.optional) { - val = true; - } else { - val = ''; // not normal, parseArg might have failed or be a mock function for testing - } - } - this.setOptionValueWithSource(name, val, valueSource); - }; +/***/ 8020: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.on('option:' + oname, (val) => { - const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`; - handleOptionValue(val, invalidValueMessage, 'cli'); - }); +"use strict"; - if (option.envVar) { - this.on('optionEnv:' + oname, (val) => { - const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`; - handleOptionValue(val, invalidValueMessage, 'env'); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NotifyNewCommitOnIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const list_utils_1 = __nccwpck_require__(4990); +const logger_1 = __nccwpck_require__(8836); +const execute_script_use_case_1 = __nccwpck_require__(155); +class NotifyNewCommitOnIssueUseCase { + constructor() { + this.taskId = 'NotifyNewCommitOnIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.mergeBranchPattern = 'Merge branch '; + this.ghAction = 'gh-action: '; + this.separator = '------------------------------------------------------'; } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const branchName = param.commit.branch; + let commitPrefix = ''; + if (param.commitPrefixBuilder.length > 0) { + param.commitPrefixBuilderParams = { + branchName: branchName, + }; + const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); + const prefixResult = await executor.invoke(param); + commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; + (0, logger_1.logDebugInfo)(`Commit prefix: ${commitPrefix}`); + } + let title = ''; + let image = ''; + if (param.release.active) { + title = 'šŸš€ Release News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitReleaseGifs); + } + else if (param.hotfix.active) { + title = 'šŸ”„šŸ› Hotfix News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitHotfixGifs); + } + else if (param.isBugfix) { + title = 'šŸ› Bugfix News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitBugfixGifs); + } + else if (param.isFeature) { + title = '✨ Feature News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitFeatureGifs); + } + else if (param.isDocs) { + title = 'šŸ“ Documentation News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitDocsGifs); + } + else if (param.isChore) { + title = 'šŸ”§ Chore News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitChoreGifs); + } + else { + title = 'šŸŖ„ Automatic News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitAutomaticActions); + } + let commentBody = ` +# ${title} - return this; - } +**Changes on branch \`${param.commit.branch}\`:** - /** - * Internal implementation shared by .option() and .requiredOption() - * - * @return {Command} `this` command for chaining - * @private - */ - _optionEx(config, flags, description, fn, defaultValue) { - if (typeof flags === 'object' && flags instanceof Option) { - throw new Error( - 'To add an Option object use addOption() instead of option() or requiredOption()', - ); - } - const option = this.createOption(flags, description); - option.makeOptionMandatory(!!config.mandatory); - if (typeof fn === 'function') { - option.default(defaultValue).argParser(fn); - } else if (fn instanceof RegExp) { - // deprecated - const regex = fn; - fn = (val, def) => { - const m = regex.exec(val); - return m ? m[0] : def; - }; - option.default(defaultValue).argParser(fn); - } else { - option.default(fn); - } +`; + let shouldWarn = false; + for (const commit of param.commit.commits) { + commentBody += ` +${this.separator} - return this.addOption(option); - } +- ${commit.id} by **${commit.author.name}** (@${commit.author.username}) +\`\`\` +${commit.message.replaceAll(`${commitPrefix}: `, '')} +\`\`\` - /** - * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. - * - * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required - * option-argument is indicated by `<>` and an optional option-argument by `[]`. - * - * See the README for more details, and see also addOption() and requiredOption(). - * - * @example - * program - * .option('-p, --pepper', 'add pepper') - * .option('-p, --pizza-type ', 'type of pizza') // required option-argument - * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default - * .option('-t, --tip ', 'add tip to purchase cost', parseFloat) // custom parse function - * - * @param {string} flags - * @param {string} [description] - * @param {(Function|*)} [parseArg] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - */ +`; + if ((commit.message.indexOf(commitPrefix) !== 0 && commitPrefix.length > 0) + && commit.message.indexOf(this.mergeBranchPattern) !== 0 + && commit.message.indexOf(this.ghAction) !== 0) { + shouldWarn = true; + } + } + if (shouldWarn && commitPrefix.length > 0) { + commentBody += ` +${this.separator} +## āš ļø Attention - option(flags, description, parseArg, defaultValue) { - return this._optionEx({}, flags, description, parseArg, defaultValue); - } +One or more commits didn't start with the prefix **${commitPrefix}**. - /** - * Add a required option which must have a value after parsing. This usually means - * the option must be specified on the command line. (Otherwise the same as .option().) - * - * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. - * - * @param {string} flags - * @param {string} [description] - * @param {(Function|*)} [parseArg] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - */ +\`\`\` +${commitPrefix}: created hello-world app +\`\`\` +`; + } + if (image && param.images.imagesOnCommit) { + commentBody += ` +${this.separator} - requiredOption(flags, description, parseArg, defaultValue) { - return this._optionEx( - { mandatory: true }, - flags, - description, - parseArg, - defaultValue, - ); - } +![image](${image}) +`; + } + if (param.issue.reopenOnPush) { + const opened = await this.issueRepository.openIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (opened) { + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was re-opened after pushing new commits to the branch \`${branchName}\`.`, param.tokens.token); + } + } + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, commentBody, param.tokens.token); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to notify the new commit on the issue, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; + } +} +exports.NotifyNewCommitOnIssueUseCase = NotifyNewCommitOnIssueUseCase; - /** - * Alter parsing of short flags with optional values. - * - * @example - * // for `.option('-f,--flag [value]'): - * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour - * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` - * - * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag. - * @return {Command} `this` command for chaining - */ - combineFlagAndOptionalValue(combine = true) { - this._combineFlagAndOptionalValue = !!combine; - return this; - } - /** - * Allow unknown options on the command line. - * - * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options. - * @return {Command} `this` command for chaining - */ - allowUnknownOption(allowUnknown = true) { - this._allowUnknownOption = !!allowUnknown; - return this; - } +/***/ }), - /** - * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. - * - * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments. - * @return {Command} `this` command for chaining - */ - allowExcessArguments(allowExcess = true) { - this._allowExcessArguments = !!allowExcess; - return this; - } +/***/ 8749: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Enable positional options. Positional means global options are specified before subcommands which lets - * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. - * The default behaviour is non-positional and global options may appear anywhere on the command line. - * - * @param {boolean} [positional] - * @return {Command} `this` command for chaining - */ - enablePositionalOptions(positional = true) { - this._enablePositionalOptions = !!positional; - return this; - } +"use strict"; - /** - * Pass through options that come after command-arguments rather than treat them as command-options, - * so actual command-options come before command-arguments. Turning this on for a subcommand requires - * positional options to have been enabled on the program (parent commands). - * The default behaviour is non-positional and options may appear before or after command-arguments. - * - * @param {boolean} [passThrough] for unknown options. - * @return {Command} `this` command for chaining - */ - passThroughOptions(passThrough = true) { - this._passThroughOptions = !!passThrough; - this._checkForBrokenPassThrough(); - return this; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPermissionsUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckPermissionsUseCase { + constructor() { + this.taskId = 'CheckPermissionsUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + /** + * If a release/hotfix issue was opened, check if author is a member of the project. + */ + if (param.isIssue && !param.issue.opened) { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue state is not 'opened'.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + else if (param.isPullRequest && !param.pullRequest.opened) { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Pull request state is not 'opened'.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + try { + const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); + const creator = param.isIssue ? param.issue.creator : param.pullRequest.creator; + const creatorIsTeamMember = creator.length > 0 + && currentProjectMembers.indexOf(creator) > -1; + if (param.labels.isMandatoryBranchedLabel) { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); + if (creatorIsTeamMember) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`@${param.issue.creator} was not authorized to create **[${param.labels.currentIssueLabels.join(',')}]** issues.`], + })); + } + } + else { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; + } +} +exports.CheckPermissionsUseCase = CheckPermissionsUseCase; - /** - * @private - */ - _checkForBrokenPassThrough() { - if ( - this.parent && - this._passThroughOptions && - !this.parent._enablePositionalOptions - ) { - throw new Error( - `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`, - ); - } - } +/***/ }), - /** - * Whether to store option values as properties on command object, - * or store separately (specify false). In both cases the option values can be accessed using .opts(). - * - * @param {boolean} [storeAsProperties=true] - * @return {Command} `this` command for chaining - */ +/***/ 155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - storeOptionsAsProperties(storeAsProperties = true) { - if (this.options.length) { - throw new Error('call .storeOptionsAsProperties() before adding options'); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommitPrefixBuilderUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +class CommitPrefixBuilderUseCase { + constructor() { + this.taskId = 'CommitPrefixBuilderUseCase'; } - if (Object.keys(this._optionValues).length) { - throw new Error( - 'call .storeOptionsAsProperties() before setting option values', - ); + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const branchName = param.commitPrefixBuilderParams.branchName; + const transforms = param.commitPrefixBuilder; // Now it's a list of transforms + const commitPrefix = this.applyTransforms(branchName, transforms); + (0, logger_1.logDebugInfo)(`Commit prefix generated: ${commitPrefix}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [], + payload: { + scriptResult: commitPrefix + } + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [], + error: error, + })); + } + return result; } - this._storeOptionsAsProperties = !!storeAsProperties; - return this; - } - - /** - * Retrieve option value. - * - * @param {string} key - * @return {object} value - */ - - getOptionValue(key) { - if (this._storeOptionsAsProperties) { - return this[key]; + applyTransforms(branchName, transforms) { + // Parse the list of transformations + const transformList = transforms.split(',').map(t => t.trim()); + let result = branchName; + // Apply each transformation sequentially + for (const transform of transformList) { + result = this.applyTransform(result, transform); + } + return result; } - return this._optionValues[key]; - } + applyTransform(input, transform) { + switch (transform) { + case "replace-slash": + return input.replace("/", "-"); + case "replace-all": + return input.replace(/[^a-zA-Z0-9-]/g, "-"); + case "lowercase": + return input.toLowerCase(); + case "uppercase": + return input.toUpperCase(); + case "kebab-case": + return input + .replace(/[^a-zA-Z0-9-]/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, "") + .toLowerCase(); + case "snake-case": + return input + .replace(/[^a-zA-Z0-9-]/g, "_") + .replace(/_+/g, "_") + .replace(/^_|_$/g, "") + .toLowerCase(); + case "camel-case": + return input + .replace(/[^a-zA-Z0-9-]/g, "-") + .split("-") + .map((word, index) => index === 0 ? word.toLowerCase() : + word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) + .join(""); + case "trim": + return input.trim(); + case "remove-numbers": + return input.replace(/\d+/g, ""); + case "remove-special": + return input.replace(/[^a-zA-Z0-9]/g, ""); + case "remove-spaces": + return input.replace(/\s+/g, ""); + case "remove-dashes": + return input.replace(/-+/g, ""); + case "remove-underscores": + return input.replace(/_+/g, ""); + case "clean-dashes": + return input.replace(/-+/g, "-").replace(/^-|-$/g, ""); + case "clean-underscores": + return input.replace(/_+/g, "_").replace(/^_|_$/g, ""); + case "prefix": + return `prefix-${input}`; + case "suffix": + return `${input}-suffix`; + default: + // If not recognized, return without changes + (0, logger_1.logDebugInfo)(`Unknown transform: ${transform}, skipping...`); + return input; + } + } +} +exports.CommitPrefixBuilderUseCase = CommitPrefixBuilderUseCase; - /** - * Store option value. - * - * @param {string} key - * @param {object} value - * @return {Command} `this` command for chaining - */ - setOptionValue(key, value) { - return this.setOptionValueWithSource(key, value, undefined); - } +/***/ }), - /** - * Store option value and where the value came from. - * - * @param {string} key - * @param {object} value - * @param {string} source - expected values are default/config/env/cli/implied - * @return {Command} `this` command for chaining - */ +/***/ 8243: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - setOptionValueWithSource(key, value, source) { - if (this._storeOptionsAsProperties) { - this[key] = value; - } else { - this._optionValues[key] = value; - } - this._optionValueSources[key] = source; - return this; - } +"use strict"; - /** - * Get source of option value. - * Expected values are default | config | env | cli | implied - * - * @param {string} key - * @return {string} - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetHotfixVersionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class GetHotfixVersionUseCase { + constructor() { + this.taskId = 'GetHotfixVersionUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + let number = -1; + if (param.isSingleAction) { + number = param.singleAction.issue; + } + else if (param.isIssue) { + number = param.issue.number; + } + else if (param.isPullRequest) { + number = param.pullRequest.number; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem identifying the issue.`], + })); + return result; + } + const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); + if (description === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem getting the description.`], + })); + return result; + } + const baseVersion = (0, content_utils_1.extractVersion)('Base Version', description); + const hotfixVersion = (0, content_utils_1.extractVersion)('Hotfix Version', description); + if (baseVersion === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the base version but there was a problem identifying the version.`], + })); + return result; + } + else if (hotfixVersion === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the hotfix version but there was a problem identifying the version.`], + })); + return result; + } + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + payload: { + baseVersion: baseVersion, + hotfixVersion: hotfixVersion, + } + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; + } +} +exports.GetHotfixVersionUseCase = GetHotfixVersionUseCase; - getOptionValueSource(key) { - return this._optionValueSources[key]; - } - /** - * Get source of option value. See also .optsWithGlobals(). - * Expected values are default | config | env | cli | implied - * - * @param {string} key - * @return {string} - */ +/***/ }), - getOptionValueSourceWithGlobals(key) { - // global overwrites local, like optsWithGlobals - let source; - this._getCommandAndAncestors().forEach((cmd) => { - if (cmd.getOptionValueSource(key) !== undefined) { - source = cmd.getOptionValueSource(key); - } - }); - return source; - } +/***/ 5966: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Get user arguments from implied or explicit arguments. - * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. - * - * @private - */ +"use strict"; - _prepareUserArgs(argv, parseOptions) { - if (argv !== undefined && !Array.isArray(argv)) { - throw new Error('first parameter to parse must be array or undefined'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetReleaseTypeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class GetReleaseTypeUseCase { + constructor() { + this.taskId = 'GetReleaseTypeUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + let number = -1; + if (param.isSingleAction) { + number = param.singleAction.issue; + } + else if (param.isIssue) { + number = param.issue.number; + } + else if (param.isPullRequest) { + number = param.pullRequest.number; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the release type but there was a problem identifying the issue.`], + })); + return result; + } + const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); + if (description === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the release type but there was a problem getting the description.`], + })); + return result; + } + const releaseType = (0, content_utils_1.extractReleaseType)('Release Type', description); + if (releaseType === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the release type but there was a problem identifying the type.`], + })); + return result; + } + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + payload: { + releaseType: releaseType, + } + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; } - parseOptions = parseOptions || {}; +} +exports.GetReleaseTypeUseCase = GetReleaseTypeUseCase; - // auto-detect argument conventions if nothing supplied - if (argv === undefined && parseOptions.from === undefined) { - if (process.versions?.electron) { - parseOptions.from = 'electron'; - } - // check node specific options for scenarios where user CLI args follow executable without scriptname - const execArgv = process.execArgv ?? []; - if ( - execArgv.includes('-e') || - execArgv.includes('--eval') || - execArgv.includes('-p') || - execArgv.includes('--print') - ) { - parseOptions.from = 'eval'; // internal usage, not documented - } - } - // default to using process.argv - if (argv === undefined) { - argv = process.argv; - } - this.rawArgs = argv.slice(); +/***/ }), - // extract the user args and scriptPath - let userArgs; - switch (parseOptions.from) { - case undefined: - case 'node': - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - break; - case 'electron': - // @ts-ignore: because defaultApp is an unknown property - if (process.defaultApp) { - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - } else { - userArgs = argv.slice(1); +/***/ 3827: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetReleaseVersionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class GetReleaseVersionUseCase { + constructor() { + this.taskId = 'GetReleaseVersionUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + let number = -1; + if (param.isSingleAction) { + number = param.singleAction.issue; + } + else if (param.isIssue) { + number = param.issue.number; + } + else if (param.isPullRequest) { + number = param.pullRequest.number; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem identifying the issue.`], + })); + return result; + } + const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); + if (description === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem getting the description.`], + })); + return result; + } + const releaseVersion = (0, content_utils_1.extractVersion)('Release Version', description); + if (releaseVersion === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + })); + return result; + } + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + payload: { + releaseVersion: releaseVersion, + } + })); } - break; - case 'user': - userArgs = argv.slice(0); - break; - case 'eval': - userArgs = argv.slice(1); - break; - default: - throw new Error( - `unexpected parse option { from: '${parseOptions.from}' }`, - ); + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; } +} +exports.GetReleaseVersionUseCase = GetReleaseVersionUseCase; - // Find default name for program from arguments. - if (!this._name && this._scriptPath) - this.nameFromFilename(this._scriptPath); - this._name = this._name || 'program'; - - return userArgs; - } - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * Use parseAsync instead of parse if any of your action handlers are async. - * - * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! - * - * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: - * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that - * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged - * - `'user'`: just user arguments - * - * @example - * program.parse(); // parse process.argv and auto-detect electron and special node flags - * program.parse(process.argv); // assume argv[0] is app and argv[1] is script - * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - optional, defaults to process.argv - * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron - * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' - * @return {Command} `this` command for chaining - */ +/***/ }), - parse(argv, parseOptions) { - const userArgs = this._prepareUserArgs(argv, parseOptions); - this._parseCommand([], userArgs); +/***/ 678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this; - } +"use strict"; - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! - * - * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: - * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that - * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged - * - `'user'`: just user arguments - * - * @example - * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags - * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script - * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - * @param {object} [parseOptions] - * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' - * @return {Promise} - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CodebaseAnalyzer = void 0; +const logger_1 = __nccwpck_require__(8836); +const constants_1 = __nccwpck_require__(8593); +/** + * Service for analyzing codebase structure and generating file descriptions + */ +class CodebaseAnalyzer { + constructor(aiRepository, fileImportAnalyzer, fileCacheManager) { + this.aiRepository = aiRepository; + this.fileImportAnalyzer = fileImportAnalyzer; + this.fileCacheManager = fileCacheManager; + } + /** + * Generate codebase analysis with file descriptions and relationships + * This runs before the main reasoning loop to provide context + * Uses relationship map built from imports + AI descriptions in batches + */ + async generateCodebaseAnalysis(param, repositoryFiles, question) { + try { + // Filter relevant files (code files, not config/docs) + const codeExtensions = ['.ts', '.tsx', '.js', '.jsx', '.py', '.java', '.kt', '.go', '.rs', '.rb', '.php', '.swift', '.dart']; + const relevantFiles = Array.from(repositoryFiles.entries()) + .filter(([path]) => { + const ext = path.split('.').pop()?.toLowerCase() || ''; + return codeExtensions.includes(`.${ext}`) || + path.includes('/src/') || + path.includes('/lib/') || + path.includes('/usecase/') || + path.includes('/repository/'); + }); + if (relevantFiles.length === 0) { + (0, logger_1.logInfo)(`āš ļø No relevant code files found for analysis`); + return []; + } + (0, logger_1.logInfo)(`šŸ” Analyzing ${relevantFiles.length} relevant files for structure and relationships...`); + // STEP 0: Load cache from Supabase + const cache = await this.fileCacheManager.loadAICache(param); + // STEP 1: Build relationship map from imports (in memory, no AI needed) + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumesMap = relationshipMaps.consumes; + const consumedByMap = relationshipMaps.consumedBy; + // STEP 2: Identify files that need AI analysis (not in cache or SHA changed) + const filesNeedingAnalysis = []; + const cachedAnalyses = []; + let cacheMissReasons = { + notInCache: 0, + shaMismatch: 0 + }; + // Track files that should be in cache but aren't + const missingFromCache = []; + for (const [filePath, content] of relevantFiles) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const cached = this.fileCacheManager.getCachedFile(cache, filePath); + if (!cached) { + cacheMissReasons.notInCache++; + missingFromCache.push(filePath); + (0, logger_1.logDebugInfo)(`āŒ Cache miss for ${filePath} (not in cache)`); + filesNeedingAnalysis.push([filePath, content]); + } + else if (cached.sha !== currentSHA) { + cacheMissReasons.shaMismatch++; + (0, logger_1.logDebugInfo)(`šŸ”„ SHA mismatch for ${filePath}: cached=${cached.sha.substring(0, 8)}..., current=${currentSHA.substring(0, 8)}...`); + filesNeedingAnalysis.push([filePath, content]); + } + else { + // Use cached data + const consumes = consumesMap.get(filePath) || []; + const consumedBy = consumedByMap.get(filePath) || []; + cachedAnalyses.push({ + path: filePath, + description: cached.description, + consumes: consumes, + consumed_by: consumedBy + }); + } + } + (0, logger_1.logInfo)(`šŸ“Š Cache hit: ${cachedAnalyses.length} files, Need analysis: ${filesNeedingAnalysis.length} files (not in cache: ${cacheMissReasons.notInCache}, SHA mismatch: ${cacheMissReasons.shaMismatch})`); + // Debug: Show detailed cache comparison + if (cacheMissReasons.notInCache > 0) { + if (cache.size > 0) { + const sampleCachePaths = Array.from(cache.keys()).slice(0, 10); + const sampleMissingPaths = missingFromCache.slice(0, 10); + (0, logger_1.logDebugInfo)(`šŸ” Cache contains ${cache.size} files. Sample cached paths: ${sampleCachePaths.join(', ')}`); + (0, logger_1.logDebugInfo)(`šŸ” Sample missing paths (${missingFromCache.length} total): ${sampleMissingPaths.join(', ')}`); + // Check if any missing paths are similar to cached paths (normalization issue) + for (const missingPath of sampleMissingPaths.slice(0, 3)) { + const normalizedMissing = missingPath.replace(/^\.\//, '').replace(/\\/g, '/'); + const foundSimilar = sampleCachePaths.find(cached => cached.includes(normalizedMissing) || normalizedMissing.includes(cached)); + if (foundSimilar) { + (0, logger_1.logDebugInfo)(`āš ļø Potential path mismatch: missing="${missingPath}" vs cached="${foundSimilar}"`); + } + } + } + else { + (0, logger_1.logDebugInfo)(`āš ļø Cache is empty! All ${relevantFiles.length} files need analysis.`); + } + } + // STEP 3: Process files needing analysis in batches with AI (only for descriptions) + // Relationships come from the map we built + const BATCH_SIZE = 20; // Process 20 files at a time + const allAnalyses = [...cachedAnalyses]; + // Create simplified schema for AI (only needs description, relationships come from map) + const FILE_DESCRIPTION_SCHEMA = { + "type": "array", + "description": "Array of file descriptions", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File path relative to repository root" + }, + "description": { + "type": "string", + "description": "Complete description of what the file does" + } + }, + "required": ["path", "description"], + "additionalProperties": false + } + }; + for (let i = 0; i < filesNeedingAnalysis.length; i += BATCH_SIZE) { + const batch = filesNeedingAnalysis.slice(i, i + BATCH_SIZE); + const batchNumber = Math.floor(i / BATCH_SIZE) + 1; + const totalBatches = Math.ceil(relevantFiles.length / BATCH_SIZE); + (0, logger_1.logInfo)(`šŸ“ Processing batch ${batchNumber}/${totalBatches} (${batch.length} files)...`); + // Prepare batch content + const batchFilesList = batch.map(([path]) => path).join('\n'); + const batchContent = batch.map(([path, content]) => `\n## ${path}\n\`\`\`\n${content}\n\`\`\``).join('\n'); + const batchPrompt = `# Codebase Structure Analysis - Batch ${batchNumber}/${totalBatches} - async parseAsync(argv, parseOptions) { - const userArgs = this._prepareUserArgs(argv, parseOptions); - await this._parseCommand([], userArgs); +You are analyzing a codebase to understand what each file does. - return this; - } +## User's Question: +${question} - /** - * Execute a sub-command executable. - * - * @private - */ +## Files to Analyze in this batch (${batch.length} files): +${batchFilesList} - _executeSubCommand(subcommand, args) { - args = args.slice(); - let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. - const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs']; +## File Contents: +${batchContent} - function findFile(baseDir, baseName) { - // Look for specified file - const localBin = path.resolve(baseDir, baseName); - if (fs.existsSync(localBin)) return localBin; +## Task: +For EACH of the ${batch.length} files listed above, - // Stop looking if candidate already has an expected extension. - if (sourceExt.includes(path.extname(baseName))) return undefined; +${constants_1.PROMPTS.CODE_BASE_ANALYSIS} - // Try all the extensions. - const foundExt = sourceExt.find((ext) => - fs.existsSync(`${localBin}${ext}`), - ); - if (foundExt) return `${localBin}${foundExt}`; +Return a JSON array with this structure: +[ + { + "path": "src/path/to/file.ts", + "description": "description_here" + }, + ... +] - return undefined; +**REQUIREMENTS**: +- You MUST return a description for ALL ${batch.length} files in this batch`; + try { + const batchResponse = await this.aiRepository.askJson(param.ai, batchPrompt, FILE_DESCRIPTION_SCHEMA, "file_descriptions"); + if (batchResponse && Array.isArray(batchResponse)) { + // Merge AI descriptions with relationship map and update cache + for (const item of batchResponse) { + if (item && typeof item.path === 'string' && typeof item.description === 'string') { + const [filePath, content] = batch.find(([p]) => p === item.path) || [item.path, '']; + const currentSHA = filePath && content ? this.fileCacheManager.calculateFileSHA(content) : ''; + const consumes = consumesMap.get(item.path) || []; + const consumedBy = consumedByMap.get(item.path) || []; + allAnalyses.push({ + path: item.path, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }); + // Update cache + if (filePath && currentSHA) { + const cachedInfo = { + path: item.path, + sha: currentSHA, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(item.path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, item.path, cachedInfo, consumes, consumedBy); + } + } + } + (0, logger_1.logInfo)(`āœ… Processed batch ${batchNumber}/${totalBatches}: ${batchResponse.length} files`); + } + else { + (0, logger_1.logError)(`āš ļø Batch ${batchNumber} failed, using fallback descriptions`); + // Fallback for this batch + for (const [path, content] of batch) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const consumes = consumesMap.get(path) || []; + const consumedBy = consumedByMap.get(path) || []; + const fallbackDesc = this.generateBasicDescription(path); + allAnalyses.push({ + path, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }); + // Update cache with fallback + const cachedInfo = { + path, + sha: currentSHA, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, path, cachedInfo, consumes, consumedBy); + } + } + } + catch (error) { + (0, logger_1.logError)(`Error processing batch ${batchNumber}: ${error}`); + // Fallback for this batch + for (const [path, content] of batch) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const consumes = consumesMap.get(path) || []; + const consumedBy = consumedByMap.get(path) || []; + const fallbackDesc = this.generateBasicDescription(path); + allAnalyses.push({ + path, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }); + // Update cache with fallback + const cachedInfo = { + path, + sha: currentSHA, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, path, cachedInfo, consumes, consumedBy); + } + } + } + // STEP 4: Cache is saved incrementally during processing + // No need to save all at once since we're using Supabase + if (allAnalyses.length > 0) { + (0, logger_1.logInfo)(`āœ… Generated analysis for ${allAnalyses.length} files (${cachedAnalyses.length} from cache, ${filesNeedingAnalysis.length} from AI)`); + return allAnalyses; + } + // Fallback: Generate simple descriptions based on file paths and basic content + (0, logger_1.logInfo)(`āš ļø AI analysis failed, generating fallback descriptions...`); + const fallbackDescriptions = this.generateFallbackFileDescriptions(relevantFiles); + // Merge with relationship maps and update cache + const fallbackResults = await Promise.all(fallbackDescriptions.map(async (item) => { + const consumes = consumesMap.get(item.path) || []; + const consumedBy = consumedByMap.get(item.path) || []; + const content = repositoryFiles.get(item.path) || ''; + const currentSHA = content ? this.fileCacheManager.calculateFileSHA(content) : ''; + // Update cache + if (content && currentSHA) { + const cachedInfo = { + path: item.path, + sha: currentSHA, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(item.path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, item.path, cachedInfo, consumes, consumedBy); + } + return { + ...item, + consumes: consumes, + consumed_by: consumedBy + }; + })); + return fallbackResults; + } + catch (error) { + (0, logger_1.logError)(`Error generating codebase analysis: ${error}`); + // Fallback to simple path-based analysis + const relevantFiles = Array.from(repositoryFiles.entries()) + .filter(([path]) => path.includes('/src/') || path.includes('/lib/')); + const fallbackDescriptions = this.generateFallbackFileDescriptions(relevantFiles); + // Try to build relationship map even in fallback + try { + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumes = relationshipMaps.consumes; + const consumedBy = relationshipMaps.consumedBy; + return fallbackDescriptions.map(item => ({ + ...item, + consumes: consumes.get(item.path) || [], + consumed_by: consumedBy.get(item.path) || [] + })); + } + catch { + return fallbackDescriptions; + } + } } - - // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. - this._checkForMissingMandatoryOptions(); - this._checkForConflictingOptions(); - - // executableFile and executableDir might be full path, or just a name - let executableFile = - subcommand._executableFile || `${this._name}-${subcommand._name}`; - let executableDir = this._executableDir || ''; - if (this._scriptPath) { - let resolvedScriptPath; // resolve possible symlink for installed npm binary - try { - resolvedScriptPath = fs.realpathSync(this._scriptPath); - } catch (err) { - resolvedScriptPath = this._scriptPath; - } - executableDir = path.resolve( - path.dirname(resolvedScriptPath), - executableDir, - ); + /** + * Generate basic description from file path (fallback) + */ + generateBasicDescription(path) { + const pathParts = path.split('/'); + const fileName = pathParts[pathParts.length - 1]; + const dir = pathParts.slice(0, -1).join('/'); + if (path.includes('/usecase/')) { + return `Use case for ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles business logic and orchestrates operations.`; + } + else if (path.includes('/repository/')) { + return `Repository for ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles data access and external service interactions.`; + } + else if (path.includes('/model/')) { + return `Data model: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Defines data structures and interfaces.`; + } + else if (path.includes('/utils/')) { + return `Utility functions: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Provides helper functions and utilities.`; + } + else if (path.includes('/actions/')) { + return `Action handler: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles action execution and workflows.`; + } + else { + return `File: ${fileName}. Located in ${dir || 'root'}.`; + } } - - // Look for a local file in preference to a command in PATH. - if (executableDir) { - let localFile = findFile(executableDir, executableFile); - - // Legacy search using prefix of script name instead of command name - if (!localFile && !subcommand._executableFile && this._scriptPath) { - const legacyName = path.basename( - this._scriptPath, - path.extname(this._scriptPath), - ); - if (legacyName !== this._name) { - localFile = findFile( - executableDir, - `${legacyName}-${subcommand._name}`, - ); + /** + * Generate fallback file descriptions when AI analysis fails + */ + generateFallbackFileDescriptions(files) { + const descriptions = []; + for (const [path] of files) { + const description = this.generateBasicDescription(path); + descriptions.push({ + path, + description, + consumes: [], // Will be filled by relationship map + consumed_by: [] // Will be filled by relationship map + }); } - } - executableFile = localFile || executableFile; + return descriptions; } + /** + * Format codebase analysis for inclusion in AI context + */ + formatCodebaseAnalysisForContext(analysis) { + if (analysis.length === 0) { + return ''; + } + const formatted = []; + formatted.push(`## šŸ“‹ Codebase Analysis & File Relationships\n\n`); + formatted.push(`This analysis provides context about the codebase structure to help you make informed decisions about which files to examine.\n\n`); + formatted.push(`**Relationship Types:**\n`); + formatted.push(`- **Consumes**: Files that this file imports/depends on\n`); + formatted.push(`- **Consumed By**: Files that import/depend on this file\n\n`); + // Group by directory for better organization + const byDirectory = new Map(); + analysis.forEach(item => { + const dir = item.path.split('/').slice(0, -1).join('/') || 'root'; + if (!byDirectory.has(dir)) { + byDirectory.set(dir, []); + } + byDirectory.get(dir).push(item); + }); + // Sort directories for consistent output + const sortedDirs = Array.from(byDirectory.keys()).sort(); + for (const dir of sortedDirs) { + const files = byDirectory.get(dir); + formatted.push(`### ${dir || 'Root'}\n\n`); + for (const file of files) { + formatted.push(`- **\`${file.path}\`**: ${file.description}`); + if (file.consumes && file.consumes.length > 0) { + formatted.push(`\n - *Consumes*: ${file.consumes.slice(0, 5).map(r => `\`${r}\``).join(', ')}${file.consumes.length > 5 ? '...' : ''}`); + } + if (file.consumed_by && file.consumed_by.length > 0) { + formatted.push(`\n - *Consumed By*: ${file.consumed_by.slice(0, 5).map(r => `\`${r}\``).join(', ')}${file.consumed_by.length > 5 ? '...' : ''}`); + } + formatted.push(`\n`); + } + formatted.push(`\n`); + } + formatted.push(`\n**Use this analysis to understand the codebase structure and identify relevant files for the task.**\n\n`); + return formatted.join(''); + } +} +exports.CodebaseAnalyzer = CodebaseAnalyzer; - launchWithNode = sourceExt.includes(path.extname(executableFile)); - - let proc; - if (process.platform !== 'win32') { - if (launchWithNode) { - args.unshift(executableFile); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); - proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' }); - } else { - proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' }); - } - } else { - args.unshift(executableFile); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); - proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' }); - } +/***/ }), - if (!proc.killed) { - // testing mainly to avoid leak warnings during unit tests with mocked spawn - const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; - signals.forEach((signal) => { - process.on(signal, () => { - if (proc.killed === false && proc.exitCode === null) { - // @ts-ignore because signals not typed to known strings - proc.kill(signal); - } - }); - }); - } +/***/ 5788: +/***/ ((__unused_webpack_module, exports) => { - // By default terminate process when spawned process terminates. - const exitCallback = this._exitCallback; - proc.on('close', (code) => { - code = code ?? 1; // code is null if spawned process terminated due to a signal - if (!exitCallback) { - process.exit(code); - } else { - exitCallback( - new CommanderError( - code, - 'commander.executeSubCommandAsync', - '(close)', - ), - ); - } - }); - proc.on('error', (err) => { - // @ts-ignore: because err.code is an unknown property - if (err.code === 'ENOENT') { - const executableDirMessage = executableDir - ? `searched for local subcommand relative to directory '${executableDir}'` - : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory'; - const executableMissing = `'${executableFile}' does not exist - - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - - ${executableDirMessage}`; - throw new Error(executableMissing); - // @ts-ignore: because err.code is an unknown property - } else if (err.code === 'EACCES') { - throw new Error(`'${executableFile}' not executable`); - } - if (!exitCallback) { - process.exit(1); - } else { - const wrappedError = new CommanderError( - 1, - 'commander.executeSubCommandAsync', - '(error)', - ); - wrappedError.nestedError = err; - exitCallback(wrappedError); - } - }); +"use strict"; - // Store the reference to the child process - this.runningCommand = proc; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommentFormatter = void 0; +/** + * Service for formatting GitHub comments and code changes + */ +class CommentFormatter { + constructor() { + this.GITHUB_COMMENT_MAX_LENGTH = 65500; // Leave some margin below 65536 + } + /** + * Format the complete reasoning comment for GitHub + */ + formatReasoningComment(question, description, steps, analyzedFiles, proposedChanges, finalAnalysis, totalIterations, todoManager) { + let comment = ''; + // Header + comment += `# šŸ¤” AI Reasoning Analysis\n\n`; + if (question) { + comment += `## šŸ“ Question\n\n${question}\n\n`; + } + comment += `---\n\n`; + // MAIN CONTENT: Summary and conclusions + comment += `## šŸ“Š Analysis Summary\n\n`; + comment += `- **Total Iterations**: ${totalIterations}\n`; + comment += `- **Files Analyzed**: ${analyzedFiles.size}\n`; + comment += `- **Changes Proposed**: ${proposedChanges.length}\n`; + // TODO List Summary + const todoStats = todoManager.getStats(); + if (todoStats.total > 0) { + comment += `- **TODO Tasks**: ${todoStats.total} (${todoStats.completed} completed, ${todoStats.in_progress} in progress, ${todoStats.pending} pending)\n`; + } + comment += `\n---\n\n`; + // Final Analysis & Conclusions (main content) + if (finalAnalysis) { + comment += `## šŸŽÆ Final Analysis & Conclusions\n\n`; + comment += `${finalAnalysis}\n\n`; + comment += `---\n\n`; + } + else { + // Fallback summary if no final analysis + comment += `## šŸŽÆ Summary\n\n`; + comment += `Analysis completed after ${totalIterations} iterations. `; + comment += `Analyzed ${analyzedFiles.size} file${analyzedFiles.size !== 1 ? 's' : ''} and `; + comment += `proposed ${proposedChanges.length} change${proposedChanges.length !== 1 ? 's' : ''}.\n\n`; + comment += `---\n\n`; + } + // Proposed Changes (main content) + if (proposedChanges.length > 0) { + comment += `## šŸ’” Proposed Changes\n\n`; + proposedChanges.forEach((change, idx) => { + comment += this.formatProposedChange(change, idx + 1); + }); + comment += `\n---\n\n`; + } + else { + comment += `## šŸ’” Proposed Changes\n\n`; + comment += `No specific code changes were proposed. The analysis focused on understanding the codebase structure and requirements.\n\n`; + comment += `---\n\n`; + } + // Analyzed Files Summary (if relevant) + if (analyzedFiles.size > 0 && analyzedFiles.size <= 10) { + comment += `## šŸ“„ Analyzed Files\n\n`; + Array.from(analyzedFiles.values()).forEach(file => { + comment += `- **\`${file.path}\`** (${file.relevance} relevance): ${file.key_findings.substring(0, 200)}${file.key_findings.length > 200 ? '...' : ''}\n`; + }); + comment += `\n---\n\n`; + } + // TODO List Summary (if relevant) + if (todoStats.total > 0) { + comment += `## šŸ“‹ TODO List Summary\n\n`; + const completedTodos = todoManager.getTodosByStatus('completed'); + const activeTodos = todoManager.getActiveTodos(); + if (completedTodos.length > 0) { + comment += `### āœ… Completed Tasks\n\n`; + completedTodos.forEach(todo => { + comment += `- ${todo.content}\n`; + }); + comment += `\n`; + } + if (activeTodos.length > 0) { + comment += `### šŸ”„ Active/Pending Tasks\n\n`; + activeTodos.forEach(todo => { + comment += `- ${todo.status === 'in_progress' ? 'šŸ”„' : 'ā³'} ${todo.content}\n`; + }); + comment += `\n`; + } + comment += `---\n\n`; + } + // COLLAPSED SECTION: Detailed Reasoning Steps + comment += `
\nšŸ”„ Detailed Reasoning Steps (${steps.length} steps) - Click to expand\n\n`; + comment += `\n\n*This section contains the detailed step-by-step reasoning process. It's collapsed by default to keep the main analysis focused.*\n\n`; + comment += `---\n\n`; + let proposalIndex = 0; + const proposalShownFlags = new Set(); + for (const step of steps) { + comment += `### Step ${step.step_number}: ${this.getActionEmoji(step.action)} ${this.formatActionName(step.action)}\n\n`; + // Show reasoning (truncated for collapsed section) + if (step.reasoning) { + const reasoningText = step.reasoning.length > 500 + ? `${step.reasoning.substring(0, 500)}...` + : step.reasoning; + comment += `${reasoningText}\n\n`; + } + // Show files involved (simplified) + if (step.files_involved && step.files_involved.length > 0) { + const uniqueFiles = [...new Set(step.files_involved)]; + comment += `**Files**: ${uniqueFiles.map(f => `\`${f}\``).join(', ')}\n\n`; + } + // Show file analysis (simplified) + if (step.action === 'analyze_code' || step.action === 'read_file') { + const relevantFiles = Array.from(analyzedFiles.values()).filter(f => step.files_involved?.includes(f.path)); + const stepAnalysis = step.file_analysis_in_step; + const filesToShow = stepAnalysis || relevantFiles; + if (filesToShow.length > 0) { + comment += `**Analysis**: `; + filesToShow.forEach((file, idx) => { + if (idx > 0) + comment += ` | `; + comment += `\`${file.path}\` (${file.relevance}): ${file.key_findings.substring(0, 100)}${file.key_findings.length > 100 ? '...' : ''}`; + }); + comment += `\n\n`; + } + } + // Show proposals (simplified reference) + const stepProposals = step.proposals_in_step; + if (stepProposals && stepProposals.length > 0) { + comment += `**Proposed Changes**: ${stepProposals.map(c => `${c.change_type} \`${c.file_path}\``).join(', ')}\n\n`; + // Mark as shown + stepProposals.forEach((change) => { + const globalIndex = proposedChanges.indexOf(change); + if (globalIndex >= 0) { + proposalShownFlags.add(globalIndex); + } + }); + } + comment += `---\n\n`; + } + comment += `\n
\n\n`; + comment += `---\n\n`; + // Footer + comment += `*Analysis completed in ${totalIterations} iterations. Analyzed ${analyzedFiles.size} files and proposed ${proposedChanges.length} changes.*\n`; + // Truncate if too long + if (comment.length > this.GITHUB_COMMENT_MAX_LENGTH) { + // Try to keep main content, truncate collapsed section + const mainContent = comment.substring(0, comment.indexOf('
')); + const truncated = mainContent + `\n\n
\nšŸ”„ Detailed Reasoning Steps - Truncated due to length\n\n*Steps section was truncated due to comment length limits.*\n\n
\n\n`; + if (truncated.length > this.GITHUB_COMMENT_MAX_LENGTH) { + // If still too long, truncate main content + const finalTruncated = truncated.substring(0, this.GITHUB_COMMENT_MAX_LENGTH - 200); + return finalTruncated + `\n\n*[Comment truncated due to length limit]*\n`; + } + return truncated; + } + return comment; + } + /** + * Format a single proposed change + */ + formatProposedChange(change, index) { + let formatted = `### ${index}. ${this.getChangeTypeEmoji(change.change_type)} ${change.change_type.toUpperCase()}: \`${change.file_path}\`\n\n`; + formatted += `**Description**: ${change.description}\n\n`; + if (change.reasoning) { + formatted += `**Reasoning**: ${change.reasoning}\n\n`; + } + if (change.suggested_code) { + const language = this.detectLanguageFromPath(change.file_path); + formatted += `**Suggested Code**:\n\n`; + formatted += `\`\`\`${language}\n${change.suggested_code}\n\`\`\`\n\n`; + } + formatted += `---\n\n`; + return formatted; + } + /** + * Detect programming language from file path/extension + */ + detectLanguageFromPath(filePath) { + const extension = filePath.split('.').pop()?.toLowerCase() || ''; + const languageMap = { + // TypeScript/JavaScript + 'ts': 'typescript', + 'tsx': 'tsx', + 'js': 'javascript', + 'jsx': 'jsx', + 'mjs': 'javascript', + 'cjs': 'javascript', + // Python + 'py': 'python', + 'pyw': 'python', + 'pyi': 'python', + // Java/Kotlin + 'java': 'java', + 'kt': 'kotlin', + 'kts': 'kotlin', + // Go + 'go': 'go', + // Rust + 'rs': 'rust', + // C/C++ + 'c': 'c', + 'cpp': 'cpp', + 'cc': 'cpp', + 'cxx': 'cpp', + 'h': 'c', + 'hpp': 'cpp', + 'hxx': 'cpp', + // C# + 'cs': 'csharp', + // Ruby + 'rb': 'ruby', + // PHP + 'php': 'php', + // Swift + 'swift': 'swift', + // Dart + 'dart': 'dart', + // Shell + 'sh': 'bash', + 'bash': 'bash', + 'zsh': 'bash', + 'fish': 'fish', + // Configuration + 'json': 'json', + 'yaml': 'yaml', + 'yml': 'yaml', + 'toml': 'toml', + 'xml': 'xml', + 'ini': 'ini', + 'conf': 'conf', + 'config': 'conf', + // Markup + 'html': 'html', + 'htm': 'html', + 'css': 'css', + 'scss': 'scss', + 'sass': 'sass', + 'less': 'less', + 'md': 'markdown', + 'markdown': 'markdown', + // SQL + 'sql': 'sql', + // Docker + 'dockerfile': 'dockerfile', + 'docker': 'dockerfile', + // Other + 'txt': 'text', + 'log': 'text', + }; + // Check for exact match + if (languageMap[extension]) { + return languageMap[extension]; + } + // Check for Dockerfile (no extension) + if (filePath.toLowerCase().includes('dockerfile')) { + return 'dockerfile'; + } + // Default to empty string if unknown + return ''; + } + /** + * Get emoji for action type + */ + getActionEmoji(action) { + const emojiMap = { + 'search_files': 'šŸ”', + 'read_file': 'šŸ“–', + 'analyze_code': 'šŸ”¬', + 'propose_changes': 'šŸ’”', + 'complete': 'āœ…' + }; + return emojiMap[action] || 'šŸ“'; + } + /** + * Format action name for display + */ + formatActionName(action) { + const nameMap = { + 'search_files': 'Search Files', + 'read_file': 'Read Files', + 'analyze_code': 'Analyze Code', + 'propose_changes': 'Propose Changes', + 'complete': 'Complete' + }; + return nameMap[action] || action; + } + /** + * Get emoji for change type + */ + getChangeTypeEmoji(changeType) { + const emojiMap = { + 'create': '✨', + 'modify': 'šŸ“', + 'delete': 'šŸ—‘ļø', + 'refactor': 'ā™»ļø' + }; + return emojiMap[changeType] || 'šŸ“'; + } +} +exports.CommentFormatter = CommentFormatter; - /** - * @private - */ - _dispatchSubcommand(commandName, operands, unknown) { - const subCommand = this._findCommand(commandName); - if (!subCommand) this.help({ error: true }); +/***/ }), - let promiseChain; - promiseChain = this._chainOrCallSubCommandHook( - promiseChain, - subCommand, - 'preSubcommand', - ); - promiseChain = this._chainOrCall(promiseChain, () => { - if (subCommand._executableHandler) { - this._executeSubCommand(subCommand, operands.concat(unknown)); - } else { - return subCommand._parseCommand(operands, unknown); - } - }); - return promiseChain; - } +/***/ 1855: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Invoke help directly if possible, or dispatch if necessary. - * e.g. help foo - * - * @private - */ +"use strict"; - _dispatchHelpCommand(subcommandName) { - if (!subcommandName) { - this.help(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileCacheManager = void 0; +const supabase_repository_1 = __nccwpck_require__(9829); +const logger_1 = __nccwpck_require__(8836); +const crypto_1 = __nccwpck_require__(6113); +/** + * Service for managing AI file cache in Supabase + */ +class FileCacheManager { + constructor() { + this.supabaseRepository = null; + } + /** + * Normalize file path for consistent comparison + * Removes leading ./ and normalizes path separators + */ + normalizePath(path) { + return path + .replace(/^\.\//, '') // Remove leading ./ + .replace(/\\/g, '/') // Normalize separators + .trim(); + } + /** + * Calculate SHA256 hash of file content + */ + calculateFileSHA(content) { + return (0, crypto_1.createHash)('sha256').update(content).digest('hex'); + } + /** + * Initialize Supabase repository if config is available + */ + initSupabaseRepository(param) { + if (!this.supabaseRepository && param.supabaseConfig) { + this.supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + } + return this.supabaseRepository; + } + /** + * Load cache from Supabase (or return empty map if Supabase not available) + * Uses normalized paths for consistent lookup + */ + async loadAICache(param) { + this.initSupabaseRepository(param); + const cache = new Map(); + if (!this.supabaseRepository) { + (0, logger_1.logInfo)(`šŸ“‚ Supabase not configured, starting with empty cache`); + return cache; + } + try { + const branch = param.commit.branch || param.branches.main; + const cachedFiles = await this.supabaseRepository.getAIFileCachesByBranch(param.owner, param.repo, branch); + for (const file of cachedFiles) { + const normalizedPath = this.normalizePath(file.path); + cache.set(normalizedPath, { + path: normalizedPath, + sha: file.sha, + description: file.description, + consumes: (file.consumes || []).map(p => this.normalizePath(p)), + consumed_by: (file.consumed_by || []).map(p => this.normalizePath(p)) + }); + } + (0, logger_1.logInfo)(`šŸ“‚ Loaded ${cache.size} files from Supabase cache`); + if (cachedFiles.length > 0) { + (0, logger_1.logDebugInfo)(`šŸ“‚ Sample cached paths: ${Array.from(cache.keys()).slice(0, 5).join(', ')}`); + } + } + catch (error) { + (0, logger_1.logError)(`Error loading AI cache from Supabase: ${error}`); + } + return cache; + } + /** + * Get cached file info by path (with path normalization) + */ + getCachedFile(cache, filePath) { + const normalizedPath = this.normalizePath(filePath); + return cache.get(normalizedPath); } - const subCommand = this._findCommand(subcommandName); - if (subCommand && !subCommand._executableHandler) { - subCommand.help(); + /** + * Save cache entry to Supabase + * Normalizes paths before saving + */ + async saveAICacheEntry(param, filePath, fileInfo, consumes, consumedBy) { + this.initSupabaseRepository(param); + if (!this.supabaseRepository) { + return; // Silently skip if Supabase not available + } + try { + const branch = param.commit.branch || param.branches.main; + const fileName = filePath.split('/').pop() || filePath; + const normalizedPath = this.normalizePath(filePath); + const normalizedConsumes = consumes.map(p => this.normalizePath(p)); + const normalizedConsumedBy = consumedBy.map(p => this.normalizePath(p)); + await this.supabaseRepository.setAIFileCache(param.owner, param.repo, branch, { + file_name: fileName, + path: normalizedPath, + sha: fileInfo.sha, + description: fileInfo.description, + consumes: normalizedConsumes, + consumed_by: normalizedConsumedBy + }); + (0, logger_1.logDebugInfo)(`šŸ’¾ Saved cache entry for ${normalizedPath}`); + } + catch (error) { + (0, logger_1.logError)(`Error saving AI cache entry to Supabase for ${filePath}: ${error}`); + } } +} +exports.FileCacheManager = FileCacheManager; - // Fallback to parsing the help flag to invoke the help. - return this._dispatchSubcommand( - subcommandName, - [], - [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'], - ); - } - /** - * Check this.args against expected this.registeredArguments. - * - * @private - */ +/***/ }), - _checkNumberOfArguments() { - // too few - this.registeredArguments.forEach((arg, i) => { - if (arg.required && this.args[i] == null) { - this.missingArgument(arg.name()); - } - }); - // too many - if ( - this.registeredArguments.length > 0 && - this.registeredArguments[this.registeredArguments.length - 1].variadic - ) { - return; +/***/ 5310: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileImportAnalyzer = void 0; +/** + * Service for extracting imports and building file relationship maps + * Supports multiple programming languages + */ +class FileImportAnalyzer { + /** + * Extract imports from a file regardless of programming language + */ + extractImportsFromFile(filePath, content) { + const imports = []; + const ext = filePath.split('.').pop()?.toLowerCase() || ''; + const dir = filePath.split('/').slice(0, -1).join('/') || ''; + // TypeScript/JavaScript + if (['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs'].includes(ext)) { + // import ... from '...' + const es6Imports = content.match(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g) || []; + es6Imports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + // require('...') + const requireImports = content.match(/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g) || []; + requireImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // Python + if (['py', 'pyw', 'pyi'].includes(ext)) { + // import ... / from ... import ... + const pyImports = content.match(/(?:^|\n)\s*(?:import\s+\w+|from\s+[\w.]+)\s+import/gm) || []; + pyImports.forEach(match => { + const fromMatch = match.match(/from\s+([\w.]+)/); + if (fromMatch) { + imports.push(fromMatch[1]); + } + else { + const importMatch = match.match(/import\s+(\w+)/); + if (importMatch) + imports.push(importMatch[1]); + } + }); + } + // Java + if (ext === 'java') { + const javaImports = content.match(/import\s+(?:static\s+)?[\w.]+\s*;/g) || []; + javaImports.forEach(match => { + const path = match.replace(/import\s+(?:static\s+)?/, '').replace(/\s*;/, ''); + imports.push(path); + }); + } + // Kotlin + if (['kt', 'kts'].includes(ext)) { + const ktImports = content.match(/import\s+[\w.]+\s*/g) || []; + ktImports.forEach(match => { + const path = match.replace(/import\s+/, '').trim(); + imports.push(path); + }); + } + // Go + if (ext === 'go') { + const goImports = content.match(/import\s*(?:\([^)]+\)|['"]([^'"]+)['"])/gs) || []; + goImports.forEach(match => { + const quoted = match.match(/['"]([^'"]+)['"]/); + if (quoted) { + imports.push(quoted[1]); + } + else { + // Multi-line import block + const multiLine = match.match(/import\s*\(([^)]+)\)/s); + if (multiLine) { + const paths = multiLine[1].match(/['"]([^'"]+)['"]/g) || []; + paths.forEach(p => { + const path = p.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + } + }); + } + // Rust + if (ext === 'rs') { + const rustImports = content.match(/use\s+[\w:]+(?:::\*)?\s*;/g) || []; + rustImports.forEach(match => { + const path = match.replace(/use\s+/, '').replace(/\s*;/, '').split('::')[0]; + imports.push(path); + }); + } + // Ruby + if (ext === 'rb') { + const rubyImports = content.match(/(?:require|require_relative)\s+['"]([^'"]+)['"]/g) || []; + rubyImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // PHP + if (ext === 'php') { + const phpImports = content.match(/(?:use|require|include)(?:_once)?\s+['"]([^'"]+)['"]/g) || []; + phpImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // Swift + if (ext === 'swift') { + const swiftImports = content.match(/import\s+\w+/g) || []; + swiftImports.forEach(match => { + const path = match.replace(/import\s+/, ''); + imports.push(path); + }); + } + // Dart + if (ext === 'dart') { + const dartImports = content.match(/import\s+['"]([^'"]+)['"]/g) || []; + dartImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // Resolve relative imports to absolute paths + return imports.map(imp => { + // Skip external packages (node_modules, stdlib, etc.) + if (!imp.startsWith('.') && !imp.startsWith('/')) { + // Try to resolve relative to current file + if (dir) { + // Check if it's a relative path that needs resolution + const possiblePath = `${dir}/${imp}`.replace(/\/+/g, '/'); + return possiblePath; + } + return imp; + } + // Resolve relative paths + if (imp.startsWith('.')) { + const resolved = this.resolveRelativePath(dir, imp); + return resolved; + } + return imp; + }).filter(imp => imp && !imp.includes('node_modules') && !imp.startsWith('http')); } - if (this.args.length > this.registeredArguments.length) { - this._excessArguments(this.args); + /** + * Resolve relative import path to absolute path + */ + resolveRelativePath(baseDir, relativePath) { + if (!relativePath.startsWith('.')) { + return relativePath; + } + let path = baseDir || ''; + const parts = relativePath.split('/'); + for (const part of parts) { + if (part === '..') { + path = path.split('/').slice(0, -1).join('/'); + } + else if (part === '.' || part === '') { + // Current directory, do nothing + } + else { + path = path ? `${path}/${part}` : part; + } + } + // Remove file extension if present and add common extensions + const withoutExt = path.replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, ''); + return withoutExt; + } + /** + * Build relationship map from all files by extracting imports + * Also builds reverse map (consumed_by) + */ + buildRelationshipMap(repositoryFiles) { + const consumesMap = new Map(); + const consumedByMap = new Map(); + // Initialize consumedBy map for all files + for (const filePath of repositoryFiles.keys()) { + consumedByMap.set(filePath, []); + } + for (const [filePath, content] of repositoryFiles.entries()) { + const imports = this.extractImportsFromFile(filePath, content); + // Resolve imports to actual file paths in the repository + const resolvedImports = []; + for (const imp of imports) { + // Try to find matching file in repository + const possiblePaths = [ + imp, + `${imp}.ts`, + `${imp}.tsx`, + `${imp}.js`, + `${imp}.jsx`, + `${imp}/index.ts`, + `${imp}/index.tsx`, + `${imp}/index.js`, + `${imp}/index.jsx`, + ]; + for (const possiblePath of possiblePaths) { + // Check exact match + if (repositoryFiles.has(possiblePath)) { + if (!resolvedImports.includes(possiblePath)) { + resolvedImports.push(possiblePath); + } + // Update reverse map + const currentConsumers = consumedByMap.get(possiblePath) || []; + if (!currentConsumers.includes(filePath)) { + currentConsumers.push(filePath); + consumedByMap.set(possiblePath, currentConsumers); + } + break; + } + // Check if any file path contains this import + for (const [repoPath] of repositoryFiles.entries()) { + if (repoPath.includes(possiblePath) || possiblePath.includes(repoPath)) { + if (!resolvedImports.includes(repoPath)) { + resolvedImports.push(repoPath); + } + // Update reverse map + const currentConsumers = consumedByMap.get(repoPath) || []; + if (!currentConsumers.includes(filePath)) { + currentConsumers.push(filePath); + consumedByMap.set(repoPath, currentConsumers); + } + } + } + } + } + consumesMap.set(filePath, resolvedImports); + } + return { consumes: consumesMap, consumedBy: consumedByMap }; } - } +} +exports.FileImportAnalyzer = FileImportAnalyzer; - /** - * Process this.args using this.registeredArguments and save as this.processedArgs! - * - * @private - */ - _processArguments() { - const myParseArg = (argument, value, previous) => { - // Extra processing for nice error message on parsing failure. - let parsedValue = value; - if (value !== null && argument.parseArg) { - const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`; - parsedValue = this._callParseArg( - argument, - value, - previous, - invalidValueMessage, - ); - } - return parsedValue; - }; +/***/ }), - this._checkNumberOfArguments(); +/***/ 9810: +/***/ ((__unused_webpack_module, exports) => { - const processedArgs = []; - this.registeredArguments.forEach((declaredArg, index) => { - let value = declaredArg.defaultValue; - if (declaredArg.variadic) { - // Collect together remaining arguments for passing together as an array. - if (index < this.args.length) { - value = this.args.slice(index); - if (declaredArg.parseArg) { - value = value.reduce((processed, v) => { - return myParseArg(declaredArg, v, processed); - }, declaredArg.defaultValue); - } - } else if (value === undefined) { - value = []; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileSearchService = void 0; +/** + * Service for building file indexes and searching files + */ +class FileSearchService { + /** + * Build file index for quick lookup by filename or directory + */ + buildFileIndex(files) { + const index = new Map(); + for (const [path, content] of files.entries()) { + const pathParts = path.split('/'); + const fileName = pathParts[pathParts.length - 1]; + // Index by filename + if (!index.has(fileName)) { + index.set(fileName, []); + } + index.get(fileName).push(path); + // Index by directory + if (pathParts.length > 1) { + const dir = pathParts.slice(0, -1).join('/'); + if (!index.has(dir)) { + index.set(dir, []); + } + index.get(dir).push(path); + } } - } else if (index < this.args.length) { - value = this.args[index]; - if (declaredArg.parseArg) { - value = myParseArg(declaredArg, value, declaredArg.defaultValue); + return index; + } + /** + * Search files by search terms (filename, directory, or pattern) + */ + searchFiles(searchTerms, fileIndex) { + const foundFiles = new Set(); + for (const term of searchTerms) { + // Exact filename match + if (fileIndex.has(term)) { + fileIndex.get(term).forEach(f => foundFiles.add(f)); + } + // Directory match + if (fileIndex.has(term)) { + fileIndex.get(term).forEach(f => foundFiles.add(f)); + } + // Pattern match (simple contains) + for (const [key, paths] of fileIndex.entries()) { + if (key.toLowerCase().includes(term.toLowerCase())) { + paths.forEach(p => foundFiles.add(p)); + } + // Also check paths + paths.forEach(path => { + if (path.toLowerCase().includes(term.toLowerCase())) { + foundFiles.add(path); + } + }); + } } - } - processedArgs[index] = value; - }); - this.processedArgs = processedArgs; - } - - /** - * Once we have a promise we chain, but call synchronously until then. - * - * @param {(Promise|undefined)} promise - * @param {Function} fn - * @return {(Promise|undefined)} - * @private - */ - - _chainOrCall(promise, fn) { - // thenable - if (promise && promise.then && typeof promise.then === 'function') { - // already have a promise, chain callback - return promise.then(() => fn()); + return Array.from(foundFiles); } - // callback might return a promise - return fn(); - } +} +exports.FileSearchService = FileSearchService; - /** - * - * @param {(Promise|undefined)} promise - * @param {string} event - * @return {(Promise|undefined)} - * @private - */ - _chainOrCallHooks(promise, event) { - let result = promise; - const hooks = []; - this._getCommandAndAncestors() - .reverse() - .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined) - .forEach((hookedCommand) => { - hookedCommand._lifeCycleHooks[event].forEach((callback) => { - hooks.push({ hookedCommand, callback }); - }); - }); - if (event === 'postAction') { - hooks.reverse(); - } +/***/ }), - hooks.forEach((hookDetail) => { - result = this._chainOrCall(result, () => { - return hookDetail.callback(hookDetail.hookedCommand, this); - }); - }); - return result; - } +/***/ 8785: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * - * @param {(Promise|undefined)} promise - * @param {Command} subCommand - * @param {string} event - * @return {(Promise|undefined)} - * @private - */ +"use strict"; - _chainOrCallSubCommandHook(promise, subCommand, event) { - let result = promise; - if (this._lifeCycleHooks[event] !== undefined) { - this._lifeCycleHooks[event].forEach((hook) => { - result = this._chainOrCall(result, () => { - return hook(this, subCommand); - }); - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ThinkCodeManager = void 0; +const logger_1 = __nccwpck_require__(8836); +/** + * Manages virtual code state - keeps files in memory and applies proposed changes + * so subsequent reasoning steps can see the accumulated progress + */ +class ThinkCodeManager { + constructor() { + this.originalFiles = new Map(); + this.virtualFiles = new Map(); + this.appliedChanges = new Map(); // file -> changes applied + this.allAppliedChanges = []; } - return result; - } - - /** - * Process arguments in context of this command. - * Returns action result, in case it is a promise. - * - * @private - */ - - _parseCommand(operands, unknown) { - const parsed = this.parseOptions(unknown); - this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env - this._parseOptionsImplied(); - operands = operands.concat(parsed.operands); - unknown = parsed.unknown; - this.args = operands.concat(unknown); - - if (operands && this._findCommand(operands[0])) { - return this._dispatchSubcommand(operands[0], operands.slice(1), unknown); + /** + * Initialize with original repository files + */ + initialize(originalFiles) { + this.originalFiles = new Map(originalFiles); + this.virtualFiles = new Map(originalFiles); + this.appliedChanges.clear(); + this.allAppliedChanges = []; + (0, logger_1.logInfo)(`šŸ“¦ Code manager initialized with ${originalFiles.size} files`); } - if ( - this._getHelpCommand() && - operands[0] === this._getHelpCommand().name() - ) { - return this._dispatchHelpCommand(operands[1]); + /** + * Get current state of a file (with applied changes) + */ + getFileContent(filePath) { + return this.virtualFiles.get(filePath); } - if (this._defaultCommandName) { - this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command - return this._dispatchSubcommand( - this._defaultCommandName, - operands, - unknown, - ); + /** + * Get all virtual files + */ + getAllFiles() { + return new Map(this.virtualFiles); } - if ( - this.commands.length && - this.args.length === 0 && - !this._actionHandler && - !this._defaultCommandName - ) { - // probably missing subcommand and no handler, user needs help (and exit) - this.help({ error: true }); + /** + * Check if a file has been modified + */ + isFileModified(filePath) { + return this.appliedChanges.has(filePath); } - - this._outputHelpIfRequested(parsed.unknown); - this._checkForMissingMandatoryOptions(); - this._checkForConflictingOptions(); - - // We do not always call this check to avoid masking a "better" error, like unknown command. - const checkForUnknownOptions = () => { - if (parsed.unknown.length > 0) { - this.unknownOption(parsed.unknown[0]); - } - }; - - const commandEvent = `command:${this.name()}`; - if (this._actionHandler) { - checkForUnknownOptions(); - this._processArguments(); - - let promiseChain; - promiseChain = this._chainOrCallHooks(promiseChain, 'preAction'); - promiseChain = this._chainOrCall(promiseChain, () => - this._actionHandler(this.processedArgs), - ); - if (this.parent) { - promiseChain = this._chainOrCall(promiseChain, () => { - this.parent.emit(commandEvent, operands, unknown); // legacy - }); - } - promiseChain = this._chainOrCallHooks(promiseChain, 'postAction'); - return promiseChain; + /** + * Get changes applied to a specific file + */ + getFileChanges(filePath) { + return this.appliedChanges.get(filePath) || []; } - if (this.parent && this.parent.listenerCount(commandEvent)) { - checkForUnknownOptions(); - this._processArguments(); - this.parent.emit(commandEvent, operands, unknown); // legacy - } else if (operands.length) { - if (this._findCommand('*')) { - // legacy default command - return this._dispatchSubcommand('*', operands, unknown); - } - if (this.listenerCount('command:*')) { - // skip option check, emit event for possible misspelling suggestion - this.emit('command:*', operands, unknown); - } else if (this.commands.length) { - this.unknownCommand(); - } else { - checkForUnknownOptions(); - this._processArguments(); - } - } else if (this.commands.length) { - checkForUnknownOptions(); - // This command has subcommands and nothing hooked up at this level, so display help (and exit). - this.help({ error: true }); - } else { - checkForUnknownOptions(); - this._processArguments(); - // fall through for caller to handle after calling .parse() + /** + * Apply a proposed change to the virtual codebase + */ + applyChange(change) { + try { + const filePath = change.file_path; + const currentContent = this.virtualFiles.get(filePath) || ''; + let newContent = currentContent; + switch (change.change_type) { + case 'create': + if (!currentContent) { + // File doesn't exist, create it with suggested code + newContent = change.suggested_code || ''; + (0, logger_1.logDebugInfo)(`āœ… Created virtual file: ${filePath}`); + } + else { + (0, logger_1.logDebugInfo)(`āš ļø File ${filePath} already exists, skipping create`); + return false; + } + break; + case 'modify': + if (currentContent) { + // Apply modification - for now, append suggested code + // In a more sophisticated implementation, we could parse and merge + if (change.suggested_code) { + // Simple strategy: append the suggested code with a marker + newContent = `${currentContent}\n\n// === AI Proposed Modification ===\n${change.suggested_code}`; + (0, logger_1.logDebugInfo)(`āœ… Modified virtual file: ${filePath}`); + } + else { + // Just note the modification + newContent = `${currentContent}\n\n// === AI Proposed Modification: ${change.description} ===`; + (0, logger_1.logDebugInfo)(`āœ… Noted modification in virtual file: ${filePath}`); + } + } + else { + (0, logger_1.logDebugInfo)(`āš ļø Cannot modify non-existent file: ${filePath}`); + return false; + } + break; + case 'delete': + // Mark as deleted but keep for reference + newContent = `// === FILE MARKED FOR DELETION ===\n// Original content:\n${currentContent}`; + (0, logger_1.logDebugInfo)(`āœ… Marked virtual file for deletion: ${filePath}`); + break; + case 'refactor': + if (currentContent && change.suggested_code) { + // Refactor: replace with new code + newContent = `${currentContent}\n\n// === AI Proposed Refactoring ===\n${change.suggested_code}`; + (0, logger_1.logDebugInfo)(`āœ… Refactored virtual file: ${filePath}`); + } + else { + (0, logger_1.logDebugInfo)(`āš ļø Cannot refactor file ${filePath}: ${currentContent ? 'no suggested code' : 'file does not exist'}`); + return false; + } + break; + default: + (0, logger_1.logDebugInfo)(`āš ļø Unknown change type: ${change.change_type}`); + return false; + } + this.virtualFiles.set(filePath, newContent); + // Track applied changes + if (!this.appliedChanges.has(filePath)) { + this.appliedChanges.set(filePath, []); + } + this.appliedChanges.get(filePath).push(change); + this.allAppliedChanges.push(change); + return true; + } + catch (error) { + (0, logger_1.logDebugInfo)(`āŒ Error applying change to ${change.file_path}: ${error}`); + return false; + } } - } + /** + * Check if a change has already been applied (to avoid duplicates) + */ + hasChangeBeenApplied(change) { + // Check by file path and description similarity + const existingChanges = this.allAppliedChanges.filter(c => c.file_path === change.file_path && + c.change_type === change.change_type && + this.areSimilar(c.description, change.description)); + return existingChanges.length > 0; + } + /** + * Get summary of all applied changes + */ + getChangesSummary() { + if (this.allAppliedChanges.length === 0) { + return 'No changes applied yet.'; + } + const summary = []; + summary.push(`\n## Applied Changes (${this.allAppliedChanges.length} total):\n`); + for (const [filePath, changes] of this.appliedChanges.entries()) { + summary.push(`\n### ${filePath} (${changes.length} change${changes.length > 1 ? 's' : ''}):`); + changes.forEach((change, idx) => { + summary.push(` ${idx + 1}. ${change.change_type.toUpperCase()}: ${change.description}`); + }); + } + return summary.join('\n'); + } + /** + * Get context about what has changed for the AI + */ + getContextForAI() { + const context = []; + if (this.allAppliedChanges.length > 0) { + context.push(`\n## Code State Changes Applied:`); + context.push(`Total changes applied: ${this.allAppliedChanges.length}`); + context.push(`Files modified: ${this.appliedChanges.size}`); + context.push(this.getChangesSummary()); + // Show modified file contents summary + context.push(`\n## Modified Files Preview:`); + for (const [filePath, changes] of this.appliedChanges.entries()) { + const currentContent = this.virtualFiles.get(filePath); + if (currentContent) { + const preview = currentContent.substring(0, 500); + context.push(`\n### ${filePath}:`); + context.push(`\`\`\`\n${preview}${currentContent.length > 500 ? '\n... (truncated)' : ''}\n\`\`\``); + } + } + } + else { + context.push(`\n## Code State: No changes applied yet.`); + } + return context.join('\n'); + } + /** + * Simple similarity check for change descriptions + */ + areSimilar(desc1, desc2) { + const normalize = (s) => s.toLowerCase().trim().replace(/\s+/g, ' '); + const n1 = normalize(desc1); + const n2 = normalize(desc2); + // Exact match + if (n1 === n2) + return true; + // Check if one contains the other (for similar proposals) + if (n1.length > 20 && n2.length > 20) { + const words1 = n1.split(' ').filter(w => w.length > 3); + const words2 = n2.split(' ').filter(w => w.length > 3); + const commonWords = words1.filter(w => words2.includes(w)); + // If 70% of significant words match, consider similar + return commonWords.length / Math.max(words1.length, words2.length) > 0.7; + } + return false; + } + /** + * Get statistics + */ + getStats() { + return { + totalFiles: this.virtualFiles.size, + modifiedFiles: this.appliedChanges.size, + totalChanges: this.allAppliedChanges.length + }; + } +} +exports.ThinkCodeManager = ThinkCodeManager; - /** - * Find matching command. - * - * @private - * @return {Command | undefined} - */ - _findCommand(name) { - if (!name) return undefined; - return this.commands.find( - (cmd) => cmd._name === name || cmd._aliases.includes(name), - ); - } - /** - * Return an option matching `arg` if any. - * - * @param {string} arg - * @return {Option} - * @package - */ +/***/ }), - _findOption(arg) { - return this.options.find((option) => option.is(arg)); - } +/***/ 3618: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Display an error message if a mandatory option does not have a value. - * Called after checking for help flags in leaf subcommand. - * - * @private - */ +"use strict"; - _checkForMissingMandatoryOptions() { - // Walk up hierarchy so can call in subcommand after checking for displaying help. - this._getCommandAndAncestors().forEach((cmd) => { - cmd.options.forEach((anOption) => { - if ( - anOption.mandatory && - cmd.getOptionValue(anOption.attributeName()) === undefined - ) { - cmd.missingMandatoryOptionValue(anOption); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ThinkTodoManager = void 0; +const logger_1 = __nccwpck_require__(8836); +/** + * Manages TODO list for the reasoning process + * Similar to how the assistant tracks high-level tasks vs iterative steps + */ +class ThinkTodoManager { + constructor() { + this.todos = new Map(); + this.nextId = 1; + } + /** + * Initialize with optional initial todos + */ + initialize(initialTodos) { + this.todos.clear(); + this.nextId = 1; + if (initialTodos && initialTodos.length > 0) { + for (const todo of initialTodos) { + this.createTodo(todo.content, todo.status || 'pending'); + } + (0, logger_1.logInfo)(`šŸ“‹ TODO list initialized with ${initialTodos.length} tasks`); } - }); - }); - } + else { + (0, logger_1.logInfo)(`šŸ“‹ TODO list initialized (empty)`); + } + } + /** + * Create a new TODO item + */ + createTodo(content, status = 'pending') { + const id = `todo_${this.nextId++}`; + const now = Date.now(); + const todo = { + id, + content, + status, + created_at: now, + updated_at: now + }; + this.todos.set(id, todo); + (0, logger_1.logDebugInfo)(`āœ… Created TODO: ${content} (${status})`); + return todo; + } + /** + * Update an existing TODO item + */ + updateTodo(id, updates) { + const todo = this.todos.get(id); + if (!todo) { + (0, logger_1.logDebugInfo)(`āš ļø TODO ${id} not found for update`); + return false; + } + const now = Date.now(); + const oldStatus = todo.status; + if (updates.status) { + todo.status = updates.status; + if (updates.status === 'completed' && !todo.completed_at) { + todo.completed_at = now; + } + } + if (updates.notes !== undefined) { + todo.notes = updates.notes; + } + if (updates.related_files) { + todo.related_files = updates.related_files; + } + if (updates.related_changes) { + todo.related_changes = updates.related_changes; + } + todo.updated_at = now; + if (oldStatus !== todo.status) { + (0, logger_1.logInfo)(`šŸ“ Updated TODO ${id}: ${oldStatus} → ${todo.status}`); + } + else { + (0, logger_1.logDebugInfo)(`šŸ“ Updated TODO ${id} (notes/metadata)`); + } + return true; + } + /** + * Get all TODOs + */ + getAllTodos() { + return Array.from(this.todos.values()).sort((a, b) => a.created_at - b.created_at); + } + /** + * Get TODOs by status + */ + getTodosByStatus(status) { + return this.getAllTodos().filter(todo => todo.status === status); + } + /** + * Get active TODOs (pending or in_progress) + */ + getActiveTodos() { + return this.getAllTodos().filter(todo => todo.status === 'pending' || todo.status === 'in_progress'); + } + /** + * Get completion statistics + */ + getStats() { + const all = this.getAllTodos(); + const pending = all.filter(t => t.status === 'pending').length; + const in_progress = all.filter(t => t.status === 'in_progress').length; + const completed = all.filter(t => t.status === 'completed').length; + const cancelled = all.filter(t => t.status === 'cancelled').length; + const total = all.length; + const completion_rate = total > 0 ? (completed / total) * 100 : 0; + return { + total, + pending, + in_progress, + completed, + cancelled, + completion_rate + }; + } + /** + * Get formatted TODO list for AI context + */ + getContextForAI() { + const stats = this.getStats(); + const activeTodos = this.getActiveTodos(); + const completedTodos = this.getTodosByStatus('completed').slice(-5); // Last 5 completed + const allTodos = this.getAllTodos(); + const context = []; + context.push(`\n## šŸ“‹ TODO List Status`); + context.push(`- **Total Tasks**: ${stats.total}`); + context.push(`- **Pending**: ${stats.pending}`); + context.push(`- **In Progress**: ${stats.in_progress}`); + context.push(`- **Completed**: ${stats.completed} (${stats.completion_rate.toFixed(1)}%)`); + context.push(`- **Cancelled**: ${stats.cancelled}`); + if (allTodos.length > 0) { + context.push(`\n### šŸ“ All TODO Items (with IDs for reference):`); + allTodos.forEach((todo, idx) => { + const statusEmoji = todo.status === 'completed' ? 'āœ…' : + todo.status === 'in_progress' ? 'šŸ”„' : + todo.status === 'cancelled' ? 'āŒ' : 'ā³'; + context.push(`${idx + 1}. ${statusEmoji} **[ID: ${todo.id}]** ${todo.status.toUpperCase()}: ${todo.content}`); + if (todo.related_files && todo.related_files.length > 0) { + context.push(` šŸ“ Related files: ${todo.related_files.join(', ')}`); + } + if (todo.notes) { + context.push(` šŸ“ Notes: ${todo.notes}`); + } + }); + context.push(`\n**āš ļø IMPORTANT**: When updating TODOs, use the EXACT ID shown above (e.g., "${allTodos[0]?.id || 'todo_1'}"). Do NOT use numeric IDs like "1" or "2".`); + } + if (activeTodos.length > 0) { + context.push(`\n### šŸ”„ Active Tasks to Work On (${activeTodos.length}):`); + activeTodos.forEach((todo, idx) => { + const statusEmoji = todo.status === 'in_progress' ? 'šŸ”„' : 'ā³'; + context.push(`${idx + 1}. ${statusEmoji} **[ID: ${todo.id}]** ${todo.status.toUpperCase()}: ${todo.content}`); + if (todo.related_files && todo.related_files.length > 0) { + context.push(` šŸ“ Related files: ${todo.related_files.join(', ')}`); + } + if (todo.notes) { + context.push(` šŸ“ Notes: ${todo.notes}`); + } + }); + } + if (completedTodos.length > 0) { + context.push(`\n### āœ… Recently Completed (${completedTodos.length}):`); + completedTodos.forEach((todo, idx) => { + context.push(`${idx + 1}. āœ… **[ID: ${todo.id}]** ${todo.content}`); + }); + } + if (activeTodos.length === 0 && stats.total > 0) { + context.push(`\nšŸŽ‰ All tasks completed!`); + } + return context.join('\n'); + } + /** + * Link a TODO to proposed changes + */ + linkTodoToChanges(todoId, changes) { + const todo = this.todos.get(todoId); + if (!todo) + return; + const changeDescriptions = changes.map(c => `${c.change_type}:${c.file_path}:${c.description.substring(0, 50)}`); + if (!todo.related_changes) { + todo.related_changes = []; + } + todo.related_changes.push(...changeDescriptions); + // Also update related files + const files = changes.map(c => c.file_path); + if (!todo.related_files) { + todo.related_files = []; + } + todo.related_files.push(...files); + todo.related_files = [...new Set(todo.related_files)]; // Remove duplicates + todo.updated_at = Date.now(); + } + /** + * Auto-update TODO status based on progress + * If changes are applied for a TODO, mark it as in_progress or completed + */ + autoUpdateFromChanges(changes) { + // Find active TODOs that might be related to these changes + const activeTodos = this.getActiveTodos(); + for (const todo of activeTodos) { + // Check if any of the changes are related to this TODO's files + if (todo.related_files) { + const relatedChanges = changes.filter(c => todo.related_files.includes(c.file_path)); + if (relatedChanges.length > 0) { + // Link changes to TODO + this.linkTodoToChanges(todo.id, relatedChanges); + // If TODO was pending, mark as in_progress + if (todo.status === 'pending') { + this.updateTodo(todo.id, { + status: 'in_progress', + notes: `Auto-updated: ${relatedChanges.length} change(s) applied` + }); + } + } + } + } + } + /** + * Get summary for final report + */ + getSummary() { + const stats = this.getStats(); + const allTodos = this.getAllTodos(); + if (allTodos.length === 0) { + return 'No TODO list was created during this analysis.'; + } + const summary = []; + summary.push(`\n## TODO List Summary`); + summary.push(`- Total tasks: ${stats.total}`); + summary.push(`- Completed: ${stats.completed} (${stats.completion_rate.toFixed(1)}%)`); + summary.push(`- In Progress: ${stats.in_progress}`); + summary.push(`- Pending: ${stats.pending}`); + summary.push(`\n### All Tasks:`); + allTodos.forEach((todo, idx) => { + const statusIcon = todo.status === 'completed' ? 'āœ…' : + todo.status === 'in_progress' ? 'šŸ”„' : + todo.status === 'cancelled' ? 'āŒ' : 'ā³'; + summary.push(`${idx + 1}. ${statusIcon} **${todo.status.toUpperCase()}**: ${todo.content}`); + if (todo.notes) { + summary.push(` Notes: ${todo.notes}`); + } + }); + return summary.join('\n'); + } +} +exports.ThinkTodoManager = ThinkTodoManager; - /** - * Display an error message if conflicting options are used together in this. - * - * @private - */ - _checkForConflictingLocalOptions() { - const definedNonDefaultOptions = this.options.filter((option) => { - const optionKey = option.attributeName(); - if (this.getOptionValue(optionKey) === undefined) { - return false; - } - return this.getOptionValueSource(optionKey) !== 'default'; - }); - const optionsWithConflicting = definedNonDefaultOptions.filter( - (option) => option.conflictsWith.length > 0, - ); +/***/ }), - optionsWithConflicting.forEach((option) => { - const conflictingAndDefined = definedNonDefaultOptions.find((defined) => - option.conflictsWith.includes(defined.attributeName()), - ); - if (conflictingAndDefined) { - this._conflictingOption(option, conflictingAndDefined); - } - }); - } +/***/ 3841: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Display an error message if conflicting options are used together. - * Called after checking for help flags in leaf subcommand. - * - * @private - */ - _checkForConflictingOptions() { - // Walk up hierarchy so can call in subcommand after checking for displaying help. - this._getCommandAndAncestors().forEach((cmd) => { - cmd._checkForConflictingLocalOptions(); - }); - } +"use strict"; - /** - * Parse options from `argv` removing known options, - * and return argv split into operands and unknown arguments. - * - * Examples: - * - * argv => operands, unknown - * --known kkk op => [op], [] - * op --known kkk => [op], [] - * sub --unknown uuu op => [sub], [--unknown uuu op] - * sub -- --unknown uuu op => [sub --unknown uuu op], [] - * - * @param {string[]} argv - * @return {{operands: string[], unknown: string[]}} - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ThinkUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const file_repository_1 = __nccwpck_require__(1503); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +const think_code_manager_1 = __nccwpck_require__(8785); +const think_todo_manager_1 = __nccwpck_require__(3618); +const file_import_analyzer_1 = __nccwpck_require__(5310); +const file_cache_manager_1 = __nccwpck_require__(1855); +const codebase_analyzer_1 = __nccwpck_require__(678); +const file_search_service_1 = __nccwpck_require__(9810); +const comment_formatter_1 = __nccwpck_require__(5788); +class ThinkUseCase { + constructor() { + this.taskId = 'ThinkUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.fileRepository = new file_repository_1.FileRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + // Services + this.fileImportAnalyzer = new file_import_analyzer_1.FileImportAnalyzer(); + this.fileCacheManager = new file_cache_manager_1.FileCacheManager(); + this.fileSearchService = new file_search_service_1.FileSearchService(); + this.commentFormatter = new comment_formatter_1.CommentFormatter(); + this.MAX_ITERATIONS = 30; // Increased to allow deeper analysis + this.MAX_FILES_TO_ANALYZE = 50; // Increased file limit + this.MAX_CONSECUTIVE_SEARCHES = 3; // Max consecutive search_files without progress + // Initialize CodebaseAnalyzer with dependencies + this.codebaseAnalyzer = new codebase_analyzer_1.CodebaseAnalyzer(this.aiRepository, this.fileImportAnalyzer, this.fileCacheManager); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + // Extract the question/prompt from the issue, PR, or comment + let question = ''; + let description = ''; + if (param.issue.isIssueComment) { + question = param.issue.commentBody || ''; + description = await this.getIssueDescription(param) || ''; + } + else if (param.pullRequest.isPullRequestReviewComment) { + question = param.pullRequest.commentBody || ''; + description = await this.getIssueDescription(param) || ''; + } + else if (param.issue.isIssue) { + description = await this.getIssueDescription(param) || ''; + question = description; + } + else if (param.singleAction.isThinkAction) { + // For CLI usage, get question from comment body if available + // This handles the case when think is called as single-action + const commentBody = param.issue.commentBody || param.inputs?.comment?.body || ''; + if (commentBody) { + question = commentBody; + description = await this.getIssueDescription(param) || ''; + } + else { + description = await this.getIssueDescription(param) || ''; + question = description || ''; + } + } + if (!question || question.length === 0) { + if (!param.singleAction.isThinkAction) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + errors: ['No question or prompt provided.'], + })); + return results; + } + } + if (param.ai.getOpenRouterModel().length === 0 || param.ai.getOpenRouterApiKey().length === 0) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + errors: ['OpenRouter model or API key not found.'], + })); + return results; + } + (0, logger_1.logInfo)(`šŸ”Ž Question: ${question}`); + (0, logger_1.logInfo)(`šŸ”Ž Description: ${description}`); + if (question.length === 0 || !question.includes(`@${param.tokenUser}`)) { + (0, logger_1.logInfo)(`šŸ”Ž Comment body is empty or does not include @${param.tokenUser}`); + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return results; + } + else { + question = question.replace(`@${param.tokenUser}`, '').trim(); + } + // Get full repository content + (0, logger_1.logInfo)(`šŸ“š Loading repository content for ${param.owner}/${param.repo}/${param.commit.branch}`); + const repositoryFiles = await this.fileRepository.getRepositoryContent(param.owner, param.repo, param.tokens.token, param.commit.branch, param.ai.getAiIgnoreFiles(), (fileName) => (0, logger_1.logDebugInfo)(`Loading: ${fileName}`), (fileName) => (0, logger_1.logDebugInfo)(`Ignoring: ${fileName}`)); + (0, logger_1.logInfo)(`šŸ“š Loaded ${repositoryFiles.size} files from repository`); + // Initialize code manager with repository files + const codeManager = new think_code_manager_1.ThinkCodeManager(); + codeManager.initialize(repositoryFiles); + // Initialize TODO manager + const todoManager = new think_todo_manager_1.ThinkTodoManager(); + // AI will create initial TODOs in first iteration if needed + // Build file index for quick lookup + const fileIndex = this.fileSearchService.buildFileIndex(repositoryFiles); + // STEP 0: Generate codebase analysis and file relationships + (0, logger_1.logInfo)(`šŸ” Step 0: Analyzing codebase structure and file relationships...`); + const codebaseAnalysis = await this.codebaseAnalyzer.generateCodebaseAnalysis(param, repositoryFiles, question); + (0, logger_1.logInfo)(`āœ… Codebase analysis completed. Analyzed ${codebaseAnalysis.length} files.`); + // Format codebase analysis for context + const codebaseAnalysisText = this.codebaseAnalyzer.formatCodebaseAnalysisForContext(codebaseAnalysis); + // Reasoning process + const steps = []; + let iteration = 0; + let complete = false; + let analyzedFiles = new Map(); + let allProposedChanges = []; + let currentContext = codebaseAnalysisText; // Start with codebase analysis + let finalAnalysis = ''; + let consecutiveSearches = 0; // Track consecutive search_files without reading + let lastProgressIteration = 0; // Track last iteration with actual progress + let filesReadInIteration = 0; + let seenActions = new Map(); // Track action patterns to detect repetition + while (!complete && iteration < this.MAX_ITERATIONS) { + iteration++; + filesReadInIteration = 0; + (0, logger_1.logInfo)(`šŸ¤” Reasoning iteration ${iteration}/${this.MAX_ITERATIONS}`); + const thinkResponse = await this.performReasoningStep(param, question, description, codeManager, todoManager, fileIndex, analyzedFiles, currentContext, iteration, steps); + if (!thinkResponse) { + (0, logger_1.logError)('No response from AI reasoning step'); + break; + } + // Handle TODO updates (can be included with any action) + if (thinkResponse.todo_updates) { + // Create new TODOs + if (thinkResponse.todo_updates.create) { + for (const todo of thinkResponse.todo_updates.create) { + const createdTodo = todoManager.createTodo(todo.content, todo.status || 'pending'); + (0, logger_1.logInfo)(`āœ… Created TODO: [${createdTodo.id}] ${todo.content}`); + } + (0, logger_1.logInfo)(`šŸ“‹ Created ${thinkResponse.todo_updates.create.length} new TODO items`); + } + // Update existing TODOs + if (thinkResponse.todo_updates.update) { + let successCount = 0; + let failedIds = []; + for (const update of thinkResponse.todo_updates.update) { + const success = todoManager.updateTodo(update.id, { + status: update.status, + notes: update.notes + }); + if (success) { + successCount++; + } + else { + failedIds.push(update.id); + } + } + if (successCount > 0) { + (0, logger_1.logInfo)(`šŸ“‹ Successfully updated ${successCount} TODO items`); + } + if (failedIds.length > 0) { + // Show available TODO IDs to help the AI + const allTodos = todoManager.getAllTodos(); + const availableIds = allTodos.map(t => t.id).join(', '); + (0, logger_1.logInfo)(`āš ļø Failed to update ${failedIds.length} TODO items. Available IDs: ${availableIds}`); + currentContext += `\n\nāš ļø TODO Update Error: Could not find TODO(s) with ID(s): ${failedIds.join(', ')}. Available TODO IDs are: ${availableIds}. Please use the EXACT ID from the TODO list above.`; + } + } + } + // Record step with associated data for better comment formatting + const step = { + step_number: iteration, + action: thinkResponse.action, + reasoning: thinkResponse.reasoning, + files_involved: [ + ...(thinkResponse.files_to_read || []), + ...(thinkResponse.files_to_search || []), + ...(thinkResponse.analyzed_files?.map(f => f.path) || []) + ], + findings: thinkResponse.reasoning, + timestamp: Date.now() + }; + // Attach proposals to step if they were generated in this step + if (thinkResponse.action === 'propose_changes' && thinkResponse.proposed_changes) { + step.proposals_in_step = thinkResponse.proposed_changes; + } + // Attach file analysis to step if provided + if (thinkResponse.action === 'analyze_code' && thinkResponse.analyzed_files) { + step.file_analysis_in_step = thinkResponse.analyzed_files; + } + steps.push(step); + (0, logger_1.logInfo)(`šŸ¤” Step ${iteration}: ${thinkResponse.action} - ${thinkResponse.reasoning.substring(0, 100)}...`); + // Track action patterns to detect repetition + const actionKey = `${thinkResponse.action}_${thinkResponse.files_to_search?.join(',') || thinkResponse.files_to_read?.join(',') || 'general'}`; + const actionCount = seenActions.get(actionKey) || 0; + seenActions.set(actionKey, actionCount + 1); + // Execute action + switch (thinkResponse.action) { + case 'search_files': + consecutiveSearches++; + if (thinkResponse.files_to_search && thinkResponse.files_to_search.length > 0) { + const foundFiles = this.fileSearchService.searchFiles(thinkResponse.files_to_search, fileIndex); + (0, logger_1.logInfo)(`šŸ” Search results: Found ${foundFiles.length} files for terms: ${thinkResponse.files_to_search.join(', ')}`); + // Detect if we're repeating the same search + if (actionCount > 1) { + currentContext += `\n\nāš ļø WARNING: You've already searched for "${thinkResponse.files_to_search.join(', ')}" ${actionCount} times. `; + if (foundFiles.length > 0) { + currentContext += `These files were found previously. Consider READING them instead of searching again.`; + } + else { + currentContext += `No files found. Consider trying different search terms or reading files from the list above.`; + } + } + if (foundFiles.length > 0) { + currentContext += `\n\nFound ${foundFiles.length} files matching search criteria:\n${foundFiles.map(f => `- ${f}`).join('\n')}`; + // If found files after multiple searches, suggest reading them + if (consecutiveSearches >= this.MAX_CONSECUTIVE_SEARCHES && foundFiles.length > 0) { + currentContext += `\n\nšŸ’” IMPORTANT: You've searched ${consecutiveSearches} times. You MUST read some of the found files now to proceed with analysis. Suggested files: ${foundFiles.slice(0, 5).join(', ')}`; + } + } + else { + currentContext += `\n\nNo files found matching search criteria: ${thinkResponse.files_to_search.join(', ')}. Available files in repository: ${Array.from(repositoryFiles.keys()).slice(0, 30).join(', ')}...`; + // If too many searches without finding files, provide full file list + if (consecutiveSearches >= this.MAX_CONSECUTIVE_SEARCHES) { + currentContext += `\n\nšŸ“‹ Here are all available files in the repository to help you:\n${Array.from(repositoryFiles.keys()).map((f, i) => `${i + 1}. ${f}`).slice(0, 100).join('\n')}${repositoryFiles.size > 100 ? '\n... and more' : ''}`; + } + } + } + break; + case 'read_file': + consecutiveSearches = 0; // Reset counter when reading files + if (thinkResponse.files_to_read && thinkResponse.files_to_read.length > 0) { + const filesToAnalyze = thinkResponse.files_to_read.slice(0, this.MAX_FILES_TO_ANALYZE - analyzedFiles.size); + (0, logger_1.logInfo)(`šŸ“– Reading ${filesToAnalyze.length} files: ${filesToAnalyze.join(', ')}`); + for (const filePath of filesToAnalyze) { + if (analyzedFiles.has(filePath)) { + (0, logger_1.logDebugInfo)(`ā­ļø Skipping already analyzed file: ${filePath}`); + continue; // Already analyzed + } + // Get content from virtual files (includes applied changes) + const content = codeManager.getFileContent(filePath); + if (content !== undefined) { + filesReadInIteration++; + const isModified = codeManager.isFileModified(filePath); + const modificationNote = isModified ? ` [MODIFIED - ${codeManager.getFileChanges(filePath).length} change(s) applied]` : ''; + (0, logger_1.logDebugInfo)(`āœ… Reading file: ${filePath} (${content.length} chars)${modificationNote}`); + // Show current state with applied changes + currentContext += `\n\n=== File: ${filePath}${modificationNote} ===\n${content.substring(0, 8000)}${content.length > 8000 ? '\n... (truncated)' : ''}`; + // If file was modified, show what changed + if (isModified) { + const changes = codeManager.getFileChanges(filePath); + currentContext += `\n\nāš ļø This file has been modified in previous steps. Changes applied: ${changes.map(c => `${c.change_type}: ${c.description}`).join(', ')}`; + } + lastProgressIteration = iteration; + } + else { + (0, logger_1.logInfo)(`āŒ File not found in repository: ${filePath}`); + // Try to find similar file names + const fileName = filePath.split('/').pop() || ''; + const similarFiles = Array.from(repositoryFiles.keys()).filter(f => f.toLowerCase().includes(fileName.toLowerCase()) || + f.split('/').pop()?.toLowerCase().includes(fileName.toLowerCase())).slice(0, 5); + currentContext += `\n\nāš ļø File not found: ${filePath}. ${similarFiles.length > 0 ? `Similar files found: ${similarFiles.join(', ')}` : 'Please check the file path.'}`; + } + } + } + break; + case 'analyze_code': + consecutiveSearches = 0; // Reset counter when analyzing + if (thinkResponse.analyzed_files && thinkResponse.analyzed_files.length > 0) { + const beforeCount = analyzedFiles.size; + for (const analysis of thinkResponse.analyzed_files) { + if (!analyzedFiles.has(analysis.path)) { + analyzedFiles.set(analysis.path, analysis); + } + } + if (analyzedFiles.size > beforeCount) { + lastProgressIteration = iteration; + } + const findings = thinkResponse.analyzed_files + .map(f => `${f.path} (${f.relevance}): ${f.key_findings}`) + .join('\n'); + currentContext += `\n\nAnalysis findings:\n${findings}`; + } + break; + case 'propose_changes': + consecutiveSearches = 0; // Reset counter when proposing changes + if (thinkResponse.proposed_changes && thinkResponse.proposed_changes.length > 0) { + // Filter out changes that have already been applied + const newChanges = thinkResponse.proposed_changes.filter(change => !codeManager.hasChangeBeenApplied(change)); + if (newChanges.length === 0) { + (0, logger_1.logInfo)(`āš ļø All proposed changes have already been applied. Skipping duplicates.`); + currentContext += `\n\nāš ļø All proposed changes in this step have already been applied in previous iterations. Please propose NEW changes or move to the next step.`; + break; + } + // Apply changes to virtual codebase + let appliedCount = 0; + for (const change of newChanges) { + if (codeManager.applyChange(change)) { + appliedCount++; + allProposedChanges.push(change); + } + } + (0, logger_1.logInfo)(`āœ… Applied ${appliedCount} new changes to virtual codebase (${newChanges.length - appliedCount} skipped)`); + // Auto-update TODOs based on applied changes + todoManager.autoUpdateFromChanges(newChanges.slice(0, appliedCount)); + // Store the index where these proposals start for proper ordering + const startIndex = allProposedChanges.length - appliedCount; + const appliedChanges = newChanges.slice(0, appliedCount); + // Attach to step with start index for proper display order + const currentStep = steps[steps.length - 1]; + if (currentStep) { + currentStep.proposals_in_step = appliedChanges; + currentStep.proposals_start_index = startIndex; + } + const changesSummary = appliedChanges + .map(c => `${c.change_type} ${c.file_path}: ${c.description}`) + .join('\n'); + currentContext += `\n\nāœ… Applied ${appliedCount} new changes to codebase:\n${changesSummary}`; + // Add context about code state + currentContext += codeManager.getContextForAI(); + lastProgressIteration = iteration; + } + break; + case 'update_todos': + consecutiveSearches = 0; // Reset counter when updating TODOs + // Note: TODO updates are handled before the switch statement + // This case is mainly for when action is explicitly update_todos + if (thinkResponse.todo_updates && (!thinkResponse.files_to_search && + !thinkResponse.files_to_read && + !thinkResponse.analyzed_files && + !thinkResponse.proposed_changes)) { + // Pure TODO update action - warn if this happens too often + (0, logger_1.logInfo)(`šŸ“‹ Pure TODO update action (no other work done)`); + currentContext += `\n\nšŸ“‹ TODO list updated. Current status:\n${todoManager.getContextForAI()}`; + currentContext += `\n\nāš ļø **NOTE**: You updated TODOs but didn't do any actual work. In the next iteration, DO THE WORK: search for files, read files, analyze code, or propose changes related to the active TODOs.`; + lastProgressIteration = iteration; + } + break; + case 'complete': + complete = true; + finalAnalysis = thinkResponse.final_analysis || thinkResponse.reasoning; + lastProgressIteration = iteration; + break; + } + // Check for stagnation - if too many iterations without progress + const iterationsWithoutProgress = iteration - lastProgressIteration; + if (iterationsWithoutProgress > 5 && !complete && iteration > 5) { + (0, logger_1.logInfo)(`āš ļø No significant progress in last ${iterationsWithoutProgress} iterations (last progress at iteration ${lastProgressIteration}). Forcing completion.`); + complete = true; + if (!finalAnalysis) { + finalAnalysis = `Analysis completed after ${iteration} iterations. Analyzed ${analyzedFiles.size} files, proposed ${allProposedChanges.length} changes.`; + } + } + // Check if stuck in TODO update loop + const recentActions = steps.slice(-3).map(s => s.action); + const allUpdateTodos = recentActions.every(a => a === 'update_todos'); + if (allUpdateTodos && recentActions.length >= 3 && iteration > 3) { + (0, logger_1.logInfo)(`āš ļø Detected loop: ${recentActions.length} consecutive update_todos actions. Warning AI to do actual work.`); + const activeTodos = todoManager.getActiveTodos(); + const todoIds = activeTodos.map(t => t.id).join(', '); + currentContext += `\n\nāš ļø **STOP UPDATING TODOs AND DO ACTUAL WORK**: You've been updating TODOs repeatedly. Pick a TODO to work on (IDs: ${todoIds}) and DO THE WORK: search for files, read files, analyze code, or propose changes. Stop just updating TODO status!`; + } + // Prevent infinite loops - check file limit + if (analyzedFiles.size >= this.MAX_FILES_TO_ANALYZE) { + (0, logger_1.logInfo)(`Reached maximum files to analyze (${this.MAX_FILES_TO_ANALYZE})`); + if (!complete) { + complete = true; + finalAnalysis = finalAnalysis || `Reached maximum file limit. Analyzed ${analyzedFiles.size} files, proposed ${allProposedChanges.length} changes.`; + } + break; + } + } + // Generate final comprehensive response + if (!finalAnalysis && complete) { + finalAnalysis = await this.generateFinalAnalysis(param, question, analyzedFiles, allProposedChanges, steps, todoManager); + } + // Format and post comprehensive reasoning comment + const formattedComment = this.commentFormatter.formatReasoningComment(question, description, steps, analyzedFiles, allProposedChanges, finalAnalysis, iteration, todoManager); + // Determine issue number + let issueNumber = param.issueNumber; + if (param.singleAction.isThinkAction && issueNumber <= 0) { + // Try to get from issue if available + issueNumber = param.issue?.number || 1; + } + // Post comment if we have a valid issue number and token + if (issueNumber > 0 && param.tokens.token) { + try { + await this.issueRepository.addComment(param.owner, param.repo, issueNumber, formattedComment, param.tokens.token); + (0, logger_1.logInfo)(`āœ… Posted reasoning comment to issue #${issueNumber}`); + } + catch (error) { + (0, logger_1.logError)(`Failed to post comment to issue: ${error}`); + } + } + else { + (0, logger_1.logInfo)(`ā­ļø Skipping comment post: issueNumber=${issueNumber}, hasToken=${!!param.tokens.token}`); + } + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: steps.map(s => `Step ${s.step_number}: ${s.action} - ${s.reasoning.substring(0, 200)}`), + payload: { + steps: steps, + analyzed_files: Array.from(analyzedFiles.values()), + proposed_changes: allProposedChanges, + final_analysis: finalAnalysis, + total_iterations: iteration, + total_files_analyzed: analyzedFiles.size, + comment_posted: issueNumber > 0 + } + })); + } + catch (error) { + (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`], + })); + } + return results; + } + async getIssueDescription(param) { + try { + const description = await this.issueRepository.getDescription(param.owner, param.repo, param.issueNumber, param.tokens.token); + return description ?? null; + } + catch (error) { + (0, logger_1.logError)(`Error getting issue description: ${error}`); + return null; + } + } + // All methods related to file imports, cache, codebase analysis, and comment formatting + // have been moved to dedicated services: + // - FileImportAnalyzer: extractImportsFromFile, resolveRelativePath, buildRelationshipMap + // - FileCacheManager: calculateFileSHA, loadAICache, saveAICacheEntry + // - CodebaseAnalyzer: generateCodebaseAnalysis, generateBasicDescription, generateFallbackFileDescriptions, formatCodebaseAnalysisForContext + // - FileSearchService: buildFileIndex, searchFiles + // - CommentFormatter: formatReasoningComment, formatProposedChange, detectLanguageFromPath, getActionEmoji, formatActionName, getChangeTypeEmoji + async performReasoningStep(param, question, description, codeManager, todoManager, fileIndex, analyzedFiles, currentContext, iteration, previousSteps) { + const analyzedFilesList = Array.from(analyzedFiles.values()); + const analyzedFilesSummary = analyzedFilesList.length > 0 + ? `\n\nPreviously analyzed files (${analyzedFilesList.length}):\n${analyzedFilesList.map(f => `- ${f.path} (${f.relevance}): ${f.key_findings.substring(0, 150)}...`).join('\n')}` + : ''; + const codeStats = codeManager.getStats(); + const codeStateInfo = codeManager.getContextForAI(); + const todoContext = todoManager.getContextForAI(); + const todoStats = todoManager.getStats(); + // Get codebase analysis from initial step (stored in currentContext at start) + const codebaseAnalysisMatch = currentContext.match(/## šŸ“‹ Codebase Analysis & File Relationships\n\n([\s\S]*?)(?=\n##|$)/); + const codebaseAnalysis = codebaseAnalysisMatch ? codebaseAnalysisMatch[1] : ''; + // Build summary of previous steps to avoid repetition + const stepsSummary = previousSteps.length > 0 + ? `\n\n## Previous Steps Taken (${previousSteps.length}):\n${previousSteps.slice(-5).map(s => `- Step ${s.step_number}: ${s.action} - ${s.reasoning.substring(0, 100)}...`).join('\n')}${previousSteps.length > 5 ? `\n... and ${previousSteps.length - 5} more steps` : ''}` + : ''; + const fileListSummary = `\n\nAvailable files in repository (${codeStats.totalFiles} files):\n${Array.from(codeManager.getAllFiles().keys()).slice(0, 50).join('\n')}${codeStats.totalFiles > 50 ? `\n... and ${codeStats.totalFiles - 50} more files` : ''}`; + const prompt = ` +# Code Analysis Assistant - parseOptions(argv) { - const operands = []; // operands, not options or values - const unknown = []; // first unknown option and remaining unknown args - let dest = operands; - const args = argv.slice(); +You are an advanced code analysis assistant similar to Cursor's Auto agent. Your role is to perform deep analysis of codebases and propose thoughtful changes. - function maybeOption(arg) { - return arg.length > 1 && arg[0] === '-'; - } +**CRITICAL CONCEPTS**: - // parse options - let activeVariadicOption = null; - while (args.length) { - const arg = args.shift(); +1. **VIRTUAL CODEBASE**: You are working with a VIRTUAL CODEBASE. When you propose changes, they are automatically applied to the code in memory. Subsequent steps will see the MODIFIED code, not the original. This allows you to build upon previous changes incrementally. - // literal - if (arg === '--') { - if (dest === unknown) dest.push(arg); - dest.push(...args); - break; - } +2. **TODO LIST SYSTEM**: You have a TODO list system to track high-level tasks. Each task in the TODO list may require multiple reasoning steps (search, read, analyze, propose). Use this to: + - Create TODOs in your first iteration to break down the problem + - Update TODO status as you make progress (pending → in_progress → completed) + - Link your actions to TODOs to show which task you're working on + - This helps you understand where you are in the overall process, even if you need many steps per task - if (activeVariadicOption && !maybeOption(arg)) { - this.emit(`option:${activeVariadicOption.name()}`, arg); - continue; - } - activeVariadicOption = null; +3. **TWO-LEVEL REASONING**: + - **High-level (TODO list)**: What major tasks need to be done? + - **Low-level (reasoning steps)**: How do I accomplish each task? (search, read, analyze, propose) - if (maybeOption(arg)) { - const option = this._findOption(arg); - // recognised option, call listener to assign value with possible custom processing - if (option) { - if (option.required) { - const value = args.shift(); - if (value === undefined) this.optionMissingArgument(option); - this.emit(`option:${option.name()}`, value); - } else if (option.optional) { - let value = null; - // historical behaviour is optional value is following arg unless an option - if (args.length > 0 && !maybeOption(args[0])) { - value = args.shift(); - } - this.emit(`option:${option.name()}`, value); - } else { - // boolean flag - this.emit(`option:${option.name()}`); - } - activeVariadicOption = option.variadic ? option : null; - continue; - } - } +${codebaseAnalysis ? `\n\n## šŸ“‹ Codebase Analysis & File Relationships\n\n${codebaseAnalysis}\n\n**This analysis helps you understand the codebase structure and relationships between files. Use it to make informed decisions about which files to examine for the task.**\n\n` : ''} - // Look for combo options following single dash, eat first one if known. - if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { - const option = this._findOption(`-${arg[1]}`); - if (option) { - if ( - option.required || - (option.optional && this._combineFlagAndOptionalValue) - ) { - // option with value following in same argument - this.emit(`option:${option.name()}`, arg.slice(2)); - } else { - // boolean option, emit and put back remainder of arg for further processing - this.emit(`option:${option.name()}`); - args.unshift(`-${arg.slice(2)}`); - } - continue; - } - } +${todoStats.total > 0 ? `\n${todoContext}\n\n**CRITICAL**: To work on a TODO, use its EXACT ID (shown above) when updating. Don't just update status - DO THE ACTUAL WORK (search, read, analyze, propose) in the same response where you update the TODO.` : iteration === 1 ? `\n\n## šŸ“‹ TODO List\n\n**IMPORTANT**: In your first response, you should create a TODO list breaking down the problem into manageable tasks. Use the \`todo_updates.create\` field to create initial TODOs. Each TODO represents a high-level task that may require multiple reasoning steps to complete.` : ''} - // Look for known long flag with value, like --foo=bar - if (/^--[^=]+=/.test(arg)) { - const index = arg.indexOf('='); - const option = this._findOption(arg.slice(0, index)); - if (option && (option.required || option.optional)) { - this.emit(`option:${option.name()}`, arg.slice(index + 1)); - continue; - } - } +## Current Task - // Not a recognised option by this command. - // Might be a command-argument, or subcommand option, or unknown option, or help command or option. +${description ? `### Context/Issue Description:\n\`\`\`\n${description}\n\`\`\`` : ''} - // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands. - if (maybeOption(arg)) { - dest = unknown; - } +### User's Question/Prompt: +\`\`\` +${question} +\`\`\` - // If using positionalOptions, stop processing our options at subcommand. - if ( - (this._enablePositionalOptions || this._passThroughOptions) && - operands.length === 0 && - unknown.length === 0 - ) { - if (this._findCommand(arg)) { - operands.push(arg); - if (args.length > 0) unknown.push(...args); - break; - } else if ( - this._getHelpCommand() && - arg === this._getHelpCommand().name() - ) { - operands.push(arg); - if (args.length > 0) operands.push(...args); - break; - } else if (this._defaultCommandName) { - unknown.push(arg); - if (args.length > 0) unknown.push(...args); - break; - } - } +## Reasoning Process (Iteration ${iteration}/${this.MAX_ITERATIONS}) - // If using passThroughOptions, stop processing options at first command-argument. - if (this._passThroughOptions) { - dest.push(arg); - if (args.length > 0) dest.push(...args); - break; - } +${iteration === 1 ? 'You are starting your analysis. Begin by understanding the question and identifying what files or areas of the codebase might be relevant.' : `You have been analyzing this problem through ${iteration - 1} previous iterations.`} - // add arg - dest.push(arg); - } +${stepsSummary} - return { operands, unknown }; - } +${codeStats.totalChanges > 0 ? `\n\n## āš ļø CODE STATE: ${codeStats.totalChanges} changes have been applied to ${codeStats.modifiedFiles} files\n\n${codeStateInfo}\n\n**IMPORTANT**: When you read files, you will see the MODIFIED version with all previous changes applied. Build upon this modified code, don't repeat changes that have already been made.` : ''} - /** - * Return an object containing local option values as key-value pairs. - * - * @return {object} - */ - opts() { - if (this._storeOptionsAsProperties) { - // Preserve original behaviour so backwards compatible when still using properties - const result = {}; - const len = this.options.length; +${analyzedFilesSummary} - for (let i = 0; i < len; i++) { - const key = this.options[i].attributeName(); - result[key] = - key === this._versionOptionName ? this._version : this[key]; - } - return result; - } +${iteration > 1 ? `\n\n## Previous Iteration Context:\n${currentContext.substring(0, 4000)}${currentContext.length > 4000 ? '\n... (truncated for brevity)' : ''}` : ''} - return this._optionValues; - } +${fileListSummary} - /** - * Return an object containing merged local and global option values as key-value pairs. - * - * @return {object} - */ - optsWithGlobals() { - // globals overwrite locals - return this._getCommandAndAncestors().reduce( - (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), - {}, - ); - } +## Your Analysis Approach - /** - * Display error message and exit (or call exitOverride). - * - * @param {string} message - * @param {object} [errorOptions] - * @param {string} [errorOptions.code] - an id string representing the error - * @param {number} [errorOptions.exitCode] - used with process.exit - */ - error(message, errorOptions) { - // output handling - this._outputConfiguration.outputError( - `${message}\n`, - this._outputConfiguration.writeErr, - ); - if (typeof this._showHelpAfterError === 'string') { - this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`); - } else if (this._showHelpAfterError) { - this._outputConfiguration.writeErr('\n'); - this.outputHelp({ error: true }); - } +1. **search_files**: Use when you need to find files by name, pattern, or path. Be specific. AVOID searching for the same terms repeatedly. +2. **read_file**: Use when you need to examine specific files. The files you read will show the CURRENT STATE (with all applied changes from previous steps). +3. **analyze_code**: Use when you've read files and want to document findings. Focus on understanding relationships and dependencies. +4. **propose_changes**: Use when you have enough context. **CRITICAL**: Only propose NEW changes that build upon what's already been done. Don't repeat changes that were already applied. +5. **update_todos** (or include with other actions): + - Create TODOs ONLY in your first iteration to break down the problem + - Update TODO status when you START working on it (in_progress) or COMPLETE it (completed) + - **IMPORTANT**: Use the EXACT TODO ID from the list above (e.g., "todo_1"), NOT numeric IDs + - Include todo_updates in the SAME response where you do the actual work +6. **complete**: Use when your analysis is finished and you have a comprehensive understanding. All TODOs should be completed or cancelled. - // exit handling - const config = errorOptions || {}; - const exitCode = config.exitCode || 1; - const code = config.code || 'commander.error'; - this._exit(exitCode, code, message); - } +## Critical Instructions - /** - * Apply any option related environment variables, if option does - * not have a value from cli or client code. - * - * @private - */ - _parseOptionsEnv() { - this.options.forEach((option) => { - if (option.envVar && option.envVar in process.env) { - const optionKey = option.attributeName(); - // Priority check. Do not overwrite cli or options from unknown source (client-code). - if ( - this.getOptionValue(optionKey) === undefined || - ['default', 'config', 'env'].includes( - this.getOptionValueSource(optionKey), - ) - ) { - if (option.required || option.optional) { - // option can take a value - // keep very simple, optional always takes value - this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]); - } else { - // boolean - // keep very simple, only care that envVar defined and not the value - this.emit(`optionEnv:${option.name()}`); - } - } - } - }); - } +- **USE TODO LIST CORRECTLY**: + - Create TODOs in iteration 1 to break down the problem into manageable tasks + - **IMPORTANT**: When updating TODOs, you MUST use the EXACT ID shown in the TODO list (e.g., "todo_1", "todo_2"). Do NOT use numeric IDs like "1" or "2" + - Each TODO represents a high-level task that may require multiple reasoning steps (search, read, analyze, propose) + +- **WORK ON TODOS, DON'T JUST UPDATE THEM**: + - When a TODO is "pending" or "in_progress", DO REAL WORK: search for files, read files, analyze code, propose changes + - Only update TODO status when you actually START working on it (mark "in_progress") or COMPLETE it (mark "completed") + - Don't waste iterations just updating TODO status - do the actual work! + +- **TRACK PROGRESS**: + - When you START working on a TODO: mark it "in_progress" AND then do the work (search, read, analyze, propose) + - When you COMPLETE work on a TODO: mark it "completed" + - Update TODOs in the same response where you do the work, don't create separate "update_todos" actions - /** - * Apply any implied option values, if option is undefined or default value. - * - * @private - */ - _parseOptionsImplied() { - const dualHelper = new DualOptions(this.options); - const hasCustomOptionValue = (optionKey) => { - return ( - this.getOptionValue(optionKey) !== undefined && - !['default', 'implied'].includes(this.getOptionValueSource(optionKey)) - ); - }; - this.options - .filter( - (option) => - option.implied !== undefined && - hasCustomOptionValue(option.attributeName()) && - dualHelper.valueFromOption( - this.getOptionValue(option.attributeName()), - option, - ), - ) - .forEach((option) => { - Object.keys(option.implied) - .filter((impliedKey) => !hasCustomOptionValue(impliedKey)) - .forEach((impliedKey) => { - this.setOptionValueWithSource( - impliedKey, - option.implied[impliedKey], - 'implied', - ); - }); - }); - } +- **AVOID REPETITION**: Don't search for the same files repeatedly. Don't propose changes that have already been applied. Don't try to update TODOs with wrong IDs. - /** - * Argument `name` is missing. - * - * @param {string} name - * @private - */ +- **BUILD INCREMENTALLY**: Each step should build upon the previous one. Read files that were modified in previous steps to see the current state. - missingArgument(name) { - const message = `error: missing required argument '${name}'`; - this.error(message, { code: 'commander.missingArgument' }); - } +- **PROGRESS FORWARD**: If you've already analyzed files, move to proposing changes. Don't re-analyze the same code. - /** - * `Option` is missing an argument. - * - * @param {Option} option - * @private - */ +- **SEE THE MODIFIED CODE**: When you read files after changes have been applied, you'll see the modified version. Use this to understand the current state and propose the NEXT logical step. - optionMissingArgument(option) { - const message = `error: option '${option.flags}' argument missing`; - this.error(message, { code: 'commander.optionMissingArgument' }); - } +- **BE SPECIFIC**: When proposing changes, be very specific about what needs to change and provide suggested_code. - /** - * `Option` does not have a value, and is a mandatory option. - * - * @param {Option} option - * @private - */ +- **THINK DEEPLY**: Don't just propose generic changes. Analyze the code structure, dependencies, and relationships before proposing changes. - missingMandatoryOptionValue(option) { - const message = `error: required option '${option.flags}' not specified`; - this.error(message, { code: 'commander.missingMandatoryOptionValue' }); - } +- **FOCUS ON ACTIVE TODOS**: Work on TODOs that are "pending" or "in_progress". Complete them by doing real work, not just updating status. - /** - * `Option` conflicts with another option. - * - * @param {Option} option - * @param {Option} conflictingOption - * @private - */ - _conflictingOption(option, conflictingOption) { - // The calling code does not know whether a negated option is the source of the - // value, so do some work to take an educated guess. - const findBestOptionFromValue = (option) => { - const optionKey = option.attributeName(); - const optionValue = this.getOptionValue(optionKey); - const negativeOption = this.options.find( - (target) => target.negate && optionKey === target.attributeName(), - ); - const positiveOption = this.options.find( - (target) => !target.negate && optionKey === target.attributeName(), - ); - if ( - negativeOption && - ((negativeOption.presetArg === undefined && optionValue === false) || - (negativeOption.presetArg !== undefined && - optionValue === negativeOption.presetArg)) - ) { - return negativeOption; - } - return positiveOption || option; - }; +## Important - const getErrorMessage = (option) => { - const bestOption = findBestOptionFromValue(option); - const optionKey = bestOption.attributeName(); - const source = this.getOptionValueSource(optionKey); - if (source === 'env') { - return `environment variable '${bestOption.envVar}'`; - } - return `option '${bestOption.flags}'`; - }; +- You must return a valid JSON object matching the schema +- Be thorough but efficient - don't request files you don't need +- Build understanding incrementally +- Connect insights across multiple files when relevant +- Each iteration should advance the analysis, not repeat previous steps +- You can include \`todo_updates\` alongside any action (not just when action is 'update_todos') +- When creating TODOs, make them specific and actionable (e.g., "Analyze authentication system" not "Do stuff") +`; + try { + const response = await this.aiRepository.askThinkJson(param.ai, prompt); + return response; + } + catch (error) { + (0, logger_1.logError)(`Error in reasoning step: ${error}`); + return undefined; + } + } + async generateFinalAnalysis(param, question, analyzedFiles, proposedChanges, steps, todoManager) { + const prompt = ` +# Final Analysis Summary - const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`; - this.error(message, { code: 'commander.conflictingOption' }); - } +Based on your analysis of the codebase, provide a comprehensive summary and recommendations. - /** - * Unknown option `flag`. - * - * @param {string} flag - * @private - */ +## User's Question: +${question} - unknownOption(flag) { - if (this._allowUnknownOption) return; - let suggestion = ''; +## Analysis Summary: +- Total steps taken: ${steps.length} +- Files analyzed: ${analyzedFiles.size} +- Proposed changes: ${proposedChanges.length} +- TODO list: ${todoManager.getSummary()} - if (flag.startsWith('--') && this._showSuggestionAfterError) { - // Looping to pick up the global options too - let candidateFlags = []; - // eslint-disable-next-line @typescript-eslint/no-this-alias - let command = this; - do { - const moreFlags = command - .createHelp() - .visibleOptions(command) - .filter((option) => option.long) - .map((option) => option.long); - candidateFlags = candidateFlags.concat(moreFlags); - command = command.parent; - } while (command && !command._enablePositionalOptions); - suggestion = suggestSimilar(flag, candidateFlags); +## Analyzed Files: +${Array.from(analyzedFiles.values()).map(f => `- ${f.path} (${f.relevance}): ${f.key_findings}`).join('\n')} + +## Proposed Changes: +${proposedChanges.map(c => ` +### ${c.change_type.toUpperCase()}: ${c.file_path} +**Description:** ${c.description} +**Reasoning:** ${c.reasoning} +${c.suggested_code ? `**Suggested Code:**\n\`\`\`\n${c.suggested_code}\n\`\`\`` : ''} +`).join('\n')} + +## Steps Taken: +${steps.map(s => `${s.step_number}. ${s.action}: ${s.reasoning.substring(0, 150)}...`).join('\n')} + +Provide a comprehensive final analysis that: +1. Summarizes what you discovered +2. Explains the key insights +3. Provides clear recommendations +4. Describes the proposed changes and their rationale +5. Notes any considerations or potential issues + +Be thorough, clear, and actionable. +`; + const response = await this.aiRepository.ask(param.ai, prompt); + return response || 'Analysis completed. Review the proposed changes and steps above.'; } +} +exports.ThinkUseCase = ThinkUseCase; - const message = `error: unknown option '${flag}'${suggestion}`; - this.error(message, { code: 'commander.unknownOption' }); - } - /** - * Excess arguments, more than expected. - * - * @param {string[]} receivedArgs - * @private - */ +/***/ }), - _excessArguments(receivedArgs) { - if (this._allowExcessArguments) return; +/***/ 5107: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const expected = this.registeredArguments.length; - const s = expected === 1 ? '' : 's'; - const forSubcommand = this.parent ? ` for '${this.name()}'` : ''; - const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; - this.error(message, { code: 'commander.excessArguments' }); - } +"use strict"; - /** - * Unknown command. - * - * @private - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UpdateTitleUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class UpdateTitleUseCase { + constructor() { + this.taskId = 'UpdateTitleUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.isIssue) { + if (param.emoji.emojiLabeledTitle) { + let _title = await this.issueRepository.getTitle(param.owner, param.repo, param.issue.number, param.tokens.token) ?? param.issue.title; + let _version = ''; + if (param.release.active) { + _version = param.release.version ?? 'Unknown Version'; + } + else if (param.hotfix.active) { + _version = param.hotfix.version ?? 'Unknown Version'; + } + const title = await this.issueRepository.updateTitleIssueFormat(param.owner, param.repo, _version, _title, param.issue.number, param.issue.branchManagementAlways, param.emoji.branchManagementEmoji, param.labels, param.tokens.token); + if (title) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The issue's title was updated from \`${_title}\` to \`${title}\`.`, + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + else if (param.isPullRequest) { + if (param.emoji.emojiLabeledTitle) { + const issueTitle = await this.issueRepository.getTitle(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (issueTitle === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update title, but there was a problem.`, + ], + })); + return result; + } + const title = await this.issueRepository.updateTitlePullRequestFormat(param.owner, param.repo, param.pullRequest.title, issueTitle, param.issueNumber, param.pullRequest.number, false, '', param.labels, param.tokens.token); + if (title) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The pull request's title was updated from \`${param.pullRequest.title}\` to \`${title}\`.`, + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update title, but there was a problem.`, + ], + error: error, + })); + } + return result; + } +} +exports.UpdateTitleUseCase = UpdateTitleUseCase; - unknownCommand() { - const unknownName = this.args[0]; - let suggestion = ''; - if (this._showSuggestionAfterError) { - const candidateNames = []; - this.createHelp() - .visibleCommands(this) - .forEach((command) => { - candidateNames.push(command.name()); - // just visible alias - if (command.alias()) candidateNames.push(command.alias()); - }); - suggestion = suggestSimilar(unknownName, candidateNames); +/***/ }), + +/***/ 3115: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AssignMemberToIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class AssignMemberToIssueUseCase { + constructor() { + this.taskId = 'AssignMemberToIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const desiredAssigneesCount = param.isIssue ? + param.issue.desiredAssigneesCount : param.pullRequest.desiredAssigneesCount; + const number = param.isIssue ? param.issue.number : param.pullRequest.number; + const result = []; + try { + (0, logger_1.logDebugInfo)(`#${number} needs ${desiredAssigneesCount} assignees.`); + const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); + const currentMembers = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); + let remainingAssignees = desiredAssigneesCount - currentMembers.length; + const pullRequestCreatorIsTeamMember = param.isPullRequest + && param.pullRequest.creator.length > 0 + && currentProjectMembers.indexOf(param.pullRequest.creator) > -1 + && !currentMembers.includes(param.pullRequest.creator); + const issueCreatorIsTeamMember = param.isIssue + && param.issue.creator.length > 0 + && currentProjectMembers.indexOf(param.issue.creator) > -1 + && !currentMembers.includes(param.issue.creator); + /** + * Assign PR creator if applicable + */ + if (pullRequestCreatorIsTeamMember) { + const creator = param.pullRequest.creator; + await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); + (0, logger_1.logDebugInfo)(`Assigned PR creator @${creator} to #${number}.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`The pull request was assigned to @${creator} (creator).`], + })); + remainingAssignees--; // Reduce the count of required assignees + } + else if (issueCreatorIsTeamMember) { + const creator = param.issue.creator; + await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); + (0, logger_1.logDebugInfo)(`Assigned Issue creator @${creator} to #${number}.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`The issue was assigned to @${creator} (creator).`], + })); + remainingAssignees--; // Reduce the count of required assignees + } + /** + * Exit if no more assignees are needed + */ + if (remainingAssignees <= 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return result; + } + /** + * Assign remaining members randomly + */ + const members = await this.projectRepository.getRandomMembers(param.owner, remainingAssignees, currentMembers, param.tokens.token); + if (members.length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to assign members to issue, but no one was found.`], + })); + return result; + } + const membersAdded = await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, members, param.tokens.token); + for (const member of membersAdded) { + if (members.includes(member)) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + param.isIssue ? `The issue was assigned to @${member}.` : `The pull request was assigned to @${member}.`, + ], + })); + } + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to assign members to issue.`], + error: error, + })); + } + return result; } +} +exports.AssignMemberToIssueUseCase = AssignMemberToIssueUseCase; - const message = `error: unknown command '${unknownName}'${suggestion}`; - this.error(message, { code: 'commander.unknownCommand' }); - } - /** - * Get or set the program version. - * - * This method auto-registers the "-V, --version" option which will print the version number. - * - * You can optionally supply the flags and description to override the defaults. - * - * @param {string} [str] - * @param {string} [flags] - * @param {string} [description] - * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments - */ +/***/ }), - version(str, flags, description) { - if (str === undefined) return this._version; - this._version = str; - flags = flags || '-V, --version'; - description = description || 'output the version number'; - const versionOption = this.createOption(flags, description); - this._versionOptionName = versionOption.attributeName(); - this._registerOption(versionOption); +/***/ 6275: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.on('option:' + versionOption.name(), () => { - this._outputConfiguration.writeOut(`${str}\n`); - this._exit(0, 'commander.version', str); - }); - return this; - } +"use strict"; - /** - * Set the description. - * - * @param {string} [str] - * @param {object} [argsDescription] - * @return {(string|Command)} - */ - description(str, argsDescription) { - if (str === undefined && argsDescription === undefined) - return this._description; - this._description = str; - if (argsDescription) { - this._argsDescription = argsDescription; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AssignReviewersToIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const pull_request_repository_1 = __nccwpck_require__(634); +const logger_1 = __nccwpck_require__(8836); +class AssignReviewersToIssueUseCase { + constructor() { + this.taskId = 'AssignReviewersToIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); } - return this; - } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const desiredReviewersCount = param.pullRequest.desiredReviewersCount; + const number = param.pullRequest.number; + const result = []; + try { + (0, logger_1.logDebugInfo)(`#${number} needs ${desiredReviewersCount} reviewers.`); + const currentReviewers = await this.pullRequestRepository.getCurrentReviewers(param.owner, param.repo, number, param.tokens.token); + const currentAssignees = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); + if (currentReviewers.length >= desiredReviewersCount) { + /** + * No more assignees needed + */ + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return result; + } + const missingReviewers = desiredReviewersCount - currentReviewers.length; + (0, logger_1.logDebugInfo)(`#${number} needs ${missingReviewers} more reviewers.`); + const excludeForReview = []; + excludeForReview.push(param.pullRequest.creator); + excludeForReview.push(...currentReviewers); + excludeForReview.push(...currentAssignees); + const members = await this.projectRepository.getRandomMembers(param.owner, missingReviewers, excludeForReview, param.tokens.token); + if (members.length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to assign members as reviewers to pull request, but no one was found.`, + ], + })); + return result; + } + const reviewersAdded = await this.pullRequestRepository.addReviewersToPullRequest(param.owner, param.repo, number, members, param.tokens.token); + for (const member of reviewersAdded) { + if (members.indexOf(member) > -1) + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `@${member} was requested to review the pull request.`, + ], + })); + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to assign members to issue.`, + ], + error: error, + })); + } + return result; + } +} +exports.AssignReviewersToIssueUseCase = AssignReviewersToIssueUseCase; - /** - * Set the summary. Used when listed as subcommand of parent. - * - * @param {string} [str] - * @return {(string|Command)} - */ - summary(str) { - if (str === undefined) return this._summary; - this._summary = str; - return this; - } - /** - * Set an alias for the command. - * - * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. - * - * @param {string} [alias] - * @return {(string|Command)} - */ +/***/ }), - alias(alias) { - if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility +/***/ 151: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** @type {Command} */ - // eslint-disable-next-line @typescript-eslint/no-this-alias - let command = this; - if ( - this.commands.length !== 0 && - this.commands[this.commands.length - 1]._executableHandler - ) { - // assume adding alias for last added executable subcommand, rather than this - command = this.commands[this.commands.length - 1]; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPriorityIssueSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckPriorityIssueSizeUseCase { + constructor() { + this.taskId = 'CheckPriorityIssueSizeUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const priority = param.labels.priorityLabelOnIssue; + if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + let priorityLabel = ``; + if (priority === param.labels.priorityHigh) { + priorityLabel = `P0`; + } + else if (priority === param.labels.priorityMedium) { + priorityLabel = `P1`; + } + else if (priority === param.labels.priorityLow) { + priorityLabel = `P2`; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + (0, logger_1.logDebugInfo)(`Priority: ${priority}`); + (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); + for (const project of param.project.getProjects()) { + const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.issueNumber, priorityLabel, param.tokens.token); + if (success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, + ], + })); + } + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the priority of the issue, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } +} +exports.CheckPriorityIssueSizeUseCase = CheckPriorityIssueSizeUseCase; - if (alias === command._name) - throw new Error("Command alias can't be the same as its name"); - const matchingCommand = this.parent?._findCommand(alias); - if (matchingCommand) { - // c.f. _registerCommand - const existingCmd = [matchingCommand.name()] - .concat(matchingCommand.aliases()) - .join('|'); - throw new Error( - `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`, - ); - } - command._aliases.push(alias); - return this; - } +/***/ }), - /** - * Set aliases for the command. - * - * Only the first alias is shown in the auto-generated help. - * - * @param {string[]} [aliases] - * @return {(string[]|Command)} - */ +/***/ 5137: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - aliases(aliases) { - // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). - if (aliases === undefined) return this._aliases; +"use strict"; - aliases.forEach((alias) => this.alias(alias)); - return this; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloseIssueAfterMergingUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const supabase_repository_1 = __nccwpck_require__(9829); +const logger_1 = __nccwpck_require__(8836); +class CloseIssueAfterMergingUseCase { + constructor() { + this.taskId = 'CloseIssueAfterMergingUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.removeBranches = async (supabaseRepository, param, branch) => { + const result = []; + if (!supabaseRepository) { + return result; + } + try { + await supabaseRepository.removeAIFileCacheByBranch(param.owner, param.repo, branch); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `AI index was removed from \`${branch}\`.`, + ] + })); + } + catch (error) { + (0, logger_1.logError)(`Error removing AI cache: ${JSON.stringify(error, null, 2)}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `There was an error removing the AI index from \`${branch}\`.`, + ], + errors: [ + JSON.stringify(error, null, 2), + ], + })); + } + return result; + }; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + let supabaseRepository = undefined; + if (param.supabaseConfig) { + supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + } + const result = []; + try { + const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (closed) { + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was closed after merging #${param.pullRequest.number}.`, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `#${param.issueNumber} was automatically closed after merging this pull request.` + ] + })); + result.push(...await this.removeBranches(supabaseRepository, param, param.pullRequest.head.replace('refs/heads/', ''))); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to close issue #${param.issueNumber}, but there was a problem.`, + ], + error: error, + })); + } + return result; + } +} +exports.CloseIssueAfterMergingUseCase = CloseIssueAfterMergingUseCase; - /** - * Set / get the command usage `str`. - * - * @param {string} [str] - * @return {(string|Command)} - */ - usage(str) { - if (str === undefined) { - if (this._usage) return this._usage; +/***/ }), - const args = this.registeredArguments.map((arg) => { - return humanReadableArgName(arg); - }); - return [] - .concat( - this.options.length || this._helpOption !== null ? '[options]' : [], - this.commands.length ? '[command]' : [], - this.registeredArguments.length ? args : [], - ) - .join(' '); +/***/ 7826: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloseNotAllowedIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class CloseNotAllowedIssueUseCase { + constructor() { + this.taskId = 'CloseNotAllowedIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (closed) { + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue has been closed because the author is not a member of the project. The user may be banned if the fact is repeated.`, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `#${param.issueNumber} was automatically closed because the author is not a member of the project.` + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to close issue #${param.issueNumber}, but there was a problem.`, + ], + error: error, + })); + } + return result; } +} +exports.CloseNotAllowedIssueUseCase = CloseNotAllowedIssueUseCase; - this._usage = str; - return this; - } - /** - * Get or set the name of the command. - * - * @param {string} [str] - * @return {(string|Command)} - */ +/***/ }), - name(str) { - if (str === undefined) return this._name; - this._name = str; - return this; - } +/***/ 5678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Set the name of the command from script filename, such as process.argv[1], - * or require.main.filename, or __filename. - * - * (Used internally and public although not documented in README.) - * - * @example - * program.nameFromFilename(require.main.filename); - * - * @param {string} filename - * @return {Command} - */ +"use strict"; - nameFromFilename(filename) { - this._name = path.basename(filename, path.extname(filename)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DeployAddedUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class DeployAddedUseCase { + constructor() { + this.taskId = 'DeployAddedUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.issue.labeled && param.issue.labelAdded === param.labels.deploy) { + (0, logger_1.logDebugInfo)(`Deploying requested.`); + if (param.release.active && param.release.branch !== undefined) { + const sanitizedTitle = param.issue.title + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + const description = param.issue.body?.match(/### Changelog\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; + const escapedDescription = description.replace(/\n/g, '\\n'); + const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; + const parameters = { + version: param.release.version, + title: sanitizedTitle, + changelog: escapedDescription, + issue: `${param.issue.number}`, + }; + await this.branchRepository.executeWorkflow(param.owner, param.repo, param.release.branch, param.workflows.release, parameters, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Executed release workflow [**${param.workflows.release}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.release}) on [**${param.release.branch}**](${releaseUrl}). - return this; - } +${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}` + ] + })); + } + else if (param.hotfix.active && param.hotfix.branch !== undefined) { + const sanitizedTitle = param.issue.title + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + const description = param.issue.body?.match(/### Hotfix Solution\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; + const escapedDescription = description.replace(/\n/g, '\\n'); + const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; + const parameters = { + version: param.hotfix.version, + title: sanitizedTitle, + changelog: escapedDescription, + issue: param.issue.number, + }; + await this.branchRepository.executeWorkflow(param.owner, param.repo, param.hotfix.branch, param.workflows.release, parameters, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Executed hotfix workflow [**${param.workflows.hotfix}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.hotfix}) on [**${param.hotfix.branch}**](${hotfixUrl}). - /** - * Get or set the directory for searching for executable subcommands of this command. - * - * @example - * program.executableDir(__dirname); - * // or - * program.executableDir('subcommands'); - * - * @param {string} [path] - * @return {(string|null|Command)} - */ +${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}\`` + ] + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to work with workflows, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; + } +} +exports.DeployAddedUseCase = DeployAddedUseCase; - executableDir(path) { - if (path === undefined) return this._executableDir; - this._executableDir = path; - return this; - } - /** - * Return program help documentation. - * - * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout - * @return {string} - */ +/***/ }), - helpInformation(contextOptions) { - const helper = this.createHelp(); - if (helper.helpWidth === undefined) { - helper.helpWidth = - contextOptions && contextOptions.error - ? this._outputConfiguration.getErrHelpWidth() - : this._outputConfiguration.getOutHelpWidth(); - } - return helper.formatHelp(this, helper); - } +/***/ 8388: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * @private - */ +"use strict"; - _getHelpContext(contextOptions) { - contextOptions = contextOptions || {}; - const context = { error: !!contextOptions.error }; - let write; - if (context.error) { - write = (arg) => this._outputConfiguration.writeErr(arg); - } else { - write = (arg) => this._outputConfiguration.writeOut(arg); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DeployedAddedUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +class DeployedAddedUseCase { + constructor() { + this.taskId = 'DeployedAddedUseCase'; } - context.write = contextOptions.write || write; - context.command = this; - return context; - } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.issue.labeled && param.issue.labelAdded === param.labels.deployed) { + (0, logger_1.logDebugInfo)(`Deploy complete.`); + if (param.release.active && param.release.branch !== undefined) { + const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Deploy complete from [${param.release.branch}](${releaseUrl})` + ] + })); + } + else if (param.hotfix.active && param.hotfix.branch !== undefined) { + const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Deploy complete from [${param.hotfix.branch}](${hotfixUrl})` + ] + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to complete the deployment, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; + } +} +exports.DeployedAddedUseCase = DeployedAddedUseCase; - /** - * Output help information for this command. - * - * Outputs built-in help, and custom text added using `.addHelpText()`. - * - * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout - */ - outputHelp(contextOptions) { - let deprecatedCallback; - if (typeof contextOptions === 'function') { - deprecatedCallback = contextOptions; - contextOptions = undefined; - } - const context = this._getHelpContext(contextOptions); +/***/ }), - this._getCommandAndAncestors() - .reverse() - .forEach((command) => command.emit('beforeAllHelp', context)); - this.emit('beforeHelp', context); +/***/ 7528: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let helpInformation = this.helpInformation(context); - if (deprecatedCallback) { - helpInformation = deprecatedCallback(helpInformation); - if ( - typeof helpInformation !== 'string' && - !Buffer.isBuffer(helpInformation) - ) { - throw new Error('outputHelp callback must return a string or a Buffer'); - } - } - context.write(helpInformation); +"use strict"; - if (this._getHelpOption()?.long) { - this.emit(this._getHelpOption().long); // deprecated +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LinkIssueProjectUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class LinkIssueProjectUseCase { + constructor() { + this.taskId = 'LinkIssueProjectUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + const columnName = param.project.getProjectColumnIssueCreated(); + try { + for (const project of param.project.getProjects()) { + const issueId = await this.issueRepository.getId(param.owner, param.repo, param.issue.number, param.tokens.token); + let actionDone = await this.projectRepository.linkContentId(project, issueId, param.tokens.token); + if (actionDone) { + /** + * Wait for 10 seconds to ensure the issue is linked to the project + */ + await new Promise(resolve => setTimeout(resolve, 10000)); + actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issue.number, columnName, param.tokens.token); + if (actionDone) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The issue was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + steps: [] + })); + } + } + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to link issue to project, but there was a problem.`, + ], + error: error, + })); + } + return result; } - this.emit('afterHelp', context); - this._getCommandAndAncestors().forEach((command) => - command.emit('afterAllHelp', context), - ); - } +} +exports.LinkIssueProjectUseCase = LinkIssueProjectUseCase; - /** - * You can pass in flags and a description to customise the built-in help option. - * Pass in false to disable the built-in help option. - * - * @example - * program.helpOption('-?, --help' 'show help'); // customise - * program.helpOption(false); // disable - * - * @param {(string | boolean)} flags - * @param {string} [description] - * @return {Command} `this` command for chaining - */ - helpOption(flags, description) { - // Support disabling built-in help option. - if (typeof flags === 'boolean') { - if (flags) { - this._helpOption = this._helpOption ?? undefined; // preserve existing option - } else { - this._helpOption = null; // disable - } - return this; - } +/***/ }), - // Customise flags and description. - flags = flags ?? '-h, --help'; - description = description ?? 'display help for command'; - this._helpOption = this.createOption(flags, description); +/***/ 8203: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this; - } +"use strict"; - /** - * Lazy create help option. - * Returns null if has been disabled with .helpOption(false). - * - * @returns {(Option | null)} the help option - * @package - */ - _getHelpOption() { - // Lazy create help option on demand. - if (this._helpOption === undefined) { - this.helpOption(undefined, undefined); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MoveIssueToInProgressUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class MoveIssueToInProgressUseCase { + constructor() { + this.taskId = 'MoveIssueToInProgressUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); } - return this._helpOption; - } - - /** - * Supply your own option to use for the built-in help option. - * This is an alternative to using helpOption() to customise the flags and description etc. - * - * @param {Option} option - * @return {Command} `this` command for chaining - */ - addHelpOption(option) { - this._helpOption = option; - return this; - } - - /** - * Output help information and exit. - * - * Outputs built-in help, and custom text added using `.addHelpText()`. - * - * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout - */ - - help(contextOptions) { - this.outputHelp(contextOptions); - let exitCode = process.exitCode || 0; - if ( - exitCode === 0 && - contextOptions && - typeof contextOptions !== 'function' && - contextOptions.error - ) { - exitCode = 1; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + const columnName = param.project.getProjectColumnIssueInProgress(); + try { + for (const project of param.project.getProjects()) { + const success = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issueNumber, columnName, param.tokens.token); + if (success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Moved issue to \`${columnName}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, + ], + })); + } + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to move the issue to \`${columnName}\`, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } - // message: do not have all displayed text available so only passing placeholder. - this._exit(exitCode, 'commander.help', '(outputHelp)'); - } +} +exports.MoveIssueToInProgressUseCase = MoveIssueToInProgressUseCase; - /** - * Add additional text to be displayed with the built-in help. - * - * Position is 'before' or 'after' to affect just this command, - * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. - * - * @param {string} position - before or after built-in help - * @param {(string | Function)} text - string to add, or a function returning a string - * @return {Command} `this` command for chaining - */ - addHelpText(position, text) { - const allowedValues = ['beforeAll', 'before', 'after', 'afterAll']; - if (!allowedValues.includes(position)) { - throw new Error(`Unexpected value for position to addHelpText. -Expecting one of '${allowedValues.join("', '")}'`); - } - const helpEvent = `${position}Help`; - this.on(helpEvent, (context) => { - let helpStr; - if (typeof text === 'function') { - helpStr = text({ error: context.error, command: context.command }); - } else { - helpStr = text; - } - // Ignore falsy value when nothing to output. - if (helpStr) { - context.write(`${helpStr}\n`); - } - }); - return this; - } - /** - * Output help information if help flags specified - * - * @param {Array} args - array of options to search for help flags - * @private - */ +/***/ }), - _outputHelpIfRequested(args) { - const helpOption = this._getHelpOption(); - const helpRequested = helpOption && args.find((arg) => helpOption.is(arg)); - if (helpRequested) { - this.outputHelp(); - // (Do not have all displayed text available so only passing placeholder.) - this._exit(0, 'commander.helpDisplayed', '(outputHelp)'); - } - } -} +/***/ 4423: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -/** - * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). - * - * @param {string[]} args - array of arguments from node.execArgv - * @returns {string[]} - * @private - */ +"use strict"; -function incrementNodeInspectorPort(args) { - // Testing for these options: - // --inspect[=[host:]port] - // --inspect-brk[=[host:]port] - // --inspect-port=[host:]port - return args.map((arg) => { - if (!arg.startsWith('--inspect')) { - return arg; +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]; } }; } - let debugOption; - let debugHost = '127.0.0.1'; - let debugPort = '9229'; - let match; - if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { - // e.g. --inspect - debugOption = match[1]; - } else if ( - (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null - ) { - debugOption = match[1]; - if (/^\d+$/.test(match[3])) { - // e.g. --inspect=1234 - debugPort = match[3]; - } else { - // e.g. --inspect=localhost - debugHost = match[3]; - } - } else if ( - (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null - ) { - // e.g. --inspect=localhost:1234 - debugOption = match[1]; - debugHost = match[3]; - debugPort = match[4]; + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PrepareBranchesUseCase = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const supabase_repository_1 = __nccwpck_require__(9829); +const logger_1 = __nccwpck_require__(8836); +const execute_script_use_case_1 = __nccwpck_require__(155); +const move_issue_to_in_progress_1 = __nccwpck_require__(8203); +class PrepareBranchesUseCase { + constructor() { + this.taskId = 'PrepareBranchesUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + this.duplicateAICacheByBranch = async (supabaseRepository, param, sourceBranch, targetBranch) => { + const result = []; + if (!supabaseRepository) { + return result; + } + try { + await supabaseRepository.duplicateAIFileCacheByBranch(param.owner, param.repo, sourceBranch, targetBranch); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `AI index was duplicated from \`${sourceBranch}\` to \`${targetBranch}\`.`, + ] + })); + } + catch (error) { + (0, logger_1.logError)(`Error duplicating AI cache: ${JSON.stringify(error, null, 2)}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `There was an error duplicating the AI index from \`${sourceBranch}\` to \`${targetBranch}\`.`, + ], + errors: [ + JSON.stringify(error, null, 2), + ], + })); + } + return result; + }; } - - if (debugOption && debugPort !== '0') { - return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + let supabaseRepository = undefined; + if (param.supabaseConfig) { + supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + } + const result = []; + try { + const issueTitle = param.issue.title; + if (!param.labels.isMandatoryBranchedLabel && issueTitle.length === 0) { + core.setFailed('Issue title not available.'); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + reminders: [ + `Tried to check the title but no one was found.` + ] + })); + return result; + } + /** + * Fetch all branches/tags + */ + await this.branchRepository.fetchRemoteBranches(); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `Take a coffee break while you work ā˜•.` + ] + })); + const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); + (0, logger_1.logDebugInfo)('Available branches:'); + branches.forEach(branch => { + (0, logger_1.logDebugInfo)(`- ${branch}`); + }); + if (param.hotfix.active) { + if (param.hotfix.baseVersion !== undefined && param.hotfix.version !== undefined && param.hotfix.branch !== undefined && param.hotfix.baseBranch !== undefined) { + const branchOid = await this.branchRepository.getCommitTag(param.hotfix.baseVersion); + const tagUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.baseBranch}`; + const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; + (0, logger_1.logDebugInfo)(`Tag branch: ${param.hotfix.baseBranch}`); + (0, logger_1.logDebugInfo)(`Hotfix branch: ${param.hotfix.branch}`); + param.currentConfiguration.parentBranch = param.hotfix.baseBranch; + param.currentConfiguration.hotfixBranch = param.hotfix.branch; + param.currentConfiguration.workingBranch = param.hotfix.branch; + if (branches.indexOf(param.hotfix.branch) === -1) { + const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.hotfix.baseBranch, param.hotfix.branch, param.issueNumber, branchOid, param.tokens.token); + if (linkResult[linkResult.length - 1].success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The tag [**${param.hotfix.baseBranch}**](${tagUrl}) was used to create the branch [**${param.hotfix.branch}**](${hotfixUrl})`, + ], + })); + (0, logger_1.logDebugInfo)(`Hotfix branch successfully linked to issue: ${JSON.stringify(linkResult)}`); + result.push(...await this.duplicateAICacheByBranch(supabaseRepository, param, param.branches.main, param.hotfix.branch)); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch [**${param.hotfix.branch}**](${hotfixUrl}) already exists and will not be created from the tag [**${param.hotfix.baseBranch}**](${tagUrl}).`, + ], + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to create a hotfix but no tag was found.`, + ] + })); + return result; + } + } + else if (param.release.active) { + if (param.release.version !== undefined && param.release.branch !== undefined) { + param.currentConfiguration.releaseBranch = param.release.branch; + param.currentConfiguration.workingBranch = param.release.branch; + (0, logger_1.logDebugInfo)(`Release branch: ${param.release.branch}`); + param.currentConfiguration.parentBranch = param.branches.development; + const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; + const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; + const mainUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.defaultBranch}`; + if (branches.indexOf(param.release.branch) === -1) { + const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.branches.development, param.release.branch, param.issueNumber, undefined, param.tokens.token); + const lastAction = linkResult[linkResult.length - 1]; + const reminders = []; + if (lastAction.success) { + const branchName = lastAction.payload.newBranchName; + let commitPrefix = ''; + if (param.commitPrefixBuilder.length > 0) { + param.commitPrefixBuilderParams = { + branchName: branchName, + }; + const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); + const prefixResult = await executor.invoke(param); + commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; + } + reminders.push(`Before deploying, apply any change needed in [**${param.release.branch}**](${releaseUrl}): +> \`\`\`bash +> git fetch -v && git checkout ${param.release.branch} +> \`\`\` +> +> Version files, changelogs..`); + if (commitPrefix.length > 0) { + reminders.push(`Commit the needed changes with this prefix: +> \`\`\` +>${commitPrefix} +> \`\`\``); + } + reminders.push(...[ + `Create the tag version in [**${param.release.branch}**](${releaseUrl}). +> Avoid using \`git merge --squash\`, otherwise the created tag will be lost.`, + `Add the **${param.labels.deploy}** label to run the \`${param.workflows.release}\` workflow.`, + `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). +> **Quick actions:** +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, + ]); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch [**${param.branches.development}**](${developmentUrl}) was used to create the branch [**${param.release.branch}**](${releaseUrl})`, + ], + reminders: reminders, + })); + (0, logger_1.logDebugInfo)(`Release branch successfully linked to issue: ${JSON.stringify(linkResult)}`); + result.push(...await this.duplicateAICacheByBranch(supabaseRepository, param, param.branches.development, param.release.branch)); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). +> **Quick actions:** +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, + ], + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to create a release but no release version was found.`, + ] + })); + } + return result; + } + (0, logger_1.logDebugInfo)(`Branch type: ${param.managementBranch}`); + const branchesResult = await this.branchRepository.manageBranches(param, param.owner, param.repo, param.issueNumber, issueTitle, param.managementBranch, param.branches.development, param.hotfix?.branch, param.hotfix.active, param.tokens.token); + result.push(...branchesResult); + const lastAction = branchesResult[branchesResult.length - 1]; + if (lastAction.success && lastAction.executed) { + const branchName = lastAction.payload.newBranchName; + param.currentConfiguration.workingBranch = branchName; + let commitPrefix = ''; + if (param.commitPrefixBuilder.length > 0) { + param.commitPrefixBuilderParams = { + branchName: branchName, + }; + const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); + const prefixResult = await executor.invoke(param); + commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; + } + const rename = lastAction.payload.baseBranchName.indexOf(`${param.branches.featureTree}/`) > -1 + || lastAction.payload.baseBranchName.indexOf(`${param.branches.bugfixTree}/`) > -1; + let step; + let reminder; + if (rename) { + const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; + step = `The branch **${lastAction.payload.baseBranchName}** was renamed to [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; + reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${param.branches.development}\`](${developmentUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${lastAction.payload.newBranchName}?expand=1)`; + } + else { + step = `The branch [**${lastAction.payload.baseBranchName}**](${lastAction.payload.baseBranchUrl}) was used to create [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; + reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${lastAction.payload.baseBranchName}...${lastAction.payload.newBranchName}?expand=1)`; + } + const reminders = []; + reminders.push(`Check out the branch: +> \`\`\`bash +> git fetch -v && git checkout ${lastAction.payload.newBranchName} +> \`\`\``); + if (commitPrefix.length > 0) { + reminders.push(`Commit the needed changes with this prefix: +> \`\`\` +>${commitPrefix} +> \`\`\``); + } + reminders.push(reminder); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + step, + ], + reminders: reminders, + })); + if (param.hotfix.active) { + const mainBranchUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.main}`; + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `After merging into [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}), open a Pull Request from [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}) to [\`${param.branches.main}\`](${mainBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${lastAction.payload.baseBranchName}?expand=1)`, + `After merging into [\`${param.branches.main}\`](${mainBranchUrl}), create the tag \`${param.hotfix.version}\`.`, + ] + })); + } + result.push(...await this.duplicateAICacheByBranch(supabaseRepository, param, param.branches.development, lastAction.payload.newBranchName)); + await new Promise(resolve => setTimeout(resolve, 10000)); + result.push(...await new move_issue_to_in_progress_1.MoveIssueToInProgressUseCase().invoke(param)); + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to prepare the hotfix branch to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; } - return arg; - }); } - -exports.Command = Command; +exports.PrepareBranchesUseCase = PrepareBranchesUseCase; /***/ }), -/***/ 12625: -/***/ ((__unused_webpack_module, exports) => { +/***/ 2354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * CommanderError class - */ -class CommanderError extends Error { - /** - * Constructs the CommanderError class - * @param {number} exitCode suggested exit code which could be used with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - */ - constructor(exitCode, code, message) { - super(message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.code = code; - this.exitCode = exitCode; - this.nestedError = undefined; - } -} +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RemoveIssueBranchesUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const logger_1 = __nccwpck_require__(8836); /** - * InvalidArgumentError class + * Remove any branch created for this issue */ -class InvalidArgumentError extends CommanderError { - /** - * Constructs the InvalidArgumentError class - * @param {string} [message] explanation of why argument is invalid - */ - constructor(message) { - super(1, 'commander.invalidArgument', message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - } +class RemoveIssueBranchesUseCase { + constructor() { + this.taskId = 'RemoveIssueBranchesUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; + const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); + for (const type of branchTypes) { + (0, logger_1.logDebugInfo)(`Checking branch type ${type}`); + let branchName = ''; + const prefix = `${type}/${param.issueNumber}-`; + (0, logger_1.logDebugInfo)(`Checking prefix ${prefix}`); + const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); + if (!matchingBranch) + continue; + branchName = matchingBranch; + const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); + if (removed) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch \`${branchName}\` was removed.`, + ], + })); + if (param.previousConfiguration?.branchType === param.branches.hotfixTree) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `Determine if the \`${param.branches.hotfixTree}\` branch is no longer required and can be removed.`, + ], + })); + } + } + } + } + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update issue's title, but there was a problem.`, + ], + error: error, + })); + } + return results; + } } - -exports.CommanderError = CommanderError; -exports.InvalidArgumentError = InvalidArgumentError; +exports.RemoveIssueBranchesUseCase = RemoveIssueBranchesUseCase; /***/ }), -/***/ 5153: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -const { humanReadableArgName } = __nccwpck_require__(69414); - -/** - * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS` - * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types - * @typedef { import("./argument.js").Argument } Argument - * @typedef { import("./command.js").Command } Command - * @typedef { import("./option.js").Option } Option - */ - -// Although this is a class, methods are static in style to allow override using subclass or just functions. -class Help { - constructor() { - this.helpWidth = undefined; - this.sortSubcommands = false; - this.sortOptions = false; - this.showGlobalOptions = false; - } +/***/ 773: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - /** - * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. - * - * @param {Command} cmd - * @returns {Command[]} - */ +"use strict"; - visibleCommands(cmd) { - const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden); - const helpCommand = cmd._getHelpCommand(); - if (helpCommand && !helpCommand._hidden) { - visibleCommands.push(helpCommand); - } - if (this.sortSubcommands) { - visibleCommands.sort((a, b) => { - // @ts-ignore: because overloaded return type - return a.name().localeCompare(b.name()); - }); +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]; } }; } - return visibleCommands; - } - - /** - * Compare options for sort. - * - * @param {Option} a - * @param {Option} b - * @returns {number} - */ - compareOptions(a, b) { - const getSortKey = (option) => { - // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated. - return option.short - ? option.short.replace(/^-/, '') - : option.long.replace(/^--/, ''); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); }; - return getSortKey(a).localeCompare(getSortKey(b)); - } - - /** - * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. - * - * @param {Command} cmd - * @returns {Option[]} - */ - - visibleOptions(cmd) { - const visibleOptions = cmd.options.filter((option) => !option.hidden); - // Built-in help option. - const helpOption = cmd._getHelpOption(); - if (helpOption && !helpOption.hidden) { - // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs. - const removeShort = helpOption.short && cmd._findOption(helpOption.short); - const removeLong = helpOption.long && cmd._findOption(helpOption.long); - if (!removeShort && !removeLong) { - visibleOptions.push(helpOption); // no changes needed - } else if (helpOption.long && !removeLong) { - visibleOptions.push( - cmd.createOption(helpOption.long, helpOption.description), - ); - } else if (helpOption.short && !removeShort) { - visibleOptions.push( - cmd.createOption(helpOption.short, helpOption.description), - ); - } + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RemoveNotNeededBranchesUseCase = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const logger_1 = __nccwpck_require__(8836); +class RemoveNotNeededBranchesUseCase { + constructor() { + this.taskId = 'RemoveNotNeededBranchesUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); } - if (this.sortOptions) { - visibleOptions.sort(this.compareOptions); + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const issueTitle = param.issue.title; + if (issueTitle.length === 0) { + core.setFailed('Issue title not available.'); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Tried to remove not needed branches related to the issue, but the issue title was not found.`, + ], + })); + return result; + } + const sanitizedTitle = this.branchRepository.formatBranchName(issueTitle, param.issueNumber); + const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); + const finalBranch = `${param.managementBranch}/${param.issueNumber}-${sanitizedTitle}`; + const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; + for (const type of branchTypes) { + let branchName = `${type}/${param.issueNumber}-${sanitizedTitle}`; + const prefix = `${type}/${param.issueNumber}-`; + if (type !== param.managementBranch) { + const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); + if (!matchingBranch) { + continue; + } + branchName = matchingBranch; + const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); + if (removed) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch \`${branchName}\` was removed.`, + ], + })); + } + else { + (0, logger_1.logError)(`Error deleting ${branchName}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to remove not needed branch \`${branchName}\`, but there was a problem.`, + ], + })); + } + } + else { + for (const branch of branches) { + if (branch.indexOf(prefix) > -1 && branch !== finalBranch) { + const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branch, param.tokens.token); + if (removed) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch \`${branch}\` was removed.`, + ], + })); + } + else { + (0, logger_1.logError)(`Error deleting ${branch}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to remove not needed branch \`${branch}\`, but there was a problem.`, + ], + })); + } + } + } + } + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to remove not needed branches related to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; } - return visibleOptions; - } +} +exports.RemoveNotNeededBranchesUseCase = RemoveNotNeededBranchesUseCase; - /** - * Get an array of the visible global options. (Not including help.) - * - * @param {Command} cmd - * @returns {Option[]} - */ - visibleGlobalOptions(cmd) { - if (!this.showGlobalOptions) return []; +/***/ }), - const globalOptions = []; - for ( - let ancestorCmd = cmd.parent; - ancestorCmd; - ancestorCmd = ancestorCmd.parent - ) { - const visibleOptions = ancestorCmd.options.filter( - (option) => !option.hidden, - ); - globalOptions.push(...visibleOptions); - } - if (this.sortOptions) { - globalOptions.sort(this.compareOptions); - } - return globalOptions; - } +/***/ 1652: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Get an array of the arguments if any have a description. - * - * @param {Command} cmd - * @returns {Argument[]} - */ +"use strict"; - visibleArguments(cmd) { - // Side effect! Apply the legacy descriptions before the arguments are displayed. - if (cmd._argsDescription) { - cmd.registeredArguments.forEach((argument) => { - argument.description = - argument.description || cmd._argsDescription[argument.name()] || ''; - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UpdateIssueTypeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class UpdateIssueTypeUseCase { + constructor() { + this.taskId = 'UpdateIssueTypeUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); } - - // If there are any arguments with a description then return all the arguments. - if (cmd.registeredArguments.find((argument) => argument.description)) { - return cmd.registeredArguments; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + await this.issueRepository.setIssueType(param.owner, param.repo, param.issueNumber, param.labels, param.issueTypes, param.tokens.token); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update issue type, but there was a problem.`, + ], + error: error, + })); + } + return result; } - return []; - } - - /** - * Get the command term to show in the list of subcommands. - * - * @param {Command} cmd - * @returns {string} - */ - - subcommandTerm(cmd) { - // Legacy. Ignores custom usage string, and nested commands. - const args = cmd.registeredArguments - .map((arg) => humanReadableArgName(arg)) - .join(' '); - return ( - cmd._name + - (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + - (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option - (args ? ' ' + args : '') - ); - } - - /** - * Get the option term to show in the list of options. - * - * @param {Option} option - * @returns {string} - */ - - optionTerm(option) { - return option.flags; - } - - /** - * Get the argument term to show in the list of arguments. - * - * @param {Argument} argument - * @returns {string} - */ - - argumentTerm(argument) { - return argument.name(); - } - - /** - * Get the longest command term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestSubcommandTermLength(cmd, helper) { - return helper.visibleCommands(cmd).reduce((max, command) => { - return Math.max(max, helper.subcommandTerm(command).length); - }, 0); - } - - /** - * Get the longest option term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestOptionTermLength(cmd, helper) { - return helper.visibleOptions(cmd).reduce((max, option) => { - return Math.max(max, helper.optionTerm(option).length); - }, 0); - } - - /** - * Get the longest global option term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ +} +exports.UpdateIssueTypeUseCase = UpdateIssueTypeUseCase; - longestGlobalOptionTermLength(cmd, helper) { - return helper.visibleGlobalOptions(cmd).reduce((max, option) => { - return Math.max(max, helper.optionTerm(option).length); - }, 0); - } - /** - * Get the longest argument term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ +/***/ }), - longestArgumentTermLength(cmd, helper) { - return helper.visibleArguments(cmd).reduce((max, argument) => { - return Math.max(max, helper.argumentTerm(argument).length); - }, 0); - } +/***/ 465: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Get the command usage to be displayed at the top of the built-in help. - * - * @param {Command} cmd - * @returns {string} - */ +"use strict"; - commandUsage(cmd) { - // Usage - let cmdName = cmd._name; - if (cmd._aliases[0]) { - cmdName = cmdName + '|' + cmd._aliases[0]; - } - let ancestorCmdNames = ''; - for ( - let ancestorCmd = cmd.parent; - ancestorCmd; - ancestorCmd = ancestorCmd.parent - ) { - ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckIssueCommentLanguageUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class CheckIssueCommentLanguageUseCase { + constructor() { + this.taskId = 'CheckIssueCommentLanguageUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.translatedKey = ``; } - return ancestorCmdNames + cmdName + ' ' + cmd.usage(); - } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + const commentBody = param.issue.commentBody; + if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return results; + } + const locale = param.locale.issue; + let prompt = ` + You are a helpful assistant that checks if the text is written in ${locale}. + + Instructions: + 1. Analyze the provided text + 2. If the text is written in ${locale}, respond with exactly "done" + 3. If the text is written in any other language, respond with exactly "must_translate" + 4. Do not provide any explanation or additional text + + The text is: ${commentBody} + `; + let result = await this.aiRepository.ask(param.ai, prompt); + if (result === "done") { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return results; + } + prompt = ` +You are a helpful assistant that translates the text to ${locale}. - /** - * Get the description for the command. - * - * @param {Command} cmd - * @returns {string} - */ +Instructions: +1. Translate the text to ${locale} +2. Do not provide any explanation or additional text +3. Return the translated text only - commandDescription(cmd) { - // @ts-ignore: because overloaded return type - return cmd.description(); - } +The text is: ${commentBody} + `; + result = await this.aiRepository.ask(param.ai, prompt); + const translatedCommentBody = `${result} +> ${commentBody} +${this.translatedKey} +`; + (0, logger_1.logInfo)(`šŸ”Ž Issue number: ${param.issue.number}`); + await this.issueRepository.updateComment(param.owner, param.repo, param.issue.number, param.issue.commentId, translatedCommentBody, param.tokens.token); + return results; + } +} +exports.CheckIssueCommentLanguageUseCase = CheckIssueCommentLanguageUseCase; - /** - * Get the subcommand summary to show in the list of subcommands. - * (Fallback to description for backwards compatibility.) - * - * @param {Command} cmd - * @returns {string} - */ - subcommandDescription(cmd) { - // @ts-ignore: because overloaded return type - return cmd.summary() || cmd.description(); - } +/***/ }), - /** - * Get the option description to show in the list of options. - * - * @param {Option} option - * @return {string} - */ +/***/ 8129: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - optionDescription(option) { - const extraInfo = []; +"use strict"; - if (option.argChoices) { - extraInfo.push( - // use stringify to match the display of the default value - `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, - ); - } - if (option.defaultValue !== undefined) { - // default for boolean and negated more for programmer than end user, - // but show true/false for boolean option as may be for hand-rolled env or config processing. - const showDefault = - option.required || - option.optional || - (option.isBoolean() && typeof option.defaultValue === 'boolean'); - if (showDefault) { - extraInfo.push( - `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`, - ); - } - } - // preset for boolean and negated are more for programmer than end user - if (option.presetArg !== undefined && option.optional) { - extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); - } - if (option.envVar !== undefined) { - extraInfo.push(`env: ${option.envVar}`); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckChangesPullRequestSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckChangesPullRequestSizeUseCase { + constructor() { + this.taskId = 'CheckChangesPullRequestSizeUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); } - if (extraInfo.length > 0) { - return `${option.description} (${extraInfo.join(', ')})`; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, param.pullRequest.head, param.pullRequest.base, param.sizeThresholds, param.labels, param.tokens.token); + (0, logger_1.logDebugInfo)(`Size: ${size}`); + (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); + (0, logger_1.logDebugInfo)(`Reason: ${reason}`); + (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnPullRequest}`); + if (param.labels.sizedLabelOnPullRequest !== size) { + /** + * Even if this is for pull reuqets, we are getting the issue labels for having a mirror of the issue labels on the pull request. + */ + const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); + labelNames.push(size); + await this.issueRepository.setLabels(param.owner, param.repo, param.pullRequest.number, labelNames, param.tokens.token); + for (const project of param.project.getProjects()) { + await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.pullRequest.number, githubSize, param.tokens.token); + } + (0, logger_1.logDebugInfo)(`Updated labels on pull request #${param.pullRequest.number}:`); + (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `${reason}, so the pull request was resized to ${size}.`, + ], + })); + } + else { + (0, logger_1.logDebugInfo)(`The pull request is already at the correct size.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the size of the changes, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } +} +exports.CheckChangesPullRequestSizeUseCase = CheckChangesPullRequestSizeUseCase; - return option.description; - } - /** - * Get the argument description to show in the list of arguments. - * - * @param {Argument} argument - * @return {string} - */ +/***/ }), - argumentDescription(argument) { - const extraInfo = []; - if (argument.argChoices) { - extraInfo.push( - // use stringify to match the display of the default value - `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, - ); - } - if (argument.defaultValue !== undefined) { - extraInfo.push( - `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`, - ); - } - if (extraInfo.length > 0) { - const extraDescripton = `(${extraInfo.join(', ')})`; - if (argument.description) { - return `${argument.description} ${extraDescripton}`; - } - return extraDescripton; - } - return argument.description; - } +/***/ 7383: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Generate the built-in help text. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {string} - */ +"use strict"; - formatHelp(cmd, helper) { - const termWidth = helper.padWidth(cmd, helper); - const helpWidth = helper.helpWidth || 80; - const itemIndentWidth = 2; - const itemSeparatorWidth = 2; // between term and description - function formatItem(term, description) { - if (description) { - const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; - return helper.wrap( - fullText, - helpWidth - itemIndentWidth, - termWidth + itemSeparatorWidth, - ); - } - return term; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPriorityPullRequestSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckPriorityPullRequestSizeUseCase { + constructor() { + this.taskId = 'CheckPriorityPullRequestSizeUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); } - function formatList(textArray) { - return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const priority = param.labels.priorityLabelOnIssue; + if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + let priorityLabel = ``; + if (priority === param.labels.priorityHigh) { + priorityLabel = `P0`; + } + else if (priority === param.labels.priorityMedium) { + priorityLabel = `P1`; + } + else if (priority === param.labels.priorityLow) { + priorityLabel = `P2`; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + (0, logger_1.logDebugInfo)(`Priority: ${priority}`); + (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); + for (const project of param.project.getProjects()) { + const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.pullRequest.number, priorityLabel, param.tokens.token); + if (success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, + ], + })); + } + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the priority of the issue, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } +} +exports.CheckPriorityPullRequestSizeUseCase = CheckPriorityPullRequestSizeUseCase; - // Usage - let output = [`Usage: ${helper.commandUsage(cmd)}`, '']; - // Description - const commandDescription = helper.commandDescription(cmd); - if (commandDescription.length > 0) { - output = output.concat([ - helper.wrap(commandDescription, helpWidth, 0), - '', - ]); - } +/***/ }), - // Arguments - const argumentList = helper.visibleArguments(cmd).map((argument) => { - return formatItem( - helper.argumentTerm(argument), - helper.argumentDescription(argument), - ); - }); - if (argumentList.length > 0) { - output = output.concat(['Arguments:', formatList(argumentList), '']); - } +/***/ 2175: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // Options - const optionList = helper.visibleOptions(cmd).map((option) => { - return formatItem( - helper.optionTerm(option), - helper.optionDescription(option), - ); - }); - if (optionList.length > 0) { - output = output.concat(['Options:', formatList(optionList), '']); - } +"use strict"; - if (this.showGlobalOptions) { - const globalOptionList = helper - .visibleGlobalOptions(cmd) - .map((option) => { - return formatItem( - helper.optionTerm(option), - helper.optionDescription(option), - ); - }); - if (globalOptionList.length > 0) { - output = output.concat([ - 'Global Options:', - formatList(globalOptionList), - '', - ]); - } +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]; } }; } - - // Commands - const commandList = helper.visibleCommands(cmd).map((cmd) => { - return formatItem( - helper.subcommandTerm(cmd), - helper.subcommandDescription(cmd), - ); - }); - if (commandList.length > 0) { - output = output.concat(['Commands:', formatList(commandList), '']); + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LinkPullRequestIssueUseCase = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const result_1 = __nccwpck_require__(7305); +const pull_request_repository_1 = __nccwpck_require__(634); +const logger_1 = __nccwpck_require__(8836); +class LinkPullRequestIssueUseCase { + constructor() { + this.taskId = 'LinkPullRequestIssueUseCase'; + this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const isLinked = await this.pullRequestRepository.isLinked(github.context.payload.pull_request?.html_url ?? ''); + if (!isLinked) { + /** + * Set the primary/default branch + */ + await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.branches.defaultBranch, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The base branch was temporarily updated to \`${param.branches.defaultBranch}\`.`, + ], + })); + /** + * Update PR's description. + */ + let prBody = param.pullRequest.body; + let updatedBody = `${prBody}\n\nResolves #${param.issueNumber}`; + await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The description was temporarily modified to include a reference to issue **#${param.issueNumber}**.`, + ], + })); + /** + * Await 20 seconds + */ + await new Promise(resolve => setTimeout(resolve, 20 * 1000)); + /** + * Restore the original branch + */ + await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.pullRequest.base, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The base branch was reverted to its original value: \`${param.pullRequest.base}\`.`, + ], + })); + /** + * Restore comment on description + */ + prBody = param.pullRequest.body; + updatedBody = prBody.replace(`\n\nResolves #${param.issueNumber}`, ""); + await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The temporary issue reference **#${param.issueNumber}** was removed from the description.`, + ], + })); + return result; + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to link pull request to project, but there was a problem.`, + ], + error: error, + })); + } + return result; } +} +exports.LinkPullRequestIssueUseCase = LinkPullRequestIssueUseCase; - return output.join('\n'); - } - - /** - * Calculate the pad width from the maximum term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - padWidth(cmd, helper) { - return Math.max( - helper.longestOptionTermLength(cmd, helper), - helper.longestGlobalOptionTermLength(cmd, helper), - helper.longestSubcommandTermLength(cmd, helper), - helper.longestArgumentTermLength(cmd, helper), - ); - } +/***/ }), - /** - * Wrap the given string to width characters per line, with lines after the first indented. - * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. - * - * @param {string} str - * @param {number} width - * @param {number} indent - * @param {number} [minColumnWidth=40] - * @return {string} - * - */ +/***/ 4311: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - wrap(str, width, indent, minColumnWidth = 40) { - // Full \s characters, minus the linefeeds. - const indents = - ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff'; - // Detect manually wrapped and indented strings by searching for line break followed by spaces. - const manualIndent = new RegExp(`[\\n][${indents}]+`); - if (str.match(manualIndent)) return str; - // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line). - const columnWidth = width - indent; - if (columnWidth < minColumnWidth) return str; +"use strict"; - const leadingStr = str.slice(0, indent); - const columnText = str.slice(indent).replace('\r\n', '\n'); - const indentString = ' '.repeat(indent); - const zeroWidthSpace = '\u200B'; - const breaks = `\\s${zeroWidthSpace}`; - // Match line end (so empty lines don't collapse), - // or as much text as will fit in column, or excess text up to first break. - const regex = new RegExp( - `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, - 'g', - ); - const lines = columnText.match(regex) || []; - return ( - leadingStr + - lines - .map((line, i) => { - if (line === '\n') return ''; // preserve empty lines - return (i > 0 ? indentString : '') + line.trimEnd(); - }) - .join('\n') - ); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LinkPullRequestProjectUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class LinkPullRequestProjectUseCase { + constructor() { + this.taskId = 'LinkPullRequestProjectUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + const columnName = param.project.getProjectColumnPullRequestCreated(); + try { + for (const project of param.project.getProjects()) { + let actionDone = await this.projectRepository.linkContentId(project, param.pullRequest.id, param.tokens.token); + if (actionDone) { + /** + * Wait for 10 seconds to ensure the pull request is linked to the project + */ + await new Promise(resolve => setTimeout(resolve, 10000)); + actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.pullRequest.number, columnName, param.tokens.token); + if (actionDone) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The pull request was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, + ], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `The pull request was linked to [**${project?.title}**](${project?.url}) but there was an error moving it to the column \`${columnName}\`.`, + ], + })); + } + } + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to link pull request to project, but there was a problem.`, + ], + error: error, + })); + } + return result; + } } - -exports.Help = Help; +exports.LinkPullRequestProjectUseCase = LinkPullRequestProjectUseCase; /***/ }), -/***/ 66558: +/***/ 158: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const { InvalidArgumentError } = __nccwpck_require__(12625); - -class Option { - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} [description] - */ - - constructor(flags, description) { - this.flags = flags; - this.description = description || ''; +"use strict"; - this.required = flags.includes('<'); // A value must be supplied when the option is specified. - this.optional = flags.includes('['); // A value is optional when the option is specified. - // variadic test ignores et al which might be used to describe custom splitting of single argument - this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. - this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. - const optionFlags = splitOptionFlags(flags); - this.short = optionFlags.shortFlag; - this.long = optionFlags.longFlag; - this.negate = false; - if (this.long) { - this.negate = this.long.startsWith('--no-'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UpdatePullRequestDescriptionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const file_repository_1 = __nccwpck_require__(1503); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const pull_request_repository_1 = __nccwpck_require__(634); +const logger_1 = __nccwpck_require__(8836); +class UpdatePullRequestDescriptionUseCase { + constructor() { + this.taskId = 'UpdatePullRequestDescriptionUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); + this.fileRepository = new file_repository_1.FileRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); } - this.defaultValue = undefined; - this.defaultValueDescription = undefined; - this.presetArg = undefined; - this.envVar = undefined; - this.parseArg = undefined; - this.hidden = false; - this.argChoices = undefined; - this.conflictsWith = []; - this.implied = undefined; - } - - /** - * Set the default value, and optionally supply the description to be displayed in the help. - * - * @param {*} value - * @param {string} [description] - * @return {Option} - */ - - default(value, description) { - this.defaultValue = value; - this.defaultValueDescription = description; - return this; - } - - /** - * Preset to use when option used without option-argument, especially optional but also boolean and negated. - * The custom processing (parseArg) is called. - * - * @example - * new Option('--color').default('GREYSCALE').preset('RGB'); - * new Option('--donate [amount]').preset('20').argParser(parseFloat); - * - * @param {*} arg - * @return {Option} - */ - - preset(arg) { - this.presetArg = arg; - return this; - } + async invoke(param) { + (0, logger_1.logDebugInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const prNumber = param.pullRequest.number; + const issueDescription = await this.issueRepository.getIssueDescription(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (issueDescription.length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + steps: [ + `No issue description found. Skipping update pull request description.` + ] + })); + return result; + } + const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); + const pullRequestCreatorIsTeamMember = param.pullRequest.creator.length > 0 + && currentProjectMembers.indexOf(param.pullRequest.creator) > -1; + if (!pullRequestCreatorIsTeamMember && param.ai.getAiMembersOnly()) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + steps: [ + `The pull request creator @${param.pullRequest.creator} is not a team member and \`AI members only\` is enabled. Skipping update pull request description.` + ] + })); + return result; + } + const changes = await this.pullRequestRepository.getPullRequestChanges(param.owner, param.repo, prNumber, param.tokens.token); + const changesDescription = await this.processChanges(changes, param.ai, param.owner, param.repo, param.tokens.token, param.pullRequest.base); + const descriptionPrompt = `this an issue descrition. +define a description for the pull request which closes the issue and avoid the use of titles (#, ##, ###). +just a text description:\n\n +${issueDescription}`; + const currentDescription = await this.aiRepository.ask(param.ai, descriptionPrompt); + // Update pull request description + await this.pullRequestRepository.updateDescription(param.owner, param.repo, prNumber, ` +#${param.issueNumber} - /** - * Add option name(s) that conflict with this option. - * An error will be displayed if conflicting options are found during parsing. - * - * @example - * new Option('--rgb').conflicts('cmyk'); - * new Option('--js').conflicts(['ts', 'jsx']); - * - * @param {(string | string[])} names - * @return {Option} - */ +## What does this PR do? - conflicts(names) { - this.conflictsWith = this.conflictsWith.concat(names); - return this; - } +${currentDescription} - /** - * Specify implied option values for when this option is set and the implied options are not. - * - * The custom processing (parseArg) is not called on the implied values. - * - * @example - * program - * .addOption(new Option('--log', 'write logging information to file')) - * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); - * - * @param {object} impliedOptionValues - * @return {Option} - */ - implies(impliedOptionValues) { - let newImplied = impliedOptionValues; - if (typeof impliedOptionValues === 'string') { - // string is not documented, but easy mistake and we can do what user probably intended. - newImplied = { [impliedOptionValues]: true }; +${changesDescription} +`, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The description has been updated with AI-generated content.` + ] + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error updating pull request description: ${error}` + ] + })); + } + return result; } - this.implied = Object.assign(this.implied || {}, newImplied); - return this; - } + shouldIgnoreFile(filename, ignorePatterns) { + return ignorePatterns.some(pattern => { + // Convert glob pattern to regex + const regexPattern = pattern + .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) + .replace(/\*/g, '.*') // Convert * to match anything + .replace(/\//g, '\\/'); // Escape forward slashes + // Allow pattern ending on /* to ignore also subdirectories and files inside + if (pattern.endsWith("/*")) { + return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); + } + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(filename); + }); + } + mergePatchSummaries(summaries) { + const mergedMap = new Map(); + for (const summary of summaries) { + const existing = mergedMap.get(summary.filePath); + if (existing) { + // Merge with existing summary + existing.summary = `${existing.summary}\n${summary.summary}`; + existing.changes = [...new Set([...existing.changes, ...summary.changes])]; + } + else { + // Create new entry + mergedMap.set(summary.filePath, { + filePath: summary.filePath, + summary: summary.summary, + changes: [...summary.changes] + }); + } + } + return Array.from(mergedMap.values()); + } + groupFilesByDirectory(files) { + const groups = { + root: [] + }; + files.forEach(file => { + const pathParts = file.filePath.split('/'); + if (pathParts.length > 1) { + const directory = pathParts.slice(0, -1).join('/'); + if (!groups[directory]) { + groups[directory] = []; + } + groups[directory].push(file); + } + else { + groups.root.push(file); + } + }); + return groups; + } + formatFileChanges(file) { + let output = `#### \`${file.filePath}\`\n\n`; + output += `${file.summary}\n\n`; + if (file.changes.length > 0) { + output += '**Changes:**\n'; + output += file.changes.map(change => `- ${change}`).join('\n'); + } + output += `\n\n--- \n\n`; + return output; + } + async processFile(change, ai, owner, repo, token, baseBranch) { + if (!change.patch) { + return []; + } + // Get the original file content + const originalContent = await this.fileRepository.getFileContent(owner, repo, change.filename, token, baseBranch); + const filePrompt = `Analyze the following code changes and provide a summary in JSON format. - /** - * Set environment variable to check for option value. - * - * An environment variable is only used if when processed the current option value is - * undefined, or the source of the current value is 'default' or 'config' or 'env'. - * - * @param {string} name - * @return {Option} - */ +### **Guidelines**: +- Output must be a **valid JSON** object. +- Provide a high-level summary of the changes. +- List the key changes in detail. +- Pay attention to the file names, don't make mistakes with uppercase, lowercase, or underscores. +- Be careful when composing the response JSON, don't make mistakes with unnecessary commas. - env(name) { - this.envVar = name; - return this; - } +### **Output Format Example**: +\`\`\`json +{ + "filePath": "src/utils/logger.ts", + "summary": "Refactored logging system for better error handling.", + "changes": [ + "Replaced \`console.error\` with \`logError\`.", + "Added support for async logging.", + "Removed unused function \`debugLog\`." + ] +} +\`\`\` - /** - * Set the custom handler for processing CLI option arguments into option values. - * - * @param {Function} [fn] - * @return {Option} - */ +### **Metadata**: +- **Filename:** ${change.filename} +- **Status:** ${change.status} +- **Changes:** +${change.additions} / -${change.deletions} - argParser(fn) { - this.parseArg = fn; - return this; - } +### **Original File Content**: +\`\`\` +${originalContent} +\`\`\` - /** - * Whether the option is mandatory and must have a value after parsing. - * - * @param {boolean} [mandatory=true] - * @return {Option} - */ +### **Patch**: +${change.patch}`; + const response = await this.aiRepository.ask(ai, filePrompt); + if (!response) { + return []; + } + try { + const cleanResponse = response.replace(/^```json\n?/, '').replace(/\n?```$/, '').trim(); + const patchSummary = JSON.parse(cleanResponse); + return [patchSummary]; + } + catch (error) { + (0, logger_1.logDebugError)(`Response: ${response}`); + (0, logger_1.logError)(`Error parsing JSON response: ${error}`); + return []; + } + } + async processChanges(changes, ai, owner, repo, token, baseBranch) { + (0, logger_1.logDebugInfo)(`Processing ${changes.length} changes`); + const processFilePromises = changes.map(async (change) => { + try { + (0, logger_1.logDebugInfo)(`Processing changes for file ${change.filename}`); + const shouldIgnoreFile = this.shouldIgnoreFile(change.filename, ai.getAiIgnoreFiles()); + if (shouldIgnoreFile) { + (0, logger_1.logDebugInfo)(`File ${change.filename} should be ignored`); + return []; + } + return await this.processFile(change, ai, owner, repo, token, baseBranch); + } + catch (error) { + (0, logger_1.logError)(error); + throw new Error(`Error processing file ${change.filename}: ${error}`); + } + }); + const fileDescriptions = (await Promise.all(processFilePromises)).flat(); + // Merge PatchSummary objects for the same file + const mergedFileDescriptions = this.mergePatchSummaries(fileDescriptions); + // Group files by directory + const groupedFiles = this.groupFilesByDirectory(mergedFileDescriptions); + // Generate a structured description + let description = ''; + // Add summary section if there are files + if (mergedFileDescriptions.length > 0) { + description += '## Summary of Changes\n\n'; + description += mergedFileDescriptions.map(file => `- **${file.filePath}**: ${file.summary}`).join('\n'); + description += '\n\n'; + } + // Add detailed changes section + description += '## Detailed Changes\n\n'; + // Process each directory group + for (const [directory, files] of Object.entries(groupedFiles)) { + if (directory === 'root') { + // Files in root directory + description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; + } + else { + // Files in subdirectories + description += `### ${directory}\n\n`; + description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; + } + } + return description; + } +} +exports.UpdatePullRequestDescriptionUseCase = UpdatePullRequestDescriptionUseCase; - makeOptionMandatory(mandatory = true) { - this.mandatory = !!mandatory; - return this; - } - /** - * Hide option in help. - * - * @param {boolean} [hide=true] - * @return {Option} - */ +/***/ }), - hideHelp(hide = true) { - this.hidden = !!hide; - return this; - } +/***/ 7112: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * @package - */ +"use strict"; - _concatValue(value, previous) { - if (previous === this.defaultValue || !Array.isArray(previous)) { - return [value]; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPullRequestCommentLanguageUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class CheckPullRequestCommentLanguageUseCase { + constructor() { + this.taskId = 'CheckPullRequestCommentLanguageUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.translatedKey = ``; } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + const commentBody = param.pullRequest.commentBody; + if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return results; + } + const locale = param.locale.pullRequest; + let prompt = ` + You are a helpful assistant that checks if the text is written in ${locale}. + + Instructions: + 1. Analyze the provided text + 2. If the text is written in ${locale}, respond with exactly "done" + 3. If the text is written in any other language, respond with exactly "must_translate" + 4. Do not provide any explanation or additional text + + The text is: ${commentBody} + `; + let result = await this.aiRepository.ask(param.ai, prompt); + if (result === "done") { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return results; + } + prompt = ` +You are a helpful assistant that translates the text to ${locale}. - return previous.concat(value); - } - - /** - * Only allow option value to be one of choices. - * - * @param {string[]} values - * @return {Option} - */ - - choices(values) { - this.argChoices = values.slice(); - this.parseArg = (arg, previous) => { - if (!this.argChoices.includes(arg)) { - throw new InvalidArgumentError( - `Allowed choices are ${this.argChoices.join(', ')}.`, - ); - } - if (this.variadic) { - return this._concatValue(arg, previous); - } - return arg; - }; - return this; - } - - /** - * Return option name. - * - * @return {string} - */ +Instructions: +1. Translate the text to ${locale} +2. Do not provide any explanation or additional text +3. Return the translated text only - name() { - if (this.long) { - return this.long.replace(/^--/, ''); +The text is: ${commentBody} + `; + result = await this.aiRepository.ask(param.ai, prompt); + const translatedCommentBody = `${result} +> ${commentBody} +${this.translatedKey} +`; + await this.issueRepository.updateComment(param.owner, param.repo, param.pullRequest.number, param.pullRequest.commentId, translatedCommentBody, param.tokens.token); + return results; } - return this.short.replace(/^-/, ''); - } - - /** - * Return option name, in a camelcase format that can be used - * as a object attribute key. - * - * @return {string} - */ +} +exports.CheckPullRequestCommentLanguageUseCase = CheckPullRequestCommentLanguageUseCase; - attributeName() { - return camelcase(this.name().replace(/^no-/, '')); - } - /** - * Check if `arg` matches the short or long flag. - * - * @param {string} arg - * @return {boolean} - * @package - */ +/***/ }), - is(arg) { - return this.short === arg || this.long === arg; - } +/***/ 8593: +/***/ ((__unused_webpack_module, exports) => { - /** - * Return whether a boolean option. - * - * Options are one of boolean, negated, required argument, or optional argument. - * - * @return {boolean} - * @package - */ +"use strict"; - isBoolean() { - return !this.required && !this.optional && !this.negate; - } -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PROMPTS = exports.ACTIONS = exports.ERRORS = exports.INPUT_KEYS = exports.WORKFLOW_ACTIVE_STATUSES = exports.WORKFLOW_STATUS = exports.DEFAULT_IMAGE_CONFIG = exports.REPO_URL = exports.TITLE = exports.COMMAND = void 0; +exports.COMMAND = 'giik'; +exports.TITLE = 'Giik'; +exports.REPO_URL = 'https://github.com/landamessenger/git-board-flow'; +exports.DEFAULT_IMAGE_CONFIG = { + issue: { + automatic: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp" + ], + feature: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", + ], + bugfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" + ], + hotfix: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" + ], + release: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", + ], + docs: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", + ], + chore: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", + ], + }, + pullRequest: { + automatic: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + ], + feature: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", + ], + bugfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", + ], + hotfix: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", + ], + release: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", + ], + docs: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", + ], + chore: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", + ], + }, + commit: { + automatic: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + feature: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + bugfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + hotfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + release: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + docs: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + chore: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ] + } +}; +exports.WORKFLOW_STATUS = { + IN_PROGRESS: 'in_progress', + QUEUED: 'queued', + COMPLETED: 'completed', + FAILED: 'failed', + CANCELLED: 'cancelled', + SKIPPED: 'skipped', + TIMED_OUT: 'timed_out', +}; +exports.WORKFLOW_ACTIVE_STATUSES = [exports.WORKFLOW_STATUS.IN_PROGRESS, exports.WORKFLOW_STATUS.QUEUED]; +exports.INPUT_KEYS = { + // Debug + DEBUG: 'debug', + // Welcome + WELCOME_TITLE: 'welcome-title', + WELCOME_MESSAGES: 'welcome-messages', + // Single action + SINGLE_ACTION: 'single-action', + SINGLE_ACTION_ISSUE: 'single-action-issue', + SINGLE_ACTION_VERSION: 'single-action-version', + SINGLE_ACTION_TITLE: 'single-action-title', + SINGLE_ACTION_CHANGELOG: 'single-action-changelog', + // Tokens + TOKEN: 'token', + // AI + OPENROUTER_API_KEY: 'openrouter-api-key', + OPENROUTER_MODEL: 'openrouter-model', + AI_PULL_REQUEST_DESCRIPTION: 'ai-pull-request-description', + AI_MEMBERS_ONLY: 'ai-members-only', + AI_IGNORE_FILES: 'ai-ignore-files', + AI_INCLUDE_REASONING: 'ai-include-reasoning', + OPENROUTER_PROVIDER_ORDER: 'openrouter-provider-order', + OPENROUTER_PROVIDER_ALLOW_FALLBACKS: 'openrouter-provider-allow-fallbacks', + OPENROUTER_PROVIDER_REQUIRE_PARAMETERS: 'openrouter-provider-require-parameters', + OPENROUTER_PROVIDER_DATA_COLLECTION: 'openrouter-provider-data-collection', + OPENROUTER_PROVIDER_IGNORE: 'openrouter-provider-ignore', + OPENROUTER_PROVIDER_QUANTIZATIONS: 'openrouter-provider-quantizations', + OPENROUTER_PROVIDER_SORT: 'openrouter-provider-sort', + // Projects + PROJECT_IDS: 'project-ids', + PROJECT_COLUMN_ISSUE_CREATED: 'project-column-issue-created', + PROJECT_COLUMN_PULL_REQUEST_CREATED: 'project-column-pull-request-created', + PROJECT_COLUMN_ISSUE_IN_PROGRESS: 'project-column-issue-in-progress', + PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS: 'project-column-pull-request-in-progress', + // Images + IMAGES_ON_ISSUE: 'images-on-issue', + IMAGES_ON_PULL_REQUEST: 'images-on-pull-request', + IMAGES_ON_COMMIT: 'images-on-commit', + IMAGES_ISSUE_AUTOMATIC: 'images-issue-automatic', + IMAGES_ISSUE_FEATURE: 'images-issue-feature', + IMAGES_ISSUE_BUGFIX: 'images-issue-bugfix', + IMAGES_ISSUE_DOCS: 'images-issue-docs', + IMAGES_ISSUE_CHORE: 'images-issue-chore', + IMAGES_ISSUE_RELEASE: 'images-issue-release', + IMAGES_ISSUE_HOTFIX: 'images-issue-hotfix', + IMAGES_PULL_REQUEST_AUTOMATIC: 'images-pull-request-automatic', + IMAGES_PULL_REQUEST_FEATURE: 'images-pull-request-feature', + IMAGES_PULL_REQUEST_BUGFIX: 'images-pull-request-bugfix', + IMAGES_PULL_REQUEST_RELEASE: 'images-pull-request-release', + IMAGES_PULL_REQUEST_HOTFIX: 'images-pull-request-hotfix', + IMAGES_PULL_REQUEST_DOCS: 'images-pull-request-docs', + IMAGES_PULL_REQUEST_CHORE: 'images-pull-request-chore', + IMAGES_COMMIT_AUTOMATIC: 'images-commit-automatic', + IMAGES_COMMIT_FEATURE: 'images-commit-feature', + IMAGES_COMMIT_BUGFIX: 'images-commit-bugfix', + IMAGES_COMMIT_RELEASE: 'images-commit-release', + IMAGES_COMMIT_HOTFIX: 'images-commit-hotfix', + IMAGES_COMMIT_DOCS: 'images-commit-docs', + IMAGES_COMMIT_CHORE: 'images-commit-chore', + // Workflows + RELEASE_WORKFLOW: 'release-workflow', + HOTFIX_WORKFLOW: 'hotfix-workflow', + // Emoji + EMOJI_LABELED_TITLE: 'emoji-labeled-title', + BRANCH_MANAGEMENT_EMOJI: 'branch-management-emoji', + // Labels + BRANCH_MANAGEMENT_LAUNCHER_LABEL: 'branch-management-launcher-label', + BUGFIX_LABEL: 'bugfix-label', + BUG_LABEL: 'bug-label', + HOTFIX_LABEL: 'hotfix-label', + ENHANCEMENT_LABEL: 'enhancement-label', + FEATURE_LABEL: 'feature-label', + RELEASE_LABEL: 'release-label', + QUESTION_LABEL: 'question-label', + HELP_LABEL: 'help-label', + DEPLOY_LABEL: 'deploy-label', + DEPLOYED_LABEL: 'deployed-label', + DOCS_LABEL: 'docs-label', + DOCUMENTATION_LABEL: 'documentation-label', + CHORE_LABEL: 'chore-label', + MAINTENANCE_LABEL: 'maintenance-label', + PRIORITY_HIGH_LABEL: 'priority-high-label', + PRIORITY_MEDIUM_LABEL: 'priority-medium-label', + PRIORITY_LOW_LABEL: 'priority-low-label', + PRIORITY_NONE_LABEL: 'priority-none-label', + SIZE_XXL_LABEL: 'size-xxl-label', + SIZE_XL_LABEL: 'size-xl-label', + SIZE_L_LABEL: 'size-l-label', + SIZE_M_LABEL: 'size-m-label', + SIZE_S_LABEL: 'size-s-label', + SIZE_XS_LABEL: 'size-xs-label', + // Issue Types + ISSUE_TYPE_BUG: 'issue-type-bug', + ISSUE_TYPE_BUG_DESCRIPTION: 'issue-type-bug-description', + ISSUE_TYPE_BUG_COLOR: 'issue-type-bug-color', + ISSUE_TYPE_HOTFIX: 'issue-type-hotfix', + ISSUE_TYPE_HOTFIX_DESCRIPTION: 'issue-type-hotfix-description', + ISSUE_TYPE_HOTFIX_COLOR: 'issue-type-hotfix-color', + ISSUE_TYPE_FEATURE: 'issue-type-feature', + ISSUE_TYPE_FEATURE_DESCRIPTION: 'issue-type-feature-description', + ISSUE_TYPE_FEATURE_COLOR: 'issue-type-feature-color', + ISSUE_TYPE_DOCUMENTATION: 'issue-type-documentation', + ISSUE_TYPE_DOCUMENTATION_DESCRIPTION: 'issue-type-documentation-description', + ISSUE_TYPE_DOCUMENTATION_COLOR: 'issue-type-documentation-color', + ISSUE_TYPE_MAINTENANCE: 'issue-type-maintenance', + ISSUE_TYPE_MAINTENANCE_DESCRIPTION: 'issue-type-maintenance-description', + ISSUE_TYPE_MAINTENANCE_COLOR: 'issue-type-maintenance-color', + ISSUE_TYPE_RELEASE: 'issue-type-release', + ISSUE_TYPE_RELEASE_DESCRIPTION: 'issue-type-release-description', + ISSUE_TYPE_RELEASE_COLOR: 'issue-type-release-color', + ISSUE_TYPE_QUESTION: 'issue-type-question', + ISSUE_TYPE_QUESTION_DESCRIPTION: 'issue-type-question-description', + ISSUE_TYPE_QUESTION_COLOR: 'issue-type-question-color', + ISSUE_TYPE_HELP: 'issue-type-help', + ISSUE_TYPE_HELP_DESCRIPTION: 'issue-type-help-description', + ISSUE_TYPE_HELP_COLOR: 'issue-type-help-color', + ISSUE_TYPE_TASK: 'issue-type-task', + ISSUE_TYPE_TASK_DESCRIPTION: 'issue-type-task-description', + ISSUE_TYPE_TASK_COLOR: 'issue-type-task-color', + // Locale + ISSUES_LOCALE: 'issues-locale', + PULL_REQUESTS_LOCALE: 'pull-requests-locale', + // Size Thresholds + SIZE_XXL_THRESHOLD_LINES: 'size-xxl-threshold-lines', + SIZE_XXL_THRESHOLD_FILES: 'size-xxl-threshold-files', + SIZE_XXL_THRESHOLD_COMMITS: 'size-xxl-threshold-commits', + SIZE_XL_THRESHOLD_LINES: 'size-xl-threshold-lines', + SIZE_XL_THRESHOLD_FILES: 'size-xl-threshold-files', + SIZE_XL_THRESHOLD_COMMITS: 'size-xl-threshold-commits', + SIZE_L_THRESHOLD_LINES: 'size-l-threshold-lines', + SIZE_L_THRESHOLD_FILES: 'size-l-threshold-files', + SIZE_L_THRESHOLD_COMMITS: 'size-l-threshold-commits', + SIZE_M_THRESHOLD_LINES: 'size-m-threshold-lines', + SIZE_M_THRESHOLD_FILES: 'size-m-threshold-files', + SIZE_M_THRESHOLD_COMMITS: 'size-m-threshold-commits', + SIZE_S_THRESHOLD_LINES: 'size-s-threshold-lines', + SIZE_S_THRESHOLD_FILES: 'size-s-threshold-files', + SIZE_S_THRESHOLD_COMMITS: 'size-s-threshold-commits', + SIZE_XS_THRESHOLD_LINES: 'size-xs-threshold-lines', + SIZE_XS_THRESHOLD_FILES: 'size-xs-threshold-files', + SIZE_XS_THRESHOLD_COMMITS: 'size-xs-threshold-commits', + // Branches + MAIN_BRANCH: 'main-branch', + DEVELOPMENT_BRANCH: 'development-branch', + FEATURE_TREE: 'feature-tree', + BUGFIX_TREE: 'bugfix-tree', + HOTFIX_TREE: 'hotfix-tree', + RELEASE_TREE: 'release-tree', + DOCS_TREE: 'docs-tree', + CHORE_TREE: 'chore-tree', + // Commit + COMMIT_PREFIX_TRANSFORMS: 'commit-prefix-transforms', + // Issue + BRANCH_MANAGEMENT_ALWAYS: 'branch-management-always', + REOPEN_ISSUE_ON_PUSH: 'reopen-issue-on-push', + DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', + // Pull Request + PULL_REQUEST_DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', + PULL_REQUEST_DESIRED_REVIEWERS_COUNT: 'desired-reviewers-count', + PULL_REQUEST_MERGE_TIMEOUT: 'merge-timeout', + // Supabase + SUPABASE_URL: 'supabase-url', + SUPABASE_KEY: 'supabase-key' +}; +exports.ERRORS = { + GIT_REPOSITORY_NOT_FOUND: 'āŒ Git repository not found' +}; +exports.ACTIONS = { + DEPLOYED: 'deployed_action', + AI_CACHE: 'ai_cache_action', + AI_CACHE_LOCAL: 'ai_cache_local_action', + PUBLISH_GITHUB_ACTION: 'publish_github_action', + CREATE_RELEASE: 'create_release', + CREATE_TAG: 'create_tag', + THINK: 'think_action', +}; +exports.PROMPTS = { + CODE_BASE_ANALYSIS: ` +You are a technical code analysis assistant. -/** - * This class is to make it easier to work with dual options, without changing the existing - * implementation. We support separate dual options for separate positive and negative options, - * like `--build` and `--no-build`, which share a single option value. This works nicely for some - * use cases, but is tricky for others where we want separate behaviours despite - * the single shared option value. - */ -class DualOptions { - /** - * @param {Option[]} options - */ - constructor(options) { - this.positiveOptions = new Map(); - this.negativeOptions = new Map(); - this.dualOptions = new Set(); - options.forEach((option) => { - if (option.negate) { - this.negativeOptions.set(option.attributeName(), option); - } else { - this.positiveOptions.set(option.attributeName(), option); - } - }); - this.negativeOptions.forEach((value, key) => { - if (this.positiveOptions.has(key)) { - this.dualOptions.add(key); - } - }); - } +Your task is to analyze the content of the following source code file in depth. - /** - * Did the value come from the option, and not from possible matching dual option? - * - * @param {*} value - * @param {Option} option - * @returns {boolean} - */ - valueFromOption(value, option) { - const optionKey = option.attributeName(); - if (!this.dualOptions.has(optionKey)) return true; +Provide a precise and highly technical explanation of what the code does, including: +- Its main purpose and functionality. +- A breakdown of the logic and flow (step by step or module by module). +- How each class, function, or major block interacts with the rest. +- The technologies, frameworks, or libraries it uses and how. +- Any relevant algorithms, patterns, or data structures implemented. +- Potential edge cases, performance considerations, or hidden behaviors. +- Dependencies and external integrations (APIs, services, databases, etc.). +- Any implicit assumptions or limitations found in the implementation. - // Use the value to deduce if (probably) came from the option. - const preset = this.negativeOptions.get(optionKey).presetArg; - const negativeValue = preset !== undefined ? preset : false; - return option.negate === (negativeValue === value); - } -} +Focus exclusively on *accurate technical analysis and understanding*, not on summarizing in simple language. -/** - * Convert string from kebab-case to camelCase. - * - * @param {string} str - * @return {string} - * @private - */ +Do not propose improvements, changes, or fixes in this stage — your only goal is to explain exactly what the code does and how it works. + `, +}; -function camelcase(str) { - return str.split('-').reduce((str, word) => { - return str + word[0].toUpperCase() + word.slice(1); - }); -} -/** - * Split the short and long flag out of something like '-m,--mixed ' - * - * @private - */ +/***/ }), -function splitOptionFlags(flags) { - let shortFlag; - let longFlag; - // Use original very loose parsing to maintain backwards compatibility for now, - // which allowed for example unintended `-sw, --short-word` [sic]. - const flagParts = flags.split(/[ |,]+/); - if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) - shortFlag = flagParts.shift(); - longFlag = flagParts.shift(); - // Add support for lone short flag without significantly changing parsing! - if (!shortFlag && /^-[^-]$/.test(longFlag)) { - shortFlag = longFlag; - longFlag = undefined; - } - return { shortFlag, longFlag }; -} +/***/ 7873: +/***/ ((__unused_webpack_module, exports) => { -exports.Option = Option; -exports.DualOptions = DualOptions; +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.injectJsonAsMarkdownBlock = exports.extractReleaseType = exports.extractVersion = void 0; +const extractVersion = (pattern, text) => { + const versionPattern = new RegExp(`###\\s*${pattern}\\s+(\\d+\\.\\d+\\.\\d+)`, 'i'); + const match = text.match(versionPattern); + return match ? match[1] : undefined; +}; +exports.extractVersion = extractVersion; +const extractReleaseType = (pattern, text) => { + const releaseTypePattern = new RegExp(`###\\s*${pattern}\\s+(Patch|Minor|Major)`, 'i'); + const match = text.match(releaseTypePattern); + return match ? match[1] : undefined; +}; +exports.extractReleaseType = extractReleaseType; +const injectJsonAsMarkdownBlock = (title, json) => { + const formattedJson = JSON.stringify(json, null, 4) // Pretty-print the JSON with 4 spaces. + .split('\n') // Split into lines. + .map(line => `> ${line}`) // Prefix each line with '> '. + .join('\n'); // Join lines back into a string. + return `> **${title}**\n>\n> \`\`\`json\n${formattedJson}\n> \`\`\``; +}; +exports.injectJsonAsMarkdownBlock = injectJsonAsMarkdownBlock; /***/ }), -/***/ 67592: +/***/ 1479: /***/ ((__unused_webpack_module, exports) => { -const maxDistance = 3; +"use strict"; -function editDistance(a, b) { - // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance - // Calculating optimal string alignment distance, no substring is edited more than once. - // (Simple implementation.) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.typesForIssue = exports.branchesForManagement = void 0; +const branchesForManagement = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { + if (labels.includes(hotfixLabel)) + return params.branches.bugfixTree; + if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) + return params.branches.bugfixTree; + if (labels.includes(releaseLabel)) + return params.branches.releaseTree; + if (labels.includes(docsLabel) || labels.includes(documentationLabel)) + return params.branches.docsTree; + if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) + return params.branches.choreTree; + if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) + return params.branches.featureTree; + return params.branches.featureTree; +}; +exports.branchesForManagement = branchesForManagement; +const typesForIssue = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { + if (labels.includes(hotfixLabel)) + return params.branches.hotfixTree; + if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) + return params.branches.bugfixTree; + if (labels.includes(releaseLabel)) + return params.branches.releaseTree; + if (labels.includes(docsLabel) || labels.includes(documentationLabel)) + return params.branches.docsTree; + if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) + return params.branches.choreTree; + if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) + return params.branches.featureTree; + return params.branches.featureTree; +}; +exports.typesForIssue = typesForIssue; - // Quick early exit, return worst case. - if (Math.abs(a.length - b.length) > maxDistance) - return Math.max(a.length, b.length); - // distance between prefix substrings of a and b - const d = []; +/***/ }), - // pure deletions turn a into empty string - for (let i = 0; i <= a.length; i++) { - d[i] = [i]; - } - // pure insertions turn empty string into b - for (let j = 0; j <= b.length; j++) { - d[0][j] = j; - } +/***/ 4990: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // fill matrix - for (let j = 1; j <= b.length; j++) { - for (let i = 1; i <= a.length; i++) { - let cost = 1; - if (a[i - 1] === b[j - 1]) { - cost = 0; - } else { - cost = 1; - } - d[i][j] = Math.min( - d[i - 1][j] + 1, // deletion - d[i][j - 1] + 1, // insertion - d[i - 1][j - 1] + cost, // substitution - ); - // transposition - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); - } - } - } +"use strict"; - return d[a.length][b.length]; -} +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRandomElement = void 0; +const chance_1 = __importDefault(__nccwpck_require__(2983)); +const chance = new chance_1.default(); +const getRandomElement = (list) => { + // Return undefined for empty lists + if (!list?.length) { + return undefined; + } + // Return first element for single item lists + if (list.length === 1) { + return list[0]; + } + // Use chance to get a random index + const randomIndex = chance.integer({ min: 0, max: list.length - 1 }); + return list[randomIndex]; +}; +exports.getRandomElement = getRandomElement; -/** - * Find close matches, restricted to same number of edits. - * - * @param {string} word - * @param {string[]} candidates - * @returns {string} - */ -function suggestSimilar(word, candidates) { - if (!candidates || candidates.length === 0) return ''; - // remove possible duplicates - candidates = Array.from(new Set(candidates)); +/***/ }), - const searchingOptions = word.startsWith('--'); - if (searchingOptions) { - word = word.slice(2); - candidates = candidates.map((candidate) => candidate.slice(2)); - } +/***/ 8836: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - let similar = []; - let bestDistance = maxDistance; - const minSimilarity = 0.4; - candidates.forEach((candidate) => { - if (candidate.length <= 1) return; // no one character guesses +"use strict"; - const distance = editDistance(word, candidate); - const length = Math.max(word.length, candidate.length); - const similarity = (length - distance) / length; - if (similarity > minSimilarity) { - if (distance < bestDistance) { - // better edit distance, throw away previous worse matches - bestDistance = distance; - similar = [candidate]; - } else if (distance === bestDistance) { - similar.push(candidate); - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.setGlobalLoggerDebug = setGlobalLoggerDebug; +exports.logInfo = logInfo; +exports.logWarning = logWarning; +exports.logError = logError; +exports.logDebugInfo = logDebugInfo; +exports.logDebugWarning = logDebugWarning; +exports.logDebugError = logDebugError; +exports.logSingleLine = logSingleLine; +const readline_1 = __importDefault(__nccwpck_require__(4521)); +let loggerDebug = false; +let loggerRemote = false; +function setGlobalLoggerDebug(debug, isRemote = false) { + loggerDebug = debug; + loggerRemote = isRemote; +} +function logInfo(message, previousWasSingleLine = false) { + if (previousWasSingleLine && !loggerRemote) { + console.log(); } - }); - - similar.sort((a, b) => a.localeCompare(b)); - if (searchingOptions) { - similar = similar.map((candidate) => `--${candidate}`); - } - - if (similar.length > 1) { - return `\n(Did you mean one of ${similar.join(', ')}?)`; - } - if (similar.length === 1) { - return `\n(Did you mean ${similar[0]}?)`; - } - return ''; + console.log(message); +} +function logWarning(message) { + console.warn(message); +} +function logError(message) { + console.error(message.toString()); +} +function logDebugInfo(message, previousWasSingleLine = false) { + if (loggerDebug) { + logInfo(message, previousWasSingleLine); + } +} +function logDebugWarning(message) { + if (loggerDebug) { + logWarning(message); + } +} +function logDebugError(message) { + if (loggerDebug) { + logError(message.toString()); + } +} +function logSingleLine(message) { + if (loggerRemote) { + console.log(message); + return; + } + readline_1.default.clearLine(process.stdout, 0); + readline_1.default.cursorTo(process.stdout, 0); + process.stdout.write(message); } - -exports.suggestSimilar = suggestSimilar; /***/ }), -/***/ 52694: -/***/ (function(module, exports) { +/***/ 9800: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// GENERATED FILE. DO NOT EDIT. -(function (global, factory) { - function preferDefault(exports) { - return exports.default || exports; - } - if (typeof define === "function" && define.amd) { - define([], function () { - var exports = {}; - factory(exports); - return preferDefault(exports); - }); - } else if (true) { - factory(exports); - if (true) module.exports = preferDefault(exports); - } else {} -})( - typeof globalThis !== "undefined" - ? globalThis - : typeof self !== "undefined" - ? self - : this, - function (_exports) { - "use strict"; - - Object.defineProperty(_exports, "__esModule", { - value: true, - }); - _exports.default = void 0; - /** - * @license - * Copyright 2009 The Closure Library Authors - * Copyright 2020 Daniel Wirtz / The long.js 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 - * - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - */ +"use strict"; - // WebAssembly optimizations to do native i64 multiplication and divide - var wasm = null; - try { - wasm = new WebAssembly.Instance( - new WebAssembly.Module( - new Uint8Array([ - // \0asm - 0, 97, 115, 109, - // version 1 - 1, 0, 0, 0, - // section "type" - 1, 13, 2, - // 0, () => i32 - 96, 0, 1, 127, - // 1, (i32, i32, i32, i32) => i32 - 96, 4, 127, 127, 127, 127, 1, 127, - // section "function" - 3, 7, 6, - // 0, type 0 - 0, - // 1, type 1 - 1, - // 2, type 1 - 1, - // 3, type 1 - 1, - // 4, type 1 - 1, - // 5, type 1 - 1, - // section "global" - 6, 6, 1, - // 0, "high", mutable i32 - 127, 1, 65, 0, 11, - // section "export" - 7, 50, 6, - // 0, "mul" - 3, 109, 117, 108, 0, 1, - // 1, "div_s" - 5, 100, 105, 118, 95, 115, 0, 2, - // 2, "div_u" - 5, 100, 105, 118, 95, 117, 0, 3, - // 3, "rem_s" - 5, 114, 101, 109, 95, 115, 0, 4, - // 4, "rem_u" - 5, 114, 101, 109, 95, 117, 0, 5, - // 5, "get_high" - 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, - // section "code" - 10, 191, 1, 6, - // 0, "get_high" - 4, 0, 35, 0, 11, - // 1, "mul" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 2, "div_s" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 3, "div_u" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 4, "rem_s" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 5, "rem_u" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - ]), - ), - {}, - ).exports; - } catch { - // no wasm support :( +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.waitForPreviousRuns = void 0; +const workflow_repository_1 = __nccwpck_require__(779); +const logger_1 = __nccwpck_require__(8836); +const waitForPreviousRuns = async (params) => { + let attempts = 0; + while (attempts < 2000) { + const workflowRepository = new workflow_repository_1.WorkflowRepository(); + const activeRuns = await workflowRepository.getActivePreviousRuns(params); + if (activeRuns.length === 0) { + (0, logger_1.logDebugInfo)("āœ… No previous runs active. Continuing..."); + return; + } + (0, logger_1.logDebugInfo)(`ā³ Found ${activeRuns.length} previous run(s) still active. Waiting 2s...`); + await new Promise((res) => setTimeout(res, 2000)); + attempts++; } + throw new Error("Timeout waiting for previous runs to finish."); +}; +exports.waitForPreviousRuns = waitForPreviousRuns; - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * @exports Long - * @class A Long class for representing a 64 bit two's-complement integer value. - * @param {number} low The low (signed) 32 bits of the long - * @param {number} high The high (signed) 32 bits of the long - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @constructor - */ - function Long(low, high, unsigned) { - /** - * The low 32 bits as a signed value. - * @type {number} - */ - this.low = low | 0; - /** - * The high 32 bits as a signed value. - * @type {number} - */ - this.high = high | 0; +/***/ }), - /** - * Whether unsigned or not. - * @type {boolean} - */ - this.unsigned = !!unsigned; - } - - // The internal representation of a long is the two given signed, 32-bit values. - // We use 32-bit pieces because these are the size of integers on which - // Javascript performs bit-operations. For operations like addition and - // multiplication, we split each number into 16 bit pieces, which can easily be - // multiplied within Javascript's floating-point representation without overflow - // or change in sign. - // - // In the algorithms below, we frequently reduce the negative case to the - // positive case by negating the input(s) and then post-processing the result. - // Note that we must ALWAYS check specially whether those values are MIN_VALUE - // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - // a positive number, it overflows back into a negative). Not handling this - // case would often result in infinite recursion. - // - // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* - // methods on which they depend. +/***/ 6676: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * An indicator used to reliably determine if an object is a Long or not. - * @type {boolean} - * @const - * @private - */ - Long.prototype.__isLong__; - Object.defineProperty(Long.prototype, "__isLong__", { - value: true, - }); +"use strict"; - /** - * @function - * @param {*} obj Object - * @returns {boolean} - * @inner - */ - function isLong(obj) { - return (obj && obj["__isLong__"]) === true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.extractVersionFromBranch = exports.extractIssueNumberFromPush = exports.extractIssueNumberFromBranch = void 0; +const logger_1 = __nccwpck_require__(8836); +const extractIssueNumberFromBranch = (branchName) => { + const match = branchName?.match(/[a-zA-Z]+\/([0-9]+)-.*/); + if (match) { + return parseInt(match[1]); } - - /** - * @function - * @param {*} value number - * @returns {number} - * @inner - */ - function ctz32(value) { - var c = Math.clz32(value & -value); - return value ? 31 - c : c; + else { + (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); + return -1; + } +}; +exports.extractIssueNumberFromBranch = extractIssueNumberFromBranch; +const extractIssueNumberFromPush = (branchName) => { + const issueNumberMatch = branchName.match(/^[^/]+\/(\d+)-/); + if (!issueNumberMatch) { + (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); + return -1; + } + const issueNumber = parseInt(issueNumberMatch[1], 10); + (0, logger_1.logDebugInfo)(`Linked Issue: #${issueNumber}`); + return issueNumber; +}; +exports.extractIssueNumberFromPush = extractIssueNumberFromPush; +const extractVersionFromBranch = (branchName) => { + const match = branchName?.match(/^[^\/]+\/(\d+\.\d+\.\d+)$/); + if (match) { + return match[1]; } + else { + (0, logger_1.logDebugInfo)('No version found in the branch name.'); + return undefined; + } +}; +exports.extractVersionFromBranch = extractVersionFromBranch; - /** - * Tests if the specified object is a Long. - * @function - * @param {*} obj Object - * @returns {boolean} - */ - Long.isLong = isLong; - /** - * A cache of the Long representations of small integer values. - * @type {!Object} - * @inner - */ - var INT_CACHE = {}; +/***/ }), - /** - * A cache of the Long representations of small unsigned integer values. - * @type {!Object} - * @inner - */ - var UINT_CACHE = {}; +/***/ 9887: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromInt(value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, 0, true); - if (cache) UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache) INT_CACHE[value] = obj; - return obj; - } +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getLatestVersion = exports.incrementVersion = void 0; +const logger_1 = __nccwpck_require__(8836); +const incrementVersion = (version, releaseType) => { + (0, logger_1.logDebugInfo)(`Incrementing version ${version}.`); + const versionParts = version.split('.').map(Number); + if (versionParts.length !== 3) { + throw new Error('Invalid version format'); + } + const [major, minor, patch] = versionParts; + switch (releaseType) { + case 'Major': + // Increment the major version and reset minor and patch + return `${major + 1}.0.0`; + case 'Minor': + // Increment the minor version and reset patch + return `${major}.${minor + 1}.0`; + case 'Patch': + // Increment the patch version + return `${major}.${minor}.${patch + 1}`; + default: + throw new Error('Unknown release type'); } +}; +exports.incrementVersion = incrementVersion; +const getLatestVersion = (versions) => { + return versions + .map(version => version.split('.').map(num => parseInt(num, 10))) + .sort((a, b) => { + for (let i = 0; i < 3; i++) { + if (a[i] > b[i]) + return 1; + if (a[i] < b[i]) + return -1; + } + return 0; + }) + .map(version => version.join('.')) + .pop(); +}; +exports.getLatestVersion = getLatestVersion; - /** - * Returns a Long representing the given 32 bit integer value. - * @function - * @param {number} value The 32 bit integer in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromInt = fromInt; - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromNumber(value, unsigned) { - if (isNaN(value)) return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) return UZERO; - if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; - } - if (value < 0) return fromNumber(-value, unsigned).neg(); - return fromBits( - value % TWO_PWR_32_DBL | 0, - (value / TWO_PWR_32_DBL) | 0, - unsigned, - ); +/***/ }), + +/***/ 8198: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.loadActionYaml = loadActionYaml; +exports.getActionInputs = getActionInputs; +exports.getActionInputsWithDefaults = getActionInputsWithDefaults; +const fs = __importStar(__nccwpck_require__(7147)); +const path = __importStar(__nccwpck_require__(1017)); +const yaml = __importStar(__nccwpck_require__(1917)); +function loadActionYaml() { + const actionYamlPath = path.join(process.cwd(), 'action.yml'); + const yamlContent = fs.readFileSync(actionYamlPath, 'utf8'); + return yaml.load(yamlContent); +} +function getActionInputs() { + const actionYaml = loadActionYaml(); + return actionYaml.inputs; +} +function getActionInputsWithDefaults() { + const inputs = getActionInputs(); + const inputsWithDefaults = {}; + for (const [key, value] of Object.entries(inputs)) { + inputsWithDefaults[key] = value.default; } + return inputsWithDefaults; +} - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @function - * @param {number} value The number in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromNumber = fromNumber; - /** - * @param {number} lowBits - * @param {number} highBits - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } +/***/ }), - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is - * assumed to use 32 bits. - * @function - * @param {number} lowBits The low 32 bits - * @param {number} highBits The high 32 bits - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromBits = fromBits; +/***/ 9491: +/***/ ((module) => { - /** - * @function - * @param {number} base - * @param {number} exponent - * @returns {number} - * @inner - */ - var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) +"use strict"; +module.exports = require("assert"); - /** - * @param {string} str - * @param {(boolean|number)=} unsigned - * @param {number=} radix - * @returns {!Long} - * @inner - */ - function fromString(str, unsigned, radix) { - if (str.length === 0) throw Error("empty string"); - if (typeof unsigned === "number") { - // For goog.math.long compatibility - radix = unsigned; - unsigned = false; - } else { - unsigned = !!unsigned; - } - if ( - str === "NaN" || - str === "Infinity" || - str === "+Infinity" || - str === "-Infinity" - ) - return unsigned ? UZERO : ZERO; - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - var p; - if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen"); - else if (p === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); - } +/***/ }), - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 8)); - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), - value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = fromNumber(pow_dbl(radix, size)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } +/***/ 852: +/***/ ((module) => { - /** - * Returns a Long representation of the given string, written using the specified radix. - * @function - * @param {string} str The textual representation of the Long - * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed - * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 - * @returns {!Long} The corresponding Long value - */ - Long.fromString = fromString; +"use strict"; +module.exports = require("async_hooks"); - /** - * @function - * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromValue(val, unsigned) { - if (typeof val === "number") return fromNumber(val, unsigned); - if (typeof val === "string") return fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return fromBits( - val.low, - val.high, - typeof unsigned === "boolean" ? unsigned : val.unsigned, - ); - } +/***/ }), - /** - * Converts the specified value to a Long using the appropriate from* function for its type. - * @function - * @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} - */ - Long.fromValue = fromValue; +/***/ 4300: +/***/ ((module) => { - // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be - // no runtime penalty for these. +"use strict"; +module.exports = require("buffer"); - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_16_DBL = 1 << 16; +/***/ }), - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_24_DBL = 1 << 24; +/***/ 2081: +/***/ ((module) => { - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +"use strict"; +module.exports = require("child_process"); - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +/***/ }), - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +/***/ 6206: +/***/ ((module) => { - /** - * @type {!Long} - * @const - * @inner - */ - var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); +"use strict"; +module.exports = require("console"); - /** - * @type {!Long} - * @inner - */ - var ZERO = fromInt(0); +/***/ }), - /** - * Signed zero. - * @type {!Long} - */ - Long.ZERO = ZERO; +/***/ 6113: +/***/ ((module) => { - /** - * @type {!Long} - * @inner - */ - var UZERO = fromInt(0, true); +"use strict"; +module.exports = require("crypto"); - /** - * Unsigned zero. - * @type {!Long} - */ - Long.UZERO = UZERO; +/***/ }), - /** - * @type {!Long} - * @inner - */ - var ONE = fromInt(1); +/***/ 7643: +/***/ ((module) => { - /** - * Signed one. - * @type {!Long} - */ - Long.ONE = ONE; +"use strict"; +module.exports = require("diagnostics_channel"); - /** - * @type {!Long} - * @inner - */ - var UONE = fromInt(1, true); +/***/ }), - /** - * Unsigned one. - * @type {!Long} - */ - Long.UONE = UONE; +/***/ 2361: +/***/ ((module) => { - /** - * @type {!Long} - * @inner - */ - var NEG_ONE = fromInt(-1); +"use strict"; +module.exports = require("events"); - /** - * Signed negative one. - * @type {!Long} - */ - Long.NEG_ONE = NEG_ONE; +/***/ }), - /** - * @type {!Long} - * @inner - */ - var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +/***/ 7147: +/***/ ((module) => { - /** - * Maximum signed value. - * @type {!Long} - */ - Long.MAX_VALUE = MAX_VALUE; +"use strict"; +module.exports = require("fs"); - /** - * @type {!Long} - * @inner - */ - var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true); +/***/ }), - /** - * Maximum unsigned value. - * @type {!Long} - */ - Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; +/***/ 3685: +/***/ ((module) => { - /** - * @type {!Long} - * @inner - */ - var MIN_VALUE = fromBits(0, 0x80000000 | 0, false); +"use strict"; +module.exports = require("http"); - /** - * Minimum signed value. - * @type {!Long} - */ - Long.MIN_VALUE = MIN_VALUE; +/***/ }), - /** - * @alias Long.prototype - * @inner - */ - var LongPrototype = Long.prototype; +/***/ 5158: +/***/ ((module) => { - /** - * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. - * @this {!Long} - * @returns {number} - */ - LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - }; +"use strict"; +module.exports = require("http2"); - /** - * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). - * @this {!Long} - * @returns {number} - */ - LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; +/***/ }), - /** - * Converts the Long to a string written in the specified radix. - * @this {!Long} - * @param {number=} radix Radix (2-36), defaults to 10 - * @returns {string} - * @override - * @throws {RangeError} If `radix` is out of range - */ - LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - if (this.isZero()) return "0"; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = fromNumber(radix), - div = this.div(radixLong), - rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else return "-" + this.neg().toString(radix); - } +/***/ 5687: +/***/ ((module) => { - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), - rem = this; - var result = ""; - while (true) { - var remDiv = rem.div(radixToPower), - intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, - digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) return digits + result; - else { - while (digits.length < 6) digits = "0" + digits; - result = "" + digits + result; - } - } - }; +"use strict"; +module.exports = require("https"); - /** - * Gets the high 32 bits as a signed integer. - * @this {!Long} - * @returns {number} Signed high bits - */ - LongPrototype.getHighBits = function getHighBits() { - return this.high; - }; +/***/ }), - /** - * Gets the high 32 bits as an unsigned integer. - * @this {!Long} - * @returns {number} Unsigned high bits - */ - LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; - }; +/***/ 1808: +/***/ ((module) => { - /** - * Gets the low 32 bits as a signed integer. - * @this {!Long} - * @returns {number} Signed low bits - */ - LongPrototype.getLowBits = function getLowBits() { - return this.low; - }; +"use strict"; +module.exports = require("net"); - /** - * Gets the low 32 bits as an unsigned integer. - * @this {!Long} - * @returns {number} Unsigned low bits - */ - LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; - }; +/***/ }), - /** - * Gets the number of bits needed to represent the absolute value of this Long. - * @this {!Long} - * @returns {number} - */ - LongPrototype.getNumBitsAbs = function getNumBitsAbs() { - if (this.isNegative()) - // Unsigned Longs are never negative - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break; - return this.high != 0 ? bit + 33 : bit + 1; - }; +/***/ 7718: +/***/ ((module) => { - /** - * Tests if this Long can be safely represented as a JavaScript number. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isSafeInteger = function isSafeInteger() { - // 2^53-1 is the maximum safe value - var top11Bits = this.high >> 21; - // [0, 2^53-1] - if (!top11Bits) return true; - // > 2^53-1 - if (this.unsigned) return false; - // [-2^53, -1] except -2^53 - return top11Bits === -1 && !(this.low === 0 && this.high === -0x200000); - }; +"use strict"; +module.exports = require("node:child_process"); - /** - * Tests if this Long's value equals zero. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; - }; +/***/ }), - /** - * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. - * @returns {boolean} - */ - LongPrototype.eqz = LongPrototype.isZero; +/***/ 6005: +/***/ ((module) => { - /** - * Tests if this Long's value is negative. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; - }; +"use strict"; +module.exports = require("node:crypto"); - /** - * Tests if this Long's value is positive or zero. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; - }; +/***/ }), - /** - * Tests if this Long's value is odd. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; - }; +/***/ 5673: +/***/ ((module) => { - /** - * Tests if this Long's value is even. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isEven = function isEven() { - return (this.low & 1) === 0; - }; +"use strict"; +module.exports = require("node:events"); - /** - * Tests if this Long's value equals the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.equals = function equals(other) { - if (!isLong(other)) other = fromValue(other); - if ( - this.unsigned !== other.unsigned && - this.high >>> 31 === 1 && - other.high >>> 31 === 1 - ) - return false; - return this.high === other.high && this.low === other.low; - }; +/***/ }), - /** - * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.eq = LongPrototype.equals; +/***/ 7561: +/***/ ((module) => { - /** - * Tests if this Long's value differs from the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.notEquals = function notEquals(other) { - return !this.eq(/* validates */ other); - }; +"use strict"; +module.exports = require("node:fs"); - /** - * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.neq = LongPrototype.notEquals; +/***/ }), - /** - * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.ne = LongPrototype.notEquals; +/***/ 9411: +/***/ ((module) => { - /** - * Tests if this Long's value is less than the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThan = function lessThan(other) { - return this.comp(/* validates */ other) < 0; - }; +"use strict"; +module.exports = require("node:path"); - /** - * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lt = LongPrototype.lessThan; +/***/ }), - /** - * Tests if this Long's value is less than or equal the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp(/* validates */ other) <= 0; - }; +/***/ 7742: +/***/ ((module) => { - /** - * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lte = LongPrototype.lessThanOrEqual; +"use strict"; +module.exports = require("node:process"); - /** - * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.le = LongPrototype.lessThanOrEqual; +/***/ }), - /** - * Tests if this Long's value is greater than the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.greaterThan = function greaterThan(other) { - return this.comp(/* validates */ other) > 0; - }; +/***/ 4492: +/***/ ((module) => { - /** - * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.gt = LongPrototype.greaterThan; +"use strict"; +module.exports = require("node:stream"); - /** - * Tests if this Long's value is greater than or equal the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp(/* validates */ other) >= 0; - }; +/***/ }), - /** - * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.gte = LongPrototype.greaterThanOrEqual; +/***/ 7261: +/***/ ((module) => { - /** - * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.ge = LongPrototype.greaterThanOrEqual; +"use strict"; +module.exports = require("node:util"); - /** - * Compares this Long's value with the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater - */ - LongPrototype.compare = function compare(other) { - if (!isLong(other)) other = fromValue(other); - if (this.eq(other)) return 0; - var thisNeg = this.isNegative(), - otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) return -1; - if (!thisNeg && otherNeg) return 1; - // At this point the sign bits are the same - if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; +/***/ }), - /** - * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater - */ - LongPrototype.comp = LongPrototype.compare; +/***/ 2037: +/***/ ((module) => { - /** - * Negates this Long's value. - * @this {!Long} - * @returns {!Long} Negated Long - */ - LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; - return this.not().add(ONE); - }; +"use strict"; +module.exports = require("os"); - /** - * Negates this Long's value. This is an alias of {@link Long#negate}. - * @function - * @returns {!Long} Negated Long - */ - LongPrototype.neg = LongPrototype.negate; +/***/ }), - /** - * Returns the sum of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} addend Addend - * @returns {!Long} Sum - */ - LongPrototype.add = function add(addend) { - if (!isLong(addend)) addend = fromValue(addend); - - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; +/***/ 1017: +/***/ ((module) => { - /** - * Returns the difference of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} subtrahend Subtrahend - * @returns {!Long} Difference - */ - LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; +"use strict"; +module.exports = require("path"); - /** - * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. - * @function - * @param {!Long|number|bigint|string} subtrahend Subtrahend - * @returns {!Long} Difference - */ - LongPrototype.sub = LongPrototype.subtract; +/***/ }), - /** - * Returns the product of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.multiply = function multiply(multiplier) { - if (this.isZero()) return this; - if (!isLong(multiplier)) multiplier = fromValue(multiplier); - - // use wasm support if present - if (wasm) { - var low = wasm["mul"]( - this.low, - this.high, - multiplier.low, - multiplier.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO; - if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); - else return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - - // If both longs are small, use float multiplication - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber( - this.toNumber() * multiplier.toNumber(), - this.unsigned, - ); +/***/ 4074: +/***/ ((module) => { - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; +"use strict"; +module.exports = require("perf_hooks"); - /** - * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. - * @function - * @param {!Long|number|bigint|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.mul = LongPrototype.multiply; +/***/ }), - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or - * unsigned if this Long is unsigned. - * @this {!Long} - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Quotient - */ - LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - if (divisor.isZero()) throw Error("division by zero"); - - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if ( - !this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1 - ) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( - this.low, - this.high, - divisor.low, - divisor.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (this.isZero()) return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(MIN_VALUE)) return ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) divisor = divisor.toUnsigned(); - if (divisor.gt(this)) return UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return UONE; - res = UZERO; - } +/***/ 3477: +/***/ ((module) => { - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2), - delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - approxRes = fromNumber(approx), - approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) approxRes = ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; +"use strict"; +module.exports = require("querystring"); - /** - * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Quotient - */ - LongPrototype.div = LongPrototype.divide; +/***/ }), - /** - * Returns this Long modulo the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( - this.low, - this.high, - divisor.low, - divisor.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; +/***/ 4521: +/***/ ((module) => { - /** - * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.mod = LongPrototype.modulo; +"use strict"; +module.exports = require("readline"); - /** - * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.rem = LongPrototype.modulo; +/***/ }), - /** - * Returns the bitwise NOT of this Long. - * @this {!Long} - * @returns {!Long} - */ - LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); - }; +/***/ 2781: +/***/ ((module) => { - /** - * Returns count leading zeros of this Long. - * @this {!Long} - * @returns {!number} - */ - LongPrototype.countLeadingZeros = function countLeadingZeros() { - return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; - }; +"use strict"; +module.exports = require("stream"); - /** - * Returns count leading zeros. This is an alias of {@link Long#countLeadingZeros}. - * @function - * @param {!Long} - * @returns {!number} - */ - LongPrototype.clz = LongPrototype.countLeadingZeros; +/***/ }), - /** - * Returns count trailing zeros of this Long. - * @this {!Long} - * @returns {!number} - */ - LongPrototype.countTrailingZeros = function countTrailingZeros() { - return this.low ? ctz32(this.low) : ctz32(this.high) + 32; - }; +/***/ 5356: +/***/ ((module) => { - /** - * Returns count trailing zeros. This is an alias of {@link Long#countTrailingZeros}. - * @function - * @param {!Long} - * @returns {!number} - */ - LongPrototype.ctz = LongPrototype.countTrailingZeros; +"use strict"; +module.exports = require("stream/web"); - /** - * Returns the bitwise AND of this Long and the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.and = function and(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low & other.low, - this.high & other.high, - this.unsigned, - ); - }; +/***/ }), - /** - * Returns the bitwise OR of this Long and the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.or = function or(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low | other.low, - this.high | other.high, - this.unsigned, - ); - }; +/***/ 1576: +/***/ ((module) => { - /** - * Returns the bitwise XOR of this Long and the given one. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.xor = function xor(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low ^ other.low, - this.high ^ other.high, - this.unsigned, - ); - }; +"use strict"; +module.exports = require("string_decoder"); - /** - * Returns this Long with bits shifted to the left by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - this.low << numBits, - (this.high << numBits) | (this.low >>> (32 - numBits)), - this.unsigned, - ); - else return fromBits(0, this.low << (numBits - 32), this.unsigned); - }; +/***/ }), - /** - * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shl = LongPrototype.shiftLeft; +/***/ 9512: +/***/ ((module) => { - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - (this.low >>> numBits) | (this.high << (32 - numBits)), - this.high >> numBits, - this.unsigned, - ); - else - return fromBits( - this.high >> (numBits - 32), - this.high >= 0 ? 0 : -1, - this.unsigned, - ); - }; +"use strict"; +module.exports = require("timers"); - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shr = LongPrototype.shiftRight; +/***/ }), - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits < 32) - return fromBits( - (this.low >>> numBits) | (this.high << (32 - numBits)), - this.high >>> numBits, - this.unsigned, - ); - if (numBits === 32) return fromBits(this.high, 0, this.unsigned); - return fromBits(this.high >>> (numBits - 32), 0, this.unsigned); - }; +/***/ 4404: +/***/ ((module) => { - /** - * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shru = LongPrototype.shiftRightUnsigned; +"use strict"; +module.exports = require("tls"); - /** - * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; +/***/ }), - /** - * Returns this Long with bits rotated to the left by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotateLeft = function rotateLeft(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - (this.low << numBits) | (this.high >>> b), - (this.high << numBits) | (this.low >>> b), - this.unsigned, - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - (this.high << numBits) | (this.low >>> b), - (this.low << numBits) | (this.high >>> b), - this.unsigned, - ); - }; - /** - * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotl = LongPrototype.rotateLeft; +/***/ 7310: +/***/ ((module) => { - /** - * Returns this Long with bits rotated to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotateRight = function rotateRight(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - (this.high << b) | (this.low >>> numBits), - (this.low << b) | (this.high >>> numBits), - this.unsigned, - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - (this.low << b) | (this.high >>> numBits), - (this.high << b) | (this.low >>> numBits), - this.unsigned, - ); - }; - /** - * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotr = LongPrototype.rotateRight; +"use strict"; +module.exports = require("url"); - /** - * Converts this Long to signed. - * @this {!Long} - * @returns {!Long} Signed long - */ - LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) return this; - return fromBits(this.low, this.high, false); - }; +/***/ }), - /** - * Converts this Long to unsigned. - * @this {!Long} - * @returns {!Long} Unsigned long - */ - LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) return this; - return fromBits(this.low, this.high, true); - }; +/***/ 3837: +/***/ ((module) => { - /** - * Converts this Long to its byte representation. - * @param {boolean=} le Whether little or big endian, defaults to big endian - * @this {!Long} - * @returns {!Array.} Byte representation - */ - LongPrototype.toBytes = function toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; +"use strict"; +module.exports = require("util"); - /** - * Converts this Long to its little endian byte representation. - * @this {!Long} - * @returns {!Array.} Little endian byte representation - */ - LongPrototype.toBytesLE = function toBytesLE() { - var hi = this.high, - lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24, - ]; - }; +/***/ }), - /** - * Converts this Long to its big endian byte representation. - * @this {!Long} - * @returns {!Array.} Big endian byte representation - */ - LongPrototype.toBytesBE = function toBytesBE() { - var hi = this.high, - lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff, - ]; - }; +/***/ 9830: +/***/ ((module) => { - /** - * Creates a Long from its byte representation. - * @param {!Array.} bytes Byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @param {boolean=} le Whether little or big endian, defaults to big endian - * @returns {Long} The corresponding Long value - */ - Long.fromBytes = function fromBytes(bytes, unsigned, le) { - return le - ? Long.fromBytesLE(bytes, unsigned) - : Long.fromBytesBE(bytes, unsigned); - }; +"use strict"; +module.exports = require("util/types"); - /** - * Creates a Long from its little endian byte representation. - * @param {!Array.} bytes Little endian byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {Long} The corresponding Long value - */ - Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { - return new Long( - bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), - bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), - unsigned, - ); - }; +/***/ }), - /** - * Creates a Long from its big endian byte representation. - * @param {!Array.} bytes Big endian byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {Long} The corresponding Long value - */ - Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { - return new Long( - (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], - (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], - unsigned, - ); - }; +/***/ 1267: +/***/ ((module) => { - // Support conversion to/from BigInt where available - if (typeof BigInt === "function") { - /** - * Returns a Long representing the given big integer. - * @function - * @param {number} value The big integer value - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromBigInt = function fromBigInt(value, unsigned) { - var lowBits = Number(BigInt.asIntN(32, value)); - var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); - return fromBits(lowBits, highBits, unsigned); - }; +"use strict"; +module.exports = require("worker_threads"); - // Override - Long.fromValue = function fromValueWithBigInt(value, unsigned) { - if (typeof value === "bigint") return Long.fromBigInt(value, unsigned); - return fromValue(value, unsigned); - }; +/***/ }), - /** - * Converts the Long to its big integer representation. - * @this {!Long} - * @returns {bigint} - */ - LongPrototype.toBigInt = function toBigInt() { - var lowBigInt = BigInt(this.low >>> 0); - var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); - return (highBigInt << BigInt(32)) | lowBigInt; - }; - } - var _default = (_exports.default = Long); - }, -); +/***/ 9796: +/***/ ((module) => { +"use strict"; +module.exports = require("zlib"); /***/ }), -/***/ 88757: +/***/ 2960: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! Axios v1.13.1 Copyright (c) 2025 Matt Zabriskie and contributors */ - - -const FormData$1 = __nccwpck_require__(91403); -const crypto = __nccwpck_require__(6113); -const url = __nccwpck_require__(57310); -const http2 = __nccwpck_require__(85158); -const proxyFromEnv = __nccwpck_require__(63329); -const http = __nccwpck_require__(13685); -const https = __nccwpck_require__(95687); -const util = __nccwpck_require__(73837); -const followRedirects = __nccwpck_require__(67707); -const zlib = __nccwpck_require__(59796); -const stream = __nccwpck_require__(12781); -const events = __nccwpck_require__(82361); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1); -const crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto); -const url__default = /*#__PURE__*/_interopDefaultLegacy(url); -const proxyFromEnv__default = /*#__PURE__*/_interopDefaultLegacy(proxyFromEnv); -const http__default = /*#__PURE__*/_interopDefaultLegacy(http); -const https__default = /*#__PURE__*/_interopDefaultLegacy(https); -const util__default = /*#__PURE__*/_interopDefaultLegacy(util); -const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); -const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); -const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); -/** - * Create a bound version of a function with a specified `this` context - * - * @param {Function} fn - The function to bind - * @param {*} thisArg - The value to be passed as the `this` parameter - * @returns {Function} A new function that will call the original function with the specified `this` context - */ -function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; + +const WritableStream = (__nccwpck_require__(4492).Writable) +const inherits = (__nccwpck_require__(7261).inherits) + +const StreamSearch = __nccwpck_require__(1142) + +const PartStream = __nccwpck_require__(1620) +const HeaderParser = __nccwpck_require__(2032) + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return + } + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } } -// utils is a library of generic helper functions non-specific to axios - -const {toString} = Object.prototype; -const {getPrototypeOf} = Object; -const {iterator, toStringTag} = Symbol; - -const kindOf = (cache => thing => { - const str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); -})(Object.create(null)); - -const kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type -}; +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } -const typeOfTest = type => thing => typeof thing === type; + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * - * @returns {boolean} True if value is an Array, otherwise false - */ -const {isArray} = Array; + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } -/** - * Determine if a value is undefined - * - * @param {*} val The value to test - * - * @returns {boolean} True if the value is undefined, otherwise false - */ -const isUndefined = typeOfTest('undefined'); + this._bparser.push(data) -/** - * Determine if a value is a Buffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val); + if (this._pause) { this._cb = cb } else { cb() } } -/** - * Determine if a value is an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -const isArrayBuffer = kindOfTest('ArrayBuffer'); +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - let result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() } - return result; } -/** - * Determine if a value is a String - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a String, otherwise false - */ -const isString = typeOfTest('string'); +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true -/** - * Determine if a value is a Function - * - * @param {*} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -const isFunction$1 = typeOfTest('function'); + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } + } + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } + } + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() + } + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} -/** - * Determine if a value is a Number - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Number, otherwise false - */ -const isNumber = typeOfTest('number'); +Dicer.prototype._unpause = function () { + if (!this._pause) { return } -/** - * Determine if a value is an Object - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an Object, otherwise false - */ -const isObject = (thing) => thing !== null && typeof thing === 'object'; + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} -/** - * Determine if a value is a Boolean - * - * @param {*} thing The value to test - * @returns {boolean} True if value is a Boolean, otherwise false - */ -const isBoolean = thing => thing === true || thing === false; +module.exports = Dicer -/** - * Determine if a value is a plain Object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a plain Object, otherwise false - */ -const isPlainObject = (val) => { - if (kindOf(val) !== 'object') { - return false; - } - const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val); -}; +/***/ }), -/** - * Determine if a value is an empty object (safely handles Buffers) - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is an empty object, otherwise false - */ -const isEmptyObject = (val) => { - // Early return for non-objects or Buffers to prevent RangeError - if (!isObject(val) || isBuffer(val)) { - return false; - } +/***/ 2032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype; - } catch (e) { - // Fallback for any other objects that might cause RangeError with Object.keys() - return false; - } -}; +"use strict"; -/** - * Determine if a value is a Date - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Date, otherwise false - */ -const isDate = kindOfTest('Date'); -/** - * Determine if a value is a File - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ -const isFile = kindOfTest('File'); +const EventEmitter = (__nccwpck_require__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) +const getLimit = __nccwpck_require__(1467) -/** - * Determine if a value is a Blob - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Blob, otherwise false - */ -const isBlob = kindOfTest('Blob'); +const StreamSearch = __nccwpck_require__(1142) -/** - * Determine if a value is a FileList - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ -const isFileList = kindOfTest('FileList'); +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex -/** - * Determine if a value is a Stream - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Stream, otherwise false - */ -const isStream = (val) => isObject(val) && isFunction$1(val.pipe); +function HeaderParser (cfg) { + EventEmitter.call(this) -/** - * Determine if a value is a FormData - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an FormData, otherwise false - */ -const isFormData = (thing) => { - let kind; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || ( - isFunction$1(thing.append) && ( - (kind = kindOf(thing)) === 'formdata' || - // detect form-data instance - (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]') - ) - ) - ) -}; + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } -/** - * Determine if a value is a URLSearchParams object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -const isURLSearchParams = kindOfTest('URLSearchParams'); + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) -const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * - * @returns {String} The String freed of excess whitespace - */ -const trim = (str) => str.trim ? - str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - * - * @param {Boolean} [allOwnKeys = false] - * @returns {any} - */ -function forEach(obj, fn, {allOwnKeys = false} = {}) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} - let i; - let l; +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h - if (isArray(obj)) { - // Iterate over array values - for (i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Buffer check - if (isBuffer(obj)) { - return; + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } } - // Iterate over object keys - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; - - for (i = 0; i < len; i++) { - key = keys[i]; - fn.call(null, obj[key], key, obj); + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } } } -function findKey(obj, key) { - if (isBuffer(obj)){ - return null; - } +module.exports = HeaderParser - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; - } - } - return null; -} -const _global = (() => { - /*eslint no-undef:0*/ - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) -})(); +/***/ }), + +/***/ 1620: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const isContextDefined = (context) => !isUndefined(context) && context !== _global; +"use strict"; -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - const {caseless, skipUndefined} = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray(val)) { - result[targetKey] = val.slice(); - } else if (!skipUndefined || !isUndefined(val)) { - result[targetKey] = val; - } - }; - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach(arguments[i], assignValue); - } - return result; +const inherits = (__nccwpck_require__(7261).inherits) +const ReadableStream = (__nccwpck_require__(4492).Readable) + +function PartStream (opts) { + ReadableStream.call(this, opts) } +inherits(PartStream, ReadableStream) -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * - * @param {Boolean} [allOwnKeys] - * @returns {Object} The resulting value of object a - */ -const extend = (a, b, thisArg, {allOwnKeys}= {}) => { - forEach(b, (val, key) => { - if (thisArg && isFunction$1(val)) { - a[key] = bind(val, thisArg); - } else { - a[key] = val; - } - }, {allOwnKeys}); - return a; -}; +PartStream.prototype._read = function (n) {} -/** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * - * @returns {string} content value without BOM - */ -const stripBOM = (content) => { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -}; +module.exports = PartStream -/** - * Inherit the prototype methods from one constructor into another - * @param {function} constructor - * @param {function} superConstructor - * @param {object} [props] - * @param {object} [descriptors] - * - * @returns {void} - */ -const inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, 'super', { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); -}; -/** - * Resolve object with deep prototype chain to a flat object - * @param {Object} sourceObj source object - * @param {Object} [destObj] - * @param {Function|Boolean} [filter] - * @param {Function} [propFilter] - * - * @returns {Object} - */ -const toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i; - let prop; - const merged = {}; - - destObj = destObj || {}; - // eslint-disable-next-line no-eq-null,eqeqeq - if (sourceObj == null) return destObj; - - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } - } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); +/***/ }), - return destObj; -}; +/***/ 1142: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Determines whether a string ends with the characters of a specified string - * - * @param {String} str - * @param {String} searchString - * @param {Number} [position= 0] - * - * @returns {boolean} - */ -const endsWith = (str, searchString, position) => { - str = String(str); - if (position === undefined || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; -}; +"use strict"; /** - * Returns new array from array like object or null if failed - * - * @param {*} [thing] + * Copyright Brian White. All rights reserved. * - * @returns {?Array} - */ -const toArray = (thing) => { - if (!thing) return null; - if (isArray(thing)) return thing; - let i = thing.length; - if (!isNumber(i)) return null; - const arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; -}; - -/** - * Checking if the Uint8Array exists and if it does, it returns a function that checks if the - * thing passed in is an instance of Uint8Array + * @see https://github.com/mscdex/streamsearch * - * @param {TypedArray} + * 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: * - * @returns {Array} - */ -// eslint-disable-next-line func-names -const isTypedArray = (TypedArray => { - // eslint-disable-next-line func-names - return thing => { - return TypedArray && thing instanceof TypedArray; - }; -})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); - -/** - * For each entry in the object, call the function with the key and value. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * - * @param {Object} obj - The object to iterate over. - * @param {Function} fn - The function to call for each entry. + * 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. * - * @returns {void} + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool */ -const forEachEntry = (obj, fn) => { - const generator = obj && obj[iterator]; - - const _iterator = generator.call(obj); +const EventEmitter = (__nccwpck_require__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) - let result; +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } - while ((result = _iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') } -}; -/** - * It takes a regular expression and a string, and returns an array of all the matches - * - * @param {string} regExp - The regular expression to match against. - * @param {string} str - The string to search. - * - * @returns {Array} - */ -const matchAll = (regExp, str) => { - let matches; - const arr = []; + const needleLength = needle.length - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') } - return arr; -}; + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } -/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ -const isHTMLForm = kindOfTest('HTMLFormElement'); + this.maxMatches = Infinity + this.matches = 0 -const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, - function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; - } - ); -}; + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 -/* Creating a function that will check if an object has a property. */ -const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); + this._lookbehind = Buffer.alloc(needleLength) -/** - * Determine if a value is a RegExp object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a RegExp object, otherwise false - */ -const isRegExp = kindOfTest('RegExp'); + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i + } +} +inherits(SBMH, EventEmitter) -const reduceDescriptors = (obj, reducer) => { - const descriptors = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} - forEach(descriptors, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; - } - }); +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} - Object.defineProperties(obj, reducedDescriptors); -}; +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] -/** - * Makes all methods read-only - * @param {Object} obj - */ + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) -const freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - // skip restricted props in strict mode - if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { - return false; + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] } - const value = obj[name]; - - if (!isFunction$1(value)) return; - - descriptor.enumerable = false; + // No match. - if ('writable' in descriptor) { - descriptor.writable = false; - return; + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } } - if (!descriptor.set) { - descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); - }; - } - }); -}; + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } -const toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff - const define = (arr) => { - arr.forEach(value => { - obj[value] = true; - }); - }; + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len - isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); + this._bufpos = len + return len + } + } - return obj; -}; + pos += (pos >= 0) * this._bufpos -const noop = () => {}; + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } -const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; -}; + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } -/** - * If the thing is a FormData object, return true, otherwise return false. - * - * @param {unknown} thing - The thing to check. - * - * @returns {boolean} - */ -function isSpecCompliantForm(thing) { - return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]); + this._bufpos = len + return len } -const toJSONObject = (obj) => { - const stack = new Array(10); +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} - const visit = (source, i) => { +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } +module.exports = SBMH - //Buffer check - if (isBuffer(source)) { - return source; - } - if(!('toJSON' in source)) { - stack[i] = source; - const target = isArray(source) ? [] : {}; +/***/ }), - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); +/***/ 727: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - stack[i] = undefined; +"use strict"; - return target; - } - } - return source; - }; +const WritableStream = (__nccwpck_require__(4492).Writable) +const { inherits } = __nccwpck_require__(7261) +const Dicer = __nccwpck_require__(2960) - return visit(obj, 0); -}; +const MultipartParser = __nccwpck_require__(2183) +const UrlencodedParser = __nccwpck_require__(8306) +const parseParams = __nccwpck_require__(1854) -const isAsyncFn = kindOfTest('AsyncFunction'); +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } -const isThenable = (thing) => - thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch); + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } -// original code -// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 + const { + headers, + ...streamOptions + } = opts -const _setImmediate = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) { - return setImmediate; + this.opts = { + autoDestroy: false, + ...streamOptions } + WritableStream.call(this, this.opts) - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({source, data}) => { - if (source === _global && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return } - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); -})( - typeof setImmediate === 'function', - isFunction$1(_global.postMessage) -); - -const asap = typeof queueMicrotask !== 'undefined' ? - queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); - -// ********************* - - -const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]); - - -const utils$1 = { - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString, - isNumber, - isBoolean, - isObject, - isPlainObject, - isEmptyObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction: isFunction$1, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap, - isIterable -}; + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [config] The config. - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * - * @returns {Error} The created error. - */ -function AxiosError(message, code, config, request, response) { - Error.call(this); +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = (new Error()).stack; + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath } - this.message = message; - this.name = 'AxiosError'; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status ? response.status : null; + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) } + throw new Error('Unsupported Content-Type.') } -utils$1.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils$1.toJSONObject(this.config), - code: this.code, - status: this.status - }; - } -}); +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} -const prototype$1 = AxiosError.prototype; -const descriptors = {}; +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy -[ - 'ERR_BAD_OPTION_VALUE', - 'ERR_BAD_OPTION', - 'ECONNABORTED', - 'ETIMEDOUT', - 'ERR_NETWORK', - 'ERR_FR_TOO_MANY_REDIRECTS', - 'ERR_DEPRECATED', - 'ERR_BAD_RESPONSE', - 'ERR_BAD_REQUEST', - 'ERR_CANCELED', - 'ERR_NOT_SUPPORT', - 'ERR_INVALID_URL' -// eslint-disable-next-line func-names -].forEach(code => { - descriptors[code] = {value: code}; -}); +module.exports.Dicer = Dicer -Object.defineProperties(AxiosError, descriptors); -Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); -// eslint-disable-next-line func-names -AxiosError.from = (error, code, config, request, response, customProps) => { - const axiosError = Object.create(prototype$1); +/***/ }), - utils$1.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }, prop => { - return prop !== 'isAxiosError'; - }); +/***/ 2183: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const msg = error && error.message ? error.message : 'Error'; +"use strict"; - // Prefer explicit code; otherwise copy the low-level error's code (e.g. ECONNREFUSED) - const errCode = code == null && error ? error.code : code; - AxiosError.call(axiosError, msg, errCode, config, request, response); - // Chain the original error on the standard field; non-enumerable to avoid JSON noise - if (error && axiosError.cause == null) { - Object.defineProperty(axiosError, 'cause', { value: error, configurable: true }); - } +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams - axiosError.name = (error && error.name) || 'Error'; +const { Readable } = __nccwpck_require__(4492) +const { inherits } = __nccwpck_require__(7261) - customProps && Object.assign(axiosError, customProps); +const Dicer = __nccwpck_require__(2960) - return axiosError; -}; +const parseParams = __nccwpck_require__(1854) +const decodeText = __nccwpck_require__(4619) +const basename = __nccwpck_require__(8647) +const getLimit = __nccwpck_require__(1467) -/** - * Determines if the given thing is a array or js object. - * - * @param {string} thing - The object or array to be visited. - * - * @returns {boolean} - */ -function isVisitable(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); -} +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i -/** - * It removes the brackets from the end of a string - * - * @param {string} key - The key of the parameter. - * - * @returns {string} the key without the brackets. - */ -function removeBrackets(key) { - return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; -} +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } -/** - * It takes a path, a key, and a boolean, and returns a string - * - * @param {string} path - The path to the current key. - * @param {string} key - The key of the current object being iterated over. - * @param {string} dots - If true, the key will be rendered with dots instead of brackets. - * - * @returns {string} The path to the current key. - */ -function renderKey(path, key, dots) { - if (!path) return key; - return path.concat(key).map(function each(token, i) { - // eslint-disable-next-line no-param-reassign - token = removeBrackets(token); - return !dots && i ? '[' + token + ']' : token; - }).join(dots ? '.' : ''); -} + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } -/** - * If the array is an array and none of its elements are visitable, then it's a flat array. - * - * @param {Array} arr - The array to check - * - * @returns {boolean} - */ -function isFlatArray(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable); -} + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } -const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); -}); + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } -/** - * Convert a data object to FormData - * - * @param {Object} obj - * @param {?Object} [formData] - * @param {?Object} [options] - * @param {Function} [options.visitor] - * @param {Boolean} [options.metaTokens = true] - * @param {Boolean} [options.dots = false] - * @param {?Boolean} [options.indexes = false] - * - * @returns {Object} - **/ + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) -/** - * It converts an object into a FormData object - * - * @param {Object} obj - The object to convert to form data. - * @param {string} formData - The FormData object to append to. - * @param {Object} options - * - * @returns - */ -function toFormData(obj, formData, options) { - if (!utils$1.isObject(obj)) { - throw new TypeError('target must be an object'); - } - - // eslint-disable-next-line no-param-reassign - formData = formData || new (FormData__default["default"] || FormData)(); - - // eslint-disable-next-line no-param-reassign - options = utils$1.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - // eslint-disable-next-line no-eq-null,eqeqeq - return !utils$1.isUndefined(source[option]); - }); + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false - const metaTokens = options.metaTokens; - // eslint-disable-next-line no-use-before-define - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy - if (!utils$1.isFunction(visitor)) { - throw new TypeError('visitor must be a function'); + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark } - function convertValue(value) { - if (value === null) return ''; - - if (utils$1.isDate(value)) { - return value.toISOString(); - } - - if (utils$1.isBoolean(value)) { - return value.toString(); + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() } - - if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError('Blob is not supported. Use a Buffer instead.'); + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) } - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') } - return value; - } + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 - /** - * Default visitor. - * - * @param {*} value - * @param {String|Number} key - * @param {Array} path - * @this {FormData} - * - * @returns {boolean} return true to visit the each prop of the value recursively - */ - function defaultVisitor(value, key, path) { - let arr = value; - - if (value && !path && typeof value === 'object') { - if (utils$1.endsWith(key, '{}')) { - // eslint-disable-next-line no-param-reassign - key = metaTokens ? key : key.slice(0, -2); - // eslint-disable-next-line no-param-reassign - value = JSON.stringify(value); - } else if ( - (utils$1.isArray(value) && isFlatArray(value)) || - ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) - )) { - // eslint-disable-next-line no-param-reassign - key = removeBrackets(key); - - arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), - convertValue(el) - ); - }); - return false; + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } } - } - if (isVisitable(value)) { - return true; - } + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } - formData.append(renderKey(path, key, dots), convertValue(value)); + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } - return false; - } + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - const stack = []; + let onData, + onEnd - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } - function build(value, path) { - if (utils$1.isUndefined(value)) return; + ++nfiles - if (stack.indexOf(value) !== -1) { - throw Error('Circular reference detected in ' + path.join('.')); - } + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } - stack.push(value); + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) - utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( - formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers - ); + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } - if (result === true) { - build(el, path ? path.concat(key) : [key]); - } - }); + file.bytesRead = nsize + } - stack.pop(); - } + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } - if (!utils$1.isObject(obj)) { - throw new TypeError('data must be an object'); - } + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false - build(obj); + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} - return formData; +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } } -/** - * It encodes a string by replacing all characters that are not in the unreserved set with - * their percent-encoded equivalents - * - * @param {string} str - The string to encode. - * - * @returns {string} The encoded string. - */ -function encode$1(str) { - const charMap = { - '!': '%21', - "'": '%27', - '(': '%28', - ')': '%29', - '~': '%7E', - '%20': '+', - '%00': '\x00' - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } } -/** - * It takes a params object and converts it to a FormData object - * - * @param {Object} params - The parameters to be converted to a FormData object. - * @param {Object} options - The options object passed to the Axios constructor. - * - * @returns {void} - */ -function AxiosURLSearchParams(params, options) { - this._pairs = []; - - params && toFormData(params, this, options); +function skipPart (part) { + part.resume() } -const prototype = AxiosURLSearchParams.prototype; +function FileStream (opts) { + Readable.call(this, opts) -prototype.append = function append(name, value) { - this._pairs.push([name, value]); -}; + this.bytesRead = 0 -prototype.toString = function toString(encoder) { - const _encode = encoder ? function(value) { - return encoder.call(this, value, encode$1); - } : encode$1; + this.truncated = false +} - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + '=' + _encode(pair[1]); - }, '').join('&'); -}; +inherits(FileStream, Readable) -/** - * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their - * URI encoded counterparts - * - * @param {string} val The value to be encoded. - * - * @returns {string} The encoded value. - */ -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'); -} +FileStream.prototype._read = function (n) {} -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @param {?(object|Function)} options - * - * @returns {string} The formatted url - */ -function buildURL(url, params, options) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - const _encode = options && options.encode || encode; +module.exports = Multipart - if (utils$1.isFunction(options)) { - options = { - serialize: options - }; - } - const serializeFn = options && options.serialize; +/***/ }), - let serializedParams; +/***/ 8306: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils$1.isURLSearchParams(params) ? - params.toString() : - new AxiosURLSearchParams(params, options).toString(_encode); - } +"use strict"; - if (serializedParams) { - const hashmarkIndex = url.indexOf("#"); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } +const Decoder = __nccwpck_require__(7100) +const decodeText = __nccwpck_require__(4619) +const getLimit = __nccwpck_require__(1467) - return url; -} +const RE_CHARSET = /^charset$/i -class InterceptorManager { - constructor() { - this.handlers = []; - } +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {void} - */ - eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break } } - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; - } - } + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn) { - utils$1.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - } + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false } -const InterceptorManager$1 = InterceptorManager; - -const transitionalDefaults = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false -}; - -const URLSearchParams = url__default["default"].URLSearchParams; - -const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; - -const DIGIT = '0123456789'; - -const ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT -}; - -const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ''; - const {length} = alphabet; - const randomValues = new Uint32Array(size); - crypto__default["default"].randomFillSync(randomValues); - for (let i = 0; i < size; i++) { - str += alphabet[randomValues[i] % length]; +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() } - return str; -}; + let idxeq; let idxamp; let i; let p = 0; const len = data.length + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } -const platform$1 = { - isNode: true, - classes: { - URLSearchParams, - FormData: FormData__default["default"], - Blob: typeof Blob !== 'undefined' && Blob || null - }, - ALPHABET, - generateString, - protocols: [ 'http', 'https', 'file', 'data' ] -}; + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' -const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() -const _navigator = typeof navigator === 'object' && navigator || undefined; + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - * - * @returns {boolean} - */ -const hasStandardBrowserEnv = hasBrowserEnv && - (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() -/** - * Determine if we're running in a standard browser webWorker environment - * - * Although the `isStandardBrowserEnv` method indicates that - * `allows axios to run in a web worker`, the WebWorker will still be - * filtered out due to its judgment standard - * `typeof window !== 'undefined' && typeof document !== 'undefined'`. - * This leads to a problem when axios post `FormData` in webWorker - */ -const hasStandardBrowserWebWorkerEnv = (() => { - return ( - typeof WorkerGlobalScope !== 'undefined' && - // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && - typeof self.importScripts === 'function' - ); -})(); + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } -const origin = hasBrowserEnv && window.location.href || 'http://localhost'; + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } -const utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv, - navigator: _navigator, - origin: origin -}); + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' -const platform = { - ...utils, - ...platform$1 -}; + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() -function toURLEncodedForm(data, options) { - return toFormData(data, new platform.classes.URLSearchParams(), { - visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { - this.append(key, value.toString('base64')); - return false; + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len } - - return helpers.defaultVisitor.apply(this, arguments); - }, - ...options - }); + } + } + cb() } -/** - * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] - * - * @param {string} name - The name of the property to get. - * - * @returns An array of strings. - */ -function parsePropPath(name) { - // foo[x][y][z] - // foo.x.y.z - // foo-x-y-z - // foo x y z - return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { - return match[0] === '[]' ? '' : match[1] || match[0]; - }); -} +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } -/** - * Convert an array to an object. - * - * @param {Array} arr - The array to convert to an object. - * - * @returns An object with the same keys and values as the array. - */ -function arrayToObject(arr) { - const obj = {}; - const keys = Object.keys(arr); - let i; - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - obj[key] = arr[key]; + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) } - return obj; + this.boy._done = true + this.boy.emit('finish') } -/** - * It takes a FormData object and returns a JavaScript object - * - * @param {string} formData The FormData object to convert to JSON. - * - * @returns {Object | null} The converted object. - */ -function formDataToJSON(formData) { - function buildPath(path, value, target, index) { - let name = path[index++]; +module.exports = UrlEncoded - if (name === '__proto__') return true; - const isNumericKey = Number.isFinite(+name); - const isLast = index >= path.length; - name = !name && utils$1.isArray(target) ? target.length : name; +/***/ }), - if (isLast) { - if (utils$1.hasOwnProp(target, name)) { - target[name] = [target[name], value]; - } else { - target[name] = value; - } +/***/ 7100: +/***/ ((module) => { - return !isNumericKey; - } +"use strict"; - if (!target[name] || !utils$1.isObject(target[name])) { - target[name] = []; - } - const result = buildPath(path, value, target[name], index); +const RE_PLUS = /\+/g - if (result && utils$1.isArray(target[name])) { - target[name] = arrayToObject(target[name]); - } +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] - return !isNumericKey; +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined +} - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { - const obj = {}; +module.exports = Decoder - utils$1.forEachEntry(formData, (name, value) => { - buildPath(parsePropPath(name), value, obj, 0); - }); - return obj; - } +/***/ }), - return null; -} +/***/ 8647: +/***/ ((module) => { -/** - * It takes a string, tries to parse it, and if it fails, it returns the stringified version - * of the input - * - * @param {any} rawValue - The value to be stringified. - * @param {Function} parser - A function that parses a string into a JavaScript object. - * @param {Function} encoder - A function that takes a value and returns a string. - * - * @returns {string} A stringified version of the rawValue. - */ -function stringifySafely(rawValue, parser, encoder) { - if (utils$1.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } +"use strict"; + + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) } } - - return (encoder || JSON.stringify)(rawValue); + return (path === '..' || path === '.' ? '' : path) } -const defaults = { - transitional: transitionalDefaults, +/***/ }), - adapter: ['xhr', 'http', 'fetch'], +/***/ 4619: +/***/ (function(module) { - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ''; - const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils$1.isObject(data); +"use strict"; - if (isObjectPayload && utils$1.isHTMLForm(data)) { - data = new FormData(data); - } - const isFormData = utils$1.isFormData(data); +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) - if (isFormData) { - return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) } + } +} - if (utils$1.isArrayBuffer(data) || - utils$1.isBuffer(data) || - utils$1.isStream(data) || - utils$1.isFile(data) || - utils$1.isBlob(data) || - utils$1.isReadableStream(data) - ) { - return data; - } - if (utils$1.isArrayBufferView(data)) { - return data.buffer; +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - if (utils$1.isURLSearchParams(data)) { - headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); - return data.toString(); + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } + return data.utf8Slice(0, data.length) + }, - let isFileList; - - if (isObjectPayload) { - if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } - - if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { - const _FormData = this.env && this.env.FormData; - - return toFormData( - isFileList ? {'files[]': data} : data, - _FormData && new _FormData(), - this.formSerializer - ); - } + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - - if (isObjectPayload || hasJSONContentType ) { - headers.setContentType('application/json', false); - return stringifySafely(data); + if (typeof data === 'string') { + return data } + return data.latin1Slice(0, data.length) + }, - return data; - }], - - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === 'json'; - - if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { - return data; + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - - if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - - try { - return JSON.parse(data, this.parseReviver); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; - } - } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } - - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - - maxContentLength: -1, - maxBodyLength: -1, - - env: { - FormData: platform.classes.FormData, - Blob: platform.classes.Blob + return data.ucs2Slice(0, data.length) }, - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) }, - headers: { - common: { - 'Accept': 'application/json, text/plain, */*', - 'Content-Type': undefined + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - } -}; - -utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { - defaults.headers[method] = {}; -}); - -const defaults$1 = defaults; - -// RawAxiosHeaders whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -const ignoreDuplicateOf = utils$1.toObjectSet([ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]); - -/** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} rawHeaders Headers needing to be parsed - * - * @returns {Object} Headers parsed into an object - */ -const parseHeaders = rawHeaders => { - const parsed = {}; - let key; - let val; - let i; - - rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { - i = line.indexOf(':'); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); - - if (!key || (parsed[key] && ignoreDuplicateOf[key])) { - return; + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } - if (key === 'set-cookie') { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} } - }); - - return parsed; -}; - -const $internals = Symbol('internals'); - -function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); -} - -function normalizeValue(value) { - if (value === false || value == null) { - return value; - } - - return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); -} - -function parseTokens(str) { - const tokens = Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - - while ((match = tokensRE.exec(str))) { - tokens[match[1]] = match[2]; - } - - return tokens; -} - -const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); - -function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils$1.isFunction(filter)) { - return filter.call(this, value, header); - } - - if (isHeaderNameFilter) { - value = header; - } - - if (!utils$1.isString(value)) return; - - if (utils$1.isString(filter)) { - return value.indexOf(filter) !== -1; - } - - if (utils$1.isRegExp(filter)) { - return filter.test(value); + return typeof data === 'string' + ? data + : data.toString() } } -function formatHeader(header) { - return header.trim() - .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { - return char.toUpperCase() + str; - }); +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text } -function buildAccessors(obj, header) { - const accessorName = utils$1.toCamelCase(' ' + header); +module.exports = decodeText - ['get', 'set', 'has'].forEach(methodName => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); -} -class AxiosHeaders { - constructor(headers) { - headers && this.set(headers); - } +/***/ }), - set(header, valueOrRewrite, rewrite) { - const self = this; +/***/ 1467: +/***/ ((module) => { - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); +"use strict"; - if (!lHeader) { - throw new Error('header name must be a non-empty string'); - } - const key = utils$1.findKey(self, lHeader); +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } - if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { - self[key || _header] = normalizeValue(_value); - } - } + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - const setHeaders = (headers, _rewrite) => - utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); + return limits[name] +} - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); - } else if (utils$1.isObject(header) && utils$1.isIterable(header)) { - let obj = {}, dest, key; - for (const entry of header) { - if (!utils$1.isArray(entry)) { - throw TypeError('Object iterator must return a key-value pair'); - } - obj[key = entry[0]] = (dest = obj[key]) ? - (utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1]; - } +/***/ }), - setHeaders(obj, valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); - } +/***/ 1854: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this; - } +"use strict"; +/* eslint-disable object-property-newline */ - get(header, parser) { - header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); +const decodeText = __nccwpck_require__(4619) - if (key) { - const value = this[key]; +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - if (!parser) { - return value; - } +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} - if (parser === true) { - return parseTokens(value); - } +function encodedReplacer (match) { + return EncodedLookup[match] +} - if (utils$1.isFunction(parser)) { - return parser.call(this, value, key); - } +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 - if (utils$1.isRegExp(parser)) { - return parser.exec(value); - } +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length - throw new TypeError('parser must be boolean|regexp|function'); + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } } + tmp += char } - - has(header, matcher) { - header = normalizeHeader(header); - - if (header) { - const key = utils$1.findKey(this, header); - - return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); - } - - return false; + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') } - delete(header, matcher) { - const self = this; - let deleted = false; - - function deleteHeader(_header) { - _header = normalizeHeader(_header); - - if (_header) { - const key = utils$1.findKey(self, _header); + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } - if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { - delete self[key]; + return res +} - deleted = true; - } - } - } +module.exports = parseParams - if (utils$1.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); - } - return deleted; - } +/***/ }), - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; +/***/ 4379: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - while (i--) { - const key = keys[i]; - if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } - } +const { Argument } = __nccwpck_require__(9414); +const { Command } = __nccwpck_require__(552); +const { CommanderError, InvalidArgumentError } = __nccwpck_require__(2625); +const { Help } = __nccwpck_require__(5153); +const { Option } = __nccwpck_require__(6558); - return deleted; - } +exports.program = new Command(); - normalize(format) { - const self = this; - const headers = {}; +exports.createCommand = (name) => new Command(name); +exports.createOption = (flags, description) => new Option(flags, description); +exports.createArgument = (name, description) => new Argument(name, description); - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); +/** + * Expose classes + */ - if (key) { - self[key] = normalizeValue(value); - delete self[header]; - return; - } +exports.Command = Command; +exports.Option = Option; +exports.Argument = Argument; +exports.Help = Help; - const normalized = format ? formatHeader(header) : String(header).trim(); +exports.CommanderError = CommanderError; +exports.InvalidArgumentError = InvalidArgumentError; +exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated - if (normalized !== header) { - delete self[header]; - } - self[normalized] = normalizeValue(value); +/***/ }), - headers[normalized] = true; - }); +/***/ 9414: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this; - } +const { InvalidArgumentError } = __nccwpck_require__(2625); - concat(...targets) { - return this.constructor.concat(this, ...targets); - } +class Argument { + /** + * Initialize a new command argument with the given name and description. + * The default is that the argument is required, and you can explicitly + * indicate this with <> around the name. Put [] around the name for an optional argument. + * + * @param {string} name + * @param {string} [description] + */ - toJSON(asStrings) { - const obj = Object.create(null); + constructor(name, description) { + this.description = description || ''; + this.variadic = false; + this.parseArg = undefined; + this.defaultValue = undefined; + this.defaultValueDescription = undefined; + this.argChoices = undefined; - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); - }); + switch (name[0]) { + case '<': // e.g. + this.required = true; + this._name = name.slice(1, -1); + break; + case '[': // e.g. [optional] + this.required = false; + this._name = name.slice(1, -1); + break; + default: + this.required = true; + this._name = name; + break; + } - return obj; + if (this._name.length > 3 && this._name.slice(-3) === '...') { + this.variadic = true; + this._name = this._name.slice(0, -3); + } } - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } + /** + * Return argument name. + * + * @return {string} + */ - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); + name() { + return this._name; } - getSetCookie() { - return this.get("set-cookie") || []; - } + /** + * @package + */ - get [Symbol.toStringTag]() { - return 'AxiosHeaders'; - } + _concatValue(value, previous) { + if (previous === this.defaultValue || !Array.isArray(previous)) { + return [value]; + } - static from(thing) { - return thing instanceof this ? thing : new this(thing); + return previous.concat(value); } - static concat(first, ...targets) { - const computed = new this(first); - - targets.forEach((target) => computed.set(target)); + /** + * Set the default value, and optionally supply the description to be displayed in the help. + * + * @param {*} value + * @param {string} [description] + * @return {Argument} + */ - return computed; + default(value, description) { + this.defaultValue = value; + this.defaultValueDescription = description; + return this; } - static accessor(header) { - const internals = this[$internals] = (this[$internals] = { - accessors: {} - }); + /** + * Set the custom handler for processing CLI command arguments into argument values. + * + * @param {Function} [fn] + * @return {Argument} + */ - const accessors = internals.accessors; - const prototype = this.prototype; + argParser(fn) { + this.parseArg = fn; + return this; + } - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); + /** + * Only allow argument value to be one of choices. + * + * @param {string[]} values + * @return {Argument} + */ - if (!accessors[lHeader]) { - buildAccessors(prototype, _header); - accessors[lHeader] = true; + choices(values) { + this.argChoices = values.slice(); + this.parseArg = (arg, previous) => { + if (!this.argChoices.includes(arg)) { + throw new InvalidArgumentError( + `Allowed choices are ${this.argChoices.join(', ')}.`, + ); } - } - - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); - + if (this.variadic) { + return this._concatValue(arg, previous); + } + return arg; + }; return this; } -} -AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); - -// reserved names hotfix -utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; - } + /** + * Make argument required. + * + * @returns {Argument} + */ + argRequired() { + this.required = true; + return this; } -}); -utils$1.freezeMethods(AxiosHeaders); - -const AxiosHeaders$1 = AxiosHeaders; + /** + * Make argument optional. + * + * @returns {Argument} + */ + argOptional() { + this.required = false; + return this; + } +} /** - * Transform the data for a request or a response - * - * @param {Array|Function} fns A single function or Array of functions - * @param {?Object} response The response object + * Takes an argument and returns its human readable equivalent for help usage. * - * @returns {*} The resulting transformed data + * @param {Argument} arg + * @return {string} + * @private */ -function transformData(fns, response) { - const config = this || defaults$1; - const context = response || config; - const headers = AxiosHeaders$1.from(context.headers); - let data = context.data; - - utils$1.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); - }); - headers.normalize(); +function humanReadableArgName(arg) { + const nameOutput = arg.name() + (arg.variadic === true ? '...' : ''); - return data; + return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; } -function isCancel(value) { - return !!(value && value.__CANCEL__); -} +exports.Argument = Argument; +exports.humanReadableArgName = humanReadableArgName; -/** - * A `CanceledError` is an object that is thrown when an operation is canceled. - * - * @param {string=} message The message. - * @param {Object=} config The config. - * @param {Object=} request The request. - * - * @returns {CanceledError} The created error. - */ -function CanceledError(message, config, request) { - // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); - this.name = 'CanceledError'; -} -utils$1.inherits(CanceledError, AxiosError, { - __CANCEL__: true -}); +/***/ }), -/** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - * - * @returns {object} The response. - */ -function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } -} +/***/ 552: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); -} +const EventEmitter = (__nccwpck_require__(5673).EventEmitter); +const childProcess = __nccwpck_require__(7718); +const path = __nccwpck_require__(9411); +const fs = __nccwpck_require__(7561); +const process = __nccwpck_require__(7742); -/** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * - * @returns {string} The combined URL - */ -function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; -} +const { Argument, humanReadableArgName } = __nccwpck_require__(9414); +const { CommanderError } = __nccwpck_require__(2625); +const { Help } = __nccwpck_require__(5153); +const { Option, DualOptions } = __nccwpck_require__(6558); +const { suggestSimilar } = __nccwpck_require__(7592); -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * - * @returns {string} The combined full path - */ -function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { - let isRelativeUrl = !isAbsoluteURL(requestedURL); - if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; -} +class Command extends EventEmitter { + /** + * Initialize a new `Command`. + * + * @param {string} [name] + */ -const VERSION = "1.13.1"; + constructor(name) { + super(); + /** @type {Command[]} */ + this.commands = []; + /** @type {Option[]} */ + this.options = []; + this.parent = null; + this._allowUnknownOption = false; + this._allowExcessArguments = true; + /** @type {Argument[]} */ + this.registeredArguments = []; + this._args = this.registeredArguments; // deprecated old name + /** @type {string[]} */ + this.args = []; // cli args with options removed + this.rawArgs = []; + this.processedArgs = []; // like .args but after custom processing and collecting variadic + this._scriptPath = null; + this._name = name || ''; + this._optionValues = {}; + this._optionValueSources = {}; // default, env, cli etc + this._storeOptionsAsProperties = false; + this._actionHandler = null; + this._executableHandler = false; + this._executableFile = null; // custom name for executable + this._executableDir = null; // custom search directory for subcommands + this._defaultCommandName = null; + this._exitCallback = null; + this._aliases = []; + this._combineFlagAndOptionalValue = true; + this._description = ''; + this._summary = ''; + this._argsDescription = undefined; // legacy + this._enablePositionalOptions = false; + this._passThroughOptions = false; + this._lifeCycleHooks = {}; // a hash of arrays + /** @type {(boolean | string)} */ + this._showHelpAfterError = false; + this._showSuggestionAfterError = true; -function parseProtocol(url) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; -} + // see .configureOutput() for docs + this._outputConfiguration = { + writeOut: (str) => process.stdout.write(str), + writeErr: (str) => process.stderr.write(str), + getOutHelpWidth: () => + process.stdout.isTTY ? process.stdout.columns : undefined, + getErrHelpWidth: () => + process.stderr.isTTY ? process.stderr.columns : undefined, + outputError: (str, write) => write(str), + }; -const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; + this._hidden = false; + /** @type {(Option | null | undefined)} */ + this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled. + this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited + /** @type {Command} */ + this._helpCommand = undefined; // lazy initialised, inherited + this._helpConfiguration = {}; + } -/** - * Parse data uri to a Buffer or Blob - * - * @param {String} uri - * @param {?Boolean} asBlob - * @param {?Object} options - * @param {?Function} options.Blob - * - * @returns {Buffer|Blob} - */ -function fromDataURI(uri, asBlob, options) { - const _Blob = options && options.Blob || platform.classes.Blob; - const protocol = parseProtocol(uri); + /** + * Copy settings that are useful to have in common across root command and subcommands. + * + * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) + * + * @param {Command} sourceCommand + * @return {Command} `this` command for chaining + */ + copyInheritedSettings(sourceCommand) { + this._outputConfiguration = sourceCommand._outputConfiguration; + this._helpOption = sourceCommand._helpOption; + this._helpCommand = sourceCommand._helpCommand; + this._helpConfiguration = sourceCommand._helpConfiguration; + this._exitCallback = sourceCommand._exitCallback; + this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties; + this._combineFlagAndOptionalValue = + sourceCommand._combineFlagAndOptionalValue; + this._allowExcessArguments = sourceCommand._allowExcessArguments; + this._enablePositionalOptions = sourceCommand._enablePositionalOptions; + this._showHelpAfterError = sourceCommand._showHelpAfterError; + this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError; - if (asBlob === undefined && _Blob) { - asBlob = true; + return this; } - if (protocol === 'data') { - uri = protocol.length ? uri.slice(protocol.length + 1) : uri; - - const match = DATA_URL_PATTERN.exec(uri); + /** + * @returns {Command[]} + * @private + */ - if (!match) { - throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); + _getCommandAndAncestors() { + const result = []; + // eslint-disable-next-line @typescript-eslint/no-this-alias + for (let command = this; command; command = command.parent) { + result.push(command); } + return result; + } - const mime = match[1]; - const isBase64 = match[2]; - const body = match[3]; - const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); + /** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * @example + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or `this` for executable command + */ - if (asBlob) { - if (!_Blob) { - throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); - } + command(nameAndArgs, actionOptsOrExecDesc, execOpts) { + let desc = actionOptsOrExecDesc; + let opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); - return new _Blob([buffer], {type: mime}); + const cmd = this.createCommand(name); + if (desc) { + cmd.description(desc); + cmd._executableHandler = true; } + if (opts.isDefault) this._defaultCommandName = cmd._name; + cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden + cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor + if (args) cmd.arguments(args); + this._registerCommand(cmd); + cmd.parent = this; + cmd.copyInheritedSettings(this); - return buffer; + if (desc) return this; + return cmd; } - throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); -} - -const kInternals = Symbol('internals'); - -class AxiosTransformStream extends stream__default["default"].Transform{ - constructor(options) { - options = utils$1.toFlatObject(options, { - maxRate: 0, - chunkSize: 64 * 1024, - minChunkSize: 100, - timeWindow: 500, - ticksRate: 2, - samplesCount: 15 - }, null, (prop, source) => { - return !utils$1.isUndefined(source[prop]); - }); - - super({ - readableHighWaterMark: options.chunkSize - }); - - const internals = this[kInternals] = { - timeWindow: options.timeWindow, - chunkSize: options.chunkSize, - maxRate: options.maxRate, - minChunkSize: options.minChunkSize, - bytesSeen: 0, - isCaptured: false, - notifiedBytesLoaded: 0, - ts: Date.now(), - bytes: 0, - onReadCallback: null - }; + /** + * Factory routine to create a new unattached command. + * + * See .command() for creating an attached subcommand, which uses this routine to + * create the command. You can override createCommand to customise subcommands. + * + * @param {string} [name] + * @return {Command} new command + */ - this.on('newListener', event => { - if (event === 'progress') { - if (!internals.isCaptured) { - internals.isCaptured = true; - } - } - }); + createCommand(name) { + return new Command(name); } - _read(size) { - const internals = this[kInternals]; - - if (internals.onReadCallback) { - internals.onReadCallback(); - } + /** + * You can customise the help with a subclass of Help by overriding createHelp, + * or by overriding Help properties using configureHelp(). + * + * @return {Help} + */ - return super._read(size); + createHelp() { + return Object.assign(new Help(), this.configureHelp()); } - _transform(chunk, encoding, callback) { - const internals = this[kInternals]; - const maxRate = internals.maxRate; - - const readableHighWaterMark = this.readableHighWaterMark; - - const timeWindow = internals.timeWindow; - - const divider = 1000 / timeWindow; - const bytesThreshold = (maxRate / divider); - const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - - const pushChunk = (_chunk, _callback) => { - const bytes = Buffer.byteLength(_chunk); - internals.bytesSeen += bytes; - internals.bytes += bytes; - - internals.isCaptured && this.emit('progress', internals.bytesSeen); - - if (this.push(_chunk)) { - process.nextTick(_callback); - } else { - internals.onReadCallback = () => { - internals.onReadCallback = null; - process.nextTick(_callback); - }; - } - }; - - const transformChunk = (_chunk, _callback) => { - const chunkSize = Buffer.byteLength(_chunk); - let chunkRemainder = null; - let maxChunkSize = readableHighWaterMark; - let bytesLeft; - let passed = 0; - - if (maxRate) { - const now = Date.now(); - - if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) { - internals.ts = now; - bytesLeft = bytesThreshold - internals.bytes; - internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; - passed = 0; - } - - bytesLeft = bytesThreshold - internals.bytes; - } - - if (maxRate) { - if (bytesLeft <= 0) { - // next time window - return setTimeout(() => { - _callback(null, _chunk); - }, timeWindow - passed); - } - - if (bytesLeft < maxChunkSize) { - maxChunkSize = bytesLeft; - } - } - - if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) { - chunkRemainder = _chunk.subarray(maxChunkSize); - _chunk = _chunk.subarray(0, maxChunkSize); - } - - pushChunk(_chunk, chunkRemainder ? () => { - process.nextTick(_callback, null, chunkRemainder); - } : _callback); - }; + /** + * You can customise the help by overriding Help properties using configureHelp(), + * or with a subclass of Help by overriding createHelp(). + * + * @param {object} [configuration] - configuration options + * @return {(Command | object)} `this` command for chaining, or stored configuration + */ - transformChunk(chunk, function transformNextChunk(err, _chunk) { - if (err) { - return callback(err); - } + configureHelp(configuration) { + if (configuration === undefined) return this._helpConfiguration; - if (_chunk) { - transformChunk(_chunk, transformNextChunk); - } else { - callback(null); - } - }); + this._helpConfiguration = configuration; + return this; } -} -const AxiosTransformStream$1 = AxiosTransformStream; + /** + * The default output goes to stdout and stderr. You can customise this for special + * applications. You can also customise the display of errors by overriding outputError. + * + * The configuration properties are all functions: + * + * // functions to change where being written, stdout and stderr + * writeOut(str) + * writeErr(str) + * // matching functions to specify width for wrapping help + * getOutHelpWidth() + * getErrHelpWidth() + * // functions based on what is being written out + * outputError(str, write) // used for displaying errors, and not used for displaying help + * + * @param {object} [configuration] - configuration options + * @return {(Command | object)} `this` command for chaining, or stored configuration + */ -const {asyncIterator} = Symbol; + configureOutput(configuration) { + if (configuration === undefined) return this._outputConfiguration; -const readBlob = async function* (blob) { - if (blob.stream) { - yield* blob.stream(); - } else if (blob.arrayBuffer) { - yield await blob.arrayBuffer(); - } else if (blob[asyncIterator]) { - yield* blob[asyncIterator](); - } else { - yield blob; + Object.assign(this._outputConfiguration, configuration); + return this; } -}; - -const readBlob$1 = readBlob; -const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_'; - -const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util__default["default"].TextEncoder(); - -const CRLF = '\r\n'; -const CRLF_BYTES = textEncoder.encode(CRLF); -const CRLF_BYTES_COUNT = 2; + /** + * Display the help or a custom message after an error occurs. + * + * @param {(boolean|string)} [displayHelp] + * @return {Command} `this` command for chaining + */ + showHelpAfterError(displayHelp = true) { + if (typeof displayHelp !== 'string') displayHelp = !!displayHelp; + this._showHelpAfterError = displayHelp; + return this; + } -class FormDataPart { - constructor(name, value) { - const {escapeName} = this.constructor; - const isStringValue = utils$1.isString(value); + /** + * Display suggestion of similar commands for unknown commands, or options for unknown options. + * + * @param {boolean} [displaySuggestion] + * @return {Command} `this` command for chaining + */ + showSuggestionAfterError(displaySuggestion = true) { + this._showSuggestionAfterError = !!displaySuggestion; + return this; + } - let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ - !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' - }${CRLF}`; + /** + * Add a prepared subcommand. + * + * See .command() for creating an attached subcommand which inherits settings from its parent. + * + * @param {Command} cmd - new subcommand + * @param {object} [opts] - configuration options + * @return {Command} `this` command for chaining + */ - if (isStringValue) { - value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); - } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; + addCommand(cmd, opts) { + if (!cmd._name) { + throw new Error(`Command passed to .addCommand() must have a name +- specify the name in Command constructor or using .name()`); } - this.headers = textEncoder.encode(headers + CRLF); - - this.contentLength = isStringValue ? value.byteLength : value.size; + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation - this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; + this._registerCommand(cmd); + cmd.parent = this; + cmd._checkForBrokenPassThrough(); - this.name = name; - this.value = value; + return this; } - async *encode(){ - yield this.headers; + /** + * Factory routine to create a new unattached argument. + * + * See .argument() for creating an attached argument, which uses this routine to + * create the argument. You can override createArgument to return a custom argument. + * + * @param {string} name + * @param {string} [description] + * @return {Argument} new argument + */ - const {value} = this; + createArgument(name, description) { + return new Argument(name, description); + } - if(utils$1.isTypedArray(value)) { - yield value; + /** + * Define argument syntax for command. + * + * The default is that the argument is required, and you can explicitly + * indicate this with <> around the name. Put [] around the name for an optional argument. + * + * @example + * program.argument(''); + * program.argument('[output-file]'); + * + * @param {string} name + * @param {string} [description] + * @param {(Function|*)} [fn] - custom argument processing function + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + */ + argument(name, description, fn, defaultValue) { + const argument = this.createArgument(name, description); + if (typeof fn === 'function') { + argument.default(defaultValue).argParser(fn); } else { - yield* readBlob$1(value); + argument.default(fn); } - - yield CRLF_BYTES; - } - - static escapeName(name) { - return String(name).replace(/[\r\n"]/g, (match) => ({ - '\r' : '%0D', - '\n' : '%0A', - '"' : '%22', - }[match])); + this.addArgument(argument); + return this; } -} -const formDataToStream = (form, headersHandler, options) => { - const { - tag = 'form-data-boundary', - size = 25, - boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET) - } = options || {}; + /** + * Define argument syntax for command, adding multiple at once (without descriptions). + * + * See also .argument(). + * + * @example + * program.arguments(' [env]'); + * + * @param {string} names + * @return {Command} `this` command for chaining + */ - if(!utils$1.isFormData(form)) { - throw TypeError('FormData instance required'); + arguments(names) { + names + .trim() + .split(/ +/) + .forEach((detail) => { + this.argument(detail); + }); + return this; } - if (boundary.length < 1 || boundary.length > 70) { - throw Error('boundary must be 10-70 characters long') + /** + * Define argument syntax for command, adding a prepared argument. + * + * @param {Argument} argument + * @return {Command} `this` command for chaining + */ + addArgument(argument) { + const previousArgument = this.registeredArguments.slice(-1)[0]; + if (previousArgument && previousArgument.variadic) { + throw new Error( + `only the last argument can be variadic '${previousArgument.name()}'`, + ); + } + if ( + argument.required && + argument.defaultValue !== undefined && + argument.parseArg === undefined + ) { + throw new Error( + `a default value for a required argument is never used: '${argument.name()}'`, + ); + } + this.registeredArguments.push(argument); + return this; } - const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); - const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF); - let contentLength = footerBytes.byteLength; + /** + * Customise or override default help command. By default a help command is automatically added if your command has subcommands. + * + * @example + * program.helpCommand('help [cmd]'); + * program.helpCommand('help [cmd]', 'show help'); + * program.helpCommand(false); // suppress default help command + * program.helpCommand(true); // add help command even if no subcommands + * + * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added + * @param {string} [description] - custom description + * @return {Command} `this` command for chaining + */ - const parts = Array.from(form.entries()).map(([name, value]) => { - const part = new FormDataPart(name, value); - contentLength += part.size; - return part; - }); + helpCommand(enableOrNameAndArgs, description) { + if (typeof enableOrNameAndArgs === 'boolean') { + this._addImplicitHelpCommand = enableOrNameAndArgs; + return this; + } - contentLength += boundaryBytes.byteLength * parts.length; + enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]'; + const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/); + const helpDescription = description ?? 'display help for command'; - contentLength = utils$1.toFiniteNumber(contentLength); + const helpCommand = this.createCommand(helpName); + helpCommand.helpOption(false); + if (helpArgs) helpCommand.arguments(helpArgs); + if (helpDescription) helpCommand.description(helpDescription); - const computedHeaders = { - 'Content-Type': `multipart/form-data; boundary=${boundary}` - }; + this._addImplicitHelpCommand = true; + this._helpCommand = helpCommand; - if (Number.isFinite(contentLength)) { - computedHeaders['Content-Length'] = contentLength; + return this; } - headersHandler && headersHandler(computedHeaders); - - return stream.Readable.from((async function *() { - for(const part of parts) { - yield boundaryBytes; - yield* part.encode(); + /** + * Add prepared custom help command. + * + * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()` + * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only + * @return {Command} `this` command for chaining + */ + addHelpCommand(helpCommand, deprecatedDescription) { + // If not passed an object, call through to helpCommand for backwards compatibility, + // as addHelpCommand was originally used like helpCommand is now. + if (typeof helpCommand !== 'object') { + this.helpCommand(helpCommand, deprecatedDescription); + return this; } - yield footerBytes; - })()); -}; - -const formDataToStream$1 = formDataToStream; - -class ZlibHeaderTransformStream extends stream__default["default"].Transform { - __transform(chunk, encoding, callback) { - this.push(chunk); - callback(); + this._addImplicitHelpCommand = true; + this._helpCommand = helpCommand; + return this; } - _transform(chunk, encoding, callback) { - if (chunk.length !== 0) { - this._transform = this.__transform; + /** + * Lazy create help command. + * + * @return {(Command|null)} + * @package + */ + _getHelpCommand() { + const hasImplicitHelpCommand = + this._addImplicitHelpCommand ?? + (this.commands.length && + !this._actionHandler && + !this._findCommand('help')); - // Add Default Compression headers if no zlib headers are present - if (chunk[0] !== 120) { // Hex: 78 - const header = Buffer.alloc(2); - header[0] = 120; // Hex: 78 - header[1] = 156; // Hex: 9C - this.push(header, encoding); + if (hasImplicitHelpCommand) { + if (this._helpCommand === undefined) { + this.helpCommand(undefined, undefined); // use default name and description } + return this._helpCommand; } - - this.__transform(chunk, encoding, callback); + return null; } -} - -const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream; - -const callbackify = (fn, reducer) => { - return utils$1.isAsyncFn(fn) ? function (...args) { - const cb = args.pop(); - fn.apply(this, args).then((value) => { - try { - reducer ? cb(null, ...reducer(value)) : cb(null, value); - } catch (err) { - cb(err); - } - }, cb); - } : fn; -}; - -const callbackify$1 = callbackify; - -/** - * Calculate data maxRate - * @param {Number} [samplesCount= 10] - * @param {Number} [min= 1000] - * @returns {Function} - */ -function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - - min = min !== undefined ? min : 1000; - - return function push(chunkLength) { - const now = Date.now(); - - const startedAt = timestamps[tail]; - - if (!firstSampleTS) { - firstSampleTS = now; - } - - bytes[head] = chunkLength; - timestamps[head] = now; - - let i = tail; - let bytesCount = 0; - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; - } - - head = (head + 1) % samplesCount; + /** + * Add hook for life cycle event. + * + * @param {string} event + * @param {Function} listener + * @return {Command} `this` command for chaining + */ - if (head === tail) { - tail = (tail + 1) % samplesCount; + hook(event, listener) { + const allowedValues = ['preSubcommand', 'preAction', 'postAction']; + if (!allowedValues.includes(event)) { + throw new Error(`Unexpected value for event passed to hook : '${event}'. +Expecting one of '${allowedValues.join("', '")}'`); } - - if (now - firstSampleTS < min) { - return; + if (this._lifeCycleHooks[event]) { + this._lifeCycleHooks[event].push(listener); + } else { + this._lifeCycleHooks[event] = [listener]; } + return this; + } - const passed = startedAt && now - startedAt; - - return passed ? Math.round(bytesCount * 1000 / passed) : undefined; - }; -} - -/** - * Throttle decorator - * @param {Function} fn - * @param {Number} freq - * @return {Function} - */ -function throttle(fn, freq) { - let timestamp = 0; - let threshold = 1000 / freq; - let lastArgs; - let timer; - - const invoke = (args, now = Date.now()) => { - timestamp = now; - lastArgs = null; - if (timer) { - clearTimeout(timer); - timer = null; - } - fn(...args); - }; + /** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} `this` command for chaining + */ - const throttled = (...args) => { - const now = Date.now(); - const passed = now - timestamp; - if ( passed >= threshold) { - invoke(args, now); + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; } else { - lastArgs = args; - if (!timer) { - timer = setTimeout(() => { - timer = null; - invoke(lastArgs); - }, threshold - passed); - } + this._exitCallback = (err) => { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; } - }; - - const flush = () => lastArgs && invoke(lastArgs); + return this; + } - return [throttled, flush]; -} + /** + * Call process.exit, and _exitCallback if defined. + * + * @param {number} exitCode exit code for using with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @return never + * @private + */ -const progressEventReducer = (listener, isDownloadStream, freq = 3) => { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); + _exit(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. + } + process.exit(exitCode); + } - return throttle(e => { - const loaded = e.loaded; - const total = e.lengthComputable ? e.total : undefined; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange = loaded <= total; + /** + * Register callback `fn` for the command. + * + * @example + * program + * .command('serve') + * .description('start service') + * .action(function() { + * // do work here + * }); + * + * @param {Function} fn + * @return {Command} `this` command for chaining + */ - bytesNotified = loaded; + action(fn) { + const listener = (args) => { + // The .action callback takes an extra parameter which is the command or options. + const expectedArgsCount = this.registeredArguments.length; + const actionArgs = args.slice(0, expectedArgsCount); + if (this._storeOptionsAsProperties) { + actionArgs[expectedArgsCount] = this; // backwards compatible "options" + } else { + actionArgs[expectedArgsCount] = this.opts(); + } + actionArgs.push(this); - const data = { - loaded, - total, - progress: total ? (loaded / total) : undefined, - bytes: progressBytes, - rate: rate ? rate : undefined, - estimated: rate && total && inRange ? (total - loaded) / rate : undefined, - event: e, - lengthComputable: total != null, - [isDownloadStream ? 'download' : 'upload']: true + return fn.apply(this, actionArgs); }; + this._actionHandler = listener; + return this; + } - listener(data); - }, freq); -}; - -const progressEventDecorator = (total, throttled) => { - const lengthComputable = total != null; - - return [(loaded) => throttled[0]({ - lengthComputable, - total, - loaded - }), throttled[1]]; -}; - -const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); - -/** - * Estimate decoded byte length of a data:// URL *without* allocating large buffers. - * - For base64: compute exact decoded size using length and padding; - * handle %XX at the character-count level (no string allocation). - * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound. - * - * @param {string} url - * @returns {number} - */ -function estimateDataURLDecodedBytes(url) { - if (!url || typeof url !== 'string') return 0; - if (!url.startsWith('data:')) return 0; - - const comma = url.indexOf(','); - if (comma < 0) return 0; - - const meta = url.slice(5, comma); - const body = url.slice(comma + 1); - const isBase64 = /;base64/i.test(meta); + /** + * Factory routine to create a new unattached option. + * + * See .option() for creating an attached option, which uses this routine to + * create the option. You can override createOption to return a custom option. + * + * @param {string} flags + * @param {string} [description] + * @return {Option} new option + */ - if (isBase64) { - let effectiveLen = body.length; - const len = body.length; // cache length + createOption(flags, description) { + return new Option(flags, description); + } - for (let i = 0; i < len; i++) { - if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) { - const a = body.charCodeAt(i + 1); - const b = body.charCodeAt(i + 2); - const isHex = - ((a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)) && - ((b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102)); + /** + * Wrap parseArgs to catch 'commander.invalidArgument'. + * + * @param {(Option | Argument)} target + * @param {string} value + * @param {*} previous + * @param {string} invalidArgumentMessage + * @private + */ - if (isHex) { - effectiveLen -= 2; - i += 2; - } + _callParseArg(target, value, previous, invalidArgumentMessage) { + try { + return target.parseArg(value, previous); + } catch (err) { + if (err.code === 'commander.invalidArgument') { + const message = `${invalidArgumentMessage} ${err.message}`; + this.error(message, { exitCode: err.exitCode, code: err.code }); } + throw err; } + } - let pad = 0; - let idx = len - 1; - - const tailIsPct3D = (j) => - j >= 2 && - body.charCodeAt(j - 2) === 37 && // '%' - body.charCodeAt(j - 1) === 51 && // '3' - (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd' - - if (idx >= 0) { - if (body.charCodeAt(idx) === 61 /* '=' */) { - pad++; - idx--; - } else if (tailIsPct3D(idx)) { - pad++; - idx -= 3; - } - } + /** + * Check for option flag conflicts. + * Register option if no conflicts found, or throw on conflict. + * + * @param {Option} option + * @private + */ - if (pad === 1 && idx >= 0) { - if (body.charCodeAt(idx) === 61 /* '=' */) { - pad++; - } else if (tailIsPct3D(idx)) { - pad++; - } + _registerOption(option) { + const matchingOption = + (option.short && this._findOption(option.short)) || + (option.long && this._findOption(option.long)); + if (matchingOption) { + const matchingFlag = + option.long && this._findOption(option.long) + ? option.long + : option.short; + throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}' +- already used by option '${matchingOption.flags}'`); } - const groups = Math.floor(effectiveLen / 4); - const bytes = groups * 3 - (pad || 0); - return bytes > 0 ? bytes : 0; + this.options.push(option); } - return Buffer.byteLength(body, 'utf8'); -} - -const zlibOptions = { - flush: zlib__default["default"].constants.Z_SYNC_FLUSH, - finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH -}; - -const brotliOptions = { - flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, - finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH -}; - -const { - HTTP2_HEADER_SCHEME, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_HEADER_STATUS -} = http2.constants; - -const isBrotliSupported = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); - -const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"]; - -const isHttps = /https:?/; - -const supportedProtocols = platform.protocols.map(protocol => { - return protocol + ':'; -}); - + /** + * Check for command name and alias conflicts with existing commands. + * Register command if no conflicts found, or throw on conflict. + * + * @param {Command} command + * @private + */ -const flushOnFinish = (stream, [throttled, flush]) => { - stream - .on('end', flush) - .on('error', flush); + _registerCommand(command) { + const knownBy = (cmd) => { + return [cmd.name()].concat(cmd.aliases()); + }; - return throttled; -}; + const alreadyUsed = knownBy(command).find((name) => + this._findCommand(name), + ); + if (alreadyUsed) { + const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|'); + const newCmd = knownBy(command).join('|'); + throw new Error( + `cannot add command '${newCmd}' as already have command '${existingCmd}'`, + ); + } -class Http2Sessions { - constructor() { - this.sessions = Object.create(null); + this.commands.push(command); } - getSession(authority, options) { - options = Object.assign({ - sessionTimeout: 1000 - }, options); - - let authoritySessions; + /** + * Add an option. + * + * @param {Option} option + * @return {Command} `this` command for chaining + */ + addOption(option) { + this._registerOption(option); - if ((authoritySessions = this.sessions[authority])) { - let len = authoritySessions.length; + const oname = option.name(); + const name = option.attributeName(); - for (let i = 0; i < len; i++) { - const [sessionHandle, sessionOptions] = authoritySessions[i]; - if (!sessionHandle.destroyed && !sessionHandle.closed && util__default["default"].isDeepStrictEqual(sessionOptions, options)) { - return sessionHandle; - } + // store default value + if (option.negate) { + // --no-foo is special and defaults foo to true, unless a --foo option is already defined + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + if (!this._findOption(positiveLongFlag)) { + this.setOptionValueWithSource( + name, + option.defaultValue === undefined ? true : option.defaultValue, + 'default', + ); } + } else if (option.defaultValue !== undefined) { + this.setOptionValueWithSource(name, option.defaultValue, 'default'); } - const session = http2.connect(authority, options); - - let removed; - - const removeSession = () => { - if (removed) { - return; + // handler for cli and env supplied values + const handleOptionValue = (val, invalidValueMessage, valueSource) => { + // val is null for optional option used without an optional-argument. + // val is undefined for boolean and negated option. + if (val == null && option.presetArg !== undefined) { + val = option.presetArg; } - removed = true; - - let entries = authoritySessions, len = entries.length, i = len; + // custom processing + const oldValue = this.getOptionValue(name); + if (val !== null && option.parseArg) { + val = this._callParseArg(option, val, oldValue, invalidValueMessage); + } else if (val !== null && option.variadic) { + val = option._concatValue(val, oldValue); + } - while (i--) { - if (entries[i][0] === session) { - entries.splice(i, 1); - if (len === 1) { - delete this.sessions[authority]; - return; - } + // Fill-in appropriate missing values. Long winded but easy to follow. + if (val == null) { + if (option.negate) { + val = false; + } else if (option.isBoolean() || option.optional) { + val = true; + } else { + val = ''; // not normal, parseArg might have failed or be a mock function for testing } } + this.setOptionValueWithSource(name, val, valueSource); }; - const originalRequestFn = session.request; - - const {sessionTimeout} = options; - - if(sessionTimeout != null) { - - let timer; - let streamsCount = 0; - - session.request = function () { - const stream = originalRequestFn.apply(this, arguments); - - streamsCount++; + this.on('option:' + oname, (val) => { + const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`; + handleOptionValue(val, invalidValueMessage, 'cli'); + }); - if (timer) { - clearTimeout(timer); - timer = null; - } + if (option.envVar) { + this.on('optionEnv:' + oname, (val) => { + const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`; + handleOptionValue(val, invalidValueMessage, 'env'); + }); + } - stream.once('close', () => { - if (!--streamsCount) { - timer = setTimeout(() => { - timer = null; - removeSession(); - }, sessionTimeout); - } - }); + return this; + } - return stream; + /** + * Internal implementation shared by .option() and .requiredOption() + * + * @return {Command} `this` command for chaining + * @private + */ + _optionEx(config, flags, description, fn, defaultValue) { + if (typeof flags === 'object' && flags instanceof Option) { + throw new Error( + 'To add an Option object use addOption() instead of option() or requiredOption()', + ); + } + const option = this.createOption(flags, description); + option.makeOptionMandatory(!!config.mandatory); + if (typeof fn === 'function') { + option.default(defaultValue).argParser(fn); + } else if (fn instanceof RegExp) { + // deprecated + const regex = fn; + fn = (val, def) => { + const m = regex.exec(val); + return m ? m[0] : def; }; + option.default(defaultValue).argParser(fn); + } else { + option.default(fn); } - session.once('close', removeSession); + return this.addOption(option); + } - let entries = this.sessions[authority], entry = [ - session, - options - ]; + /** + * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. + * + * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required + * option-argument is indicated by `<>` and an optional option-argument by `[]`. + * + * See the README for more details, and see also addOption() and requiredOption(). + * + * @example + * program + * .option('-p, --pepper', 'add pepper') + * .option('-p, --pizza-type ', 'type of pizza') // required option-argument + * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default + * .option('-t, --tip ', 'add tip to purchase cost', parseFloat) // custom parse function + * + * @param {string} flags + * @param {string} [description] + * @param {(Function|*)} [parseArg] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + */ + + option(flags, description, parseArg, defaultValue) { + return this._optionEx({}, flags, description, parseArg, defaultValue); + } - entries ? this.sessions[authority].push(entry) : authoritySessions = this.sessions[authority] = [entry]; + /** + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. + * + * @param {string} flags + * @param {string} [description] + * @param {(Function|*)} [parseArg] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + */ - return session; + requiredOption(flags, description, parseArg, defaultValue) { + return this._optionEx( + { mandatory: true }, + flags, + description, + parseArg, + defaultValue, + ); } -} -const http2Sessions = new Http2Sessions(); + /** + * Alter parsing of short flags with optional values. + * + * @example + * // for `.option('-f,--flag [value]'): + * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour + * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` + * + * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag. + * @return {Command} `this` command for chaining + */ + combineFlagAndOptionalValue(combine = true) { + this._combineFlagAndOptionalValue = !!combine; + return this; + } + /** + * Allow unknown options on the command line. + * + * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options. + * @return {Command} `this` command for chaining + */ + allowUnknownOption(allowUnknown = true) { + this._allowUnknownOption = !!allowUnknown; + return this; + } -/** - * If the proxy or config beforeRedirects functions are defined, call them with the options - * object. - * - * @param {Object} options - The options object that was passed to the request. - * - * @returns {Object} - */ -function dispatchBeforeRedirect(options, responseDetails) { - if (options.beforeRedirects.proxy) { - options.beforeRedirects.proxy(options); + /** + * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. + * + * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments. + * @return {Command} `this` command for chaining + */ + allowExcessArguments(allowExcess = true) { + this._allowExcessArguments = !!allowExcess; + return this; } - if (options.beforeRedirects.config) { - options.beforeRedirects.config(options, responseDetails); + + /** + * Enable positional options. Positional means global options are specified before subcommands which lets + * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. + * The default behaviour is non-positional and global options may appear anywhere on the command line. + * + * @param {boolean} [positional] + * @return {Command} `this` command for chaining + */ + enablePositionalOptions(positional = true) { + this._enablePositionalOptions = !!positional; + return this; } -} -/** - * If the proxy or config afterRedirects functions are defined, call them with the options - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} configProxy configuration from Axios options object - * @param {string} location - * - * @returns {http.ClientRequestArgs} - */ -function setProxy(options, configProxy, location) { - let proxy = configProxy; - if (!proxy && proxy !== false) { - const proxyUrl = proxyFromEnv__default["default"].getProxyForUrl(location); - if (proxyUrl) { - proxy = new URL(proxyUrl); - } + /** + * Pass through options that come after command-arguments rather than treat them as command-options, + * so actual command-options come before command-arguments. Turning this on for a subcommand requires + * positional options to have been enabled on the program (parent commands). + * The default behaviour is non-positional and options may appear before or after command-arguments. + * + * @param {boolean} [passThrough] for unknown options. + * @return {Command} `this` command for chaining + */ + passThroughOptions(passThrough = true) { + this._passThroughOptions = !!passThrough; + this._checkForBrokenPassThrough(); + return this; } - if (proxy) { - // Basic proxy authorization - if (proxy.username) { - proxy.auth = (proxy.username || '') + ':' + (proxy.password || ''); - } - if (proxy.auth) { - // Support proxy auth object form - if (proxy.auth.username || proxy.auth.password) { - proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || ''); - } - const base64 = Buffer - .from(proxy.auth, 'utf8') - .toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } + /** + * @private + */ - options.headers.host = options.hostname + (options.port ? ':' + options.port : ''); - const proxyHost = proxy.hostname || proxy.host; - options.hostname = proxyHost; - // Replace 'host' since options is not a URL object - options.host = proxyHost; - options.port = proxy.port; - options.path = location; - if (proxy.protocol) { - options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`; + _checkForBrokenPassThrough() { + if ( + this.parent && + this._passThroughOptions && + !this.parent._enablePositionalOptions + ) { + throw new Error( + `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`, + ); } } - options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { - // Configure proxy for redirected request, passing the original config proxy to apply - // the exact same logic as if the redirected request was performed by axios directly. - setProxy(redirectOptions, configProxy, redirectOptions.href); - }; -} + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} [storeAsProperties=true] + * @return {Command} `this` command for chaining + */ + + storeOptionsAsProperties(storeAsProperties = true) { + if (this.options.length) { + throw new Error('call .storeOptionsAsProperties() before adding options'); + } + if (Object.keys(this._optionValues).length) { + throw new Error( + 'call .storeOptionsAsProperties() before setting option values', + ); + } + this._storeOptionsAsProperties = !!storeAsProperties; + return this; + } -const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process'; + /** + * Retrieve option value. + * + * @param {string} key + * @return {object} value + */ -// temporary hotfix + getOptionValue(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; + } -const wrapAsync = (asyncExecutor) => { - return new Promise((resolve, reject) => { - let onDone; - let isDone; + /** + * Store option value. + * + * @param {string} key + * @param {object} value + * @return {Command} `this` command for chaining + */ - const done = (value, isRejected) => { - if (isDone) return; - isDone = true; - onDone && onDone(value, isRejected); - }; + setOptionValue(key, value) { + return this.setOptionValueWithSource(key, value, undefined); + } - const _resolve = (value) => { - done(value); - resolve(value); - }; + /** + * Store option value and where the value came from. + * + * @param {string} key + * @param {object} value + * @param {string} source - expected values are default/config/env/cli/implied + * @return {Command} `this` command for chaining + */ - const _reject = (reason) => { - done(reason, true); - reject(reason); - }; + setOptionValueWithSource(key, value, source) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } + this._optionValueSources[key] = source; + return this; + } - asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); - }) -}; + /** + * Get source of option value. + * Expected values are default | config | env | cli | implied + * + * @param {string} key + * @return {string} + */ -const resolveFamily = ({address, family}) => { - if (!utils$1.isString(address)) { - throw TypeError('address must be a string'); + getOptionValueSource(key) { + return this._optionValueSources[key]; } - return ({ - address, - family: family || (address.indexOf('.') < 0 ? 6 : 4) - }); -}; -const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family}); + /** + * Get source of option value. See also .optsWithGlobals(). + * Expected values are default | config | env | cli | implied + * + * @param {string} key + * @return {string} + */ -const http2Transport = { - request(options, cb) { - const authority = options.protocol + '//' + options.hostname + ':' + (options.port || 80); + getOptionValueSourceWithGlobals(key) { + // global overwrites local, like optsWithGlobals + let source; + this._getCommandAndAncestors().forEach((cmd) => { + if (cmd.getOptionValueSource(key) !== undefined) { + source = cmd.getOptionValueSource(key); + } + }); + return source; + } - const {http2Options, headers} = options; + /** + * Get user arguments from implied or explicit arguments. + * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. + * + * @private + */ - const session = http2Sessions.getSession(authority, http2Options); + _prepareUserArgs(argv, parseOptions) { + if (argv !== undefined && !Array.isArray(argv)) { + throw new Error('first parameter to parse must be array or undefined'); + } + parseOptions = parseOptions || {}; - const http2Headers = { - [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''), - [HTTP2_HEADER_METHOD]: options.method, - [HTTP2_HEADER_PATH]: options.path, - }; + // auto-detect argument conventions if nothing supplied + if (argv === undefined && parseOptions.from === undefined) { + if (process.versions?.electron) { + parseOptions.from = 'electron'; + } + // check node specific options for scenarios where user CLI args follow executable without scriptname + const execArgv = process.execArgv ?? []; + if ( + execArgv.includes('-e') || + execArgv.includes('--eval') || + execArgv.includes('-p') || + execArgv.includes('--print') + ) { + parseOptions.from = 'eval'; // internal usage, not documented + } + } - utils$1.forEach(headers, (header, name) => { - name.charAt(0) !== ':' && (http2Headers[name] = header); - }); + // default to using process.argv + if (argv === undefined) { + argv = process.argv; + } + this.rawArgs = argv.slice(); - const req = session.request(http2Headers); + // extract the user args and scriptPath + let userArgs; + switch (parseOptions.from) { + case undefined: + case 'node': + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + break; + case 'electron': + // @ts-ignore: because defaultApp is an unknown property + if (process.defaultApp) { + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + } else { + userArgs = argv.slice(1); + } + break; + case 'user': + userArgs = argv.slice(0); + break; + case 'eval': + userArgs = argv.slice(1); + break; + default: + throw new Error( + `unexpected parse option { from: '${parseOptions.from}' }`, + ); + } - req.once('response', (responseHeaders) => { - const response = req; //duplex + // Find default name for program from arguments. + if (!this._name && this._scriptPath) + this.nameFromFilename(this._scriptPath); + this._name = this._name || 'program'; - responseHeaders = Object.assign({}, responseHeaders); + return userArgs; + } - const status = responseHeaders[HTTP2_HEADER_STATUS]; + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. + * + * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! + * + * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: + * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that + * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged + * - `'user'`: just user arguments + * + * @example + * program.parse(); // parse process.argv and auto-detect electron and special node flags + * program.parse(process.argv); // assume argv[0] is app and argv[1] is script + * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] - optional, defaults to process.argv + * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron + * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' + * @return {Command} `this` command for chaining + */ - delete responseHeaders[HTTP2_HEADER_STATUS]; + parse(argv, parseOptions) { + const userArgs = this._prepareUserArgs(argv, parseOptions); + this._parseCommand([], userArgs); - response.headers = responseHeaders; + return this; + } - response.statusCode = +status; + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! + * + * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: + * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that + * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged + * - `'user'`: just user arguments + * + * @example + * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags + * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script + * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] + * @param {object} [parseOptions] + * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' + * @return {Promise} + */ - cb(response); - }); + async parseAsync(argv, parseOptions) { + const userArgs = this._prepareUserArgs(argv, parseOptions); + await this._parseCommand([], userArgs); - return req; + return this; } -}; - -/*eslint consistent-return:0*/ -const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { - return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { - let {data, lookup, family, httpVersion = 1, http2Options} = config; - const {responseType, responseEncoding} = config; - const method = config.method.toUpperCase(); - let isDone; - let rejected = false; - let req; - httpVersion = +httpVersion; - - if (Number.isNaN(httpVersion)) { - throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); - } + /** + * Execute a sub-command executable. + * + * @private + */ - if (httpVersion !== 1 && httpVersion !== 2) { - throw TypeError(`Unsupported protocol version '${httpVersion}'`); - } + _executeSubCommand(subcommand, args) { + args = args.slice(); + let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. + const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs']; - const isHttp2 = httpVersion === 2; + function findFile(baseDir, baseName) { + // Look for specified file + const localBin = path.resolve(baseDir, baseName); + if (fs.existsSync(localBin)) return localBin; - if (lookup) { - const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); - // hotfix to support opt.all option which is required for node 20.x - lookup = (hostname, opt, cb) => { - _lookup(hostname, opt, (err, arg0, arg1) => { - if (err) { - return cb(err); - } + // Stop looking if candidate already has an expected extension. + if (sourceExt.includes(path.extname(baseName))) return undefined; - const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; + // Try all the extensions. + const foundExt = sourceExt.find((ext) => + fs.existsSync(`${localBin}${ext}`), + ); + if (foundExt) return `${localBin}${foundExt}`; - opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); - }); - }; + return undefined; } - const abortEmitter = new events.EventEmitter(); + // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. + this._checkForMissingMandatoryOptions(); + this._checkForConflictingOptions(); - function abort(reason) { + // executableFile and executableDir might be full path, or just a name + let executableFile = + subcommand._executableFile || `${this._name}-${subcommand._name}`; + let executableDir = this._executableDir || ''; + if (this._scriptPath) { + let resolvedScriptPath; // resolve possible symlink for installed npm binary try { - abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason); - } catch(err) { - console.warn('emit error', err); + resolvedScriptPath = fs.realpathSync(this._scriptPath); + } catch (err) { + resolvedScriptPath = this._scriptPath; } + executableDir = path.resolve( + path.dirname(resolvedScriptPath), + executableDir, + ); } - abortEmitter.once('abort', reject); + // Look for a local file in preference to a command in PATH. + if (executableDir) { + let localFile = findFile(executableDir, executableFile); - const onFinished = () => { - if (config.cancelToken) { - config.cancelToken.unsubscribe(abort); + // Legacy search using prefix of script name instead of command name + if (!localFile && !subcommand._executableFile && this._scriptPath) { + const legacyName = path.basename( + this._scriptPath, + path.extname(this._scriptPath), + ); + if (legacyName !== this._name) { + localFile = findFile( + executableDir, + `${legacyName}-${subcommand._name}`, + ); + } } + executableFile = localFile || executableFile; + } - if (config.signal) { - config.signal.removeEventListener('abort', abort); - } + launchWithNode = sourceExt.includes(path.extname(executableFile)); - abortEmitter.removeAllListeners(); - }; + let proc; + if (process.platform !== 'win32') { + if (launchWithNode) { + args.unshift(executableFile); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); - if (config.cancelToken || config.signal) { - config.cancelToken && config.cancelToken.subscribe(abort); - if (config.signal) { - config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); + proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' }); } + } else { + args.unshift(executableFile); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' }); } - onDone((response, isRejected) => { - isDone = true; + if (!proc.killed) { + // testing mainly to avoid leak warnings during unit tests with mocked spawn + const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach((signal) => { + process.on(signal, () => { + if (proc.killed === false && proc.exitCode === null) { + // @ts-ignore because signals not typed to known strings + proc.kill(signal); + } + }); + }); + } - if (isRejected) { - rejected = true; - onFinished(); - return; + // By default terminate process when spawned process terminates. + const exitCallback = this._exitCallback; + proc.on('close', (code) => { + code = code ?? 1; // code is null if spawned process terminated due to a signal + if (!exitCallback) { + process.exit(code); + } else { + exitCallback( + new CommanderError( + code, + 'commander.executeSubCommandAsync', + '(close)', + ), + ); } - - const {data} = response; - - if (data instanceof stream__default["default"].Readable || data instanceof stream__default["default"].Duplex) { - const offListeners = stream__default["default"].finished(data, () => { - offListeners(); - onFinished(); - }); + }); + proc.on('error', (err) => { + // @ts-ignore: because err.code is an unknown property + if (err.code === 'ENOENT') { + const executableDirMessage = executableDir + ? `searched for local subcommand relative to directory '${executableDir}'` + : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory'; + const executableMissing = `'${executableFile}' does not exist + - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead + - if the default executable name is not suitable, use the executableFile option to supply a custom name or path + - ${executableDirMessage}`; + throw new Error(executableMissing); + // @ts-ignore: because err.code is an unknown property + } else if (err.code === 'EACCES') { + throw new Error(`'${executableFile}' not executable`); + } + if (!exitCallback) { + process.exit(1); } else { - onFinished(); + const wrappedError = new CommanderError( + 1, + 'commander.executeSubCommandAsync', + '(error)', + ); + wrappedError.nestedError = err; + exitCallback(wrappedError); } }); + // Store the reference to the child process + this.runningCommand = proc; + } + /** + * @private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this.help({ error: true }); - - // Parse url - const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); - const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); - const protocol = parsed.protocol || supportedProtocols[0]; - - if (protocol === 'data:') { - // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set. - if (config.maxContentLength > -1) { - // Use the exact string passed to fromDataURI (config.url); fall back to fullPath if needed. - const dataUrl = String(config.url || fullPath || ''); - const estimated = estimateDataURLDecodedBytes(dataUrl); - - if (estimated > config.maxContentLength) { - return reject(new AxiosError( - 'maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, - config - )); - } - } - - let convertedData; - - if (method !== 'GET') { - return settle(resolve, reject, { - status: 405, - statusText: 'method not allowed', - headers: {}, - config - }); - } - - try { - convertedData = fromDataURI(config.url, responseType === 'blob', { - Blob: config.env && config.env.Blob - }); - } catch (err) { - throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); + let promiseChain; + promiseChain = this._chainOrCallSubCommandHook( + promiseChain, + subCommand, + 'preSubcommand', + ); + promiseChain = this._chainOrCall(promiseChain, () => { + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); + } else { + return subCommand._parseCommand(operands, unknown); } + }); + return promiseChain; + } - if (responseType === 'text') { - convertedData = convertedData.toString(responseEncoding); - - if (!responseEncoding || responseEncoding === 'utf8') { - convertedData = utils$1.stripBOM(convertedData); - } - } else if (responseType === 'stream') { - convertedData = stream__default["default"].Readable.from(convertedData); - } + /** + * Invoke help directly if possible, or dispatch if necessary. + * e.g. help foo + * + * @private + */ - return settle(resolve, reject, { - data: convertedData, - status: 200, - statusText: 'OK', - headers: new AxiosHeaders$1(), - config - }); + _dispatchHelpCommand(subcommandName) { + if (!subcommandName) { + this.help(); } - - if (supportedProtocols.indexOf(protocol) === -1) { - return reject(new AxiosError( - 'Unsupported protocol ' + protocol, - AxiosError.ERR_BAD_REQUEST, - config - )); + const subCommand = this._findCommand(subcommandName); + if (subCommand && !subCommand._executableHandler) { + subCommand.help(); } - const headers = AxiosHeaders$1.from(config.headers).normalize(); - - // Set User-Agent (required by some servers) - // See https://github.com/axios/axios/issues/69 - // User-Agent is specified; handle case where no UA header is desired - // Only set header if it hasn't been set in config - headers.set('User-Agent', 'axios/' + VERSION, false); - - const {onUploadProgress, onDownloadProgress} = config; - const maxRate = config.maxRate; - let maxUploadRate = undefined; - let maxDownloadRate = undefined; - - // support for spec compliant FormData objects - if (utils$1.isSpecCompliantForm(data)) { - const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); + // Fallback to parsing the help flag to invoke the help. + return this._dispatchSubcommand( + subcommandName, + [], + [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'], + ); + } - data = formDataToStream$1(data, (formHeaders) => { - headers.set(formHeaders); - }, { - tag: `axios-${VERSION}-boundary`, - boundary: userBoundary && userBoundary[1] || undefined - }); - // support for https://www.npmjs.com/package/form-data api - } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { - headers.set(data.getHeaders()); + /** + * Check this.args against expected this.registeredArguments. + * + * @private + */ - if (!headers.hasContentLength()) { - try { - const knownLength = await util__default["default"].promisify(data.getLength).call(data); - Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); - /*eslint no-empty:0*/ - } catch (e) { - } - } - } else if (utils$1.isBlob(data) || utils$1.isFile(data)) { - data.size && headers.setContentType(data.type || 'application/octet-stream'); - headers.setContentLength(data.size || 0); - data = stream__default["default"].Readable.from(readBlob$1(data)); - } else if (data && !utils$1.isStream(data)) { - if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils$1.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(new AxiosError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - AxiosError.ERR_BAD_REQUEST, - config - )); + _checkNumberOfArguments() { + // too few + this.registeredArguments.forEach((arg, i) => { + if (arg.required && this.args[i] == null) { + this.missingArgument(arg.name()); } + }); + // too many + if ( + this.registeredArguments.length > 0 && + this.registeredArguments[this.registeredArguments.length - 1].variadic + ) { + return; + } + if (this.args.length > this.registeredArguments.length) { + this._excessArguments(this.args); + } + } - // Add Content-Length header if data exists - headers.setContentLength(data.length, false); + /** + * Process this.args using this.registeredArguments and save as this.processedArgs! + * + * @private + */ - if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { - return reject(new AxiosError( - 'Request body larger than maxBodyLength limit', - AxiosError.ERR_BAD_REQUEST, - config - )); + _processArguments() { + const myParseArg = (argument, value, previous) => { + // Extra processing for nice error message on parsing failure. + let parsedValue = value; + if (value !== null && argument.parseArg) { + const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`; + parsedValue = this._callParseArg( + argument, + value, + previous, + invalidValueMessage, + ); } - } - - const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); + return parsedValue; + }; - if (utils$1.isArray(maxRate)) { - maxUploadRate = maxRate[0]; - maxDownloadRate = maxRate[1]; - } else { - maxUploadRate = maxDownloadRate = maxRate; - } + this._checkNumberOfArguments(); - if (data && (onUploadProgress || maxUploadRate)) { - if (!utils$1.isStream(data)) { - data = stream__default["default"].Readable.from(data, {objectMode: false}); + const processedArgs = []; + this.registeredArguments.forEach((declaredArg, index) => { + let value = declaredArg.defaultValue; + if (declaredArg.variadic) { + // Collect together remaining arguments for passing together as an array. + if (index < this.args.length) { + value = this.args.slice(index); + if (declaredArg.parseArg) { + value = value.reduce((processed, v) => { + return myParseArg(declaredArg, v, processed); + }, declaredArg.defaultValue); + } + } else if (value === undefined) { + value = []; + } + } else if (index < this.args.length) { + value = this.args[index]; + if (declaredArg.parseArg) { + value = myParseArg(declaredArg, value, declaredArg.defaultValue); + } } + processedArgs[index] = value; + }); + this.processedArgs = processedArgs; + } - data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxUploadRate) - })], utils$1.noop); + /** + * Once we have a promise we chain, but call synchronously until then. + * + * @param {(Promise|undefined)} promise + * @param {Function} fn + * @return {(Promise|undefined)} + * @private + */ - onUploadProgress && data.on('progress', flushOnFinish( - data, - progressEventDecorator( - contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) - ) - )); + _chainOrCall(promise, fn) { + // thenable + if (promise && promise.then && typeof promise.then === 'function') { + // already have a promise, chain callback + return promise.then(() => fn()); } + // callback might return a promise + return fn(); + } - // HTTP basic authentication - let auth = undefined; - if (config.auth) { - const username = config.auth.username || ''; - const password = config.auth.password || ''; - auth = username + ':' + password; - } + /** + * + * @param {(Promise|undefined)} promise + * @param {string} event + * @return {(Promise|undefined)} + * @private + */ - if (!auth && parsed.username) { - const urlUsername = parsed.username; - const urlPassword = parsed.password; - auth = urlUsername + ':' + urlPassword; + _chainOrCallHooks(promise, event) { + let result = promise; + const hooks = []; + this._getCommandAndAncestors() + .reverse() + .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined) + .forEach((hookedCommand) => { + hookedCommand._lifeCycleHooks[event].forEach((callback) => { + hooks.push({ hookedCommand, callback }); + }); + }); + if (event === 'postAction') { + hooks.reverse(); } - auth && headers.delete('authorization'); + hooks.forEach((hookDetail) => { + result = this._chainOrCall(result, () => { + return hookDetail.callback(hookDetail.hookedCommand, this); + }); + }); + return result; + } - let path; + /** + * + * @param {(Promise|undefined)} promise + * @param {Command} subCommand + * @param {string} event + * @return {(Promise|undefined)} + * @private + */ - try { - path = buildURL( - parsed.pathname + parsed.search, - config.params, - config.paramsSerializer - ).replace(/^\?/, ''); - } catch (err) { - const customErr = new Error(err.message); - customErr.config = config; - customErr.url = config.url; - customErr.exists = true; - return reject(customErr); + _chainOrCallSubCommandHook(promise, subCommand, event) { + let result = promise; + if (this._lifeCycleHooks[event] !== undefined) { + this._lifeCycleHooks[event].forEach((hook) => { + result = this._chainOrCall(result, () => { + return hook(this, subCommand); + }); + }); } + return result; + } - headers.set( - 'Accept-Encoding', - 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false - ); - - const options = { - path, - method: method, - headers: headers.toJSON(), - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth, - protocol, - family, - beforeRedirect: dispatchBeforeRedirect, - beforeRedirects: {}, - http2Options - }; + /** + * Process arguments in context of this command. + * Returns action result, in case it is a promise. + * + * @private + */ - // cacheable-lookup integration hotfix - !utils$1.isUndefined(lookup) && (options.lookup = lookup); + _parseCommand(operands, unknown) { + const parsed = this.parseOptions(unknown); + this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env + this._parseOptionsImplied(); + operands = operands.concat(parsed.operands); + unknown = parsed.unknown; + this.args = operands.concat(unknown); - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; - options.port = parsed.port; - setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + if (operands && this._findCommand(operands[0])) { + return this._dispatchSubcommand(operands[0], operands.slice(1), unknown); } - - let transport; - const isHttpsRequest = isHttps.test(options.protocol); - options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; - - if (isHttp2) { - transport = http2Transport; - } else { - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsRequest ? https__default["default"] : http__default["default"]; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - if (config.beforeRedirect) { - options.beforeRedirects.config = config.beforeRedirect; - } - transport = isHttpsRequest ? httpsFollow : httpFollow; - } + if ( + this._getHelpCommand() && + operands[0] === this._getHelpCommand().name() + ) { + return this._dispatchHelpCommand(operands[1]); } - - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } else { - // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited - options.maxBodyLength = Infinity; + if (this._defaultCommandName) { + this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command + return this._dispatchSubcommand( + this._defaultCommandName, + operands, + unknown, + ); } - - if (config.insecureHTTPParser) { - options.insecureHTTPParser = config.insecureHTTPParser; + if ( + this.commands.length && + this.args.length === 0 && + !this._actionHandler && + !this._defaultCommandName + ) { + // probably missing subcommand and no handler, user needs help (and exit) + this.help({ error: true }); } - // Create the request - req = transport.request(options, function handleResponse(res) { - if (req.destroyed) return; + this._outputHelpIfRequested(parsed.unknown); + this._checkForMissingMandatoryOptions(); + this._checkForConflictingOptions(); - const streams = [res]; + // We do not always call this check to avoid masking a "better" error, like unknown command. + const checkForUnknownOptions = () => { + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); + } + }; - const responseLength = utils$1.toFiniteNumber(res.headers['content-length']); + const commandEvent = `command:${this.name()}`; + if (this._actionHandler) { + checkForUnknownOptions(); + this._processArguments(); - if (onDownloadProgress || maxDownloadRate) { - const transformStream = new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxDownloadRate) + let promiseChain; + promiseChain = this._chainOrCallHooks(promiseChain, 'preAction'); + promiseChain = this._chainOrCall(promiseChain, () => + this._actionHandler(this.processedArgs), + ); + if (this.parent) { + promiseChain = this._chainOrCall(promiseChain, () => { + this.parent.emit(commandEvent, operands, unknown); // legacy }); - - onDownloadProgress && transformStream.on('progress', flushOnFinish( - transformStream, - progressEventDecorator( - responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) - ) - )); - - streams.push(transformStream); } - - // decompress the response body transparently if required - let responseStream = res; - - // return the last request in case of redirects - const lastRequest = res.req || req; - - // if decompress disabled we should not decompress - if (config.decompress !== false && res.headers['content-encoding']) { - // if no content, but headers still say that it is encoded, - // remove the header not confuse downstream operations - if (method === 'HEAD' || res.statusCode === 204) { - delete res.headers['content-encoding']; - } - - switch ((res.headers['content-encoding'] || '').toLowerCase()) { - /*eslint default-case:0*/ - case 'gzip': - case 'x-gzip': - case 'compress': - case 'x-compress': - // add the unzipper to the body stream processing pipeline - streams.push(zlib__default["default"].createUnzip(zlibOptions)); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - case 'deflate': - streams.push(new ZlibHeaderTransformStream$1()); - - // add the unzipper to the body stream processing pipeline - streams.push(zlib__default["default"].createUnzip(zlibOptions)); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - case 'br': - if (isBrotliSupported) { - streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions)); - delete res.headers['content-encoding']; - } - } + promiseChain = this._chainOrCallHooks(promiseChain, 'postAction'); + return promiseChain; + } + if (this.parent && this.parent.listenerCount(commandEvent)) { + checkForUnknownOptions(); + this._processArguments(); + this.parent.emit(commandEvent, operands, unknown); // legacy + } else if (operands.length) { + if (this._findCommand('*')) { + // legacy default command + return this._dispatchSubcommand('*', operands, unknown); } - - responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; - - - - const response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: new AxiosHeaders$1(res.headers), - config, - request: lastRequest - }; - - if (responseType === 'stream') { - response.data = responseStream; - settle(resolve, reject, response); + if (this.listenerCount('command:*')) { + // skip option check, emit event for possible misspelling suggestion + this.emit('command:*', operands, unknown); + } else if (this.commands.length) { + this.unknownCommand(); } else { - const responseBuffer = []; - let totalResponseBytes = 0; - - responseStream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; - - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { - // stream.destroy() emit aborted event before calling reject() on Node.js v16 - rejected = true; - responseStream.destroy(); - abort(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); - } - }); + checkForUnknownOptions(); + this._processArguments(); + } + } else if (this.commands.length) { + checkForUnknownOptions(); + // This command has subcommands and nothing hooked up at this level, so display help (and exit). + this.help({ error: true }); + } else { + checkForUnknownOptions(); + this._processArguments(); + // fall through for caller to handle after calling .parse() + } + } - responseStream.on('aborted', function handlerStreamAborted() { - if (rejected) { - return; - } + /** + * Find matching command. + * + * @private + * @return {Command | undefined} + */ + _findCommand(name) { + if (!name) return undefined; + return this.commands.find( + (cmd) => cmd._name === name || cmd._aliases.includes(name), + ); + } - const err = new AxiosError( - 'stream has been aborted', - AxiosError.ERR_BAD_RESPONSE, - config, - lastRequest - ); - responseStream.destroy(err); - reject(err); - }); + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @package + */ - responseStream.on('error', function handleStreamError(err) { - if (req.destroyed) return; - reject(AxiosError.from(err, null, config, lastRequest)); - }); + _findOption(arg) { + return this.options.find((option) => option.is(arg)); + } - responseStream.on('end', function handleStreamEnd() { - try { - let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); - if (responseType !== 'arraybuffer') { - responseData = responseData.toString(responseEncoding); - if (!responseEncoding || responseEncoding === 'utf8') { - responseData = utils$1.stripBOM(responseData); - } - } - response.data = responseData; - } catch (err) { - return reject(AxiosError.from(err, null, config, response.request, response)); - } - settle(resolve, reject, response); - }); - } + /** + * Display an error message if a mandatory option does not have a value. + * Called after checking for help flags in leaf subcommand. + * + * @private + */ - abortEmitter.once('abort', err => { - if (!responseStream.destroyed) { - responseStream.emit('error', err); - responseStream.destroy(); + _checkForMissingMandatoryOptions() { + // Walk up hierarchy so can call in subcommand after checking for displaying help. + this._getCommandAndAncestors().forEach((cmd) => { + cmd.options.forEach((anOption) => { + if ( + anOption.mandatory && + cmd.getOptionValue(anOption.attributeName()) === undefined + ) { + cmd.missingMandatoryOptionValue(anOption); } }); }); + } - abortEmitter.once('abort', err => { - if (req.close) { - req.close(); - } else { - req.destroy(err); + /** + * Display an error message if conflicting options are used together in this. + * + * @private + */ + _checkForConflictingLocalOptions() { + const definedNonDefaultOptions = this.options.filter((option) => { + const optionKey = option.attributeName(); + if (this.getOptionValue(optionKey) === undefined) { + return false; } + return this.getOptionValueSource(optionKey) !== 'default'; }); - // Handle errors - req.on('error', function handleRequestError(err) { - // @todo remove - // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; - reject(AxiosError.from(err, null, config, req)); - }); + const optionsWithConflicting = definedNonDefaultOptions.filter( + (option) => option.conflictsWith.length > 0, + ); - // set tcp keep alive to prevent drop connection by peer - req.on('socket', function handleRequestSocket(socket) { - // default interval of sending ack packet is 1 minute - socket.setKeepAlive(true, 1000 * 60); + optionsWithConflicting.forEach((option) => { + const conflictingAndDefined = definedNonDefaultOptions.find((defined) => + option.conflictsWith.includes(defined.attributeName()), + ); + if (conflictingAndDefined) { + this._conflictingOption(option, conflictingAndDefined); + } }); + } - // Handle request timeout - if (config.timeout) { - // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. - const timeout = parseInt(config.timeout, 10); + /** + * Display an error message if conflicting options are used together. + * Called after checking for help flags in leaf subcommand. + * + * @private + */ + _checkForConflictingOptions() { + // Walk up hierarchy so can call in subcommand after checking for displaying help. + this._getCommandAndAncestors().forEach((cmd) => { + cmd._checkForConflictingLocalOptions(); + }); + } - if (Number.isNaN(timeout)) { - abort(new AxiosError( - 'error trying to parse `config.timeout` to int', - AxiosError.ERR_BAD_OPTION_VALUE, - config, - req - )); + /** + * Parse options from `argv` removing known options, + * and return argv split into operands and unknown arguments. + * + * Examples: + * + * argv => operands, unknown + * --known kkk op => [op], [] + * op --known kkk => [op], [] + * sub --unknown uuu op => [sub], [--unknown uuu op] + * sub -- --unknown uuu op => [sub --unknown uuu op], [] + * + * @param {string[]} argv + * @return {{operands: string[], unknown: string[]}} + */ - return; - } + parseOptions(argv) { + const operands = []; // operands, not options or values + const unknown = []; // first unknown option and remaining unknown args + let dest = operands; + const args = argv.slice(); - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devouring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(timeout, function handleRequestTimeout() { - if (isDone) return; - let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - abort(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - req - )); - }); + function maybeOption(arg) { + return arg.length > 1 && arg[0] === '-'; } + // parse options + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); - // Send the request - if (utils$1.isStream(data)) { - let ended = false; - let errored = false; - - data.on('end', () => { - ended = true; - }); + // literal + if (arg === '--') { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } - data.once('error', err => { - errored = true; - req.destroy(err); - }); + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; - data.on('close', () => { - if (!ended && !errored) { - abort(new CanceledError('Request stream has been aborted', config, req)); + if (maybeOption(arg)) { + const option = this._findOption(arg); + // recognised option, call listener to assign value with possible custom processing + if (option) { + if (option.required) { + const value = args.shift(); + if (value === undefined) this.optionMissingArgument(option); + this.emit(`option:${option.name()}`, value); + } else if (option.optional) { + let value = null; + // historical behaviour is optional value is following arg unless an option + if (args.length > 0 && !maybeOption(args[0])) { + value = args.shift(); + } + this.emit(`option:${option.name()}`, value); + } else { + // boolean flag + this.emit(`option:${option.name()}`); + } + activeVariadicOption = option.variadic ? option : null; + continue; } - }); - - data.pipe(req); - } else { - data && req.write(data); - req.end(); - } - }); -}; - -const isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { - url = new URL(url, platform.origin); - - return ( - origin.protocol === url.protocol && - origin.host === url.host && - (isMSIE || origin.port === url.port) - ); -})( - new URL(platform.origin), - platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) -) : () => true; + } -const cookies = platform.hasStandardBrowserEnv ? + // Look for combo options following single dash, eat first one if known. + if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + const option = this._findOption(`-${arg[1]}`); + if (option) { + if ( + option.required || + (option.optional && this._combineFlagAndOptionalValue) + ) { + // option with value following in same argument + this.emit(`option:${option.name()}`, arg.slice(2)); + } else { + // boolean option, emit and put back remainder of arg for further processing + this.emit(`option:${option.name()}`); + args.unshift(`-${arg.slice(2)}`); + } + continue; + } + } - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure, sameSite) { - if (typeof document === 'undefined') return; + // Look for known long flag with value, like --foo=bar + if (/^--[^=]+=/.test(arg)) { + const index = arg.indexOf('='); + const option = this._findOption(arg.slice(0, index)); + if (option && (option.required || option.optional)) { + this.emit(`option:${option.name()}`, arg.slice(index + 1)); + continue; + } + } - const cookie = [`${name}=${encodeURIComponent(value)}`]; + // Not a recognised option by this command. + // Might be a command-argument, or subcommand option, or unknown option, or help command or option. - if (utils$1.isNumber(expires)) { - cookie.push(`expires=${new Date(expires).toUTCString()}`); - } - if (utils$1.isString(path)) { - cookie.push(`path=${path}`); - } - if (utils$1.isString(domain)) { - cookie.push(`domain=${domain}`); - } - if (secure === true) { - cookie.push('secure'); - } - if (utils$1.isString(sameSite)) { - cookie.push(`SameSite=${sameSite}`); + // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands. + if (maybeOption(arg)) { + dest = unknown; } - document.cookie = cookie.join('; '); - }, + // If using positionalOptions, stop processing our options at subcommand. + if ( + (this._enablePositionalOptions || this._passThroughOptions) && + operands.length === 0 && + unknown.length === 0 + ) { + if (this._findCommand(arg)) { + operands.push(arg); + if (args.length > 0) unknown.push(...args); + break; + } else if ( + this._getHelpCommand() && + arg === this._getHelpCommand().name() + ) { + operands.push(arg); + if (args.length > 0) operands.push(...args); + break; + } else if (this._defaultCommandName) { + unknown.push(arg); + if (args.length > 0) unknown.push(...args); + break; + } + } - read(name) { - if (typeof document === 'undefined') return null; - const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)')); - return match ? decodeURIComponent(match[1]) : null; - }, + // If using passThroughOptions, stop processing options at first command-argument. + if (this._passThroughOptions) { + dest.push(arg); + if (args.length > 0) dest.push(...args); + break; + } - remove(name) { - this.write(name, '', Date.now() - 86400000, '/'); + // add arg + dest.push(arg); } - } - - : - - // Non-standard browser env (web workers, react-native) lack needed support. - { - write() {}, - read() { - return null; - }, - remove() {} - }; - -const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; -/** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * - * @returns {Object} New object resulting from merging config2 to config1 - */ -function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - const config = {}; - - function getMergedValue(target, source, prop, caseless) { - if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({caseless}, target, source); - } else if (utils$1.isPlainObject(source)) { - return utils$1.merge({}, source); - } else if (utils$1.isArray(source)) { - return source.slice(); - } - return source; + return { operands, unknown }; } - // eslint-disable-next-line consistent-return - function mergeDeepProperties(a, b, prop, caseless) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(a, b, prop, caseless); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a, prop, caseless); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } - } - - // eslint-disable-next-line consistent-return - function defaultToConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a); - } - } - - // eslint-disable-next-line consistent-return - function mergeDirectKeys(a, b, prop) { - if (prop in config2) { - return getMergedValue(a, b); - } else if (prop in config1) { - return getMergedValue(undefined, a); - } - } - - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true) - }; - - utils$1.forEach(Object.keys({...config1, ...config2}), function computeConfigValue(prop) { - const merge = mergeMap[prop] || mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); - (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; -} - -const resolveConfig = (config) => { - const newConfig = mergeConfig({}, config); - - let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; + /** + * Return an object containing local option values as key-value pairs. + * + * @return {object} + */ + opts() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + const result = {}; + const len = this.options.length; - newConfig.headers = headers = AxiosHeaders$1.from(headers); + for (let i = 0; i < len; i++) { + const key = this.options[i].attributeName(); + result[key] = + key === this._versionOptionName ? this._version : this[key]; + } + return result; + } - newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer); + return this._optionValues; + } - // HTTP basic authentication - if (auth) { - headers.set('Authorization', 'Basic ' + - btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) + /** + * Return an object containing merged local and global option values as key-value pairs. + * + * @return {object} + */ + optsWithGlobals() { + // globals overwrite locals + return this._getCommandAndAncestors().reduce( + (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), + {}, ); } - if (utils$1.isFormData(data)) { - if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - headers.setContentType(undefined); // browser handles it - } else if (utils$1.isFunction(data.getHeaders)) { - // Node.js FormData (like form-data package) - const formHeaders = data.getHeaders(); - // Only set safe headers to avoid overwriting security headers - const allowedHeaders = ['content-type', 'content-length']; - Object.entries(formHeaders).forEach(([key, val]) => { - if (allowedHeaders.includes(key.toLowerCase())) { - headers.set(key, val); - } - }); + /** + * Display error message and exit (or call exitOverride). + * + * @param {string} message + * @param {object} [errorOptions] + * @param {string} [errorOptions.code] - an id string representing the error + * @param {number} [errorOptions.exitCode] - used with process.exit + */ + error(message, errorOptions) { + // output handling + this._outputConfiguration.outputError( + `${message}\n`, + this._outputConfiguration.writeErr, + ); + if (typeof this._showHelpAfterError === 'string') { + this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`); + } else if (this._showHelpAfterError) { + this._outputConfiguration.writeErr('\n'); + this.outputHelp({ error: true }); } - } - - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - - if (platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); - if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { - // Add xsrf header - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); + // exit handling + const config = errorOptions || {}; + const exitCode = config.exitCode || 1; + const code = config.code || 'commander.error'; + this._exit(exitCode, code, message); + } - if (xsrfValue) { - headers.set(xsrfHeaderName, xsrfValue); + /** + * Apply any option related environment variables, if option does + * not have a value from cli or client code. + * + * @private + */ + _parseOptionsEnv() { + this.options.forEach((option) => { + if (option.envVar && option.envVar in process.env) { + const optionKey = option.attributeName(); + // Priority check. Do not overwrite cli or options from unknown source (client-code). + if ( + this.getOptionValue(optionKey) === undefined || + ['default', 'config', 'env'].includes( + this.getOptionValueSource(optionKey), + ) + ) { + if (option.required || option.optional) { + // option can take a value + // keep very simple, optional always takes value + this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]); + } else { + // boolean + // keep very simple, only care that envVar defined and not the value + this.emit(`optionEnv:${option.name()}`); + } + } } - } + }); } - return newConfig; -}; - -const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; + /** + * Apply any implied option values, if option is undefined or default value. + * + * @private + */ + _parseOptionsImplied() { + const dualHelper = new DualOptions(this.options); + const hasCustomOptionValue = (optionKey) => { + return ( + this.getOptionValue(optionKey) !== undefined && + !['default', 'implied'].includes(this.getOptionValueSource(optionKey)) + ); + }; + this.options + .filter( + (option) => + option.implied !== undefined && + hasCustomOptionValue(option.attributeName()) && + dualHelper.valueFromOption( + this.getOptionValue(option.attributeName()), + option, + ), + ) + .forEach((option) => { + Object.keys(option.implied) + .filter((impliedKey) => !hasCustomOptionValue(impliedKey)) + .forEach((impliedKey) => { + this.setOptionValueWithSource( + impliedKey, + option.implied[impliedKey], + 'implied', + ); + }); + }); + } -const xhrAdapter = isXHRAdapterSupported && function (config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - const _config = resolveConfig(config); - let requestData = _config.data; - const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); - let {responseType, onUploadProgress, onDownloadProgress} = _config; - let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; + /** + * Argument `name` is missing. + * + * @param {string} name + * @private + */ - function done() { - flushUpload && flushUpload(); // flush events - flushDownload && flushDownload(); // flush events + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + this.error(message, { code: 'commander.missingArgument' }); + } - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); + /** + * `Option` is missing an argument. + * + * @param {Option} option + * @private + */ - _config.signal && _config.signal.removeEventListener('abort', onCanceled); - } + optionMissingArgument(option) { + const message = `error: option '${option.flags}' argument missing`; + this.error(message, { code: 'commander.optionMissingArgument' }); + } - let request = new XMLHttpRequest(); + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @private + */ - request.open(_config.method.toUpperCase(), _config.url, true); + missingMandatoryOptionValue(option) { + const message = `error: required option '${option.flags}' not specified`; + this.error(message, { code: 'commander.missingMandatoryOptionValue' }); + } - // Set the request timeout in MS - request.timeout = _config.timeout; + /** + * `Option` conflicts with another option. + * + * @param {Option} option + * @param {Option} conflictingOption + * @private + */ + _conflictingOption(option, conflictingOption) { + // The calling code does not know whether a negated option is the source of the + // value, so do some work to take an educated guess. + const findBestOptionFromValue = (option) => { + const optionKey = option.attributeName(); + const optionValue = this.getOptionValue(optionKey); + const negativeOption = this.options.find( + (target) => target.negate && optionKey === target.attributeName(), + ); + const positiveOption = this.options.find( + (target) => !target.negate && optionKey === target.attributeName(), + ); + if ( + negativeOption && + ((negativeOption.presetArg === undefined && optionValue === false) || + (negativeOption.presetArg !== undefined && + optionValue === negativeOption.presetArg)) + ) { + return negativeOption; + } + return positiveOption || option; + }; - function onloadend() { - if (!request) { - return; + const getErrorMessage = (option) => { + const bestOption = findBestOptionFromValue(option); + const optionKey = bestOption.attributeName(); + const source = this.getOptionValueSource(optionKey); + if (source === 'env') { + return `environment variable '${bestOption.envVar}'`; } - // Prepare the response - const responseHeaders = AxiosHeaders$1.from( - 'getAllResponseHeaders' in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }; + return `option '${bestOption.flags}'`; + }; - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); + const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`; + this.error(message, { code: 'commander.conflictingOption' }); + } - // Clean up request - request = null; - } + /** + * Unknown option `flag`. + * + * @param {string} flag + * @private + */ - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } + unknownOption(flag) { + if (this._allowUnknownOption) return; + let suggestion = ''; - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; + if (flag.startsWith('--') && this._showSuggestionAfterError) { + // Looping to pick up the global options too + let candidateFlags = []; + // eslint-disable-next-line @typescript-eslint/no-this-alias + let command = this; + do { + const moreFlags = command + .createHelp() + .visibleOptions(command) + .filter((option) => option.long) + .map((option) => option.long); + candidateFlags = candidateFlags.concat(moreFlags); + command = command.parent; + } while (command && !command._enablePositionalOptions); + suggestion = suggestSimilar(flag, candidateFlags); } - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } + const message = `error: unknown option '${flag}'${suggestion}`; + this.error(message, { code: 'commander.unknownOption' }); + } + + /** + * Excess arguments, more than expected. + * + * @param {string[]} receivedArgs + * @private + */ - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); + _excessArguments(receivedArgs) { + if (this._allowExcessArguments) return; - // Clean up request - request = null; - }; + const expected = this.registeredArguments.length; + const s = expected === 1 ? '' : 's'; + const forSubcommand = this.parent ? ` for '${this.name()}'` : ''; + const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; + this.error(message, { code: 'commander.excessArguments' }); + } - // Handle low level network errors - request.onerror = function handleError(event) { - // Browsers deliver a ProgressEvent in XHR onerror - // (message may be empty; when present, surface it) - // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event - const msg = event && event.message ? event.message : 'Network Error'; - const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request); - // attach the underlying event for consumers who want details - err.event = event || null; - reject(err); - request = null; - }; - - // Handle timeout - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = _config.transitional || transitionalDefaults; - if (_config.timeoutErrorMessage) { - timeoutErrorMessage = _config.timeoutErrorMessage; - } - reject(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - request)); - - // Clean up request - request = null; - }; + /** + * Unknown command. + * + * @private + */ - // Remove Content-Type if data is undefined - requestData === undefined && requestHeaders.setContentType(null); + unknownCommand() { + const unknownName = this.args[0]; + let suggestion = ''; - // Add headers to the request - if ('setRequestHeader' in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); + if (this._showSuggestionAfterError) { + const candidateNames = []; + this.createHelp() + .visibleCommands(this) + .forEach((command) => { + candidateNames.push(command.name()); + // just visible alias + if (command.alias()) candidateNames.push(command.alias()); + }); + suggestion = suggestSimilar(unknownName, candidateNames); } - // Add withCredentials to request if needed - if (!utils$1.isUndefined(_config.withCredentials)) { - request.withCredentials = !!_config.withCredentials; - } + const message = `error: unknown command '${unknownName}'${suggestion}`; + this.error(message, { code: 'commander.unknownCommand' }); + } - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = _config.responseType; - } + /** + * Get or set the program version. + * + * This method auto-registers the "-V, --version" option which will print the version number. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {string} [str] + * @param {string} [flags] + * @param {string} [description] + * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments + */ + + version(str, flags, description) { + if (str === undefined) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + const versionOption = this.createOption(flags, description); + this._versionOptionName = versionOption.attributeName(); + this._registerOption(versionOption); + + this.on('option:' + versionOption.name(), () => { + this._outputConfiguration.writeOut(`${str}\n`); + this._exit(0, 'commander.version', str); + }); + return this; + } - // Handle progress if needed - if (onDownloadProgress) { - ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); - request.addEventListener('progress', downloadThrottled); + /** + * Set the description. + * + * @param {string} [str] + * @param {object} [argsDescription] + * @return {(string|Command)} + */ + description(str, argsDescription) { + if (str === undefined && argsDescription === undefined) + return this._description; + this._description = str; + if (argsDescription) { + this._argsDescription = argsDescription; } + return this; + } - // Not all browsers support upload events - if (onUploadProgress && request.upload) { - ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); - - request.upload.addEventListener('progress', uploadThrottled); + /** + * Set the summary. Used when listed as subcommand of parent. + * + * @param {string} [str] + * @return {(string|Command)} + */ + summary(str) { + if (str === undefined) return this._summary; + this._summary = str; + return this; + } - request.upload.addEventListener('loadend', flushUpload); - } + /** + * Set an alias for the command. + * + * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. + * + * @param {string} [alias] + * @return {(string|Command)} + */ - if (_config.cancelToken || _config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = cancel => { - if (!request) { - return; - } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); - request.abort(); - request = null; - }; + alias(alias) { + if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility - _config.cancelToken && _config.cancelToken.subscribe(onCanceled); - if (_config.signal) { - _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); - } + /** @type {Command} */ + // eslint-disable-next-line @typescript-eslint/no-this-alias + let command = this; + if ( + this.commands.length !== 0 && + this.commands[this.commands.length - 1]._executableHandler + ) { + // assume adding alias for last added executable subcommand, rather than this + command = this.commands[this.commands.length - 1]; } - const protocol = parseProtocol(_config.url); - - if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); - return; + if (alias === command._name) + throw new Error("Command alias can't be the same as its name"); + const matchingCommand = this.parent?._findCommand(alias); + if (matchingCommand) { + // c.f. _registerCommand + const existingCmd = [matchingCommand.name()] + .concat(matchingCommand.aliases()) + .join('|'); + throw new Error( + `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`, + ); } + command._aliases.push(alias); + return this; + } - // Send the request - request.send(requestData || null); - }); -}; - -const composeSignals = (signals, timeout) => { - const {length} = (signals = signals ? signals.filter(Boolean) : []); + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {(string[]|Command)} + */ - if (timeout || length) { - let controller = new AbortController(); + aliases(aliases) { + // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). + if (aliases === undefined) return this._aliases; - let aborted; + aliases.forEach((alias) => this.alias(alias)); + return this; + } - const onabort = function (reason) { - if (!aborted) { - aborted = true; - unsubscribe(); - const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); - } - }; + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {(string|Command)} + */ - let timer = timeout && setTimeout(() => { - timer = null; - onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); - }, timeout); - - const unsubscribe = () => { - if (signals) { - timer && clearTimeout(timer); - timer = null; - signals.forEach(signal => { - signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); - }); - signals = null; - } - }; + usage(str) { + if (str === undefined) { + if (this._usage) return this._usage; - signals.forEach((signal) => signal.addEventListener('abort', onabort)); + const args = this.registeredArguments.map((arg) => { + return humanReadableArgName(arg); + }); + return [] + .concat( + this.options.length || this._helpOption !== null ? '[options]' : [], + this.commands.length ? '[command]' : [], + this.registeredArguments.length ? args : [], + ) + .join(' '); + } - const {signal} = controller; + this._usage = str; + return this; + } - signal.unsubscribe = () => utils$1.asap(unsubscribe); + /** + * Get or set the name of the command. + * + * @param {string} [str] + * @return {(string|Command)} + */ - return signal; + name(str) { + if (str === undefined) return this._name; + this._name = str; + return this; } -}; -const composeSignals$1 = composeSignals; + /** + * Set the name of the command from script filename, such as process.argv[1], + * or require.main.filename, or __filename. + * + * (Used internally and public although not documented in README.) + * + * @example + * program.nameFromFilename(require.main.filename); + * + * @param {string} filename + * @return {Command} + */ -const streamChunk = function* (chunk, chunkSize) { - let len = chunk.byteLength; + nameFromFilename(filename) { + this._name = path.basename(filename, path.extname(filename)); - if (!chunkSize || len < chunkSize) { - yield chunk; - return; + return this; } - let pos = 0; - let end; + /** + * Get or set the directory for searching for executable subcommands of this command. + * + * @example + * program.executableDir(__dirname); + * // or + * program.executableDir('subcommands'); + * + * @param {string} [path] + * @return {(string|null|Command)} + */ - while (pos < len) { - end = pos + chunkSize; - yield chunk.slice(pos, end); - pos = end; + executableDir(path) { + if (path === undefined) return this._executableDir; + this._executableDir = path; + return this; } -}; -const readBytes = async function* (iterable, chunkSize) { - for await (const chunk of readStream(iterable)) { - yield* streamChunk(chunk, chunkSize); - } -}; + /** + * Return program help documentation. + * + * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout + * @return {string} + */ -const readStream = async function* (stream) { - if (stream[Symbol.asyncIterator]) { - yield* stream; - return; + helpInformation(contextOptions) { + const helper = this.createHelp(); + if (helper.helpWidth === undefined) { + helper.helpWidth = + contextOptions && contextOptions.error + ? this._outputConfiguration.getErrHelpWidth() + : this._outputConfiguration.getOutHelpWidth(); + } + return helper.formatHelp(this, helper); } - const reader = stream.getReader(); - try { - for (;;) { - const {done, value} = await reader.read(); - if (done) { - break; - } - yield value; + /** + * @private + */ + + _getHelpContext(contextOptions) { + contextOptions = contextOptions || {}; + const context = { error: !!contextOptions.error }; + let write; + if (context.error) { + write = (arg) => this._outputConfiguration.writeErr(arg); + } else { + write = (arg) => this._outputConfiguration.writeOut(arg); } - } finally { - await reader.cancel(); + context.write = contextOptions.write || write; + context.command = this; + return context; } -}; -const trackStream = (stream, chunkSize, onProgress, onFinish) => { - const iterator = readBytes(stream, chunkSize); + /** + * Output help information for this command. + * + * Outputs built-in help, and custom text added using `.addHelpText()`. + * + * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout + */ - let bytes = 0; - let done; - let _onFinish = (e) => { - if (!done) { - done = true; - onFinish && onFinish(e); + outputHelp(contextOptions) { + let deprecatedCallback; + if (typeof contextOptions === 'function') { + deprecatedCallback = contextOptions; + contextOptions = undefined; } - }; - - return new ReadableStream({ - async pull(controller) { - try { - const {done, value} = await iterator.next(); + const context = this._getHelpContext(contextOptions); - if (done) { - _onFinish(); - controller.close(); - return; - } + this._getCommandAndAncestors() + .reverse() + .forEach((command) => command.emit('beforeAllHelp', context)); + this.emit('beforeHelp', context); - let len = value.byteLength; - if (onProgress) { - let loadedBytes = bytes += len; - onProgress(loadedBytes); - } - controller.enqueue(new Uint8Array(value)); - } catch (err) { - _onFinish(err); - throw err; + let helpInformation = this.helpInformation(context); + if (deprecatedCallback) { + helpInformation = deprecatedCallback(helpInformation); + if ( + typeof helpInformation !== 'string' && + !Buffer.isBuffer(helpInformation) + ) { + throw new Error('outputHelp callback must return a string or a Buffer'); } - }, - cancel(reason) { - _onFinish(reason); - return iterator.return(); } - }, { - highWaterMark: 2 - }) -}; - -const DEFAULT_CHUNK_SIZE = 64 * 1024; + context.write(helpInformation); -const {isFunction} = utils$1; + if (this._getHelpOption()?.long) { + this.emit(this._getHelpOption().long); // deprecated + } + this.emit('afterHelp', context); + this._getCommandAndAncestors().forEach((command) => + command.emit('afterAllHelp', context), + ); + } -const globalFetchAPI = (({Request, Response}) => ({ - Request, Response -}))(utils$1.global); + /** + * You can pass in flags and a description to customise the built-in help option. + * Pass in false to disable the built-in help option. + * + * @example + * program.helpOption('-?, --help' 'show help'); // customise + * program.helpOption(false); // disable + * + * @param {(string | boolean)} flags + * @param {string} [description] + * @return {Command} `this` command for chaining + */ -const { - ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1 -} = utils$1.global; + helpOption(flags, description) { + // Support disabling built-in help option. + if (typeof flags === 'boolean') { + if (flags) { + this._helpOption = this._helpOption ?? undefined; // preserve existing option + } else { + this._helpOption = null; // disable + } + return this; + } + // Customise flags and description. + flags = flags ?? '-h, --help'; + description = description ?? 'display help for command'; + this._helpOption = this.createOption(flags, description); -const test = (fn, ...args) => { - try { - return !!fn(...args); - } catch (e) { - return false + return this; } -}; - -const factory = (env) => { - env = utils$1.merge.call({ - skipUndefined: true - }, globalFetchAPI, env); - - const {fetch: envFetch, Request, Response} = env; - const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function'; - const isRequestSupported = isFunction(Request); - const isResponseSupported = isFunction(Response); - if (!isFetchSupported) { - return false; + /** + * Lazy create help option. + * Returns null if has been disabled with .helpOption(false). + * + * @returns {(Option | null)} the help option + * @package + */ + _getHelpOption() { + // Lazy create help option on demand. + if (this._helpOption === undefined) { + this.helpOption(undefined, undefined); + } + return this._helpOption; } - const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1); - - const encodeText = isFetchSupported && (typeof TextEncoder$1 === 'function' ? - ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : - async (str) => new Uint8Array(await new Request(str).arrayBuffer()) - ); - - const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => { - let duplexAccessed = false; - - const hasContentType = new Request(platform.origin, { - body: new ReadableStream$1(), - method: 'POST', - get duplex() { - duplexAccessed = true; - return 'half'; - }, - }).headers.has('Content-Type'); - - return duplexAccessed && !hasContentType; - }); - - const supportsResponseStream = isResponseSupported && isReadableStreamSupported && - test(() => utils$1.isReadableStream(new Response('').body)); - - const resolvers = { - stream: supportsResponseStream && ((res) => res.body) - }; - - isFetchSupported && ((() => { - ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { - !resolvers[type] && (resolvers[type] = (res, config) => { - let method = res && res[type]; - - if (method) { - return method.call(res); - } + /** + * Supply your own option to use for the built-in help option. + * This is an alternative to using helpOption() to customise the flags and description etc. + * + * @param {Option} option + * @return {Command} `this` command for chaining + */ + addHelpOption(option) { + this._helpOption = option; + return this; + } - throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); - }); - }); - })()); + /** + * Output help information and exit. + * + * Outputs built-in help, and custom text added using `.addHelpText()`. + * + * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout + */ - const getBodyLength = async (body) => { - if (body == null) { - return 0; + help(contextOptions) { + this.outputHelp(contextOptions); + let exitCode = process.exitCode || 0; + if ( + exitCode === 0 && + contextOptions && + typeof contextOptions !== 'function' && + contextOptions.error + ) { + exitCode = 1; } + // message: do not have all displayed text available so only passing placeholder. + this._exit(exitCode, 'commander.help', '(outputHelp)'); + } - if (utils$1.isBlob(body)) { - return body.size; + /** + * Add additional text to be displayed with the built-in help. + * + * Position is 'before' or 'after' to affect just this command, + * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. + * + * @param {string} position - before or after built-in help + * @param {(string | Function)} text - string to add, or a function returning a string + * @return {Command} `this` command for chaining + */ + addHelpText(position, text) { + const allowedValues = ['beforeAll', 'before', 'after', 'afterAll']; + if (!allowedValues.includes(position)) { + throw new Error(`Unexpected value for position to addHelpText. +Expecting one of '${allowedValues.join("', '")}'`); } + const helpEvent = `${position}Help`; + this.on(helpEvent, (context) => { + let helpStr; + if (typeof text === 'function') { + helpStr = text({ error: context.error, command: context.command }); + } else { + helpStr = text; + } + // Ignore falsy value when nothing to output. + if (helpStr) { + context.write(`${helpStr}\n`); + } + }); + return this; + } - if (utils$1.isSpecCompliantForm(body)) { - const _request = new Request(platform.origin, { - method: 'POST', - body, - }); - return (await _request.arrayBuffer()).byteLength; - } + /** + * Output help information if help flags specified + * + * @param {Array} args - array of options to search for help flags + * @private + */ - if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { - return body.byteLength; + _outputHelpIfRequested(args) { + const helpOption = this._getHelpOption(); + const helpRequested = helpOption && args.find((arg) => helpOption.is(arg)); + if (helpRequested) { + this.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + this._exit(0, 'commander.helpDisplayed', '(outputHelp)'); } + } +} - if (utils$1.isURLSearchParams(body)) { - body = body + ''; - } +/** + * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * + * @param {string[]} args - array of arguments from node.execArgv + * @returns {string[]} + * @private + */ - if (utils$1.isString(body)) { - return (await encodeText(body)).byteLength; +function incrementNodeInspectorPort(args) { + // Testing for these options: + // --inspect[=[host:]port] + // --inspect-brk[=[host:]port] + // --inspect-port=[host:]port + return args.map((arg) => { + if (!arg.startsWith('--inspect')) { + return arg; } - }; - - const resolveBodyLength = async (headers, body) => { - const length = utils$1.toFiniteNumber(headers.getContentLength()); - - return length == null ? getBodyLength(body) : length; - }; - - return async (config) => { - let { - url, - method, - data, - signal, - cancelToken, - timeout, - onDownloadProgress, - onUploadProgress, - responseType, - headers, - withCredentials = 'same-origin', - fetchOptions - } = resolveConfig(config); - - let _fetch = envFetch || fetch; - - responseType = responseType ? (responseType + '').toLowerCase() : 'text'; - - let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); - - let request = null; - - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { - composedSignal.unsubscribe(); - }); - - let requestContentLength; - - try { - if ( - onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && - (requestContentLength = await resolveBodyLength(headers, data)) !== 0 - ) { - let _request = new Request(url, { - method: 'POST', - body: data, - duplex: "half" - }); - - let contentTypeHeader; - - if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { - headers.setContentType(contentTypeHeader); - } - - if (_request.body) { - const [onProgress, flush] = progressEventDecorator( - requestContentLength, - progressEventReducer(asyncDecorator(onUploadProgress)) - ); - - data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); - } - } - - if (!utils$1.isString(withCredentials)) { - withCredentials = withCredentials ? 'include' : 'omit'; + let debugOption; + let debugHost = '127.0.0.1'; + let debugPort = '9229'; + let match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ( + (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null + ) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; } + } else if ( + (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null + ) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; + } - // Cloudflare Workers throws when credentials are defined - // see https://github.com/cloudflare/workerd/issues/902 - const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype; - - const resolvedOptions = { - ...fetchOptions, - signal: composedSignal, - method: method.toUpperCase(), - headers: headers.normalize().toJSON(), - body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : undefined - }; - - request = isRequestSupported && new Request(url, resolvedOptions); - - let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions)); - - const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); - - if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { - const options = {}; - - ['status', 'statusText', 'headers'].forEach(prop => { - options[prop] = response[prop]; - }); - - const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); - - const [onProgress, flush] = onDownloadProgress && progressEventDecorator( - responseContentLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true) - ) || []; - - response = new Response( - trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { - flush && flush(); - unsubscribe && unsubscribe(); - }), - options - ); - } + if (debugOption && debugPort !== '0') { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + return arg; + }); +} - responseType = responseType || 'text'; +exports.Command = Command; - let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); - !isStreamResponse && unsubscribe && unsubscribe(); +/***/ }), - return await new Promise((resolve, reject) => { - settle(resolve, reject, { - data: responseData, - headers: AxiosHeaders$1.from(response.headers), - status: response.status, - statusText: response.statusText, - config, - request - }); - }) - } catch (err) { - unsubscribe && unsubscribe(); +/***/ 2625: +/***/ ((__unused_webpack_module, exports) => { - if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) { - throw Object.assign( - new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), - { - cause: err.cause || err - } - ) - } +/** + * CommanderError class + */ +class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {number} exitCode suggested exit code which could be used with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + */ + constructor(exitCode, code, message) { + super(message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + this.nestedError = undefined; + } +} - throw AxiosError.from(err, err && err.code, config, request); - } +/** + * InvalidArgumentError class + */ +class InvalidArgumentError extends CommanderError { + /** + * Constructs the InvalidArgumentError class + * @param {string} [message] explanation of why argument is invalid + */ + constructor(message) { + super(1, 'commander.invalidArgument', message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; } -}; - -const seedCache = new Map(); - -const getFetch = (config) => { - let env = (config && config.env) || {}; - const {fetch, Request, Response} = env; - const seeds = [ - Request, Response, fetch - ]; - - let len = seeds.length, i = len, - seed, target, map = seedCache; +} - while (i--) { - seed = seeds[i]; - target = map.get(seed); +exports.CommanderError = CommanderError; +exports.InvalidArgumentError = InvalidArgumentError; - target === undefined && map.set(seed, target = (i ? new Map() : factory(env))); - map = target; - } +/***/ }), - return target; -}; +/***/ 5153: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -getFetch(); +const { humanReadableArgName } = __nccwpck_require__(9414); /** - * Known adapters mapping. - * Provides environment-specific adapters for Axios: - * - `http` for Node.js - * - `xhr` for browsers - * - `fetch` for fetch API-based requests - * - * @type {Object} + * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS` + * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types + * @typedef { import("./argument.js").Argument } Argument + * @typedef { import("./command.js").Command } Command + * @typedef { import("./option.js").Option } Option */ -const knownAdapters = { - http: httpAdapter, - xhr: xhrAdapter, - fetch: { - get: getFetch, + +// Although this is a class, methods are static in style to allow override using subclass or just functions. +class Help { + constructor() { + this.helpWidth = undefined; + this.sortSubcommands = false; + this.sortOptions = false; + this.showGlobalOptions = false; } -}; -// Assign adapter names for easier debugging and identification -utils$1.forEach(knownAdapters, (fn, value) => { - if (fn) { - try { - Object.defineProperty(fn, 'name', { value }); - } catch (e) { - // eslint-disable-next-line no-empty + /** + * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. + * + * @param {Command} cmd + * @returns {Command[]} + */ + + visibleCommands(cmd) { + const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden); + const helpCommand = cmd._getHelpCommand(); + if (helpCommand && !helpCommand._hidden) { + visibleCommands.push(helpCommand); + } + if (this.sortSubcommands) { + visibleCommands.sort((a, b) => { + // @ts-ignore: because overloaded return type + return a.name().localeCompare(b.name()); + }); } - Object.defineProperty(fn, 'adapterName', { value }); + return visibleCommands; } -}); - -/** - * Render a rejection reason string for unknown or unsupported adapters - * - * @param {string} reason - * @returns {string} - */ -const renderReason = (reason) => `- ${reason}`; -/** - * Check if the adapter is resolved (function, null, or false) - * - * @param {Function|null|false} adapter - * @returns {boolean} - */ -const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + /** + * Compare options for sort. + * + * @param {Option} a + * @param {Option} b + * @returns {number} + */ + compareOptions(a, b) { + const getSortKey = (option) => { + // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated. + return option.short + ? option.short.replace(/^-/, '') + : option.long.replace(/^--/, ''); + }; + return getSortKey(a).localeCompare(getSortKey(b)); + } -/** - * Get the first suitable adapter from the provided list. - * Tries each adapter in order until a supported one is found. - * Throws an AxiosError if no adapter is suitable. - * - * @param {Array|string|Function} adapters - Adapter(s) by name or function. - * @param {Object} config - Axios request configuration - * @throws {AxiosError} If no suitable adapter is available - * @returns {Function} The resolved adapter function - */ -function getAdapter(adapters, config) { - adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + /** + * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. + * + * @param {Command} cmd + * @returns {Option[]} + */ - const { length } = adapters; - let nameOrAdapter; - let adapter; + visibleOptions(cmd) { + const visibleOptions = cmd.options.filter((option) => !option.hidden); + // Built-in help option. + const helpOption = cmd._getHelpOption(); + if (helpOption && !helpOption.hidden) { + // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs. + const removeShort = helpOption.short && cmd._findOption(helpOption.short); + const removeLong = helpOption.long && cmd._findOption(helpOption.long); + if (!removeShort && !removeLong) { + visibleOptions.push(helpOption); // no changes needed + } else if (helpOption.long && !removeLong) { + visibleOptions.push( + cmd.createOption(helpOption.long, helpOption.description), + ); + } else if (helpOption.short && !removeShort) { + visibleOptions.push( + cmd.createOption(helpOption.short, helpOption.description), + ); + } + } + if (this.sortOptions) { + visibleOptions.sort(this.compareOptions); + } + return visibleOptions; + } - const rejectedReasons = {}; + /** + * Get an array of the visible global options. (Not including help.) + * + * @param {Command} cmd + * @returns {Option[]} + */ - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - let id; + visibleGlobalOptions(cmd) { + if (!this.showGlobalOptions) return []; - adapter = nameOrAdapter; + const globalOptions = []; + for ( + let ancestorCmd = cmd.parent; + ancestorCmd; + ancestorCmd = ancestorCmd.parent + ) { + const visibleOptions = ancestorCmd.options.filter( + (option) => !option.hidden, + ); + globalOptions.push(...visibleOptions); + } + if (this.sortOptions) { + globalOptions.sort(this.compareOptions); + } + return globalOptions; + } - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + /** + * Get an array of the arguments if any have a description. + * + * @param {Command} cmd + * @returns {Argument[]} + */ - if (adapter === undefined) { - throw new AxiosError(`Unknown adapter '${id}'`); - } + visibleArguments(cmd) { + // Side effect! Apply the legacy descriptions before the arguments are displayed. + if (cmd._argsDescription) { + cmd.registeredArguments.forEach((argument) => { + argument.description = + argument.description || cmd._argsDescription[argument.name()] || ''; + }); } - if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) { - break; + // If there are any arguments with a description then return all the arguments. + if (cmd.registeredArguments.find((argument) => argument.description)) { + return cmd.registeredArguments; } - - rejectedReasons[id || '#' + i] = adapter; + return []; } - if (!adapter) { - const reasons = Object.entries(rejectedReasons) - .map(([id, state]) => `adapter ${id} ` + - (state === false ? 'is not supported by the environment' : 'is not available in the build') - ); - - let s = length ? - (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : - 'as no adapter specified'; + /** + * Get the command term to show in the list of subcommands. + * + * @param {Command} cmd + * @returns {string} + */ - throw new AxiosError( - `There is no suitable adapter to dispatch the request ` + s, - 'ERR_NOT_SUPPORT' + subcommandTerm(cmd) { + // Legacy. Ignores custom usage string, and nested commands. + const args = cmd.registeredArguments + .map((arg) => humanReadableArgName(arg)) + .join(' '); + return ( + cmd._name + + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + + (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option + (args ? ' ' + args : '') ); } - return adapter; -} - -/** - * Exports Axios adapters and utility to resolve an adapter - */ -const adapters = { /** - * Resolve an adapter from a list of adapter names or functions. - * @type {Function} + * Get the option term to show in the list of options. + * + * @param {Option} option + * @returns {string} */ - getAdapter, + + optionTerm(option) { + return option.flags; + } /** - * Exposes all known adapters - * @type {Object} + * Get the argument term to show in the list of arguments. + * + * @param {Argument} argument + * @returns {string} */ - adapters: knownAdapters -}; -/** - * Throws a `CanceledError` if cancellation has been requested. - * - * @param {Object} config The config that is to be used for the request - * - * @returns {void} - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); + argumentTerm(argument) { + return argument.name(); } - if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); + /** + * Get the longest command term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ + + longestSubcommandTermLength(cmd, helper) { + return helper.visibleCommands(cmd).reduce((max, command) => { + return Math.max(max, helper.subcommandTerm(command).length); + }, 0); } -} -/** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * - * @returns {Promise} The Promise to be fulfilled - */ -function dispatchRequest(config) { - throwIfCancellationRequested(config); + /** + * Get the longest option term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ - config.headers = AxiosHeaders$1.from(config.headers); + longestOptionTermLength(cmd, helper) { + return helper.visibleOptions(cmd).reduce((max, option) => { + return Math.max(max, helper.optionTerm(option).length); + }, 0); + } - // Transform request data - config.data = transformData.call( - config, - config.transformRequest - ); + /** + * Get the longest global option term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ - if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { - config.headers.setContentType('application/x-www-form-urlencoded', false); + longestGlobalOptionTermLength(cmd, helper) { + return helper.visibleGlobalOptions(cmd).reduce((max, option) => { + return Math.max(max, helper.optionTerm(option).length); + }, 0); } - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter, config); - - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); + /** + * Get the longest argument term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ - // Transform response data - response.data = transformData.call( - config, - config.transformResponse, - response - ); + longestArgumentTermLength(cmd, helper) { + return helper.visibleArguments(cmd).reduce((max, argument) => { + return Math.max(max, helper.argumentTerm(argument).length); + }, 0); + } - response.headers = AxiosHeaders$1.from(response.headers); + /** + * Get the command usage to be displayed at the top of the built-in help. + * + * @param {Command} cmd + * @returns {string} + */ - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - config.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders$1.from(reason.response.headers); - } + commandUsage(cmd) { + // Usage + let cmdName = cmd._name; + if (cmd._aliases[0]) { + cmdName = cmdName + '|' + cmd._aliases[0]; } + let ancestorCmdNames = ''; + for ( + let ancestorCmd = cmd.parent; + ancestorCmd; + ancestorCmd = ancestorCmd.parent + ) { + ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames; + } + return ancestorCmdNames + cmdName + ' ' + cmd.usage(); + } - return Promise.reject(reason); - }); -} - -const validators$1 = {}; + /** + * Get the description for the command. + * + * @param {Command} cmd + * @returns {string} + */ -// eslint-disable-next-line func-names -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { - validators$1[type] = function validator(thing) { - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; -}); + commandDescription(cmd) { + // @ts-ignore: because overloaded return type + return cmd.description(); + } -const deprecatedWarnings = {}; + /** + * Get the subcommand summary to show in the list of subcommands. + * (Fallback to description for backwards compatibility.) + * + * @param {Command} cmd + * @returns {string} + */ -/** - * Transitional option validator - * - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * - * @returns {function} - */ -validators$1.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + subcommandDescription(cmd) { + // @ts-ignore: because overloaded return type + return cmd.summary() || cmd.description(); } - // eslint-disable-next-line func-names - return (value, opt, opts) => { - if (validator === false) { - throw new AxiosError( - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError.ERR_DEPRECATED - ); - } + /** + * Get the option description to show in the list of options. + * + * @param {Option} option + * @return {string} + */ - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - // eslint-disable-next-line no-console - console.warn( - formatMessage( - opt, - ' has been deprecated since v' + version + ' and will be removed in the near future' - ) + optionDescription(option) { + const extraInfo = []; + + if (option.argChoices) { + extraInfo.push( + // use stringify to match the display of the default value + `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, ); } - - return validator ? validator(value, opt, opts) : true; - }; -}; - -validators$1.spelling = function spelling(correctSpelling) { - return (value, opt) => { - // eslint-disable-next-line no-console - console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); - return true; - } -}; - -/** - * Assert object's properties type - * - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - * - * @returns {object} - */ - -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== 'object') { - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); - } - const keys = Object.keys(options); - let i = keys.length; - while (i-- > 0) { - const opt = keys[i]; - const validator = schema[opt]; - if (validator) { - const value = options[opt]; - const result = value === undefined || validator(value, opt, options); - if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); + if (option.defaultValue !== undefined) { + // default for boolean and negated more for programmer than end user, + // but show true/false for boolean option as may be for hand-rolled env or config processing. + const showDefault = + option.required || + option.optional || + (option.isBoolean() && typeof option.defaultValue === 'boolean'); + if (showDefault) { + extraInfo.push( + `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`, + ); } - continue; } - if (allowUnknown !== true) { - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + // preset for boolean and negated are more for programmer than end user + if (option.presetArg !== undefined && option.optional) { + extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); + } + if (option.envVar !== undefined) { + extraInfo.push(`env: ${option.envVar}`); + } + if (extraInfo.length > 0) { + return `${option.description} (${extraInfo.join(', ')})`; } - } -} - -const validator = { - assertOptions, - validators: validators$1 -}; - -const validators = validator.validators; -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - * - * @return {Axios} A new instance of Axios - */ -class Axios { - constructor(instanceConfig) { - this.defaults = instanceConfig || {}; - this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() - }; + return option.description; } /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config + * Get the argument description to show in the list of arguments. * - * @returns {Promise} The Promise to be fulfilled + * @param {Argument} argument + * @return {string} */ - async request(configOrUrl, config) { - try { - return await this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) { - let dummy = {}; - Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); - - // slice off the Error: ... line - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; - try { - if (!err.stack) { - err.stack = stack; - // match without the 2 top stack lines - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { - err.stack += '\n' + stack; - } - } catch (e) { - // ignore the case where "stack" is an un-writable property - } + argumentDescription(argument) { + const extraInfo = []; + if (argument.argChoices) { + extraInfo.push( + // use stringify to match the display of the default value + `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, + ); + } + if (argument.defaultValue !== undefined) { + extraInfo.push( + `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`, + ); + } + if (extraInfo.length > 0) { + const extraDescripton = `(${extraInfo.join(', ')})`; + if (argument.description) { + return `${argument.description} ${extraDescripton}`; } - - throw err; + return extraDescripton; } + return argument.description; } - _request(configOrUrl, config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof configOrUrl === 'string') { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; + /** + * Generate the built-in help text. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {string} + */ + + formatHelp(cmd, helper) { + const termWidth = helper.padWidth(cmd, helper); + const helpWidth = helper.helpWidth || 80; + const itemIndentWidth = 2; + const itemSeparatorWidth = 2; // between term and description + function formatItem(term, description) { + if (description) { + const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; + return helper.wrap( + fullText, + helpWidth - itemIndentWidth, + termWidth + itemSeparatorWidth, + ); + } + return term; + } + function formatList(textArray) { + return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); } - config = mergeConfig(this.defaults, config); + // Usage + let output = [`Usage: ${helper.commandUsage(cmd)}`, '']; - const {transitional, paramsSerializer, headers} = config; + // Description + const commandDescription = helper.commandDescription(cmd); + if (commandDescription.length > 0) { + output = output.concat([ + helper.wrap(commandDescription, helpWidth, 0), + '', + ]); + } - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); + // Arguments + const argumentList = helper.visibleArguments(cmd).map((argument) => { + return formatItem( + helper.argumentTerm(argument), + helper.argumentDescription(argument), + ); + }); + if (argumentList.length > 0) { + output = output.concat(['Arguments:', formatList(argumentList), '']); } - if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { - config.paramsSerializer = { - serialize: paramsSerializer - }; - } else { - validator.assertOptions(paramsSerializer, { - encode: validators.function, - serialize: validators.function - }, true); + // Options + const optionList = helper.visibleOptions(cmd).map((option) => { + return formatItem( + helper.optionTerm(option), + helper.optionDescription(option), + ); + }); + if (optionList.length > 0) { + output = output.concat(['Options:', formatList(optionList), '']); + } + + if (this.showGlobalOptions) { + const globalOptionList = helper + .visibleGlobalOptions(cmd) + .map((option) => { + return formatItem( + helper.optionTerm(option), + helper.optionDescription(option), + ); + }); + if (globalOptionList.length > 0) { + output = output.concat([ + 'Global Options:', + formatList(globalOptionList), + '', + ]); } } - // Set config.allowAbsoluteUrls - if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) { - config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; - } else { - config.allowAbsoluteUrls = true; + // Commands + const commandList = helper.visibleCommands(cmd).map((cmd) => { + return formatItem( + helper.subcommandTerm(cmd), + helper.subcommandDescription(cmd), + ); + }); + if (commandList.length > 0) { + output = output.concat(['Commands:', formatList(commandList), '']); } - validator.assertOptions(config, { - baseUrl: validators.spelling('baseURL'), - withXsrfToken: validators.spelling('withXSRFToken') - }, true); + return output.join('\n'); + } + + /** + * Calculate the pad width from the maximum term length. + * + * @param {Command} cmd + * @param {Help} helper + * @returns {number} + */ + + padWidth(cmd, helper) { + return Math.max( + helper.longestOptionTermLength(cmd, helper), + helper.longestGlobalOptionTermLength(cmd, helper), + helper.longestSubcommandTermLength(cmd, helper), + helper.longestArgumentTermLength(cmd, helper), + ); + } + + /** + * Wrap the given string to width characters per line, with lines after the first indented. + * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @param {number} [minColumnWidth=40] + * @return {string} + * + */ - // Set config.method - config.method = (config.method || this.defaults.method || 'get').toLowerCase(); + wrap(str, width, indent, minColumnWidth = 40) { + // Full \s characters, minus the linefeeds. + const indents = + ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff'; + // Detect manually wrapped and indented strings by searching for line break followed by spaces. + const manualIndent = new RegExp(`[\\n][${indents}]+`); + if (str.match(manualIndent)) return str; + // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line). + const columnWidth = width - indent; + if (columnWidth < minColumnWidth) return str; - // Flatten headers - let contextHeaders = headers && utils$1.merge( - headers.common, - headers[config.method] + const leadingStr = str.slice(0, indent); + const columnText = str.slice(indent).replace('\r\n', '\n'); + const indentString = ' '.repeat(indent); + const zeroWidthSpace = '\u200B'; + const breaks = `\\s${zeroWidthSpace}`; + // Match line end (so empty lines don't collapse), + // or as much text as will fit in column, or excess text up to first break. + const regex = new RegExp( + `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, + 'g', ); - - headers && utils$1.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - (method) => { - delete headers[method]; - } + const lines = columnText.match(regex) || []; + return ( + leadingStr + + lines + .map((line, i) => { + if (line === '\n') return ''; // preserve empty lines + return (i > 0 ? indentString : '') + line.trimEnd(); + }) + .join('\n') ); + } +} - config.headers = AxiosHeaders$1.concat(contextHeaders, headers); - - // filter out skipped interceptors - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; - } - - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; +exports.Help = Help; - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); +/***/ }), - let promise; - let i = 0; - let len; +/***/ 6558: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), undefined]; - chain.unshift(...requestInterceptorChain); - chain.push(...responseInterceptorChain); - len = chain.length; +const { InvalidArgumentError } = __nccwpck_require__(2625); - promise = Promise.resolve(config); +class Option { + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} [description] + */ - while (i < len) { - promise = promise.then(chain[i++], chain[i++]); - } + constructor(flags, description) { + this.flags = flags; + this.description = description || ''; - return promise; + this.required = flags.includes('<'); // A value must be supplied when the option is specified. + this.optional = flags.includes('['); // A value is optional when the option is specified. + // variadic test ignores et al which might be used to describe custom splitting of single argument + this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + const optionFlags = splitOptionFlags(flags); + this.short = optionFlags.shortFlag; + this.long = optionFlags.longFlag; + this.negate = false; + if (this.long) { + this.negate = this.long.startsWith('--no-'); } + this.defaultValue = undefined; + this.defaultValueDescription = undefined; + this.presetArg = undefined; + this.envVar = undefined; + this.parseArg = undefined; + this.hidden = false; + this.argChoices = undefined; + this.conflictsWith = []; + this.implied = undefined; + } - len = requestInterceptorChain.length; - - let newConfig = config; + /** + * Set the default value, and optionally supply the description to be displayed in the help. + * + * @param {*} value + * @param {string} [description] + * @return {Option} + */ - while (i < len) { - const onFulfilled = requestInterceptorChain[i++]; - const onRejected = requestInterceptorChain[i++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; - } - } + default(value, description) { + this.defaultValue = value; + this.defaultValueDescription = description; + return this; + } - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); - } + /** + * Preset to use when option used without option-argument, especially optional but also boolean and negated. + * The custom processing (parseArg) is called. + * + * @example + * new Option('--color').default('GREYSCALE').preset('RGB'); + * new Option('--donate [amount]').preset('20').argParser(parseFloat); + * + * @param {*} arg + * @return {Option} + */ - i = 0; - len = responseInterceptorChain.length; + preset(arg) { + this.presetArg = arg; + return this; + } - while (i < len) { - promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); - } + /** + * Add option name(s) that conflict with this option. + * An error will be displayed if conflicting options are found during parsing. + * + * @example + * new Option('--rgb').conflicts('cmyk'); + * new Option('--js').conflicts(['ts', 'jsx']); + * + * @param {(string | string[])} names + * @return {Option} + */ - return promise; + conflicts(names) { + this.conflictsWith = this.conflictsWith.concat(names); + return this; } - getUri(config) { - config = mergeConfig(this.defaults, config); - const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); - return buildURL(fullPath, config.params, config.paramsSerializer); + /** + * Specify implied option values for when this option is set and the implied options are not. + * + * The custom processing (parseArg) is not called on the implied values. + * + * @example + * program + * .addOption(new Option('--log', 'write logging information to file')) + * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); + * + * @param {object} impliedOptionValues + * @return {Option} + */ + implies(impliedOptionValues) { + let newImplied = impliedOptionValues; + if (typeof impliedOptionValues === 'string') { + // string is not documented, but easy mistake and we can do what user probably intended. + newImplied = { [impliedOptionValues]: true }; + } + this.implied = Object.assign(this.implied || {}, newImplied); + return this; } -} - -// Provide aliases for supported request methods -utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method, - url, - data: (config || {}).data - })); - }; -}); -utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ + /** + * Set environment variable to check for option value. + * + * An environment variable is only used if when processed the current option value is + * undefined, or the source of the current value is 'default' or 'config' or 'env'. + * + * @param {string} name + * @return {Option} + */ - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { - 'Content-Type': 'multipart/form-data' - } : {}, - url, - data - })); - }; + env(name) { + this.envVar = name; + return this; } - Axios.prototype[method] = generateHTTPMethod(); - - Axios.prototype[method + 'Form'] = generateHTTPMethod(true); -}); - -const Axios$1 = Axios; + /** + * Set the custom handler for processing CLI option arguments into option values. + * + * @param {Function} [fn] + * @return {Option} + */ -/** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @param {Function} executor The executor function. - * - * @returns {CancelToken} - */ -class CancelToken { - constructor(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); - } + argParser(fn) { + this.parseArg = fn; + return this; + } - let resolvePromise; + /** + * Whether the option is mandatory and must have a value after parsing. + * + * @param {boolean} [mandatory=true] + * @return {Option} + */ - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); + makeOptionMandatory(mandatory = true) { + this.mandatory = !!mandatory; + return this; + } - const token = this; + /** + * Hide option in help. + * + * @param {boolean} [hide=true] + * @return {Option} + */ - // eslint-disable-next-line func-names - this.promise.then(cancel => { - if (!token._listeners) return; + hideHelp(hide = true) { + this.hidden = !!hide; + return this; + } - let i = token._listeners.length; + /** + * @package + */ - while (i-- > 0) { - token._listeners[i](cancel); - } - token._listeners = null; - }); + _concatValue(value, previous) { + if (previous === this.defaultValue || !Array.isArray(previous)) { + return [value]; + } - // eslint-disable-next-line func-names - this.promise.then = onfulfilled => { - let _resolve; - // eslint-disable-next-line func-names - const promise = new Promise(resolve => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; + return previous.concat(value); + } - return promise; - }; + /** + * Only allow option value to be one of choices. + * + * @param {string[]} values + * @return {Option} + */ - executor(function cancel(message, config, request) { - if (token.reason) { - // Cancellation has already been requested - return; + choices(values) { + this.argChoices = values.slice(); + this.parseArg = (arg, previous) => { + if (!this.argChoices.includes(arg)) { + throw new InvalidArgumentError( + `Allowed choices are ${this.argChoices.join(', ')}.`, + ); } - - token.reason = new CanceledError(message, config, request); - resolvePromise(token.reason); - }); + if (this.variadic) { + return this._concatValue(arg, previous); + } + return arg; + }; + return this; } /** - * Throws a `CanceledError` if cancellation has been requested. + * Return option name. + * + * @return {string} */ - throwIfRequested() { - if (this.reason) { - throw this.reason; + + name() { + if (this.long) { + return this.long.replace(/^--/, ''); } + return this.short.replace(/^-/, ''); } /** - * Subscribe to the cancel signal + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {string} */ - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; - } - - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; - } + attributeName() { + return camelcase(this.name().replace(/^no-/, '')); } /** - * Unsubscribe from the cancel signal + * Check if `arg` matches the short or long flag. + * + * @param {string} arg + * @return {boolean} + * @package */ - unsubscribe(listener) { - if (!this._listeners) { - return; - } - const index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); - } + is(arg) { + return this.short === arg || this.long === arg; } - toAbortSignal() { - const controller = new AbortController(); - - const abort = (err) => { - controller.abort(err); - }; - - this.subscribe(abort); - - controller.signal.unsubscribe = () => this.unsubscribe(abort); + /** + * Return whether a boolean option. + * + * Options are one of boolean, negated, required argument, or optional argument. + * + * @return {boolean} + * @package + */ - return controller.signal; + isBoolean() { + return !this.required && !this.optional && !this.negate; } +} +/** + * This class is to make it easier to work with dual options, without changing the existing + * implementation. We support separate dual options for separate positive and negative options, + * like `--build` and `--no-build`, which share a single option value. This works nicely for some + * use cases, but is tricky for others where we want separate behaviours despite + * the single shared option value. + */ +class DualOptions { /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. + * @param {Option[]} options */ - static source() { - let cancel; - const token = new CancelToken(function executor(c) { - cancel = c; + constructor(options) { + this.positiveOptions = new Map(); + this.negativeOptions = new Map(); + this.dualOptions = new Set(); + options.forEach((option) => { + if (option.negate) { + this.negativeOptions.set(option.attributeName(), option); + } else { + this.positiveOptions.set(option.attributeName(), option); + } + }); + this.negativeOptions.forEach((value, key) => { + if (this.positiveOptions.has(key)) { + this.dualOptions.add(key); + } }); - return { - token, - cancel - }; } -} -const CancelToken$1 = CancelToken; + /** + * Did the value come from the option, and not from possible matching dual option? + * + * @param {*} value + * @param {Option} option + * @returns {boolean} + */ + valueFromOption(value, option) { + const optionKey = option.attributeName(); + if (!this.dualOptions.has(optionKey)) return true; -/** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * - * @returns {Function} - */ -function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; + // Use the value to deduce if (probably) came from the option. + const preset = this.negativeOptions.get(optionKey).presetArg; + const negativeValue = preset !== undefined ? preset : false; + return option.negate === (negativeValue === value); + } } /** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test + * Convert string from kebab-case to camelCase. * - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + * @param {string} str + * @return {string} + * @private */ -function isAxiosError(payload) { - return utils$1.isObject(payload) && (payload.isAxiosError === true); -} - -const HttpStatusCode = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - PayloadTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - UnprocessableEntity: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511, - WebServerIsDown: 521, - ConnectionTimedOut: 522, - OriginIsUnreachable: 523, - TimeoutOccurred: 524, - SslHandshakeFailed: 525, - InvalidSslCertificate: 526, -}; - -Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; -}); -const HttpStatusCode$1 = HttpStatusCode; +function camelcase(str) { + return str.split('-').reduce((str, word) => { + return str + word[0].toUpperCase() + word.slice(1); + }); +} /** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance + * Split the short and long flag out of something like '-m,--mixed ' * - * @returns {Axios} A new instance of Axios + * @private */ -function createInstance(defaultConfig) { - const context = new Axios$1(defaultConfig); - const instance = bind(Axios$1.prototype.request, context); - // Copy axios.prototype to instance - utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); +function splitOptionFlags(flags) { + let shortFlag; + let longFlag; + // Use original very loose parsing to maintain backwards compatibility for now, + // which allowed for example unintended `-sw, --short-word` [sic]. + const flagParts = flags.split(/[ |,]+/); + if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) + shortFlag = flagParts.shift(); + longFlag = flagParts.shift(); + // Add support for lone short flag without significantly changing parsing! + if (!shortFlag && /^-[^-]$/.test(longFlag)) { + shortFlag = longFlag; + longFlag = undefined; + } + return { shortFlag, longFlag }; +} + +exports.Option = Option; +exports.DualOptions = DualOptions; - // Copy context to instance - utils$1.extend(instance, context, null, {allOwnKeys: true}); - // Factory for creating new instances - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; +/***/ }), - return instance; -} +/***/ 7592: +/***/ ((__unused_webpack_module, exports) => { -// Create the default instance to be exported -const axios = createInstance(defaults$1); +const maxDistance = 3; -// Expose Axios class to allow class inheritance -axios.Axios = Axios$1; +function editDistance(a, b) { + // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance + // Calculating optimal string alignment distance, no substring is edited more than once. + // (Simple implementation.) -// Expose Cancel & CancelToken -axios.CanceledError = CanceledError; -axios.CancelToken = CancelToken$1; -axios.isCancel = isCancel; -axios.VERSION = VERSION; -axios.toFormData = toFormData; + // Quick early exit, return worst case. + if (Math.abs(a.length - b.length) > maxDistance) + return Math.max(a.length, b.length); -// Expose AxiosError class -axios.AxiosError = AxiosError; + // distance between prefix substrings of a and b + const d = []; -// alias for CanceledError for backward compatibility -axios.Cancel = axios.CanceledError; + // pure deletions turn a into empty string + for (let i = 0; i <= a.length; i++) { + d[i] = [i]; + } + // pure insertions turn empty string into b + for (let j = 0; j <= b.length; j++) { + d[0][j] = j; + } -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; + // fill matrix + for (let j = 1; j <= b.length; j++) { + for (let i = 1; i <= a.length; i++) { + let cost = 1; + if (a[i - 1] === b[j - 1]) { + cost = 0; + } else { + cost = 1; + } + d[i][j] = Math.min( + d[i - 1][j] + 1, // deletion + d[i][j - 1] + 1, // insertion + d[i - 1][j - 1] + cost, // substitution + ); + // transposition + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); + } + } + } -axios.spread = spread; + return d[a.length][b.length]; +} -// Expose isAxiosError -axios.isAxiosError = isAxiosError; +/** + * Find close matches, restricted to same number of edits. + * + * @param {string} word + * @param {string[]} candidates + * @returns {string} + */ -// Expose mergeConfig -axios.mergeConfig = mergeConfig; +function suggestSimilar(word, candidates) { + if (!candidates || candidates.length === 0) return ''; + // remove possible duplicates + candidates = Array.from(new Set(candidates)); -axios.AxiosHeaders = AxiosHeaders$1; + const searchingOptions = word.startsWith('--'); + if (searchingOptions) { + word = word.slice(2); + candidates = candidates.map((candidate) => candidate.slice(2)); + } -axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); + let similar = []; + let bestDistance = maxDistance; + const minSimilarity = 0.4; + candidates.forEach((candidate) => { + if (candidate.length <= 1) return; // no one character guesses -axios.getAdapter = adapters.getAdapter; + const distance = editDistance(word, candidate); + const length = Math.max(word.length, candidate.length); + const similarity = (length - distance) / length; + if (similarity > minSimilarity) { + if (distance < bestDistance) { + // better edit distance, throw away previous worse matches + bestDistance = distance; + similar = [candidate]; + } else if (distance === bestDistance) { + similar.push(candidate); + } + } + }); -axios.HttpStatusCode = HttpStatusCode$1; + similar.sort((a, b) => a.localeCompare(b)); + if (searchingOptions) { + similar = similar.map((candidate) => `--${candidate}`); + } -axios.default = axios; + if (similar.length > 1) { + return `\n(Did you mean one of ${similar.join(', ')}?)`; + } + if (similar.length === 1) { + return `\n(Did you mean ${similar[0]}?)`; + } + return ''; +} -module.exports = axios; -//# sourceMappingURL=axios.cjs.map +exports.suggestSimilar = suggestSimilar; /***/ }), -/***/ 46192: +/***/ 6192: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { "use strict"; @@ -157785,7 +77700,7 @@ __nccwpck_require__.d(__webpack_exports__, { }); // EXTERNAL MODULE: external "node:process" -var external_node_process_ = __nccwpck_require__(97742); +var external_node_process_ = __nccwpck_require__(7742); ;// CONCATENATED MODULE: ./node_modules/ansi-regex/index.js function ansiRegex({onlyFirst = false} = {}) { // Valid string terminator sequences are BEL, ESC\, and 0x9c @@ -158256,7 +78171,7 @@ function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) { // EXTERNAL MODULE: ./node_modules/emoji-regex/index.js -var emoji_regex = __nccwpck_require__(18212); +var emoji_regex = __nccwpck_require__(8212); ;// CONCATENATED MODULE: ./node_modules/string-width/index.js @@ -158342,7 +78257,7 @@ function stringWidth(string, options = {}) { } // EXTERNAL MODULE: ./node_modules/chalk/source/index.js + 5 modules -var source = __nccwpck_require__(77037); +var source = __nccwpck_require__(7037); ;// CONCATENATED MODULE: ./node_modules/widest-line/index.js @@ -158357,7 +78272,7 @@ function widestLine(string) { } // EXTERNAL MODULE: ./node_modules/cli-boxes/index.js -var cli_boxes = __nccwpck_require__(83733); +var cli_boxes = __nccwpck_require__(3733); ;// CONCATENATED MODULE: ./node_modules/camelcase/index.js const UPPERCASE = /[\p{Lu}]/u; const LOWERCASE = /[\p{Ll}]/u; @@ -158471,7 +78386,7 @@ function camelCase(input, options) { } // EXTERNAL MODULE: ./node_modules/ansi-align/index.js -var ansi_align = __nccwpck_require__(22225); +var ansi_align = __nccwpck_require__(2225); ;// CONCATENATED MODULE: ./node_modules/ansi-styles/index.js const ANSI_BACKGROUND_OFFSET = 10; @@ -159302,7 +79217,7 @@ function boxen(text, options) { /***/ }), -/***/ 77037: +/***/ 7037: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { "use strict"; @@ -159552,7 +79467,7 @@ const ansiStyles = assembleStyles(); /* harmony default export */ const ansi_styles = (ansiStyles); // EXTERNAL MODULE: external "node:process" -var external_node_process_ = __nccwpck_require__(97742); +var external_node_process_ = __nccwpck_require__(7742); ;// CONCATENATED MODULE: external "node:os" const external_node_os_namespaceObject = require("node:os"); ;// CONCATENATED MODULE: external "node:tty" @@ -159997,15 +79912,7 @@ const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); /***/ }), -/***/ 56569: -/***/ ((module) => { - -"use strict"; -module.exports = {"i8":"1.14.0"}; - -/***/ }), - -/***/ 70094: +/***/ 94: /***/ ((module) => { "use strict"; @@ -160013,68 +79920,12 @@ module.exports = JSON.parse('{"single":{"topLeft":"ā”Œ","top":"─","topRight":" /***/ }), -/***/ 49968: +/***/ 9968: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"name":"dotenv","version":"16.6.1","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}'); -/***/ }), - -/***/ 53765: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"application/1d-interleaved-parityfec":{"source":"iana"},"application/3gpdash-qoe-report+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/3gpp-ims+xml":{"source":"iana","compressible":true},"application/3gpphal+json":{"source":"iana","compressible":true},"application/3gpphalforms+json":{"source":"iana","compressible":true},"application/a2l":{"source":"iana"},"application/ace+cbor":{"source":"iana"},"application/activemessage":{"source":"iana"},"application/activity+json":{"source":"iana","compressible":true},"application/alto-costmap+json":{"source":"iana","compressible":true},"application/alto-costmapfilter+json":{"source":"iana","compressible":true},"application/alto-directory+json":{"source":"iana","compressible":true},"application/alto-endpointcost+json":{"source":"iana","compressible":true},"application/alto-endpointcostparams+json":{"source":"iana","compressible":true},"application/alto-endpointprop+json":{"source":"iana","compressible":true},"application/alto-endpointpropparams+json":{"source":"iana","compressible":true},"application/alto-error+json":{"source":"iana","compressible":true},"application/alto-networkmap+json":{"source":"iana","compressible":true},"application/alto-networkmapfilter+json":{"source":"iana","compressible":true},"application/alto-updatestreamcontrol+json":{"source":"iana","compressible":true},"application/alto-updatestreamparams+json":{"source":"iana","compressible":true},"application/aml":{"source":"iana"},"application/andrew-inset":{"source":"iana","extensions":["ez"]},"application/applefile":{"source":"iana"},"application/applixware":{"source":"apache","extensions":["aw"]},"application/at+jwt":{"source":"iana"},"application/atf":{"source":"iana"},"application/atfx":{"source":"iana"},"application/atom+xml":{"source":"iana","compressible":true,"extensions":["atom"]},"application/atomcat+xml":{"source":"iana","compressible":true,"extensions":["atomcat"]},"application/atomdeleted+xml":{"source":"iana","compressible":true,"extensions":["atomdeleted"]},"application/atomicmail":{"source":"iana"},"application/atomsvc+xml":{"source":"iana","compressible":true,"extensions":["atomsvc"]},"application/atsc-dwd+xml":{"source":"iana","compressible":true,"extensions":["dwd"]},"application/atsc-dynamic-event-message":{"source":"iana"},"application/atsc-held+xml":{"source":"iana","compressible":true,"extensions":["held"]},"application/atsc-rdt+json":{"source":"iana","compressible":true},"application/atsc-rsat+xml":{"source":"iana","compressible":true,"extensions":["rsat"]},"application/atxml":{"source":"iana"},"application/auth-policy+xml":{"source":"iana","compressible":true},"application/bacnet-xdd+zip":{"source":"iana","compressible":false},"application/batch-smtp":{"source":"iana"},"application/bdoc":{"compressible":false,"extensions":["bdoc"]},"application/beep+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/calendar+json":{"source":"iana","compressible":true},"application/calendar+xml":{"source":"iana","compressible":true,"extensions":["xcs"]},"application/call-completion":{"source":"iana"},"application/cals-1840":{"source":"iana"},"application/captive+json":{"source":"iana","compressible":true},"application/cbor":{"source":"iana"},"application/cbor-seq":{"source":"iana"},"application/cccex":{"source":"iana"},"application/ccmp+xml":{"source":"iana","compressible":true},"application/ccxml+xml":{"source":"iana","compressible":true,"extensions":["ccxml"]},"application/cdfx+xml":{"source":"iana","compressible":true,"extensions":["cdfx"]},"application/cdmi-capability":{"source":"iana","extensions":["cdmia"]},"application/cdmi-container":{"source":"iana","extensions":["cdmic"]},"application/cdmi-domain":{"source":"iana","extensions":["cdmid"]},"application/cdmi-object":{"source":"iana","extensions":["cdmio"]},"application/cdmi-queue":{"source":"iana","extensions":["cdmiq"]},"application/cdni":{"source":"iana"},"application/cea":{"source":"iana"},"application/cea-2018+xml":{"source":"iana","compressible":true},"application/cellml+xml":{"source":"iana","compressible":true},"application/cfw":{"source":"iana"},"application/city+json":{"source":"iana","compressible":true},"application/clr":{"source":"iana"},"application/clue+xml":{"source":"iana","compressible":true},"application/clue_info+xml":{"source":"iana","compressible":true},"application/cms":{"source":"iana"},"application/cnrp+xml":{"source":"iana","compressible":true},"application/coap-group+json":{"source":"iana","compressible":true},"application/coap-payload":{"source":"iana"},"application/commonground":{"source":"iana"},"application/conference-info+xml":{"source":"iana","compressible":true},"application/cose":{"source":"iana"},"application/cose-key":{"source":"iana"},"application/cose-key-set":{"source":"iana"},"application/cpl+xml":{"source":"iana","compressible":true,"extensions":["cpl"]},"application/csrattrs":{"source":"iana"},"application/csta+xml":{"source":"iana","compressible":true},"application/cstadata+xml":{"source":"iana","compressible":true},"application/csvm+json":{"source":"iana","compressible":true},"application/cu-seeme":{"source":"apache","extensions":["cu"]},"application/cwt":{"source":"iana"},"application/cybercash":{"source":"iana"},"application/dart":{"compressible":true},"application/dash+xml":{"source":"iana","compressible":true,"extensions":["mpd"]},"application/dash-patch+xml":{"source":"iana","compressible":true,"extensions":["mpp"]},"application/dashdelta":{"source":"iana"},"application/davmount+xml":{"source":"iana","compressible":true,"extensions":["davmount"]},"application/dca-rft":{"source":"iana"},"application/dcd":{"source":"iana"},"application/dec-dx":{"source":"iana"},"application/dialog-info+xml":{"source":"iana","compressible":true},"application/dicom":{"source":"iana"},"application/dicom+json":{"source":"iana","compressible":true},"application/dicom+xml":{"source":"iana","compressible":true},"application/dii":{"source":"iana"},"application/dit":{"source":"iana"},"application/dns":{"source":"iana"},"application/dns+json":{"source":"iana","compressible":true},"application/dns-message":{"source":"iana"},"application/docbook+xml":{"source":"apache","compressible":true,"extensions":["dbk"]},"application/dots+cbor":{"source":"iana"},"application/dskpp+xml":{"source":"iana","compressible":true},"application/dssc+der":{"source":"iana","extensions":["dssc"]},"application/dssc+xml":{"source":"iana","compressible":true,"extensions":["xdssc"]},"application/dvcs":{"source":"iana"},"application/ecmascript":{"source":"iana","compressible":true,"extensions":["es","ecma"]},"application/edi-consent":{"source":"iana"},"application/edi-x12":{"source":"iana","compressible":false},"application/edifact":{"source":"iana","compressible":false},"application/efi":{"source":"iana"},"application/elm+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/elm+xml":{"source":"iana","compressible":true},"application/emergencycalldata.cap+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/emergencycalldata.comment+xml":{"source":"iana","compressible":true},"application/emergencycalldata.control+xml":{"source":"iana","compressible":true},"application/emergencycalldata.deviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.ecall.msd":{"source":"iana"},"application/emergencycalldata.providerinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.serviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.subscriberinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.veds+xml":{"source":"iana","compressible":true},"application/emma+xml":{"source":"iana","compressible":true,"extensions":["emma"]},"application/emotionml+xml":{"source":"iana","compressible":true,"extensions":["emotionml"]},"application/encaprtp":{"source":"iana"},"application/epp+xml":{"source":"iana","compressible":true},"application/epub+zip":{"source":"iana","compressible":false,"extensions":["epub"]},"application/eshop":{"source":"iana"},"application/exi":{"source":"iana","extensions":["exi"]},"application/expect-ct-report+json":{"source":"iana","compressible":true},"application/express":{"source":"iana","extensions":["exp"]},"application/fastinfoset":{"source":"iana"},"application/fastsoap":{"source":"iana"},"application/fdt+xml":{"source":"iana","compressible":true,"extensions":["fdt"]},"application/fhir+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/fhir+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/fido.trusted-apps+json":{"compressible":true},"application/fits":{"source":"iana"},"application/flexfec":{"source":"iana"},"application/font-sfnt":{"source":"iana"},"application/font-tdpfr":{"source":"iana","extensions":["pfr"]},"application/font-woff":{"source":"iana","compressible":false},"application/framework-attributes+xml":{"source":"iana","compressible":true},"application/geo+json":{"source":"iana","compressible":true,"extensions":["geojson"]},"application/geo+json-seq":{"source":"iana"},"application/geopackage+sqlite3":{"source":"iana"},"application/geoxacml+xml":{"source":"iana","compressible":true},"application/gltf-buffer":{"source":"iana"},"application/gml+xml":{"source":"iana","compressible":true,"extensions":["gml"]},"application/gpx+xml":{"source":"apache","compressible":true,"extensions":["gpx"]},"application/gxf":{"source":"apache","extensions":["gxf"]},"application/gzip":{"source":"iana","compressible":false,"extensions":["gz"]},"application/h224":{"source":"iana"},"application/held+xml":{"source":"iana","compressible":true},"application/hjson":{"extensions":["hjson"]},"application/http":{"source":"iana"},"application/hyperstudio":{"source":"iana","extensions":["stk"]},"application/ibe-key-request+xml":{"source":"iana","compressible":true},"application/ibe-pkg-reply+xml":{"source":"iana","compressible":true},"application/ibe-pp-data":{"source":"iana"},"application/iges":{"source":"iana"},"application/im-iscomposing+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/index":{"source":"iana"},"application/index.cmd":{"source":"iana"},"application/index.obj":{"source":"iana"},"application/index.response":{"source":"iana"},"application/index.vnd":{"source":"iana"},"application/inkml+xml":{"source":"iana","compressible":true,"extensions":["ink","inkml"]},"application/iotp":{"source":"iana"},"application/ipfix":{"source":"iana","extensions":["ipfix"]},"application/ipp":{"source":"iana"},"application/isup":{"source":"iana"},"application/its+xml":{"source":"iana","compressible":true,"extensions":["its"]},"application/java-archive":{"source":"apache","compressible":false,"extensions":["jar","war","ear"]},"application/java-serialized-object":{"source":"apache","compressible":false,"extensions":["ser"]},"application/java-vm":{"source":"apache","compressible":false,"extensions":["class"]},"application/javascript":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["js","mjs"]},"application/jf2feed+json":{"source":"iana","compressible":true},"application/jose":{"source":"iana"},"application/jose+json":{"source":"iana","compressible":true},"application/jrd+json":{"source":"iana","compressible":true},"application/jscalendar+json":{"source":"iana","compressible":true},"application/json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["json","map"]},"application/json-patch+json":{"source":"iana","compressible":true},"application/json-seq":{"source":"iana"},"application/json5":{"extensions":["json5"]},"application/jsonml+json":{"source":"apache","compressible":true,"extensions":["jsonml"]},"application/jwk+json":{"source":"iana","compressible":true},"application/jwk-set+json":{"source":"iana","compressible":true},"application/jwt":{"source":"iana"},"application/kpml-request+xml":{"source":"iana","compressible":true},"application/kpml-response+xml":{"source":"iana","compressible":true},"application/ld+json":{"source":"iana","compressible":true,"extensions":["jsonld"]},"application/lgr+xml":{"source":"iana","compressible":true,"extensions":["lgr"]},"application/link-format":{"source":"iana"},"application/load-control+xml":{"source":"iana","compressible":true},"application/lost+xml":{"source":"iana","compressible":true,"extensions":["lostxml"]},"application/lostsync+xml":{"source":"iana","compressible":true},"application/lpf+zip":{"source":"iana","compressible":false},"application/lxf":{"source":"iana"},"application/mac-binhex40":{"source":"iana","extensions":["hqx"]},"application/mac-compactpro":{"source":"apache","extensions":["cpt"]},"application/macwriteii":{"source":"iana"},"application/mads+xml":{"source":"iana","compressible":true,"extensions":["mads"]},"application/manifest+json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["webmanifest"]},"application/marc":{"source":"iana","extensions":["mrc"]},"application/marcxml+xml":{"source":"iana","compressible":true,"extensions":["mrcx"]},"application/mathematica":{"source":"iana","extensions":["ma","nb","mb"]},"application/mathml+xml":{"source":"iana","compressible":true,"extensions":["mathml"]},"application/mathml-content+xml":{"source":"iana","compressible":true},"application/mathml-presentation+xml":{"source":"iana","compressible":true},"application/mbms-associated-procedure-description+xml":{"source":"iana","compressible":true},"application/mbms-deregister+xml":{"source":"iana","compressible":true},"application/mbms-envelope+xml":{"source":"iana","compressible":true},"application/mbms-msk+xml":{"source":"iana","compressible":true},"application/mbms-msk-response+xml":{"source":"iana","compressible":true},"application/mbms-protection-description+xml":{"source":"iana","compressible":true},"application/mbms-reception-report+xml":{"source":"iana","compressible":true},"application/mbms-register+xml":{"source":"iana","compressible":true},"application/mbms-register-response+xml":{"source":"iana","compressible":true},"application/mbms-schedule+xml":{"source":"iana","compressible":true},"application/mbms-user-service-description+xml":{"source":"iana","compressible":true},"application/mbox":{"source":"iana","extensions":["mbox"]},"application/media-policy-dataset+xml":{"source":"iana","compressible":true,"extensions":["mpf"]},"application/media_control+xml":{"source":"iana","compressible":true},"application/mediaservercontrol+xml":{"source":"iana","compressible":true,"extensions":["mscml"]},"application/merge-patch+json":{"source":"iana","compressible":true},"application/metalink+xml":{"source":"apache","compressible":true,"extensions":["metalink"]},"application/metalink4+xml":{"source":"iana","compressible":true,"extensions":["meta4"]},"application/mets+xml":{"source":"iana","compressible":true,"extensions":["mets"]},"application/mf4":{"source":"iana"},"application/mikey":{"source":"iana"},"application/mipc":{"source":"iana"},"application/missing-blocks+cbor-seq":{"source":"iana"},"application/mmt-aei+xml":{"source":"iana","compressible":true,"extensions":["maei"]},"application/mmt-usd+xml":{"source":"iana","compressible":true,"extensions":["musd"]},"application/mods+xml":{"source":"iana","compressible":true,"extensions":["mods"]},"application/moss-keys":{"source":"iana"},"application/moss-signature":{"source":"iana"},"application/mosskey-data":{"source":"iana"},"application/mosskey-request":{"source":"iana"},"application/mp21":{"source":"iana","extensions":["m21","mp21"]},"application/mp4":{"source":"iana","extensions":["mp4s","m4p"]},"application/mpeg4-generic":{"source":"iana"},"application/mpeg4-iod":{"source":"iana"},"application/mpeg4-iod-xmt":{"source":"iana"},"application/mrb-consumer+xml":{"source":"iana","compressible":true},"application/mrb-publish+xml":{"source":"iana","compressible":true},"application/msc-ivr+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msc-mixer+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msword":{"source":"iana","compressible":false,"extensions":["doc","dot"]},"application/mud+json":{"source":"iana","compressible":true},"application/multipart-core":{"source":"iana"},"application/mxf":{"source":"iana","extensions":["mxf"]},"application/n-quads":{"source":"iana","extensions":["nq"]},"application/n-triples":{"source":"iana","extensions":["nt"]},"application/nasdata":{"source":"iana"},"application/news-checkgroups":{"source":"iana","charset":"US-ASCII"},"application/news-groupinfo":{"source":"iana","charset":"US-ASCII"},"application/news-transmission":{"source":"iana"},"application/nlsml+xml":{"source":"iana","compressible":true},"application/node":{"source":"iana","extensions":["cjs"]},"application/nss":{"source":"iana"},"application/oauth-authz-req+jwt":{"source":"iana"},"application/oblivious-dns-message":{"source":"iana"},"application/ocsp-request":{"source":"iana"},"application/ocsp-response":{"source":"iana"},"application/octet-stream":{"source":"iana","compressible":false,"extensions":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{"source":"iana","extensions":["oda"]},"application/odm+xml":{"source":"iana","compressible":true},"application/odx":{"source":"iana"},"application/oebps-package+xml":{"source":"iana","compressible":true,"extensions":["opf"]},"application/ogg":{"source":"iana","compressible":false,"extensions":["ogx"]},"application/omdoc+xml":{"source":"apache","compressible":true,"extensions":["omdoc"]},"application/onenote":{"source":"apache","extensions":["onetoc","onetoc2","onetmp","onepkg"]},"application/opc-nodeset+xml":{"source":"iana","compressible":true},"application/oscore":{"source":"iana"},"application/oxps":{"source":"iana","extensions":["oxps"]},"application/p21":{"source":"iana"},"application/p21+zip":{"source":"iana","compressible":false},"application/p2p-overlay+xml":{"source":"iana","compressible":true,"extensions":["relo"]},"application/parityfec":{"source":"iana"},"application/passport":{"source":"iana"},"application/patch-ops-error+xml":{"source":"iana","compressible":true,"extensions":["xer"]},"application/pdf":{"source":"iana","compressible":false,"extensions":["pdf"]},"application/pdx":{"source":"iana"},"application/pem-certificate-chain":{"source":"iana"},"application/pgp-encrypted":{"source":"iana","compressible":false,"extensions":["pgp"]},"application/pgp-keys":{"source":"iana","extensions":["asc"]},"application/pgp-signature":{"source":"iana","extensions":["asc","sig"]},"application/pics-rules":{"source":"apache","extensions":["prf"]},"application/pidf+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pidf-diff+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pkcs10":{"source":"iana","extensions":["p10"]},"application/pkcs12":{"source":"iana"},"application/pkcs7-mime":{"source":"iana","extensions":["p7m","p7c"]},"application/pkcs7-signature":{"source":"iana","extensions":["p7s"]},"application/pkcs8":{"source":"iana","extensions":["p8"]},"application/pkcs8-encrypted":{"source":"iana"},"application/pkix-attr-cert":{"source":"iana","extensions":["ac"]},"application/pkix-cert":{"source":"iana","extensions":["cer"]},"application/pkix-crl":{"source":"iana","extensions":["crl"]},"application/pkix-pkipath":{"source":"iana","extensions":["pkipath"]},"application/pkixcmp":{"source":"iana","extensions":["pki"]},"application/pls+xml":{"source":"iana","compressible":true,"extensions":["pls"]},"application/poc-settings+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/postscript":{"source":"iana","compressible":true,"extensions":["ai","eps","ps"]},"application/ppsp-tracker+json":{"source":"iana","compressible":true},"application/problem+json":{"source":"iana","compressible":true},"application/problem+xml":{"source":"iana","compressible":true},"application/provenance+xml":{"source":"iana","compressible":true,"extensions":["provx"]},"application/prs.alvestrand.titrax-sheet":{"source":"iana"},"application/prs.cww":{"source":"iana","extensions":["cww"]},"application/prs.cyn":{"source":"iana","charset":"7-BIT"},"application/prs.hpub+zip":{"source":"iana","compressible":false},"application/prs.nprend":{"source":"iana"},"application/prs.plucker":{"source":"iana"},"application/prs.rdf-xml-crypt":{"source":"iana"},"application/prs.xsf+xml":{"source":"iana","compressible":true},"application/pskc+xml":{"source":"iana","compressible":true,"extensions":["pskcxml"]},"application/pvd+json":{"source":"iana","compressible":true},"application/qsig":{"source":"iana"},"application/raml+yaml":{"compressible":true,"extensions":["raml"]},"application/raptorfec":{"source":"iana"},"application/rdap+json":{"source":"iana","compressible":true},"application/rdf+xml":{"source":"iana","compressible":true,"extensions":["rdf","owl"]},"application/reginfo+xml":{"source":"iana","compressible":true,"extensions":["rif"]},"application/relax-ng-compact-syntax":{"source":"iana","extensions":["rnc"]},"application/remote-printing":{"source":"iana"},"application/reputon+json":{"source":"iana","compressible":true},"application/resource-lists+xml":{"source":"iana","compressible":true,"extensions":["rl"]},"application/resource-lists-diff+xml":{"source":"iana","compressible":true,"extensions":["rld"]},"application/rfc+xml":{"source":"iana","compressible":true},"application/riscos":{"source":"iana"},"application/rlmi+xml":{"source":"iana","compressible":true},"application/rls-services+xml":{"source":"iana","compressible":true,"extensions":["rs"]},"application/route-apd+xml":{"source":"iana","compressible":true,"extensions":["rapd"]},"application/route-s-tsid+xml":{"source":"iana","compressible":true,"extensions":["sls"]},"application/route-usd+xml":{"source":"iana","compressible":true,"extensions":["rusd"]},"application/rpki-ghostbusters":{"source":"iana","extensions":["gbr"]},"application/rpki-manifest":{"source":"iana","extensions":["mft"]},"application/rpki-publication":{"source":"iana"},"application/rpki-roa":{"source":"iana","extensions":["roa"]},"application/rpki-updown":{"source":"iana"},"application/rsd+xml":{"source":"apache","compressible":true,"extensions":["rsd"]},"application/rss+xml":{"source":"apache","compressible":true,"extensions":["rss"]},"application/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"application/rtploopback":{"source":"iana"},"application/rtx":{"source":"iana"},"application/samlassertion+xml":{"source":"iana","compressible":true},"application/samlmetadata+xml":{"source":"iana","compressible":true},"application/sarif+json":{"source":"iana","compressible":true},"application/sarif-external-properties+json":{"source":"iana","compressible":true},"application/sbe":{"source":"iana"},"application/sbml+xml":{"source":"iana","compressible":true,"extensions":["sbml"]},"application/scaip+xml":{"source":"iana","compressible":true},"application/scim+json":{"source":"iana","compressible":true},"application/scvp-cv-request":{"source":"iana","extensions":["scq"]},"application/scvp-cv-response":{"source":"iana","extensions":["scs"]},"application/scvp-vp-request":{"source":"iana","extensions":["spq"]},"application/scvp-vp-response":{"source":"iana","extensions":["spp"]},"application/sdp":{"source":"iana","extensions":["sdp"]},"application/secevent+jwt":{"source":"iana"},"application/senml+cbor":{"source":"iana"},"application/senml+json":{"source":"iana","compressible":true},"application/senml+xml":{"source":"iana","compressible":true,"extensions":["senmlx"]},"application/senml-etch+cbor":{"source":"iana"},"application/senml-etch+json":{"source":"iana","compressible":true},"application/senml-exi":{"source":"iana"},"application/sensml+cbor":{"source":"iana"},"application/sensml+json":{"source":"iana","compressible":true},"application/sensml+xml":{"source":"iana","compressible":true,"extensions":["sensmlx"]},"application/sensml-exi":{"source":"iana"},"application/sep+xml":{"source":"iana","compressible":true},"application/sep-exi":{"source":"iana"},"application/session-info":{"source":"iana"},"application/set-payment":{"source":"iana"},"application/set-payment-initiation":{"source":"iana","extensions":["setpay"]},"application/set-registration":{"source":"iana"},"application/set-registration-initiation":{"source":"iana","extensions":["setreg"]},"application/sgml":{"source":"iana"},"application/sgml-open-catalog":{"source":"iana"},"application/shf+xml":{"source":"iana","compressible":true,"extensions":["shf"]},"application/sieve":{"source":"iana","extensions":["siv","sieve"]},"application/simple-filter+xml":{"source":"iana","compressible":true},"application/simple-message-summary":{"source":"iana"},"application/simplesymbolcontainer":{"source":"iana"},"application/sipc":{"source":"iana"},"application/slate":{"source":"iana"},"application/smil":{"source":"iana"},"application/smil+xml":{"source":"iana","compressible":true,"extensions":["smi","smil"]},"application/smpte336m":{"source":"iana"},"application/soap+fastinfoset":{"source":"iana"},"application/soap+xml":{"source":"iana","compressible":true},"application/sparql-query":{"source":"iana","extensions":["rq"]},"application/sparql-results+xml":{"source":"iana","compressible":true,"extensions":["srx"]},"application/spdx+json":{"source":"iana","compressible":true},"application/spirits-event+xml":{"source":"iana","compressible":true},"application/sql":{"source":"iana"},"application/srgs":{"source":"iana","extensions":["gram"]},"application/srgs+xml":{"source":"iana","compressible":true,"extensions":["grxml"]},"application/sru+xml":{"source":"iana","compressible":true,"extensions":["sru"]},"application/ssdl+xml":{"source":"apache","compressible":true,"extensions":["ssdl"]},"application/ssml+xml":{"source":"iana","compressible":true,"extensions":["ssml"]},"application/stix+json":{"source":"iana","compressible":true},"application/swid+xml":{"source":"iana","compressible":true,"extensions":["swidtag"]},"application/tamp-apex-update":{"source":"iana"},"application/tamp-apex-update-confirm":{"source":"iana"},"application/tamp-community-update":{"source":"iana"},"application/tamp-community-update-confirm":{"source":"iana"},"application/tamp-error":{"source":"iana"},"application/tamp-sequence-adjust":{"source":"iana"},"application/tamp-sequence-adjust-confirm":{"source":"iana"},"application/tamp-status-query":{"source":"iana"},"application/tamp-status-response":{"source":"iana"},"application/tamp-update":{"source":"iana"},"application/tamp-update-confirm":{"source":"iana"},"application/tar":{"compressible":true},"application/taxii+json":{"source":"iana","compressible":true},"application/td+json":{"source":"iana","compressible":true},"application/tei+xml":{"source":"iana","compressible":true,"extensions":["tei","teicorpus"]},"application/tetra_isi":{"source":"iana"},"application/thraud+xml":{"source":"iana","compressible":true,"extensions":["tfi"]},"application/timestamp-query":{"source":"iana"},"application/timestamp-reply":{"source":"iana"},"application/timestamped-data":{"source":"iana","extensions":["tsd"]},"application/tlsrpt+gzip":{"source":"iana"},"application/tlsrpt+json":{"source":"iana","compressible":true},"application/tnauthlist":{"source":"iana"},"application/token-introspection+jwt":{"source":"iana"},"application/toml":{"compressible":true,"extensions":["toml"]},"application/trickle-ice-sdpfrag":{"source":"iana"},"application/trig":{"source":"iana","extensions":["trig"]},"application/ttml+xml":{"source":"iana","compressible":true,"extensions":["ttml"]},"application/tve-trigger":{"source":"iana"},"application/tzif":{"source":"iana"},"application/tzif-leap":{"source":"iana"},"application/ubjson":{"compressible":false,"extensions":["ubj"]},"application/ulpfec":{"source":"iana"},"application/urc-grpsheet+xml":{"source":"iana","compressible":true},"application/urc-ressheet+xml":{"source":"iana","compressible":true,"extensions":["rsheet"]},"application/urc-targetdesc+xml":{"source":"iana","compressible":true,"extensions":["td"]},"application/urc-uisocketdesc+xml":{"source":"iana","compressible":true},"application/vcard+json":{"source":"iana","compressible":true},"application/vcard+xml":{"source":"iana","compressible":true},"application/vemmi":{"source":"iana"},"application/vividence.scriptfile":{"source":"apache"},"application/vnd.1000minds.decision-model+xml":{"source":"iana","compressible":true,"extensions":["1km"]},"application/vnd.3gpp-prose+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-prose-pc3ch+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-v2x-local-service-information":{"source":"iana"},"application/vnd.3gpp.5gnas":{"source":"iana"},"application/vnd.3gpp.access-transfer-events+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.bsf+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gmop+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gtpc":{"source":"iana"},"application/vnd.3gpp.interworking-data":{"source":"iana"},"application/vnd.3gpp.lpp":{"source":"iana"},"application/vnd.3gpp.mc-signalling-ear":{"source":"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-payload":{"source":"iana"},"application/vnd.3gpp.mcdata-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-signalling":{"source":"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-floor-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-signed+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-init-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-transmission-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mid-call+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ngap":{"source":"iana"},"application/vnd.3gpp.pfcp":{"source":"iana"},"application/vnd.3gpp.pic-bw-large":{"source":"iana","extensions":["plb"]},"application/vnd.3gpp.pic-bw-small":{"source":"iana","extensions":["psb"]},"application/vnd.3gpp.pic-bw-var":{"source":"iana","extensions":["pvb"]},"application/vnd.3gpp.s1ap":{"source":"iana"},"application/vnd.3gpp.sms":{"source":"iana"},"application/vnd.3gpp.sms+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-ext+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.state-and-event-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ussd+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.bcmcsinfo+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.sms":{"source":"iana"},"application/vnd.3gpp2.tcap":{"source":"iana","extensions":["tcap"]},"application/vnd.3lightssoftware.imagescal":{"source":"iana"},"application/vnd.3m.post-it-notes":{"source":"iana","extensions":["pwn"]},"application/vnd.accpac.simply.aso":{"source":"iana","extensions":["aso"]},"application/vnd.accpac.simply.imp":{"source":"iana","extensions":["imp"]},"application/vnd.acucobol":{"source":"iana","extensions":["acu"]},"application/vnd.acucorp":{"source":"iana","extensions":["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{"source":"apache","compressible":false,"extensions":["air"]},"application/vnd.adobe.flash.movie":{"source":"iana"},"application/vnd.adobe.formscentral.fcdt":{"source":"iana","extensions":["fcdt"]},"application/vnd.adobe.fxp":{"source":"iana","extensions":["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{"source":"iana"},"application/vnd.adobe.xdp+xml":{"source":"iana","compressible":true,"extensions":["xdp"]},"application/vnd.adobe.xfdf":{"source":"iana","extensions":["xfdf"]},"application/vnd.aether.imp":{"source":"iana"},"application/vnd.afpc.afplinedata":{"source":"iana"},"application/vnd.afpc.afplinedata-pagedef":{"source":"iana"},"application/vnd.afpc.cmoca-cmresource":{"source":"iana"},"application/vnd.afpc.foca-charset":{"source":"iana"},"application/vnd.afpc.foca-codedfont":{"source":"iana"},"application/vnd.afpc.foca-codepage":{"source":"iana"},"application/vnd.afpc.modca":{"source":"iana"},"application/vnd.afpc.modca-cmtable":{"source":"iana"},"application/vnd.afpc.modca-formdef":{"source":"iana"},"application/vnd.afpc.modca-mediummap":{"source":"iana"},"application/vnd.afpc.modca-objectcontainer":{"source":"iana"},"application/vnd.afpc.modca-overlay":{"source":"iana"},"application/vnd.afpc.modca-pagesegment":{"source":"iana"},"application/vnd.age":{"source":"iana","extensions":["age"]},"application/vnd.ah-barcode":{"source":"iana"},"application/vnd.ahead.space":{"source":"iana","extensions":["ahead"]},"application/vnd.airzip.filesecure.azf":{"source":"iana","extensions":["azf"]},"application/vnd.airzip.filesecure.azs":{"source":"iana","extensions":["azs"]},"application/vnd.amadeus+json":{"source":"iana","compressible":true},"application/vnd.amazon.ebook":{"source":"apache","extensions":["azw"]},"application/vnd.amazon.mobi8-ebook":{"source":"iana"},"application/vnd.americandynamics.acc":{"source":"iana","extensions":["acc"]},"application/vnd.amiga.ami":{"source":"iana","extensions":["ami"]},"application/vnd.amundsen.maze+xml":{"source":"iana","compressible":true},"application/vnd.android.ota":{"source":"iana"},"application/vnd.android.package-archive":{"source":"apache","compressible":false,"extensions":["apk"]},"application/vnd.anki":{"source":"iana"},"application/vnd.anser-web-certificate-issue-initiation":{"source":"iana","extensions":["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{"source":"apache","extensions":["fti"]},"application/vnd.antix.game-component":{"source":"iana","extensions":["atx"]},"application/vnd.apache.arrow.file":{"source":"iana"},"application/vnd.apache.arrow.stream":{"source":"iana"},"application/vnd.apache.thrift.binary":{"source":"iana"},"application/vnd.apache.thrift.compact":{"source":"iana"},"application/vnd.apache.thrift.json":{"source":"iana"},"application/vnd.api+json":{"source":"iana","compressible":true},"application/vnd.aplextor.warrp+json":{"source":"iana","compressible":true},"application/vnd.apothekende.reservation+json":{"source":"iana","compressible":true},"application/vnd.apple.installer+xml":{"source":"iana","compressible":true,"extensions":["mpkg"]},"application/vnd.apple.keynote":{"source":"iana","extensions":["key"]},"application/vnd.apple.mpegurl":{"source":"iana","extensions":["m3u8"]},"application/vnd.apple.numbers":{"source":"iana","extensions":["numbers"]},"application/vnd.apple.pages":{"source":"iana","extensions":["pages"]},"application/vnd.apple.pkpass":{"compressible":false,"extensions":["pkpass"]},"application/vnd.arastra.swi":{"source":"iana"},"application/vnd.aristanetworks.swi":{"source":"iana","extensions":["swi"]},"application/vnd.artisan+json":{"source":"iana","compressible":true},"application/vnd.artsquare":{"source":"iana"},"application/vnd.astraea-software.iota":{"source":"iana","extensions":["iota"]},"application/vnd.audiograph":{"source":"iana","extensions":["aep"]},"application/vnd.autopackage":{"source":"iana"},"application/vnd.avalon+json":{"source":"iana","compressible":true},"application/vnd.avistar+xml":{"source":"iana","compressible":true},"application/vnd.balsamiq.bmml+xml":{"source":"iana","compressible":true,"extensions":["bmml"]},"application/vnd.balsamiq.bmpr":{"source":"iana"},"application/vnd.banana-accounting":{"source":"iana"},"application/vnd.bbf.usp.error":{"source":"iana"},"application/vnd.bbf.usp.msg":{"source":"iana"},"application/vnd.bbf.usp.msg+json":{"source":"iana","compressible":true},"application/vnd.bekitzur-stech+json":{"source":"iana","compressible":true},"application/vnd.bint.med-content":{"source":"iana"},"application/vnd.biopax.rdf+xml":{"source":"iana","compressible":true},"application/vnd.blink-idb-value-wrapper":{"source":"iana"},"application/vnd.blueice.multipass":{"source":"iana","extensions":["mpm"]},"application/vnd.bluetooth.ep.oob":{"source":"iana"},"application/vnd.bluetooth.le.oob":{"source":"iana"},"application/vnd.bmi":{"source":"iana","extensions":["bmi"]},"application/vnd.bpf":{"source":"iana"},"application/vnd.bpf3":{"source":"iana"},"application/vnd.businessobjects":{"source":"iana","extensions":["rep"]},"application/vnd.byu.uapi+json":{"source":"iana","compressible":true},"application/vnd.cab-jscript":{"source":"iana"},"application/vnd.canon-cpdl":{"source":"iana"},"application/vnd.canon-lips":{"source":"iana"},"application/vnd.capasystems-pg+json":{"source":"iana","compressible":true},"application/vnd.cendio.thinlinc.clientconf":{"source":"iana"},"application/vnd.century-systems.tcp_stream":{"source":"iana"},"application/vnd.chemdraw+xml":{"source":"iana","compressible":true,"extensions":["cdxml"]},"application/vnd.chess-pgn":{"source":"iana"},"application/vnd.chipnuts.karaoke-mmd":{"source":"iana","extensions":["mmd"]},"application/vnd.ciedi":{"source":"iana"},"application/vnd.cinderella":{"source":"iana","extensions":["cdy"]},"application/vnd.cirpack.isdn-ext":{"source":"iana"},"application/vnd.citationstyles.style+xml":{"source":"iana","compressible":true,"extensions":["csl"]},"application/vnd.claymore":{"source":"iana","extensions":["cla"]},"application/vnd.cloanto.rp9":{"source":"iana","extensions":["rp9"]},"application/vnd.clonk.c4group":{"source":"iana","extensions":["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{"source":"iana","extensions":["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{"source":"iana","extensions":["c11amz"]},"application/vnd.coffeescript":{"source":"iana"},"application/vnd.collabio.xodocuments.document":{"source":"iana"},"application/vnd.collabio.xodocuments.document-template":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation-template":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{"source":"iana"},"application/vnd.collection+json":{"source":"iana","compressible":true},"application/vnd.collection.doc+json":{"source":"iana","compressible":true},"application/vnd.collection.next+json":{"source":"iana","compressible":true},"application/vnd.comicbook+zip":{"source":"iana","compressible":false},"application/vnd.comicbook-rar":{"source":"iana"},"application/vnd.commerce-battelle":{"source":"iana"},"application/vnd.commonspace":{"source":"iana","extensions":["csp"]},"application/vnd.contact.cmsg":{"source":"iana","extensions":["cdbcmsg"]},"application/vnd.coreos.ignition+json":{"source":"iana","compressible":true},"application/vnd.cosmocaller":{"source":"iana","extensions":["cmc"]},"application/vnd.crick.clicker":{"source":"iana","extensions":["clkx"]},"application/vnd.crick.clicker.keyboard":{"source":"iana","extensions":["clkk"]},"application/vnd.crick.clicker.palette":{"source":"iana","extensions":["clkp"]},"application/vnd.crick.clicker.template":{"source":"iana","extensions":["clkt"]},"application/vnd.crick.clicker.wordbank":{"source":"iana","extensions":["clkw"]},"application/vnd.criticaltools.wbs+xml":{"source":"iana","compressible":true,"extensions":["wbs"]},"application/vnd.cryptii.pipe+json":{"source":"iana","compressible":true},"application/vnd.crypto-shade-file":{"source":"iana"},"application/vnd.cryptomator.encrypted":{"source":"iana"},"application/vnd.cryptomator.vault":{"source":"iana"},"application/vnd.ctc-posml":{"source":"iana","extensions":["pml"]},"application/vnd.ctct.ws+xml":{"source":"iana","compressible":true},"application/vnd.cups-pdf":{"source":"iana"},"application/vnd.cups-postscript":{"source":"iana"},"application/vnd.cups-ppd":{"source":"iana","extensions":["ppd"]},"application/vnd.cups-raster":{"source":"iana"},"application/vnd.cups-raw":{"source":"iana"},"application/vnd.curl":{"source":"iana"},"application/vnd.curl.car":{"source":"apache","extensions":["car"]},"application/vnd.curl.pcurl":{"source":"apache","extensions":["pcurl"]},"application/vnd.cyan.dean.root+xml":{"source":"iana","compressible":true},"application/vnd.cybank":{"source":"iana"},"application/vnd.cyclonedx+json":{"source":"iana","compressible":true},"application/vnd.cyclonedx+xml":{"source":"iana","compressible":true},"application/vnd.d2l.coursepackage1p0+zip":{"source":"iana","compressible":false},"application/vnd.d3m-dataset":{"source":"iana"},"application/vnd.d3m-problem":{"source":"iana"},"application/vnd.dart":{"source":"iana","compressible":true,"extensions":["dart"]},"application/vnd.data-vision.rdz":{"source":"iana","extensions":["rdz"]},"application/vnd.datapackage+json":{"source":"iana","compressible":true},"application/vnd.dataresource+json":{"source":"iana","compressible":true},"application/vnd.dbf":{"source":"iana","extensions":["dbf"]},"application/vnd.debian.binary-package":{"source":"iana"},"application/vnd.dece.data":{"source":"iana","extensions":["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{"source":"iana","compressible":true,"extensions":["uvt","uvvt"]},"application/vnd.dece.unspecified":{"source":"iana","extensions":["uvx","uvvx"]},"application/vnd.dece.zip":{"source":"iana","extensions":["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{"source":"iana","extensions":["fe_launch"]},"application/vnd.desmume.movie":{"source":"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{"source":"iana"},"application/vnd.dm.delegation+xml":{"source":"iana","compressible":true},"application/vnd.dna":{"source":"iana","extensions":["dna"]},"application/vnd.document+json":{"source":"iana","compressible":true},"application/vnd.dolby.mlp":{"source":"apache","extensions":["mlp"]},"application/vnd.dolby.mobile.1":{"source":"iana"},"application/vnd.dolby.mobile.2":{"source":"iana"},"application/vnd.doremir.scorecloud-binary-document":{"source":"iana"},"application/vnd.dpgraph":{"source":"iana","extensions":["dpg"]},"application/vnd.dreamfactory":{"source":"iana","extensions":["dfac"]},"application/vnd.drive+json":{"source":"iana","compressible":true},"application/vnd.ds-keypoint":{"source":"apache","extensions":["kpxx"]},"application/vnd.dtg.local":{"source":"iana"},"application/vnd.dtg.local.flash":{"source":"iana"},"application/vnd.dtg.local.html":{"source":"iana"},"application/vnd.dvb.ait":{"source":"iana","extensions":["ait"]},"application/vnd.dvb.dvbisl+xml":{"source":"iana","compressible":true},"application/vnd.dvb.dvbj":{"source":"iana"},"application/vnd.dvb.esgcontainer":{"source":"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess2":{"source":"iana"},"application/vnd.dvb.ipdcesgpdd":{"source":"iana"},"application/vnd.dvb.ipdcroaming":{"source":"iana"},"application/vnd.dvb.iptv.alfec-base":{"source":"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{"source":"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-container+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-generic+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-msglist+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-request+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-response+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-init+xml":{"source":"iana","compressible":true},"application/vnd.dvb.pfr":{"source":"iana"},"application/vnd.dvb.service":{"source":"iana","extensions":["svc"]},"application/vnd.dxr":{"source":"iana"},"application/vnd.dynageo":{"source":"iana","extensions":["geo"]},"application/vnd.dzr":{"source":"iana"},"application/vnd.easykaraoke.cdgdownload":{"source":"iana"},"application/vnd.ecdis-update":{"source":"iana"},"application/vnd.ecip.rlp":{"source":"iana"},"application/vnd.eclipse.ditto+json":{"source":"iana","compressible":true},"application/vnd.ecowin.chart":{"source":"iana","extensions":["mag"]},"application/vnd.ecowin.filerequest":{"source":"iana"},"application/vnd.ecowin.fileupdate":{"source":"iana"},"application/vnd.ecowin.series":{"source":"iana"},"application/vnd.ecowin.seriesrequest":{"source":"iana"},"application/vnd.ecowin.seriesupdate":{"source":"iana"},"application/vnd.efi.img":{"source":"iana"},"application/vnd.efi.iso":{"source":"iana"},"application/vnd.emclient.accessrequest+xml":{"source":"iana","compressible":true},"application/vnd.enliven":{"source":"iana","extensions":["nml"]},"application/vnd.enphase.envoy":{"source":"iana"},"application/vnd.eprints.data+xml":{"source":"iana","compressible":true},"application/vnd.epson.esf":{"source":"iana","extensions":["esf"]},"application/vnd.epson.msf":{"source":"iana","extensions":["msf"]},"application/vnd.epson.quickanime":{"source":"iana","extensions":["qam"]},"application/vnd.epson.salt":{"source":"iana","extensions":["slt"]},"application/vnd.epson.ssf":{"source":"iana","extensions":["ssf"]},"application/vnd.ericsson.quickcall":{"source":"iana"},"application/vnd.espass-espass+zip":{"source":"iana","compressible":false},"application/vnd.eszigno3+xml":{"source":"iana","compressible":true,"extensions":["es3","et3"]},"application/vnd.etsi.aoc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.asic-e+zip":{"source":"iana","compressible":false},"application/vnd.etsi.asic-s+zip":{"source":"iana","compressible":false},"application/vnd.etsi.cug+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvcommand+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-bc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-cod+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-npvr+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvservice+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsync+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvueprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mcid+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mheg5":{"source":"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{"source":"iana","compressible":true},"application/vnd.etsi.pstn+xml":{"source":"iana","compressible":true},"application/vnd.etsi.sci+xml":{"source":"iana","compressible":true},"application/vnd.etsi.simservs+xml":{"source":"iana","compressible":true},"application/vnd.etsi.timestamp-token":{"source":"iana"},"application/vnd.etsi.tsl+xml":{"source":"iana","compressible":true},"application/vnd.etsi.tsl.der":{"source":"iana"},"application/vnd.eu.kasparian.car+json":{"source":"iana","compressible":true},"application/vnd.eudora.data":{"source":"iana"},"application/vnd.evolv.ecig.profile":{"source":"iana"},"application/vnd.evolv.ecig.settings":{"source":"iana"},"application/vnd.evolv.ecig.theme":{"source":"iana"},"application/vnd.exstream-empower+zip":{"source":"iana","compressible":false},"application/vnd.exstream-package":{"source":"iana"},"application/vnd.ezpix-album":{"source":"iana","extensions":["ez2"]},"application/vnd.ezpix-package":{"source":"iana","extensions":["ez3"]},"application/vnd.f-secure.mobile":{"source":"iana"},"application/vnd.familysearch.gedcom+zip":{"source":"iana","compressible":false},"application/vnd.fastcopy-disk-image":{"source":"iana"},"application/vnd.fdf":{"source":"iana","extensions":["fdf"]},"application/vnd.fdsn.mseed":{"source":"iana","extensions":["mseed"]},"application/vnd.fdsn.seed":{"source":"iana","extensions":["seed","dataless"]},"application/vnd.ffsns":{"source":"iana"},"application/vnd.ficlab.flb+zip":{"source":"iana","compressible":false},"application/vnd.filmit.zfc":{"source":"iana"},"application/vnd.fints":{"source":"iana"},"application/vnd.firemonkeys.cloudcell":{"source":"iana"},"application/vnd.flographit":{"source":"iana","extensions":["gph"]},"application/vnd.fluxtime.clip":{"source":"iana","extensions":["ftc"]},"application/vnd.font-fontforge-sfd":{"source":"iana"},"application/vnd.framemaker":{"source":"iana","extensions":["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{"source":"iana","extensions":["fnc"]},"application/vnd.frogans.ltf":{"source":"iana","extensions":["ltf"]},"application/vnd.fsc.weblaunch":{"source":"iana","extensions":["fsc"]},"application/vnd.fujifilm.fb.docuworks":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.container":{"source":"iana"},"application/vnd.fujifilm.fb.jfi+xml":{"source":"iana","compressible":true},"application/vnd.fujitsu.oasys":{"source":"iana","extensions":["oas"]},"application/vnd.fujitsu.oasys2":{"source":"iana","extensions":["oa2"]},"application/vnd.fujitsu.oasys3":{"source":"iana","extensions":["oa3"]},"application/vnd.fujitsu.oasysgp":{"source":"iana","extensions":["fg5"]},"application/vnd.fujitsu.oasysprs":{"source":"iana","extensions":["bh2"]},"application/vnd.fujixerox.art-ex":{"source":"iana"},"application/vnd.fujixerox.art4":{"source":"iana"},"application/vnd.fujixerox.ddd":{"source":"iana","extensions":["ddd"]},"application/vnd.fujixerox.docuworks":{"source":"iana","extensions":["xdw"]},"application/vnd.fujixerox.docuworks.binder":{"source":"iana","extensions":["xbd"]},"application/vnd.fujixerox.docuworks.container":{"source":"iana"},"application/vnd.fujixerox.hbpl":{"source":"iana"},"application/vnd.fut-misnet":{"source":"iana"},"application/vnd.futoin+cbor":{"source":"iana"},"application/vnd.futoin+json":{"source":"iana","compressible":true},"application/vnd.fuzzysheet":{"source":"iana","extensions":["fzs"]},"application/vnd.genomatix.tuxedo":{"source":"iana","extensions":["txd"]},"application/vnd.gentics.grd+json":{"source":"iana","compressible":true},"application/vnd.geo+json":{"source":"iana","compressible":true},"application/vnd.geocube+xml":{"source":"iana","compressible":true},"application/vnd.geogebra.file":{"source":"iana","extensions":["ggb"]},"application/vnd.geogebra.slides":{"source":"iana"},"application/vnd.geogebra.tool":{"source":"iana","extensions":["ggt"]},"application/vnd.geometry-explorer":{"source":"iana","extensions":["gex","gre"]},"application/vnd.geonext":{"source":"iana","extensions":["gxt"]},"application/vnd.geoplan":{"source":"iana","extensions":["g2w"]},"application/vnd.geospace":{"source":"iana","extensions":["g3w"]},"application/vnd.gerber":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt-response":{"source":"iana"},"application/vnd.gmx":{"source":"iana","extensions":["gmx"]},"application/vnd.google-apps.document":{"compressible":false,"extensions":["gdoc"]},"application/vnd.google-apps.presentation":{"compressible":false,"extensions":["gslides"]},"application/vnd.google-apps.spreadsheet":{"compressible":false,"extensions":["gsheet"]},"application/vnd.google-earth.kml+xml":{"source":"iana","compressible":true,"extensions":["kml"]},"application/vnd.google-earth.kmz":{"source":"iana","compressible":false,"extensions":["kmz"]},"application/vnd.gov.sk.e-form+xml":{"source":"iana","compressible":true},"application/vnd.gov.sk.e-form+zip":{"source":"iana","compressible":false},"application/vnd.gov.sk.xmldatacontainer+xml":{"source":"iana","compressible":true},"application/vnd.grafeq":{"source":"iana","extensions":["gqf","gqs"]},"application/vnd.gridmp":{"source":"iana"},"application/vnd.groove-account":{"source":"iana","extensions":["gac"]},"application/vnd.groove-help":{"source":"iana","extensions":["ghf"]},"application/vnd.groove-identity-message":{"source":"iana","extensions":["gim"]},"application/vnd.groove-injector":{"source":"iana","extensions":["grv"]},"application/vnd.groove-tool-message":{"source":"iana","extensions":["gtm"]},"application/vnd.groove-tool-template":{"source":"iana","extensions":["tpl"]},"application/vnd.groove-vcard":{"source":"iana","extensions":["vcg"]},"application/vnd.hal+json":{"source":"iana","compressible":true},"application/vnd.hal+xml":{"source":"iana","compressible":true,"extensions":["hal"]},"application/vnd.handheld-entertainment+xml":{"source":"iana","compressible":true,"extensions":["zmm"]},"application/vnd.hbci":{"source":"iana","extensions":["hbci"]},"application/vnd.hc+json":{"source":"iana","compressible":true},"application/vnd.hcl-bireports":{"source":"iana"},"application/vnd.hdt":{"source":"iana"},"application/vnd.heroku+json":{"source":"iana","compressible":true},"application/vnd.hhe.lesson-player":{"source":"iana","extensions":["les"]},"application/vnd.hl7cda+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hl7v2+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hp-hpgl":{"source":"iana","extensions":["hpgl"]},"application/vnd.hp-hpid":{"source":"iana","extensions":["hpid"]},"application/vnd.hp-hps":{"source":"iana","extensions":["hps"]},"application/vnd.hp-jlyt":{"source":"iana","extensions":["jlt"]},"application/vnd.hp-pcl":{"source":"iana","extensions":["pcl"]},"application/vnd.hp-pclxl":{"source":"iana","extensions":["pclxl"]},"application/vnd.httphone":{"source":"iana"},"application/vnd.hydrostatix.sof-data":{"source":"iana","extensions":["sfd-hdstx"]},"application/vnd.hyper+json":{"source":"iana","compressible":true},"application/vnd.hyper-item+json":{"source":"iana","compressible":true},"application/vnd.hyperdrive+json":{"source":"iana","compressible":true},"application/vnd.hzn-3d-crossword":{"source":"iana"},"application/vnd.ibm.afplinedata":{"source":"iana"},"application/vnd.ibm.electronic-media":{"source":"iana"},"application/vnd.ibm.minipay":{"source":"iana","extensions":["mpy"]},"application/vnd.ibm.modcap":{"source":"iana","extensions":["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{"source":"iana","extensions":["irm"]},"application/vnd.ibm.secure-container":{"source":"iana","extensions":["sc"]},"application/vnd.iccprofile":{"source":"iana","extensions":["icc","icm"]},"application/vnd.ieee.1905":{"source":"iana"},"application/vnd.igloader":{"source":"iana","extensions":["igl"]},"application/vnd.imagemeter.folder+zip":{"source":"iana","compressible":false},"application/vnd.imagemeter.image+zip":{"source":"iana","compressible":false},"application/vnd.immervision-ivp":{"source":"iana","extensions":["ivp"]},"application/vnd.immervision-ivu":{"source":"iana","extensions":["ivu"]},"application/vnd.ims.imsccv1p1":{"source":"iana"},"application/vnd.ims.imsccv1p2":{"source":"iana"},"application/vnd.ims.imsccv1p3":{"source":"iana"},"application/vnd.ims.lis.v2.result+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy.id+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings.simple+json":{"source":"iana","compressible":true},"application/vnd.informedcontrol.rms+xml":{"source":"iana","compressible":true},"application/vnd.informix-visionary":{"source":"iana"},"application/vnd.infotech.project":{"source":"iana"},"application/vnd.infotech.project+xml":{"source":"iana","compressible":true},"application/vnd.innopath.wamp.notification":{"source":"iana"},"application/vnd.insors.igm":{"source":"iana","extensions":["igm"]},"application/vnd.intercon.formnet":{"source":"iana","extensions":["xpw","xpx"]},"application/vnd.intergeo":{"source":"iana","extensions":["i2g"]},"application/vnd.intertrust.digibox":{"source":"iana"},"application/vnd.intertrust.nncp":{"source":"iana"},"application/vnd.intu.qbo":{"source":"iana","extensions":["qbo"]},"application/vnd.intu.qfx":{"source":"iana","extensions":["qfx"]},"application/vnd.iptc.g2.catalogitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.conceptitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.knowledgeitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsmessage+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.packageitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.planningitem+xml":{"source":"iana","compressible":true},"application/vnd.ipunplugged.rcprofile":{"source":"iana","extensions":["rcprofile"]},"application/vnd.irepository.package+xml":{"source":"iana","compressible":true,"extensions":["irp"]},"application/vnd.is-xpr":{"source":"iana","extensions":["xpr"]},"application/vnd.isac.fcs":{"source":"iana","extensions":["fcs"]},"application/vnd.iso11783-10+zip":{"source":"iana","compressible":false},"application/vnd.jam":{"source":"iana","extensions":["jam"]},"application/vnd.japannet-directory-service":{"source":"iana"},"application/vnd.japannet-jpnstore-wakeup":{"source":"iana"},"application/vnd.japannet-payment-wakeup":{"source":"iana"},"application/vnd.japannet-registration":{"source":"iana"},"application/vnd.japannet-registration-wakeup":{"source":"iana"},"application/vnd.japannet-setstore-wakeup":{"source":"iana"},"application/vnd.japannet-verification":{"source":"iana"},"application/vnd.japannet-verification-wakeup":{"source":"iana"},"application/vnd.jcp.javame.midlet-rms":{"source":"iana","extensions":["rms"]},"application/vnd.jisp":{"source":"iana","extensions":["jisp"]},"application/vnd.joost.joda-archive":{"source":"iana","extensions":["joda"]},"application/vnd.jsk.isdn-ngn":{"source":"iana"},"application/vnd.kahootz":{"source":"iana","extensions":["ktz","ktr"]},"application/vnd.kde.karbon":{"source":"iana","extensions":["karbon"]},"application/vnd.kde.kchart":{"source":"iana","extensions":["chrt"]},"application/vnd.kde.kformula":{"source":"iana","extensions":["kfo"]},"application/vnd.kde.kivio":{"source":"iana","extensions":["flw"]},"application/vnd.kde.kontour":{"source":"iana","extensions":["kon"]},"application/vnd.kde.kpresenter":{"source":"iana","extensions":["kpr","kpt"]},"application/vnd.kde.kspread":{"source":"iana","extensions":["ksp"]},"application/vnd.kde.kword":{"source":"iana","extensions":["kwd","kwt"]},"application/vnd.kenameaapp":{"source":"iana","extensions":["htke"]},"application/vnd.kidspiration":{"source":"iana","extensions":["kia"]},"application/vnd.kinar":{"source":"iana","extensions":["kne","knp"]},"application/vnd.koan":{"source":"iana","extensions":["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{"source":"iana","extensions":["sse"]},"application/vnd.las":{"source":"iana"},"application/vnd.las.las+json":{"source":"iana","compressible":true},"application/vnd.las.las+xml":{"source":"iana","compressible":true,"extensions":["lasxml"]},"application/vnd.laszip":{"source":"iana"},"application/vnd.leap+json":{"source":"iana","compressible":true},"application/vnd.liberty-request+xml":{"source":"iana","compressible":true},"application/vnd.llamagraphics.life-balance.desktop":{"source":"iana","extensions":["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{"source":"iana","compressible":true,"extensions":["lbe"]},"application/vnd.logipipe.circuit+zip":{"source":"iana","compressible":false},"application/vnd.loom":{"source":"iana"},"application/vnd.lotus-1-2-3":{"source":"iana","extensions":["123"]},"application/vnd.lotus-approach":{"source":"iana","extensions":["apr"]},"application/vnd.lotus-freelance":{"source":"iana","extensions":["pre"]},"application/vnd.lotus-notes":{"source":"iana","extensions":["nsf"]},"application/vnd.lotus-organizer":{"source":"iana","extensions":["org"]},"application/vnd.lotus-screencam":{"source":"iana","extensions":["scm"]},"application/vnd.lotus-wordpro":{"source":"iana","extensions":["lwp"]},"application/vnd.macports.portpkg":{"source":"iana","extensions":["portpkg"]},"application/vnd.mapbox-vector-tile":{"source":"iana","extensions":["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.conftoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.license+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.mdcf":{"source":"iana"},"application/vnd.mason+json":{"source":"iana","compressible":true},"application/vnd.maxar.archive.3tz+zip":{"source":"iana","compressible":false},"application/vnd.maxmind.maxmind-db":{"source":"iana"},"application/vnd.mcd":{"source":"iana","extensions":["mcd"]},"application/vnd.medcalcdata":{"source":"iana","extensions":["mc1"]},"application/vnd.mediastation.cdkey":{"source":"iana","extensions":["cdkey"]},"application/vnd.meridian-slingshot":{"source":"iana"},"application/vnd.mfer":{"source":"iana","extensions":["mwf"]},"application/vnd.mfmp":{"source":"iana","extensions":["mfm"]},"application/vnd.micro+json":{"source":"iana","compressible":true},"application/vnd.micrografx.flo":{"source":"iana","extensions":["flo"]},"application/vnd.micrografx.igx":{"source":"iana","extensions":["igx"]},"application/vnd.microsoft.portable-executable":{"source":"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{"source":"iana"},"application/vnd.miele+json":{"source":"iana","compressible":true},"application/vnd.mif":{"source":"iana","extensions":["mif"]},"application/vnd.minisoft-hp3000-save":{"source":"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{"source":"iana"},"application/vnd.mobius.daf":{"source":"iana","extensions":["daf"]},"application/vnd.mobius.dis":{"source":"iana","extensions":["dis"]},"application/vnd.mobius.mbk":{"source":"iana","extensions":["mbk"]},"application/vnd.mobius.mqy":{"source":"iana","extensions":["mqy"]},"application/vnd.mobius.msl":{"source":"iana","extensions":["msl"]},"application/vnd.mobius.plc":{"source":"iana","extensions":["plc"]},"application/vnd.mobius.txf":{"source":"iana","extensions":["txf"]},"application/vnd.mophun.application":{"source":"iana","extensions":["mpn"]},"application/vnd.mophun.certificate":{"source":"iana","extensions":["mpc"]},"application/vnd.motorola.flexsuite":{"source":"iana"},"application/vnd.motorola.flexsuite.adsi":{"source":"iana"},"application/vnd.motorola.flexsuite.fis":{"source":"iana"},"application/vnd.motorola.flexsuite.gotap":{"source":"iana"},"application/vnd.motorola.flexsuite.kmr":{"source":"iana"},"application/vnd.motorola.flexsuite.ttc":{"source":"iana"},"application/vnd.motorola.flexsuite.wem":{"source":"iana"},"application/vnd.motorola.iprm":{"source":"iana"},"application/vnd.mozilla.xul+xml":{"source":"iana","compressible":true,"extensions":["xul"]},"application/vnd.ms-3mfdocument":{"source":"iana"},"application/vnd.ms-artgalry":{"source":"iana","extensions":["cil"]},"application/vnd.ms-asf":{"source":"iana"},"application/vnd.ms-cab-compressed":{"source":"iana","extensions":["cab"]},"application/vnd.ms-color.iccprofile":{"source":"apache"},"application/vnd.ms-excel":{"source":"iana","compressible":false,"extensions":["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{"source":"iana","extensions":["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{"source":"iana","extensions":["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{"source":"iana","extensions":["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{"source":"iana","extensions":["xltm"]},"application/vnd.ms-fontobject":{"source":"iana","compressible":true,"extensions":["eot"]},"application/vnd.ms-htmlhelp":{"source":"iana","extensions":["chm"]},"application/vnd.ms-ims":{"source":"iana","extensions":["ims"]},"application/vnd.ms-lrm":{"source":"iana","extensions":["lrm"]},"application/vnd.ms-office.activex+xml":{"source":"iana","compressible":true},"application/vnd.ms-officetheme":{"source":"iana","extensions":["thmx"]},"application/vnd.ms-opentype":{"source":"apache","compressible":true},"application/vnd.ms-outlook":{"compressible":false,"extensions":["msg"]},"application/vnd.ms-package.obfuscated-opentype":{"source":"apache"},"application/vnd.ms-pki.seccat":{"source":"apache","extensions":["cat"]},"application/vnd.ms-pki.stl":{"source":"apache","extensions":["stl"]},"application/vnd.ms-playready.initiator+xml":{"source":"iana","compressible":true},"application/vnd.ms-powerpoint":{"source":"iana","compressible":false,"extensions":["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{"source":"iana","extensions":["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{"source":"iana","extensions":["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{"source":"iana","extensions":["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{"source":"iana","extensions":["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{"source":"iana","extensions":["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{"source":"iana","compressible":true},"application/vnd.ms-printing.printticket+xml":{"source":"apache","compressible":true},"application/vnd.ms-printschematicket+xml":{"source":"iana","compressible":true},"application/vnd.ms-project":{"source":"iana","extensions":["mpp","mpt"]},"application/vnd.ms-tnef":{"source":"iana"},"application/vnd.ms-windows.devicepairing":{"source":"iana"},"application/vnd.ms-windows.nwprinting.oob":{"source":"iana"},"application/vnd.ms-windows.printerpairing":{"source":"iana"},"application/vnd.ms-windows.wsd.oob":{"source":"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.lic-resp":{"source":"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.meter-resp":{"source":"iana"},"application/vnd.ms-word.document.macroenabled.12":{"source":"iana","extensions":["docm"]},"application/vnd.ms-word.template.macroenabled.12":{"source":"iana","extensions":["dotm"]},"application/vnd.ms-works":{"source":"iana","extensions":["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{"source":"iana","extensions":["wpl"]},"application/vnd.ms-xpsdocument":{"source":"iana","compressible":false,"extensions":["xps"]},"application/vnd.msa-disk-image":{"source":"iana"},"application/vnd.mseq":{"source":"iana","extensions":["mseq"]},"application/vnd.msign":{"source":"iana"},"application/vnd.multiad.creator":{"source":"iana"},"application/vnd.multiad.creator.cif":{"source":"iana"},"application/vnd.music-niff":{"source":"iana"},"application/vnd.musician":{"source":"iana","extensions":["mus"]},"application/vnd.muvee.style":{"source":"iana","extensions":["msty"]},"application/vnd.mynfc":{"source":"iana","extensions":["taglet"]},"application/vnd.nacamar.ybrid+json":{"source":"iana","compressible":true},"application/vnd.ncd.control":{"source":"iana"},"application/vnd.ncd.reference":{"source":"iana"},"application/vnd.nearst.inv+json":{"source":"iana","compressible":true},"application/vnd.nebumind.line":{"source":"iana"},"application/vnd.nervana":{"source":"iana"},"application/vnd.netfpx":{"source":"iana"},"application/vnd.neurolanguage.nlu":{"source":"iana","extensions":["nlu"]},"application/vnd.nimn":{"source":"iana"},"application/vnd.nintendo.nitro.rom":{"source":"iana"},"application/vnd.nintendo.snes.rom":{"source":"iana"},"application/vnd.nitf":{"source":"iana","extensions":["ntf","nitf"]},"application/vnd.noblenet-directory":{"source":"iana","extensions":["nnd"]},"application/vnd.noblenet-sealer":{"source":"iana","extensions":["nns"]},"application/vnd.noblenet-web":{"source":"iana","extensions":["nnw"]},"application/vnd.nokia.catalogs":{"source":"iana"},"application/vnd.nokia.conml+wbxml":{"source":"iana"},"application/vnd.nokia.conml+xml":{"source":"iana","compressible":true},"application/vnd.nokia.iptv.config+xml":{"source":"iana","compressible":true},"application/vnd.nokia.isds-radio-presets":{"source":"iana"},"application/vnd.nokia.landmark+wbxml":{"source":"iana"},"application/vnd.nokia.landmark+xml":{"source":"iana","compressible":true},"application/vnd.nokia.landmarkcollection+xml":{"source":"iana","compressible":true},"application/vnd.nokia.n-gage.ac+xml":{"source":"iana","compressible":true,"extensions":["ac"]},"application/vnd.nokia.n-gage.data":{"source":"iana","extensions":["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{"source":"iana","extensions":["n-gage"]},"application/vnd.nokia.ncd":{"source":"iana"},"application/vnd.nokia.pcd+wbxml":{"source":"iana"},"application/vnd.nokia.pcd+xml":{"source":"iana","compressible":true},"application/vnd.nokia.radio-preset":{"source":"iana","extensions":["rpst"]},"application/vnd.nokia.radio-presets":{"source":"iana","extensions":["rpss"]},"application/vnd.novadigm.edm":{"source":"iana","extensions":["edm"]},"application/vnd.novadigm.edx":{"source":"iana","extensions":["edx"]},"application/vnd.novadigm.ext":{"source":"iana","extensions":["ext"]},"application/vnd.ntt-local.content-share":{"source":"iana"},"application/vnd.ntt-local.file-transfer":{"source":"iana"},"application/vnd.ntt-local.ogw_remote-access":{"source":"iana"},"application/vnd.ntt-local.sip-ta_remote":{"source":"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{"source":"iana"},"application/vnd.oasis.opendocument.chart":{"source":"iana","extensions":["odc"]},"application/vnd.oasis.opendocument.chart-template":{"source":"iana","extensions":["otc"]},"application/vnd.oasis.opendocument.database":{"source":"iana","extensions":["odb"]},"application/vnd.oasis.opendocument.formula":{"source":"iana","extensions":["odf"]},"application/vnd.oasis.opendocument.formula-template":{"source":"iana","extensions":["odft"]},"application/vnd.oasis.opendocument.graphics":{"source":"iana","compressible":false,"extensions":["odg"]},"application/vnd.oasis.opendocument.graphics-template":{"source":"iana","extensions":["otg"]},"application/vnd.oasis.opendocument.image":{"source":"iana","extensions":["odi"]},"application/vnd.oasis.opendocument.image-template":{"source":"iana","extensions":["oti"]},"application/vnd.oasis.opendocument.presentation":{"source":"iana","compressible":false,"extensions":["odp"]},"application/vnd.oasis.opendocument.presentation-template":{"source":"iana","extensions":["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{"source":"iana","compressible":false,"extensions":["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{"source":"iana","extensions":["ots"]},"application/vnd.oasis.opendocument.text":{"source":"iana","compressible":false,"extensions":["odt"]},"application/vnd.oasis.opendocument.text-master":{"source":"iana","extensions":["odm"]},"application/vnd.oasis.opendocument.text-template":{"source":"iana","extensions":["ott"]},"application/vnd.oasis.opendocument.text-web":{"source":"iana","extensions":["oth"]},"application/vnd.obn":{"source":"iana"},"application/vnd.ocf+cbor":{"source":"iana"},"application/vnd.oci.image.manifest.v1+json":{"source":"iana","compressible":true},"application/vnd.oftn.l10n+json":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessdownload+xml":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessstreaming+xml":{"source":"iana","compressible":true},"application/vnd.oipf.cspg-hexbinary":{"source":"iana"},"application/vnd.oipf.dae.svg+xml":{"source":"iana","compressible":true},"application/vnd.oipf.dae.xhtml+xml":{"source":"iana","compressible":true},"application/vnd.oipf.mippvcontrolmessage+xml":{"source":"iana","compressible":true},"application/vnd.oipf.pae.gem":{"source":"iana"},"application/vnd.oipf.spdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.oipf.spdlist+xml":{"source":"iana","compressible":true},"application/vnd.oipf.ueprofile+xml":{"source":"iana","compressible":true},"application/vnd.oipf.userprofile+xml":{"source":"iana","compressible":true},"application/vnd.olpc-sugar":{"source":"iana","extensions":["xo"]},"application/vnd.oma-scws-config":{"source":"iana"},"application/vnd.oma-scws-http-request":{"source":"iana"},"application/vnd.oma-scws-http-response":{"source":"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.drm-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.imd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.ltkm":{"source":"iana"},"application/vnd.oma.bcast.notification+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.provisioningtrigger":{"source":"iana"},"application/vnd.oma.bcast.sgboot":{"source":"iana"},"application/vnd.oma.bcast.sgdd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sgdu":{"source":"iana"},"application/vnd.oma.bcast.simple-symbol-container":{"source":"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sprov+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.stkm":{"source":"iana"},"application/vnd.oma.cab-address-book+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-feature-handler+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-pcc+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-subs-invite+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-user-prefs+xml":{"source":"iana","compressible":true},"application/vnd.oma.dcd":{"source":"iana"},"application/vnd.oma.dcdc":{"source":"iana"},"application/vnd.oma.dd2+xml":{"source":"iana","compressible":true,"extensions":["dd2"]},"application/vnd.oma.drm.risd+xml":{"source":"iana","compressible":true},"application/vnd.oma.group-usage-list+xml":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+cbor":{"source":"iana"},"application/vnd.oma.lwm2m+json":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+tlv":{"source":"iana"},"application/vnd.oma.pal+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.detailed-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.final-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.groups+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.invocation-descriptor+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.optimized-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.push":{"source":"iana"},"application/vnd.oma.scidm.messages+xml":{"source":"iana","compressible":true},"application/vnd.oma.xcap-directory+xml":{"source":"iana","compressible":true},"application/vnd.omads-email+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-file+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-folder+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omaloc-supl-init":{"source":"iana"},"application/vnd.onepager":{"source":"iana"},"application/vnd.onepagertamp":{"source":"iana"},"application/vnd.onepagertamx":{"source":"iana"},"application/vnd.onepagertat":{"source":"iana"},"application/vnd.onepagertatp":{"source":"iana"},"application/vnd.onepagertatx":{"source":"iana"},"application/vnd.openblox.game+xml":{"source":"iana","compressible":true,"extensions":["obgx"]},"application/vnd.openblox.game-binary":{"source":"iana"},"application/vnd.openeye.oeb":{"source":"iana"},"application/vnd.openofficeorg.extension":{"source":"apache","extensions":["oxt"]},"application/vnd.openstreetmap.data+xml":{"source":"iana","compressible":true,"extensions":["osm"]},"application/vnd.opentimestamps.ots":{"source":"iana"},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawing+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{"source":"iana","compressible":false,"extensions":["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slide":{"source":"iana","extensions":["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{"source":"iana","extensions":["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.template":{"source":"iana","extensions":["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"source":"iana","compressible":false,"extensions":["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{"source":"iana","extensions":["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.theme+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.vmldrawing":{"source":"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{"source":"iana","compressible":false,"extensions":["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{"source":"iana","extensions":["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.core-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.relationships+xml":{"source":"iana","compressible":true},"application/vnd.oracle.resource+json":{"source":"iana","compressible":true},"application/vnd.orange.indata":{"source":"iana"},"application/vnd.osa.netdeploy":{"source":"iana"},"application/vnd.osgeo.mapguide.package":{"source":"iana","extensions":["mgp"]},"application/vnd.osgi.bundle":{"source":"iana"},"application/vnd.osgi.dp":{"source":"iana","extensions":["dp"]},"application/vnd.osgi.subsystem":{"source":"iana","extensions":["esa"]},"application/vnd.otps.ct-kip+xml":{"source":"iana","compressible":true},"application/vnd.oxli.countgraph":{"source":"iana"},"application/vnd.pagerduty+json":{"source":"iana","compressible":true},"application/vnd.palm":{"source":"iana","extensions":["pdb","pqa","oprc"]},"application/vnd.panoply":{"source":"iana"},"application/vnd.paos.xml":{"source":"iana"},"application/vnd.patentdive":{"source":"iana"},"application/vnd.patientecommsdoc":{"source":"iana"},"application/vnd.pawaafile":{"source":"iana","extensions":["paw"]},"application/vnd.pcos":{"source":"iana"},"application/vnd.pg.format":{"source":"iana","extensions":["str"]},"application/vnd.pg.osasli":{"source":"iana","extensions":["ei6"]},"application/vnd.piaccess.application-licence":{"source":"iana"},"application/vnd.picsel":{"source":"iana","extensions":["efif"]},"application/vnd.pmi.widget":{"source":"iana","extensions":["wg"]},"application/vnd.poc.group-advertisement+xml":{"source":"iana","compressible":true},"application/vnd.pocketlearn":{"source":"iana","extensions":["plf"]},"application/vnd.powerbuilder6":{"source":"iana","extensions":["pbd"]},"application/vnd.powerbuilder6-s":{"source":"iana"},"application/vnd.powerbuilder7":{"source":"iana"},"application/vnd.powerbuilder7-s":{"source":"iana"},"application/vnd.powerbuilder75":{"source":"iana"},"application/vnd.powerbuilder75-s":{"source":"iana"},"application/vnd.preminet":{"source":"iana"},"application/vnd.previewsystems.box":{"source":"iana","extensions":["box"]},"application/vnd.proteus.magazine":{"source":"iana","extensions":["mgz"]},"application/vnd.psfs":{"source":"iana"},"application/vnd.publishare-delta-tree":{"source":"iana","extensions":["qps"]},"application/vnd.pvi.ptid1":{"source":"iana","extensions":["ptid"]},"application/vnd.pwg-multiplexed":{"source":"iana"},"application/vnd.pwg-xhtml-print+xml":{"source":"iana","compressible":true},"application/vnd.qualcomm.brew-app-res":{"source":"iana"},"application/vnd.quarantainenet":{"source":"iana"},"application/vnd.quark.quarkxpress":{"source":"iana","extensions":["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{"source":"iana"},"application/vnd.radisys.moml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conn+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-stream+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-base+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-detect+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-group+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-speech+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-transform+xml":{"source":"iana","compressible":true},"application/vnd.rainstor.data":{"source":"iana"},"application/vnd.rapid":{"source":"iana"},"application/vnd.rar":{"source":"iana","extensions":["rar"]},"application/vnd.realvnc.bed":{"source":"iana","extensions":["bed"]},"application/vnd.recordare.musicxml":{"source":"iana","extensions":["mxl"]},"application/vnd.recordare.musicxml+xml":{"source":"iana","compressible":true,"extensions":["musicxml"]},"application/vnd.renlearn.rlprint":{"source":"iana"},"application/vnd.resilient.logic":{"source":"iana"},"application/vnd.restful+json":{"source":"iana","compressible":true},"application/vnd.rig.cryptonote":{"source":"iana","extensions":["cryptonote"]},"application/vnd.rim.cod":{"source":"apache","extensions":["cod"]},"application/vnd.rn-realmedia":{"source":"apache","extensions":["rm"]},"application/vnd.rn-realmedia-vbr":{"source":"apache","extensions":["rmvb"]},"application/vnd.route66.link66+xml":{"source":"iana","compressible":true,"extensions":["link66"]},"application/vnd.rs-274x":{"source":"iana"},"application/vnd.ruckus.download":{"source":"iana"},"application/vnd.s3sms":{"source":"iana"},"application/vnd.sailingtracker.track":{"source":"iana","extensions":["st"]},"application/vnd.sar":{"source":"iana"},"application/vnd.sbm.cid":{"source":"iana"},"application/vnd.sbm.mid2":{"source":"iana"},"application/vnd.scribus":{"source":"iana"},"application/vnd.sealed.3df":{"source":"iana"},"application/vnd.sealed.csf":{"source":"iana"},"application/vnd.sealed.doc":{"source":"iana"},"application/vnd.sealed.eml":{"source":"iana"},"application/vnd.sealed.mht":{"source":"iana"},"application/vnd.sealed.net":{"source":"iana"},"application/vnd.sealed.ppt":{"source":"iana"},"application/vnd.sealed.tiff":{"source":"iana"},"application/vnd.sealed.xls":{"source":"iana"},"application/vnd.sealedmedia.softseal.html":{"source":"iana"},"application/vnd.sealedmedia.softseal.pdf":{"source":"iana"},"application/vnd.seemail":{"source":"iana","extensions":["see"]},"application/vnd.seis+json":{"source":"iana","compressible":true},"application/vnd.sema":{"source":"iana","extensions":["sema"]},"application/vnd.semd":{"source":"iana","extensions":["semd"]},"application/vnd.semf":{"source":"iana","extensions":["semf"]},"application/vnd.shade-save-file":{"source":"iana"},"application/vnd.shana.informed.formdata":{"source":"iana","extensions":["ifm"]},"application/vnd.shana.informed.formtemplate":{"source":"iana","extensions":["itp"]},"application/vnd.shana.informed.interchange":{"source":"iana","extensions":["iif"]},"application/vnd.shana.informed.package":{"source":"iana","extensions":["ipk"]},"application/vnd.shootproof+json":{"source":"iana","compressible":true},"application/vnd.shopkick+json":{"source":"iana","compressible":true},"application/vnd.shp":{"source":"iana"},"application/vnd.shx":{"source":"iana"},"application/vnd.sigrok.session":{"source":"iana"},"application/vnd.simtech-mindmapper":{"source":"iana","extensions":["twd","twds"]},"application/vnd.siren+json":{"source":"iana","compressible":true},"application/vnd.smaf":{"source":"iana","extensions":["mmf"]},"application/vnd.smart.notebook":{"source":"iana"},"application/vnd.smart.teacher":{"source":"iana","extensions":["teacher"]},"application/vnd.snesdev-page-table":{"source":"iana"},"application/vnd.software602.filler.form+xml":{"source":"iana","compressible":true,"extensions":["fo"]},"application/vnd.software602.filler.form-xml-zip":{"source":"iana"},"application/vnd.solent.sdkm+xml":{"source":"iana","compressible":true,"extensions":["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{"source":"iana","extensions":["dxp"]},"application/vnd.spotfire.sfs":{"source":"iana","extensions":["sfs"]},"application/vnd.sqlite3":{"source":"iana"},"application/vnd.sss-cod":{"source":"iana"},"application/vnd.sss-dtf":{"source":"iana"},"application/vnd.sss-ntf":{"source":"iana"},"application/vnd.stardivision.calc":{"source":"apache","extensions":["sdc"]},"application/vnd.stardivision.draw":{"source":"apache","extensions":["sda"]},"application/vnd.stardivision.impress":{"source":"apache","extensions":["sdd"]},"application/vnd.stardivision.math":{"source":"apache","extensions":["smf"]},"application/vnd.stardivision.writer":{"source":"apache","extensions":["sdw","vor"]},"application/vnd.stardivision.writer-global":{"source":"apache","extensions":["sgl"]},"application/vnd.stepmania.package":{"source":"iana","extensions":["smzip"]},"application/vnd.stepmania.stepchart":{"source":"iana","extensions":["sm"]},"application/vnd.street-stream":{"source":"iana"},"application/vnd.sun.wadl+xml":{"source":"iana","compressible":true,"extensions":["wadl"]},"application/vnd.sun.xml.calc":{"source":"apache","extensions":["sxc"]},"application/vnd.sun.xml.calc.template":{"source":"apache","extensions":["stc"]},"application/vnd.sun.xml.draw":{"source":"apache","extensions":["sxd"]},"application/vnd.sun.xml.draw.template":{"source":"apache","extensions":["std"]},"application/vnd.sun.xml.impress":{"source":"apache","extensions":["sxi"]},"application/vnd.sun.xml.impress.template":{"source":"apache","extensions":["sti"]},"application/vnd.sun.xml.math":{"source":"apache","extensions":["sxm"]},"application/vnd.sun.xml.writer":{"source":"apache","extensions":["sxw"]},"application/vnd.sun.xml.writer.global":{"source":"apache","extensions":["sxg"]},"application/vnd.sun.xml.writer.template":{"source":"apache","extensions":["stw"]},"application/vnd.sus-calendar":{"source":"iana","extensions":["sus","susp"]},"application/vnd.svd":{"source":"iana","extensions":["svd"]},"application/vnd.swiftview-ics":{"source":"iana"},"application/vnd.sycle+xml":{"source":"iana","compressible":true},"application/vnd.syft+json":{"source":"iana","compressible":true},"application/vnd.symbian.install":{"source":"apache","extensions":["sis","sisx"]},"application/vnd.syncml+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xsm"]},"application/vnd.syncml.dm+wbxml":{"source":"iana","charset":"UTF-8","extensions":["bdm"]},"application/vnd.syncml.dm+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xdm"]},"application/vnd.syncml.dm.notification":{"source":"iana"},"application/vnd.syncml.dmddf+wbxml":{"source":"iana"},"application/vnd.syncml.dmddf+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{"source":"iana"},"application/vnd.syncml.dmtnds+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.syncml.ds.notification":{"source":"iana"},"application/vnd.tableschema+json":{"source":"iana","compressible":true},"application/vnd.tao.intent-module-archive":{"source":"iana","extensions":["tao"]},"application/vnd.tcpdump.pcap":{"source":"iana","extensions":["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{"source":"iana","compressible":true},"application/vnd.tmd.mediaflex.api+xml":{"source":"iana","compressible":true},"application/vnd.tml":{"source":"iana"},"application/vnd.tmobile-livetv":{"source":"iana","extensions":["tmo"]},"application/vnd.tri.onesource":{"source":"iana"},"application/vnd.trid.tpt":{"source":"iana","extensions":["tpt"]},"application/vnd.triscape.mxs":{"source":"iana","extensions":["mxs"]},"application/vnd.trueapp":{"source":"iana","extensions":["tra"]},"application/vnd.truedoc":{"source":"iana"},"application/vnd.ubisoft.webplayer":{"source":"iana"},"application/vnd.ufdl":{"source":"iana","extensions":["ufd","ufdl"]},"application/vnd.uiq.theme":{"source":"iana","extensions":["utz"]},"application/vnd.umajin":{"source":"iana","extensions":["umj"]},"application/vnd.unity":{"source":"iana","extensions":["unityweb"]},"application/vnd.uoml+xml":{"source":"iana","compressible":true,"extensions":["uoml"]},"application/vnd.uplanet.alert":{"source":"iana"},"application/vnd.uplanet.alert-wbxml":{"source":"iana"},"application/vnd.uplanet.bearer-choice":{"source":"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{"source":"iana"},"application/vnd.uplanet.cacheop":{"source":"iana"},"application/vnd.uplanet.cacheop-wbxml":{"source":"iana"},"application/vnd.uplanet.channel":{"source":"iana"},"application/vnd.uplanet.channel-wbxml":{"source":"iana"},"application/vnd.uplanet.list":{"source":"iana"},"application/vnd.uplanet.list-wbxml":{"source":"iana"},"application/vnd.uplanet.listcmd":{"source":"iana"},"application/vnd.uplanet.listcmd-wbxml":{"source":"iana"},"application/vnd.uplanet.signal":{"source":"iana"},"application/vnd.uri-map":{"source":"iana"},"application/vnd.valve.source.material":{"source":"iana"},"application/vnd.vcx":{"source":"iana","extensions":["vcx"]},"application/vnd.vd-study":{"source":"iana"},"application/vnd.vectorworks":{"source":"iana"},"application/vnd.vel+json":{"source":"iana","compressible":true},"application/vnd.verimatrix.vcas":{"source":"iana"},"application/vnd.veritone.aion+json":{"source":"iana","compressible":true},"application/vnd.veryant.thin":{"source":"iana"},"application/vnd.ves.encrypted":{"source":"iana"},"application/vnd.vidsoft.vidconference":{"source":"iana"},"application/vnd.visio":{"source":"iana","extensions":["vsd","vst","vss","vsw"]},"application/vnd.visionary":{"source":"iana","extensions":["vis"]},"application/vnd.vividence.scriptfile":{"source":"iana"},"application/vnd.vsf":{"source":"iana","extensions":["vsf"]},"application/vnd.wap.sic":{"source":"iana"},"application/vnd.wap.slc":{"source":"iana"},"application/vnd.wap.wbxml":{"source":"iana","charset":"UTF-8","extensions":["wbxml"]},"application/vnd.wap.wmlc":{"source":"iana","extensions":["wmlc"]},"application/vnd.wap.wmlscriptc":{"source":"iana","extensions":["wmlsc"]},"application/vnd.webturbo":{"source":"iana","extensions":["wtb"]},"application/vnd.wfa.dpp":{"source":"iana"},"application/vnd.wfa.p2p":{"source":"iana"},"application/vnd.wfa.wsc":{"source":"iana"},"application/vnd.windows.devicepairing":{"source":"iana"},"application/vnd.wmc":{"source":"iana"},"application/vnd.wmf.bootstrap":{"source":"iana"},"application/vnd.wolfram.mathematica":{"source":"iana"},"application/vnd.wolfram.mathematica.package":{"source":"iana"},"application/vnd.wolfram.player":{"source":"iana","extensions":["nbp"]},"application/vnd.wordperfect":{"source":"iana","extensions":["wpd"]},"application/vnd.wqd":{"source":"iana","extensions":["wqd"]},"application/vnd.wrq-hp3000-labelled":{"source":"iana"},"application/vnd.wt.stf":{"source":"iana","extensions":["stf"]},"application/vnd.wv.csp+wbxml":{"source":"iana"},"application/vnd.wv.csp+xml":{"source":"iana","compressible":true},"application/vnd.wv.ssp+xml":{"source":"iana","compressible":true},"application/vnd.xacml+json":{"source":"iana","compressible":true},"application/vnd.xara":{"source":"iana","extensions":["xar"]},"application/vnd.xfdl":{"source":"iana","extensions":["xfdl"]},"application/vnd.xfdl.webform":{"source":"iana"},"application/vnd.xmi+xml":{"source":"iana","compressible":true},"application/vnd.xmpie.cpkg":{"source":"iana"},"application/vnd.xmpie.dpkg":{"source":"iana"},"application/vnd.xmpie.plan":{"source":"iana"},"application/vnd.xmpie.ppkg":{"source":"iana"},"application/vnd.xmpie.xlim":{"source":"iana"},"application/vnd.yamaha.hv-dic":{"source":"iana","extensions":["hvd"]},"application/vnd.yamaha.hv-script":{"source":"iana","extensions":["hvs"]},"application/vnd.yamaha.hv-voice":{"source":"iana","extensions":["hvp"]},"application/vnd.yamaha.openscoreformat":{"source":"iana","extensions":["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{"source":"iana","compressible":true,"extensions":["osfpvg"]},"application/vnd.yamaha.remote-setup":{"source":"iana"},"application/vnd.yamaha.smaf-audio":{"source":"iana","extensions":["saf"]},"application/vnd.yamaha.smaf-phrase":{"source":"iana","extensions":["spf"]},"application/vnd.yamaha.through-ngn":{"source":"iana"},"application/vnd.yamaha.tunnel-udpencap":{"source":"iana"},"application/vnd.yaoweme":{"source":"iana"},"application/vnd.yellowriver-custom-menu":{"source":"iana","extensions":["cmp"]},"application/vnd.youtube.yt":{"source":"iana"},"application/vnd.zul":{"source":"iana","extensions":["zir","zirz"]},"application/vnd.zzazz.deck+xml":{"source":"iana","compressible":true,"extensions":["zaz"]},"application/voicexml+xml":{"source":"iana","compressible":true,"extensions":["vxml"]},"application/voucher-cms+json":{"source":"iana","compressible":true},"application/vq-rtcpxr":{"source":"iana"},"application/wasm":{"source":"iana","compressible":true,"extensions":["wasm"]},"application/watcherinfo+xml":{"source":"iana","compressible":true,"extensions":["wif"]},"application/webpush-options+json":{"source":"iana","compressible":true},"application/whoispp-query":{"source":"iana"},"application/whoispp-response":{"source":"iana"},"application/widget":{"source":"iana","extensions":["wgt"]},"application/winhlp":{"source":"apache","extensions":["hlp"]},"application/wita":{"source":"iana"},"application/wordperfect5.1":{"source":"iana"},"application/wsdl+xml":{"source":"iana","compressible":true,"extensions":["wsdl"]},"application/wspolicy+xml":{"source":"iana","compressible":true,"extensions":["wspolicy"]},"application/x-7z-compressed":{"source":"apache","compressible":false,"extensions":["7z"]},"application/x-abiword":{"source":"apache","extensions":["abw"]},"application/x-ace-compressed":{"source":"apache","extensions":["ace"]},"application/x-amf":{"source":"apache"},"application/x-apple-diskimage":{"source":"apache","extensions":["dmg"]},"application/x-arj":{"compressible":false,"extensions":["arj"]},"application/x-authorware-bin":{"source":"apache","extensions":["aab","x32","u32","vox"]},"application/x-authorware-map":{"source":"apache","extensions":["aam"]},"application/x-authorware-seg":{"source":"apache","extensions":["aas"]},"application/x-bcpio":{"source":"apache","extensions":["bcpio"]},"application/x-bdoc":{"compressible":false,"extensions":["bdoc"]},"application/x-bittorrent":{"source":"apache","extensions":["torrent"]},"application/x-blorb":{"source":"apache","extensions":["blb","blorb"]},"application/x-bzip":{"source":"apache","compressible":false,"extensions":["bz"]},"application/x-bzip2":{"source":"apache","compressible":false,"extensions":["bz2","boz"]},"application/x-cbr":{"source":"apache","extensions":["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{"source":"apache","extensions":["vcd"]},"application/x-cfs-compressed":{"source":"apache","extensions":["cfs"]},"application/x-chat":{"source":"apache","extensions":["chat"]},"application/x-chess-pgn":{"source":"apache","extensions":["pgn"]},"application/x-chrome-extension":{"extensions":["crx"]},"application/x-cocoa":{"source":"nginx","extensions":["cco"]},"application/x-compress":{"source":"apache"},"application/x-conference":{"source":"apache","extensions":["nsc"]},"application/x-cpio":{"source":"apache","extensions":["cpio"]},"application/x-csh":{"source":"apache","extensions":["csh"]},"application/x-deb":{"compressible":false},"application/x-debian-package":{"source":"apache","extensions":["deb","udeb"]},"application/x-dgc-compressed":{"source":"apache","extensions":["dgc"]},"application/x-director":{"source":"apache","extensions":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{"source":"apache","extensions":["wad"]},"application/x-dtbncx+xml":{"source":"apache","compressible":true,"extensions":["ncx"]},"application/x-dtbook+xml":{"source":"apache","compressible":true,"extensions":["dtb"]},"application/x-dtbresource+xml":{"source":"apache","compressible":true,"extensions":["res"]},"application/x-dvi":{"source":"apache","compressible":false,"extensions":["dvi"]},"application/x-envoy":{"source":"apache","extensions":["evy"]},"application/x-eva":{"source":"apache","extensions":["eva"]},"application/x-font-bdf":{"source":"apache","extensions":["bdf"]},"application/x-font-dos":{"source":"apache"},"application/x-font-framemaker":{"source":"apache"},"application/x-font-ghostscript":{"source":"apache","extensions":["gsf"]},"application/x-font-libgrx":{"source":"apache"},"application/x-font-linux-psf":{"source":"apache","extensions":["psf"]},"application/x-font-pcf":{"source":"apache","extensions":["pcf"]},"application/x-font-snf":{"source":"apache","extensions":["snf"]},"application/x-font-speedo":{"source":"apache"},"application/x-font-sunos-news":{"source":"apache"},"application/x-font-type1":{"source":"apache","extensions":["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{"source":"apache"},"application/x-freearc":{"source":"apache","extensions":["arc"]},"application/x-futuresplash":{"source":"apache","extensions":["spl"]},"application/x-gca-compressed":{"source":"apache","extensions":["gca"]},"application/x-glulx":{"source":"apache","extensions":["ulx"]},"application/x-gnumeric":{"source":"apache","extensions":["gnumeric"]},"application/x-gramps-xml":{"source":"apache","extensions":["gramps"]},"application/x-gtar":{"source":"apache","extensions":["gtar"]},"application/x-gzip":{"source":"apache"},"application/x-hdf":{"source":"apache","extensions":["hdf"]},"application/x-httpd-php":{"compressible":true,"extensions":["php"]},"application/x-install-instructions":{"source":"apache","extensions":["install"]},"application/x-iso9660-image":{"source":"apache","extensions":["iso"]},"application/x-iwork-keynote-sffkey":{"extensions":["key"]},"application/x-iwork-numbers-sffnumbers":{"extensions":["numbers"]},"application/x-iwork-pages-sffpages":{"extensions":["pages"]},"application/x-java-archive-diff":{"source":"nginx","extensions":["jardiff"]},"application/x-java-jnlp-file":{"source":"apache","compressible":false,"extensions":["jnlp"]},"application/x-javascript":{"compressible":true},"application/x-keepass2":{"extensions":["kdbx"]},"application/x-latex":{"source":"apache","compressible":false,"extensions":["latex"]},"application/x-lua-bytecode":{"extensions":["luac"]},"application/x-lzh-compressed":{"source":"apache","extensions":["lzh","lha"]},"application/x-makeself":{"source":"nginx","extensions":["run"]},"application/x-mie":{"source":"apache","extensions":["mie"]},"application/x-mobipocket-ebook":{"source":"apache","extensions":["prc","mobi"]},"application/x-mpegurl":{"compressible":false},"application/x-ms-application":{"source":"apache","extensions":["application"]},"application/x-ms-shortcut":{"source":"apache","extensions":["lnk"]},"application/x-ms-wmd":{"source":"apache","extensions":["wmd"]},"application/x-ms-wmz":{"source":"apache","extensions":["wmz"]},"application/x-ms-xbap":{"source":"apache","extensions":["xbap"]},"application/x-msaccess":{"source":"apache","extensions":["mdb"]},"application/x-msbinder":{"source":"apache","extensions":["obd"]},"application/x-mscardfile":{"source":"apache","extensions":["crd"]},"application/x-msclip":{"source":"apache","extensions":["clp"]},"application/x-msdos-program":{"extensions":["exe"]},"application/x-msdownload":{"source":"apache","extensions":["exe","dll","com","bat","msi"]},"application/x-msmediaview":{"source":"apache","extensions":["mvb","m13","m14"]},"application/x-msmetafile":{"source":"apache","extensions":["wmf","wmz","emf","emz"]},"application/x-msmoney":{"source":"apache","extensions":["mny"]},"application/x-mspublisher":{"source":"apache","extensions":["pub"]},"application/x-msschedule":{"source":"apache","extensions":["scd"]},"application/x-msterminal":{"source":"apache","extensions":["trm"]},"application/x-mswrite":{"source":"apache","extensions":["wri"]},"application/x-netcdf":{"source":"apache","extensions":["nc","cdf"]},"application/x-ns-proxy-autoconfig":{"compressible":true,"extensions":["pac"]},"application/x-nzb":{"source":"apache","extensions":["nzb"]},"application/x-perl":{"source":"nginx","extensions":["pl","pm"]},"application/x-pilot":{"source":"nginx","extensions":["prc","pdb"]},"application/x-pkcs12":{"source":"apache","compressible":false,"extensions":["p12","pfx"]},"application/x-pkcs7-certificates":{"source":"apache","extensions":["p7b","spc"]},"application/x-pkcs7-certreqresp":{"source":"apache","extensions":["p7r"]},"application/x-pki-message":{"source":"iana"},"application/x-rar-compressed":{"source":"apache","compressible":false,"extensions":["rar"]},"application/x-redhat-package-manager":{"source":"nginx","extensions":["rpm"]},"application/x-research-info-systems":{"source":"apache","extensions":["ris"]},"application/x-sea":{"source":"nginx","extensions":["sea"]},"application/x-sh":{"source":"apache","compressible":true,"extensions":["sh"]},"application/x-shar":{"source":"apache","extensions":["shar"]},"application/x-shockwave-flash":{"source":"apache","compressible":false,"extensions":["swf"]},"application/x-silverlight-app":{"source":"apache","extensions":["xap"]},"application/x-sql":{"source":"apache","extensions":["sql"]},"application/x-stuffit":{"source":"apache","compressible":false,"extensions":["sit"]},"application/x-stuffitx":{"source":"apache","extensions":["sitx"]},"application/x-subrip":{"source":"apache","extensions":["srt"]},"application/x-sv4cpio":{"source":"apache","extensions":["sv4cpio"]},"application/x-sv4crc":{"source":"apache","extensions":["sv4crc"]},"application/x-t3vm-image":{"source":"apache","extensions":["t3"]},"application/x-tads":{"source":"apache","extensions":["gam"]},"application/x-tar":{"source":"apache","compressible":true,"extensions":["tar"]},"application/x-tcl":{"source":"apache","extensions":["tcl","tk"]},"application/x-tex":{"source":"apache","extensions":["tex"]},"application/x-tex-tfm":{"source":"apache","extensions":["tfm"]},"application/x-texinfo":{"source":"apache","extensions":["texinfo","texi"]},"application/x-tgif":{"source":"apache","extensions":["obj"]},"application/x-ustar":{"source":"apache","extensions":["ustar"]},"application/x-virtualbox-hdd":{"compressible":true,"extensions":["hdd"]},"application/x-virtualbox-ova":{"compressible":true,"extensions":["ova"]},"application/x-virtualbox-ovf":{"compressible":true,"extensions":["ovf"]},"application/x-virtualbox-vbox":{"compressible":true,"extensions":["vbox"]},"application/x-virtualbox-vbox-extpack":{"compressible":false,"extensions":["vbox-extpack"]},"application/x-virtualbox-vdi":{"compressible":true,"extensions":["vdi"]},"application/x-virtualbox-vhd":{"compressible":true,"extensions":["vhd"]},"application/x-virtualbox-vmdk":{"compressible":true,"extensions":["vmdk"]},"application/x-wais-source":{"source":"apache","extensions":["src"]},"application/x-web-app-manifest+json":{"compressible":true,"extensions":["webapp"]},"application/x-www-form-urlencoded":{"source":"iana","compressible":true},"application/x-x509-ca-cert":{"source":"iana","extensions":["der","crt","pem"]},"application/x-x509-ca-ra-cert":{"source":"iana"},"application/x-x509-next-ca-cert":{"source":"iana"},"application/x-xfig":{"source":"apache","extensions":["fig"]},"application/x-xliff+xml":{"source":"apache","compressible":true,"extensions":["xlf"]},"application/x-xpinstall":{"source":"apache","compressible":false,"extensions":["xpi"]},"application/x-xz":{"source":"apache","extensions":["xz"]},"application/x-zmachine":{"source":"apache","extensions":["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{"source":"iana"},"application/xacml+xml":{"source":"iana","compressible":true},"application/xaml+xml":{"source":"apache","compressible":true,"extensions":["xaml"]},"application/xcap-att+xml":{"source":"iana","compressible":true,"extensions":["xav"]},"application/xcap-caps+xml":{"source":"iana","compressible":true,"extensions":["xca"]},"application/xcap-diff+xml":{"source":"iana","compressible":true,"extensions":["xdf"]},"application/xcap-el+xml":{"source":"iana","compressible":true,"extensions":["xel"]},"application/xcap-error+xml":{"source":"iana","compressible":true},"application/xcap-ns+xml":{"source":"iana","compressible":true,"extensions":["xns"]},"application/xcon-conference-info+xml":{"source":"iana","compressible":true},"application/xcon-conference-info-diff+xml":{"source":"iana","compressible":true},"application/xenc+xml":{"source":"iana","compressible":true,"extensions":["xenc"]},"application/xhtml+xml":{"source":"iana","compressible":true,"extensions":["xhtml","xht"]},"application/xhtml-voice+xml":{"source":"apache","compressible":true},"application/xliff+xml":{"source":"iana","compressible":true,"extensions":["xlf"]},"application/xml":{"source":"iana","compressible":true,"extensions":["xml","xsl","xsd","rng"]},"application/xml-dtd":{"source":"iana","compressible":true,"extensions":["dtd"]},"application/xml-external-parsed-entity":{"source":"iana"},"application/xml-patch+xml":{"source":"iana","compressible":true},"application/xmpp+xml":{"source":"iana","compressible":true},"application/xop+xml":{"source":"iana","compressible":true,"extensions":["xop"]},"application/xproc+xml":{"source":"apache","compressible":true,"extensions":["xpl"]},"application/xslt+xml":{"source":"iana","compressible":true,"extensions":["xsl","xslt"]},"application/xspf+xml":{"source":"apache","compressible":true,"extensions":["xspf"]},"application/xv+xml":{"source":"iana","compressible":true,"extensions":["mxml","xhvml","xvml","xvm"]},"application/yang":{"source":"iana","extensions":["yang"]},"application/yang-data+json":{"source":"iana","compressible":true},"application/yang-data+xml":{"source":"iana","compressible":true},"application/yang-patch+json":{"source":"iana","compressible":true},"application/yang-patch+xml":{"source":"iana","compressible":true},"application/yin+xml":{"source":"iana","compressible":true,"extensions":["yin"]},"application/zip":{"source":"iana","compressible":false,"extensions":["zip"]},"application/zlib":{"source":"iana"},"application/zstd":{"source":"iana"},"audio/1d-interleaved-parityfec":{"source":"iana"},"audio/32kadpcm":{"source":"iana"},"audio/3gpp":{"source":"iana","compressible":false,"extensions":["3gpp"]},"audio/3gpp2":{"source":"iana"},"audio/aac":{"source":"iana"},"audio/ac3":{"source":"iana"},"audio/adpcm":{"source":"apache","extensions":["adp"]},"audio/amr":{"source":"iana","extensions":["amr"]},"audio/amr-wb":{"source":"iana"},"audio/amr-wb+":{"source":"iana"},"audio/aptx":{"source":"iana"},"audio/asc":{"source":"iana"},"audio/atrac-advanced-lossless":{"source":"iana"},"audio/atrac-x":{"source":"iana"},"audio/atrac3":{"source":"iana"},"audio/basic":{"source":"iana","compressible":false,"extensions":["au","snd"]},"audio/bv16":{"source":"iana"},"audio/bv32":{"source":"iana"},"audio/clearmode":{"source":"iana"},"audio/cn":{"source":"iana"},"audio/dat12":{"source":"iana"},"audio/dls":{"source":"iana"},"audio/dsr-es201108":{"source":"iana"},"audio/dsr-es202050":{"source":"iana"},"audio/dsr-es202211":{"source":"iana"},"audio/dsr-es202212":{"source":"iana"},"audio/dv":{"source":"iana"},"audio/dvi4":{"source":"iana"},"audio/eac3":{"source":"iana"},"audio/encaprtp":{"source":"iana"},"audio/evrc":{"source":"iana"},"audio/evrc-qcp":{"source":"iana"},"audio/evrc0":{"source":"iana"},"audio/evrc1":{"source":"iana"},"audio/evrcb":{"source":"iana"},"audio/evrcb0":{"source":"iana"},"audio/evrcb1":{"source":"iana"},"audio/evrcnw":{"source":"iana"},"audio/evrcnw0":{"source":"iana"},"audio/evrcnw1":{"source":"iana"},"audio/evrcwb":{"source":"iana"},"audio/evrcwb0":{"source":"iana"},"audio/evrcwb1":{"source":"iana"},"audio/evs":{"source":"iana"},"audio/flexfec":{"source":"iana"},"audio/fwdred":{"source":"iana"},"audio/g711-0":{"source":"iana"},"audio/g719":{"source":"iana"},"audio/g722":{"source":"iana"},"audio/g7221":{"source":"iana"},"audio/g723":{"source":"iana"},"audio/g726-16":{"source":"iana"},"audio/g726-24":{"source":"iana"},"audio/g726-32":{"source":"iana"},"audio/g726-40":{"source":"iana"},"audio/g728":{"source":"iana"},"audio/g729":{"source":"iana"},"audio/g7291":{"source":"iana"},"audio/g729d":{"source":"iana"},"audio/g729e":{"source":"iana"},"audio/gsm":{"source":"iana"},"audio/gsm-efr":{"source":"iana"},"audio/gsm-hr-08":{"source":"iana"},"audio/ilbc":{"source":"iana"},"audio/ip-mr_v2.5":{"source":"iana"},"audio/isac":{"source":"apache"},"audio/l16":{"source":"iana"},"audio/l20":{"source":"iana"},"audio/l24":{"source":"iana","compressible":false},"audio/l8":{"source":"iana"},"audio/lpc":{"source":"iana"},"audio/melp":{"source":"iana"},"audio/melp1200":{"source":"iana"},"audio/melp2400":{"source":"iana"},"audio/melp600":{"source":"iana"},"audio/mhas":{"source":"iana"},"audio/midi":{"source":"apache","extensions":["mid","midi","kar","rmi"]},"audio/mobile-xmf":{"source":"iana","extensions":["mxmf"]},"audio/mp3":{"compressible":false,"extensions":["mp3"]},"audio/mp4":{"source":"iana","compressible":false,"extensions":["m4a","mp4a"]},"audio/mp4a-latm":{"source":"iana"},"audio/mpa":{"source":"iana"},"audio/mpa-robust":{"source":"iana"},"audio/mpeg":{"source":"iana","compressible":false,"extensions":["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{"source":"iana"},"audio/musepack":{"source":"apache"},"audio/ogg":{"source":"iana","compressible":false,"extensions":["oga","ogg","spx","opus"]},"audio/opus":{"source":"iana"},"audio/parityfec":{"source":"iana"},"audio/pcma":{"source":"iana"},"audio/pcma-wb":{"source":"iana"},"audio/pcmu":{"source":"iana"},"audio/pcmu-wb":{"source":"iana"},"audio/prs.sid":{"source":"iana"},"audio/qcelp":{"source":"iana"},"audio/raptorfec":{"source":"iana"},"audio/red":{"source":"iana"},"audio/rtp-enc-aescm128":{"source":"iana"},"audio/rtp-midi":{"source":"iana"},"audio/rtploopback":{"source":"iana"},"audio/rtx":{"source":"iana"},"audio/s3m":{"source":"apache","extensions":["s3m"]},"audio/scip":{"source":"iana"},"audio/silk":{"source":"apache","extensions":["sil"]},"audio/smv":{"source":"iana"},"audio/smv-qcp":{"source":"iana"},"audio/smv0":{"source":"iana"},"audio/sofa":{"source":"iana"},"audio/sp-midi":{"source":"iana"},"audio/speex":{"source":"iana"},"audio/t140c":{"source":"iana"},"audio/t38":{"source":"iana"},"audio/telephone-event":{"source":"iana"},"audio/tetra_acelp":{"source":"iana"},"audio/tetra_acelp_bb":{"source":"iana"},"audio/tone":{"source":"iana"},"audio/tsvcis":{"source":"iana"},"audio/uemclip":{"source":"iana"},"audio/ulpfec":{"source":"iana"},"audio/usac":{"source":"iana"},"audio/vdvi":{"source":"iana"},"audio/vmr-wb":{"source":"iana"},"audio/vnd.3gpp.iufp":{"source":"iana"},"audio/vnd.4sb":{"source":"iana"},"audio/vnd.audiokoz":{"source":"iana"},"audio/vnd.celp":{"source":"iana"},"audio/vnd.cisco.nse":{"source":"iana"},"audio/vnd.cmles.radio-events":{"source":"iana"},"audio/vnd.cns.anp1":{"source":"iana"},"audio/vnd.cns.inf1":{"source":"iana"},"audio/vnd.dece.audio":{"source":"iana","extensions":["uva","uvva"]},"audio/vnd.digital-winds":{"source":"iana","extensions":["eol"]},"audio/vnd.dlna.adts":{"source":"iana"},"audio/vnd.dolby.heaac.1":{"source":"iana"},"audio/vnd.dolby.heaac.2":{"source":"iana"},"audio/vnd.dolby.mlp":{"source":"iana"},"audio/vnd.dolby.mps":{"source":"iana"},"audio/vnd.dolby.pl2":{"source":"iana"},"audio/vnd.dolby.pl2x":{"source":"iana"},"audio/vnd.dolby.pl2z":{"source":"iana"},"audio/vnd.dolby.pulse.1":{"source":"iana"},"audio/vnd.dra":{"source":"iana","extensions":["dra"]},"audio/vnd.dts":{"source":"iana","extensions":["dts"]},"audio/vnd.dts.hd":{"source":"iana","extensions":["dtshd"]},"audio/vnd.dts.uhd":{"source":"iana"},"audio/vnd.dvb.file":{"source":"iana"},"audio/vnd.everad.plj":{"source":"iana"},"audio/vnd.hns.audio":{"source":"iana"},"audio/vnd.lucent.voice":{"source":"iana","extensions":["lvp"]},"audio/vnd.ms-playready.media.pya":{"source":"iana","extensions":["pya"]},"audio/vnd.nokia.mobile-xmf":{"source":"iana"},"audio/vnd.nortel.vbk":{"source":"iana"},"audio/vnd.nuera.ecelp4800":{"source":"iana","extensions":["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{"source":"iana","extensions":["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{"source":"iana","extensions":["ecelp9600"]},"audio/vnd.octel.sbc":{"source":"iana"},"audio/vnd.presonus.multitrack":{"source":"iana"},"audio/vnd.qcelp":{"source":"iana"},"audio/vnd.rhetorex.32kadpcm":{"source":"iana"},"audio/vnd.rip":{"source":"iana","extensions":["rip"]},"audio/vnd.rn-realaudio":{"compressible":false},"audio/vnd.sealedmedia.softseal.mpeg":{"source":"iana"},"audio/vnd.vmx.cvsd":{"source":"iana"},"audio/vnd.wave":{"compressible":false},"audio/vorbis":{"source":"iana","compressible":false},"audio/vorbis-config":{"source":"iana"},"audio/wav":{"compressible":false,"extensions":["wav"]},"audio/wave":{"compressible":false,"extensions":["wav"]},"audio/webm":{"source":"apache","compressible":false,"extensions":["weba"]},"audio/x-aac":{"source":"apache","compressible":false,"extensions":["aac"]},"audio/x-aiff":{"source":"apache","extensions":["aif","aiff","aifc"]},"audio/x-caf":{"source":"apache","compressible":false,"extensions":["caf"]},"audio/x-flac":{"source":"apache","extensions":["flac"]},"audio/x-m4a":{"source":"nginx","extensions":["m4a"]},"audio/x-matroska":{"source":"apache","extensions":["mka"]},"audio/x-mpegurl":{"source":"apache","extensions":["m3u"]},"audio/x-ms-wax":{"source":"apache","extensions":["wax"]},"audio/x-ms-wma":{"source":"apache","extensions":["wma"]},"audio/x-pn-realaudio":{"source":"apache","extensions":["ram","ra"]},"audio/x-pn-realaudio-plugin":{"source":"apache","extensions":["rmp"]},"audio/x-realaudio":{"source":"nginx","extensions":["ra"]},"audio/x-tta":{"source":"apache"},"audio/x-wav":{"source":"apache","extensions":["wav"]},"audio/xm":{"source":"apache","extensions":["xm"]},"chemical/x-cdx":{"source":"apache","extensions":["cdx"]},"chemical/x-cif":{"source":"apache","extensions":["cif"]},"chemical/x-cmdf":{"source":"apache","extensions":["cmdf"]},"chemical/x-cml":{"source":"apache","extensions":["cml"]},"chemical/x-csml":{"source":"apache","extensions":["csml"]},"chemical/x-pdb":{"source":"apache"},"chemical/x-xyz":{"source":"apache","extensions":["xyz"]},"font/collection":{"source":"iana","extensions":["ttc"]},"font/otf":{"source":"iana","compressible":true,"extensions":["otf"]},"font/sfnt":{"source":"iana"},"font/ttf":{"source":"iana","compressible":true,"extensions":["ttf"]},"font/woff":{"source":"iana","extensions":["woff"]},"font/woff2":{"source":"iana","extensions":["woff2"]},"image/aces":{"source":"iana","extensions":["exr"]},"image/apng":{"compressible":false,"extensions":["apng"]},"image/avci":{"source":"iana","extensions":["avci"]},"image/avcs":{"source":"iana","extensions":["avcs"]},"image/avif":{"source":"iana","compressible":false,"extensions":["avif"]},"image/bmp":{"source":"iana","compressible":true,"extensions":["bmp"]},"image/cgm":{"source":"iana","extensions":["cgm"]},"image/dicom-rle":{"source":"iana","extensions":["drle"]},"image/emf":{"source":"iana","extensions":["emf"]},"image/fits":{"source":"iana","extensions":["fits"]},"image/g3fax":{"source":"iana","extensions":["g3"]},"image/gif":{"source":"iana","compressible":false,"extensions":["gif"]},"image/heic":{"source":"iana","extensions":["heic"]},"image/heic-sequence":{"source":"iana","extensions":["heics"]},"image/heif":{"source":"iana","extensions":["heif"]},"image/heif-sequence":{"source":"iana","extensions":["heifs"]},"image/hej2k":{"source":"iana","extensions":["hej2"]},"image/hsj2":{"source":"iana","extensions":["hsj2"]},"image/ief":{"source":"iana","extensions":["ief"]},"image/jls":{"source":"iana","extensions":["jls"]},"image/jp2":{"source":"iana","compressible":false,"extensions":["jp2","jpg2"]},"image/jpeg":{"source":"iana","compressible":false,"extensions":["jpeg","jpg","jpe"]},"image/jph":{"source":"iana","extensions":["jph"]},"image/jphc":{"source":"iana","extensions":["jhc"]},"image/jpm":{"source":"iana","compressible":false,"extensions":["jpm"]},"image/jpx":{"source":"iana","compressible":false,"extensions":["jpx","jpf"]},"image/jxr":{"source":"iana","extensions":["jxr"]},"image/jxra":{"source":"iana","extensions":["jxra"]},"image/jxrs":{"source":"iana","extensions":["jxrs"]},"image/jxs":{"source":"iana","extensions":["jxs"]},"image/jxsc":{"source":"iana","extensions":["jxsc"]},"image/jxsi":{"source":"iana","extensions":["jxsi"]},"image/jxss":{"source":"iana","extensions":["jxss"]},"image/ktx":{"source":"iana","extensions":["ktx"]},"image/ktx2":{"source":"iana","extensions":["ktx2"]},"image/naplps":{"source":"iana"},"image/pjpeg":{"compressible":false},"image/png":{"source":"iana","compressible":false,"extensions":["png"]},"image/prs.btif":{"source":"iana","extensions":["btif"]},"image/prs.pti":{"source":"iana","extensions":["pti"]},"image/pwg-raster":{"source":"iana"},"image/sgi":{"source":"apache","extensions":["sgi"]},"image/svg+xml":{"source":"iana","compressible":true,"extensions":["svg","svgz"]},"image/t38":{"source":"iana","extensions":["t38"]},"image/tiff":{"source":"iana","compressible":false,"extensions":["tif","tiff"]},"image/tiff-fx":{"source":"iana","extensions":["tfx"]},"image/vnd.adobe.photoshop":{"source":"iana","compressible":true,"extensions":["psd"]},"image/vnd.airzip.accelerator.azv":{"source":"iana","extensions":["azv"]},"image/vnd.cns.inf2":{"source":"iana"},"image/vnd.dece.graphic":{"source":"iana","extensions":["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{"source":"iana","extensions":["djvu","djv"]},"image/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"image/vnd.dwg":{"source":"iana","extensions":["dwg"]},"image/vnd.dxf":{"source":"iana","extensions":["dxf"]},"image/vnd.fastbidsheet":{"source":"iana","extensions":["fbs"]},"image/vnd.fpx":{"source":"iana","extensions":["fpx"]},"image/vnd.fst":{"source":"iana","extensions":["fst"]},"image/vnd.fujixerox.edmics-mmr":{"source":"iana","extensions":["mmr"]},"image/vnd.fujixerox.edmics-rlc":{"source":"iana","extensions":["rlc"]},"image/vnd.globalgraphics.pgb":{"source":"iana"},"image/vnd.microsoft.icon":{"source":"iana","compressible":true,"extensions":["ico"]},"image/vnd.mix":{"source":"iana"},"image/vnd.mozilla.apng":{"source":"iana"},"image/vnd.ms-dds":{"compressible":true,"extensions":["dds"]},"image/vnd.ms-modi":{"source":"iana","extensions":["mdi"]},"image/vnd.ms-photo":{"source":"apache","extensions":["wdp"]},"image/vnd.net-fpx":{"source":"iana","extensions":["npx"]},"image/vnd.pco.b16":{"source":"iana","extensions":["b16"]},"image/vnd.radiance":{"source":"iana"},"image/vnd.sealed.png":{"source":"iana"},"image/vnd.sealedmedia.softseal.gif":{"source":"iana"},"image/vnd.sealedmedia.softseal.jpg":{"source":"iana"},"image/vnd.svf":{"source":"iana"},"image/vnd.tencent.tap":{"source":"iana","extensions":["tap"]},"image/vnd.valve.source.texture":{"source":"iana","extensions":["vtf"]},"image/vnd.wap.wbmp":{"source":"iana","extensions":["wbmp"]},"image/vnd.xiff":{"source":"iana","extensions":["xif"]},"image/vnd.zbrush.pcx":{"source":"iana","extensions":["pcx"]},"image/webp":{"source":"apache","extensions":["webp"]},"image/wmf":{"source":"iana","extensions":["wmf"]},"image/x-3ds":{"source":"apache","extensions":["3ds"]},"image/x-cmu-raster":{"source":"apache","extensions":["ras"]},"image/x-cmx":{"source":"apache","extensions":["cmx"]},"image/x-freehand":{"source":"apache","extensions":["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{"source":"apache","compressible":true,"extensions":["ico"]},"image/x-jng":{"source":"nginx","extensions":["jng"]},"image/x-mrsid-image":{"source":"apache","extensions":["sid"]},"image/x-ms-bmp":{"source":"nginx","compressible":true,"extensions":["bmp"]},"image/x-pcx":{"source":"apache","extensions":["pcx"]},"image/x-pict":{"source":"apache","extensions":["pic","pct"]},"image/x-portable-anymap":{"source":"apache","extensions":["pnm"]},"image/x-portable-bitmap":{"source":"apache","extensions":["pbm"]},"image/x-portable-graymap":{"source":"apache","extensions":["pgm"]},"image/x-portable-pixmap":{"source":"apache","extensions":["ppm"]},"image/x-rgb":{"source":"apache","extensions":["rgb"]},"image/x-tga":{"source":"apache","extensions":["tga"]},"image/x-xbitmap":{"source":"apache","extensions":["xbm"]},"image/x-xcf":{"compressible":false},"image/x-xpixmap":{"source":"apache","extensions":["xpm"]},"image/x-xwindowdump":{"source":"apache","extensions":["xwd"]},"message/cpim":{"source":"iana"},"message/delivery-status":{"source":"iana"},"message/disposition-notification":{"source":"iana","extensions":["disposition-notification"]},"message/external-body":{"source":"iana"},"message/feedback-report":{"source":"iana"},"message/global":{"source":"iana","extensions":["u8msg"]},"message/global-delivery-status":{"source":"iana","extensions":["u8dsn"]},"message/global-disposition-notification":{"source":"iana","extensions":["u8mdn"]},"message/global-headers":{"source":"iana","extensions":["u8hdr"]},"message/http":{"source":"iana","compressible":false},"message/imdn+xml":{"source":"iana","compressible":true},"message/news":{"source":"iana"},"message/partial":{"source":"iana","compressible":false},"message/rfc822":{"source":"iana","compressible":true,"extensions":["eml","mime"]},"message/s-http":{"source":"iana"},"message/sip":{"source":"iana"},"message/sipfrag":{"source":"iana"},"message/tracking-status":{"source":"iana"},"message/vnd.si.simp":{"source":"iana"},"message/vnd.wfa.wsc":{"source":"iana","extensions":["wsc"]},"model/3mf":{"source":"iana","extensions":["3mf"]},"model/e57":{"source":"iana"},"model/gltf+json":{"source":"iana","compressible":true,"extensions":["gltf"]},"model/gltf-binary":{"source":"iana","compressible":true,"extensions":["glb"]},"model/iges":{"source":"iana","compressible":false,"extensions":["igs","iges"]},"model/mesh":{"source":"iana","compressible":false,"extensions":["msh","mesh","silo"]},"model/mtl":{"source":"iana","extensions":["mtl"]},"model/obj":{"source":"iana","extensions":["obj"]},"model/step":{"source":"iana"},"model/step+xml":{"source":"iana","compressible":true,"extensions":["stpx"]},"model/step+zip":{"source":"iana","compressible":false,"extensions":["stpz"]},"model/step-xml+zip":{"source":"iana","compressible":false,"extensions":["stpxz"]},"model/stl":{"source":"iana","extensions":["stl"]},"model/vnd.collada+xml":{"source":"iana","compressible":true,"extensions":["dae"]},"model/vnd.dwf":{"source":"iana","extensions":["dwf"]},"model/vnd.flatland.3dml":{"source":"iana"},"model/vnd.gdl":{"source":"iana","extensions":["gdl"]},"model/vnd.gs-gdl":{"source":"apache"},"model/vnd.gs.gdl":{"source":"iana"},"model/vnd.gtw":{"source":"iana","extensions":["gtw"]},"model/vnd.moml+xml":{"source":"iana","compressible":true},"model/vnd.mts":{"source":"iana","extensions":["mts"]},"model/vnd.opengex":{"source":"iana","extensions":["ogex"]},"model/vnd.parasolid.transmit.binary":{"source":"iana","extensions":["x_b"]},"model/vnd.parasolid.transmit.text":{"source":"iana","extensions":["x_t"]},"model/vnd.pytha.pyox":{"source":"iana"},"model/vnd.rosette.annotated-data-model":{"source":"iana"},"model/vnd.sap.vds":{"source":"iana","extensions":["vds"]},"model/vnd.usdz+zip":{"source":"iana","compressible":false,"extensions":["usdz"]},"model/vnd.valve.source.compiled-map":{"source":"iana","extensions":["bsp"]},"model/vnd.vtu":{"source":"iana","extensions":["vtu"]},"model/vrml":{"source":"iana","compressible":false,"extensions":["wrl","vrml"]},"model/x3d+binary":{"source":"apache","compressible":false,"extensions":["x3db","x3dbz"]},"model/x3d+fastinfoset":{"source":"iana","extensions":["x3db"]},"model/x3d+vrml":{"source":"apache","compressible":false,"extensions":["x3dv","x3dvz"]},"model/x3d+xml":{"source":"iana","compressible":true,"extensions":["x3d","x3dz"]},"model/x3d-vrml":{"source":"iana","extensions":["x3dv"]},"multipart/alternative":{"source":"iana","compressible":false},"multipart/appledouble":{"source":"iana"},"multipart/byteranges":{"source":"iana"},"multipart/digest":{"source":"iana"},"multipart/encrypted":{"source":"iana","compressible":false},"multipart/form-data":{"source":"iana","compressible":false},"multipart/header-set":{"source":"iana"},"multipart/mixed":{"source":"iana"},"multipart/multilingual":{"source":"iana"},"multipart/parallel":{"source":"iana"},"multipart/related":{"source":"iana","compressible":false},"multipart/report":{"source":"iana"},"multipart/signed":{"source":"iana","compressible":false},"multipart/vnd.bint.med-plus":{"source":"iana"},"multipart/voice-message":{"source":"iana"},"multipart/x-mixed-replace":{"source":"iana"},"text/1d-interleaved-parityfec":{"source":"iana"},"text/cache-manifest":{"source":"iana","compressible":true,"extensions":["appcache","manifest"]},"text/calendar":{"source":"iana","extensions":["ics","ifb"]},"text/calender":{"compressible":true},"text/cmd":{"compressible":true},"text/coffeescript":{"extensions":["coffee","litcoffee"]},"text/cql":{"source":"iana"},"text/cql-expression":{"source":"iana"},"text/cql-identifier":{"source":"iana"},"text/css":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["css"]},"text/csv":{"source":"iana","compressible":true,"extensions":["csv"]},"text/csv-schema":{"source":"iana"},"text/directory":{"source":"iana"},"text/dns":{"source":"iana"},"text/ecmascript":{"source":"iana"},"text/encaprtp":{"source":"iana"},"text/enriched":{"source":"iana"},"text/fhirpath":{"source":"iana"},"text/flexfec":{"source":"iana"},"text/fwdred":{"source":"iana"},"text/gff3":{"source":"iana"},"text/grammar-ref-list":{"source":"iana"},"text/html":{"source":"iana","compressible":true,"extensions":["html","htm","shtml"]},"text/jade":{"extensions":["jade"]},"text/javascript":{"source":"iana","compressible":true},"text/jcr-cnd":{"source":"iana"},"text/jsx":{"compressible":true,"extensions":["jsx"]},"text/less":{"compressible":true,"extensions":["less"]},"text/markdown":{"source":"iana","compressible":true,"extensions":["markdown","md"]},"text/mathml":{"source":"nginx","extensions":["mml"]},"text/mdx":{"compressible":true,"extensions":["mdx"]},"text/mizar":{"source":"iana"},"text/n3":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["n3"]},"text/parameters":{"source":"iana","charset":"UTF-8"},"text/parityfec":{"source":"iana"},"text/plain":{"source":"iana","compressible":true,"extensions":["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{"source":"iana","charset":"UTF-8"},"text/prs.fallenstein.rst":{"source":"iana"},"text/prs.lines.tag":{"source":"iana","extensions":["dsc"]},"text/prs.prop.logic":{"source":"iana"},"text/raptorfec":{"source":"iana"},"text/red":{"source":"iana"},"text/rfc822-headers":{"source":"iana"},"text/richtext":{"source":"iana","compressible":true,"extensions":["rtx"]},"text/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"text/rtp-enc-aescm128":{"source":"iana"},"text/rtploopback":{"source":"iana"},"text/rtx":{"source":"iana"},"text/sgml":{"source":"iana","extensions":["sgml","sgm"]},"text/shaclc":{"source":"iana"},"text/shex":{"source":"iana","extensions":["shex"]},"text/slim":{"extensions":["slim","slm"]},"text/spdx":{"source":"iana","extensions":["spdx"]},"text/strings":{"source":"iana"},"text/stylus":{"extensions":["stylus","styl"]},"text/t140":{"source":"iana"},"text/tab-separated-values":{"source":"iana","compressible":true,"extensions":["tsv"]},"text/troff":{"source":"iana","extensions":["t","tr","roff","man","me","ms"]},"text/turtle":{"source":"iana","charset":"UTF-8","extensions":["ttl"]},"text/ulpfec":{"source":"iana"},"text/uri-list":{"source":"iana","compressible":true,"extensions":["uri","uris","urls"]},"text/vcard":{"source":"iana","compressible":true,"extensions":["vcard"]},"text/vnd.a":{"source":"iana"},"text/vnd.abc":{"source":"iana"},"text/vnd.ascii-art":{"source":"iana"},"text/vnd.curl":{"source":"iana","extensions":["curl"]},"text/vnd.curl.dcurl":{"source":"apache","extensions":["dcurl"]},"text/vnd.curl.mcurl":{"source":"apache","extensions":["mcurl"]},"text/vnd.curl.scurl":{"source":"apache","extensions":["scurl"]},"text/vnd.debian.copyright":{"source":"iana","charset":"UTF-8"},"text/vnd.dmclientscript":{"source":"iana"},"text/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"text/vnd.esmertec.theme-descriptor":{"source":"iana","charset":"UTF-8"},"text/vnd.familysearch.gedcom":{"source":"iana","extensions":["ged"]},"text/vnd.ficlab.flt":{"source":"iana"},"text/vnd.fly":{"source":"iana","extensions":["fly"]},"text/vnd.fmi.flexstor":{"source":"iana","extensions":["flx"]},"text/vnd.gml":{"source":"iana"},"text/vnd.graphviz":{"source":"iana","extensions":["gv"]},"text/vnd.hans":{"source":"iana"},"text/vnd.hgl":{"source":"iana"},"text/vnd.in3d.3dml":{"source":"iana","extensions":["3dml"]},"text/vnd.in3d.spot":{"source":"iana","extensions":["spot"]},"text/vnd.iptc.newsml":{"source":"iana"},"text/vnd.iptc.nitf":{"source":"iana"},"text/vnd.latex-z":{"source":"iana"},"text/vnd.motorola.reflex":{"source":"iana"},"text/vnd.ms-mediapackage":{"source":"iana"},"text/vnd.net2phone.commcenter.command":{"source":"iana"},"text/vnd.radisys.msml-basic-layout":{"source":"iana"},"text/vnd.senx.warpscript":{"source":"iana"},"text/vnd.si.uricatalogue":{"source":"iana"},"text/vnd.sosi":{"source":"iana"},"text/vnd.sun.j2me.app-descriptor":{"source":"iana","charset":"UTF-8","extensions":["jad"]},"text/vnd.trolltech.linguist":{"source":"iana","charset":"UTF-8"},"text/vnd.wap.si":{"source":"iana"},"text/vnd.wap.sl":{"source":"iana"},"text/vnd.wap.wml":{"source":"iana","extensions":["wml"]},"text/vnd.wap.wmlscript":{"source":"iana","extensions":["wmls"]},"text/vtt":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["vtt"]},"text/x-asm":{"source":"apache","extensions":["s","asm"]},"text/x-c":{"source":"apache","extensions":["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{"source":"nginx","extensions":["htc"]},"text/x-fortran":{"source":"apache","extensions":["f","for","f77","f90"]},"text/x-gwt-rpc":{"compressible":true},"text/x-handlebars-template":{"extensions":["hbs"]},"text/x-java-source":{"source":"apache","extensions":["java"]},"text/x-jquery-tmpl":{"compressible":true},"text/x-lua":{"extensions":["lua"]},"text/x-markdown":{"compressible":true,"extensions":["mkd"]},"text/x-nfo":{"source":"apache","extensions":["nfo"]},"text/x-opml":{"source":"apache","extensions":["opml"]},"text/x-org":{"compressible":true,"extensions":["org"]},"text/x-pascal":{"source":"apache","extensions":["p","pas"]},"text/x-processing":{"compressible":true,"extensions":["pde"]},"text/x-sass":{"extensions":["sass"]},"text/x-scss":{"extensions":["scss"]},"text/x-setext":{"source":"apache","extensions":["etx"]},"text/x-sfv":{"source":"apache","extensions":["sfv"]},"text/x-suse-ymp":{"compressible":true,"extensions":["ymp"]},"text/x-uuencode":{"source":"apache","extensions":["uu"]},"text/x-vcalendar":{"source":"apache","extensions":["vcs"]},"text/x-vcard":{"source":"apache","extensions":["vcf"]},"text/xml":{"source":"iana","compressible":true,"extensions":["xml"]},"text/xml-external-parsed-entity":{"source":"iana"},"text/yaml":{"compressible":true,"extensions":["yaml","yml"]},"video/1d-interleaved-parityfec":{"source":"iana"},"video/3gpp":{"source":"iana","extensions":["3gp","3gpp"]},"video/3gpp-tt":{"source":"iana"},"video/3gpp2":{"source":"iana","extensions":["3g2"]},"video/av1":{"source":"iana"},"video/bmpeg":{"source":"iana"},"video/bt656":{"source":"iana"},"video/celb":{"source":"iana"},"video/dv":{"source":"iana"},"video/encaprtp":{"source":"iana"},"video/ffv1":{"source":"iana"},"video/flexfec":{"source":"iana"},"video/h261":{"source":"iana","extensions":["h261"]},"video/h263":{"source":"iana","extensions":["h263"]},"video/h263-1998":{"source":"iana"},"video/h263-2000":{"source":"iana"},"video/h264":{"source":"iana","extensions":["h264"]},"video/h264-rcdo":{"source":"iana"},"video/h264-svc":{"source":"iana"},"video/h265":{"source":"iana"},"video/iso.segment":{"source":"iana","extensions":["m4s"]},"video/jpeg":{"source":"iana","extensions":["jpgv"]},"video/jpeg2000":{"source":"iana"},"video/jpm":{"source":"apache","extensions":["jpm","jpgm"]},"video/jxsv":{"source":"iana"},"video/mj2":{"source":"iana","extensions":["mj2","mjp2"]},"video/mp1s":{"source":"iana"},"video/mp2p":{"source":"iana"},"video/mp2t":{"source":"iana","extensions":["ts"]},"video/mp4":{"source":"iana","compressible":false,"extensions":["mp4","mp4v","mpg4"]},"video/mp4v-es":{"source":"iana"},"video/mpeg":{"source":"iana","compressible":false,"extensions":["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{"source":"iana"},"video/mpv":{"source":"iana"},"video/nv":{"source":"iana"},"video/ogg":{"source":"iana","compressible":false,"extensions":["ogv"]},"video/parityfec":{"source":"iana"},"video/pointer":{"source":"iana"},"video/quicktime":{"source":"iana","compressible":false,"extensions":["qt","mov"]},"video/raptorfec":{"source":"iana"},"video/raw":{"source":"iana"},"video/rtp-enc-aescm128":{"source":"iana"},"video/rtploopback":{"source":"iana"},"video/rtx":{"source":"iana"},"video/scip":{"source":"iana"},"video/smpte291":{"source":"iana"},"video/smpte292m":{"source":"iana"},"video/ulpfec":{"source":"iana"},"video/vc1":{"source":"iana"},"video/vc2":{"source":"iana"},"video/vnd.cctv":{"source":"iana"},"video/vnd.dece.hd":{"source":"iana","extensions":["uvh","uvvh"]},"video/vnd.dece.mobile":{"source":"iana","extensions":["uvm","uvvm"]},"video/vnd.dece.mp4":{"source":"iana"},"video/vnd.dece.pd":{"source":"iana","extensions":["uvp","uvvp"]},"video/vnd.dece.sd":{"source":"iana","extensions":["uvs","uvvs"]},"video/vnd.dece.video":{"source":"iana","extensions":["uvv","uvvv"]},"video/vnd.directv.mpeg":{"source":"iana"},"video/vnd.directv.mpeg-tts":{"source":"iana"},"video/vnd.dlna.mpeg-tts":{"source":"iana"},"video/vnd.dvb.file":{"source":"iana","extensions":["dvb"]},"video/vnd.fvt":{"source":"iana","extensions":["fvt"]},"video/vnd.hns.video":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.ttsavc":{"source":"iana"},"video/vnd.iptvforum.ttsmpeg2":{"source":"iana"},"video/vnd.motorola.video":{"source":"iana"},"video/vnd.motorola.videop":{"source":"iana"},"video/vnd.mpegurl":{"source":"iana","extensions":["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{"source":"iana","extensions":["pyv"]},"video/vnd.nokia.interleaved-multimedia":{"source":"iana"},"video/vnd.nokia.mp4vr":{"source":"iana"},"video/vnd.nokia.videovoip":{"source":"iana"},"video/vnd.objectvideo":{"source":"iana"},"video/vnd.radgamettools.bink":{"source":"iana"},"video/vnd.radgamettools.smacker":{"source":"iana"},"video/vnd.sealed.mpeg1":{"source":"iana"},"video/vnd.sealed.mpeg4":{"source":"iana"},"video/vnd.sealed.swf":{"source":"iana"},"video/vnd.sealedmedia.softseal.mov":{"source":"iana"},"video/vnd.uvvu.mp4":{"source":"iana","extensions":["uvu","uvvu"]},"video/vnd.vivo":{"source":"iana","extensions":["viv"]},"video/vnd.youtube.yt":{"source":"iana"},"video/vp8":{"source":"iana"},"video/vp9":{"source":"iana"},"video/webm":{"source":"apache","compressible":false,"extensions":["webm"]},"video/x-f4v":{"source":"apache","extensions":["f4v"]},"video/x-fli":{"source":"apache","extensions":["fli"]},"video/x-flv":{"source":"apache","compressible":false,"extensions":["flv"]},"video/x-m4v":{"source":"apache","extensions":["m4v"]},"video/x-matroska":{"source":"apache","compressible":false,"extensions":["mkv","mk3d","mks"]},"video/x-mng":{"source":"apache","extensions":["mng"]},"video/x-ms-asf":{"source":"apache","extensions":["asf","asx"]},"video/x-ms-vob":{"source":"apache","extensions":["vob"]},"video/x-ms-wm":{"source":"apache","extensions":["wm"]},"video/x-ms-wmv":{"source":"apache","compressible":false,"extensions":["wmv"]},"video/x-ms-wmx":{"source":"apache","extensions":["wmx"]},"video/x-ms-wvx":{"source":"apache","extensions":["wvx"]},"video/x-msvideo":{"source":"apache","extensions":["avi"]},"video/x-sgi-movie":{"source":"apache","extensions":["movie"]},"video/x-smv":{"source":"apache","extensions":["smv"]},"x-conference/x-cooltalk":{"source":"apache","extensions":["ice"]},"x-shader/x-fragment":{"compressible":true},"x-shader/x-vertex":{"compressible":true}}'); - -/***/ }), - -/***/ 44784: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"nested":{"Api":{"fields":{"name":{"type":"string","id":1},"methods":{"rule":"repeated","type":"Method","id":2},"options":{"rule":"repeated","type":"Option","id":3},"version":{"type":"string","id":4},"sourceContext":{"type":"SourceContext","id":5},"mixins":{"rule":"repeated","type":"Mixin","id":6},"syntax":{"type":"Syntax","id":7}}},"Method":{"fields":{"name":{"type":"string","id":1},"requestTypeUrl":{"type":"string","id":2},"requestStreaming":{"type":"bool","id":3},"responseTypeUrl":{"type":"string","id":4},"responseStreaming":{"type":"bool","id":5},"options":{"rule":"repeated","type":"Option","id":6},"syntax":{"type":"Syntax","id":7}}},"Mixin":{"fields":{"name":{"type":"string","id":1},"root":{"type":"string","id":2}}},"SourceContext":{"fields":{"fileName":{"type":"string","id":1}}},"Option":{"fields":{"name":{"type":"string","id":1},"value":{"type":"Any","id":2}}},"Syntax":{"values":{"SYNTAX_PROTO2":0,"SYNTAX_PROTO3":1}}}}}}}}'); - -/***/ }), - -/***/ 43571: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"options":{"go_package":"google.golang.org/protobuf/types/descriptorpb","java_package":"com.google.protobuf","java_outer_classname":"DescriptorProtos","csharp_namespace":"Google.Protobuf.Reflection","objc_class_prefix":"GPB","cc_enable_arenas":true,"optimize_for":"SPEED"},"nested":{"FileDescriptorSet":{"edition":"proto2","fields":{"file":{"rule":"repeated","type":"FileDescriptorProto","id":1}},"extensions":[[536000000,536000000]]},"Edition":{"edition":"proto2","values":{"EDITION_UNKNOWN":0,"EDITION_LEGACY":900,"EDITION_PROTO2":998,"EDITION_PROTO3":999,"EDITION_2023":1000,"EDITION_2024":1001,"EDITION_1_TEST_ONLY":1,"EDITION_2_TEST_ONLY":2,"EDITION_99997_TEST_ONLY":99997,"EDITION_99998_TEST_ONLY":99998,"EDITION_99999_TEST_ONLY":99999,"EDITION_MAX":2147483647}},"FileDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"package":{"type":"string","id":2},"dependency":{"rule":"repeated","type":"string","id":3},"publicDependency":{"rule":"repeated","type":"int32","id":10},"weakDependency":{"rule":"repeated","type":"int32","id":11},"optionDependency":{"rule":"repeated","type":"string","id":15},"messageType":{"rule":"repeated","type":"DescriptorProto","id":4},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":5},"service":{"rule":"repeated","type":"ServiceDescriptorProto","id":6},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":7},"options":{"type":"FileOptions","id":8},"sourceCodeInfo":{"type":"SourceCodeInfo","id":9},"syntax":{"type":"string","id":12},"edition":{"type":"Edition","id":14}}},"DescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"field":{"rule":"repeated","type":"FieldDescriptorProto","id":2},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":6},"nestedType":{"rule":"repeated","type":"DescriptorProto","id":3},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":4},"extensionRange":{"rule":"repeated","type":"ExtensionRange","id":5},"oneofDecl":{"rule":"repeated","type":"OneofDescriptorProto","id":8},"options":{"type":"MessageOptions","id":7},"reservedRange":{"rule":"repeated","type":"ReservedRange","id":9},"reservedName":{"rule":"repeated","type":"string","id":10},"visibility":{"type":"SymbolVisibility","id":11}},"nested":{"ExtensionRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2},"options":{"type":"ExtensionRangeOptions","id":3}}},"ReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"ExtensionRangeOptions":{"edition":"proto2","fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999},"declaration":{"rule":"repeated","type":"Declaration","id":2,"options":{"retention":"RETENTION_SOURCE"}},"features":{"type":"FeatureSet","id":50},"verification":{"type":"VerificationState","id":3,"options":{"default":"UNVERIFIED","retention":"RETENTION_SOURCE"}}},"extensions":[[1000,536870911]],"nested":{"Declaration":{"fields":{"number":{"type":"int32","id":1},"fullName":{"type":"string","id":2},"type":{"type":"string","id":3},"reserved":{"type":"bool","id":5},"repeated":{"type":"bool","id":6}},"reserved":[[4,4]]},"VerificationState":{"values":{"DECLARATION":0,"UNVERIFIED":1}}}},"FieldDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":3},"label":{"type":"Label","id":4},"type":{"type":"Type","id":5},"typeName":{"type":"string","id":6},"extendee":{"type":"string","id":2},"defaultValue":{"type":"string","id":7},"oneofIndex":{"type":"int32","id":9},"jsonName":{"type":"string","id":10},"options":{"type":"FieldOptions","id":8},"proto3Optional":{"type":"bool","id":17}},"nested":{"Type":{"values":{"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Label":{"values":{"LABEL_OPTIONAL":1,"LABEL_REPEATED":3,"LABEL_REQUIRED":2}}}},"OneofDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"options":{"type":"OneofOptions","id":2}}},"EnumDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"value":{"rule":"repeated","type":"EnumValueDescriptorProto","id":2},"options":{"type":"EnumOptions","id":3},"reservedRange":{"rule":"repeated","type":"EnumReservedRange","id":4},"reservedName":{"rule":"repeated","type":"string","id":5},"visibility":{"type":"SymbolVisibility","id":6}},"nested":{"EnumReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"EnumValueDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"type":"EnumValueOptions","id":3}}},"ServiceDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"method":{"rule":"repeated","type":"MethodDescriptorProto","id":2},"options":{"type":"ServiceOptions","id":3}}},"MethodDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"inputType":{"type":"string","id":2},"outputType":{"type":"string","id":3},"options":{"type":"MethodOptions","id":4},"clientStreaming":{"type":"bool","id":5},"serverStreaming":{"type":"bool","id":6}}},"FileOptions":{"edition":"proto2","fields":{"javaPackage":{"type":"string","id":1},"javaOuterClassname":{"type":"string","id":8},"javaMultipleFiles":{"type":"bool","id":10},"javaGenerateEqualsAndHash":{"type":"bool","id":20,"options":{"deprecated":true}},"javaStringCheckUtf8":{"type":"bool","id":27},"optimizeFor":{"type":"OptimizeMode","id":9,"options":{"default":"SPEED"}},"goPackage":{"type":"string","id":11},"ccGenericServices":{"type":"bool","id":16},"javaGenericServices":{"type":"bool","id":17},"pyGenericServices":{"type":"bool","id":18},"deprecated":{"type":"bool","id":23},"ccEnableArenas":{"type":"bool","id":31,"options":{"default":true}},"objcClassPrefix":{"type":"string","id":36},"csharpNamespace":{"type":"string","id":37},"swiftPrefix":{"type":"string","id":39},"phpClassPrefix":{"type":"string","id":40},"phpNamespace":{"type":"string","id":41},"phpMetadataNamespace":{"type":"string","id":44},"rubyPackage":{"type":"string","id":45},"features":{"type":"FeatureSet","id":50},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[42,42],[38,38],"php_generic_services"],"nested":{"OptimizeMode":{"values":{"SPEED":1,"CODE_SIZE":2,"LITE_RUNTIME":3}}}},"MessageOptions":{"edition":"proto2","fields":{"messageSetWireFormat":{"type":"bool","id":1},"noStandardDescriptorAccessor":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3},"mapEntry":{"type":"bool","id":7},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":11,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":12},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[4,4],[5,5],[6,6],[8,8],[9,9]]},"FieldOptions":{"edition":"proto2","fields":{"ctype":{"type":"CType","id":1,"options":{"default":"STRING"}},"packed":{"type":"bool","id":2},"jstype":{"type":"JSType","id":6,"options":{"default":"JS_NORMAL"}},"lazy":{"type":"bool","id":5},"unverifiedLazy":{"type":"bool","id":15},"deprecated":{"type":"bool","id":3},"weak":{"type":"bool","id":10,"options":{"deprecated":true}},"debugRedact":{"type":"bool","id":16},"retention":{"type":"OptionRetention","id":17},"targets":{"rule":"repeated","type":"OptionTargetType","id":19},"editionDefaults":{"rule":"repeated","type":"EditionDefault","id":20},"features":{"type":"FeatureSet","id":21},"featureSupport":{"type":"FeatureSupport","id":22},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[4,4],[18,18]],"nested":{"CType":{"values":{"STRING":0,"CORD":1,"STRING_PIECE":2}},"JSType":{"values":{"JS_NORMAL":0,"JS_STRING":1,"JS_NUMBER":2}},"OptionRetention":{"values":{"RETENTION_UNKNOWN":0,"RETENTION_RUNTIME":1,"RETENTION_SOURCE":2}},"OptionTargetType":{"values":{"TARGET_TYPE_UNKNOWN":0,"TARGET_TYPE_FILE":1,"TARGET_TYPE_EXTENSION_RANGE":2,"TARGET_TYPE_MESSAGE":3,"TARGET_TYPE_FIELD":4,"TARGET_TYPE_ONEOF":5,"TARGET_TYPE_ENUM":6,"TARGET_TYPE_ENUM_ENTRY":7,"TARGET_TYPE_SERVICE":8,"TARGET_TYPE_METHOD":9}},"EditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"value":{"type":"string","id":2}}},"FeatureSupport":{"fields":{"editionIntroduced":{"type":"Edition","id":1},"editionDeprecated":{"type":"Edition","id":2},"deprecationWarning":{"type":"string","id":3},"editionRemoved":{"type":"Edition","id":4}}}}},"OneofOptions":{"edition":"proto2","fields":{"features":{"type":"FeatureSet","id":1},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]]},"EnumOptions":{"edition":"proto2","fields":{"allowAlias":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":6,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":7},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[5,5]]},"EnumValueOptions":{"edition":"proto2","fields":{"deprecated":{"type":"bool","id":1},"features":{"type":"FeatureSet","id":2},"debugRedact":{"type":"bool","id":3},"featureSupport":{"type":"FieldOptions.FeatureSupport","id":4},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]]},"ServiceOptions":{"edition":"proto2","fields":{"features":{"type":"FeatureSet","id":34},"deprecated":{"type":"bool","id":33},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]]},"MethodOptions":{"edition":"proto2","fields":{"deprecated":{"type":"bool","id":33},"idempotencyLevel":{"type":"IdempotencyLevel","id":34,"options":{"default":"IDEMPOTENCY_UNKNOWN"}},"features":{"type":"FeatureSet","id":35},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"nested":{"IdempotencyLevel":{"values":{"IDEMPOTENCY_UNKNOWN":0,"NO_SIDE_EFFECTS":1,"IDEMPOTENT":2}}}},"UninterpretedOption":{"edition":"proto2","fields":{"name":{"rule":"repeated","type":"NamePart","id":2},"identifierValue":{"type":"string","id":3},"positiveIntValue":{"type":"uint64","id":4},"negativeIntValue":{"type":"int64","id":5},"doubleValue":{"type":"double","id":6},"stringValue":{"type":"bytes","id":7},"aggregateValue":{"type":"string","id":8}},"nested":{"NamePart":{"fields":{"namePart":{"rule":"required","type":"string","id":1},"isExtension":{"rule":"required","type":"bool","id":2}}}}},"FeatureSet":{"edition":"proto2","fields":{"fieldPresence":{"type":"FieldPresence","id":1,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},"enumType":{"type":"EnumType","id":2,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},"repeatedFieldEncoding":{"type":"RepeatedFieldEncoding","id":3,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},"utf8Validation":{"type":"Utf8Validation","id":4,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},"messageEncoding":{"type":"MessageEncoding","id":5,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_LEGACY","edition_defaults.value":"LENGTH_PREFIXED"}},"jsonFormat":{"type":"JsonFormat","id":6,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}},"enforceNamingStyle":{"type":"EnforceNamingStyle","id":7,"options":{"retention":"RETENTION_SOURCE","targets":"TARGET_TYPE_METHOD","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"STYLE2024"}},"defaultSymbolVisibility":{"type":"VisibilityFeature.DefaultSymbolVisibility","id":8,"options":{"retention":"RETENTION_SOURCE","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"EXPORT_TOP_LEVEL"}}},"extensions":[[1000,9994],[9995,9999],[10000,10000]],"reserved":[[999,999]],"nested":{"FieldPresence":{"values":{"FIELD_PRESENCE_UNKNOWN":0,"EXPLICIT":1,"IMPLICIT":2,"LEGACY_REQUIRED":3}},"EnumType":{"values":{"ENUM_TYPE_UNKNOWN":0,"OPEN":1,"CLOSED":2}},"RepeatedFieldEncoding":{"values":{"REPEATED_FIELD_ENCODING_UNKNOWN":0,"PACKED":1,"EXPANDED":2}},"Utf8Validation":{"values":{"UTF8_VALIDATION_UNKNOWN":0,"VERIFY":2,"NONE":3}},"MessageEncoding":{"values":{"MESSAGE_ENCODING_UNKNOWN":0,"LENGTH_PREFIXED":1,"DELIMITED":2}},"JsonFormat":{"values":{"JSON_FORMAT_UNKNOWN":0,"ALLOW":1,"LEGACY_BEST_EFFORT":2}},"EnforceNamingStyle":{"values":{"ENFORCE_NAMING_STYLE_UNKNOWN":0,"STYLE2024":1,"STYLE_LEGACY":2}},"VisibilityFeature":{"fields":{},"reserved":[[1,536870911]],"nested":{"DefaultSymbolVisibility":{"values":{"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN":0,"EXPORT_ALL":1,"EXPORT_TOP_LEVEL":2,"LOCAL_ALL":3,"STRICT":4}}}}}},"FeatureSetDefaults":{"edition":"proto2","fields":{"defaults":{"rule":"repeated","type":"FeatureSetEditionDefault","id":1},"minimumEdition":{"type":"Edition","id":4},"maximumEdition":{"type":"Edition","id":5}},"nested":{"FeatureSetEditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"overridableFeatures":{"type":"FeatureSet","id":4},"fixedFeatures":{"type":"FeatureSet","id":5}},"reserved":[[1,1],[2,2],"features"]}}},"SourceCodeInfo":{"edition":"proto2","fields":{"location":{"rule":"repeated","type":"Location","id":1}},"extensions":[[536000000,536000000]],"nested":{"Location":{"fields":{"path":{"rule":"repeated","type":"int32","id":1,"options":{"packed":true}},"span":{"rule":"repeated","type":"int32","id":2,"options":{"packed":true}},"leadingComments":{"type":"string","id":3},"trailingComments":{"type":"string","id":4},"leadingDetachedComments":{"rule":"repeated","type":"string","id":6}}}}},"GeneratedCodeInfo":{"edition":"proto2","fields":{"annotation":{"rule":"repeated","type":"Annotation","id":1}},"nested":{"Annotation":{"fields":{"path":{"rule":"repeated","type":"int32","id":1,"options":{"packed":true}},"sourceFile":{"type":"string","id":2},"begin":{"type":"int32","id":3},"end":{"type":"int32","id":4},"semantic":{"type":"Semantic","id":5}},"nested":{"Semantic":{"values":{"NONE":0,"SET":1,"ALIAS":2}}}}}},"SymbolVisibility":{"edition":"proto2","values":{"VISIBILITY_UNSET":0,"VISIBILITY_LOCAL":1,"VISIBILITY_EXPORT":2}}}}}}}}'); - -/***/ }), - -/***/ 73342: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"nested":{"SourceContext":{"fields":{"fileName":{"type":"string","id":1}}}}}}}}}'); - -/***/ }), - -/***/ 58783: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"nested":{"Type":{"fields":{"name":{"type":"string","id":1},"fields":{"rule":"repeated","type":"Field","id":2},"oneofs":{"rule":"repeated","type":"string","id":3},"options":{"rule":"repeated","type":"Option","id":4},"sourceContext":{"type":"SourceContext","id":5},"syntax":{"type":"Syntax","id":6}}},"Field":{"fields":{"kind":{"type":"Kind","id":1},"cardinality":{"type":"Cardinality","id":2},"number":{"type":"int32","id":3},"name":{"type":"string","id":4},"typeUrl":{"type":"string","id":6},"oneofIndex":{"type":"int32","id":7},"packed":{"type":"bool","id":8},"options":{"rule":"repeated","type":"Option","id":9},"jsonName":{"type":"string","id":10},"defaultValue":{"type":"string","id":11}},"nested":{"Kind":{"values":{"TYPE_UNKNOWN":0,"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Cardinality":{"values":{"CARDINALITY_UNKNOWN":0,"CARDINALITY_OPTIONAL":1,"CARDINALITY_REQUIRED":2,"CARDINALITY_REPEATED":3}}}},"Enum":{"fields":{"name":{"type":"string","id":1},"enumvalue":{"rule":"repeated","type":"EnumValue","id":2},"options":{"rule":"repeated","type":"Option","id":3},"sourceContext":{"type":"SourceContext","id":4},"syntax":{"type":"Syntax","id":5}}},"EnumValue":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"rule":"repeated","type":"Option","id":3}}},"Option":{"fields":{"name":{"type":"string","id":1},"value":{"type":"Any","id":2}}},"Syntax":{"values":{"SYNTAX_PROTO2":0,"SYNTAX_PROTO3":1}},"Any":{"fields":{"type_url":{"type":"string","id":1},"value":{"type":"bytes","id":2}}},"SourceContext":{"fields":{"fileName":{"type":"string","id":1}}}}}}}}}'); - -/***/ }), - -/***/ 66674: -/***/ ((module) => { - -"use strict"; -module.exports = {"i8":"1.17.0"}; - -/***/ }), - -/***/ 72020: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]]'); - /***/ }) /******/ }); @@ -160147,7 +79998,7 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(56733); +/******/ var __webpack_exports__ = __nccwpck_require__(6733); /******/ module.exports = __webpack_exports__; /******/ /******/ })() diff --git a/build/cli/lib/protocol/crypto/build/Release/sshcrypto.node b/build/cli/lib/protocol/crypto/build/Release/sshcrypto.node index 320bf0fd..86cad96c 100755 Binary files a/build/cli/lib/protocol/crypto/build/Release/sshcrypto.node and b/build/cli/lib/protocol/crypto/build/Release/sshcrypto.node differ diff --git a/build/cli/runner/cli.d.ts b/build/cli/runner/cli.d.ts deleted file mode 100644 index e0c8ad7a..00000000 --- a/build/cli/runner/cli.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env node -/** - * CLI Entry Point - * - * This script serves as the main entry point for the CLI application. - * It executes the common compiled binary with the provided command line arguments. - */ -export {}; diff --git a/build/cli/runner/github_action.d.ts b/build/cli/runner/github_action.d.ts deleted file mode 100644 index 799fa864..00000000 --- a/build/cli/runner/github_action.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * This script serves as a runner for GitHub Actions, executing the common - * compiled binary with the necessary environment variables. - * - * It sets up environment variables for the GitHub Action, - * including passing through all INPUT_* variables from the parent process. - */ -export {}; diff --git a/build/cli/src/data/model/ai_response_schema.d.ts b/build/cli/src/data/model/ai_response_schema.d.ts new file mode 100644 index 00000000..54adfc1c --- /dev/null +++ b/build/cli/src/data/model/ai_response_schema.d.ts @@ -0,0 +1,31 @@ +/** + * JSON Schema for AiResponse interface + * This schema is used to enforce structured JSON responses from the AI + */ +export declare const AI_RESPONSE_JSON_SCHEMA: { + type: string; + properties: { + text_response: { + type: string; + description: string; + }; + action: { + type: string; + enum: string[]; + description: string; + }; + related_files: { + type: string; + items: { + type: string; + }; + description: string; + }; + complete: { + type: string; + description: string; + }; + }; + required: string[]; + additionalProperties: boolean; +}; diff --git a/build/cli/src/data/model/codebase_analysis_schema.d.ts b/build/cli/src/data/model/codebase_analysis_schema.d.ts new file mode 100644 index 00000000..b2bb7f82 --- /dev/null +++ b/build/cli/src/data/model/codebase_analysis_schema.d.ts @@ -0,0 +1,30 @@ +/** + * JSON Schema for codebase analysis responses + * Used in Step 0 of the thinking process to analyze codebase structure + */ +export declare const CODEBASE_ANALYSIS_JSON_SCHEMA: { + type: string; + description: string; + items: { + type: string; + properties: { + path: { + type: string; + description: string; + }; + description: { + type: string; + description: string; + }; + relationships: { + type: string; + description: string; + items: { + type: string; + }; + }; + }; + required: string[]; + additionalProperties: boolean; + }; +}; diff --git a/build/cli/src/data/model/execution.d.ts b/build/cli/src/data/model/execution.d.ts index 6e382aac..187bf263 100644 --- a/build/cli/src/data/model/execution.d.ts +++ b/build/cli/src/data/model/execution.d.ts @@ -2,7 +2,6 @@ import { Ai } from "./ai"; import { Branches } from "./branches"; import { Commit } from "./commit"; import { Config } from "./config"; -import { DockerConfig } from "./docker_config"; import { Emoji } from "./emoji"; import { Hotfix } from "./hotfix"; import { Images } from "./images"; @@ -50,7 +49,6 @@ export declare class Execution { previousConfiguration: Config | undefined; currentConfiguration: Config; tokenUser: string | undefined; - dockerConfig: DockerConfig; supabaseConfig: SupabaseConfig | undefined; inputs: any | undefined; get eventName(): string; @@ -72,6 +70,6 @@ export declare class Execution { get cleanIssueBranches(): boolean; get commit(): Commit; get runnedByToken(): boolean; - constructor(debug: boolean, dockerConfig: DockerConfig, singleAction: SingleAction, commitPrefixBuilder: string, issue: Issue, pullRequest: PullRequest, emoji: Emoji, giphy: Images, tokens: Tokens, ai: Ai, labels: Labels, issueTypes: IssueTypes, locale: Locale, sizeThresholds: SizeThresholds, branches: Branches, release: Release, hotfix: Hotfix, workflows: Workflows, project: Projects, supabaseConfig: SupabaseConfig | undefined, welcome: Welcome | undefined, inputs: any | undefined); + constructor(debug: boolean, singleAction: SingleAction, commitPrefixBuilder: string, issue: Issue, pullRequest: PullRequest, emoji: Emoji, giphy: Images, tokens: Tokens, ai: Ai, labels: Labels, issueTypes: IssueTypes, locale: Locale, sizeThresholds: SizeThresholds, branches: Branches, release: Release, hotfix: Hotfix, workflows: Workflows, project: Projects, supabaseConfig: SupabaseConfig | undefined, welcome: Welcome | undefined, inputs: any | undefined); setup: () => Promise; } diff --git a/build/cli/src/data/model/single_action.d.ts b/build/cli/src/data/model/single_action.d.ts index 5bffd29a..f58a9c9f 100644 --- a/build/cli/src/data/model/single_action.d.ts +++ b/build/cli/src/data/model/single_action.d.ts @@ -20,13 +20,12 @@ export declare class SingleAction { title: string; changelog: string; get isDeployedAction(): boolean; - get isCompileVectorServerAction(): boolean; - get isVectorAction(): boolean; - get isVectorLocalAction(): boolean; - get isVectorRemovalAction(): boolean; + get isAiCacheAction(): boolean; + get isAiCacheLocalAction(): boolean; get isPublishGithubAction(): boolean; get isCreateReleaseAction(): boolean; get isCreateTagAction(): boolean; + get isThinkAction(): boolean; get enabledSingleAction(): boolean; get validSingleAction(): boolean; get isSingleActionWithoutIssue(): boolean; diff --git a/build/cli/src/data/model/think_response.d.ts b/build/cli/src/data/model/think_response.d.ts new file mode 100644 index 00000000..38b58e15 --- /dev/null +++ b/build/cli/src/data/model/think_response.d.ts @@ -0,0 +1,56 @@ +export interface FileAnalysis { + path: string; + key_findings: string; + relevance: 'high' | 'medium' | 'low'; +} +export interface ProposedChange { + file_path: string; + change_type: 'create' | 'modify' | 'delete' | 'refactor'; + description: string; + suggested_code?: string; + reasoning: string; +} +export interface ThinkResponse { + reasoning: string; + action: 'search_files' | 'read_file' | 'analyze_code' | 'propose_changes' | 'complete' | 'update_todos'; + files_to_search?: string[]; + files_to_read?: string[]; + analyzed_files?: FileAnalysis[]; + proposed_changes?: ProposedChange[]; + todo_updates?: { + create?: Array<{ + content: string; + status?: 'pending' | 'in_progress'; + }>; + update?: Array<{ + id: string; + status?: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + notes?: string; + }>; + }; + complete: boolean; + final_analysis?: string; +} +export interface ThinkStep { + step_number: number; + action: string; + reasoning: string; + files_involved?: string[]; + findings?: string; + timestamp: number; +} +export interface ThinkTodoItem { + id: string; + content: string; + status: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + created_at: number; + updated_at: number; + completed_at?: number; + related_files?: string[]; + related_changes?: string[]; + notes?: string; +} +export interface ThinkTodoList { + items: ThinkTodoItem[]; + last_updated: number; +} diff --git a/build/cli/src/data/model/think_response_schema.d.ts b/build/cli/src/data/model/think_response_schema.d.ts new file mode 100644 index 00000000..d178403d --- /dev/null +++ b/build/cli/src/data/model/think_response_schema.d.ts @@ -0,0 +1,131 @@ +/** + * JSON Schema for ThinkResponse interface + * This schema is used for structured AI reasoning and analysis responses + */ +export declare const THINK_RESPONSE_JSON_SCHEMA: { + type: string; + properties: { + reasoning: { + type: string; + description: string; + }; + action: { + type: string; + enum: string[]; + description: string; + }; + files_to_search: { + type: string; + items: { + type: string; + }; + description: string; + }; + files_to_read: { + type: string; + items: { + type: string; + }; + description: string; + }; + analyzed_files: { + type: string; + items: { + type: string; + properties: { + path: { + type: string; + }; + key_findings: { + type: string; + }; + relevance: { + type: string; + enum: string[]; + }; + }; + required: string[]; + }; + description: string; + }; + proposed_changes: { + type: string; + items: { + type: string; + properties: { + file_path: { + type: string; + }; + change_type: { + type: string; + enum: string[]; + }; + description: { + type: string; + }; + suggested_code: { + type: string; + }; + reasoning: { + type: string; + }; + }; + required: string[]; + }; + description: string; + }; + complete: { + type: string; + description: string; + }; + final_analysis: { + type: string; + description: string; + }; + todo_updates: { + type: string; + description: string; + properties: { + create: { + type: string; + items: { + type: string; + properties: { + content: { + type: string; + }; + status: { + type: string; + enum: string[]; + }; + }; + required: string[]; + }; + description: string; + }; + update: { + type: string; + items: { + type: string; + properties: { + id: { + type: string; + }; + status: { + type: string; + enum: string[]; + }; + notes: { + type: string; + }; + }; + required: string[]; + }; + description: string; + }; + }; + }; + }; + required: string[]; + additionalProperties: boolean; +}; diff --git a/build/cli/src/data/model/tokens.d.ts b/build/cli/src/data/model/tokens.d.ts index f6247503..2e473be2 100644 --- a/build/cli/src/data/model/tokens.d.ts +++ b/build/cli/src/data/model/tokens.d.ts @@ -1,5 +1,4 @@ export declare class Tokens { token: string; - classicToken: string; - constructor(token: string, classicToken: string); + constructor(token: string); } diff --git a/build/cli/src/data/repository/ai_repository.d.ts b/build/cli/src/data/repository/ai_repository.d.ts index e5766b62..16d3a60c 100644 --- a/build/cli/src/data/repository/ai_repository.d.ts +++ b/build/cli/src/data/repository/ai_repository.d.ts @@ -1,5 +1,6 @@ import { Ai } from '../model/ai'; export declare class AiRepository { ask: (ai: Ai, prompt: string) => Promise; - askJson: (ai: Ai, prompt: string) => Promise; + askJson: (ai: Ai, prompt: string, schema?: any, schemaName?: string) => Promise; + askThinkJson: (ai: Ai, prompt: string) => Promise; } diff --git a/build/cli/src/data/repository/cache_repository.d.ts b/build/cli/src/data/repository/cache_repository.d.ts deleted file mode 100644 index 53c64153..00000000 --- a/build/cli/src/data/repository/cache_repository.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -export declare class CacheRepository { - private isGitHubActions; - private ensureCacheDirectory; - /** - * Saves data to the GitHub Actions cache - * @param key The unique key for the cache entry - * @param paths List of file paths to cache - * @returns Promise True if cache was saved successfully - */ - saveCache(key: string, paths: string[]): Promise; - /** - * Retrieves data from the GitHub Actions cache - * @param key The unique key for the cache entry - * @param paths List of file paths to restore - * @returns Promise True if cache was restored successfully - */ - restoreCache(key: string, paths: string[]): Promise; -} diff --git a/build/cli/src/data/repository/file_repository.d.ts b/build/cli/src/data/repository/file_repository.d.ts index ac551a2f..e1698a15 100644 --- a/build/cli/src/data/repository/file_repository.d.ts +++ b/build/cli/src/data/repository/file_repository.d.ts @@ -1,4 +1,3 @@ -import { ChunkedFile } from "../model/chunked_file"; export interface FileTreeNodeWithNoContent { name: string; type: 'file' | 'directory'; @@ -17,9 +16,6 @@ export declare class FileRepository { private isMediaOrPdfFile; getFileContent: (owner: string, repository: string, path: string, token: string, branch: string) => Promise; getRepositoryContent: (owner: string, repository: string, token: string, branch: string, ignoreFiles: string[], progress: (fileName: string) => void, ignoredFiles: (fileName: string) => void) => Promise>; - getChunkedRepositoryContent: (owner: string, repository: string, branch: string, chunkSize: number, token: string, ignoreFiles: string[], progress: (fileName: string) => void, ignoredFiles: (fileName: string) => void) => Promise>; - getChunksByLines: (path: string, content: string, shasum: string, chunkSize: number) => ChunkedFile[]; - getChunksByBlocks: (path: string, content: string, shasum: string, chunkSize: number) => ChunkedFile[]; private shouldIgnoreFile; private extractCodeBlocks; private shouldIgnoreLine; diff --git a/build/cli/src/data/repository/supabase_repository.d.ts b/build/cli/src/data/repository/supabase_repository.d.ts index fdf01749..a9e56edd 100644 --- a/build/cli/src/data/repository/supabase_repository.d.ts +++ b/build/cli/src/data/repository/supabase_repository.d.ts @@ -1,27 +1,61 @@ -import { ChunkedFile } from '../model/chunked_file'; -import { ChunkedFileChunk } from '../model/chunked_file_chunk'; import { SupabaseConfig } from '../model/supabase_config'; +export interface AICachedFileInfo { + owner: string; + repository: string; + branch: string; + file_name: string; + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; + created_at?: string; + last_updated?: string; +} export declare class SupabaseRepository { - private readonly CHUNKS_TABLE; + private readonly AI_FILE_CACHE_TABLE; private readonly MAX_BATCH_SIZE; private readonly DEFAULT_TIMEOUT; private supabase; constructor(config: SupabaseConfig); - setChunkedFile: (owner: string, repository: string, branch: string, chunkedFile: ChunkedFile) => Promise; - removeChunksByShasum: (owner: string, repository: string, branch: string, shasum: string) => Promise; - getChunkedFileByShasum: (owner: string, repository: string, branch: string, type: string, shasum: string) => Promise; - getChunks: (owner: string, repository: string, branch: string, path: string, type: string, index: number) => Promise; - getChunksByShasum: (owner: string, repository: string, branch: string, shasum: string) => Promise; - updateVector: (owner: string, repository: string, branch: string, path: string, index: number, chunkIndex: number, vector: number[]) => Promise; - matchChunks: (owner: string, repository: string, branch: string, type: string, queryEmbedding: number[], matchCount?: number) => Promise; - duplicateChunksByBranch: (owner: string, repository: string, sourceBranch: string, targetBranch: string) => Promise; - removeChunksByBranch: (owner: string, repository: string, branch: string) => Promise; - getDistinctPaths: (owner: string, repository: string, branch: string) => Promise; - removeChunksByPath: (owner: string, repository: string, branch: string, path: string) => Promise; + /** + * Set or update AI file cache entry + * If SHA hasn't changed, this will update the entry + */ + setAIFileCache: (owner: string, repository: string, branch: string, fileInfo: { + file_name: string; + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; + }) => Promise; + /** + * Get AI file cache entry by path + */ + getAIFileCache: (owner: string, repository: string, branch: string, filePath: string) => Promise; + /** + * Get all AI file cache entries for a branch + */ + getAIFileCachesByBranch: (owner: string, repository: string, branch: string) => Promise; + /** + * Remove AI file cache entry by path + */ + removeAIFileCacheByPath: (owner: string, repository: string, branch: string, filePath: string) => Promise; + /** + * Duplicate AI file cache entries from one branch to another + */ + duplicateAIFileCacheByBranch: (owner: string, repository: string, sourceBranch: string, targetBranch: string) => Promise; + /** + * Remove all AI file cache entries for a branch + */ + removeAIFileCacheByBranch: (owner: string, repository: string, branch: string) => Promise; + /** + * Get SHA by path (for checking if file is cached) + */ getShasumByPath: (owner: string, repository: string, branch: string, path: string) => Promise; - private countBranchEntries; - private duplicateFileEntries; - private duplicateBranchEntries; - private deleteBranchEntries; - getVectorOfChunkContent: (owner: string, repository: string, content: string) => Promise; + /** + * Get distinct paths for a branch + */ + getDistinctPaths: (owner: string, repository: string, branch: string) => Promise; } diff --git a/build/cli/src/usecase/actions/prepare_local_vector_server_use_case.d.ts b/build/cli/src/usecase/actions/prepare_local_vector_server_use_case.d.ts deleted file mode 100644 index 9087aec2..00000000 --- a/build/cli/src/usecase/actions/prepare_local_vector_server_use_case.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Execution } from '../../data/model/execution'; -import { Result } from '../../data/model/result'; -import { ParamUseCase } from '../base/param_usecase'; -export declare class PrepareLocalVectorServerUseCase implements ParamUseCase { - taskId: string; - private dockerRepository; - invoke(param: Execution): Promise; -} diff --git a/build/cli/src/usecase/actions/vector_action_removal_use_case.d.ts b/build/cli/src/usecase/actions/vector_action_removal_use_case.d.ts index 5ffdf184..38e75fbe 100644 --- a/build/cli/src/usecase/actions/vector_action_removal_use_case.d.ts +++ b/build/cli/src/usecase/actions/vector_action_removal_use_case.d.ts @@ -4,5 +4,5 @@ import { ParamUseCase } from '../base/param_usecase'; export declare class VectorActionRemovalUseCase implements ParamUseCase { taskId: string; invoke(param: Execution): Promise; - private removeChunksByBranch; + private removeAICacheByBranch; } diff --git a/build/cli/src/usecase/actions/vector_action_use_case.d.ts b/build/cli/src/usecase/actions/vector_action_use_case.d.ts index 5ef0b741..862ba6a4 100644 --- a/build/cli/src/usecase/actions/vector_action_use_case.d.ts +++ b/build/cli/src/usecase/actions/vector_action_use_case.d.ts @@ -3,12 +3,14 @@ import { Result } from '../../data/model/result'; import { ParamUseCase } from '../base/param_usecase'; export declare class VectorActionUseCase implements ParamUseCase { taskId: string; - private dockerRepository; private fileRepository; - private readonly CODE_INSTRUCTION_BLOCK; - private readonly CODE_INSTRUCTION_LINE; + private aiRepository; + private fileImportAnalyzer; + private fileCacheManager; + private codebaseAnalyzer; + constructor(); invoke(param: Execution): Promise; - private checkChunksInSupabase; - private uploadChunksToSupabase; - private duplicateChunksToBranch; + private checkAICacheInSupabase; + private uploadAICacheToSupabase; + private duplicateAICacheToBranch; } diff --git a/build/cli/src/usecase/steps/common/services/codebase_analyzer.d.ts b/build/cli/src/usecase/steps/common/services/codebase_analyzer.d.ts new file mode 100644 index 00000000..5a63f75d --- /dev/null +++ b/build/cli/src/usecase/steps/common/services/codebase_analyzer.d.ts @@ -0,0 +1,37 @@ +import { Execution } from '../../../../data/model/execution'; +import { AiRepository } from '../../../../data/repository/ai_repository'; +import { FileImportAnalyzer } from './file_import_analyzer'; +import { FileCacheManager } from './file_cache_manager'; +export interface FileAnalysisResult { + path: string; + description: string; + consumes: string[]; + consumed_by: string[]; +} +/** + * Service for analyzing codebase structure and generating file descriptions + */ +export declare class CodebaseAnalyzer { + private aiRepository; + private fileImportAnalyzer; + private fileCacheManager; + constructor(aiRepository: AiRepository, fileImportAnalyzer: FileImportAnalyzer, fileCacheManager: FileCacheManager); + /** + * Generate codebase analysis with file descriptions and relationships + * This runs before the main reasoning loop to provide context + * Uses relationship map built from imports + AI descriptions in batches + */ + generateCodebaseAnalysis(param: Execution, repositoryFiles: Map, question: string): Promise; + /** + * Generate basic description from file path (fallback) + */ + generateBasicDescription(path: string): string; + /** + * Generate fallback file descriptions when AI analysis fails + */ + generateFallbackFileDescriptions(files: Array<[string, string]>): FileAnalysisResult[]; + /** + * Format codebase analysis for inclusion in AI context + */ + formatCodebaseAnalysisForContext(analysis: FileAnalysisResult[]): string; +} diff --git a/build/cli/src/usecase/steps/common/services/comment_formatter.d.ts b/build/cli/src/usecase/steps/common/services/comment_formatter.d.ts new file mode 100644 index 00000000..c0013f16 --- /dev/null +++ b/build/cli/src/usecase/steps/common/services/comment_formatter.d.ts @@ -0,0 +1,32 @@ +import { ThinkStep, ProposedChange, FileAnalysis } from '../../../../data/model/think_response'; +import { ThinkTodoManager } from '../think_todo_manager'; +/** + * Service for formatting GitHub comments and code changes + */ +export declare class CommentFormatter { + private readonly GITHUB_COMMENT_MAX_LENGTH; + /** + * Format the complete reasoning comment for GitHub + */ + formatReasoningComment(question: string, description: string, steps: ThinkStep[], analyzedFiles: Map, proposedChanges: ProposedChange[], finalAnalysis: string, totalIterations: number, todoManager: ThinkTodoManager): string; + /** + * Format a single proposed change + */ + formatProposedChange(change: ProposedChange, index: number): string; + /** + * Detect programming language from file path/extension + */ + detectLanguageFromPath(filePath: string): string; + /** + * Get emoji for action type + */ + getActionEmoji(action: string): string; + /** + * Format action name for display + */ + formatActionName(action: string): string; + /** + * Get emoji for change type + */ + getChangeTypeEmoji(changeType: string): string; +} diff --git a/build/cli/src/usecase/steps/common/services/file_cache_manager.d.ts b/build/cli/src/usecase/steps/common/services/file_cache_manager.d.ts new file mode 100644 index 00000000..3ae0e95f --- /dev/null +++ b/build/cli/src/usecase/steps/common/services/file_cache_manager.d.ts @@ -0,0 +1,36 @@ +import { Execution } from '../../../../data/model/execution'; +import { SupabaseRepository } from '../../../../data/repository/supabase_repository'; +import { CachedFileInfo } from './types'; +/** + * Service for managing AI file cache in Supabase + */ +export declare class FileCacheManager { + private supabaseRepository; + /** + * Normalize file path for consistent comparison + * Removes leading ./ and normalizes path separators + */ + private normalizePath; + /** + * Calculate SHA256 hash of file content + */ + calculateFileSHA(content: string): string; + /** + * Initialize Supabase repository if config is available + */ + initSupabaseRepository(param: Execution): SupabaseRepository | null; + /** + * Load cache from Supabase (or return empty map if Supabase not available) + * Uses normalized paths for consistent lookup + */ + loadAICache(param: Execution): Promise>; + /** + * Get cached file info by path (with path normalization) + */ + getCachedFile(cache: Map, filePath: string): CachedFileInfo | undefined; + /** + * Save cache entry to Supabase + * Normalizes paths before saving + */ + saveAICacheEntry(param: Execution, filePath: string, fileInfo: CachedFileInfo, consumes: string[], consumedBy: string[]): Promise; +} diff --git a/build/cli/src/usecase/steps/common/services/file_import_analyzer.d.ts b/build/cli/src/usecase/steps/common/services/file_import_analyzer.d.ts new file mode 100644 index 00000000..f2b5da10 --- /dev/null +++ b/build/cli/src/usecase/steps/common/services/file_import_analyzer.d.ts @@ -0,0 +1,22 @@ +/** + * Service for extracting imports and building file relationship maps + * Supports multiple programming languages + */ +export declare class FileImportAnalyzer { + /** + * Extract imports from a file regardless of programming language + */ + extractImportsFromFile(filePath: string, content: string): string[]; + /** + * Resolve relative import path to absolute path + */ + resolveRelativePath(baseDir: string, relativePath: string): string; + /** + * Build relationship map from all files by extracting imports + * Also builds reverse map (consumed_by) + */ + buildRelationshipMap(repositoryFiles: Map): { + consumes: Map; + consumedBy: Map; + }; +} diff --git a/build/cli/src/usecase/steps/common/services/file_search_service.d.ts b/build/cli/src/usecase/steps/common/services/file_search_service.d.ts new file mode 100644 index 00000000..1a601ce8 --- /dev/null +++ b/build/cli/src/usecase/steps/common/services/file_search_service.d.ts @@ -0,0 +1,13 @@ +/** + * Service for building file indexes and searching files + */ +export declare class FileSearchService { + /** + * Build file index for quick lookup by filename or directory + */ + buildFileIndex(files: Map): Map; + /** + * Search files by search terms (filename, directory, or pattern) + */ + searchFiles(searchTerms: string[], fileIndex: Map): string[]; +} diff --git a/build/cli/src/usecase/steps/common/services/types.d.ts b/build/cli/src/usecase/steps/common/services/types.d.ts new file mode 100644 index 00000000..84a081ba --- /dev/null +++ b/build/cli/src/usecase/steps/common/services/types.d.ts @@ -0,0 +1,14 @@ +/** + * Shared types for codebase analysis services + */ +export interface CachedFileInfo { + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; +} +export interface FileRelationshipMap { + consumes: Map; + consumedBy: Map; +} diff --git a/build/cli/src/usecase/steps/common/think_code_manager.d.ts b/build/cli/src/usecase/steps/common/think_code_manager.d.ts new file mode 100644 index 00000000..465bde74 --- /dev/null +++ b/build/cli/src/usecase/steps/common/think_code_manager.d.ts @@ -0,0 +1,59 @@ +import { ProposedChange } from '../../../data/model/think_response'; +/** + * Manages virtual code state - keeps files in memory and applies proposed changes + * so subsequent reasoning steps can see the accumulated progress + */ +export declare class ThinkCodeManager { + private originalFiles; + private virtualFiles; + private appliedChanges; + private allAppliedChanges; + /** + * Initialize with original repository files + */ + initialize(originalFiles: Map): void; + /** + * Get current state of a file (with applied changes) + */ + getFileContent(filePath: string): string | undefined; + /** + * Get all virtual files + */ + getAllFiles(): Map; + /** + * Check if a file has been modified + */ + isFileModified(filePath: string): boolean; + /** + * Get changes applied to a specific file + */ + getFileChanges(filePath: string): ProposedChange[]; + /** + * Apply a proposed change to the virtual codebase + */ + applyChange(change: ProposedChange): boolean; + /** + * Check if a change has already been applied (to avoid duplicates) + */ + hasChangeBeenApplied(change: ProposedChange): boolean; + /** + * Get summary of all applied changes + */ + getChangesSummary(): string; + /** + * Get context about what has changed for the AI + */ + getContextForAI(): string; + /** + * Simple similarity check for change descriptions + */ + private areSimilar; + /** + * Get statistics + */ + getStats(): { + totalFiles: number; + modifiedFiles: number; + totalChanges: number; + }; +} diff --git a/build/cli/src/usecase/steps/common/think_todo_manager.d.ts b/build/cli/src/usecase/steps/common/think_todo_manager.d.ts new file mode 100644 index 00000000..03857149 --- /dev/null +++ b/build/cli/src/usecase/steps/common/think_todo_manager.d.ts @@ -0,0 +1,70 @@ +import { ThinkTodoItem } from '../../../data/model/think_response'; +import { ProposedChange } from '../../../data/model/think_response'; +/** + * Manages TODO list for the reasoning process + * Similar to how the assistant tracks high-level tasks vs iterative steps + */ +export declare class ThinkTodoManager { + private todos; + private nextId; + /** + * Initialize with optional initial todos + */ + initialize(initialTodos?: Array<{ + content: string; + status?: 'pending' | 'in_progress'; + }>): void; + /** + * Create a new TODO item + */ + createTodo(content: string, status?: 'pending' | 'in_progress'): ThinkTodoItem; + /** + * Update an existing TODO item + */ + updateTodo(id: string, updates: { + status?: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + notes?: string; + related_files?: string[]; + related_changes?: string[]; + }): boolean; + /** + * Get all TODOs + */ + getAllTodos(): ThinkTodoItem[]; + /** + * Get TODOs by status + */ + getTodosByStatus(status: ThinkTodoItem['status']): ThinkTodoItem[]; + /** + * Get active TODOs (pending or in_progress) + */ + getActiveTodos(): ThinkTodoItem[]; + /** + * Get completion statistics + */ + getStats(): { + total: number; + pending: number; + in_progress: number; + completed: number; + cancelled: number; + completion_rate: number; + }; + /** + * Get formatted TODO list for AI context + */ + getContextForAI(): string; + /** + * Link a TODO to proposed changes + */ + linkTodoToChanges(todoId: string, changes: ProposedChange[]): void; + /** + * Auto-update TODO status based on progress + * If changes are applied for a TODO, mark it as in_progress or completed + */ + autoUpdateFromChanges(changes: ProposedChange[]): void; + /** + * Get summary for final report + */ + getSummary(): string; +} diff --git a/build/cli/src/usecase/steps/common/think_use_case.d.ts b/build/cli/src/usecase/steps/common/think_use_case.d.ts new file mode 100644 index 00000000..ead15fe7 --- /dev/null +++ b/build/cli/src/usecase/steps/common/think_use_case.d.ts @@ -0,0 +1,22 @@ +import { Execution } from '../../../data/model/execution'; +import { Result } from '../../../data/model/result'; +import { ParamUseCase } from '../../base/param_usecase'; +export declare class ThinkUseCase implements ParamUseCase { + taskId: string; + private aiRepository; + private fileRepository; + private issueRepository; + private fileImportAnalyzer; + private fileCacheManager; + private codebaseAnalyzer; + private fileSearchService; + private commentFormatter; + private readonly MAX_ITERATIONS; + private readonly MAX_FILES_TO_ANALYZE; + private readonly MAX_CONSECUTIVE_SEARCHES; + constructor(); + invoke(param: Execution): Promise; + private getIssueDescription; + private performReasoningStep; + private generateFinalAnalysis; +} diff --git a/build/cli/src/usecase/steps/issue/prepare_branches_use_case.d.ts b/build/cli/src/usecase/steps/issue/prepare_branches_use_case.d.ts index 1d6abab2..4c0c63ea 100644 --- a/build/cli/src/usecase/steps/issue/prepare_branches_use_case.d.ts +++ b/build/cli/src/usecase/steps/issue/prepare_branches_use_case.d.ts @@ -5,5 +5,5 @@ export declare class PrepareBranchesUseCase implements ParamUseCase; - private duplicateChunksByBranch; + private duplicateAICacheByBranch; } diff --git a/build/cli/src/utils/constants.d.ts b/build/cli/src/utils/constants.d.ts index 3bb23aef..992fd05f 100644 --- a/build/cli/src/utils/constants.d.ts +++ b/build/cli/src/utils/constants.d.ts @@ -1,5 +1,5 @@ -export declare const COMMAND = "git-board-flow"; -export declare const TITLE = "Git Board Flow"; +export declare const COMMAND = "giik"; +export declare const TITLE = "Giik"; export declare const REPO_URL = "https://github.com/landamessenger/git-board-flow"; export declare const DEFAULT_IMAGE_CONFIG: { issue: { @@ -44,18 +44,12 @@ export declare const INPUT_KEYS: { readonly DEBUG: "debug"; readonly WELCOME_TITLE: "welcome-title"; readonly WELCOME_MESSAGES: "welcome-messages"; - readonly DOCKER_CONTAINER_NAME: "docker-container-name"; - readonly DOCKER_DOMAIN: "docker-domain"; - readonly DOCKER_PORT: "docker-port"; - readonly DOCKER_CACHE_OS: "docker-cache-os"; - readonly DOCKER_CACHE_ARCH: "docker-cache-arch"; readonly SINGLE_ACTION: "single-action"; readonly SINGLE_ACTION_ISSUE: "single-action-issue"; readonly SINGLE_ACTION_VERSION: "single-action-version"; readonly SINGLE_ACTION_TITLE: "single-action-title"; readonly SINGLE_ACTION_CHANGELOG: "single-action-changelog"; readonly TOKEN: "token"; - readonly CLASSIC_TOKEN: "classic-token"; readonly OPENROUTER_API_KEY: "openrouter-api-key"; readonly OPENROUTER_MODEL: "openrouter-model"; readonly AI_PULL_REQUEST_DESCRIPTION: "ai-pull-request-description"; @@ -197,11 +191,13 @@ export declare const ERRORS: { }; export declare const ACTIONS: { readonly DEPLOYED: "deployed_action"; - readonly COMPILE_VECTOR_SERVER: "compile_vector_server"; - readonly VECTOR: "vector_action"; - readonly VECTOR_LOCAL: "vector_local"; - readonly VECTOR_REMOVAL: "vector_removal"; + readonly AI_CACHE: "ai_cache_action"; + readonly AI_CACHE_LOCAL: "ai_cache_local_action"; readonly PUBLISH_GITHUB_ACTION: "publish_github_action"; readonly CREATE_RELEASE: "create_release"; readonly CREATE_TAG: "create_tag"; + readonly THINK: "think_action"; +}; +export declare const PROMPTS: { + readonly CODE_BASE_ANALYSIS: "\nYou are a technical code analysis assistant.\n\nYour task is to analyze the content of the following source code file in depth.\n\nProvide a precise and highly technical explanation of what the code does, including:\n- Its main purpose and functionality.\n- A breakdown of the logic and flow (step by step or module by module).\n- How each class, function, or major block interacts with the rest.\n- The technologies, frameworks, or libraries it uses and how.\n- Any relevant algorithms, patterns, or data structures implemented.\n- Potential edge cases, performance considerations, or hidden behaviors.\n- Dependencies and external integrations (APIs, services, databases, etc.).\n- Any implicit assumptions or limitations found in the implementation.\n\nFocus exclusively on *accurate technical analysis and understanding*, not on summarizing in simple language.\n\nDo not propose improvements, changes, or fixes in this stage — your only goal is to explain exactly what the code does and how it works.\n "; }; diff --git a/build/github_action/build/Release/cpufeatures.node b/build/github_action/build/Release/cpufeatures.node index ddb5b2ba..7fc79247 100755 Binary files a/build/github_action/build/Release/cpufeatures.node and b/build/github_action/build/Release/cpufeatures.node differ diff --git a/build/github_action/index.js b/build/github_action/index.js index 7a383b0b..6fb42c3b 100644 --- a/build/github_action/index.js +++ b/build/github_action/index.js @@ -1,7 +1,7 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 87351: +/***/ 7351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -31,7 +31,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(22037)); +const os = __importStar(__nccwpck_require__(2037)); const utils_1 = __nccwpck_require__(5278); /** * Commands @@ -104,7 +104,7 @@ function escapeProperty(s) { /***/ }), -/***/ 42186: +/***/ 2186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -143,12 +143,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(87351); +const command_1 = __nccwpck_require__(7351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const oidc_utils_1 = __nccwpck_require__(98041); +const os = __importStar(__nccwpck_require__(2037)); +const path = __importStar(__nccwpck_require__(1017)); +const oidc_utils_1 = __nccwpck_require__(8041); /** * The code to exit an action */ @@ -433,12 +433,12 @@ exports.getIDToken = getIDToken; /** * Summary exports */ -var summary_1 = __nccwpck_require__(81327); +var summary_1 = __nccwpck_require__(1327); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ -var summary_2 = __nccwpck_require__(81327); +var summary_2 = __nccwpck_require__(1327); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports @@ -450,7 +450,7 @@ Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: funct /** * Platform utilities exports */ -exports.platform = __importStar(__nccwpck_require__(85243)); +exports.platform = __importStar(__nccwpck_require__(5243)); //# sourceMappingURL=core.js.map /***/ }), @@ -489,8 +489,8 @@ exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const crypto = __importStar(__nccwpck_require__(6113)); -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); +const fs = __importStar(__nccwpck_require__(7147)); +const os = __importStar(__nccwpck_require__(2037)); const utils_1 = __nccwpck_require__(5278); function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; @@ -524,7 +524,7 @@ exports.prepareKeyValueMessage = prepareKeyValueMessage; /***/ }), -/***/ 98041: +/***/ 8041: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -540,9 +540,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(96255); -const auth_1 = __nccwpck_require__(35526); -const core_1 = __nccwpck_require__(42186); +const http_client_1 = __nccwpck_require__(6255); +const auth_1 = __nccwpck_require__(5526); +const core_1 = __nccwpck_require__(2186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { @@ -638,7 +638,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(71017)); +const path = __importStar(__nccwpck_require__(1017)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. @@ -677,7 +677,7 @@ exports.toPlatformPath = toPlatformPath; /***/ }), -/***/ 85243: +/***/ 5243: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -719,8 +719,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; -const os_1 = __importDefault(__nccwpck_require__(22037)); -const exec = __importStar(__nccwpck_require__(71514)); +const os_1 = __importDefault(__nccwpck_require__(2037)); +const exec = __importStar(__nccwpck_require__(1514)); const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { silent: true @@ -778,7 +778,7 @@ exports.getDetails = getDetails; /***/ }), -/***/ 81327: +/***/ 1327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -794,8 +794,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(22037); -const fs_1 = __nccwpck_require__(57147); +const os_1 = __nccwpck_require__(2037); +const fs_1 = __nccwpck_require__(7147); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; @@ -1115,7 +1115,7 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 71514: +/***/ 1514: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1150,8 +1150,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(71576); -const tr = __importStar(__nccwpck_require__(88159)); +const string_decoder_1 = __nccwpck_require__(1576); +const tr = __importStar(__nccwpck_require__(8159)); /** * Exec a command. * Output will be streamed to the live console. @@ -1225,7 +1225,7 @@ exports.getExecOutput = getExecOutput; /***/ }), -/***/ 88159: +/***/ 8159: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1260,13 +1260,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const events = __importStar(__nccwpck_require__(82361)); -const child = __importStar(__nccwpck_require__(32081)); -const path = __importStar(__nccwpck_require__(71017)); -const io = __importStar(__nccwpck_require__(47351)); -const ioUtil = __importStar(__nccwpck_require__(81962)); -const timers_1 = __nccwpck_require__(39512); +const os = __importStar(__nccwpck_require__(2037)); +const events = __importStar(__nccwpck_require__(2361)); +const child = __importStar(__nccwpck_require__(2081)); +const path = __importStar(__nccwpck_require__(1017)); +const io = __importStar(__nccwpck_require__(7436)); +const ioUtil = __importStar(__nccwpck_require__(1962)); +const timers_1 = __nccwpck_require__(9512); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* @@ -1850,15 +1850,15 @@ class ExecState extends events.EventEmitter { /***/ }), -/***/ 74087: +/***/ 4087: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Context = void 0; -const fs_1 = __nccwpck_require__(57147); -const os_1 = __nccwpck_require__(22037); +const fs_1 = __nccwpck_require__(7147); +const os_1 = __nccwpck_require__(2037); class Context { /** * Hydrate the context from the environment @@ -1913,7 +1913,7 @@ exports.Context = Context; /***/ }), -/***/ 95438: +/***/ 5438: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1943,8 +1943,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const utils_1 = __nccwpck_require__(73030); +const Context = __importStar(__nccwpck_require__(4087)); +const utils_1 = __nccwpck_require__(3030); exports.context = new Context.Context(); /** * Returns a hydrated octokit ready to use for GitHub Actions @@ -1961,7 +1961,7 @@ exports.getOctokit = getOctokit; /***/ }), -/***/ 47914: +/***/ 7914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2000,8 +2000,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(96255)); -const undici_1 = __nccwpck_require__(41773); +const httpClient = __importStar(__nccwpck_require__(6255)); +const undici_1 = __nccwpck_require__(1773); function getAuthString(token, options) { if (!token && !options.auth) { throw new Error('Parameter token or opts.auth is required'); @@ -2038,7 +2038,7 @@ exports.getApiBaseUrl = getApiBaseUrl; /***/ }), -/***/ 73030: +/***/ 3030: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2068,12 +2068,12 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(74087)); -const Utils = __importStar(__nccwpck_require__(47914)); +const Context = __importStar(__nccwpck_require__(4087)); +const Utils = __importStar(__nccwpck_require__(7914)); // octokit + plugins -const core_1 = __nccwpck_require__(76762); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(83044); -const plugin_paginate_rest_1 = __nccwpck_require__(64193); +const core_1 = __nccwpck_require__(6762); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(3044); +const plugin_paginate_rest_1 = __nccwpck_require__(4193); exports.context = new Context.Context(); const baseUrl = Utils.getApiBaseUrl(); exports.defaults = { @@ -2104,7 +2104,7 @@ exports.getOctokitOptions = getOctokitOptions; /***/ }), -/***/ 35526: +/***/ 5526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -2192,7 +2192,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 96255: +/***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2232,11 +2232,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(13685)); -const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(19835)); -const tunnel = __importStar(__nccwpck_require__(74294)); -const undici_1 = __nccwpck_require__(41773); +const http = __importStar(__nccwpck_require__(3685)); +const https = __importStar(__nccwpck_require__(5687)); +const pm = __importStar(__nccwpck_require__(9835)); +const tunnel = __importStar(__nccwpck_require__(4294)); +const undici_1 = __nccwpck_require__(1773); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -2851,7 +2851,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 19835: +/***/ 9835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -2953,7 +2953,7 @@ class DecodedURL extends URL { /***/ }), -/***/ 81962: +/***/ 1962: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2989,8 +2989,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge var _a; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -const fs = __importStar(__nccwpck_require__(57147)); -const path = __importStar(__nccwpck_require__(71017)); +const fs = __importStar(__nccwpck_require__(7147)); +const path = __importStar(__nccwpck_require__(1017)); _a = fs.promises // export const {open} = 'fs' , exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; @@ -3143,7 +3143,7 @@ exports.getCmdPath = getCmdPath; /***/ }), -/***/ 47351: +/***/ 7436: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -3178,9 +3178,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; -const assert_1 = __nccwpck_require__(39491); -const path = __importStar(__nccwpck_require__(71017)); -const ioUtil = __importStar(__nccwpck_require__(81962)); +const assert_1 = __nccwpck_require__(9491); +const path = __importStar(__nccwpck_require__(1017)); +const ioUtil = __importStar(__nccwpck_require__(1962)); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js @@ -3449,135123 +3449,52932 @@ function copyFile(srcFile, destFile, force) { /***/ }), -/***/ 3358: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 334: +/***/ ((module) => { "use strict"; -/** - * @license - * Copyright 2020 Balena Ltd. - * - * 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. - * - * ------------------------------------------------------------------------ - * - * Copyright 2018 Zeit, Inc. - * Licensed under the MIT License. See file LICENSE.md for a full copy. - * - * ------------------------------------------------------------------------ - */ - -/** - * This module implements the [dockerignore - * spec](https://docs.docker.com/engine/reference/builder/#dockerignore-file), - * closely following Docker's (Moby) Golang implementation: - * https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go - * https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go - * https://github.com/moby/moby/blob/v19.03.8/pkg/archive/archive.go#L825 - * - * Something the spec is not clear about, but we discovered by reading source code - * and testing against the "docker build" command, is the handling of backslashes and - * forward slashes as path separators and escape characters in the .dockerignore file - * across platforms including Windows, Linux and macOS: - * - * * On Linux and macOS, only forward slashes can be used as path separators in the - * .dockerignore file, and the backslash works as an escape character. - * * On Windows, both forward slashes and backslashes are allowed as path separators - * in the .dockerignore file, and the backslash is not used as an escape character. - * - * This is consistent with how Windows works generally: both forward slashes and - * backslashes are accepted as path separators by the cmd.exe Command Prompt or - * PowerShell, and by library functions like the Golang filepath.Clean or the - * Node.js path.normalize. - * - * Similarly, path strings provided to the IgnoreBase.ignores() and IgnoreBase.filter() - * methods can use either forward slashes or backslashes as path separators on Windows, - * but only forward slashes are accepted as path separators on Linux and macOS. - */ - -const path = __nccwpck_require__(71017); - -const factory = options => new IgnoreBase(options); // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L538-L539 -// Fixes typescript module import - - -factory.default = factory; -module.exports = factory; - -function make_array(subject) { - return Array.isArray(subject) ? subject : [subject]; -} - -const REGEX_TRAILING_SLASH = /(?<=.)\/$/; -const REGEX_TRAILING_BACKSLASH = /(?<=.)\\$/; -const REGEX_TRAILING_PATH_SEP = path.sep === '\\' ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH; -const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('dockerignore') : 'dockerignore'; // An implementation of Go's filepath.Clean -// https://golang.org/pkg/path/filepath/#Clean -// https://github.com/golang/go/blob/master/src/path/filepath/path.go -// Note that, like Go, on Windows this function converts forward slashes -// to backslashes. - -function cleanPath(file) { - return path.normalize(file).replace(REGEX_TRAILING_PATH_SEP, ''); -} // Javascript port of Golang's filepath.ToSlash -// https://golang.org/pkg/path/filepath/#ToSlash -// https://github.com/golang/go/blob/master/src/path/filepath/path.go -// Convert any OS-specific path separator to '/'. Backslash is converted -// to forward slash on Windows, but not on Linux/macOS. -// Note that both forward slashes and backslashes are valid path separators on -// Windows. As a result, code such as `pattern.split(path.sep).join('/')` fails -// on Windows when forward slashes are used as path separators. - - -function toSlash(file) { - if (path.sep === '/') { - return file; +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); - return file.replace(/\\/g, '/'); -} // Javascript port of Golang's filepath.FromSlash -// https://github.com/golang/go/blob/master/src/path/filepath/path.go +// 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 + }; +} -function fromSlash(file) { - if (path.sep === '/') { - return file; +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; } - - return file.replace(/\//g, path.sep); + return `token ${token}`; } -class IgnoreBase { - constructor({ - // https://github.com/kaelzhang/node-ignore/blob/5.1.4/index.js#L372 - ignorecase = true - } = {}) { - this._rules = []; - this._ignorecase = ignorecase; - this[KEY_IGNORE] = true; +// 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); +} - this._initCache(); +// 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); - _initCache() { - this._cache = {}; - } // @param {Array.|string|Ignore} pattern - - - add(pattern) { - this._added = false; - - if (typeof pattern === 'string') { - pattern = pattern.split(/\r?\n/g); - } - - make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache(); - } +/***/ }), - return this; - } // legacy +/***/ 6762: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; - addPattern(pattern) { - return this.add(pattern); +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); - _addPattern(pattern) { - // https://github.com/kaelzhang/node-ignore/issues/32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules); - this._added = true; - return; - } - - if (this._checkPattern(pattern)) { - const rule = this._createRule(pattern.trim()); +// pkg/dist-src/index.js +var index_exports = {}; +__export(index_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(index_exports); +var import_universal_user_agent = __nccwpck_require__(5030); +var import_before_after_hook = __nccwpck_require__(3682); +var import_request = __nccwpck_require__(6234); +var import_graphql = __nccwpck_require__(8467); +var import_auth_token = __nccwpck_require__(334); - if (rule !== null) { - this._added = true; +// pkg/dist-src/version.js +var VERSION = "5.2.2"; - this._rules.push(rule); - } - } +// pkg/dist-src/index.js +var noop = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = noop; } - - _checkPattern(pattern) { - // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L34-L40 - return pattern && typeof pattern === 'string' && pattern.indexOf('#') !== 0 && pattern.trim() !== ""; + if (typeof logger.info !== "function") { + logger.info = noop; } - - filter(paths) { - return make_array(paths).filter(path => this._filter(path)); + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; } - - createFilter() { - return path => this._filter(path); + if (typeof logger.error !== "function") { + logger.error = consoleError; } - - ignores(path) { - return !this._filter(path); - } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L41-L53 - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L29-L55 - - - _createRule(pattern) { - const origin = pattern; - let negative = false; // > An optional prefix "!" which negates the pattern; - // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L43-L46 - - if (pattern[0] === '!') { - negative = true; - pattern = pattern.substring(1).trim(); - } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L47-L53 - - - if (pattern.length > 0) { - pattern = cleanPath(pattern); - pattern = toSlash(pattern); - - if (pattern.length > 1 && pattern[0] === '/') { - pattern = pattern.slice(1); + return logger; +} +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 + ) + ); } - } // https://github.com/moby/moby/blob/v19.03.8/builder/dockerignore/dockerignore.go#L54-L55 - - - if (negative) { - pattern = '!' + pattern; - } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L30 - - - pattern = pattern.trim(); - - if (pattern === "") { - return null; - } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L34 - // convert forward slashes to backslashes on Windows - - - pattern = cleanPath(pattern); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L36-L42 - - if (pattern[0] === '!') { - if (pattern.length === 1) { - return 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)) + ); } - - negative = true; - pattern = pattern.substring(1); - } else { - negative = false; - } - - return { - origin, - pattern, - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L54 - dirs: pattern.split(path.sep), - negative }; - } // @returns `Boolean` true if the `path` is NOT ignored - - - _filter(path) { - if (!path) { - return false; + 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 (path in this._cache) { - return this._cache[path]; + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; } - - return this._cache[path] = this._test(path); - } // @returns {Boolean} true if a file is NOT ignored - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L62 - - - _test(file) { - file = fromSlash(file); // equivalent to golang filepath.Dir() https://golang.org/src/path/filepath/path.go - - const parentPath = cleanPath(path.dirname(file)); - const parentPathDirs = parentPath.split(path.sep); - let matched = false; - - this._rules.forEach(rule => { - let match = this._match(file, rule); // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L80 - - - if (!match && parentPath !== ".") { - // Check to see if the pattern matches one of our parent dirs. - if (rule.dirs.includes('**')) { - // Ah shucks! We have to test every possible parent path that has - // a number of dirs _n_ where - // `rule.dirs.filter(doubleStar).length <= _n_ <= parentPathDirs.length` - // since the ** can imply any number of directories including 0 - for (let i = rule.dirs.filter(x => x !== '**').length; i <= parentPathDirs.length; i++) { - match = match || this._match(parentPathDirs.slice(0, i).join(path.sep), rule); - } - } else if (rule.dirs.length <= parentPathDirs.length) { - // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L83 - match = this._match(parentPathDirs.slice(0, rule.dirs.length).join(path.sep), rule); - } + 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 = createLogger(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); - if (match) { - matched = !rule.negative; - } - }); - return !matched; - } // @returns {Boolean} true if a file is matched by a rule +/***/ }), +/***/ 9440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _match(file, rule) { - return this._compile(rule).regexp.test(file); - } // https://github.com/moby/moby/blob/v19.03.8/pkg/fileutils/fileutils.go#L139 +"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); - _compile(rule) { - if (rule.regexp) { - return rule; - } +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); - let regStr = '^'; // Go through the pattern and convert it to a regexp. +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(5030); - let escapedSlash = path.sep === '\\' ? '\\\\' : path.sep; +// pkg/dist-src/version.js +var VERSION = "9.0.6"; - for (let i = 0; i < rule.pattern.length; i++) { - const ch = rule.pattern[i]; +// 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: "" + } +}; - if (ch === '*') { - if (rule.pattern[i + 1] === '*') { - // is some flavor of "**" - i++; // Treat **/ as ** so eat the "/" +// 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; + }, {}); +} - if (rule.pattern[i + 1] === path.sep) { - i++; - } +// 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); +} - if (rule.pattern[i + 1] === undefined) { - // is "**EOF" - to align with .gitignore just accept all - regStr += ".*"; - } else { - // is "**" - // Note that this allows for any # of /'s (even 0) because - // the .* will eat everything, even /'s - regStr += `(.*${escapedSlash})?`; - } - } else { - // is "*" so map it to anything but "/" - regStr += `[^${escapedSlash}]*`; - } - } else if (ch === '?') { - // "?" is any char except "/" - regStr += `[^${escapedSlash}]`; - } else if (ch === '.' || ch === '$') { - // Escape some regexp special chars that have no meaning - // in golang's filepath.Match - regStr += `\\${ch}`; - } else if (ch === '\\') { - // escape next char. Note that a trailing \ in the pattern - // will be left alone (but need to escape it) - if (path.sep === '\\') { - // On windows map "\" to "\\", meaning an escaped backslash, - // and then just continue because filepath.Match on - // Windows doesn't allow escaping at all - regStr += escapedSlash; - continue; - } - - if (rule.pattern[i + 1] !== undefined) { - regStr += '\\' + rule.pattern[i + 1]; - i++; - } else { - regStr += '\\'; - } - } else { - regStr += ch; - } +// 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; +} - regStr += "$"; - rule.regexp = new RegExp(regStr, this._ignorecase ? 'i' : ''); - return rule; +// 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; } - -/***/ }), - -/***/ 8258: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.registerAdminService = registerAdminService; -exports.addAdminServicesToServer = addAdminServicesToServer; -const registeredAdminServices = []; -function registerAdminService(getServiceDefinition, getHandlers) { - registeredAdminServices.push({ getServiceDefinition, getHandlers }); -} -function addAdminServicesToServer(server) { - for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { - server.addService(getServiceDefinition(), getHandlers()); +// 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; } -//# sourceMappingURL=admin.js.map - -/***/ }), - -/***/ 34186: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// 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("&"); +} -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BackoffTimeout = void 0; -const constants_1 = __nccwpck_require__(90634); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'backoff'; -const INITIAL_BACKOFF_MS = 1000; -const BACKOFF_MULTIPLIER = 1.6; -const MAX_BACKOFF_MS = 120000; -const BACKOFF_JITTER = 0.2; -/** - * Get a number uniformly at random in the range [min, max) - * @param min - * @param max - */ -function uniformRandom(min, max) { - return Math.random() * (max - min) + min; +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? { }, 0); - clearTimeout(this.timerId); - } - static getNextId() { - return this.nextId++; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '{' + this.id + '} ' + text); +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]; } - runTimer(delay) { - var _a, _b; - this.trace('runTimer(delay=' + delay + ')'); - this.endTime = this.startTime; - this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); - clearTimeout(this.timerId); - this.timerId = setTimeout(() => { - this.trace('timer fired'); - this.running = false; - this.callback(); - }, delay); - if (!this.hasRef) { - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Call the callback after the current amount of delay time - */ - runOnce() { - this.trace('runOnce()'); - this.running = true; - this.startTime = new Date(); - this.runTimer(this.nextDelay); - const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); - const jitterMagnitude = nextBackoff * this.jitter; - this.nextDelay = - nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); - } - /** - * Stop the timer. The callback will not be called until `runOnce` is called - * again. - */ - stop() { - this.trace('stop()'); - clearTimeout(this.timerId); - this.running = false; - } - /** - * Reset the delay time to its initial value. If the timer is still running, - * retroactively apply that reset to the current timer. - */ - reset() { - this.trace('reset() running=' + this.running); - this.nextDelay = this.initialDelay; - if (this.running) { - const now = new Date(); - const newEndTime = this.startTime; - newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); - clearTimeout(this.timerId); - if (now < newEndTime) { - this.runTimer(newEndTime.getTime() - now.getTime()); - } - else { - this.running = false; - } - } - } - /** - * Check whether the timer is currently running. - */ - isRunning() { - return this.running; - } - /** - * Set that while the timer is running, it should keep the Node process - * running. - */ - ref() { - var _a, _b; - this.hasRef = true; - (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Set that while the timer is running, it should not keep the Node process - * running. - */ - unref() { - var _a, _b; - this.hasRef = false; - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Get the approximate timestamp of when the timer will fire. Only valid if - * this.isRunning() is true. - */ - getEndTime() { - return this.endTime; + } + 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(""); } -exports.BackoffTimeout = BackoffTimeout; -BackoffTimeout.nextId = 0; -//# sourceMappingURL=backoff-timeout.js.map - -/***/ }), - -/***/ 21426: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CallCredentials = void 0; -const metadata_1 = __nccwpck_require__(83665); -function isCurrentOauth2Client(client) { - return ('getRequestHeaders' in client && - typeof client.getRequestHeaders === 'function'); +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); } -/** - * A class that represents a generic method of adding authentication-related - * metadata on a per-request basis. - */ -class CallCredentials { - /** - * Creates a new CallCredentials object from a given function that generates - * Metadata objects. - * @param metadataGenerator A function that accepts a set of options, and - * generates a Metadata object based on these options, which is passed back - * to the caller via a supplied (err, metadata) callback. - */ - static createFromMetadataGenerator(metadataGenerator) { - return new SingleCallCredentials(metadataGenerator); - } - /** - * Create a gRPC credential from a Google credential object. - * @param googleCredentials The authentication client to use. - * @return The resulting CallCredentials object. - */ - static createFromGoogleCredential(googleCredentials) { - return CallCredentials.createFromMetadataGenerator((options, callback) => { - let getHeaders; - if (isCurrentOauth2Client(googleCredentials)) { - getHeaders = googleCredentials.getRequestHeaders(options.service_url); - } - else { - getHeaders = new Promise((resolve, reject) => { - googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { - if (err) { - reject(err); - return; - } - if (!headers) { - reject(new Error('Headers not set by metadata plugin')); - return; - } - resolve(headers); - }); - }); - } - getHeaders.then(headers => { - const metadata = new metadata_1.Metadata(); - for (const key of Object.keys(headers)) { - metadata.add(key, headers[key]); - } - callback(null, metadata); - }, err => { - callback(err); - }); - }); - } - static createEmpty() { - return new EmptyCallCredentials(); - } +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } } -exports.CallCredentials = CallCredentials; -class ComposedCallCredentials extends CallCredentials { - constructor(creds) { - super(); - this.creds = creds; - } - async generateMetadata(options) { - const base = new metadata_1.Metadata(); - const generated = await Promise.all(this.creds.map(cred => cred.generateMetadata(options))); - for (const gen of generated) { - base.merge(gen); - } - return base; - } - compose(other) { - return new ComposedCallCredentials(this.creds.concat([other])); - } - _equals(other) { - if (this === other) { - return true; +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)); + } + }); } - if (other instanceof ComposedCallCredentials) { - return this.creds.every((value, index) => value._equals(other.creds[index])); + } 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())); + } + }); } - else { - return false; + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); } + } } -} -class SingleCallCredentials extends CallCredentials { - constructor(metadataGenerator) { - super(); - this.metadataGenerator = metadataGenerator; - } - generateMetadata(options) { - return new Promise((resolve, reject) => { - this.metadataGenerator(options, (err, metadata) => { - if (metadata !== undefined) { - resolve(metadata); - } - else { - reject(err); - } - }); - }); - } - compose(other) { - return new ComposedCallCredentials([this, other]); + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof SingleCallCredentials) { - return this.metadataGenerator === other.metadataGenerator; + } + 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); } - else { - return false; + 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(/\/$/, ""); + } } -class EmptyCallCredentials extends CallCredentials { - generateMetadata(options) { - return Promise.resolve(new metadata_1.Metadata()); + +// 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(","); } - compose(other) { - return other; + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } } - _equals(other) { - return other instanceof EmptyCallCredentials; + } + 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 + ); } -//# sourceMappingURL=call-credentials.js.map -/***/ }), +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} -/***/ 78710: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// 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 + }); +} -"use strict"; +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InterceptingListenerImpl = void 0; -exports.statusOrFromValue = statusOrFromValue; -exports.statusOrFromError = statusOrFromError; -exports.isInterceptingListener = isInterceptingListener; -const metadata_1 = __nccwpck_require__(83665); -function statusOrFromValue(value) { - return { - ok: true, - value: value - }; -} -function statusOrFromError(error) { - var _a; - return { - ok: false, - error: Object.assign(Object.assign({}, error), { metadata: (_a = error.metadata) !== null && _a !== void 0 ? _a : new metadata_1.Metadata() }) - }; -} -function isInterceptingListener(listener) { - return (listener.onReceiveMetadata !== undefined && - listener.onReceiveMetadata.length === 1); -} -class InterceptingListenerImpl { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.processingMessage = false; - this.pendingStatus = null; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextListener.onReceiveStatus(this.pendingStatus); - } - } - onReceiveMetadata(metadata) { - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, metadata => { - this.processingMetadata = false; - this.nextListener.onReceiveMetadata(metadata); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - /* If this listener processes messages asynchronously, the last message may - * be reordered with respect to the status */ - this.processingMessage = true; - this.listener.onReceiveMessage(message, msg => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } - else { - this.nextListener.onReceiveMessage(msg); - this.processPendingStatus(); - } - }); - } - onReceiveStatus(status) { - this.listener.onReceiveStatus(status, processedStatus => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = processedStatus; - } - else { - this.nextListener.onReceiveStatus(processedStatus); - } - }); - } -} -exports.InterceptingListenerImpl = InterceptingListenerImpl; -//# sourceMappingURL=call-interface.js.map /***/ }), -/***/ 70380: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8467: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getNextCallNumber = getNextCallNumber; -let nextCallNumber = 0; -function getNextCallNumber() { - return nextCallNumber++; -} -//# sourceMappingURL=call-number.js.map +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 index_exports = {}; +__export(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest +}); +module.exports = __toCommonJS(index_exports); +var import_request3 = __nccwpck_require__(6234); +var import_universal_user_agent = __nccwpck_require__(5030); -/***/ 97453: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// pkg/dist-src/version.js +var VERSION = "7.1.1"; -"use strict"; +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(6234); -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = void 0; -exports.callErrorFromStatus = callErrorFromStatus; -const events_1 = __nccwpck_require__(82361); -const stream_1 = __nccwpck_require__(12781); -const constants_1 = __nccwpck_require__(90634); -/** - * Construct a ServiceError from a StatusObject. This function exists primarily - * as an attempt to make the error stack trace clearly communicate that the - * error is not necessarily a problem in gRPC itself. - * @param status - */ -function callErrorFromStatus(status, callerStack) { - const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; - const error = new Error(message); - const stack = `${error.stack}\nfor call at\n${callerStack}`; - return Object.assign(new Error(message), status, { stack }); +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(6234); + +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); } -class ClientUnaryCallImpl extends events_1.EventEmitter { - constructor() { - super(); - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; +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); } -} -exports.ClientUnaryCallImpl = ClientUnaryCallImpl; -class ClientReadableStreamImpl extends stream_1.Readable { - constructor(deserialize) { - super({ objectMode: true }); - this.deserialize = deserialize; + } +}; + +// 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`) + ); } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + 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` + ) + ); } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + 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; } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; + if (!result.variables) { + result.variables = {}; } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + 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; + }); } -exports.ClientReadableStreamImpl = ClientReadableStreamImpl; -class ClientWritableStreamImpl extends stream_1.Writable { - constructor(serialize) { - super({ objectMode: true }); - this.serialize = serialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _write(chunk, encoding, cb) { - var _a; - const context = { - callback: cb, - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } + +// 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 + }); } -exports.ClientWritableStreamImpl = ClientWritableStreamImpl; -class ClientDuplexStreamImpl extends stream_1.Duplex { - constructor(serialize, deserialize) { - super({ objectMode: true }); - this.serialize = serialize; - this.deserialize = deserialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); - } - _write(chunk, encoding, cb) { - var _a; - const context = { - callback: cb, - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } + +// 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" + }); } -exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl; -//# sourceMappingURL=call.js.map +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + /***/ }), -/***/ 25649: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4193: +/***/ ((module) => { "use strict"; -/* - * Copyright 2024 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FileWatcherCertificateProvider = void 0; -const fs = __nccwpck_require__(57147); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const util_1 = __nccwpck_require__(73837); -const TRACER_NAME = 'certificate_provider'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const readFilePromise = (0, util_1.promisify)(fs.readFile); -class FileWatcherCertificateProvider { - constructor(config) { - this.config = config; - this.refreshTimer = null; - this.fileResultPromise = null; - this.latestCaUpdate = undefined; - this.caListeners = new Set(); - this.latestIdentityUpdate = undefined; - this.identityListeners = new Set(); - this.lastUpdateTime = null; - if ((config.certificateFile === undefined) !== (config.privateKeyFile === undefined)) { - throw new Error('certificateFile and privateKeyFile must be set or unset together'); - } - if (config.certificateFile === undefined && config.caCertificateFile === undefined) { - throw new Error('At least one of certificateFile and caCertificateFile must be set'); - } - trace('File watcher constructed with config ' + JSON.stringify(config)); - } - updateCertificates() { - if (this.fileResultPromise) { - return; - } - this.fileResultPromise = Promise.allSettled([ - this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), - this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), - this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() - ]); - this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { - if (!this.refreshTimer) { - return; - } - trace('File watcher read certificates certificate ' + certificateResult.status + ', privateKey ' + privateKeyResult.status + ', CA certificate ' + caCertificateResult.status); - this.lastUpdateTime = new Date(); - this.fileResultPromise = null; - if (certificateResult.status === 'fulfilled' && privateKeyResult.status === 'fulfilled') { - this.latestIdentityUpdate = { - certificate: certificateResult.value, - privateKey: privateKeyResult.value - }; - } - else { - this.latestIdentityUpdate = null; - } - if (caCertificateResult.status === 'fulfilled') { - this.latestCaUpdate = { - caCertificate: caCertificateResult.value - }; - } - else { - this.latestCaUpdate = null; - } - for (const listener of this.identityListeners) { - listener(this.latestIdentityUpdate); - } - for (const listener of this.caListeners) { - listener(this.latestCaUpdate); - } - }); - trace('File watcher initiated certificate update'); - } - maybeStartWatchingFiles() { - if (!this.refreshTimer) { - /* Perform the first read immediately, but only if there was not already - * a recent read, to avoid reading from the filesystem significantly more - * frequently than configured if the provider quickly switches between - * used and unused. */ - const timeSinceLastUpdate = this.lastUpdateTime ? (new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity; - if (timeSinceLastUpdate > this.config.refreshIntervalMs) { - this.updateCertificates(); - } - if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { - // Clear out old updates if they are definitely stale - this.latestCaUpdate = undefined; - this.latestIdentityUpdate = undefined; - } - this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); - trace('File watcher started watching'); - } - } - maybeStopWatchingFiles() { - if (this.caListeners.size === 0 && this.identityListeners.size === 0) { - this.fileResultPromise = null; - if (this.refreshTimer) { - clearInterval(this.refreshTimer); - this.refreshTimer = null; - } - } - } - addCaCertificateListener(listener) { - this.caListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestCaUpdate !== undefined) { - process.nextTick(listener, this.latestCaUpdate); - } - } - removeCaCertificateListener(listener) { - this.caListeners.delete(listener); - this.maybeStopWatchingFiles(); - } - addIdentityCertificateListener(listener) { - this.identityListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestIdentityUpdate !== undefined) { - process.nextTick(listener, this.latestIdentityUpdate); - } - } - removeIdentityCertificateListener(listener) { - this.identityListeners.delete(listener); - this.maybeStopWatchingFiles(); - } -} -exports.FileWatcherCertificateProvider = FileWatcherCertificateProvider; -//# sourceMappingURL=certificate-provider.js.map - -/***/ }), +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); -/***/ 44030: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composePaginateRest: () => composePaginateRest, + isPaginatingEndpoint: () => isPaginatingEndpoint, + paginateRest: () => paginateRest, + paginatingEndpoints: () => paginatingEndpoints +}); +module.exports = __toCommonJS(dist_src_exports); -"use strict"; +// pkg/dist-src/version.js +var VERSION = "9.2.2"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChannelCredentials = void 0; -exports.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials; -const tls_1 = __nccwpck_require__(24404); -const call_credentials_1 = __nccwpck_require__(21426); -const tls_helpers_1 = __nccwpck_require__(86581); -const uri_parser_1 = __nccwpck_require__(65974); -const resolver_1 = __nccwpck_require__(31594); -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function verifyIsBufferOrNull(obj, friendlyName) { - if (obj && !(obj instanceof Buffer)) { - throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); - } -} -/** - * A class that contains credentials for communicating over a channel, as well - * as a set of per-call credentials, which are applied to every method call made - * over a channel initialized with an instance of this class. - */ -class ChannelCredentials { - /** - * Returns a copy of this object with the included set of per-call credentials - * expanded to include callCredentials. - * @param callCredentials A CallCredentials object to associate with this - * instance. - */ - compose(callCredentials) { - return new ComposedChannelCredentialsImpl(this, callCredentials); - } - /** - * Return a new ChannelCredentials instance with a given set of credentials. - * The resulting instance can be used to construct a Channel that communicates - * over TLS. - * @param rootCerts The root certificate data. - * @param privateKey The client certificate private key, if available. - * @param certChain The client certificate key chain, if available. - * @param verifyOptions Additional options to modify certificate verification - */ - static createSsl(rootCerts, privateKey, certChain, verifyOptions) { - var _a; - verifyIsBufferOrNull(rootCerts, 'Root certificate'); - verifyIsBufferOrNull(privateKey, 'Private key'); - verifyIsBufferOrNull(certChain, 'Certificate chain'); - if (privateKey && !certChain) { - throw new Error('Private key must be given with accompanying certificate chain'); - } - if (!privateKey && certChain) { - throw new Error('Certificate chain must be given with accompanying private key'); - } - const secureContext = (0, tls_1.createSecureContext)({ - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, - key: privateKey !== null && privateKey !== void 0 ? privateKey : undefined, - cert: certChain !== null && certChain !== void 0 ? certChain : undefined, - ciphers: tls_helpers_1.CIPHER_SUITES, - }); - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with credentials created using - * the provided secureContext. The resulting instances can be used to - * construct a Channel that communicates over TLS. gRPC will not override - * anything in the provided secureContext, so the environment variables - * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will - * not be applied. - * @param secureContext The return value of tls.createSecureContext() - * @param verifyOptions Additional options to modify certificate verification - */ - static createFromSecureContext(secureContext, verifyOptions) { - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with no credentials. - */ - static createInsecure() { - return new InsecureChannelCredentialsImpl(); - } -} -exports.ChannelCredentials = ChannelCredentials; -class InsecureChannelCredentialsImpl extends ChannelCredentials { - constructor() { - super(); - } - compose(callCredentials) { - throw new Error('Cannot compose insecure credentials'); - } - _isSecure() { - return false; - } - _equals(other) { - return other instanceof InsecureChannelCredentialsImpl; - } - _createSecureConnector(channelTarget, options, callCredentials) { - return { - connect(socket) { - return Promise.resolve({ - socket, - secure: false - }); - }, - waitForReady: () => { - return Promise.resolve(); - }, - getCallCredentials: () => { - return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); - }, - destroy() { } - }; - } -} -function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) { - var _a, _b; - const connectionOptions = { - secureContext: secureContext +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] }; - let realTarget = channelTarget; - if ('grpc.http_connect_target' in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); - if (parsedTarget) { - realTarget = parsedTarget; - } - } - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); - const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath; - connectionOptions.host = remoteHost; - if (verifyOptions.checkServerIdentity) { - connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; - } - if (verifyOptions.rejectUnauthorized !== undefined) { - connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; - } - connectionOptions.ALPNProtocols = ['h2']; - if (options['grpc.ssl_target_name_override']) { - const sslTargetNameOverride = options['grpc.ssl_target_name_override']; - const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity; - connectionOptions.checkServerIdentity = (host, cert) => { - return originalCheckServerIdentity(sslTargetNameOverride, cert); - }; - connectionOptions.servername = sslTargetNameOverride; - } - else { - connectionOptions.servername = remoteHost; - } - if (options['grpc-node.tls_enable_trace']) { - connectionOptions.enableTrace = true; - } - return connectionOptions; -} -class SecureConnectorImpl { - constructor(connectionOptions, callCredentials) { - this.connectionOptions = connectionOptions; - this.callCredentials = callCredentials; - } - connect(socket) { - const tlsConnectOptions = Object.assign({ socket: socket }, this.connectionOptions); - return new Promise((resolve, reject) => { - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.on('error', (error) => { - reject(error); - }); - }); - } - waitForReady() { - return Promise.resolve(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { } -} -class SecureChannelCredentialsImpl extends ChannelCredentials { - constructor(secureContext, verifyOptions) { - super(); - this.secureContext = secureContext; - this.verifyOptions = verifyOptions; - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof SecureChannelCredentialsImpl) { - return (this.secureContext === other.secureContext && - this.verifyOptions.checkServerIdentity === - other.verifyOptions.checkServerIdentity); - } - else { - return false; - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); - return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } + } + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) + return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + return response; } -class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { - constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) { - super(); - this.caCertificateProvider = caCertificateProvider; - this.identityCertificateProvider = identityCertificateProvider; - this.verifyOptions = verifyOptions; - this.refcount = 0; - /** - * `undefined` means that the certificates have not yet been loaded. `null` - * means that an attempt to load them has completed, and has failed. - */ - this.latestCaUpdate = undefined; - /** - * `undefined` means that the certificates have not yet been loaded. `null` - * means that an attempt to load them has completed, and has failed. - */ - this.latestIdentityUpdate = undefined; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - this.secureContextWatchers = []; - } - _isSecure() { - return true; - } - _equals(other) { - var _a, _b; - if (this === other) { - return true; - } - if (other instanceof CertificateProviderChannelCredentialsImpl) { - return this.caCertificateProvider === other.caCertificateProvider && - this.identityCertificateProvider === other.identityCertificateProvider && - ((_a = this.verifyOptions) === null || _a === void 0 ? void 0 : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === void 0 ? void 0 : _b.checkServerIdentity); - } - else { - return false; - } - } - ref() { - var _a; - if (this.refcount === 0) { - this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - this.refcount += 1; - } - unref() { - var _a; - this.refcount -= 1; - if (this.refcount === 0) { - this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - this.ref(); - return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } - maybeUpdateWatchers() { - if (this.hasReceivedUpdates()) { - for (const watcher of this.secureContextWatchers) { - watcher(this.getLatestSecureContext()); - } - this.secureContextWatchers = []; - } - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.maybeUpdateWatchers(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.maybeUpdateWatchers(); - } - hasReceivedUpdates() { - if (this.latestCaUpdate === undefined) { - return false; - } - if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { - return false; - } - return true; - } - getSecureContext() { - if (this.hasReceivedUpdates()) { - return Promise.resolve(this.getLatestSecureContext()); - } - else { - return new Promise(resolve => { - this.secureContextWatchers.push(resolve); - }); - } - } - getLatestSecureContext() { - var _a, _b; - if (!this.latestCaUpdate) { - return null; - } - if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { - return null; - } + +// pkg/dist-src/iterator.js +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) + return { done: true }; try { - return (0, tls_1.createSecureContext)({ - ca: this.latestCaUpdate.caCertificate, - key: (_a = this.latestIdentityUpdate) === null || _a === void 0 ? void 0 : _a.privateKey, - cert: (_b = this.latestIdentityUpdate) === null || _b === void 0 ? void 0 : _b.certificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to createSecureContext with error ' + e.message); - return null; - } - } -} -CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class { - constructor(parent, channelTarget, options, callCredentials) { - this.parent = parent; - this.channelTarget = channelTarget; - this.options = options; - this.callCredentials = callCredentials; - } - connect(socket) { - return new Promise((resolve, reject) => { - const secureContext = this.parent.getLatestSecureContext(); - if (!secureContext) { - reject(new Error('Failed to load credentials')); - return; - } - if (socket.closed) { - reject(new Error('Socket closed while loading credentials')); + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) + throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] } - const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); - const tlsConnectOptions = Object.assign({ socket: socket }, connnectionOptions); - const closeCallback = () => { - reject(new Error('Socket closed')); - }; - const errorCallback = (error) => { - reject(error); - }; - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - tlsSocket.removeListener('close', closeCallback); - tlsSocket.removeListener('error', errorCallback); - if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.once('close', closeCallback); - tlsSocket.once('error', errorCallback); - }); - } - async waitForReady() { - await this.parent.getSecureContext(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { - this.parent.unref(); - } -}; -function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) { - return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); -} -class ComposedChannelCredentialsImpl extends ChannelCredentials { - constructor(channelCredentials, callCredentials) { - super(); - this.channelCredentials = channelCredentials; - this.callCredentials = callCredentials; - if (!channelCredentials._isSecure()) { - throw new Error('Cannot compose insecure credentials'); - } - } - compose(callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials); - return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof ComposedChannelCredentialsImpl) { - return (this.channelCredentials._equals(other.channelCredentials) && - this.callCredentials._equals(other.callCredentials)); - } - else { - return false; + }; } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); - } + } + }) + }; } -//# sourceMappingURL=channel-credentials.js.map - -/***/ }), - -/***/ 99810: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.recognizedOptions = void 0; -exports.channelOptionsEqual = channelOptionsEqual; -/** - * This is for checking provided options at runtime. This is an object for - * easier membership checking. - */ -exports.recognizedOptions = { - 'grpc.ssl_target_name_override': true, - 'grpc.primary_user_agent': true, - 'grpc.secondary_user_agent': true, - 'grpc.default_authority': true, - 'grpc.keepalive_time_ms': true, - 'grpc.keepalive_timeout_ms': true, - 'grpc.keepalive_permit_without_calls': true, - 'grpc.service_config': true, - 'grpc.max_concurrent_streams': true, - 'grpc.initial_reconnect_backoff_ms': true, - 'grpc.max_reconnect_backoff_ms': true, - 'grpc.use_local_subchannel_pool': true, - 'grpc.max_send_message_length': true, - 'grpc.max_receive_message_length': true, - 'grpc.enable_http_proxy': true, - 'grpc.enable_channelz': true, - 'grpc.dns_min_time_between_resolutions_ms': true, - 'grpc.enable_retries': true, - 'grpc.per_rpc_retry_buffer_size': true, - 'grpc.retry_buffer_size': true, - 'grpc.max_connection_age_ms': true, - 'grpc.max_connection_age_grace_ms': true, - 'grpc-node.max_session_memory': true, - 'grpc.service_config_disable_resolution': true, - 'grpc.client_idle_timeout_ms': true, - 'grpc-node.tls_enable_trace': true, - 'grpc.lb.ring_hash.ring_size_cap': true, - 'grpc-node.retry_max_attempts_limit': true, - 'grpc-node.flow_control_window': true, - 'grpc.server_call_metric_recording': true -}; -function channelOptionsEqual(options1, options2) { - const keys1 = Object.keys(options1).sort(); - const keys2 = Object.keys(options2).sort(); - if (keys1.length !== keys2.length) { - return false; - } - for (let i = 0; i < keys1.length; i += 1) { - if (keys1[i] !== keys2[i]) { - return false; - } - if (options1[keys1[i]] !== options2[keys2[i]]) { - return false; - } - } - return true; +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); } -//# sourceMappingURL=channel-options.js.map - -/***/ }), - -/***/ 13860: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChannelImplementation = void 0; -const channel_credentials_1 = __nccwpck_require__(44030); -const internal_channel_1 = __nccwpck_require__(69672); -class ChannelImplementation { - constructor(target, credentials, options) { - if (typeof target !== 'string') { - throw new TypeError('Channel target must be a string'); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError('Channel credentials must be a ChannelCredentials object'); - } - if (options) { - if (typeof options !== 'object') { - throw new TypeError('Channel options must be an object'); - } - } - this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); - } - close() { - this.internalChannel.close(); - } - getTarget() { - return this.internalChannel.getTarget(); - } - getConnectivityState(tryToConnect) { - return this.internalChannel.getConnectivityState(tryToConnect); - } - watchConnectivityState(currentState, deadline, callback) { - this.internalChannel.watchConnectivityState(currentState, deadline, callback); +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.internalChannel.getChannelzRef(); + let earlyExit = false; + function done() { + earlyExit = true; } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== 'string') { - throw new TypeError('Channel#createCall: method must be a string'); - } - if (!(typeof deadline === 'number' || deadline instanceof Date)) { - throw new TypeError('Channel#createCall: deadline must be a number or Date'); - } - return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; } + return gather(octokit, results, iterator2, mapFn); + }); } -exports.ChannelImplementation = ChannelImplementation; -//# sourceMappingURL=channel.js.map - -/***/ }), - -/***/ 79975: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.registerChannelzSocket = exports.registerChannelzServer = exports.registerChannelzSubchannel = exports.registerChannelzChannel = exports.ChannelzCallTrackerStub = exports.ChannelzCallTracker = exports.ChannelzChildrenTrackerStub = exports.ChannelzChildrenTracker = exports.ChannelzTrace = exports.ChannelzTraceStub = void 0; -exports.unregisterChannelzRef = unregisterChannelzRef; -exports.getChannelzHandlers = getChannelzHandlers; -exports.getChannelzServiceDefinition = getChannelzServiceDefinition; -exports.setup = setup; -const net_1 = __nccwpck_require__(41808); -const ordered_map_1 = __nccwpck_require__(12592); -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const subchannel_address_1 = __nccwpck_require__(99905); -const admin_1 = __nccwpck_require__(8258); -const make_client_1 = __nccwpck_require__(38541); -function channelRefToMessage(ref) { - return { - channel_id: ref.id, - name: ref.name, - }; -} -function subchannelRefToMessage(ref) { - return { - subchannel_id: ref.id, - name: ref.name, - }; -} -function serverRefToMessage(ref) { - return { - server_id: ref.id, - }; -} -function socketRefToMessage(ref) { - return { - socket_id: ref.id, - name: ref.name, - }; -} -/** - * The loose upper bound on the number of events that should be retained in a - * trace. This may be exceeded by up to a factor of 2. Arbitrarily chosen as a - * number that should be large enough to contain the recent relevant - * information, but small enough to not use excessive memory. - */ -const TARGET_RETAINED_TRACES = 32; -/** - * Default number of sockets/servers/channels/subchannels to return - */ -const DEFAULT_MAX_RESULTS = 100; -class ChannelzTraceStub { - constructor() { - this.events = []; - this.creationTimestamp = new Date(); - this.eventsLogged = 0; - } - addTrace() { } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: [], - }; - } -} -exports.ChannelzTraceStub = ChannelzTraceStub; -class ChannelzTrace { - constructor() { - this.events = []; - this.eventsLogged = 0; - this.creationTimestamp = new Date(); - } - addTrace(severity, description, child) { - const timestamp = new Date(); - this.events.push({ - description: description, - severity: severity, - timestamp: timestamp, - childChannel: (child === null || child === void 0 ? void 0 : child.kind) === 'channel' ? child : undefined, - childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === 'subchannel' ? child : undefined, - }); - // Whenever the trace array gets too large, discard the first half - if (this.events.length >= TARGET_RETAINED_TRACES * 2) { - this.events = this.events.slice(TARGET_RETAINED_TRACES); - } - this.eventsLogged += 1; - } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: this.events.map(event => { - return { - description: event.description, - severity: event.severity, - timestamp: dateToProtoTimestamp(event.timestamp), - channel_ref: event.childChannel - ? channelRefToMessage(event.childChannel) - : null, - subchannel_ref: event.childSubchannel - ? subchannelRefToMessage(event.childSubchannel) - : null, - }; - }), - }; - } -} -exports.ChannelzTrace = ChannelzTrace; -class ChannelzChildrenTracker { - constructor() { - this.channelChildren = new ordered_map_1.OrderedMap(); - this.subchannelChildren = new ordered_map_1.OrderedMap(); - this.socketChildren = new ordered_map_1.OrderedMap(); - this.trackerMap = { - ["channel" /* EntityTypes.channel */]: this.channelChildren, - ["subchannel" /* EntityTypes.subchannel */]: this.subchannelChildren, - ["socket" /* EntityTypes.socket */]: this.socketChildren, - }; - } - refChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.find(child.id); - if (trackedChild.equals(tracker.end())) { - tracker.setElement(child.id, { - ref: child, - count: 1, - }, trackedChild); - } - else { - trackedChild.pointer[1].count += 1; - } - } - unrefChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.getElementByKey(child.id); - if (trackedChild !== undefined) { - trackedChild.count -= 1; - if (trackedChild.count === 0) { - tracker.eraseElementByKey(child.id); - } - } - } - getChildLists() { - return { - channels: this.channelChildren, - subchannels: this.subchannelChildren, - sockets: this.socketChildren, - }; - } -} -exports.ChannelzChildrenTracker = ChannelzChildrenTracker; -class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { - refChild() { } - unrefChild() { } -} -exports.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; -class ChannelzCallTracker { - constructor() { - this.callsStarted = 0; - this.callsSucceeded = 0; - this.callsFailed = 0; - this.lastCallStartedTimestamp = null; - } - addCallStarted() { - this.callsStarted += 1; - this.lastCallStartedTimestamp = new Date(); - } - addCallSucceeded() { - this.callsSucceeded += 1; - } - addCallFailed() { - this.callsFailed += 1; - } -} -exports.ChannelzCallTracker = ChannelzCallTracker; -class ChannelzCallTrackerStub extends ChannelzCallTracker { - addCallStarted() { } - addCallSucceeded() { } - addCallFailed() { } -} -exports.ChannelzCallTrackerStub = ChannelzCallTrackerStub; -const entityMaps = { - ["channel" /* EntityTypes.channel */]: new ordered_map_1.OrderedMap(), - ["subchannel" /* EntityTypes.subchannel */]: new ordered_map_1.OrderedMap(), - ["server" /* EntityTypes.server */]: new ordered_map_1.OrderedMap(), - ["socket" /* EntityTypes.socket */]: new ordered_map_1.OrderedMap(), -}; -const generateRegisterFn = (kind) => { - let nextId = 1; - function getNextId() { - return nextId++; - } - const entityMap = entityMaps[kind]; - return (name, getInfo, channelzEnabled) => { - const id = getNextId(); - const ref = { id, name, kind }; - if (channelzEnabled) { - entityMap.setElement(id, { ref, getInfo }); - } - return ref; - }; -}; -exports.registerChannelzChannel = generateRegisterFn("channel" /* EntityTypes.channel */); -exports.registerChannelzSubchannel = generateRegisterFn("subchannel" /* EntityTypes.subchannel */); -exports.registerChannelzServer = generateRegisterFn("server" /* EntityTypes.server */); -exports.registerChannelzSocket = generateRegisterFn("socket" /* EntityTypes.socket */); -function unregisterChannelzRef(ref) { - entityMaps[ref.kind].eraseElementByKey(ref.id); -} -/** - * Parse a single section of an IPv6 address as two bytes - * @param addressSection A hexadecimal string of length up to 4 - * @returns The pair of bytes representing this address section - */ -function parseIPv6Section(addressSection) { - const numberValue = Number.parseInt(addressSection, 16); - return [(numberValue / 256) | 0, numberValue % 256]; -} -/** - * Parse a chunk of an IPv6 address string to some number of bytes - * @param addressChunk Some number of segments of up to 4 hexadecimal - * characters each, joined by colons. - * @returns The list of bytes representing this address chunk - */ -function parseIPv6Chunk(addressChunk) { - if (addressChunk === '') { - return []; - } - const bytePairs = addressChunk - .split(':') - .map(section => parseIPv6Section(section)); - const result = []; - return result.concat(...bytePairs); -} -function isIPv6MappedIPv4(ipAddress) { - return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith('::ffff:') && (0, net_1.isIPv4)(ipAddress.substring(7)); -} -/** - * Prerequisite: isIPv4(ipAddress) - * @param ipAddress - * @returns - */ -function ipv4AddressStringToBuffer(ipAddress) { - return Buffer.from(Uint8Array.from(ipAddress.split('.').map(segment => Number.parseInt(segment)))); -} -/** - * Converts an IPv4 or IPv6 address from string representation to binary - * representation - * @param ipAddress an IP address in standard IPv4 or IPv6 text format - * @returns - */ -function ipAddressStringToBuffer(ipAddress) { - if ((0, net_1.isIPv4)(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress); - } - else if (isIPv6MappedIPv4(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress.substring(7)); - } - else if ((0, net_1.isIPv6)(ipAddress)) { - let leftSection; - let rightSection; - const doubleColonIndex = ipAddress.indexOf('::'); - if (doubleColonIndex === -1) { - leftSection = ipAddress; - rightSection = ''; - } - else { - leftSection = ipAddress.substring(0, doubleColonIndex); - rightSection = ipAddress.substring(doubleColonIndex + 2); - } - const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); - const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); - const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); - return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); - } - else { - return null; - } -} -function connectivityStateToMessage(state) { - switch (state) { - case connectivity_state_1.ConnectivityState.CONNECTING: - return { - state: 'CONNECTING', - }; - case connectivity_state_1.ConnectivityState.IDLE: - return { - state: 'IDLE', - }; - case connectivity_state_1.ConnectivityState.READY: - return { - state: 'READY', - }; - case connectivity_state_1.ConnectivityState.SHUTDOWN: - return { - state: 'SHUTDOWN', - }; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - return { - state: 'TRANSIENT_FAILURE', - }; - default: - return { - state: 'UNKNOWN', - }; - } -} -function dateToProtoTimestamp(date) { - if (!date) { - return null; - } - const millisSinceEpoch = date.getTime(); - return { - seconds: (millisSinceEpoch / 1000) | 0, - nanos: (millisSinceEpoch % 1000) * 1000000, - }; -} -function getChannelMessage(channelEntry) { - const resolvedInfo = channelEntry.getInfo(); - const channelRef = []; - const subchannelRef = []; - resolvedInfo.children.channels.forEach(el => { - channelRef.push(channelRefToMessage(el[1].ref)); - }); - resolvedInfo.children.subchannels.forEach(el => { - subchannelRef.push(subchannelRefToMessage(el[1].ref)); - }); - return { - ref: channelRefToMessage(channelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - channel_ref: channelRef, - subchannel_ref: subchannelRef, - }; -} -function GetChannel(call, callback) { - const channelId = parseInt(call.request.channel_id, 10); - const channelEntry = entityMaps["channel" /* EntityTypes.channel */].getElementByKey(channelId); - if (channelEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No channel data found for id ' + channelId, - }); - return; - } - callback(null, { channel: getChannelMessage(channelEntry) }); -} -function GetTopChannels(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resultList = []; - const startId = parseInt(call.request.start_channel_id, 10); - const channelEntries = entityMaps["channel" /* EntityTypes.channel */]; - let i; - for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getChannelMessage(i.pointer[1])); - } - callback(null, { - channel: resultList, - end: i.equals(channelEntries.end()), - }); -} -function getServerMessage(serverEntry) { - const resolvedInfo = serverEntry.getInfo(); - const listenSocket = []; - resolvedInfo.listenerChildren.sockets.forEach(el => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - return { - ref: serverRefToMessage(serverEntry.ref), - data: { - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - listen_socket: listenSocket, - }; -} -function GetServer(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntries = entityMaps["server" /* EntityTypes.server */]; - const serverEntry = serverEntries.getElementByKey(serverId); - if (serverEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No server data found for id ' + serverId, - }); - return; - } - callback(null, { server: getServerMessage(serverEntry) }); -} -function GetServers(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const startId = parseInt(call.request.start_server_id, 10); - const serverEntries = entityMaps["server" /* EntityTypes.server */]; - const resultList = []; - let i; - for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getServerMessage(i.pointer[1])); - } - callback(null, { - server: resultList, - end: i.equals(serverEntries.end()), - }); -} -function GetSubchannel(call, callback) { - const subchannelId = parseInt(call.request.subchannel_id, 10); - const subchannelEntry = entityMaps["subchannel" /* EntityTypes.subchannel */].getElementByKey(subchannelId); - if (subchannelEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No subchannel data found for id ' + subchannelId, - }); - return; - } - const resolvedInfo = subchannelEntry.getInfo(); - const listenSocket = []; - resolvedInfo.children.sockets.forEach(el => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - const subchannelMessage = { - ref: subchannelRefToMessage(subchannelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - socket_ref: listenSocket, - }; - callback(null, { subchannel: subchannelMessage }); -} -function subchannelAddressToAddressMessage(subchannelAddress) { - var _a; - if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { - return { - address: 'tcpip_address', - tcpip_address: { - ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : undefined, - port: subchannelAddress.port, - }, - }; - } - else { - return { - address: 'uds_address', - uds_address: { - filename: subchannelAddress.path, - }, - }; - } -} -function GetSocket(call, callback) { - var _a, _b, _c, _d, _e; - const socketId = parseInt(call.request.socket_id, 10); - const socketEntry = entityMaps["socket" /* EntityTypes.socket */].getElementByKey(socketId); - if (socketEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No socket data found for id ' + socketId, - }); - return; - } - const resolvedInfo = socketEntry.getInfo(); - const securityMessage = resolvedInfo.security - ? { - model: 'tls', - tls: { - cipher_suite: resolvedInfo.security.cipherSuiteStandardName - ? 'standard_name' - : 'other_name', - standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : undefined, - other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : undefined, - local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : undefined, - remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : undefined, - }, - } - : null; - const socketMessage = { - ref: socketRefToMessage(socketEntry.ref), - local: resolvedInfo.localAddress - ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) - : null, - remote: resolvedInfo.remoteAddress - ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) - : null, - remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : undefined, - security: securityMessage, - data: { - keep_alives_sent: resolvedInfo.keepAlivesSent, - streams_started: resolvedInfo.streamsStarted, - streams_succeeded: resolvedInfo.streamsSucceeded, - streams_failed: resolvedInfo.streamsFailed, - last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), - last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), - messages_received: resolvedInfo.messagesReceived, - messages_sent: resolvedInfo.messagesSent, - last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), - last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), - local_flow_control_window: resolvedInfo.localFlowControlWindow - ? { value: resolvedInfo.localFlowControlWindow } - : null, - remote_flow_control_window: resolvedInfo.remoteFlowControlWindow - ? { value: resolvedInfo.remoteFlowControlWindow } - : null, - }, - }; - callback(null, { socket: socketMessage }); -} -function GetServerSockets(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntry = entityMaps["server" /* EntityTypes.server */].getElementByKey(serverId); - if (serverEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No server data found for id ' + serverId, - }); - return; - } - const startId = parseInt(call.request.start_socket_id, 10); - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resolvedInfo = serverEntry.getInfo(); - // If we wanted to include listener sockets in the result, this line would - // instead say - // const allSockets = resolvedInfo.listenerChildren.sockets.concat(resolvedInfo.sessionChildren.sockets).sort((ref1, ref2) => ref1.id - ref2.id); - const allSockets = resolvedInfo.sessionChildren.sockets; - const resultList = []; - let i; - for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(socketRefToMessage(i.pointer[1].ref)); - } - callback(null, { - socket_ref: resultList, - end: i.equals(allSockets.end()), - }); -} -function getChannelzHandlers() { - return { - GetChannel, - GetTopChannels, - GetServer, - GetServers, - GetSubchannel, - GetSocket, - GetServerSockets, - }; -} -let loadedChannelzDefinition = null; -function getChannelzServiceDefinition() { - if (loadedChannelzDefinition) { - return loadedChannelzDefinition; - } - /* The purpose of this complexity is to avoid loading @grpc/proto-loader at - * runtime for users who will not use/enable channelz. */ - const loaderLoadSync = (__nccwpck_require__(48934)/* .loadSync */ .J_); - const loadedProto = loaderLoadSync('channelz.proto', { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [__nccwpck_require__.ab + "proto"], - }); - const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); - loadedChannelzDefinition = - channelzGrpcObject.grpc.channelz.v1.Channelz.service; - return loadedChannelzDefinition; +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = [ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/secret-scanning/alerts", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/columns/{column_id}/cards", + "GET /projects/{project_id}/collaborators", + "GET /projects/{project_id}/columns", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /repositories/{repository_id}/environments/{environment_name}/secrets", + "GET /repositories/{repository_id}/environments/{environment_name}/variables", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +]; + +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } } -function setup() { - (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); + +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; } -//# sourceMappingURL=channelz.js.map +paginateRest.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + /***/ }), -/***/ 82127: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3044: +/***/ ((module) => { "use strict"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = void 0; -exports.getInterceptingCall = getInterceptingCall; -const metadata_1 = __nccwpck_require__(83665); -const call_interface_1 = __nccwpck_require__(78710); -const constants_1 = __nccwpck_require__(90634); -const error_1 = __nccwpck_require__(22336); -/** - * Error class associated with passing both interceptors and interceptor - * providers to a client constructor or as call options. - */ -class InterceptorConfigurationError extends Error { - constructor(message) { - super(message); - this.name = 'InterceptorConfigurationError'; - Error.captureStackTrace(this, InterceptorConfigurationError); - } -} -exports.InterceptorConfigurationError = InterceptorConfigurationError; -class ListenerBuilder { - constructor() { - this.metadata = undefined; - this.message = undefined; - this.status = undefined; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveStatus(onReceiveStatus) { - this.status = onReceiveStatus; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveStatus: this.status, - }; - } -} -exports.ListenerBuilder = ListenerBuilder; -class RequesterBuilder { - constructor() { - this.start = undefined; - this.message = undefined; - this.halfClose = undefined; - this.cancel = undefined; - } - withStart(start) { - this.start = start; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withHalfClose(halfClose) { - this.halfClose = halfClose; - return this; - } - withCancel(cancel) { - this.cancel = cancel; - return this; - } - build() { - return { - start: this.start, - sendMessage: this.message, - halfClose: this.halfClose, - cancel: this.cancel, - }; - } -} -exports.RequesterBuilder = RequesterBuilder; -/** - * A Listener with a default pass-through implementation of each method. Used - * for filling out Listeners with some methods omitted. - */ -const defaultListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveStatus: (status, next) => { - next(status); - }, +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 }); }; -/** - * A Requester with a default pass-through implementation of each method. Used - * for filling out Requesters with some methods omitted. - */ -const defaultRequester = { - start: (metadata, listener, next) => { - next(metadata, listener); - }, - sendMessage: (message, next) => { - next(message); - }, - halfClose: next => { - next(); - }, - cancel: next => { - next(); - }, +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; }; -class InterceptingCall { - constructor(nextCall, requester) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - /** - * Indicates that metadata has been passed to the requester's start - * method but it has not been passed to the corresponding next callback - */ - this.processingMetadata = false; - /** - * Message context for a pending message that is waiting for - */ - this.pendingMessageContext = null; - /** - * Indicates that a message has been passed to the requester's sendMessage - * method but it has not been passed to the corresponding next callback - */ - this.processingMessage = false; - /** - * Indicates that a status was received but could not be propagated because - * a message was still being processed. - */ - this.pendingHalfClose = false; - if (requester) { - this.requester = { - start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start, - sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage, - halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose, - cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel, - }; - } - else { - this.requester = defaultRequester; - } - } - cancelWithStatus(status, details) { - this.requester.cancel(() => { - this.nextCall.cancelWithStatus(status, details); - }); - } - getPeer() { - return this.nextCall.getPeer(); - } - processPendingMessage() { - if (this.pendingMessageContext) { - this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); - this.pendingMessageContext = null; - this.pendingMessage = null; - } - } - processPendingHalfClose() { - if (this.pendingHalfClose) { - this.nextCall.halfClose(); - } - } - start(metadata, interceptingListener) { - var _a, _b, _c, _d, _e, _f; - const fullInterceptingListener = { - onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : (metadata => { }), - onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : (message => { }), - onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status => { }), - }; - this.processingMetadata = true; - this.requester.start(metadata, fullInterceptingListener, (md, listener) => { - var _a, _b, _c; - this.processingMetadata = false; - let finalInterceptingListener; - if ((0, call_interface_1.isInterceptingListener)(listener)) { - finalInterceptingListener = listener; - } - else { - const fullListener = { - onReceiveMetadata: (_a = listener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultListener.onReceiveMetadata, - onReceiveMessage: (_b = listener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultListener.onReceiveMessage, - onReceiveStatus: (_c = listener.onReceiveStatus) !== null && _c !== void 0 ? _c : defaultListener.onReceiveStatus, - }; - finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); - } - this.nextCall.start(md, finalInterceptingListener); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context, message) { - this.processingMessage = true; - this.requester.sendMessage(message, finalMessage => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessageContext = context; - this.pendingMessage = message; - } - else { - this.nextCall.sendMessageWithContext(context, finalMessage); - this.processPendingHalfClose(); - } - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - startRead() { - this.nextCall.startRead(); - } - halfClose() { - this.requester.halfClose(() => { - if (this.processingMetadata || this.processingMessage) { - this.pendingHalfClose = true; - } - else { - this.nextCall.halfClose(); - } - }); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } -} -exports.InterceptingCall = InterceptingCall; -function getCall(channel, path, options) { - var _a, _b; - const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity; - const host = options.host; - const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null; - const propagateFlags = options.propagate_flags; - const credentials = options.credentials; - const call = channel.createCall(path, deadline, host, parent, propagateFlags); - if (credentials) { - call.setCredentials(credentials); - } - return call; -} -/** - * InterceptingCall implementation that directly owns the underlying Call - * object and handles serialization and deseraizliation. - */ -class BaseInterceptingCall { - constructor(call, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - methodDefinition) { - this.call = call; - this.methodDefinition = methodDefinition; - } - cancelWithStatus(status, details) { - this.call.cancelWithStatus(status, details); - } - getPeer() { - return this.call.getPeer(); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context, message) { - let serialized; - try { - serialized = this.methodDefinition.requestSerialize(message); - } - catch (e) { - this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); - return; - } - this.call.sendMessageWithContext(context, serialized); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - start(metadata, interceptingListener) { - let readError = null; - this.call.start(metadata, { - onReceiveMetadata: metadata => { - var _a; - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata); - }, - onReceiveMessage: message => { - var _a; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let deserialized; - try { - deserialized = this.methodDefinition.responseDeserialize(message); - } - catch (e) { - readError = { - code: constants_1.Status.INTERNAL, - details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, - metadata: new metadata_1.Metadata(), - }; - this.call.cancelWithStatus(readError.code, readError.details); - return; - } - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized); - }, - onReceiveStatus: status => { - var _a, _b; - if (readError) { - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError); - } - else { - (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status); - } - }, - }); - } - startRead() { - this.call.startRead(); - } - halfClose() { - this.call.halfClose(); - } - getAuthContext() { - return this.call.getAuthContext(); - } -} -/** - * BaseInterceptingCall with special-cased behavior for methods with unary - * responses. - */ -class BaseUnaryInterceptingCall extends BaseInterceptingCall { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - constructor(call, methodDefinition) { - super(call, methodDefinition); - } - start(metadata, listener) { - var _a, _b; - let receivedMessage = false; - const wrapperListener = { - onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : (metadata => { }), - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage: (message) => { - var _a; - receivedMessage = true; - (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, message); - }, - onReceiveStatus: (status) => { - var _a, _b; - if (!receivedMessage) { - (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, null); - } - (_b = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(listener, status); - }, - }; - super.start(metadata, wrapperListener); - this.call.startRead(); - } -} -/** - * BaseInterceptingCall with special-cased behavior for methods with streaming - * responses. - */ -class BaseStreamingInterceptingCall extends BaseInterceptingCall { -} -function getBottomInterceptingCall(channel, options, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -methodDefinition) { - const call = getCall(channel, methodDefinition.path, options); - if (methodDefinition.responseStream) { - return new BaseStreamingInterceptingCall(call, methodDefinition); - } - else { - return new BaseUnaryInterceptingCall(call, methodDefinition); - } -} -function getInterceptingCall(interceptorArgs, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -methodDefinition, options, channel) { - if (interceptorArgs.clientInterceptors.length > 0 && - interceptorArgs.clientInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as options ' + - 'to the client constructor. Only one of these is allowed.'); - } - if (interceptorArgs.callInterceptors.length > 0 && - interceptorArgs.callInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as call ' + - 'options. Only one of these is allowed.'); - } - let interceptors = []; - // Interceptors passed to the call override interceptors passed to the client constructor - if (interceptorArgs.callInterceptors.length > 0 || - interceptorArgs.callInterceptorProviders.length > 0) { - interceptors = [] - .concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map(provider => provider(methodDefinition))) - .filter(interceptor => interceptor); - // Filter out falsy values when providers return nothing - } - else { - interceptors = [] - .concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map(provider => provider(methodDefinition))) - .filter(interceptor => interceptor); - // Filter out falsy values when providers return nothing - } - const interceptorOptions = Object.assign({}, options, { - method_definition: methodDefinition, - }); - /* For each interceptor in the list, the nextCall function passed to it is - * based on the next interceptor in the list, using a nextCall function - * constructed with the following interceptor in the list, and so on. The - * initialValue, which is effectively at the end of the list, is a nextCall - * function that invokes getBottomInterceptingCall, the result of which - * handles (de)serialization and also gets the underlying call from the - * channel. */ - const getCall = interceptors.reduceRight((nextCall, nextInterceptor) => { - return currentOptions => nextInterceptor(currentOptions, nextCall); - }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); - return getCall(interceptorOptions); -} -//# sourceMappingURL=client-interceptors.js.map - -/***/ }), +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -/***/ 87172: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); -"use strict"; +// pkg/dist-src/version.js +var VERSION = "10.4.1"; -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Client = void 0; -const call_1 = __nccwpck_require__(97453); -const channel_1 = __nccwpck_require__(13860); -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const client_interceptors_1 = __nccwpck_require__(82127); -const CHANNEL_SYMBOL = Symbol(); -const INTERCEPTOR_SYMBOL = Symbol(); -const INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); -const CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); -function isFunction(arg) { - return typeof arg === 'function'; -} -function getErrorStackString(error) { - var _a; - return ((_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n').slice(1).join('\n')) || 'no stack trace available'; -} -/** - * A generic gRPC client. Primarily useful as a base class for all generated - * clients. - */ -class Client { - constructor(address, credentials, options = {}) { - var _a, _b; - options = Object.assign({}, options); - this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : []; - delete options.interceptors; - this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : []; - delete options.interceptor_providers; - if (this[INTERCEPTOR_SYMBOL].length > 0 && - this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { - throw new Error('Both interceptors and interceptor_providers were passed as options ' + - 'to the client constructor. Only one of these is allowed.'); - } - this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = - options.callInvocationTransformer; - delete options.callInvocationTransformer; - if (options.channelOverride) { - this[CHANNEL_SYMBOL] = options.channelOverride; - } - else if (options.channelFactoryOverride) { - const channelFactoryOverride = options.channelFactoryOverride; - delete options.channelFactoryOverride; - this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); - } - else { - this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); - } - } - close() { - this[CHANNEL_SYMBOL].close(); - } - getChannel() { - return this[CHANNEL_SYMBOL]; - } - waitForReady(deadline, callback) { - const checkState = (err) => { - if (err) { - callback(new Error('Failed to connect before the deadline')); - return; - } - let newState; - try { - newState = this[CHANNEL_SYMBOL].getConnectivityState(true); - } - catch (e) { - callback(new Error('The channel has been closed')); - return; - } - if (newState === connectivity_state_1.ConnectivityState.READY) { - callback(); - } - else { - try { - this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); - } - catch (e) { - callback(new Error('The channel has been closed')); - } - } - }; - setImmediate(checkState); - } - checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { - if (isFunction(arg1)) { - return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 }; - } - else if (isFunction(arg2)) { - if (arg1 instanceof metadata_1.Metadata) { - return { metadata: arg1, options: {}, callback: arg2 }; - } - else { - return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 }; - } - } - else { - if (!(arg1 instanceof metadata_1.Metadata && - arg2 instanceof Object && - isFunction(arg3))) { - throw new Error('Incorrect arguments passed'); - } - return { metadata: arg1, options: arg2, callback: arg3 }; - } - } - makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - argument: argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientUnaryCallImpl(), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: metadata => { - emitter.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); - } - responseMessage = message; - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: 'No message received', - metadata: status.metadata, - }, callerStack)); - } - else { - callProperties.callback(null, responseMessage); - } - } - else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - emitter.emit('status', status); - }, - }); - call.sendMessage(argument); - call.halfClose(); - return emitter; - } - makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientWritableStreamImpl(serialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: metadata => { - emitter.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); - } - responseMessage = message; - call.startRead(); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: 'No message received', - metadata: status.metadata, - }, callerStack)); - } - else { - callProperties.callback(null, responseMessage); - } - } - else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - emitter.emit('status', status); - }, - }); - return emitter; - } - checkMetadataAndOptions(arg1, arg2) { - let metadata; - let options; - if (arg1 instanceof metadata_1.Metadata) { - metadata = arg1; - if (arg2) { - options = arg2; - } - else { - options = {}; - } - } - else { - if (arg1) { - options = arg1; - } - else { - options = {}; - } - metadata = new metadata_1.Metadata(); - } - return { metadata, options }; - } - makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - argument: argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientReadableStreamImpl(deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - stream.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata) { - stream.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - stream.emit('status', status); - }, - }); - call.sendMessage(argument); - call.halfClose(); - return stream; - } - makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - stream.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata) { - stream.emit('metadata', metadata); - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - stream.emit('status', status); - }, - }); - return stream; - } -} -exports.Client = Client; -//# sourceMappingURL=client.js.map - -/***/ }), - -/***/ 54789: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CompressionAlgorithms = void 0; -var CompressionAlgorithms; -(function (CompressionAlgorithms) { - CompressionAlgorithms[CompressionAlgorithms["identity"] = 0] = "identity"; - CompressionAlgorithms[CompressionAlgorithms["deflate"] = 1] = "deflate"; - CompressionAlgorithms[CompressionAlgorithms["gzip"] = 2] = "gzip"; -})(CompressionAlgorithms || (exports.CompressionAlgorithms = CompressionAlgorithms = {})); -//# sourceMappingURL=compression-algorithms.js.map - -/***/ }), - -/***/ 47616: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CompressionFilterFactory = exports.CompressionFilter = void 0; -const zlib = __nccwpck_require__(59796); -const compression_algorithms_1 = __nccwpck_require__(54789); -const constants_1 = __nccwpck_require__(90634); -const filter_1 = __nccwpck_require__(43392); -const logging = __nccwpck_require__(35993); -const isCompressionAlgorithmKey = (key) => { - return (typeof key === 'number' && typeof compression_algorithms_1.CompressionAlgorithms[key] === 'string'); -}; -class CompressionHandler { - /** - * @param message Raw uncompressed message bytes - * @param compress Indicates whether the message should be compressed - * @return Framed message, compressed if applicable - */ - async writeMessage(message, compress) { - let messageBuffer = message; - if (compress) { - messageBuffer = await this.compressMessage(messageBuffer); - } - const output = Buffer.allocUnsafe(messageBuffer.length + 5); - output.writeUInt8(compress ? 1 : 0, 0); - output.writeUInt32BE(messageBuffer.length, 1); - messageBuffer.copy(output, 5); - return output; - } - /** - * @param data Framed message, possibly compressed - * @return Uncompressed message - */ - async readMessage(data) { - const compressed = data.readUInt8(0) === 1; - let messageBuffer = data.slice(5); - if (compressed) { - messageBuffer = await this.decompressMessage(messageBuffer); - } - return messageBuffer; - } -} -class IdentityHandler extends CompressionHandler { - async compressMessage(message) { - return message; - } - async writeMessage(message, compress) { - const output = Buffer.allocUnsafe(message.length + 5); - /* With "identity" compression, messages should always be marked as - * uncompressed */ - output.writeUInt8(0, 0); - output.writeUInt32BE(message.length, 1); - message.copy(output, 5); - return output; - } - decompressMessage(message) { - return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); - } -} -class DeflateHandler extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.deflate(message, (err, output) => { - if (err) { - reject(err); - } - else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createInflate(); - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } -} -class GzipHandler extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.gzip(message, (err, output) => { - if (err) { - reject(err); - } - else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createGunzip(); - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } -} -class UnknownHandler extends CompressionHandler { - constructor(compressionName) { - super(); - this.compressionName = compressionName; - } - compressMessage(message) { - return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); - } - decompressMessage(message) { - // This should be unreachable - return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); - } -} -function getCompressionHandler(compressionName, maxReceiveMessageSize) { - switch (compressionName) { - case 'identity': - return new IdentityHandler(); - case 'deflate': - return new DeflateHandler(maxReceiveMessageSize); - case 'gzip': - return new GzipHandler(maxReceiveMessageSize); - default: - return new UnknownHandler(compressionName); - } -} -class CompressionFilter extends filter_1.BaseFilter { - constructor(channelOptions, sharedFilterConfig) { - var _a, _b, _c; - super(); - this.sharedFilterConfig = sharedFilterConfig; - this.sendCompression = new IdentityHandler(); - this.receiveCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = 'identity'; - const compressionAlgorithmKey = channelOptions['grpc.default_compression_algorithm']; - this.maxReceiveMessageLength = (_a = channelOptions['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.maxSendMessageLength = (_b = channelOptions['grpc.max_send_message_length']) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - if (compressionAlgorithmKey !== undefined) { - if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { - const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; - const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === void 0 ? void 0 : _c.split(','); - /** - * There are two possible situations here: - * 1) We don't have any info yet from the server about what compression it supports - * In that case we should just use what the client tells us to use - * 2) We've previously received a response from the server including a grpc-accept-encoding header - * In that case we only want to use the encoding chosen by the client if the server supports it - */ - if (!serverSupportedEncodings || - serverSupportedEncodings.includes(clientSelectedEncoding)) { - this.currentCompressionAlgorithm = clientSelectedEncoding; - this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1); - } - } - else { - logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); - } - } - } - async sendMetadata(metadata) { - const headers = await metadata; - headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); - headers.set('accept-encoding', 'identity'); - // No need to send the header if it's "identity" - behavior is identical; save the bandwidth - if (this.currentCompressionAlgorithm === 'identity') { - headers.remove('grpc-encoding'); - } - else { - headers.set('grpc-encoding', this.currentCompressionAlgorithm); - } - return headers; - } - receiveMetadata(metadata) { - const receiveEncoding = metadata.get('grpc-encoding'); - if (receiveEncoding.length > 0) { - const encoding = receiveEncoding[0]; - if (typeof encoding === 'string') { - this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); - } - } - metadata.remove('grpc-encoding'); - /* Check to see if the compression we're using to send messages is supported by the server - * If not, reset the sendCompression filter and have it use the default IdentityHandler */ - const serverSupportedEncodingsHeader = metadata.get('grpc-accept-encoding')[0]; - if (serverSupportedEncodingsHeader) { - this.sharedFilterConfig.serverSupportedEncodingHeader = - serverSupportedEncodingsHeader; - const serverSupportedEncodings = serverSupportedEncodingsHeader.split(','); - if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { - this.sendCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = 'identity'; - } - } - metadata.remove('grpc-accept-encoding'); - return metadata; - } - async sendMessage(message) { - var _a; - /* This filter is special. The input message is the bare message bytes, - * and the output is a framed and possibly compressed message. For this - * reason, this filter should be at the bottom of the filter stack */ - const resolvedMessage = await message; - if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { - throw { - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` - }; - } - let compress; - if (this.sendCompression instanceof IdentityHandler) { - compress = false; - } - else { - compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2 /* WriteFlags.NoCompress */) === 0; - } - return { - message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), - flags: resolvedMessage.flags, - }; - } - async receiveMessage(message) { - /* This filter is also special. The input message is framed and possibly - * compressed, and the output message is deframed and uncompressed. So - * this is another reason that this filter should be at the bottom of the - * filter stack. */ - return this.receiveCompression.readMessage(await message); - } -} -exports.CompressionFilter = CompressionFilter; -class CompressionFilterFactory { - constructor(channel, options) { - this.options = options; - this.sharedFilterConfig = {}; - } - createFilter() { - return new CompressionFilter(this.options, this.sharedFilterConfig); - } -} -exports.CompressionFilterFactory = CompressionFilterFactory; -//# sourceMappingURL=compression-filter.js.map - -/***/ }), - -/***/ 80878: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ConnectivityState = void 0; -var ConnectivityState; -(function (ConnectivityState) { - ConnectivityState[ConnectivityState["IDLE"] = 0] = "IDLE"; - ConnectivityState[ConnectivityState["CONNECTING"] = 1] = "CONNECTING"; - ConnectivityState[ConnectivityState["READY"] = 2] = "READY"; - ConnectivityState[ConnectivityState["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; - ConnectivityState[ConnectivityState["SHUTDOWN"] = 4] = "SHUTDOWN"; -})(ConnectivityState || (exports.ConnectivityState = ConnectivityState = {})); -//# sourceMappingURL=connectivity-state.js.map - -/***/ }), - -/***/ 90634: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = void 0; -var Status; -(function (Status) { - Status[Status["OK"] = 0] = "OK"; - Status[Status["CANCELLED"] = 1] = "CANCELLED"; - Status[Status["UNKNOWN"] = 2] = "UNKNOWN"; - Status[Status["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; - Status[Status["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; - Status[Status["NOT_FOUND"] = 5] = "NOT_FOUND"; - Status[Status["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; - Status[Status["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; - Status[Status["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; - Status[Status["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; - Status[Status["ABORTED"] = 10] = "ABORTED"; - Status[Status["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; - Status[Status["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; - Status[Status["INTERNAL"] = 13] = "INTERNAL"; - Status[Status["UNAVAILABLE"] = 14] = "UNAVAILABLE"; - Status[Status["DATA_LOSS"] = 15] = "DATA_LOSS"; - Status[Status["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; -})(Status || (exports.Status = Status = {})); -var LogVerbosity; -(function (LogVerbosity) { - LogVerbosity[LogVerbosity["DEBUG"] = 0] = "DEBUG"; - LogVerbosity[LogVerbosity["INFO"] = 1] = "INFO"; - LogVerbosity[LogVerbosity["ERROR"] = 2] = "ERROR"; - LogVerbosity[LogVerbosity["NONE"] = 3] = "NONE"; -})(LogVerbosity || (exports.LogVerbosity = LogVerbosity = {})); -/** - * NOTE: This enum is not currently used in any implemented API in this - * library. It is included only for type parity with the other implementation. - */ -var Propagate; -(function (Propagate) { - Propagate[Propagate["DEADLINE"] = 1] = "DEADLINE"; - Propagate[Propagate["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; - Propagate[Propagate["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; - Propagate[Propagate["CANCELLATION"] = 8] = "CANCELLATION"; - // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43 - Propagate[Propagate["DEFAULTS"] = 65535] = "DEFAULTS"; -})(Propagate || (exports.Propagate = Propagate = {})); -// -1 means unlimited -exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; -// 4 MB default -exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 39129: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; -const constants_1 = __nccwpck_require__(90634); -const INAPPROPRIATE_CONTROL_PLANE_CODES = [ - constants_1.Status.OK, - constants_1.Status.INVALID_ARGUMENT, - constants_1.Status.NOT_FOUND, - constants_1.Status.ALREADY_EXISTS, - constants_1.Status.FAILED_PRECONDITION, - constants_1.Status.ABORTED, - constants_1.Status.OUT_OF_RANGE, - constants_1.Status.DATA_LOSS, -]; -function restrictControlPlaneStatusCode(code, details) { - if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { - return { - code: constants_1.Status.INTERNAL, - details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}`, - }; - } - else { - return { code, details }; - } -} -//# sourceMappingURL=control-plane-status.js.map - -/***/ }), - -/***/ 511: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.minDeadline = minDeadline; -exports.getDeadlineTimeoutString = getDeadlineTimeoutString; -exports.getRelativeTimeout = getRelativeTimeout; -exports.deadlineToString = deadlineToString; -exports.formatDateDifference = formatDateDifference; -function minDeadline(...deadlineList) { - let minValue = Infinity; - for (const deadline of deadlineList) { - const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; - if (deadlineMsecs < minValue) { - minValue = deadlineMsecs; - } - } - return minValue; -} -const units = [ - ['m', 1], - ['S', 1000], - ['M', 60 * 1000], - ['H', 60 * 60 * 1000], -]; -function getDeadlineTimeoutString(deadline) { - const now = new Date().getTime(); - if (deadline instanceof Date) { - deadline = deadline.getTime(); - } - const timeoutMs = Math.max(deadline - now, 0); - for (const [unit, factor] of units) { - const amount = timeoutMs / factor; - if (amount < 1e8) { - return String(Math.ceil(amount)) + unit; - } - } - throw new Error('Deadline is too far in the future'); -} -/** - * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args - * In particular, "When delay is larger than 2147483647 or less than 1, the - * delay will be set to 1. Non-integer delays are truncated to an integer." - * This number of milliseconds is almost 25 days. - */ -const MAX_TIMEOUT_TIME = 2147483647; -/** - * Get the timeout value that should be passed to setTimeout now for the timer - * to end at the deadline. For any deadline before now, the timer should end - * immediately, represented by a value of 0. For any deadline more than - * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will - * end at that time, so it is treated as infinitely far in the future. - * @param deadline - * @returns - */ -function getRelativeTimeout(deadline) { - const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; - const now = new Date().getTime(); - const timeout = deadlineMs - now; - if (timeout < 0) { - return 0; - } - else if (timeout > MAX_TIMEOUT_TIME) { - return Infinity; - } - else { - return timeout; - } -} -function deadlineToString(deadline) { - if (deadline instanceof Date) { - return deadline.toISOString(); - } - else { - const dateDeadline = new Date(deadline); - if (Number.isNaN(dateDeadline.getTime())) { - return '' + deadline; - } - else { - return dateDeadline.toISOString(); - } - } -} -/** - * Calculate the difference between two dates as a number of seconds and format - * it as a string. - * @param startDate - * @param endDate - * @returns - */ -function formatDateDifference(startDate, endDate) { - return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + 's'; -} -//# sourceMappingURL=deadline.js.map - -/***/ }), - -/***/ 62668: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.durationMessageToDuration = durationMessageToDuration; -exports.msToDuration = msToDuration; -exports.durationToMs = durationToMs; -exports.isDuration = isDuration; -exports.isDurationMessage = isDurationMessage; -exports.parseDuration = parseDuration; -exports.durationToString = durationToString; -function durationMessageToDuration(message) { - return { - seconds: Number.parseInt(message.seconds), - nanos: message.nanos - }; -} -function msToDuration(millis) { - return { - seconds: (millis / 1000) | 0, - nanos: ((millis % 1000) * 1000000) | 0, - }; -} -function durationToMs(duration) { - return (duration.seconds * 1000 + duration.nanos / 1000000) | 0; -} -function isDuration(value) { - return typeof value.seconds === 'number' && typeof value.nanos === 'number'; -} -function isDurationMessage(value) { - return typeof value.seconds === 'string' && typeof value.nanos === 'number'; -} -const durationRegex = /^(\d+)(?:\.(\d+))?s$/; -function parseDuration(value) { - const match = value.match(durationRegex); - if (!match) { - return null; - } - return { - seconds: Number.parseInt(match[1], 10), - nanos: match[2] ? Number.parseInt(match[2].padEnd(9, '0'), 10) : 0 - }; -} -function durationToString(duration) { - if (duration.nanos === 0) { - return `${duration.seconds}s`; - } - let scaleFactor; - if (duration.nanos % 1000000 === 0) { - scaleFactor = 1000000; - } - else if (duration.nanos % 1000 === 0) { - scaleFactor = 1000; - } - else { - scaleFactor = 1; - } - return `${duration.seconds}.${duration.nanos / scaleFactor}s`; -} -//# sourceMappingURL=duration.js.map - -/***/ }), - -/***/ 29160: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2024 gRPC 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 - * - * 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 _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; -exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : 'false') === 'true'; -//# sourceMappingURL=environment.js.map - -/***/ }), - -/***/ 22336: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getErrorMessage = getErrorMessage; -exports.getErrorCode = getErrorCode; -function getErrorMessage(error) { - if (error instanceof Error) { - return error.message; - } - else { - return String(error); - } -} -function getErrorCode(error) { - if (typeof error === 'object' && - error !== null && - 'code' in error && - typeof error.code === 'number') { - return error.code; - } - else { - return null; - } -} -//# sourceMappingURL=error.js.map - -/***/ }), - -/***/ 37626: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports.createCertificateProviderChannelCredentials = exports.FileWatcherCertificateProvider = exports.createCertificateProviderServerCredentials = exports.createServerCredentialsWithInterceptors = exports.BaseSubchannelWrapper = exports.registerAdminService = exports.FilterStackFactory = exports.BaseFilter = exports.statusOrFromError = exports.statusOrFromValue = exports.PickResultType = exports.QueuePicker = exports.UnavailablePicker = exports.ChildLoadBalancerHandler = exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.subchannelAddressToString = exports.LeafLoadBalancer = exports.isLoadBalancerNameRegistered = exports.parseLoadBalancingConfig = exports.selectLbConfigFromList = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = exports.BackoffTimeout = exports.parseDuration = exports.durationToMs = exports.splitHostPort = exports.uriToString = exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports.createResolver = exports.registerResolver = exports.log = exports.trace = void 0; -var logging_1 = __nccwpck_require__(35993); -Object.defineProperty(exports, "trace", ({ enumerable: true, get: function () { return logging_1.trace; } })); -Object.defineProperty(exports, "log", ({ enumerable: true, get: function () { return logging_1.log; } })); -var resolver_1 = __nccwpck_require__(31594); -Object.defineProperty(exports, "registerResolver", ({ enumerable: true, get: function () { return resolver_1.registerResolver; } })); -Object.defineProperty(exports, "createResolver", ({ enumerable: true, get: function () { return resolver_1.createResolver; } })); -Object.defineProperty(exports, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", ({ enumerable: true, get: function () { return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY; } })); -var uri_parser_1 = __nccwpck_require__(65974); -Object.defineProperty(exports, "uriToString", ({ enumerable: true, get: function () { return uri_parser_1.uriToString; } })); -Object.defineProperty(exports, "splitHostPort", ({ enumerable: true, get: function () { return uri_parser_1.splitHostPort; } })); -var duration_1 = __nccwpck_require__(62668); -Object.defineProperty(exports, "durationToMs", ({ enumerable: true, get: function () { return duration_1.durationToMs; } })); -Object.defineProperty(exports, "parseDuration", ({ enumerable: true, get: function () { return duration_1.parseDuration; } })); -var backoff_timeout_1 = __nccwpck_require__(34186); -Object.defineProperty(exports, "BackoffTimeout", ({ enumerable: true, get: function () { return backoff_timeout_1.BackoffTimeout; } })); -var load_balancer_1 = __nccwpck_require__(52680); -Object.defineProperty(exports, "createChildChannelControlHelper", ({ enumerable: true, get: function () { return load_balancer_1.createChildChannelControlHelper; } })); -Object.defineProperty(exports, "registerLoadBalancerType", ({ enumerable: true, get: function () { return load_balancer_1.registerLoadBalancerType; } })); -Object.defineProperty(exports, "selectLbConfigFromList", ({ enumerable: true, get: function () { return load_balancer_1.selectLbConfigFromList; } })); -Object.defineProperty(exports, "parseLoadBalancingConfig", ({ enumerable: true, get: function () { return load_balancer_1.parseLoadBalancingConfig; } })); -Object.defineProperty(exports, "isLoadBalancerNameRegistered", ({ enumerable: true, get: function () { return load_balancer_1.isLoadBalancerNameRegistered; } })); -var load_balancer_pick_first_1 = __nccwpck_require__(38977); -Object.defineProperty(exports, "LeafLoadBalancer", ({ enumerable: true, get: function () { return load_balancer_pick_first_1.LeafLoadBalancer; } })); -var subchannel_address_1 = __nccwpck_require__(99905); -Object.defineProperty(exports, "subchannelAddressToString", ({ enumerable: true, get: function () { return subchannel_address_1.subchannelAddressToString; } })); -Object.defineProperty(exports, "endpointToString", ({ enumerable: true, get: function () { return subchannel_address_1.endpointToString; } })); -Object.defineProperty(exports, "endpointHasAddress", ({ enumerable: true, get: function () { return subchannel_address_1.endpointHasAddress; } })); -Object.defineProperty(exports, "EndpointMap", ({ enumerable: true, get: function () { return subchannel_address_1.EndpointMap; } })); -var load_balancer_child_handler_1 = __nccwpck_require__(17559); -Object.defineProperty(exports, "ChildLoadBalancerHandler", ({ enumerable: true, get: function () { return load_balancer_child_handler_1.ChildLoadBalancerHandler; } })); -var picker_1 = __nccwpck_require__(81611); -Object.defineProperty(exports, "UnavailablePicker", ({ enumerable: true, get: function () { return picker_1.UnavailablePicker; } })); -Object.defineProperty(exports, "QueuePicker", ({ enumerable: true, get: function () { return picker_1.QueuePicker; } })); -Object.defineProperty(exports, "PickResultType", ({ enumerable: true, get: function () { return picker_1.PickResultType; } })); -var call_interface_1 = __nccwpck_require__(78710); -Object.defineProperty(exports, "statusOrFromValue", ({ enumerable: true, get: function () { return call_interface_1.statusOrFromValue; } })); -Object.defineProperty(exports, "statusOrFromError", ({ enumerable: true, get: function () { return call_interface_1.statusOrFromError; } })); -var filter_1 = __nccwpck_require__(43392); -Object.defineProperty(exports, "BaseFilter", ({ enumerable: true, get: function () { return filter_1.BaseFilter; } })); -var filter_stack_1 = __nccwpck_require__(66450); -Object.defineProperty(exports, "FilterStackFactory", ({ enumerable: true, get: function () { return filter_stack_1.FilterStackFactory; } })); -var admin_1 = __nccwpck_require__(8258); -Object.defineProperty(exports, "registerAdminService", ({ enumerable: true, get: function () { return admin_1.registerAdminService; } })); -var subchannel_interface_1 = __nccwpck_require__(12258); -Object.defineProperty(exports, "BaseSubchannelWrapper", ({ enumerable: true, get: function () { return subchannel_interface_1.BaseSubchannelWrapper; } })); -var server_credentials_1 = __nccwpck_require__(63828); -Object.defineProperty(exports, "createServerCredentialsWithInterceptors", ({ enumerable: true, get: function () { return server_credentials_1.createServerCredentialsWithInterceptors; } })); -Object.defineProperty(exports, "createCertificateProviderServerCredentials", ({ enumerable: true, get: function () { return server_credentials_1.createCertificateProviderServerCredentials; } })); -var certificate_provider_1 = __nccwpck_require__(25649); -Object.defineProperty(exports, "FileWatcherCertificateProvider", ({ enumerable: true, get: function () { return certificate_provider_1.FileWatcherCertificateProvider; } })); -var channel_credentials_1 = __nccwpck_require__(44030); -Object.defineProperty(exports, "createCertificateProviderChannelCredentials", ({ enumerable: true, get: function () { return channel_credentials_1.createCertificateProviderChannelCredentials; } })); -var internal_channel_1 = __nccwpck_require__(69672); -Object.defineProperty(exports, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", ({ enumerable: true, get: function () { return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX; } })); -//# sourceMappingURL=experimental.js.map - -/***/ }), - -/***/ 66450: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FilterStackFactory = exports.FilterStack = void 0; -class FilterStack { - constructor(filters) { - this.filters = filters; - } - sendMetadata(metadata) { - let result = metadata; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMetadata(result); - } - return result; - } - receiveMetadata(metadata) { - let result = metadata; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMetadata(result); - } - return result; - } - sendMessage(message) { - let result = message; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMessage(result); - } - return result; - } - receiveMessage(message) { - let result = message; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMessage(result); - } - return result; - } - receiveTrailers(status) { - let result = status; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveTrailers(result); - } - return result; - } - push(filters) { - this.filters.unshift(...filters); - } - getFilters() { - return this.filters; - } -} -exports.FilterStack = FilterStack; -class FilterStackFactory { - constructor(factories) { - this.factories = factories; - } - push(filterFactories) { - this.factories.unshift(...filterFactories); - } - clone() { - return new FilterStackFactory([...this.factories]); - } - createFilter() { - return new FilterStack(this.factories.map(factory => factory.createFilter())); - } -} -exports.FilterStackFactory = FilterStackFactory; -//# sourceMappingURL=filter-stack.js.map - -/***/ }), - -/***/ 43392: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseFilter = void 0; -class BaseFilter { - async sendMetadata(metadata) { - return metadata; - } - receiveMetadata(metadata) { - return metadata; - } - async sendMessage(message) { - return message; - } - async receiveMessage(message) { - return message; - } - receiveTrailers(status) { - return status; - } -} -exports.BaseFilter = BaseFilter; -//# sourceMappingURL=filter.js.map - -/***/ }), - -/***/ 24000: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseCIDR = parseCIDR; -exports.mapProxyName = mapProxyName; -exports.getProxiedConnection = getProxiedConnection; -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const net_1 = __nccwpck_require__(41808); -const http = __nccwpck_require__(13685); -const logging = __nccwpck_require__(35993); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const url_1 = __nccwpck_require__(57310); -const resolver_dns_1 = __nccwpck_require__(54886); -const TRACER_NAME = 'proxy'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -function getProxyInfo() { - let proxyEnv = ''; - let envVar = ''; - /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. - * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The - * fallback behavior can be removed if there's a demand for it. - */ - if (process.env.grpc_proxy) { - envVar = 'grpc_proxy'; - proxyEnv = process.env.grpc_proxy; - } - else if (process.env.https_proxy) { - envVar = 'https_proxy'; - proxyEnv = process.env.https_proxy; - } - else if (process.env.http_proxy) { - envVar = 'http_proxy'; - proxyEnv = process.env.http_proxy; - } - else { - return {}; - } - let proxyUrl; - try { - proxyUrl = new url_1.URL(proxyEnv); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); - return {}; - } - if (proxyUrl.protocol !== 'http:') { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); - return {}; - } - let userCred = null; - if (proxyUrl.username) { - if (proxyUrl.password) { - (0, logging_1.log)(constants_1.LogVerbosity.INFO, 'userinfo found in proxy URI'); - userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); - } - else { - userCred = proxyUrl.username; - } - } - const hostname = proxyUrl.hostname; - let port = proxyUrl.port; - /* The proxy URL uses the scheme "http:", which has a default port number of - * 80. We need to set that explicitly here if it is omitted because otherwise - * it will use gRPC's default port 443. */ - if (port === '') { - port = '80'; - } - const result = { - address: `${hostname}:${port}`, - }; - if (userCred) { - result.creds = userCred; - } - trace('Proxy server ' + result.address + ' set by environment variable ' + envVar); - return result; -} -function getNoProxyHostList() { - /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ - let noProxyStr = process.env.no_grpc_proxy; - let envVar = 'no_grpc_proxy'; - if (!noProxyStr) { - noProxyStr = process.env.no_proxy; - envVar = 'no_proxy'; - } - if (noProxyStr) { - trace('No proxy server list set by environment variable ' + envVar); - return noProxyStr.split(','); - } - else { - return []; - } -} -/* - * The groups correspond to CIDR parts as follows: - * 1. ip - * 2. prefixLength - */ -function parseCIDR(cidrString) { - const splitRange = cidrString.split('/'); - if (splitRange.length !== 2) { - return null; - } - const prefixLength = parseInt(splitRange[1], 10); - if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { - return null; - } - return { - ip: ipToInt(splitRange[0]), - prefixLength: prefixLength - }; -} -function ipToInt(ip) { - return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); -} -function isIpInCIDR(cidr, serverHost) { - const ip = cidr.ip; - const mask = -1 << (32 - cidr.prefixLength); - const hostIP = ipToInt(serverHost); - return (hostIP & mask) === (ip & mask); -} -function hostMatchesNoProxyList(serverHost) { - for (const host of getNoProxyHostList()) { - const parsedCIDR = parseCIDR(host); - // host is a CIDR and serverHost is an IP address - if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { - return true; - } - else if (serverHost.endsWith(host)) { - // host is a single IP or a domain name suffix - return true; - } - } - return false; -} -function mapProxyName(target, options) { - var _a; - const noProxyResult = { - target: target, - extraOptions: {}, - }; - if (((_a = options['grpc.enable_http_proxy']) !== null && _a !== void 0 ? _a : 1) === 0) { - return noProxyResult; - } - if (target.scheme === 'unix') { - return noProxyResult; - } - const proxyInfo = getProxyInfo(); - if (!proxyInfo.address) { - return noProxyResult; - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (!hostPort) { - return noProxyResult; - } - const serverHost = hostPort.host; - if (hostMatchesNoProxyList(serverHost)) { - trace('Not using proxy for target in no_proxy list: ' + (0, uri_parser_1.uriToString)(target)); - return noProxyResult; - } - const extraOptions = { - 'grpc.http_connect_target': (0, uri_parser_1.uriToString)(target), - }; - if (proxyInfo.creds) { - extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; - } - return { - target: { - scheme: 'dns', - path: proxyInfo.address, - }, - extraOptions: extraOptions, - }; -} -function getProxiedConnection(address, channelOptions) { - var _a; - if (!('grpc.http_connect_target' in channelOptions)) { - return Promise.resolve(null); - } - const realTarget = channelOptions['grpc.http_connect_target']; - const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); - if (parsedTarget === null) { - return Promise.resolve(null); - } - const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); - if (splitHostPost === null) { - return Promise.resolve(null); - } - const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`; - const options = { - method: 'CONNECT', - path: hostPort, - }; - const headers = { - Host: hostPort, - }; - // Connect to the subchannel address as a proxy - if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { - options.host = address.host; - options.port = address.port; - } - else { - options.socketPath = address.path; - } - if ('grpc.http_connect_creds' in channelOptions) { - headers['Proxy-Authorization'] = - 'Basic ' + - Buffer.from(channelOptions['grpc.http_connect_creds']).toString('base64'); - } - options.headers = headers; - const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); - trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); - return new Promise((resolve, reject) => { - const request = http.request(options); - request.once('connect', (res, socket, head) => { - request.removeAllListeners(); - socket.removeAllListeners(); - if (res.statusCode === 200) { - trace('Successfully connected to ' + - options.path + - ' through proxy ' + - proxyAddressString); - // The HTTP client may have already read a few bytes of the proxied - // connection. If that's the case, put them back into the socket. - // See https://github.com/grpc/grpc-node/issues/2744. - if (head.length > 0) { - socket.unshift(head); - } - trace('Successfully established a plaintext connection to ' + - options.path + - ' through proxy ' + - proxyAddressString); - resolve(socket); - } - else { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to ' + - options.path + - ' through proxy ' + - proxyAddressString + - ' with status ' + - res.statusCode); - reject(); - } - }); - request.once('error', err => { - request.removeAllListeners(); - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to proxy ' + - proxyAddressString + - ' with error ' + - err.message); - reject(); - }); - request.end(); - }); -} -//# sourceMappingURL=http_proxy.js.map - -/***/ }), - -/***/ 7025: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.experimental = exports.ServerMetricRecorder = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = exports.addAdminServicesToServer = exports.getChannelzHandlers = exports.getChannelzServiceDefinition = exports.InterceptorConfigurationError = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.compressionAlgorithms = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = void 0; -const call_credentials_1 = __nccwpck_require__(21426); -Object.defineProperty(exports, "CallCredentials", ({ enumerable: true, get: function () { return call_credentials_1.CallCredentials; } })); -const channel_1 = __nccwpck_require__(13860); -Object.defineProperty(exports, "Channel", ({ enumerable: true, get: function () { return channel_1.ChannelImplementation; } })); -const compression_algorithms_1 = __nccwpck_require__(54789); -Object.defineProperty(exports, "compressionAlgorithms", ({ enumerable: true, get: function () { return compression_algorithms_1.CompressionAlgorithms; } })); -const connectivity_state_1 = __nccwpck_require__(80878); -Object.defineProperty(exports, "connectivityState", ({ enumerable: true, get: function () { return connectivity_state_1.ConnectivityState; } })); -const channel_credentials_1 = __nccwpck_require__(44030); -Object.defineProperty(exports, "ChannelCredentials", ({ enumerable: true, get: function () { return channel_credentials_1.ChannelCredentials; } })); -const client_1 = __nccwpck_require__(87172); -Object.defineProperty(exports, "Client", ({ enumerable: true, get: function () { return client_1.Client; } })); -const constants_1 = __nccwpck_require__(90634); -Object.defineProperty(exports, "logVerbosity", ({ enumerable: true, get: function () { return constants_1.LogVerbosity; } })); -Object.defineProperty(exports, "status", ({ enumerable: true, get: function () { return constants_1.Status; } })); -Object.defineProperty(exports, "propagate", ({ enumerable: true, get: function () { return constants_1.Propagate; } })); -const logging = __nccwpck_require__(35993); -const make_client_1 = __nccwpck_require__(38541); -Object.defineProperty(exports, "loadPackageDefinition", ({ enumerable: true, get: function () { return make_client_1.loadPackageDefinition; } })); -Object.defineProperty(exports, "makeClientConstructor", ({ enumerable: true, get: function () { return make_client_1.makeClientConstructor; } })); -Object.defineProperty(exports, "makeGenericClientConstructor", ({ enumerable: true, get: function () { return make_client_1.makeClientConstructor; } })); -const metadata_1 = __nccwpck_require__(83665); -Object.defineProperty(exports, "Metadata", ({ enumerable: true, get: function () { return metadata_1.Metadata; } })); -const server_1 = __nccwpck_require__(33389); -Object.defineProperty(exports, "Server", ({ enumerable: true, get: function () { return server_1.Server; } })); -const server_credentials_1 = __nccwpck_require__(63828); -Object.defineProperty(exports, "ServerCredentials", ({ enumerable: true, get: function () { return server_credentials_1.ServerCredentials; } })); -const status_builder_1 = __nccwpck_require__(73155); -Object.defineProperty(exports, "StatusBuilder", ({ enumerable: true, get: function () { return status_builder_1.StatusBuilder; } })); -/**** Client Credentials ****/ -// Using assign only copies enumerable properties, which is what we want -exports.credentials = { - /** - * Combine a ChannelCredentials with any number of CallCredentials into a - * single ChannelCredentials object. - * @param channelCredentials The ChannelCredentials object. - * @param callCredentials Any number of CallCredentials objects. - * @return The resulting ChannelCredentials object. - */ - combineChannelCredentials: (channelCredentials, ...callCredentials) => { - return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); - }, - /** - * Combine any number of CallCredentials into a single CallCredentials - * object. - * @param first The first CallCredentials object. - * @param additional Any number of additional CallCredentials objects. - * @return The resulting CallCredentials object. - */ - combineCallCredentials: (first, ...additional) => { - return additional.reduce((acc, other) => acc.compose(other), first); - }, - // from channel-credentials.ts - createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, - createSsl: channel_credentials_1.ChannelCredentials.createSsl, - createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, - // from call-credentials.ts - createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, - createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, - createEmpty: call_credentials_1.CallCredentials.createEmpty, -}; -/** - * Close a Client object. - * @param client The client to close. - */ -const closeClient = (client) => client.close(); -exports.closeClient = closeClient; -const waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); -exports.waitForClientReady = waitForClientReady; -/* eslint-enable @typescript-eslint/no-explicit-any */ -/**** Unimplemented function stubs ****/ -/* eslint-disable @typescript-eslint/no-explicit-any */ -const loadObject = (value, options) => { - throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); -}; -exports.loadObject = loadObject; -const load = (filename, format, options) => { - throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); -}; -exports.load = load; -const setLogger = (logger) => { - logging.setLogger(logger); -}; -exports.setLogger = setLogger; -const setLogVerbosity = (verbosity) => { - logging.setLoggerVerbosity(verbosity); -}; -exports.setLogVerbosity = setLogVerbosity; -const getClientChannel = (client) => { - return client_1.Client.prototype.getChannel.call(client); -}; -exports.getClientChannel = getClientChannel; -var client_interceptors_1 = __nccwpck_require__(82127); -Object.defineProperty(exports, "ListenerBuilder", ({ enumerable: true, get: function () { return client_interceptors_1.ListenerBuilder; } })); -Object.defineProperty(exports, "RequesterBuilder", ({ enumerable: true, get: function () { return client_interceptors_1.RequesterBuilder; } })); -Object.defineProperty(exports, "InterceptingCall", ({ enumerable: true, get: function () { return client_interceptors_1.InterceptingCall; } })); -Object.defineProperty(exports, "InterceptorConfigurationError", ({ enumerable: true, get: function () { return client_interceptors_1.InterceptorConfigurationError; } })); -var channelz_1 = __nccwpck_require__(79975); -Object.defineProperty(exports, "getChannelzServiceDefinition", ({ enumerable: true, get: function () { return channelz_1.getChannelzServiceDefinition; } })); -Object.defineProperty(exports, "getChannelzHandlers", ({ enumerable: true, get: function () { return channelz_1.getChannelzHandlers; } })); -var admin_1 = __nccwpck_require__(8258); -Object.defineProperty(exports, "addAdminServicesToServer", ({ enumerable: true, get: function () { return admin_1.addAdminServicesToServer; } })); -var server_interceptors_1 = __nccwpck_require__(20998); -Object.defineProperty(exports, "ServerListenerBuilder", ({ enumerable: true, get: function () { return server_interceptors_1.ServerListenerBuilder; } })); -Object.defineProperty(exports, "ResponderBuilder", ({ enumerable: true, get: function () { return server_interceptors_1.ResponderBuilder; } })); -Object.defineProperty(exports, "ServerInterceptingCall", ({ enumerable: true, get: function () { return server_interceptors_1.ServerInterceptingCall; } })); -var orca_1 = __nccwpck_require__(31791); -Object.defineProperty(exports, "ServerMetricRecorder", ({ enumerable: true, get: function () { return orca_1.ServerMetricRecorder; } })); -const experimental = __nccwpck_require__(37626); -exports.experimental = experimental; -const resolver_dns = __nccwpck_require__(54886); -const resolver_uds = __nccwpck_require__(5252); -const resolver_ip = __nccwpck_require__(97902); -const load_balancer_pick_first = __nccwpck_require__(38977); -const load_balancer_round_robin = __nccwpck_require__(92787); -const load_balancer_outlier_detection = __nccwpck_require__(76828); -const load_balancer_weighted_round_robin = __nccwpck_require__(69544); -const channelz = __nccwpck_require__(79975); -(() => { - resolver_dns.setup(); - resolver_uds.setup(); - resolver_ip.setup(); - load_balancer_pick_first.setup(); - load_balancer_round_robin.setup(); - load_balancer_outlier_detection.setup(); - load_balancer_weighted_round_robin.setup(); - channelz.setup(); -})(); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 69672: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.InternalChannel = exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0; -const channel_credentials_1 = __nccwpck_require__(44030); -const resolving_load_balancer_1 = __nccwpck_require__(19192); -const subchannel_pool_1 = __nccwpck_require__(87440); -const picker_1 = __nccwpck_require__(81611); -const metadata_1 = __nccwpck_require__(83665); -const constants_1 = __nccwpck_require__(90634); -const filter_stack_1 = __nccwpck_require__(66450); -const compression_filter_1 = __nccwpck_require__(47616); -const resolver_1 = __nccwpck_require__(31594); -const logging_1 = __nccwpck_require__(35993); -const http_proxy_1 = __nccwpck_require__(24000); -const uri_parser_1 = __nccwpck_require__(65974); -const connectivity_state_1 = __nccwpck_require__(80878); -const channelz_1 = __nccwpck_require__(79975); -const load_balancing_call_1 = __nccwpck_require__(776); -const deadline_1 = __nccwpck_require__(511); -const resolving_call_1 = __nccwpck_require__(39909); -const call_number_1 = __nccwpck_require__(70380); -const control_plane_status_1 = __nccwpck_require__(39129); -const retrying_call_1 = __nccwpck_require__(48159); -const subchannel_interface_1 = __nccwpck_require__(12258); -/** - * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args - */ -const MAX_TIMEOUT_TIME = 2147483647; -const MIN_IDLE_TIMEOUT_MS = 1000; -// 30 minutes -const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; -const RETRY_THROTTLER_MAP = new Map(); -const DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; // 16 MB -const DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; // 1 MB -class ChannelSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, channel) { - super(childSubchannel); - this.channel = channel; - this.refCount = 0; - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { - channel.throttleKeepalive(keepaliveTime); - }; - } - ref() { - if (this.refCount === 0) { - this.child.addConnectivityStateListener(this.subchannelStateListener); - this.channel.addWrappedSubchannel(this); - } - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - this.child.removeConnectivityStateListener(this.subchannelStateListener); - this.channel.removeWrappedSubchannel(this); - } - } -} -class ShutdownPicker { - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.DROP, - status: { - code: constants_1.Status.UNAVAILABLE, - details: 'Channel closed before call started', - metadata: new metadata_1.Metadata() - }, - subchannel: null, - onCallStarted: null, - onCallEnded: null - }; - } -} -exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = 'grpc.internal.no_subchannel'; -class ChannelzInfoTracker { - constructor(target) { - this.target = target; - this.trace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.state = connectivity_state_1.ConnectivityState.IDLE; - } - getChannelzInfoCallback() { - return () => { - return { - target: this.target, - state: this.state, - trace: this.trace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }; - }; - } -} -class InternalChannel { - constructor(target, credentials, options) { - var _a, _b, _c, _d, _e, _f; - this.credentials = credentials; - this.options = options; - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - this.currentPicker = new picker_1.UnavailablePicker(); - /** - * Calls queued up to get a call config. Should only be populated before the - * first time the resolver returns a result, which includes the ConfigSelector. - */ - this.configSelectionQueue = []; - this.pickQueue = []; - this.connectivityStateWatchers = []; - /** - * This timer does not do anything on its own. Its purpose is to hold the - * event loop open while there are any pending calls for the channel that - * have not yet been assigned to specific subchannels. In other words, - * the invariant is that callRefTimer is reffed if and only if pickQueue - * is non-empty. In addition, the timer is null while the state is IDLE or - * SHUTDOWN and there are no pending calls. - */ - this.callRefTimer = null; - this.configSelector = null; - /** - * This is the error from the name resolver if it failed most recently. It - * is only used to end calls that start while there is no config selector - * and the name resolver is in backoff, so it should be nulled if - * configSelector becomes set or the channel state becomes anything other - * than TRANSIENT_FAILURE. - */ - this.currentResolutionError = null; - this.wrappedSubchannels = new Set(); - this.callCount = 0; - this.idleTimer = null; - // Channelz info - this.channelzEnabled = true; - /** - * Randomly generated ID to be passed to the config selector, for use by - * ring_hash in xDS. An integer distributed approximately uniformly between - * 0 and MAX_SAFE_INTEGER. - */ - this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); - if (typeof target !== 'string') { - throw new TypeError('Channel target must be a string'); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError('Channel credentials must be a ChannelCredentials object'); - } - if (options) { - if (typeof options !== 'object') { - throw new TypeError('Channel options must be an object'); - } - } - this.channelzInfoTracker = new ChannelzInfoTracker(target); - const originalTargetUri = (0, uri_parser_1.parseUri)(target); - if (originalTargetUri === null) { - throw new Error(`Could not parse target name "${target}"`); - } - /* This ensures that the target has a scheme that is registered with the - * resolver */ - const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); - if (defaultSchemeMapResult === null) { - throw new Error(`Could not find a default scheme for target name "${target}"`); - } - if (this.options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - } - this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Channel created'); - } - if (this.options['grpc.default_authority']) { - this.defaultAuthority = this.options['grpc.default_authority']; - } - else { - this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); - } - const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); - this.target = proxyMapResult.target; - this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); - /* The global boolean parameter to getSubchannelPool has the inverse meaning to what - * the grpc.use_local_subchannel_pool channel option means. */ - this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options['grpc.use_local_subchannel_pool']) !== null && _a !== void 0 ? _a : 0) === 0); - this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options['grpc.retry_buffer_size']) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options['grpc.per_rpc_retry_buffer_size']) !== null && _c !== void 0 ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); - this.keepaliveTime = (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : -1; - this.idleTimeoutMs = Math.max((_e = this.options['grpc.client_idle_timeout_ms']) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); - const channelControlHelper = { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const finalSubchannelArgs = {}; - for (const [key, value] of Object.entries(subchannelArgs)) { - if (!key.startsWith(exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { - finalSubchannelArgs[key] = value; - } - } - const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials); - subchannel.throttleKeepalive(this.keepaliveTime); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Created subchannel or used existing subchannel', subchannel.getChannelzRef()); - } - const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); - return wrappedSubchannel; - }, - updateState: (connectivityState, picker) => { - this.currentPicker = picker; - const queueCopy = this.pickQueue.slice(); - this.pickQueue = []; - if (queueCopy.length > 0) { - this.callRefTimerUnref(); - } - for (const call of queueCopy) { - call.doPick(); - } - this.updateState(connectivityState); - }, - requestReresolution: () => { - // This should never be called. - throw new Error('Resolving load balancer should never call requestReresolution'); - }, - addChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.refChild(child); - } - }, - removeChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.unrefChild(child); - } - }, - }; - this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => { - var _a; - if (serviceConfig.retryThrottling) { - RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); - } - else { - RETRY_THROTTLER_MAP.delete(this.getTarget()); - } - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Address resolution succeeded'); - } - (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); - this.configSelector = configSelector; - this.currentResolutionError = null; - /* We process the queue asynchronously to ensure that the corresponding - * load balancer update has completed. */ - process.nextTick(() => { - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.getConfig(); - } - }); - }, status => { - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_WARNING', 'Address resolution failed with code ' + - status.code + - ' and details "' + - status.details + - '"'); - } - if (this.configSelectionQueue.length > 0) { - this.trace('Name resolution failed with calls queued for config selection'); - } - if (this.configSelector === null) { - this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); - } - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.reportResolverError(status); - } - }); - this.filterStackFactory = new filter_stack_1.FilterStackFactory([ - new compression_filter_1.CompressionFilterFactory(this, this.options), - ]); - this.trace('Channel constructed with options ' + - JSON.stringify(options, undefined, 2)); - const error = new Error(); - if ((0, logging_1.isTracerEnabled)('channel_stacktrace')) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'channel_stacktrace', '(' + - this.channelzRef.id + - ') ' + - 'Channel constructed \n' + - ((_f = error.stack) === null || _f === void 0 ? void 0 : _f.substring(error.stack.indexOf('\n') + 1))); - } - this.lastActivityTimestamp = new Date(); - } - trace(text, verbosityOverride) { - (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, 'channel', '(' + this.channelzRef.id + ') ' + (0, uri_parser_1.uriToString)(this.target) + ' ' + text); - } - callRefTimerRef() { - var _a, _b, _c, _d; - if (!this.callRefTimer) { - this.callRefTimer = setInterval(() => { }, MAX_TIMEOUT_TIME); - } - // If the hasRef function does not exist, always run the code - if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { - this.trace('callRefTimer.ref | configSelectionQueue.length=' + - this.configSelectionQueue.length + - ' pickQueue.length=' + - this.pickQueue.length); - (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); - } - } - callRefTimerUnref() { - var _a, _b, _c; - // If the timer or the hasRef function does not exist, always run the code - if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { - this.trace('callRefTimer.unref | configSelectionQueue.length=' + - this.configSelectionQueue.length + - ' pickQueue.length=' + - this.pickQueue.length); - (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - } - removeConnectivityStateWatcher(watcherObject) { - const watcherIndex = this.connectivityStateWatchers.findIndex(value => value === watcherObject); - if (watcherIndex >= 0) { - this.connectivityStateWatchers.splice(watcherIndex, 1); - } - } - updateState(newState) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'connectivity_state', '(' + - this.channelzRef.id + - ') ' + - (0, uri_parser_1.uriToString)(this.target) + - ' ' + - connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); - } - this.connectivityState = newState; - this.channelzInfoTracker.state = newState; - const watchersCopy = this.connectivityStateWatchers.slice(); - for (const watcherObject of watchersCopy) { - if (newState !== watcherObject.currentState) { - if (watcherObject.timer) { - clearTimeout(watcherObject.timer); - } - this.removeConnectivityStateWatcher(watcherObject); - watcherObject.callback(); - } - } - if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.currentResolutionError = null; - } - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - for (const wrappedSubchannel of this.wrappedSubchannels) { - wrappedSubchannel.throttleKeepalive(newKeepaliveTime); - } - } - } - addWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.add(wrappedSubchannel); - } - removeWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.delete(wrappedSubchannel); - } - doPick(metadata, extraPickInfo) { - return this.currentPicker.pick({ - metadata: metadata, - extraPickInfo: extraPickInfo, - }); - } - queueCallForPick(call) { - this.pickQueue.push(call); - this.callRefTimerRef(); - } - getConfig(method, metadata) { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { - this.resolvingLoadBalancer.exitIdle(); - } - if (this.configSelector) { - return { - type: 'SUCCESS', - config: this.configSelector.invoke(method, metadata, this.randomChannelId), - }; - } - else { - if (this.currentResolutionError) { - return { - type: 'ERROR', - error: this.currentResolutionError, - }; - } - else { - return { - type: 'NONE', - }; - } - } - } - queueCallForConfig(call) { - this.configSelectionQueue.push(call); - this.callRefTimerRef(); - } - enterIdle() { - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.IDLE); - this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); - if (this.idleTimer) { - clearTimeout(this.idleTimer); - this.idleTimer = null; - } - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - this.callRefTimer = null; - } - } - startIdleTimeout(timeoutMs) { - var _a, _b; - this.idleTimer = setTimeout(() => { - if (this.callCount > 0) { - /* If there is currently a call, the channel will not go idle for a - * period of at least idleTimeoutMs, so check again after that time. - */ - this.startIdleTimeout(this.idleTimeoutMs); - return; - } - const now = new Date(); - const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); - if (timeSinceLastActivity >= this.idleTimeoutMs) { - this.trace('Idle timer triggered after ' + - this.idleTimeoutMs + - 'ms of inactivity'); - this.enterIdle(); - } - else { - /* Whenever the timer fires with the latest activity being too recent, - * set the timer again for the time when the time since the last - * activity is equal to the timeout. This should result in the timer - * firing no more than once every idleTimeoutMs/2 on average. */ - this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); - } - }, timeoutMs); - (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - maybeStartIdleTimer() { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && - !this.idleTimer) { - this.startIdleTimeout(this.idleTimeoutMs); - } - } - onCallStart() { - if (this.channelzEnabled) { - this.channelzInfoTracker.callTracker.addCallStarted(); - } - this.callCount += 1; - } - onCallEnd(status) { - if (this.channelzEnabled) { - if (status.code === constants_1.Status.OK) { - this.channelzInfoTracker.callTracker.addCallSucceeded(); - } - else { - this.channelzInfoTracker.callTracker.addCallFailed(); - } - } - this.callCount -= 1; - this.lastActivityTimestamp = new Date(); - this.maybeStartIdleTimer(); - } - createLoadBalancingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createLoadBalancingCall [' + callNumber + '] method="' + method + '"'); - return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); - } - createRetryingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createRetryingCall [' + callNumber + '] method="' + method + '"'); - return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); - } - createResolvingCall(method, deadline, host, parentCall, propagateFlags) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createResolvingCall [' + - callNumber + - '] method="' + - method + - '", deadline=' + - (0, deadline_1.deadlineToString)(deadline)); - const finalOptions = { - deadline: deadline, - flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, - host: host !== null && host !== void 0 ? host : this.defaultAuthority, - parentCall: parentCall, - }; - const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber); - this.onCallStart(); - call.addStatusWatcher(status => { - this.onCallEnd(status); - }); - return call; - } - close() { - var _a; - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); - this.currentPicker = new ShutdownPicker(); - for (const call of this.configSelectionQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); - } - this.configSelectionQueue = []; - for (const call of this.pickQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); - } - this.pickQueue = []; - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - } - if (this.idleTimer) { - clearTimeout(this.idleTimer); - } - if (this.channelzEnabled) { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - this.subchannelPool.unrefUnusedSubchannels(); - (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); - this.configSelector = null; - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - const connectivityState = this.connectivityState; - if (tryToConnect) { - this.resolvingLoadBalancer.exitIdle(); - this.lastActivityTimestamp = new Date(); - this.maybeStartIdleTimer(); - } - return connectivityState; - } - watchConnectivityState(currentState, deadline, callback) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error('Channel has been shut down'); - } - let timer = null; - if (deadline !== Infinity) { - const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); - const now = new Date(); - if (deadline === -Infinity || deadlineDate <= now) { - process.nextTick(callback, new Error('Deadline passed without connectivity state change')); - return; - } - timer = setTimeout(() => { - this.removeConnectivityStateWatcher(watcherObject); - callback(new Error('Deadline passed without connectivity state change')); - }, deadlineDate.getTime() - now.getTime()); - } - const watcherObject = { - currentState, - callback, - timer, - }; - this.connectivityStateWatchers.push(watcherObject); - } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== 'string') { - throw new TypeError('Channel#createCall: method must be a string'); - } - if (!(typeof deadline === 'number' || deadline instanceof Date)) { - throw new TypeError('Channel#createCall: deadline must be a number or Date'); - } - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error('Channel has been shut down'); - } - return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); - } - getOptions() { - return this.options; - } -} -exports.InternalChannel = InternalChannel; -//# sourceMappingURL=internal-channel.js.map - -/***/ }), - -/***/ 17559: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2020 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChildLoadBalancerHandler = void 0; -const load_balancer_1 = __nccwpck_require__(52680); -const connectivity_state_1 = __nccwpck_require__(80878); -const TYPE_NAME = 'child_load_balancer_helper'; -class ChildLoadBalancerHandler { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.currentChild = null; - this.pendingChild = null; - this.latestConfig = null; - this.ChildPolicyHelper = class { - constructor(parent) { - this.parent = parent; - this.child = null; - } - createSubchannel(subchannelAddress, subchannelArgs) { - return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - } - updateState(connectivityState, picker, errorMessage) { - var _a; - if (this.calledByPendingChild()) { - if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { - return; - } - (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy(); - this.parent.currentChild = this.parent.pendingChild; - this.parent.pendingChild = null; - } - else if (!this.calledByCurrentChild()) { - return; - } - this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - requestReresolution() { - var _a; - const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild; - if (this.child === latestChild) { - this.parent.channelControlHelper.requestReresolution(); - } - } - setChild(newChild) { - this.child = newChild; - } - addChannelzChild(child) { - this.parent.channelControlHelper.addChannelzChild(child); - } - removeChannelzChild(child) { - this.parent.channelControlHelper.removeChannelzChild(child); - } - calledByPendingChild() { - return this.child === this.parent.pendingChild; - } - calledByCurrentChild() { - return this.child === this.parent.currentChild; - } - }; - } - configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { - return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); - } - /** - * Prerequisites: lbConfig !== null and lbConfig.name is registered - * @param endpointList - * @param lbConfig - * @param attributes - */ - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - let childToUpdate; - if (this.currentChild === null || - this.latestConfig === null || - this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { - const newHelper = new this.ChildPolicyHelper(this); - const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper); - newHelper.setChild(newChild); - if (this.currentChild === null) { - this.currentChild = newChild; - childToUpdate = this.currentChild; - } - else { - if (this.pendingChild) { - this.pendingChild.destroy(); - } - this.pendingChild = newChild; - childToUpdate = this.pendingChild; - } - } - else { - if (this.pendingChild === null) { - childToUpdate = this.currentChild; - } - else { - childToUpdate = this.pendingChild; - } - } - this.latestConfig = lbConfig; - return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); - } - exitIdle() { - if (this.currentChild) { - this.currentChild.exitIdle(); - if (this.pendingChild) { - this.pendingChild.exitIdle(); - } - } - } - resetBackoff() { - if (this.currentChild) { - this.currentChild.resetBackoff(); - if (this.pendingChild) { - this.pendingChild.resetBackoff(); - } - } - } - destroy() { - /* Note: state updates are only propagated from the child balancer if that - * object is equal to this.currentChild or this.pendingChild. Since this - * function sets both of those to null, no further state updates will - * occur after this function returns. */ - if (this.currentChild) { - this.currentChild.destroy(); - this.currentChild = null; - } - if (this.pendingChild) { - this.pendingChild.destroy(); - this.pendingChild = null; - } - } - getTypeName() { - return TYPE_NAME; - } -} -exports.ChildLoadBalancerHandler = ChildLoadBalancerHandler; -//# sourceMappingURL=load-balancer-child-handler.js.map - -/***/ }), - -/***/ 76828: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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 _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OutlierDetectionLoadBalancer = exports.OutlierDetectionLoadBalancingConfig = void 0; -exports.setup = setup; -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const duration_1 = __nccwpck_require__(62668); -const experimental_1 = __nccwpck_require__(37626); -const load_balancer_1 = __nccwpck_require__(52680); -const load_balancer_child_handler_1 = __nccwpck_require__(17559); -const picker_1 = __nccwpck_require__(81611); -const subchannel_address_1 = __nccwpck_require__(99905); -const subchannel_interface_1 = __nccwpck_require__(12258); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'outlier_detection'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'outlier_detection'; -const OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : 'true') === 'true'; -const defaultSuccessRateEjectionConfig = { - stdev_factor: 1900, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 100, -}; -const defaultFailurePercentageEjectionConfig = { - threshold: 85, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 50, -}; -function validateFieldType(obj, fieldName, expectedType, objectName) { - if (fieldName in obj && - obj[fieldName] !== undefined && - typeof obj[fieldName] !== expectedType) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } -} -function validatePositiveDuration(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - if (fieldName in obj && obj[fieldName] !== undefined) { - if (!(0, duration_1.isDuration)(obj[fieldName])) { - throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); - } - if (!(obj[fieldName].seconds >= 0 && - obj[fieldName].seconds <= 315576000000 && - obj[fieldName].nanos >= 0 && - obj[fieldName].nanos <= 999999999)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); - } - } -} -function validatePercentage(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - validateFieldType(obj, fieldName, 'number', objectName); - if (fieldName in obj && - obj[fieldName] !== undefined && - !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); - } -} -class OutlierDetectionLoadBalancingConfig { - constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { - this.childPolicy = childPolicy; - if (childPolicy.getLoadBalancerName() === 'pick_first') { - throw new Error('outlier_detection LB policy cannot have a pick_first child policy'); - } - this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 10000; - this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 30000; - this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 300000; - this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10; - this.successRateEjection = successRateEjection - ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; - this.failurePercentageEjection = failurePercentageEjection - ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - var _a, _b; - return { - outlier_detection: { - interval: (0, duration_1.msToDuration)(this.intervalMs), - base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), - max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), - max_ejection_percent: this.maxEjectionPercent, - success_rate_ejection: (_a = this.successRateEjection) !== null && _a !== void 0 ? _a : undefined, - failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : undefined, - child_policy: [this.childPolicy.toJsonObject()], - }, - }; - } - getIntervalMs() { - return this.intervalMs; - } - getBaseEjectionTimeMs() { - return this.baseEjectionTimeMs; - } - getMaxEjectionTimeMs() { - return this.maxEjectionTimeMs; - } - getMaxEjectionPercent() { - return this.maxEjectionPercent; - } - getSuccessRateEjectionConfig() { - return this.successRateEjection; - } - getFailurePercentageEjectionConfig() { - return this.failurePercentageEjection; - } - getChildPolicy() { - return this.childPolicy; - } - static createFromJson(obj) { - var _a; - validatePositiveDuration(obj, 'interval'); - validatePositiveDuration(obj, 'base_ejection_time'); - validatePositiveDuration(obj, 'max_ejection_time'); - validatePercentage(obj, 'max_ejection_percent'); - if ('success_rate_ejection' in obj && - obj.success_rate_ejection !== undefined) { - if (typeof obj.success_rate_ejection !== 'object') { - throw new Error('outlier detection config success_rate_ejection must be an object'); - } - validateFieldType(obj.success_rate_ejection, 'stdev_factor', 'number', 'success_rate_ejection'); - validatePercentage(obj.success_rate_ejection, 'enforcement_percentage', 'success_rate_ejection'); - validateFieldType(obj.success_rate_ejection, 'minimum_hosts', 'number', 'success_rate_ejection'); - validateFieldType(obj.success_rate_ejection, 'request_volume', 'number', 'success_rate_ejection'); - } - if ('failure_percentage_ejection' in obj && - obj.failure_percentage_ejection !== undefined) { - if (typeof obj.failure_percentage_ejection !== 'object') { - throw new Error('outlier detection config failure_percentage_ejection must be an object'); - } - validatePercentage(obj.failure_percentage_ejection, 'threshold', 'failure_percentage_ejection'); - validatePercentage(obj.failure_percentage_ejection, 'enforcement_percentage', 'failure_percentage_ejection'); - validateFieldType(obj.failure_percentage_ejection, 'minimum_hosts', 'number', 'failure_percentage_ejection'); - validateFieldType(obj.failure_percentage_ejection, 'request_volume', 'number', 'failure_percentage_ejection'); - } - if (!('child_policy' in obj) || !Array.isArray(obj.child_policy)) { - throw new Error('outlier detection config child_policy must be an array'); - } - const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); - if (!childPolicy) { - throw new Error('outlier detection config child_policy: no valid recognized policy found'); - } - return new OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a = obj.max_ejection_percent) !== null && _a !== void 0 ? _a : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); - } -} -exports.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; -class OutlierDetectionSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, mapEntry) { - super(childSubchannel); - this.mapEntry = mapEntry; - this.refCount = 0; - } - ref() { - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - if (this.mapEntry) { - const index = this.mapEntry.subchannelWrappers.indexOf(this); - if (index >= 0) { - this.mapEntry.subchannelWrappers.splice(index, 1); - } - } - } - } - eject() { - this.setHealthy(false); - } - uneject() { - this.setHealthy(true); - } - getMapEntry() { - return this.mapEntry; - } - getWrappedSubchannel() { - return this.child; - } -} -function createEmptyBucket() { - return { - success: 0, - failure: 0, - }; -} -class CallCounter { - constructor() { - this.activeBucket = createEmptyBucket(); - this.inactiveBucket = createEmptyBucket(); - } - addSuccess() { - this.activeBucket.success += 1; - } - addFailure() { - this.activeBucket.failure += 1; - } - switchBuckets() { - this.inactiveBucket = this.activeBucket; - this.activeBucket = createEmptyBucket(); - } - getLastSuccesses() { - return this.inactiveBucket.success; - } - getLastFailures() { - return this.inactiveBucket.failure; - } -} -class OutlierDetectionPicker { - constructor(wrappedPicker, countCalls) { - this.wrappedPicker = wrappedPicker; - this.countCalls = countCalls; - } - pick(pickArgs) { - const wrappedPick = this.wrappedPicker.pick(pickArgs); - if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { - const subchannelWrapper = wrappedPick.subchannel; - const mapEntry = subchannelWrapper.getMapEntry(); - if (mapEntry) { - let onCallEnded = wrappedPick.onCallEnded; - if (this.countCalls) { - onCallEnded = (statusCode, details, metadata) => { - var _a; - if (statusCode === constants_1.Status.OK) { - mapEntry.counter.addSuccess(); - } - else { - mapEntry.counter.addFailure(); - } - (_a = wrappedPick.onCallEnded) === null || _a === void 0 ? void 0 : _a.call(wrappedPick, statusCode, details, metadata); - }; - } - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded: onCallEnded }); - } - else { - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } - else { - return wrappedPick; - } - } -} -class OutlierDetectionLoadBalancer { - constructor(channelControlHelper) { - this.entryMap = new subchannel_address_1.EndpointMap(); - this.latestConfig = null; - this.timerStartTime = null; - this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); - const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); - if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) { - // If the address is ejected, propagate that to the new subchannel wrapper - subchannelWrapper.eject(); - } - mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper); - return subchannelWrapper; - }, - updateState: (connectivityState, picker, errorMessage) => { - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage); - } - else { - channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - }, - })); - this.ejectionTimer = setInterval(() => { }, 0); - clearInterval(this.ejectionTimer); - } - isCountingEnabled() { - return (this.latestConfig !== null && - (this.latestConfig.getSuccessRateEjectionConfig() !== null || - this.latestConfig.getFailurePercentageEjectionConfig() !== null)); - } - getCurrentEjectionPercent() { - let ejectionCount = 0; - for (const mapEntry of this.entryMap.values()) { - if (mapEntry.currentEjectionTimestamp !== null) { - ejectionCount += 1; - } - } - return (ejectionCount * 100) / this.entryMap.size; - } - runSuccessRateCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); - if (!successRateConfig) { - return; - } - trace('Running success rate check'); - // Step 1 - const targetRequestVolume = successRateConfig.request_volume; - let addresesWithTargetVolume = 0; - const successRates = []; - for (const [endpoint, mapEntry] of this.entryMap.entries()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace('Stats for ' + - (0, subchannel_address_1.endpointToString)(endpoint) + - ': successes=' + - successes + - ' failures=' + - failures + - ' targetRequestVolume=' + - targetRequestVolume); - if (successes + failures >= targetRequestVolume) { - addresesWithTargetVolume += 1; - successRates.push(successes / (successes + failures)); - } - } - trace('Found ' + - addresesWithTargetVolume + - ' success rate candidates; currentEjectionPercent=' + - this.getCurrentEjectionPercent() + - ' successRates=[' + - successRates + - ']'); - if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { - return; - } - // Step 2 - const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; - let successRateDeviationSum = 0; - for (const rate of successRates) { - const deviation = rate - successRateMean; - successRateDeviationSum += deviation * deviation; - } - const successRateVariance = successRateDeviationSum / successRates.length; - const successRateStdev = Math.sqrt(successRateVariance); - const ejectionThreshold = successRateMean - - successRateStdev * (successRateConfig.stdev_factor / 1000); - trace('stdev=' + successRateStdev + ' ejectionThreshold=' + ejectionThreshold); - // Step 3 - for (const [address, mapEntry] of this.entryMap.entries()) { - // Step 3.i - if (this.getCurrentEjectionPercent() >= - this.latestConfig.getMaxEjectionPercent()) { - break; - } - // Step 3.ii - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures < targetRequestVolume) { - continue; - } - // Step 3.iii - const successRate = successes / (successes + failures); - trace('Checking candidate ' + address + ' successRate=' + successRate); - if (successRate < ejectionThreshold) { - const randomNumber = Math.random() * 100; - trace('Candidate ' + - address + - ' randomNumber=' + - randomNumber + - ' enforcement_percentage=' + - successRateConfig.enforcement_percentage); - if (randomNumber < successRateConfig.enforcement_percentage) { - trace('Ejecting candidate ' + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - runFailurePercentageCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); - if (!failurePercentageConfig) { - return; - } - trace('Running failure percentage check. threshold=' + - failurePercentageConfig.threshold + - ' request volume threshold=' + - failurePercentageConfig.request_volume); - // Step 1 - let addressesWithTargetVolume = 0; - for (const mapEntry of this.entryMap.values()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures >= failurePercentageConfig.request_volume) { - addressesWithTargetVolume += 1; - } - } - if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { - return; - } - // Step 2 - for (const [address, mapEntry] of this.entryMap.entries()) { - // Step 2.i - if (this.getCurrentEjectionPercent() >= - this.latestConfig.getMaxEjectionPercent()) { - break; - } - // Step 2.ii - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace('Candidate successes=' + successes + ' failures=' + failures); - if (successes + failures < failurePercentageConfig.request_volume) { - continue; - } - // Step 2.iii - const failurePercentage = (failures * 100) / (failures + successes); - if (failurePercentage > failurePercentageConfig.threshold) { - const randomNumber = Math.random() * 100; - trace('Candidate ' + - address + - ' randomNumber=' + - randomNumber + - ' enforcement_percentage=' + - failurePercentageConfig.enforcement_percentage); - if (randomNumber < failurePercentageConfig.enforcement_percentage) { - trace('Ejecting candidate ' + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - eject(mapEntry, ejectionTimestamp) { - mapEntry.currentEjectionTimestamp = new Date(); - mapEntry.ejectionTimeMultiplier += 1; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.eject(); - } - } - uneject(mapEntry) { - mapEntry.currentEjectionTimestamp = null; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.uneject(); - } - } - switchAllBuckets() { - for (const mapEntry of this.entryMap.values()) { - mapEntry.counter.switchBuckets(); - } - } - startTimer(delayMs) { - var _a, _b; - this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); - (_b = (_a = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - runChecks() { - const ejectionTimestamp = new Date(); - trace('Ejection timer running'); - this.switchAllBuckets(); - if (!this.latestConfig) { - return; - } - this.timerStartTime = ejectionTimestamp; - this.startTimer(this.latestConfig.getIntervalMs()); - this.runSuccessRateCheck(ejectionTimestamp); - this.runFailurePercentageCheck(ejectionTimestamp); - for (const [address, mapEntry] of this.entryMap.entries()) { - if (mapEntry.currentEjectionTimestamp === null) { - if (mapEntry.ejectionTimeMultiplier > 0) { - mapEntry.ejectionTimeMultiplier -= 1; - } - } - else { - const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); - const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); - const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); - returnTime.setMilliseconds(returnTime.getMilliseconds() + - Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); - if (returnTime < new Date()) { - trace('Unejecting ' + address); - this.uneject(mapEntry); - } - } - } - } - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { - return false; - } - trace('Received update with config: ' + JSON.stringify(lbConfig.toJsonObject(), undefined, 2)); - if (endpointList.ok) { - for (const endpoint of endpointList.value) { - if (!this.entryMap.has(endpoint)) { - trace('Adding map entry for ' + (0, subchannel_address_1.endpointToString)(endpoint)); - this.entryMap.set(endpoint, { - counter: new CallCounter(), - currentEjectionTimestamp: null, - ejectionTimeMultiplier: 0, - subchannelWrappers: [], - }); - } - } - this.entryMap.deleteMissing(endpointList.value); - } - const childPolicy = lbConfig.getChildPolicy(); - this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); - if (lbConfig.getSuccessRateEjectionConfig() || - lbConfig.getFailurePercentageEjectionConfig()) { - if (this.timerStartTime) { - trace('Previous timer existed. Replacing timer'); - clearTimeout(this.ejectionTimer); - const remainingDelay = lbConfig.getIntervalMs() - - (new Date().getTime() - this.timerStartTime.getTime()); - this.startTimer(remainingDelay); - } - else { - trace('Starting new timer'); - this.timerStartTime = new Date(); - this.startTimer(lbConfig.getIntervalMs()); - this.switchAllBuckets(); - } - } - else { - trace('Counting disabled. Cancelling timer.'); - this.timerStartTime = null; - clearTimeout(this.ejectionTimer); - for (const mapEntry of this.entryMap.values()) { - this.uneject(mapEntry); - mapEntry.ejectionTimeMultiplier = 0; - } - } - this.latestConfig = lbConfig; - return true; - } - exitIdle() { - this.childBalancer.exitIdle(); - } - resetBackoff() { - this.childBalancer.resetBackoff(); - } - destroy() { - clearTimeout(this.ejectionTimer); - this.childBalancer.destroy(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; -function setup() { - if (OUTLIER_DETECTION_ENABLED) { - (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); - } -} -//# sourceMappingURL=load-balancer-outlier-detection.js.map - -/***/ }), - -/***/ 38977: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LeafLoadBalancer = exports.PickFirstLoadBalancer = exports.PickFirstLoadBalancingConfig = void 0; -exports.shuffled = shuffled; -exports.setup = setup; -const load_balancer_1 = __nccwpck_require__(52680); -const connectivity_state_1 = __nccwpck_require__(80878); -const picker_1 = __nccwpck_require__(81611); -const subchannel_address_1 = __nccwpck_require__(99905); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const subchannel_address_2 = __nccwpck_require__(99905); -const net_1 = __nccwpck_require__(41808); -const call_interface_1 = __nccwpck_require__(78710); -const TRACER_NAME = 'pick_first'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'pick_first'; -/** - * Delay after starting a connection on a subchannel before starting a - * connection on the next subchannel in the list, for Happy Eyeballs algorithm. - */ -const CONNECTION_DELAY_INTERVAL_MS = 250; -class PickFirstLoadBalancingConfig { - constructor(shuffleAddressList) { - this.shuffleAddressList = shuffleAddressList; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - [TYPE_NAME]: { - shuffleAddressList: this.shuffleAddressList, - }, - }; - } - getShuffleAddressList() { - return this.shuffleAddressList; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - if ('shuffleAddressList' in obj && - !(typeof obj.shuffleAddressList === 'boolean')) { - throw new Error('pick_first config field shuffleAddressList must be a boolean if provided'); - } - return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); - } -} -exports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; -/** - * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the - * picked subchannel. - */ -class PickFirstPicker { - constructor(subchannel) { - this.subchannel = subchannel; - } - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.COMPLETE, - subchannel: this.subchannel, - status: null, - onCallStarted: null, - onCallEnded: null, - }; - } -} -/** - * Return a new array with the elements of the input array in a random order - * @param list The input array - * @returns A shuffled array of the elements of list - */ -function shuffled(list) { - const result = list.slice(); - for (let i = result.length - 1; i > 1; i--) { - const j = Math.floor(Math.random() * (i + 1)); - const temp = result[i]; - result[i] = result[j]; - result[j] = temp; - } - return result; -} -/** - * Interleave addresses in addressList by family in accordance with RFC-8304 section 4 - * @param addressList - * @returns - */ -function interleaveAddressFamilies(addressList) { - if (addressList.length === 0) { - return []; - } - const result = []; - const ipv6Addresses = []; - const ipv4Addresses = []; - const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); - for (const address of addressList) { - if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { - ipv6Addresses.push(address); - } - else { - ipv4Addresses.push(address); - } - } - const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; - const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; - for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { - if (i < firstList.length) { - result.push(firstList[i]); - } - if (i < secondList.length) { - result.push(secondList[i]); - } - } - return result; -} -const REPORT_HEALTH_STATUS_OPTION_NAME = 'grpc-node.internal.pick-first.report_health_status'; -class PickFirstLoadBalancer { - /** - * Load balancer that attempts to connect to each backend in the address list - * in order, and picks the first one that connects, using it for every - * request. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - */ - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - /** - * The list of subchannels this load balancer is currently attempting to - * connect to. - */ - this.children = []; - /** - * The current connectivity state of the load balancer. - */ - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The index within the `subchannels` array of the subchannel with the most - * recently started connection attempt. - */ - this.currentSubchannelIndex = 0; - /** - * The currently picked subchannel used for making calls. Populated if - * and only if the load balancer's current state is READY. In that case, - * the subchannel's current state is also READY. - */ - this.currentPick = null; - /** - * Listener callback attached to each subchannel in the `subchannels` list - * while establishing a connection. - */ - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { - this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); - }; - this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); - /** - * The LB policy enters sticky TRANSIENT_FAILURE mode when all - * subchannels have failed to connect at least once, and it stays in that - * mode until a connection attempt is successful. While in sticky TF mode, - * the LB policy continuously attempts to connect to all of its subchannels. - */ - this.stickyTransientFailureMode = false; - this.reportHealthStatus = false; - /** - * The most recent error reported by any subchannel as it transitioned to - * TRANSIENT_FAILURE. - */ - this.lastError = null; - this.latestAddressList = null; - this.latestOptions = {}; - this.latestResolutionNote = ''; - this.connectionDelayTimeout = setTimeout(() => { }, 0); - clearTimeout(this.connectionDelayTimeout); - } - allChildrenHaveReportedTF() { - return this.children.every(child => child.hasReportedTransientFailure); - } - resetChildrenReportedTF() { - this.children.every(child => child.hasReportedTransientFailure = false); - } - calculateAndReportNewState() { - var _a; - if (this.currentPick) { - if (this.reportHealthStatus && !this.currentPick.isHealthy()) { - const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null); - } - } - else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - else { - if (this.stickyTransientFailureMode) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - } - } - requestReresolution() { - this.channelControlHelper.requestReresolution(); - } - maybeEnterStickyTransientFailureMode() { - if (!this.allChildrenHaveReportedTF()) { - return; - } - this.requestReresolution(); - this.resetChildrenReportedTF(); - if (this.stickyTransientFailureMode) { - this.calculateAndReportNewState(); - return; - } - this.stickyTransientFailureMode = true; - for (const { subchannel } of this.children) { - subchannel.startConnecting(); - } - this.calculateAndReportNewState(); - } - removeCurrentPick() { - if (this.currentPick !== null) { - this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); - this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()); - this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); - // Unref last, to avoid triggering listeners - this.currentPick.unref(); - this.currentPick = null; - } - } - onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { - var _a; - if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) { - if (newState !== connectivity_state_1.ConnectivityState.READY) { - this.removeCurrentPick(); - this.calculateAndReportNewState(); - } - return; - } - for (const [index, child] of this.children.entries()) { - if (subchannel.realSubchannelEquals(child.subchannel)) { - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(child.subchannel); - } - if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - if (errorMessage) { - this.lastError = errorMessage; - } - this.maybeEnterStickyTransientFailureMode(); - if (index === this.currentSubchannelIndex) { - this.startNextSubchannelConnecting(index + 1); - } - } - child.subchannel.startConnecting(); - return; - } - } - } - startNextSubchannelConnecting(startIndex) { - clearTimeout(this.connectionDelayTimeout); - for (const [index, child] of this.children.entries()) { - if (index >= startIndex) { - const subchannelState = child.subchannel.getConnectivityState(); - if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || - subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { - this.startConnecting(index); - return; - } - } - } - this.maybeEnterStickyTransientFailureMode(); - } - /** - * Have a single subchannel in the `subchannels` list start connecting. - * @param subchannelIndex The index into the `subchannels` list. - */ - startConnecting(subchannelIndex) { - var _a, _b; - clearTimeout(this.connectionDelayTimeout); - this.currentSubchannelIndex = subchannelIndex; - if (this.children[subchannelIndex].subchannel.getConnectivityState() === - connectivity_state_1.ConnectivityState.IDLE) { - trace('Start connecting to subchannel with address ' + - this.children[subchannelIndex].subchannel.getAddress()); - process.nextTick(() => { - var _a; - (_a = this.children[subchannelIndex]) === null || _a === void 0 ? void 0 : _a.subchannel.startConnecting(); - }); - } - this.connectionDelayTimeout = setTimeout(() => { - this.startNextSubchannelConnecting(subchannelIndex + 1); - }, CONNECTION_DELAY_INTERVAL_MS); - (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Declare that the specified subchannel should be used to make requests. - * This functions the same independent of whether subchannel is a member of - * this.children and whether it is equal to this.currentPick. - * Prerequisite: subchannel.getConnectivityState() === READY. - * @param subchannel - */ - pickSubchannel(subchannel) { - trace('Pick subchannel with address ' + subchannel.getAddress()); - this.stickyTransientFailureMode = false; - /* Ref before removeCurrentPick and resetSubchannelList to avoid the - * refcount dropping to 0 during this process. */ - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - this.removeCurrentPick(); - this.resetSubchannelList(); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); - this.currentPick = subchannel; - clearTimeout(this.connectionDelayTimeout); - this.calculateAndReportNewState(); - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - /* Always remoev the connectivity state listener. If the subchannel is - getting picked, it will be re-added then. */ - child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - /* Refs are counted independently for the children list and the - * currentPick, so we call unref whether or not the child is the - * currentPick. Channelz child references are also refcounted, so - * removeChannelzChild can be handled the same way. */ - child.subchannel.unref(); - this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); - } - this.currentSubchannelIndex = 0; - this.children = []; - } - connectToAddressList(addressList, options) { - trace('connectToAddressList([' + addressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); - const newChildrenList = addressList.map(address => ({ - subchannel: this.channelControlHelper.createSubchannel(address, options), - hasReportedTransientFailure: false, - })); - for (const { subchannel } of newChildrenList) { - if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(subchannel); - return; - } - } - /* Ref each subchannel before resetting the list, to ensure that - * subchannels shared between the list don't drop to 0 refs during the - * transition. */ - for (const { subchannel } of newChildrenList) { - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - } - this.resetSubchannelList(); - this.children = newChildrenList; - for (const { subchannel } of this.children) { - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - for (const child of this.children) { - if (child.subchannel.getConnectivityState() === - connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - } - } - this.startNextSubchannelConnecting(0); - this.calculateAndReportNewState(); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0 && this.currentPick === null) { - this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - let endpointList = maybeEndpointList.value; - this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; - /* Previously, an update would be discarded if it was identical to the - * previous update, to minimize churn. Now the DNS resolver is - * rate-limited, so that is less of a concern. */ - if (lbConfig.getShuffleAddressList()) { - endpointList = shuffled(endpointList); - } - const rawAddressList = [].concat(...endpointList.map(endpoint => endpoint.addresses)); - trace('updateAddressList([' + rawAddressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); - const addressList = interleaveAddressFamilies(rawAddressList); - this.latestAddressList = addressList; - this.latestOptions = options; - this.connectToAddressList(addressList, options); - this.latestResolutionNote = resolutionNote; - if (rawAddressList.length > 0) { - return true; - } - else { - this.lastError = 'No addresses resolved'; - return false; - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && - this.latestAddressList) { - this.connectToAddressList(this.latestAddressList, this.latestOptions); - } - } - resetBackoff() { - /* The pick first load balancer does not have a connection backoff, so this - * does nothing */ - } - destroy() { - this.resetSubchannelList(); - this.removeCurrentPick(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.PickFirstLoadBalancer = PickFirstLoadBalancer; -const LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); -/** - * This class handles the leaf load balancing operations for a single endpoint. - * It is a thin wrapper around a PickFirstLoadBalancer with a different API - * that more closely reflects how it will be used as a leaf balancer. - */ -class LeafLoadBalancer { - constructor(endpoint, channelControlHelper, options, resolutionNote) { - this.endpoint = endpoint; - this.options = options; - this.resolutionNote = resolutionNote; - this.latestState = connectivity_state_1.ConnectivityState.IDLE; - const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - this.latestState = connectivityState; - this.latestPicker = picker; - channelControlHelper.updateState(connectivityState, picker, errorMessage); - }, - }); - this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper); - this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); - } - startConnecting() { - this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote); - } - /** - * Update the endpoint associated with this LeafLoadBalancer to a new - * endpoint. Does not trigger connection establishment if a connection - * attempt is not already in progress. - * @param newEndpoint - */ - updateEndpoint(newEndpoint, newOptions) { - this.options = newOptions; - this.endpoint = newEndpoint; - if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { - this.startConnecting(); - } - } - getConnectivityState() { - return this.latestState; - } - getPicker() { - return this.latestPicker; - } - getEndpoint() { - return this.endpoint; - } - exitIdle() { - this.pickFirstBalancer.exitIdle(); - } - destroy() { - this.pickFirstBalancer.destroy(); - } -} -exports.LeafLoadBalancer = LeafLoadBalancer; -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); - (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); -} -//# sourceMappingURL=load-balancer-pick-first.js.map - -/***/ }), - -/***/ 92787: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RoundRobinLoadBalancer = void 0; -exports.setup = setup; -const load_balancer_1 = __nccwpck_require__(52680); -const connectivity_state_1 = __nccwpck_require__(80878); -const picker_1 = __nccwpck_require__(81611); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const subchannel_address_1 = __nccwpck_require__(99905); -const load_balancer_pick_first_1 = __nccwpck_require__(38977); -const TRACER_NAME = 'round_robin'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'round_robin'; -class RoundRobinLoadBalancingConfig { - getLoadBalancerName() { - return TYPE_NAME; - } - constructor() { } - toJsonObject() { - return { - [TYPE_NAME]: {}, - }; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - return new RoundRobinLoadBalancingConfig(); - } -} -class RoundRobinPicker { - constructor(children, nextIndex = 0) { - this.children = children; - this.nextIndex = nextIndex; - } - pick(pickArgs) { - const childPicker = this.children[this.nextIndex].picker; - this.nextIndex = (this.nextIndex + 1) % this.children.length; - return childPicker.pick(pickArgs); - } - /** - * Check what the next subchannel returned would be. Used by the load - * balancer implementation to preserve this part of the picker state if - * possible when a subchannel connects or disconnects. - */ - peekNextEndpoint() { - return this.children[this.nextIndex].endpoint; - } -} -function rotateArray(list, startIndex) { - return [...list.slice(startIndex), ...list.slice(0, startIndex)]; -} -class RoundRobinLoadBalancer { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.children = []; - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.currentReadyPicker = null; - this.updatesPaused = false; - this.lastError = null; - this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - /* Ensure that name resolution is requested again after active - * connections are dropped. This is more aggressive than necessary to - * accomplish that, so we are counting on resolvers to have - * reasonable rate limits. */ - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - }, - }); - } - countChildrenWithState(state) { - return this.children.filter(child => child.getConnectivityState() === state) - .length; - } - calculateAndUpdateState() { - if (this.updatesPaused) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const readyChildren = this.children.filter(child => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); - let index = 0; - if (this.currentReadyPicker !== null) { - const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); - index = readyChildren.findIndex(child => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); - if (index < 0) { - index = 0; - } - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map(child => ({ - endpoint: child.getEndpoint(), - picker: child.getPicker(), - })), index), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - /* round_robin should keep all children connected, this is how we do that. - * We can't do this more efficiently in the individual child's updateState - * callback because that doesn't have a reference to which child the state - * change is associated with. */ - for (const child of this.children) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.currentReadyPicker = picker; - } - else { - this.currentReadyPicker = null; - } - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - child.destroy(); - } - this.children = []; - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - const startIndex = (Math.random() * maybeEndpointList.value.length) | 0; - const endpointList = rotateArray(maybeEndpointList.value, startIndex); - this.resetSubchannelList(); - if (endpointList.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - } - trace('Connect to endpoint list ' + endpointList.map(subchannel_address_1.endpointToString)); - this.updatesPaused = true; - this.children = endpointList.map(endpoint => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, options, resolutionNote)); - for (const child of this.children) { - child.startConnecting(); - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - return true; - } - exitIdle() { - /* The round_robin LB policy is only in the IDLE state if it has no - * addresses to try to connect to and it has no picked subchannel. - * In that case, there is no meaningful action that can be taken here. */ - } - resetBackoff() { - // This LB policy has no backoff to reset - } - destroy() { - this.resetSubchannelList(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer; -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); -} -//# sourceMappingURL=load-balancer-round-robin.js.map - -/***/ }), - -/***/ 69544: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WeightedRoundRobinLoadBalancingConfig = void 0; -exports.setup = setup; -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const duration_1 = __nccwpck_require__(62668); -const load_balancer_1 = __nccwpck_require__(52680); -const load_balancer_pick_first_1 = __nccwpck_require__(38977); -const logging = __nccwpck_require__(35993); -const orca_1 = __nccwpck_require__(31791); -const picker_1 = __nccwpck_require__(81611); -const priority_queue_1 = __nccwpck_require__(38386); -const subchannel_address_1 = __nccwpck_require__(99905); -const TRACER_NAME = 'weighted_round_robin'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'weighted_round_robin'; -const DEFAULT_OOB_REPORTING_PERIOD_MS = 10000; -const DEFAULT_BLACKOUT_PERIOD_MS = 10000; -const DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 60000; -const DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1000; -const DEFAULT_ERROR_UTILIZATION_PENALTY = 1; -function validateFieldType(obj, fieldName, expectedType) { - if (fieldName in obj && - obj[fieldName] !== undefined && - typeof obj[fieldName] !== expectedType) { - throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } -} -function parseDurationField(obj, fieldName) { - if (fieldName in obj && obj[fieldName] !== undefined && obj[fieldName] !== null) { - let durationObject; - if ((0, duration_1.isDuration)(obj[fieldName])) { - durationObject = obj[fieldName]; - } - else if ((0, duration_1.isDurationMessage)(obj[fieldName])) { - durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]); - } - else if (typeof obj[fieldName] === 'string') { - const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]); - if (!parsedDuration) { - throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); - } - durationObject = parsedDuration; - } - else { - throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); - } - return (0, duration_1.durationToMs)(durationObject); - } - return null; -} -class WeightedRoundRobinLoadBalancingConfig { - constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) { - this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== void 0 ? enableOobLoadReport : false; - this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== void 0 ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS; - this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== void 0 ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS; - this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== void 0 ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; - this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== void 0 ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); - this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== void 0 ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - enable_oob_load_report: this.enableOobLoadReport, - oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)), - blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)), - weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)), - weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)), - error_utilization_penalty: this.errorUtilizationPenalty - }; - } - static createFromJson(obj) { - validateFieldType(obj, 'enable_oob_load_report', 'boolean'); - validateFieldType(obj, 'error_utilization_penalty', 'number'); - if (obj.error_utilization_penalty < 0) { - throw new Error('weighted round robin config error_utilization_penalty < 0'); - } - return new WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, 'oob_load_reporting_period'), parseDurationField(obj, 'blackout_period'), parseDurationField(obj, 'weight_expiration_period'), parseDurationField(obj, 'weight_update_period'), obj.error_utilization_penalty); - } - getEnableOobLoadReport() { - return this.enableOobLoadReport; - } - getOobLoadReportingPeriodMs() { - return this.oobLoadReportingPeriodMs; - } - getBlackoutPeriodMs() { - return this.blackoutPeriodMs; - } - getWeightExpirationPeriodMs() { - return this.weightExpirationPeriodMs; - } - getWeightUpdatePeriodMs() { - return this.weightUpdatePeriodMs; - } - getErrorUtilizationPenalty() { - return this.errorUtilizationPenalty; - } -} -exports.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig; -class WeightedRoundRobinPicker { - constructor(children, metricsHandler) { - this.metricsHandler = metricsHandler; - this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline); - const positiveWeight = children.filter(picker => picker.weight > 0); - let averageWeight; - if (positiveWeight.length < 2) { - averageWeight = 1; - } - else { - let weightSum = 0; - for (const { weight } of positiveWeight) { - weightSum += weight; - } - averageWeight = weightSum / positiveWeight.length; - } - for (const child of children) { - const period = child.weight > 0 ? 1 / child.weight : averageWeight; - this.queue.push({ - endpointName: child.endpointName, - picker: child.picker, - period: period, - deadline: Math.random() * period - }); - } - } - pick(pickArgs) { - const entry = this.queue.pop(); - this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period })); - const childPick = entry.picker.pick(pickArgs); - if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) { - if (this.metricsHandler) { - return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)(loadReport => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) }); - } - else { - const subchannelWrapper = childPick.subchannel; - return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } - else { - return childPick; - } - } -} -class WeightedRoundRobinLoadBalancer { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.latestConfig = null; - this.children = new Map(); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.updatesPaused = false; - this.lastError = null; - this.weightUpdateTimer = null; - } - countChildrenWithState(state) { - let count = 0; - for (const entry of this.children.values()) { - if (entry.child.getConnectivityState() === state) { - count += 1; - } - } - return count; - } - updateWeight(entry, loadReport) { - var _a, _b; - const qps = loadReport.rps_fractional; - let utilization = loadReport.application_utilization; - if (utilization > 0 && qps > 0) { - utilization += (loadReport.eps / qps) * ((_b = (_a = this.latestConfig) === null || _a === void 0 ? void 0 : _a.getErrorUtilizationPenalty()) !== null && _b !== void 0 ? _b : 0); - } - const newWeight = utilization === 0 ? 0 : qps / utilization; - if (newWeight === 0) { - return; - } - const now = new Date(); - if (entry.nonEmptySince === null) { - entry.nonEmptySince = now; - } - entry.lastUpdated = now; - entry.weight = newWeight; - } - getWeight(entry) { - if (!this.latestConfig) { - return 0; - } - const now = new Date().getTime(); - if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { - entry.nonEmptySince = null; - return 0; - } - const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); - if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { - return 0; - } - return entry.weight; - } - calculateAndUpdateState() { - if (this.updatesPaused || !this.latestConfig) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const weightedPickers = []; - for (const [endpoint, entry] of this.children) { - if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - continue; - } - weightedPickers.push({ - endpointName: endpoint, - picker: entry.child.getPicker(), - weight: this.getWeight(entry) - }); - } - trace('Created picker with weights: ' + weightedPickers.map(entry => entry.endpointName + ':' + entry.weight).join(',')); - let metricsHandler; - if (!this.latestConfig.getEnableOobLoadReport()) { - metricsHandler = (loadReport, endpointName) => { - const childEntry = this.children.get(endpointName); - if (childEntry) { - this.updateWeight(childEntry, loadReport); - } - }; - } - else { - metricsHandler = null; - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - /* round_robin should keep all children connected, this is how we do that. - * We can't do this more efficiently in the individual child's updateState - * callback because that doesn't have a reference to which child the state - * change is associated with. */ - for (const { child } of this.children.values()) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - var _a, _b; - if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.size === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - if (maybeEndpointList.value.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - return false; - } - trace('Connect to endpoint list ' + maybeEndpointList.value.map(subchannel_address_1.endpointToString)); - const now = new Date(); - const seenEndpointNames = new Set(); - this.updatesPaused = true; - this.latestConfig = lbConfig; - for (const endpoint of maybeEndpointList.value) { - const name = (0, subchannel_address_1.endpointToString)(endpoint); - seenEndpointNames.add(name); - let entry = this.children.get(name); - if (!entry) { - entry = { - child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - /* Ensure that name resolution is requested again after active - * connections are dropped. This is more aggressive than necessary to - * accomplish that, so we are counting on resolvers to have - * reasonable rate limits. */ - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - entry.nonEmptySince = null; - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - }, - createSubchannel: (subchannelAddress, subchannelArgs) => { - const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - if (entry === null || entry === void 0 ? void 0 : entry.oobMetricsListener) { - return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs()); - } - else { - return subchannel; - } - } - }), options, resolutionNote), - lastUpdated: now, - nonEmptySince: null, - weight: 0, - oobMetricsListener: null - }; - this.children.set(name, entry); - } - if (lbConfig.getEnableOobLoadReport()) { - entry.oobMetricsListener = loadReport => { - this.updateWeight(entry, loadReport); - }; - } - else { - entry.oobMetricsListener = null; - } - } - for (const [endpointName, entry] of this.children) { - if (seenEndpointNames.has(endpointName)) { - entry.child.startConnecting(); - } - else { - entry.child.destroy(); - this.children.delete(endpointName); - } - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - this.weightUpdateTimer = (_b = (_a = setInterval(() => { - if (this.currentState === connectivity_state_1.ConnectivityState.READY) { - this.calculateAndUpdateState(); - } - }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - return true; - } - exitIdle() { - /* The weighted_round_robin LB policy is only in the IDLE state if it has - * no addresses to try to connect to and it has no picked subchannel. - * In that case, there is no meaningful action that can be taken here. */ - } - resetBackoff() { - // This LB policy has no backoff to reset - } - destroy() { - for (const entry of this.children.values()) { - entry.child.destroy(); - } - this.children.clear(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - } - getTypeName() { - return TYPE_NAME; - } -} -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig); -} -//# sourceMappingURL=load-balancer-weighted-round-robin.js.map - -/***/ }), - -/***/ 52680: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createChildChannelControlHelper = createChildChannelControlHelper; -exports.registerLoadBalancerType = registerLoadBalancerType; -exports.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; -exports.createLoadBalancer = createLoadBalancer; -exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; -exports.parseLoadBalancingConfig = parseLoadBalancingConfig; -exports.getDefaultConfig = getDefaultConfig; -exports.selectLbConfigFromList = selectLbConfigFromList; -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -/** - * Create a child ChannelControlHelper that overrides some methods of the - * parent while letting others pass through to the parent unmodified. This - * allows other code to create these children without needing to know about - * all of the methods to be passed through. - * @param parent - * @param overrides - */ -function createChildChannelControlHelper(parent, overrides) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - return { - createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent), - updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent), - requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent), - addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent), - removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent), - }; -} -const registeredLoadBalancerTypes = {}; -let defaultLoadBalancerType = null; -function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { - registeredLoadBalancerTypes[typeName] = { - LoadBalancer: loadBalancerType, - LoadBalancingConfig: loadBalancingConfigType, - }; -} -function registerDefaultLoadBalancerType(typeName) { - defaultLoadBalancerType = typeName; -} -function createLoadBalancer(config, channelControlHelper) { - const typeName = config.getLoadBalancerName(); - if (typeName in registeredLoadBalancerTypes) { - return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper); - } - else { - return null; - } -} -function isLoadBalancerNameRegistered(typeName) { - return typeName in registeredLoadBalancerTypes; -} -function parseLoadBalancingConfig(rawConfig) { - const keys = Object.keys(rawConfig); - if (keys.length !== 1) { - throw new Error('Provided load balancing config has multiple conflicting entries'); - } - const typeName = keys[0]; - if (typeName in registeredLoadBalancerTypes) { - try { - return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); - } - catch (e) { - throw new Error(`${typeName}: ${e.message}`); - } - } - else { - throw new Error(`Unrecognized load balancing config name ${typeName}`); - } -} -function getDefaultConfig() { - if (!defaultLoadBalancerType) { - throw new Error('No default load balancer type registered'); - } - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); -} -function selectLbConfigFromList(configs, fallbackTodefault = false) { - for (const config of configs) { - try { - return parseLoadBalancingConfig(config); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, 'Config parsing failed with error', e.message); - continue; - } - } - if (fallbackTodefault) { - if (defaultLoadBalancerType) { - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); - } - else { - return null; - } - } - else { - return null; - } -} -//# sourceMappingURL=load-balancer.js.map - -/***/ }), - -/***/ 776: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LoadBalancingCall = void 0; -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const deadline_1 = __nccwpck_require__(511); -const metadata_1 = __nccwpck_require__(83665); -const picker_1 = __nccwpck_require__(81611); -const uri_parser_1 = __nccwpck_require__(65974); -const logging = __nccwpck_require__(35993); -const control_plane_status_1 = __nccwpck_require__(39129); -const http2 = __nccwpck_require__(85158); -const TRACER_NAME = 'load_balancing_call'; -class LoadBalancingCall { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { - var _a, _b; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.metadata = null; - this.listener = null; - this.onCallEnded = null; - this.childStartTime = null; - const splitPath = this.methodName.split('/'); - let serviceName = ''; - /* The standard path format is "/{serviceName}/{methodName}", so if we split - * by '/', the first item should be empty and the second should be the - * service name */ - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; - /* Currently, call credentials are only allowed on HTTPS connections, so we - * can assume that the scheme is "https" */ - this.serviceUrl = `https://${hostname}/${serviceName}`; - this.startTime = new Date(); - } - getDeadlineInfo() { - var _a, _b; - const deadlineInfo = []; - if (this.childStartTime) { - if (this.childStartTime > this.startTime) { - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - deadlineInfo.push('wait_for_ready'); - } - deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); - } - deadlineInfo.push(...this.child.getDeadlineInfo()); - return deadlineInfo; - } - else { - if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) { - deadlineInfo.push('wait_for_ready'); - } - deadlineInfo.push('Waiting for LB pick'); - } - return deadlineInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - outputStatus(status, progress) { - var _a, _b; - if (!this.ended) { - this.ended = true; - this.trace('ended with status: code=' + - status.code + - ' details="' + - status.details + - '" start time=' + - this.startTime.toISOString()); - const finalStatus = Object.assign(Object.assign({}, status), { progress }); - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); - (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); - } - } - doPick() { - var _a, _b; - if (this.ended) { - return; - } - if (!this.metadata) { - throw new Error('doPick called before start'); - } - this.trace('Pick called'); - const finalMetadata = this.metadata.clone(); - const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); - const subchannelString = pickResult.subchannel - ? '(' + - pickResult.subchannel.getChannelzRef().id + - ') ' + - pickResult.subchannel.getAddress() - : '' + pickResult.subchannel; - this.trace('Pick result: ' + - picker_1.PickResultType[pickResult.pickResultType] + - ' subchannel: ' + - subchannelString + - ' status: ' + - ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + - ' ' + - ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); - switch (pickResult.pickResultType) { - case picker_1.PickResultType.COMPLETE: - const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); - combinedCallCredentials - .generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }) - .then(credsMetadata => { - var _a; - /* If this call was cancelled (e.g. by the deadline) before - * metadata generation finished, we shouldn't do anything with - * it. */ - if (this.ended) { - this.trace('Credentials metadata generation finished after call ended'); - return; - } - finalMetadata.merge(credsMetadata); - if (finalMetadata.get('authorization').length > 1) { - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: '"authorization" metadata cannot have multiple values', - metadata: new metadata_1.Metadata(), - }, 'PROCESSED'); - } - if (pickResult.subchannel.getConnectivityState() !== - connectivity_state_1.ConnectivityState.READY) { - this.trace('Picked subchannel ' + - subchannelString + - ' has state ' + - connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + - ' after getting credentials metadata. Retrying pick'); - this.doPick(); - return; - } - if (this.deadline !== Infinity) { - finalMetadata.set('grpc-timeout', (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); - } - try { - this.child = pickResult - .subchannel.getRealSubchannel() - .createCall(finalMetadata, this.host, this.methodName, { - onReceiveMetadata: metadata => { - this.trace('Received metadata'); - this.listener.onReceiveMetadata(metadata); - }, - onReceiveMessage: message => { - this.trace('Received message'); - this.listener.onReceiveMessage(message); - }, - onReceiveStatus: status => { - this.trace('Received status'); - if (status.rstCode === - http2.constants.NGHTTP2_REFUSED_STREAM) { - this.outputStatus(status, 'REFUSED'); - } - else { - this.outputStatus(status, 'PROCESSED'); - } - }, - }); - this.childStartTime = new Date(); - } - catch (error) { - this.trace('Failed to start call on picked subchannel ' + - subchannelString + - ' with error ' + - error.message); - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: 'Failed to start HTTP/2 stream with error ' + - error.message, - metadata: new metadata_1.Metadata(), - }, 'NOT_STARTED'); - return; - } - (_a = pickResult.onCallStarted) === null || _a === void 0 ? void 0 : _a.call(pickResult); - this.onCallEnded = pickResult.onCallEnded; - this.trace('Created child call [' + this.child.getCallNumber() + ']'); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (error) => { - // We assume the error code isn't 0 (Status.OK) - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); - this.outputStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }, 'PROCESSED'); - }); - break; - case picker_1.PickResultType.DROP: - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'DROP'); - }); - break; - case picker_1.PickResultType.TRANSIENT_FAILURE: - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForPick(this); - } - else { - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'PROCESSED'); - }); - } - break; - case picker_1.PickResultType.QUEUE: - this.channel.queueCallForPick(this); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ code: status, details: details, metadata: new metadata_1.Metadata() }, 'PROCESSED'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace('start called'); - this.listener = listener; - this.metadata = metadata; - this.doPick(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - if (this.child) { - this.child.sendMessageWithContext(context, message); - } - else { - this.pendingMessage = { context, message }; - } - } - startRead() { - this.trace('startRead called'); - if (this.child) { - this.child.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - this.trace('halfClose called'); - if (this.child) { - this.child.halfClose(); - } - else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - throw new Error('Method not implemented.'); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } - else { - return null; - } - } -} -exports.LoadBalancingCall = LoadBalancingCall; -//# sourceMappingURL=load-balancing-call.js.map - -/***/ }), - -/***/ 35993: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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 _a, _b, _c, _d; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = void 0; -exports.trace = trace; -exports.isTracerEnabled = isTracerEnabled; -const constants_1 = __nccwpck_require__(90634); -const process_1 = __nccwpck_require__(77282); -const clientVersion = (__nccwpck_require__(56569)/* .version */ .i8); -const DEFAULT_LOGGER = { - error: (message, ...optionalParams) => { - console.error('E ' + message, ...optionalParams); - }, - info: (message, ...optionalParams) => { - console.error('I ' + message, ...optionalParams); - }, - debug: (message, ...optionalParams) => { - console.error('D ' + message, ...optionalParams); - }, -}; -let _logger = DEFAULT_LOGGER; -let _logVerbosity = constants_1.LogVerbosity.ERROR; -const verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : ''; -switch (verbosityString.toUpperCase()) { - case 'DEBUG': - _logVerbosity = constants_1.LogVerbosity.DEBUG; - break; - case 'INFO': - _logVerbosity = constants_1.LogVerbosity.INFO; - break; - case 'ERROR': - _logVerbosity = constants_1.LogVerbosity.ERROR; - break; - case 'NONE': - _logVerbosity = constants_1.LogVerbosity.NONE; - break; - default: - // Ignore any other values -} -const getLogger = () => { - return _logger; -}; -exports.getLogger = getLogger; -const setLogger = (logger) => { - _logger = logger; -}; -exports.setLogger = setLogger; -const setLoggerVerbosity = (verbosity) => { - _logVerbosity = verbosity; -}; -exports.setLoggerVerbosity = setLoggerVerbosity; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const log = (severity, ...args) => { - let logFunction; - if (severity >= _logVerbosity) { - switch (severity) { - case constants_1.LogVerbosity.DEBUG: - logFunction = _logger.debug; - break; - case constants_1.LogVerbosity.INFO: - logFunction = _logger.info; - break; - case constants_1.LogVerbosity.ERROR: - logFunction = _logger.error; - break; - } - /* Fall back to _logger.error when other methods are not available for - * compatiblity with older behavior that always logged to _logger.error */ - if (!logFunction) { - logFunction = _logger.error; - } - if (logFunction) { - logFunction.bind(_logger)(...args); - } - } -}; -exports.log = log; -const tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : ''; -const enabledTracers = new Set(); -const disabledTracers = new Set(); -for (const tracerName of tracersString.split(',')) { - if (tracerName.startsWith('-')) { - disabledTracers.add(tracerName.substring(1)); - } - else { - enabledTracers.add(tracerName); - } -} -const allEnabled = enabledTracers.has('all'); -function trace(severity, tracer, text) { - if (isTracerEnabled(tracer)) { - (0, exports.log)(severity, new Date().toISOString() + - ' | v' + - clientVersion + - ' ' + - process_1.pid + - ' | ' + - tracer + - ' | ' + - text); - } -} -function isTracerEnabled(tracer) { - return (!disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer))); -} -//# sourceMappingURL=logging.js.map - -/***/ }), - -/***/ 38541: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.makeClientConstructor = makeClientConstructor; -exports.loadPackageDefinition = loadPackageDefinition; -const client_1 = __nccwpck_require__(87172); -/** - * Map with short names for each of the requester maker functions. Used in - * makeClientConstructor - * @private - */ -const requesterFuncs = { - unary: client_1.Client.prototype.makeUnaryRequest, - server_stream: client_1.Client.prototype.makeServerStreamRequest, - client_stream: client_1.Client.prototype.makeClientStreamRequest, - bidi: client_1.Client.prototype.makeBidiStreamRequest, -}; -/** - * Returns true, if given key is included in the blacklisted - * keys. - * @param key key for check, string. - */ -function isPrototypePolluted(key) { - return ['__proto__', 'prototype', 'constructor'].includes(key); -} -/** - * Creates a constructor for a client with the given methods, as specified in - * the methods argument. The resulting class will have an instance method for - * each method in the service, which is a partial application of one of the - * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` - * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` - * arguments predefined. - * @param methods An object mapping method names to - * method attributes - * @param serviceName The fully qualified name of the service - * @param classOptions An options object. - * @return New client constructor, which is a subclass of - * {@link grpc.Client}, and has the same arguments as that constructor. - */ -function makeClientConstructor(methods, serviceName, classOptions) { - if (!classOptions) { - classOptions = {}; - } - class ServiceClientImpl extends client_1.Client { - } - Object.keys(methods).forEach(name => { - if (isPrototypePolluted(name)) { - return; - } - const attrs = methods[name]; - let methodType; - // TODO(murgatroid99): Verify that we don't need this anymore - if (typeof name === 'string' && name.charAt(0) === '$') { - throw new Error('Method names cannot start with $'); - } - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = 'bidi'; - } - else { - methodType = 'client_stream'; - } - } - else { - if (attrs.responseStream) { - methodType = 'server_stream'; - } - else { - methodType = 'unary'; - } - } - const serialize = attrs.requestSerialize; - const deserialize = attrs.responseDeserialize; - const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); - ServiceClientImpl.prototype[name] = methodFunc; - // Associate all provided attributes with the method - Object.assign(ServiceClientImpl.prototype[name], attrs); - if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { - ServiceClientImpl.prototype[attrs.originalName] = - ServiceClientImpl.prototype[name]; - } - }); - ServiceClientImpl.service = methods; - ServiceClientImpl.serviceName = serviceName; - return ServiceClientImpl; -} -function partial(fn, path, serialize, deserialize) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function (...args) { - return fn.call(this, path, serialize, deserialize, ...args); - }; -} -function isProtobufTypeDefinition(obj) { - return 'format' in obj; -} -/** - * Load a gRPC package definition as a gRPC object hierarchy. - * @param packageDef The package definition object. - * @return The resulting gRPC object. - */ -function loadPackageDefinition(packageDef) { - const result = {}; - for (const serviceFqn in packageDef) { - if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { - const service = packageDef[serviceFqn]; - const nameComponents = serviceFqn.split('.'); - if (nameComponents.some((comp) => isPrototypePolluted(comp))) { - continue; - } - const serviceName = nameComponents[nameComponents.length - 1]; - let current = result; - for (const packageName of nameComponents.slice(0, -1)) { - if (!current[packageName]) { - current[packageName] = {}; - } - current = current[packageName]; - } - if (isProtobufTypeDefinition(service)) { - current[serviceName] = service; - } - else { - current[serviceName] = makeClientConstructor(service, serviceName, {}); - } - } - } - return result; -} -//# sourceMappingURL=make-client.js.map - -/***/ }), - -/***/ 83665: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Metadata = void 0; -const logging_1 = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const error_1 = __nccwpck_require__(22336); -const LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; -const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; -function isLegalKey(key) { - return LEGAL_KEY_REGEX.test(key); -} -function isLegalNonBinaryValue(value) { - return LEGAL_NON_BINARY_VALUE_REGEX.test(value); -} -function isBinaryKey(key) { - return key.endsWith('-bin'); -} -function isCustomMetadata(key) { - return !key.startsWith('grpc-'); -} -function normalizeKey(key) { - return key.toLowerCase(); -} -function validate(key, value) { - if (!isLegalKey(key)) { - throw new Error('Metadata key "' + key + '" contains illegal characters'); - } - if (value !== null && value !== undefined) { - if (isBinaryKey(key)) { - if (!Buffer.isBuffer(value)) { - throw new Error("keys that end with '-bin' must have Buffer values"); - } - } - else { - if (Buffer.isBuffer(value)) { - throw new Error("keys that don't end with '-bin' must have String values"); - } - if (!isLegalNonBinaryValue(value)) { - throw new Error('Metadata string value "' + value + '" contains illegal characters'); - } - } - } -} -/** - * A class for storing metadata. Keys are normalized to lowercase ASCII. - */ -class Metadata { - constructor(options = {}) { - this.internalRepr = new Map(); - this.opaqueData = new Map(); - this.options = options; - } - /** - * Sets the given value for the given key by replacing any other values - * associated with that key. Normalizes the key. - * @param key The key to whose value should be set. - * @param value The value to set. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - set(key, value) { - key = normalizeKey(key); - validate(key, value); - this.internalRepr.set(key, [value]); - } - /** - * Adds the given value for the given key by appending to a list of previous - * values associated with that key. Normalizes the key. - * @param key The key for which a new value should be appended. - * @param value The value to add. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - add(key, value) { - key = normalizeKey(key); - validate(key, value); - const existingValue = this.internalRepr.get(key); - if (existingValue === undefined) { - this.internalRepr.set(key, [value]); - } - else { - existingValue.push(value); - } - } - /** - * Removes the given key and any associated values. Normalizes the key. - * @param key The key whose values should be removed. - */ - remove(key) { - key = normalizeKey(key); - // validate(key); - this.internalRepr.delete(key); - } - /** - * Gets a list of all values associated with the key. Normalizes the key. - * @param key The key whose value should be retrieved. - * @return A list of values associated with the given key. - */ - get(key) { - key = normalizeKey(key); - // validate(key); - return this.internalRepr.get(key) || []; - } - /** - * Gets a plain object mapping each key to the first value associated with it. - * This reflects the most common way that people will want to see metadata. - * @return A key/value mapping of the metadata. - */ - getMap() { - const result = {}; - for (const [key, values] of this.internalRepr) { - if (values.length > 0) { - const v = values[0]; - result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; - } - } - return result; - } - /** - * Clones the metadata object. - * @return The newly cloned object. - */ - clone() { - const newMetadata = new Metadata(this.options); - const newInternalRepr = newMetadata.internalRepr; - for (const [key, value] of this.internalRepr) { - const clonedValue = value.map(v => { - if (Buffer.isBuffer(v)) { - return Buffer.from(v); - } - else { - return v; - } - }); - newInternalRepr.set(key, clonedValue); - } - return newMetadata; - } - /** - * Merges all key-value pairs from a given Metadata object into this one. - * If both this object and the given object have values in the same key, - * values from the other Metadata object will be appended to this object's - * values. - * @param other A Metadata object. - */ - merge(other) { - for (const [key, values] of other.internalRepr) { - const mergedValue = (this.internalRepr.get(key) || []).concat(values); - this.internalRepr.set(key, mergedValue); - } - } - setOptions(options) { - this.options = options; - } - getOptions() { - return this.options; - } - /** - * Creates an OutgoingHttpHeaders object that can be used with the http2 API. - */ - toHttp2Headers() { - // NOTE: Node <8.9 formats http2 headers incorrectly. - const result = {}; - for (const [key, values] of this.internalRepr) { - if (key.startsWith(':')) { - continue; - } - // We assume that the user's interaction with this object is limited to - // through its public API (i.e. keys and values are already validated). - result[key] = values.map(bufToString); - } - return result; - } - /** - * This modifies the behavior of JSON.stringify to show an object - * representation of the metadata map. - */ - toJSON() { - const result = {}; - for (const [key, values] of this.internalRepr) { - result[key] = values; - } - return result; - } - /** - * Attach additional data of any type to the metadata object, which will not - * be included when sending headers. The data can later be retrieved with - * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this - * library. - * @param key - * @param value - */ - setOpaque(key, value) { - this.opaqueData.set(key, value); - } - /** - * Retrieve data previously added with `setOpaque`. - * @param key - * @returns - */ - getOpaque(key) { - return this.opaqueData.get(key); - } - /** - * Returns a new Metadata object based fields in a given IncomingHttpHeaders - * object. - * @param headers An IncomingHttpHeaders object. - */ - static fromHttp2Headers(headers) { - const result = new Metadata(); - for (const key of Object.keys(headers)) { - // Reserved headers (beginning with `:`) are not valid keys. - if (key.charAt(0) === ':') { - continue; - } - const values = headers[key]; - try { - if (isBinaryKey(key)) { - if (Array.isArray(values)) { - values.forEach(value => { - result.add(key, Buffer.from(value, 'base64')); - }); - } - else if (values !== undefined) { - if (isCustomMetadata(key)) { - values.split(',').forEach(v => { - result.add(key, Buffer.from(v.trim(), 'base64')); - }); - } - else { - result.add(key, Buffer.from(values, 'base64')); - } - } - } - else { - if (Array.isArray(values)) { - values.forEach(value => { - result.add(key, value); - }); - } - else if (values !== undefined) { - result.add(key, values); - } - } - } - catch (error) { - const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); - } - } - return result; - } -} -exports.Metadata = Metadata; -const bufToString = (val) => { - return Buffer.isBuffer(val) ? val.toString('base64') : val; -}; -//# sourceMappingURL=metadata.js.map - -/***/ }), - -/***/ 31791: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OrcaOobMetricsSubchannelWrapper = exports.GRPC_METRICS_HEADER = exports.ServerMetricRecorder = exports.PerRequestMetricRecorder = void 0; -exports.createOrcaClient = createOrcaClient; -exports.createMetricsReader = createMetricsReader; -const make_client_1 = __nccwpck_require__(38541); -const duration_1 = __nccwpck_require__(62668); -const channel_credentials_1 = __nccwpck_require__(44030); -const subchannel_interface_1 = __nccwpck_require__(12258); -const constants_1 = __nccwpck_require__(90634); -const backoff_timeout_1 = __nccwpck_require__(34186); -const connectivity_state_1 = __nccwpck_require__(80878); -const loadedOrcaProto = null; -function loadOrcaProto() { - if (loadedOrcaProto) { - return loadedOrcaProto; - } - /* The purpose of this complexity is to avoid loading @grpc/proto-loader at - * runtime for users who will not use/enable ORCA. */ - const loaderLoadSync = (__nccwpck_require__(48934)/* .loadSync */ .J_); - const loadedProto = loaderLoadSync('xds/service/orca/v3/orca.proto', { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [ - __nccwpck_require__.ab + "xds", - __nccwpck_require__.ab + "protoc-gen-validate" - ], - }); - return (0, make_client_1.loadPackageDefinition)(loadedProto); -} -/** - * ORCA metrics recorder for a single request - */ -class PerRequestMetricRecorder { - constructor() { - this.message = {}; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordRequestCostMetric(name, value) { - if (!this.message.request_cost) { - this.message.request_cost = {}; - } - this.message.request_cost[name] = value; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - /** - * Records an opaque named metric measurement for the call. - * @param name - * @param value - */ - recordNamedMetric(name, value) { - if (!this.message.named_metrics) { - this.message.named_metrics = {}; - } - this.message.named_metrics[name] = value; - } - /** - * Records the CPU utilization metric measurement for the call. - * @param value - */ - recordCPUUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordMemoryUtilizationMetric(value) { - this.message.mem_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - /** - * Records the queries per second measurement. - * @param value - */ - recordQpsMetric(value) { - this.message.rps_fractional = value; - } - /** - * Records the errors per second measurement. - * @param value - */ - recordEpsMetric(value) { - this.message.eps = value; - } - serialize() { - const orcaProto = loadOrcaProto(); - return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); - } -} -exports.PerRequestMetricRecorder = PerRequestMetricRecorder; -const DEFAULT_REPORT_INTERVAL_MS = 30000; -class ServerMetricRecorder { - constructor() { - this.message = {}; - this.serviceImplementation = { - StreamCoreMetrics: call => { - const reportInterval = call.request.report_interval ? - (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : - DEFAULT_REPORT_INTERVAL_MS; - const reportTimer = setInterval(() => { - call.write(this.message); - }, reportInterval); - call.on('cancelled', () => { - clearInterval(reportTimer); - }); - } - }; - } - putUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - setAllUtilizationMetrics(metrics) { - this.message.utilization = Object.assign({}, metrics); - } - deleteUtilizationMetric(name) { - var _a; - (_a = this.message.utilization) === null || _a === void 0 ? true : delete _a[name]; - } - setCpuUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - deleteCpuUtilizationMetric() { - delete this.message.cpu_utilization; - } - setApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - deleteApplicationUtilizationMetric() { - delete this.message.application_utilization; - } - setQpsMetric(value) { - this.message.rps_fractional = value; - } - deleteQpsMetric() { - delete this.message.rps_fractional; - } - setEpsMetric(value) { - this.message.eps = value; - } - deleteEpsMetric() { - delete this.message.eps; - } - addToServer(server) { - const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; - server.addService(serviceDefinition, this.serviceImplementation); - } -} -exports.ServerMetricRecorder = ServerMetricRecorder; -function createOrcaClient(channel) { - const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; - return new ClientClass('unused', channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel }); -} -exports.GRPC_METRICS_HEADER = 'endpoint-load-metrics-bin'; -const PARSED_LOAD_REPORT_KEY = 'grpc_orca_load_report'; -/** - * Create an onCallEnded callback for use in a picker. - * @param listener The listener to handle metrics, whenever they are provided. - * @param previousOnCallEnded The previous onCallEnded callback to propagate - * to, if applicable. - * @returns - */ -function createMetricsReader(listener, previousOnCallEnded) { - return (code, details, metadata) => { - let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY); - if (parsedLoadReport) { - listener(parsedLoadReport); - } - else { - const serializedLoadReport = metadata.get(exports.GRPC_METRICS_HEADER); - if (serializedLoadReport.length > 0) { - const orcaProto = loadOrcaProto(); - parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]); - listener(parsedLoadReport); - metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); - } - } - if (previousOnCallEnded) { - previousOnCallEnded(code, details, metadata); - } - }; -} -const DATA_PRODUCER_KEY = 'orca_oob_metrics'; -class OobMetricsDataWatcher { - constructor(metricsListener, intervalMs) { - this.metricsListener = metricsListener; - this.intervalMs = intervalMs; - this.dataProducer = null; - } - setSubchannel(subchannel) { - const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); - this.dataProducer = producer; - producer.addDataWatcher(this); - } - destroy() { - var _a; - (_a = this.dataProducer) === null || _a === void 0 ? void 0 : _a.removeDataWatcher(this); - } - getInterval() { - return this.intervalMs; - } - onMetricsUpdate(metrics) { - this.metricsListener(metrics); - } -} -class OobMetricsDataProducer { - constructor(subchannel) { - this.subchannel = subchannel; - this.dataWatchers = new Set(); - this.orcaSupported = true; - this.metricsCall = null; - this.currentInterval = Infinity; - this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription()); - this.subchannelStateListener = () => this.updateMetricsSubscription(); - const channel = subchannel.getChannel(); - this.client = createOrcaClient(channel); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - addDataWatcher(dataWatcher) { - this.dataWatchers.add(dataWatcher); - this.updateMetricsSubscription(); - } - removeDataWatcher(dataWatcher) { - var _a; - this.dataWatchers.delete(dataWatcher); - if (this.dataWatchers.size === 0) { - this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.metricsCall = null; - this.client.close(); - this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - } - else { - this.updateMetricsSubscription(); - } - } - updateMetricsSubscription() { - var _a; - if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - return; - } - const newInterval = Math.min(...Array.from(this.dataWatchers).map(watcher => watcher.getInterval())); - if (!this.metricsCall || newInterval !== this.currentInterval) { - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.currentInterval = newInterval; - const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) }); - this.metricsCall = metricsCall; - metricsCall.on('data', (report) => { - this.dataWatchers.forEach(watcher => { - watcher.onMetricsUpdate(report); - }); - }); - metricsCall.on('error', (error) => { - this.metricsCall = null; - if (error.code === constants_1.Status.UNIMPLEMENTED) { - this.orcaSupported = false; - return; - } - if (error.code === constants_1.Status.CANCELLED) { - return; - } - this.backoffTimer.runOnce(); - }); - } - } -} -class OrcaOobMetricsSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(child, metricsListener, intervalMs) { - super(child); - this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); - } - getWrappedSubchannel() { - return this.child; - } -} -exports.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper; -function createOobMetricsDataProducer(subchannel) { - return new OobMetricsDataProducer(subchannel); -} -//# sourceMappingURL=orca.js.map - -/***/ }), - -/***/ 81611: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = void 0; -const metadata_1 = __nccwpck_require__(83665); -const constants_1 = __nccwpck_require__(90634); -var PickResultType; -(function (PickResultType) { - PickResultType[PickResultType["COMPLETE"] = 0] = "COMPLETE"; - PickResultType[PickResultType["QUEUE"] = 1] = "QUEUE"; - PickResultType[PickResultType["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; - PickResultType[PickResultType["DROP"] = 3] = "DROP"; -})(PickResultType || (exports.PickResultType = PickResultType = {})); -/** - * A standard picker representing a load balancer in the TRANSIENT_FAILURE - * state. Always responds to every pick request with an UNAVAILABLE status. - */ -class UnavailablePicker { - constructor(status) { - this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: 'No connection established', metadata: new metadata_1.Metadata() }, status); - } - pick(pickArgs) { - return { - pickResultType: PickResultType.TRANSIENT_FAILURE, - subchannel: null, - status: this.status, - onCallStarted: null, - onCallEnded: null, - }; - } -} -exports.UnavailablePicker = UnavailablePicker; -/** - * A standard picker representing a load balancer in the IDLE or CONNECTING - * state. Always responds to every pick request with a QUEUE pick result - * indicating that the pick should be tried again with the next `Picker`. Also - * reports back to the load balancer that a connection should be established - * once any pick is attempted. - * If the childPicker is provided, delegate to it instead of returning the - * hardcoded QUEUE pick result, but still calls exitIdle. - */ -class QueuePicker { - // Constructed with a load balancer. Calls exitIdle on it the first time pick is called - constructor(loadBalancer, childPicker) { - this.loadBalancer = loadBalancer; - this.childPicker = childPicker; - this.calledExitIdle = false; - } - pick(pickArgs) { - if (!this.calledExitIdle) { - process.nextTick(() => { - this.loadBalancer.exitIdle(); - }); - this.calledExitIdle = true; - } - if (this.childPicker) { - return this.childPicker.pick(pickArgs); - } - else { - return { - pickResultType: PickResultType.QUEUE, - subchannel: null, - status: null, - onCallStarted: null, - onCallEnded: null, - }; - } - } -} -exports.QueuePicker = QueuePicker; -//# sourceMappingURL=picker.js.map - -/***/ }), - -/***/ 38386: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PriorityQueue = void 0; -const top = 0; -const parent = (i) => Math.floor(i / 2); -const left = (i) => i * 2 + 1; -const right = (i) => i * 2 + 2; -/** - * A generic priority queue implemented as an array-based binary heap. - * Adapted from https://stackoverflow.com/a/42919752/159388 - */ -class PriorityQueue { - /** - * - * @param comparator Returns true if the first argument should precede the - * second in the queue. Defaults to `(a, b) => a > b` - */ - constructor(comparator = (a, b) => a > b) { - this.comparator = comparator; - this.heap = []; - } - /** - * @returns The number of items currently in the queue - */ - size() { - return this.heap.length; - } - /** - * @returns True if there are no items in the queue, false otherwise - */ - isEmpty() { - return this.size() == 0; - } - /** - * Look at the front item that would be popped, without modifying the contents - * of the queue - * @returns The front item in the queue, or undefined if the queue is empty - */ - peek() { - return this.heap[top]; - } - /** - * Add the items to the queue - * @param values The items to add - * @returns The new size of the queue after adding the items - */ - push(...values) { - values.forEach(value => { - this.heap.push(value); - this.siftUp(); - }); - return this.size(); - } - /** - * Remove the front item in the queue and return it - * @returns The front item in the queue, or undefined if the queue is empty - */ - pop() { - const poppedValue = this.peek(); - const bottom = this.size() - 1; - if (bottom > top) { - this.swap(top, bottom); - } - this.heap.pop(); - this.siftDown(); - return poppedValue; - } - /** - * Simultaneously remove the front item in the queue and add the provided - * item. - * @param value The item to add - * @returns The front item in the queue, or undefined if the queue is empty - */ - replace(value) { - const replacedValue = this.peek(); - this.heap[top] = value; - this.siftDown(); - return replacedValue; - } - greater(i, j) { - return this.comparator(this.heap[i], this.heap[j]); - } - swap(i, j) { - [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; - } - siftUp() { - let node = this.size() - 1; - while (node > top && this.greater(node, parent(node))) { - this.swap(node, parent(node)); - node = parent(node); - } - } - siftDown() { - let node = top; - while ((left(node) < this.size() && this.greater(left(node), node)) || - (right(node) < this.size() && this.greater(right(node), node))) { - let maxChild = (right(node) < this.size() && this.greater(right(node), left(node))) ? right(node) : left(node); - this.swap(node, maxChild); - node = maxChild; - } - } -} -exports.PriorityQueue = PriorityQueue; -//# sourceMappingURL=priority-queue.js.map - -/***/ }), - -/***/ 54886: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_PORT = void 0; -exports.setup = setup; -const resolver_1 = __nccwpck_require__(31594); -const dns_1 = __nccwpck_require__(9523); -const service_config_1 = __nccwpck_require__(21761); -const constants_1 = __nccwpck_require__(90634); -const call_interface_1 = __nccwpck_require__(78710); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const constants_2 = __nccwpck_require__(90634); -const uri_parser_1 = __nccwpck_require__(65974); -const net_1 = __nccwpck_require__(41808); -const backoff_timeout_1 = __nccwpck_require__(34186); -const environment_1 = __nccwpck_require__(29160); -const TRACER_NAME = 'dns_resolver'; -function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); -} -/** - * The default TCP port to connect to if not explicitly specified in the target. - */ -exports.DEFAULT_PORT = 443; -const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30000; -/** - * Resolver implementation that handles DNS names and IP addresses. - */ -class DnsResolver { - constructor(target, listener, channelOptions) { - var _a, _b, _c; - this.target = target; - this.listener = listener; - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.continueResolving = false; - this.isNextResolutionTimerRunning = false; - this.isServiceConfigEnabled = true; - this.returnedIpResult = false; - this.alternativeResolver = new dns_1.promises.Resolver(); - trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); - if (target.authority) { - this.alternativeResolver.setServers([target.authority]); - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (hostPort === null) { - this.ipResult = null; - this.dnsHostname = null; - this.port = null; - } - else { - if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { - this.ipResult = [ - { - addresses: [ - { - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports.DEFAULT_PORT, - }, - ], - }, - ]; - this.dnsHostname = null; - this.port = null; - } - else { - this.ipResult = null; - this.dnsHostname = hostPort.host; - this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports.DEFAULT_PORT; - } - } - this.percentage = Math.random() * 100; - if (channelOptions['grpc.service_config_disable_resolution'] === 1) { - this.isServiceConfigEnabled = false; - } - this.defaultResolutionError = { - code: constants_1.Status.UNAVAILABLE, - details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, - metadata: new metadata_1.Metadata(), - }; - const backoffOptions = { - initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], - maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], - }; - this.backoff = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, backoffOptions); - this.backoff.unref(); - this.minTimeBetweenResolutionsMs = - (_c = channelOptions['grpc.dns_min_time_between_resolutions_ms']) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; - this.nextResolutionTimer = setTimeout(() => { }, 0); - clearTimeout(this.nextResolutionTimer); - } - /** - * If the target is an IP address, just provide that address as a result. - * Otherwise, initiate A, AAAA, and TXT lookups - */ - startResolution() { - if (this.ipResult !== null) { - if (!this.returnedIpResult) { - trace('Returning IP address for target ' + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, ''); - }); - this.returnedIpResult = true; - } - this.backoff.stop(); - this.backoff.reset(); - this.stopNextResolutionTimer(); - return; - } - if (this.dnsHostname === null) { - trace('Failed to parse DNS address ' + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}` - }), {}, null, ''); - }); - this.stopNextResolutionTimer(); - } - else { - if (this.pendingLookupPromise !== null) { - return; - } - trace('Looking up DNS hostname ' + this.dnsHostname); - /* We clear out latestLookupResult here to ensure that it contains the - * latest result since the last time we started resolving. That way, the - * TXT resolution handler can use it, but only if it finishes second. We - * don't clear out any previous service config results because it's - * better to use a service config that's slightly out of date than to - * revert to an effectively blank one. */ - this.latestLookupResult = null; - const hostname = this.dnsHostname; - this.pendingLookupPromise = this.lookup(hostname); - this.pendingLookupPromise.then(addressList => { - if (this.pendingLookupPromise === null) { - return; - } - this.pendingLookupPromise = null; - this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map(address => ({ - addresses: [address], - }))); - const allAddressesString = '[' + - addressList.map(addr => addr.host + ':' + addr.port).join(',') + - ']'; - trace('Resolved addresses for target ' + - (0, uri_parser_1.uriToString)(this.target) + - ': ' + - allAddressesString); - /* If the TXT lookup has not yet finished, both of the last two - * arguments will be null, which is the equivalent of getting an - * empty TXT response. When the TXT lookup does finish, its handler - * can update the service config by using the same address list */ - const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); - this.handleHealthStatus(healthStatus); - }, err => { - if (this.pendingLookupPromise === null) { - return; - } - trace('Resolution error for target ' + - (0, uri_parser_1.uriToString)(this.target) + - ': ' + - err.message); - this.pendingLookupPromise = null; - this.stopNextResolutionTimer(); - this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, ''); - }); - /* If there already is a still-pending TXT resolution, we can just use - * that result when it comes in */ - if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { - /* We handle the TXT query promise differently than the others because - * the name resolution attempt as a whole is a success even if the TXT - * lookup fails */ - this.pendingTxtPromise = this.resolveTxt(hostname); - this.pendingTxtPromise.then(txtRecord => { - if (this.pendingTxtPromise === null) { - return; - } - this.pendingTxtPromise = null; - let serviceConfig; - try { - serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); - if (serviceConfig) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig); - } - else { - this.latestServiceConfigResult = null; - } - } - catch (err) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Parsing service config failed with error ${err.message}` - }); - } - if (this.latestLookupResult !== null) { - /* We rely here on the assumption that calling this function with - * identical parameters will be essentialy idempotent, and calling - * it with the same address list and a different service config - * should result in a fast and seamless switchover. */ - this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); - } - }, err => { - /* If TXT lookup fails we should do nothing, which means that we - * continue to use the result of the most recent successful lookup, - * or the default null config object if there has never been a - * successful lookup. We do not set the latestServiceConfigError - * here because that is specifically used for response validation - * errors. We still need to handle this error so that it does not - * bubble up as an unhandled promise rejection. */ - }); - } - } - } - /** - * The ResolverListener returns a boolean indicating whether the LB policy - * accepted the resolution result. A false result on an otherwise successful - * resolution should be treated as a resolution failure. - * @param healthStatus - */ - handleHealthStatus(healthStatus) { - if (healthStatus) { - this.backoff.stop(); - this.backoff.reset(); - } - else { - this.continueResolving = true; - } - } - async lookup(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace('Using alternative DNS resolver.'); - const records = await Promise.allSettled([ - this.alternativeResolver.resolve4(hostname), - this.alternativeResolver.resolve6(hostname), - ]); - if (records.every(result => result.status === 'rejected')) { - throw new Error(records[0].reason); - } - return records - .reduce((acc, result) => { - return result.status === 'fulfilled' - ? [...acc, ...result.value] - : acc; - }, []) - .map(addr => ({ - host: addr, - port: +this.port, - })); - } - /* We lookup both address families here and then split them up later - * because when looking up a single family, dns.lookup outputs an error - * if the name exists but there are no records for that family, and that - * error is indistinguishable from other kinds of errors */ - const addressList = await dns_1.promises.lookup(hostname, { all: true }); - return addressList.map(addr => ({ host: addr.address, port: +this.port })); - } - async resolveTxt(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace('Using alternative DNS resolver.'); - return this.alternativeResolver.resolveTxt(hostname); - } - return dns_1.promises.resolveTxt(hostname); - } - startNextResolutionTimer() { - var _a, _b; - clearTimeout(this.nextResolutionTimer); - this.nextResolutionTimer = setTimeout(() => { - this.stopNextResolutionTimer(); - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, this.minTimeBetweenResolutionsMs); - (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - this.isNextResolutionTimerRunning = true; - } - stopNextResolutionTimer() { - clearTimeout(this.nextResolutionTimer); - this.isNextResolutionTimerRunning = false; - } - startResolutionWithBackoff() { - if (this.pendingLookupPromise === null) { - this.continueResolving = false; - this.backoff.runOnce(); - this.startNextResolutionTimer(); - this.startResolution(); - } - } - updateResolution() { - /* If there is a pending lookup, just let it finish. Otherwise, if the - * nextResolutionTimer or backoff timer is running, set the - * continueResolving flag to resolve when whichever of those timers - * fires. Otherwise, start resolving immediately. */ - if (this.pendingLookupPromise === null) { - if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { - if (this.isNextResolutionTimerRunning) { - trace('resolution update delayed by "min time between resolutions" rate limit'); - } - else { - trace('resolution update delayed by backoff timer until ' + - this.backoff.getEndTime().toISOString()); - } - this.continueResolving = true; - } - else { - this.startResolutionWithBackoff(); - } - } - } - /** - * Reset the resolver to the same state it had when it was created. In-flight - * DNS requests cannot be cancelled, but they are discarded and their results - * will be ignored. - */ - destroy() { - this.continueResolving = false; - this.backoff.reset(); - this.backoff.stop(); - this.stopNextResolutionTimer(); - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.returnedIpResult = false; - } - /** - * Get the default authority for the given target. For IP targets, that is - * the IP address. For DNS targets, it is the hostname. - * @param target - */ - static getDefaultAuthority(target) { - return target.path; - } -} -/** - * Set up the DNS resolver class by registering it as the handler for the - * "dns:" prefix and as the default resolver. - */ -function setup() { - (0, resolver_1.registerResolver)('dns', DnsResolver); - (0, resolver_1.registerDefaultScheme)('dns'); -} -//# sourceMappingURL=resolver-dns.js.map - -/***/ }), - -/***/ 97902: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setup = setup; -const net_1 = __nccwpck_require__(41808); -const call_interface_1 = __nccwpck_require__(78710); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const resolver_1 = __nccwpck_require__(31594); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'ip_resolver'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const IPV4_SCHEME = 'ipv4'; -const IPV6_SCHEME = 'ipv6'; -/** - * The default TCP port to connect to if not explicitly specified in the target. - */ -const DEFAULT_PORT = 443; -class IpResolver { - constructor(target, listener, channelOptions) { - var _a; - this.listener = listener; - this.endpoints = []; - this.error = null; - this.hasReturnedResult = false; - trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); - const addresses = []; - if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Unrecognized scheme ${target.scheme} in IP resolver`, - metadata: new metadata_1.Metadata(), - }; - return; - } - const pathList = target.path.split(','); - for (const path of pathList) { - const hostPort = (0, uri_parser_1.splitHostPort)(path); - if (hostPort === null) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata(), - }; - return; - } - if ((target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host)) || - (target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host))) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata(), - }; - return; - } - addresses.push({ - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT, - }); - } - this.endpoints = addresses.map(address => ({ addresses: [address] })); - trace('Parsed ' + target.scheme + ' address list ' + addresses.map(subchannel_address_1.subchannelAddressToString)); - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(() => { - if (this.error) { - this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, ''); - } - else { - this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); - } - }); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return target.path.split(',')[0]; - } -} -function setup() { - (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); - (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); -} -//# sourceMappingURL=resolver-ip.js.map - -/***/ }), - -/***/ 5252: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setup = setup; -const resolver_1 = __nccwpck_require__(31594); -const call_interface_1 = __nccwpck_require__(78710); -class UdsResolver { - constructor(target, listener, channelOptions) { - this.listener = listener; - this.hasReturnedResult = false; - this.endpoints = []; - let path; - if (target.authority === '') { - path = '/' + target.path; - } - else { - path = target.path; - } - this.endpoints = [{ addresses: [{ path }] }]; - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return 'localhost'; - } -} -function setup() { - (0, resolver_1.registerResolver)('unix', UdsResolver); -} -//# sourceMappingURL=resolver-uds.js.map - -/***/ }), - -/***/ 31594: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0; -exports.registerResolver = registerResolver; -exports.registerDefaultScheme = registerDefaultScheme; -exports.createResolver = createResolver; -exports.getDefaultAuthority = getDefaultAuthority; -exports.mapUriDefaultScheme = mapUriDefaultScheme; -const uri_parser_1 = __nccwpck_require__(65974); -exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = 'grpc.internal.config_selector'; -const registeredResolvers = {}; -let defaultScheme = null; -/** - * Register a resolver class to handle target names prefixed with the `prefix` - * string. This prefix should correspond to a URI scheme name listed in the - * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) - * @param prefix - * @param resolverClass - */ -function registerResolver(scheme, resolverClass) { - registeredResolvers[scheme] = resolverClass; -} -/** - * Register a default resolver to handle target names that do not start with - * any registered prefix. - * @param resolverClass - */ -function registerDefaultScheme(scheme) { - defaultScheme = scheme; -} -/** - * Create a name resolver for the specified target, if possible. Throws an - * error if no such name resolver can be created. - * @param target - * @param listener - */ -function createResolver(target, listener, options) { - if (target.scheme !== undefined && target.scheme in registeredResolvers) { - return new registeredResolvers[target.scheme](target, listener, options); - } - else { - throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); - } -} -/** - * Get the default authority for the specified target, if possible. Throws an - * error if no registered name resolver can parse that target string. - * @param target - */ -function getDefaultAuthority(target) { - if (target.scheme !== undefined && target.scheme in registeredResolvers) { - return registeredResolvers[target.scheme].getDefaultAuthority(target); - } - else { - throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); - } -} -function mapUriDefaultScheme(target) { - if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { - if (defaultScheme !== null) { - return { - scheme: defaultScheme, - authority: undefined, - path: (0, uri_parser_1.uriToString)(target), - }; - } - else { - return null; - } - } - return target; -} -//# sourceMappingURL=resolver.js.map - -/***/ }), - -/***/ 39909: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ResolvingCall = void 0; -const call_credentials_1 = __nccwpck_require__(21426); -const constants_1 = __nccwpck_require__(90634); -const deadline_1 = __nccwpck_require__(511); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const control_plane_status_1 = __nccwpck_require__(39129); -const TRACER_NAME = 'resolving_call'; -class ResolvingCall { - constructor(channel, method, options, filterStackFactory, callNumber) { - this.channel = channel; - this.method = method; - this.filterStackFactory = filterStackFactory; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.readFilterPending = false; - this.writeFilterPending = false; - this.pendingChildStatus = null; - this.metadata = null; - this.listener = null; - this.statusWatchers = []; - this.deadlineTimer = setTimeout(() => { }, 0); - this.filterStack = null; - this.deadlineStartTime = null; - this.configReceivedTime = null; - this.childStartTime = null; - /** - * Credentials configured for this specific call. Does not include - * call credentials associated with the channel credentials used to create - * the channel. - */ - this.credentials = call_credentials_1.CallCredentials.createEmpty(); - this.deadline = options.deadline; - this.host = options.host; - if (options.parentCall) { - if (options.flags & constants_1.Propagate.CANCELLATION) { - options.parentCall.on('cancelled', () => { - this.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled by parent call'); - }); - } - if (options.flags & constants_1.Propagate.DEADLINE) { - this.trace('Propagating deadline from parent: ' + - options.parentCall.getDeadline()); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); - } - } - this.trace('Created'); - this.runDeadlineTimer(); - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - runDeadlineTimer() { - clearTimeout(this.deadlineTimer); - this.deadlineStartTime = new Date(); - this.trace('Deadline: ' + (0, deadline_1.deadlineToString)(this.deadline)); - const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); - if (timeout !== Infinity) { - this.trace('Deadline will be reached in ' + timeout + 'ms'); - const handleDeadline = () => { - if (!this.deadlineStartTime) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - return; - } - const deadlineInfo = []; - const deadlineEndTime = new Date(); - deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); - if (this.configReceivedTime) { - if (this.configReceivedTime > this.deadlineStartTime) { - deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); - } - if (this.childStartTime) { - if (this.childStartTime > this.configReceivedTime) { - deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); - } - } - else { - deadlineInfo.push('waiting for metadata filters'); - } - } - else { - deadlineInfo.push('waiting for name resolution'); - } - if (this.child) { - deadlineInfo.push(...this.child.getDeadlineInfo()); - } - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(',')); - }; - if (timeout <= 0) { - process.nextTick(handleDeadline); - } - else { - this.deadlineTimer = setTimeout(handleDeadline, timeout); - } - } - } - outputStatus(status) { - if (!this.ended) { - this.ended = true; - if (!this.filterStack) { - this.filterStack = this.filterStackFactory.createFilter(); - } - clearTimeout(this.deadlineTimer); - const filteredStatus = this.filterStack.receiveTrailers(status); - this.trace('ended with status: code=' + - filteredStatus.code + - ' details="' + - filteredStatus.details + - '"'); - this.statusWatchers.forEach(watcher => watcher(filteredStatus)); - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus); - }); - } - } - sendMessageOnChild(context, message) { - if (!this.child) { - throw new Error('sendMessageonChild called with child not populated'); - } - const child = this.child; - this.writeFilterPending = true; - this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })).then(filteredMessage => { - this.writeFilterPending = false; - child.sendMessageWithContext(context, filteredMessage.message); - if (this.pendingHalfClose) { - child.halfClose(); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - } - getConfig() { - if (this.ended) { - return; - } - if (!this.metadata || !this.listener) { - throw new Error('getConfig called before start'); - } - const configResult = this.channel.getConfig(this.method, this.metadata); - if (configResult.type === 'NONE') { - this.channel.queueCallForConfig(this); - return; - } - else if (configResult.type === 'ERROR') { - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } - else { - this.outputStatus(configResult.error); - } - return; - } - // configResult.type === 'SUCCESS' - this.configReceivedTime = new Date(); - const config = configResult.config; - if (config.status !== constants_1.Status.OK) { - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, 'Failed to route call to method ' + this.method); - this.outputStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }); - return; - } - if (config.methodConfig.timeout) { - const configDeadline = new Date(); - configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); - configDeadline.setMilliseconds(configDeadline.getMilliseconds() + - config.methodConfig.timeout.nanos / 1000000); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); - this.runDeadlineTimer(); - } - this.filterStackFactory.push(config.dynamicFilterFactories); - this.filterStack = this.filterStackFactory.createFilter(); - this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then(filteredMetadata => { - this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); - this.trace('Created child [' + this.child.getCallNumber() + ']'); - this.childStartTime = new Date(); - this.child.start(filteredMetadata, { - onReceiveMetadata: metadata => { - this.trace('Received metadata'); - this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); - }, - onReceiveMessage: message => { - this.trace('Received message'); - this.readFilterPending = true; - this.filterStack.receiveMessage(message).then(filteredMesssage => { - this.trace('Finished filtering received message'); - this.readFilterPending = false; - this.listener.onReceiveMessage(filteredMesssage); - if (this.pendingChildStatus) { - this.outputStatus(this.pendingChildStatus); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - }, - onReceiveStatus: status => { - this.trace('Received status'); - if (this.readFilterPending) { - this.pendingChildStatus = status; - } - else { - this.outputStatus(status); - } - }, - }); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); - } - else if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (status) => { - this.outputStatus(status); - }); - } - reportResolverError(status) { - var _a; - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } - else { - this.outputStatus(status); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ - code: status, - details: details, - metadata: new metadata_1.Metadata(), - }); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace('start called'); - this.metadata = metadata.clone(); - this.listener = listener; - this.getConfig(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - if (this.child) { - this.sendMessageOnChild(context, message); - } - else { - this.pendingMessage = { context, message }; - } - } - startRead() { - this.trace('startRead called'); - if (this.child) { - this.child.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - this.trace('halfClose called'); - if (this.child && !this.writeFilterPending) { - this.child.halfClose(); - } - else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - this.credentials = credentials; - } - addStatusWatcher(watcher) { - this.statusWatchers.push(watcher); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } - else { - return null; - } - } -} -exports.ResolvingCall = ResolvingCall; -//# sourceMappingURL=resolving-call.js.map - -/***/ }), - -/***/ 19192: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ResolvingLoadBalancer = void 0; -const load_balancer_1 = __nccwpck_require__(52680); -const service_config_1 = __nccwpck_require__(21761); -const connectivity_state_1 = __nccwpck_require__(80878); -const resolver_1 = __nccwpck_require__(31594); -const picker_1 = __nccwpck_require__(81611); -const backoff_timeout_1 = __nccwpck_require__(34186); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const constants_2 = __nccwpck_require__(90634); -const uri_parser_1 = __nccwpck_require__(65974); -const load_balancer_child_handler_1 = __nccwpck_require__(17559); -const TRACER_NAME = 'resolving_load_balancer'; -function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); -} -/** - * Name match levels in order from most to least specific. This is the order in - * which searches will be performed. - */ -const NAME_MATCH_LEVEL_ORDER = [ - 'SERVICE_AND_METHOD', - 'SERVICE', - 'EMPTY', -]; -function hasMatchingName(service, method, methodConfig, matchLevel) { - for (const name of methodConfig.name) { - switch (matchLevel) { - case 'EMPTY': - if (!name.service && !name.method) { - return true; - } - break; - case 'SERVICE': - if (name.service === service && !name.method) { - return true; - } - break; - case 'SERVICE_AND_METHOD': - if (name.service === service && name.method === method) { - return true; - } - } - } - return false; -} -function findMatchingConfig(service, method, methodConfigs, matchLevel) { - for (const config of methodConfigs) { - if (hasMatchingName(service, method, config, matchLevel)) { - return config; - } - } - return null; -} -function getDefaultConfigSelector(serviceConfig) { - return { - invoke(methodName, metadata) { - var _a, _b; - const splitName = methodName.split('/').filter(x => x.length > 0); - const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ''; - const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ''; - if (serviceConfig && serviceConfig.methodConfig) { - /* Check for the following in order, and return the first method - * config that matches: - * 1. A name that exactly matches the service and method - * 2. A name with no method set that matches the service - * 3. An empty name - */ - for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { - const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); - if (matchingConfig) { - return { - methodConfig: matchingConfig, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [], - }; - } - } - } - return { - methodConfig: { name: [] }, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [], - }; - }, - unref() { } - }; -} -class ResolvingLoadBalancer { - /** - * Wrapper class that behaves like a `LoadBalancer` and also handles name - * resolution internally. - * @param target The address of the backend to connect to. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - * @param defaultServiceConfig The default service configuration to be used - * if none is provided by the name resolver. A `null` value indicates - * that the default behavior should be the default unconfigured behavior. - * In practice, that means using the "pick first" load balancer - * implmentation - */ - constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { - this.target = target; - this.channelControlHelper = channelControlHelper; - this.channelOptions = channelOptions; - this.onSuccessfulResolution = onSuccessfulResolution; - this.onFailedResolution = onFailedResolution; - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.latestChildErrorMessage = null; - /** - * This resolving load balancer's current connectivity state. - */ - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The service config object from the last successful resolution, if - * available. A value of null indicates that we have not yet received a valid - * service config from the resolver. - */ - this.previousServiceConfig = null; - /** - * Indicates whether we should attempt to resolve again after the backoff - * timer runs out. - */ - this.continueResolving = false; - if (channelOptions['grpc.service_config']) { - this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions['grpc.service_config'])); - } - else { - this.defaultServiceConfig = { - loadBalancingConfig: [], - methodConfig: [], - }; - } - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ - createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), - requestReresolution: () => { - /* If the backoffTimeout is running, we're still backing off from - * making resolve requests, so we shouldn't make another one here. - * In that case, the backoff timer callback will call - * updateResolution */ - if (this.backoffTimeout.isRunning()) { - trace('requestReresolution delayed by backoff timer until ' + - this.backoffTimeout.getEndTime().toISOString()); - this.continueResolving = true; - } - else { - this.updateResolution(); - } - }, - updateState: (newState, picker, errorMessage) => { - this.latestChildState = newState; - this.latestChildPicker = picker; - this.latestChildErrorMessage = errorMessage; - this.updateState(newState, picker, errorMessage); - }, - addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), - removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper), - }); - this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions); - const backoffOptions = { - initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], - maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.updateResolution(); - this.continueResolving = false; - } - else { - this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); - } - }, backoffOptions); - this.backoffTimeout.unref(); - } - handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) { - var _a, _b; - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - let resultAccepted = true; - let workingServiceConfig = null; - if (serviceConfig === null) { - workingServiceConfig = this.defaultServiceConfig; - } - else if (serviceConfig.ok) { - workingServiceConfig = serviceConfig.value; - } - else { - if (this.previousServiceConfig !== null) { - workingServiceConfig = this.previousServiceConfig; - } - else { - resultAccepted = false; - this.handleResolutionFailure(serviceConfig.error); - } - } - if (workingServiceConfig !== null) { - const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : []; - const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); - if (loadBalancingConfig === null) { - resultAccepted = false; - this.handleResolutionFailure({ - code: constants_1.Status.UNAVAILABLE, - details: 'All load balancer options in service config are not compatible', - metadata: new metadata_1.Metadata(), - }); - } - else { - resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote); - } - } - if (resultAccepted) { - this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== void 0 ? _b : getDefaultConfigSelector(workingServiceConfig)); - } - return resultAccepted; - } - updateResolution() { - this.innerResolver.updateResolution(); - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { - /* this.latestChildPicker is initialized as new QueuePicker(this), which - * is an appropriate value here if the child LB policy is unset. - * Otherwise, we want to delegate to the child here, in case that - * triggers something. */ - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); - } - this.backoffTimeout.runOnce(); - } - updateState(connectivityState, picker, errorMessage) { - trace((0, uri_parser_1.uriToString)(this.target) + - ' ' + - connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[connectivityState]); - // Ensure that this.exitIdle() is called by the picker - if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { - picker = new picker_1.QueuePicker(this, picker); - } - this.currentState = connectivityState; - this.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - handleResolutionFailure(error) { - if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error), error.details); - this.onFailedResolution(error); - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || - this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - if (this.backoffTimeout.isRunning()) { - this.continueResolving = true; - } - else { - this.updateResolution(); - } - } - this.childLoadBalancer.exitIdle(); - } - updateAddressList(endpointList, lbConfig) { - throw new Error('updateAddressList not supported on ResolvingLoadBalancer'); - } - resetBackoff() { - this.backoffTimeout.reset(); - this.childLoadBalancer.resetBackoff(); - } - destroy() { - this.childLoadBalancer.destroy(); - this.innerResolver.destroy(); - this.backoffTimeout.reset(); - this.backoffTimeout.stop(); - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.previousServiceConfig = null; - this.continueResolving = false; - } - getTypeName() { - return 'resolving_load_balancer'; - } -} -exports.ResolvingLoadBalancer = ResolvingLoadBalancer; -//# sourceMappingURL=resolving-load-balancer.js.map - -/***/ }), - -/***/ 48159: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RetryingCall = exports.MessageBufferTracker = exports.RetryThrottler = void 0; -const constants_1 = __nccwpck_require__(90634); -const deadline_1 = __nccwpck_require__(511); -const metadata_1 = __nccwpck_require__(83665); -const logging = __nccwpck_require__(35993); -const TRACER_NAME = 'retrying_call'; -class RetryThrottler { - constructor(maxTokens, tokenRatio, previousRetryThrottler) { - this.maxTokens = maxTokens; - this.tokenRatio = tokenRatio; - if (previousRetryThrottler) { - /* When carrying over tokens from a previous config, rescale them to the - * new max value */ - this.tokens = - previousRetryThrottler.tokens * - (maxTokens / previousRetryThrottler.maxTokens); - } - else { - this.tokens = maxTokens; - } - } - addCallSucceeded() { - this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); - } - addCallFailed() { - this.tokens = Math.max(this.tokens - 1, 0); - } - canRetryCall() { - return this.tokens > (this.maxTokens / 2); - } -} -exports.RetryThrottler = RetryThrottler; -class MessageBufferTracker { - constructor(totalLimit, limitPerCall) { - this.totalLimit = totalLimit; - this.limitPerCall = limitPerCall; - this.totalAllocated = 0; - this.allocatedPerCall = new Map(); - } - allocate(size, callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.limitPerCall - currentPerCall < size || - this.totalLimit - this.totalAllocated < size) { - return false; - } - this.allocatedPerCall.set(callId, currentPerCall + size); - this.totalAllocated += size; - return true; - } - free(size, callId) { - var _a; - if (this.totalAllocated < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= size; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (currentPerCall < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); - } - this.allocatedPerCall.set(callId, currentPerCall - size); - } - freeAll(callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.totalAllocated < currentPerCall) { - throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= currentPerCall; - this.allocatedPerCall.delete(callId); - } -} -exports.MessageBufferTracker = MessageBufferTracker; -const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = 'grpc-previous-rpc-attempts'; -const DEFAULT_MAX_ATTEMPTS_LIMIT = 5; -class RetryingCall { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { - var _a; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.bufferTracker = bufferTracker; - this.retryThrottler = retryThrottler; - this.listener = null; - this.initialMetadata = null; - this.underlyingCalls = []; - this.writeBuffer = []; - /** - * The offset of message indices in the writeBuffer. For example, if - * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 - * is in writeBuffer[5]. - */ - this.writeBufferOffset = 0; - /** - * Tracks whether a read has been started, so that we know whether to start - * reads on new child calls. This only matters for the first read, because - * once a message comes in the child call becomes committed and there will - * be no new child calls. - */ - this.readStarted = false; - this.transparentRetryUsed = false; - /** - * Number of attempts so far - */ - this.attempts = 0; - this.hedgingTimer = null; - this.committedCallIndex = null; - this.initialRetryBackoffSec = 0; - this.nextRetryBackoffSec = 0; - const maxAttemptsLimit = (_a = channel.getOptions()['grpc-node.retry_max_attempts_limit']) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT; - if (channel.getOptions()['grpc.enable_retries'] === 0) { - this.state = 'NO_RETRY'; - this.maxAttempts = 1; - } - else if (callConfig.methodConfig.retryPolicy) { - this.state = 'RETRY'; - const retryPolicy = callConfig.methodConfig.retryPolicy; - this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); - this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); - } - else if (callConfig.methodConfig.hedgingPolicy) { - this.state = 'HEDGING'; - this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit); - } - else { - this.state = 'TRANSPARENT_ONLY'; - this.maxAttempts = 1; - } - this.startTime = new Date(); - } - getDeadlineInfo() { - if (this.underlyingCalls.length === 0) { - return []; - } - const deadlineInfo = []; - const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; - if (this.underlyingCalls.length > 1) { - deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); - } - if (latestCall.startTime > this.startTime) { - deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); - } - deadlineInfo.push(...latestCall.call.getDeadlineInfo()); - return deadlineInfo; - } - getCallNumber() { - return this.callNumber; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - reportStatus(statusObject) { - this.trace('ended with status: code=' + - statusObject.code + - ' details="' + - statusObject.details + - '" start time=' + - this.startTime.toISOString()); - this.bufferTracker.freeAll(this.callNumber); - this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; - this.writeBuffer = []; - process.nextTick(() => { - var _a; - // Explicitly construct status object to remove progress field - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({ - code: statusObject.code, - details: statusObject.details, - metadata: statusObject.metadata, - }); - }); - } - cancelWithStatus(status, details) { - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); - for (const { call } of this.underlyingCalls) { - call.cancelWithStatus(status, details); - } - } - getPeer() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getPeer(); - } - else { - return 'unknown'; - } - } - getBufferEntry(messageIndex) { - var _a; - return ((_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : { - entryType: 'FREED', - allocated: false, - }); - } - getNextBufferIndex() { - return this.writeBufferOffset + this.writeBuffer.length; - } - clearSentMessages() { - if (this.state !== 'COMMITTED') { - return; - } - let earliestNeededMessageIndex; - if (this.underlyingCalls[this.committedCallIndex].state === 'COMPLETED') { - /* If the committed call is completed, clear all messages, even if some - * have not been sent. */ - earliestNeededMessageIndex = this.getNextBufferIndex(); - } - else { - earliestNeededMessageIndex = - this.underlyingCalls[this.committedCallIndex].nextMessageToSend; - } - for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) { - const bufferEntry = this.getBufferEntry(messageIndex); - if (bufferEntry.allocated) { - this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); - } - } - this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); - this.writeBufferOffset = earliestNeededMessageIndex; - } - commitCall(index) { - var _a, _b; - if (this.state === 'COMMITTED') { - return; - } - this.trace('Committing call [' + - this.underlyingCalls[index].call.getCallNumber() + - '] at index ' + - index); - this.state = 'COMMITTED'; - (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); - this.committedCallIndex = index; - for (let i = 0; i < this.underlyingCalls.length; i++) { - if (i === index) { - continue; - } - if (this.underlyingCalls[i].state === 'COMPLETED') { - continue; - } - this.underlyingCalls[i].state = 'COMPLETED'; - this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, 'Discarded in favor of other hedged attempt'); - } - this.clearSentMessages(); - } - commitCallWithMostMessages() { - if (this.state === 'COMMITTED') { - return; - } - let mostMessages = -1; - let callWithMostMessages = -1; - for (const [index, childCall] of this.underlyingCalls.entries()) { - if (childCall.state === 'ACTIVE' && - childCall.nextMessageToSend > mostMessages) { - mostMessages = childCall.nextMessageToSend; - callWithMostMessages = index; - } - } - if (callWithMostMessages === -1) { - /* There are no active calls, disable retries to force the next call that - * is started to be committed. */ - this.state = 'TRANSPARENT_ONLY'; - } - else { - this.commitCall(callWithMostMessages); - } - } - isStatusCodeInList(list, code) { - return list.some(value => { - var _a; - return value === code || - value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); - }); - } - getNextRetryJitter() { - /* Jitter of +-20% is applied: https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff */ - return Math.random() * (1.2 - 0.8) + 0.8; - } - getNextRetryBackoffMs() { - var _a; - const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy; - if (!retryPolicy) { - return 0; - } - const jitter = this.getNextRetryJitter(); - const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1000; - const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); - this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); - return nextBackoffMs; - } - maybeRetryCall(pushback, callback) { - if (this.state !== 'RETRY') { - callback(false); - return; - } - if (this.attempts >= this.maxAttempts) { - callback(false); - return; - } - let retryDelayMs; - if (pushback === null) { - retryDelayMs = this.getNextRetryBackoffMs(); - } - else if (pushback < 0) { - this.state = 'TRANSPARENT_ONLY'; - callback(false); - return; - } - else { - retryDelayMs = pushback; - this.nextRetryBackoffSec = this.initialRetryBackoffSec; - } - setTimeout(() => { - var _a, _b; - if (this.state !== 'RETRY') { - callback(false); - return; - } - if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) { - callback(true); - this.attempts += 1; - this.startNewAttempt(); - } - else { - this.trace('Retry attempt denied by throttling policy'); - callback(false); - } - }, retryDelayMs); - } - countActiveCalls() { - let count = 0; - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE') { - count += 1; - } - } - return count; - } - handleProcessedStatus(status, callIndex, pushback) { - var _a, _b, _c; - switch (this.state) { - case 'COMMITTED': - case 'NO_RETRY': - case 'TRANSPARENT_ONLY': - this.commitCall(callIndex); - this.reportStatus(status); - break; - case 'HEDGING': - if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) { - (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed(); - let delayMs; - if (pushback === null) { - delayMs = 0; - } - else if (pushback < 0) { - this.state = 'TRANSPARENT_ONLY'; - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - else { - delayMs = pushback; - } - setTimeout(() => { - this.maybeStartHedgingAttempt(); - // If after trying to start a call there are no active calls, this was the last one - if (this.countActiveCalls() === 0) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }, delayMs); - } - else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - case 'RETRY': - if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { - (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed(); - this.maybeRetryCall(pushback, retried => { - if (!retried) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }); - } - else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - } - } - getPushback(metadata) { - const mdValue = metadata.get('grpc-retry-pushback-ms'); - if (mdValue.length === 0) { - return null; - } - try { - return parseInt(mdValue[0]); - } - catch (e) { - return -1; - } - } - handleChildStatus(status, callIndex) { - var _a; - if (this.underlyingCalls[callIndex].state === 'COMPLETED') { - return; - } - this.trace('state=' + - this.state + - ' handling status with progress ' + - status.progress + - ' from child [' + - this.underlyingCalls[callIndex].call.getCallNumber() + - '] in state ' + - this.underlyingCalls[callIndex].state); - this.underlyingCalls[callIndex].state = 'COMPLETED'; - if (status.code === constants_1.Status.OK) { - (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === 'NO_RETRY') { - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === 'COMMITTED') { - this.reportStatus(status); - return; - } - const pushback = this.getPushback(status.metadata); - switch (status.progress) { - case 'NOT_STARTED': - // RPC never leaves the client, always safe to retry - this.startNewAttempt(); - break; - case 'REFUSED': - // RPC reaches the server library, but not the server application logic - if (this.transparentRetryUsed) { - this.handleProcessedStatus(status, callIndex, pushback); - } - else { - this.transparentRetryUsed = true; - this.startNewAttempt(); - } - break; - case 'DROP': - this.commitCall(callIndex); - this.reportStatus(status); - break; - case 'PROCESSED': - this.handleProcessedStatus(status, callIndex, pushback); - break; - } - } - maybeStartHedgingAttempt() { - if (this.state !== 'HEDGING') { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - if (this.attempts >= this.maxAttempts) { - return; - } - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - maybeStartHedgingTimer() { - var _a, _b, _c; - if (this.hedgingTimer) { - clearTimeout(this.hedgingTimer); - } - if (this.state !== 'HEDGING') { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; - if (this.attempts >= this.maxAttempts) { - return; - } - const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : '0s'; - const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); - this.hedgingTimer = setTimeout(() => { - this.maybeStartHedgingAttempt(); - }, hedgingDelaySec * 1000); - (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - startNewAttempt() { - const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); - this.trace('Created child call [' + - child.getCallNumber() + - '] for attempt ' + - this.attempts); - const index = this.underlyingCalls.length; - this.underlyingCalls.push({ - state: 'ACTIVE', - call: child, - nextMessageToSend: 0, - startTime: new Date(), - }); - const previousAttempts = this.attempts - 1; - const initialMetadata = this.initialMetadata.clone(); - if (previousAttempts > 0) { - initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - let receivedMetadata = false; - child.start(initialMetadata, { - onReceiveMetadata: metadata => { - this.trace('Received metadata from child [' + child.getCallNumber() + ']'); - this.commitCall(index); - receivedMetadata = true; - if (previousAttempts > 0) { - metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - if (this.underlyingCalls[index].state === 'ACTIVE') { - this.listener.onReceiveMetadata(metadata); - } - }, - onReceiveMessage: message => { - this.trace('Received message from child [' + child.getCallNumber() + ']'); - this.commitCall(index); - if (this.underlyingCalls[index].state === 'ACTIVE') { - this.listener.onReceiveMessage(message); - } - }, - onReceiveStatus: status => { - this.trace('Received status from child [' + child.getCallNumber() + ']'); - if (!receivedMetadata && previousAttempts > 0) { - status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - this.handleChildStatus(status, index); - }, - }); - this.sendNextChildMessage(index); - if (this.readStarted) { - child.startRead(); - } - } - start(metadata, listener) { - this.trace('start called'); - this.listener = listener; - this.initialMetadata = metadata; - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - handleChildWriteCompleted(childIndex) { - var _a, _b; - const childCall = this.underlyingCalls[childIndex]; - const messageIndex = childCall.nextMessageToSend; - (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a); - this.clearSentMessages(); - childCall.nextMessageToSend += 1; - this.sendNextChildMessage(childIndex); - } - sendNextChildMessage(childIndex) { - const childCall = this.underlyingCalls[childIndex]; - if (childCall.state === 'COMPLETED') { - return; - } - if (this.getBufferEntry(childCall.nextMessageToSend)) { - const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend); - switch (bufferEntry.entryType) { - case 'MESSAGE': - childCall.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(childIndex); - }, - }, bufferEntry.message.message); - break; - case 'HALF_CLOSE': - childCall.nextMessageToSend += 1; - childCall.call.halfClose(); - break; - case 'FREED': - // Should not be possible - break; - } - } - } - sendMessageWithContext(context, message) { - var _a; - this.trace('write() called with message of length ' + message.length); - const writeObj = { - message, - flags: context.flags, - }; - const messageIndex = this.getNextBufferIndex(); - const bufferEntry = { - entryType: 'MESSAGE', - message: writeObj, - allocated: this.bufferTracker.allocate(message.length, this.callNumber), - }; - this.writeBuffer.push(bufferEntry); - if (bufferEntry.allocated) { - (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); - for (const [callIndex, call] of this.underlyingCalls.entries()) { - if (call.state === 'ACTIVE' && - call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(callIndex); - }, - }, message); - } - } - } - else { - this.commitCallWithMostMessages(); - // commitCallWithMostMessages can fail if we are between ping attempts - if (this.committedCallIndex === null) { - return; - } - const call = this.underlyingCalls[this.committedCallIndex]; - bufferEntry.callback = context.callback; - if (call.state === 'ACTIVE' && call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(this.committedCallIndex); - }, - }, message); - } - } - } - startRead() { - this.trace('startRead called'); - this.readStarted = true; - for (const underlyingCall of this.underlyingCalls) { - if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === 'ACTIVE') { - underlyingCall.call.startRead(); - } - } - } - halfClose() { - this.trace('halfClose called'); - const halfCloseIndex = this.getNextBufferIndex(); - this.writeBuffer.push({ - entryType: 'HALF_CLOSE', - allocated: false, - }); - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE' && - call.nextMessageToSend === halfCloseIndex) { - call.nextMessageToSend += 1; - call.call.halfClose(); - } - } - } - setCredentials(newCredentials) { - throw new Error('Method not implemented.'); - } - getMethod() { - return this.methodName; - } - getHost() { - return this.host; - } - getAuthContext() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getAuthContext(); - } - else { - return null; - } - } -} -exports.RetryingCall = RetryingCall; -//# sourceMappingURL=retrying-call.js.map - -/***/ }), - -/***/ 62533: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = void 0; -exports.serverErrorToStatus = serverErrorToStatus; -const events_1 = __nccwpck_require__(82361); -const stream_1 = __nccwpck_require__(12781); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -function serverErrorToStatus(error, overrideTrailers) { - var _a; - const status = { - code: constants_1.Status.UNKNOWN, - details: 'message' in error ? error.message : 'Unknown Error', - metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error.metadata) !== null && _a !== void 0 ? _a : null, - }; - if ('code' in error && - typeof error.code === 'number' && - Number.isInteger(error.code)) { - status.code = error.code; - if ('details' in error && typeof error.details === 'string') { - status.details = error.details; - } - } - return status; -} -class ServerUnaryCallImpl extends events_1.EventEmitter { - constructor(path, call, metadata, request) { - super(); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request; - this.cancelled = false; - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } -} -exports.ServerUnaryCallImpl = ServerUnaryCallImpl; -class ServerReadableStreamImpl extends stream_1.Readable { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.cancelled = false; - } - _read(size) { - this.call.startRead(); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } -} -exports.ServerReadableStreamImpl = ServerReadableStreamImpl; -class ServerWritableStreamImpl extends stream_1.Writable { - constructor(path, call, metadata, request) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request; - this.pendingStatus = { - code: constants_1.Status.OK, - details: 'OK', - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on('error', err => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _write(chunk, encoding, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } -} -exports.ServerWritableStreamImpl = ServerWritableStreamImpl; -class ServerDuplexStreamImpl extends stream_1.Duplex { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.pendingStatus = { - code: constants_1.Status.OK, - details: 'OK', - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on('error', err => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _read(size) { - this.call.startRead(); - } - _write(chunk, encoding, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } -} -exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl; -//# sourceMappingURL=server-call.js.map - -/***/ }), - -/***/ 63828: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ServerCredentials = void 0; -exports.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials; -exports.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors; -const tls_helpers_1 = __nccwpck_require__(86581); -class ServerCredentials { - constructor(serverConstructorOptions, contextOptions) { - this.serverConstructorOptions = serverConstructorOptions; - this.watchers = new Set(); - this.latestContextOptions = null; - this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null; - } - _addWatcher(watcher) { - this.watchers.add(watcher); - } - _removeWatcher(watcher) { - this.watchers.delete(watcher); - } - getWatcherCount() { - return this.watchers.size; - } - updateSecureContextOptions(options) { - this.latestContextOptions = options; - for (const watcher of this.watchers) { - watcher(this.latestContextOptions); - } - } - _isSecure() { - return this.serverConstructorOptions !== null; - } - _getSecureContextOptions() { - return this.latestContextOptions; - } - _getConstructorOptions() { - return this.serverConstructorOptions; - } - _getInterceptors() { - return []; - } - static createInsecure() { - return new InsecureServerCredentials(); - } - static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { - var _a; - if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { - throw new TypeError('rootCerts must be null or a Buffer'); - } - if (!Array.isArray(keyCertPairs)) { - throw new TypeError('keyCertPairs must be an array'); - } - if (typeof checkClientCertificate !== 'boolean') { - throw new TypeError('checkClientCertificate must be a boolean'); - } - const cert = []; - const key = []; - for (let i = 0; i < keyCertPairs.length; i++) { - const pair = keyCertPairs[i]; - if (pair === null || typeof pair !== 'object') { - throw new TypeError(`keyCertPair[${i}] must be an object`); - } - if (!Buffer.isBuffer(pair.private_key)) { - throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); - } - if (!Buffer.isBuffer(pair.cert_chain)) { - throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); - } - cert.push(pair.cert_chain); - key.push(pair.private_key); - } - return new SecureServerCredentials({ - requestCert: checkClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES, - }, { - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, - cert, - key, - }); - } -} -exports.ServerCredentials = ServerCredentials; -class InsecureServerCredentials extends ServerCredentials { - constructor() { - super(null); - } - _getSettings() { - return null; - } - _equals(other) { - return other instanceof InsecureServerCredentials; - } -} -class SecureServerCredentials extends ServerCredentials { - constructor(constructorOptions, contextOptions) { - super(constructorOptions, contextOptions); - this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions); - } - /** - * Checks equality by checking the options that are actually set by - * createSsl. - * @param other - * @returns - */ - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof SecureServerCredentials)) { - return false; - } - // options.ca equality check - if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { - if (!this.options.ca.equals(other.options.ca)) { - return false; - } - } - else { - if (this.options.ca !== other.options.ca) { - return false; - } - } - // options.cert equality check - if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { - if (this.options.cert.length !== other.options.cert.length) { - return false; - } - for (let i = 0; i < this.options.cert.length; i++) { - const thisCert = this.options.cert[i]; - const otherCert = other.options.cert[i]; - if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { - if (!thisCert.equals(otherCert)) { - return false; - } - } - else { - if (thisCert !== otherCert) { - return false; - } - } - } - } - else { - if (this.options.cert !== other.options.cert) { - return false; - } - } - // options.key equality check - if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { - if (this.options.key.length !== other.options.key.length) { - return false; - } - for (let i = 0; i < this.options.key.length; i++) { - const thisKey = this.options.key[i]; - const otherKey = other.options.key[i]; - if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { - if (!thisKey.equals(otherKey)) { - return false; - } - } - else { - if (thisKey !== otherKey) { - return false; - } - } - } - } - else { - if (this.options.key !== other.options.key) { - return false; - } - } - // options.requestCert equality check - if (this.options.requestCert !== other.options.requestCert) { - return false; - } - /* ciphers is derived from a value that is constant for the process, so no - * equality check is needed. */ - return true; - } -} -class CertificateProviderServerCredentials extends ServerCredentials { - constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) { - super({ - requestCert: caCertificateProvider !== null, - rejectUnauthorized: requireClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - this.identityCertificateProvider = identityCertificateProvider; - this.caCertificateProvider = caCertificateProvider; - this.requireClientCertificate = requireClientCertificate; - this.latestCaUpdate = null; - this.latestIdentityUpdate = null; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - } - _addWatcher(watcher) { - var _a; - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.addCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - super._addWatcher(watcher); - } - _removeWatcher(watcher) { - var _a; - super._removeWatcher(watcher); - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof CertificateProviderServerCredentials)) { - return false; - } - return (this.caCertificateProvider === other.caCertificateProvider && - this.identityCertificateProvider === other.identityCertificateProvider && - this.requireClientCertificate === other.requireClientCertificate); - } - calculateSecureContextOptions() { - var _a; - if (this.latestIdentityUpdate === null) { - return null; - } - if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { - return null; - } - return { - ca: (_a = this.latestCaUpdate) === null || _a === void 0 ? void 0 : _a.caCertificate, - cert: [this.latestIdentityUpdate.certificate], - key: [this.latestIdentityUpdate.privateKey], - }; - } - finalizeUpdate() { - const secureContextOptions = this.calculateSecureContextOptions(); - this.updateSecureContextOptions(secureContextOptions); - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.finalizeUpdate(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.finalizeUpdate(); - } -} -function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) { - return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate); -} -class InterceptorServerCredentials extends ServerCredentials { - constructor(childCredentials, interceptors) { - super({}); - this.childCredentials = childCredentials; - this.interceptors = interceptors; - } - _isSecure() { - return this.childCredentials._isSecure(); - } - _equals(other) { - if (!(other instanceof InterceptorServerCredentials)) { - return false; - } - if (!(this.childCredentials._equals(other.childCredentials))) { - return false; - } - if (this.interceptors.length !== other.interceptors.length) { - return false; - } - for (let i = 0; i < this.interceptors.length; i++) { - if (this.interceptors[i] !== other.interceptors[i]) { - return false; - } - } - return true; - } - _getInterceptors() { - return this.interceptors; - } - _addWatcher(watcher) { - this.childCredentials._addWatcher(watcher); - } - _removeWatcher(watcher) { - this.childCredentials._removeWatcher(watcher); - } - _getConstructorOptions() { - return this.childCredentials._getConstructorOptions(); - } - _getSecureContextOptions() { - return this.childCredentials._getSecureContextOptions(); - } -} -function createServerCredentialsWithInterceptors(credentials, interceptors) { - return new InterceptorServerCredentials(credentials, interceptors); -} -//# sourceMappingURL=server-credentials.js.map - -/***/ }), - -/***/ 20998: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2024 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseServerInterceptingCall = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = void 0; -exports.isInterceptingServerListener = isInterceptingServerListener; -exports.getServerInterceptingCall = getServerInterceptingCall; -const metadata_1 = __nccwpck_require__(83665); -const constants_1 = __nccwpck_require__(90634); -const http2 = __nccwpck_require__(85158); -const error_1 = __nccwpck_require__(22336); -const zlib = __nccwpck_require__(59796); -const stream_decoder_1 = __nccwpck_require__(16575); -const logging = __nccwpck_require__(35993); -const tls_1 = __nccwpck_require__(24404); -const orca_1 = __nccwpck_require__(31791); -const TRACER_NAME = 'server_call'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -class ServerListenerBuilder { - constructor() { - this.metadata = undefined; - this.message = undefined; - this.halfClose = undefined; - this.cancel = undefined; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveHalfClose(onReceiveHalfClose) { - this.halfClose = onReceiveHalfClose; - return this; - } - withOnCancel(onCancel) { - this.cancel = onCancel; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveHalfClose: this.halfClose, - onCancel: this.cancel, - }; - } -} -exports.ServerListenerBuilder = ServerListenerBuilder; -function isInterceptingServerListener(listener) { - return (listener.onReceiveMetadata !== undefined && - listener.onReceiveMetadata.length === 1); -} -class InterceptingServerListenerImpl { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - /** - * Once the call is cancelled, ignore all other events. - */ - this.cancelled = false; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.pendingMessage = null; - this.processingMessage = false; - this.hasPendingHalfClose = false; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingHalfClose() { - if (this.hasPendingHalfClose) { - this.nextListener.onReceiveHalfClose(); - this.hasPendingHalfClose = false; - } - } - onReceiveMetadata(metadata) { - if (this.cancelled) { - return; - } - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, interceptedMetadata => { - this.processingMetadata = false; - if (this.cancelled) { - return; - } - this.nextListener.onReceiveMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - onReceiveMessage(message) { - if (this.cancelled) { - return; - } - this.processingMessage = true; - this.listener.onReceiveMessage(message, msg => { - this.processingMessage = false; - if (this.cancelled) { - return; - } - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } - else { - this.nextListener.onReceiveMessage(msg); - this.processPendingHalfClose(); - } - }); - } - onReceiveHalfClose() { - if (this.cancelled) { - return; - } - this.listener.onReceiveHalfClose(() => { - if (this.cancelled) { - return; - } - if (this.processingMetadata || this.processingMessage) { - this.hasPendingHalfClose = true; - } - else { - this.nextListener.onReceiveHalfClose(); - } - }); - } - onCancel() { - this.cancelled = true; - this.listener.onCancel(); - this.nextListener.onCancel(); - } -} -class ResponderBuilder { - constructor() { - this.start = undefined; - this.metadata = undefined; - this.message = undefined; - this.status = undefined; - } - withStart(start) { - this.start = start; - return this; - } - withSendMetadata(sendMetadata) { - this.metadata = sendMetadata; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withSendStatus(sendStatus) { - this.status = sendStatus; - return this; - } - build() { - return { - start: this.start, - sendMetadata: this.metadata, - sendMessage: this.message, - sendStatus: this.status, - }; - } -} -exports.ResponderBuilder = ResponderBuilder; -const defaultServerListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveHalfClose: next => { - next(); - }, - onCancel: () => { }, -}; -const defaultResponder = { - start: next => { - next(); - }, - sendMetadata: (metadata, next) => { - next(metadata); - }, - sendMessage: (message, next) => { - next(message); - }, - sendStatus: (status, next) => { - next(status); - }, -}; -class ServerInterceptingCall { - constructor(nextCall, responder) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - this.processingMetadata = false; - this.sentMetadata = false; - this.processingMessage = false; - this.pendingMessage = null; - this.pendingMessageCallback = null; - this.pendingStatus = null; - this.responder = { - start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start, - sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata, - sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage, - sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus, - }; - } - processPendingMessage() { - if (this.pendingMessageCallback) { - this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); - this.pendingMessage = null; - this.pendingMessageCallback = null; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextCall.sendStatus(this.pendingStatus); - this.pendingStatus = null; - } - } - start(listener) { - this.responder.start(interceptedListener => { - var _a, _b, _c, _d; - const fullInterceptedListener = { - onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata, - onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage, - onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose, - onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel, - }; - const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); - this.nextCall.start(finalInterceptingListener); - }); - } - sendMetadata(metadata) { - this.processingMetadata = true; - this.sentMetadata = true; - this.responder.sendMetadata(metadata, interceptedMetadata => { - this.processingMetadata = false; - this.nextCall.sendMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - sendMessage(message, callback) { - this.processingMessage = true; - if (!this.sentMetadata) { - this.sendMetadata(new metadata_1.Metadata()); - } - this.responder.sendMessage(message, interceptedMessage => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = interceptedMessage; - this.pendingMessageCallback = callback; - } - else { - this.nextCall.sendMessage(interceptedMessage, callback); - } - }); - } - sendStatus(status) { - this.responder.sendStatus(status, interceptedStatus => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = interceptedStatus; - } - else { - this.nextCall.sendStatus(interceptedStatus); - } - }); - } - startRead() { - this.nextCall.startRead(); - } - getPeer() { - return this.nextCall.getPeer(); - } - getDeadline() { - return this.nextCall.getDeadline(); - } - getHost() { - return this.nextCall.getHost(); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } - getConnectionInfo() { - return this.nextCall.getConnectionInfo(); - } - getMetricsRecorder() { - return this.nextCall.getMetricsRecorder(); - } -} -exports.ServerInterceptingCall = ServerInterceptingCall; -const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding'; -const GRPC_ENCODING_HEADER = 'grpc-encoding'; -const GRPC_MESSAGE_HEADER = 'grpc-message'; -const GRPC_STATUS_HEADER = 'grpc-status'; -const GRPC_TIMEOUT_HEADER = 'grpc-timeout'; -const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; -const deadlineUnitsToMs = { - H: 3600000, - M: 60000, - S: 1000, - m: 1, - u: 0.001, - n: 0.000001, -}; -const defaultCompressionHeaders = { - // TODO(cjihrig): Remove these encoding headers from the default response - // once compression is integrated. - [GRPC_ACCEPT_ENCODING_HEADER]: 'identity,deflate,gzip', - [GRPC_ENCODING_HEADER]: 'identity', -}; -const defaultResponseHeaders = { - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, - [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', -}; -const defaultResponseOptions = { - waitForTrailers: true, -}; -class BaseServerInterceptingCall { - constructor(stream, headers, callEventTracker, handler, options) { - var _a, _b; - this.stream = stream; - this.callEventTracker = callEventTracker; - this.handler = handler; - this.listener = null; - this.deadlineTimer = null; - this.deadline = Infinity; - this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.cancelled = false; - this.metadataSent = false; - this.wantTrailers = false; - this.cancelNotified = false; - this.incomingEncoding = 'identity'; - this.readQueue = []; - this.isReadPending = false; - this.receivedHalfClose = false; - this.streamEnded = false; - this.metricsRecorder = new orca_1.PerRequestMetricRecorder(); - this.stream.once('error', (err) => { - /* We need an error handler to avoid uncaught error event exceptions, but - * there is nothing we can reasonably do here. Any error event should - * have a corresponding close event, which handles emitting the cancelled - * event. And the stream is now in a bad state, so we can't reasonably - * expect to be able to send an error over it. */ - }); - this.stream.once('close', () => { - var _a; - trace('Request to method ' + - ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + - ' stream closed with rstCode ' + - this.stream.rstCode); - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(false); - this.callEventTracker.onCallEnd({ - code: constants_1.Status.CANCELLED, - details: 'Stream closed before sending status', - metadata: null, - }); - } - this.notifyOnCancel(); - }); - this.stream.on('data', (data) => { - this.handleDataFrame(data); - }); - this.stream.pause(); - this.stream.on('end', () => { - this.handleEndEvent(); - }); - if ('grpc.max_send_message_length' in options) { - this.maxSendMessageSize = options['grpc.max_send_message_length']; - } - if ('grpc.max_receive_message_length' in options) { - this.maxReceiveMessageSize = options['grpc.max_receive_message_length']; - } - this.host = (_a = headers[':authority']) !== null && _a !== void 0 ? _a : headers.host; - this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize); - const metadata = metadata_1.Metadata.fromHttp2Headers(headers); - if (logging.isTracerEnabled(TRACER_NAME)) { - trace('Request to ' + - this.handler.path + - ' received headers ' + - JSON.stringify(metadata.toJSON())); - } - const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); - if (timeoutHeader.length > 0) { - this.handleTimeoutHeader(timeoutHeader[0]); - } - const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); - if (encodingHeader.length > 0) { - this.incomingEncoding = encodingHeader[0]; - } - // Remove several headers that should not be propagated to the application - metadata.remove(GRPC_TIMEOUT_HEADER); - metadata.remove(GRPC_ENCODING_HEADER); - metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); - metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); - metadata.remove(http2.constants.HTTP2_HEADER_TE); - metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); - this.metadata = metadata; - const socket = (_b = stream.session) === null || _b === void 0 ? void 0 : _b.socket; - this.connectionInfo = { - localAddress: socket === null || socket === void 0 ? void 0 : socket.localAddress, - localPort: socket === null || socket === void 0 ? void 0 : socket.localPort, - remoteAddress: socket === null || socket === void 0 ? void 0 : socket.remoteAddress, - remotePort: socket === null || socket === void 0 ? void 0 : socket.remotePort - }; - this.shouldSendMetrics = !!options['grpc.server_call_metric_recording']; - } - handleTimeoutHeader(timeoutHeader) { - const match = timeoutHeader.toString().match(DEADLINE_REGEX); - if (match === null) { - const status = { - code: constants_1.Status.INTERNAL, - details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, - metadata: null, - }; - // Wait for the constructor to complete before sending the error. - process.nextTick(() => { - this.sendStatus(status); - }); - return; - } - const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0; - const now = new Date(); - this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); - this.deadlineTimer = setTimeout(() => { - const status = { - code: constants_1.Status.DEADLINE_EXCEEDED, - details: 'Deadline exceeded', - metadata: null, - }; - this.sendStatus(status); - }, timeout); - } - checkCancelled() { - /* In some cases the stream can become destroyed before the close event - * fires. That creates a race condition that this check works around */ - if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { - this.notifyOnCancel(); - this.cancelled = true; - } - return this.cancelled; - } - notifyOnCancel() { - if (this.cancelNotified) { - return; - } - this.cancelNotified = true; - this.cancelled = true; - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel(); - }); - if (this.deadlineTimer) { - clearTimeout(this.deadlineTimer); - } - // Flush incoming data frames - this.stream.resume(); - } - /** - * A server handler can start sending messages without explicitly sending - * metadata. In that case, we need to send headers before sending any - * messages. This function does that if necessary. - */ - maybeSendMetadata() { - if (!this.metadataSent) { - this.sendMetadata(new metadata_1.Metadata()); - } - } - /** - * Serialize a message to a length-delimited byte string. - * @param value - * @returns - */ - serializeMessage(value) { - const messageBuffer = this.handler.serialize(value); - const byteLength = messageBuffer.byteLength; - const output = Buffer.allocUnsafe(byteLength + 5); - /* Note: response compression is currently not supported, so this - * compressed bit is always 0. */ - output.writeUInt8(0, 0); - output.writeUInt32BE(byteLength, 1); - messageBuffer.copy(output, 5); - return output; - } - decompressMessage(message, encoding) { - const messageContents = message.subarray(5); - if (encoding === 'identity') { - return messageContents; - } - else if (encoding === 'deflate' || encoding === 'gzip') { - let decompresser; - if (encoding === 'deflate') { - decompresser = zlib.createInflate(); - } - else { - decompresser = zlib.createGunzip(); - } - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(messageContents); - decompresser.end(); - }); - } - else { - return Promise.reject({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received message compressed with unsupported encoding "${encoding}"`, - }); - } - } - async decompressAndMaybePush(queueEntry) { - if (queueEntry.type !== 'COMPRESSED') { - throw new Error(`Invalid queue entry type: ${queueEntry.type}`); - } - const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; - const compressedMessageEncoding = compressed - ? this.incomingEncoding - : 'identity'; - let decompressedMessage; - try { - decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); - } - catch (err) { - this.sendStatus(err); - return; - } - try { - queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); - } - catch (err) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error deserializing request: ${err.message}`, - }); - return; - } - queueEntry.type = 'READABLE'; - this.maybePushNextMessage(); - } - maybePushNextMessage() { - if (this.listener && - this.isReadPending && - this.readQueue.length > 0 && - this.readQueue[0].type !== 'COMPRESSED') { - this.isReadPending = false; - const nextQueueEntry = this.readQueue.shift(); - if (nextQueueEntry.type === 'READABLE') { - this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); - } - else { - // nextQueueEntry.type === 'HALF_CLOSE' - this.listener.onReceiveHalfClose(); - } - } - } - handleDataFrame(data) { - var _a; - if (this.checkCancelled()) { - return; - } - trace('Request to ' + - this.handler.path + - ' received data frame of size ' + - data.length); - let rawMessages; - try { - rawMessages = this.decoder.write(data); - } - catch (e) { - this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message }); - return; - } - for (const messageBytes of rawMessages) { - this.stream.pause(); - const queueEntry = { - type: 'COMPRESSED', - compressedMessage: messageBytes, - parsedMessage: null, - }; - this.readQueue.push(queueEntry); - this.decompressAndMaybePush(queueEntry); - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived(); - } - } - handleEndEvent() { - this.readQueue.push({ - type: 'HALF_CLOSE', - compressedMessage: null, - parsedMessage: null, - }); - this.receivedHalfClose = true; - this.maybePushNextMessage(); - } - start(listener) { - trace('Request to ' + this.handler.path + ' start called'); - if (this.checkCancelled()) { - return; - } - this.listener = listener; - listener.onReceiveMetadata(this.metadata); - } - sendMetadata(metadata) { - if (this.checkCancelled()) { - return; - } - if (this.metadataSent) { - return; - } - this.metadataSent = true; - const custom = metadata ? metadata.toHttp2Headers() : null; - const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); - this.stream.respond(headers, defaultResponseOptions); - } - sendMessage(message, callback) { - if (this.checkCancelled()) { - return; - } - let response; - try { - response = this.serializeMessage(message); - } - catch (e) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, - metadata: null, - }); - return; - } - if (this.maxSendMessageSize !== -1 && - response.length - 5 > this.maxSendMessageSize) { - this.sendStatus({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, - metadata: null, - }); - return; - } - this.maybeSendMetadata(); - trace('Request to ' + - this.handler.path + - ' sent data frame of size ' + - response.length); - this.stream.write(response, error => { - var _a; - if (error) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`, - metadata: null, - }); - return; - } - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent(); - callback(); - }); - } - sendStatus(status) { - var _a, _b, _c; - if (this.checkCancelled()) { - return; - } - trace('Request to method ' + - ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + - ' ended with status code: ' + - constants_1.Status[status.code] + - ' details: ' + - status.details); - const statusMetadata = (_c = (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.clone()) !== null && _c !== void 0 ? _c : new metadata_1.Metadata(); - if (this.shouldSendMetrics) { - statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); - } - if (this.metadataSent) { - if (!this.wantTrailers) { - this.wantTrailers = true; - this.stream.once('wantTrailers', () => { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers()); - this.stream.sendTrailers(trailersToSend); - this.notifyOnCancel(); - }); - this.stream.end(); - } - else { - this.notifyOnCancel(); - } - } - else { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - // Trailers-only response - const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers()); - this.stream.respond(trailersToSend, { endStream: true }); - this.notifyOnCancel(); - } - } - startRead() { - trace('Request to ' + this.handler.path + ' startRead called'); - if (this.checkCancelled()) { - return; - } - this.isReadPending = true; - if (this.readQueue.length === 0) { - if (!this.receivedHalfClose) { - this.stream.resume(); - } - } - else { - this.maybePushNextMessage(); - } - } - getPeer() { - var _a; - const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket; - if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) { - if (socket.remotePort) { - return `${socket.remoteAddress}:${socket.remotePort}`; - } - else { - return socket.remoteAddress; - } - } - else { - return 'unknown'; - } - } - getDeadline() { - return this.deadline; - } - getHost() { - return this.host; - } - getAuthContext() { - var _a; - if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { - const peerCertificate = this.stream.session.socket.getPeerCertificate(); - return { - transportSecurityType: 'ssl', - sslPeerCertificate: peerCertificate.raw ? peerCertificate : undefined - }; - } - else { - return {}; - } - } - getConnectionInfo() { - return this.connectionInfo; - } - getMetricsRecorder() { - return this.metricsRecorder; - } -} -exports.BaseServerInterceptingCall = BaseServerInterceptingCall; -function getServerInterceptingCall(interceptors, stream, headers, callEventTracker, handler, options) { - const methodDefinition = { - path: handler.path, - requestStream: handler.type === 'clientStream' || handler.type === 'bidi', - responseStream: handler.type === 'serverStream' || handler.type === 'bidi', - requestDeserialize: handler.deserialize, - responseSerialize: handler.serialize, - }; - const baseCall = new BaseServerInterceptingCall(stream, headers, callEventTracker, handler, options); - return interceptors.reduce((call, interceptor) => { - return interceptor(methodDefinition, call); - }, baseCall); -} -//# sourceMappingURL=server-interceptors.js.map - -/***/ }), - -/***/ 33389: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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 __runInitializers = (this && this.__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; -}; -var __esDecorate = (this && this.__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; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Server = void 0; -const http2 = __nccwpck_require__(85158); -const util = __nccwpck_require__(73837); -const constants_1 = __nccwpck_require__(90634); -const server_call_1 = __nccwpck_require__(62533); -const server_credentials_1 = __nccwpck_require__(63828); -const resolver_1 = __nccwpck_require__(31594); -const logging = __nccwpck_require__(35993); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const channelz_1 = __nccwpck_require__(79975); -const server_interceptors_1 = __nccwpck_require__(20998); -const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); -const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); -const KEEPALIVE_TIMEOUT_MS = 20000; -const MAX_CONNECTION_IDLE_MS = ~(1 << 31); -const { HTTP2_HEADER_PATH } = http2.constants; -const TRACER_NAME = 'server'; -const kMaxAge = Buffer.from('max_age'); -function serverCallTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'server_call', text); -} -function noop() { } -/** - * Decorator to wrap a class method with util.deprecate - * @param message The message to output if the deprecated method is called - * @returns - */ -function deprecate(message) { - return function (target, context) { - return util.deprecate(target, message); - }; -} -function getUnimplementedStatusResponse(methodName) { - return { - code: constants_1.Status.UNIMPLEMENTED, - details: `The server does not implement the method ${methodName}`, - }; -} -function getDefaultHandler(handlerType, methodName) { - const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); - switch (handlerType) { - case 'unary': - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case 'clientStream': - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case 'serverStream': - return (call) => { - call.emit('error', unimplementedStatusResponse); - }; - case 'bidi': - return (call) => { - call.emit('error', unimplementedStatusResponse); - }; - default: - throw new Error(`Invalid handlerType ${handlerType}`); - } -} -let Server = (() => { - var _a; - let _instanceExtraInitializers = []; - let _start_decorators; - return _a = class Server { - constructor(options) { - var _b, _c, _d, _e, _f, _g; - this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), new Map()); - this.http2Servers = new Map(); - this.sessionIdleTimeouts = new Map(); - this.handlers = new Map(); - this.sessions = new Map(); - /** - * This field only exists to ensure that the start method throws an error if - * it is called twice, as it did previously. - */ - this.started = false; - this.shutdown = false; - this.serverAddressString = 'null'; - // Channelz Info - this.channelzEnabled = true; - this.options = options !== null && options !== void 0 ? options : {}; - if (this.options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - } - else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzServer)('server', () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace('CT_INFO', 'Server created'); - this.maxConnectionAgeMs = - (_b = this.options['grpc.max_connection_age_ms']) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS; - this.maxConnectionAgeGraceMs = - (_c = this.options['grpc.max_connection_age_grace_ms']) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS; - this.keepaliveTimeMs = - (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS; - this.keepaliveTimeoutMs = - (_e = this.options['grpc.keepalive_timeout_ms']) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS; - this.sessionIdleTimeout = - (_f = this.options['grpc.max_connection_idle_ms']) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS; - this.commonServerOptions = { - maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, - }; - if ('grpc-node.max_session_memory' in this.options) { - this.commonServerOptions.maxSessionMemory = - this.options['grpc-node.max_session_memory']; - } - else { - /* By default, set a very large max session memory limit, to effectively - * disable enforcement of the limit. Some testing indicates that Node's - * behavior degrades badly when this limit is reached, so we solve that - * by disabling the check entirely. */ - this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; - } - if ('grpc.max_concurrent_streams' in this.options) { - this.commonServerOptions.settings = { - maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], - }; - } - this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : []; - this.trace('Server constructed'); - } - getChannelzInfo() { - return { - trace: this.channelzTrace, - callTracker: this.callTracker, - listenerChildren: this.listenerChildrenTracker.getChildLists(), - sessionChildren: this.sessionChildrenTracker.getChildLists(), - }; - } - getChannelzSessionInfo(session) { - var _b, _c, _d; - const sessionInfo = this.sessions.get(session); - const sessionSocket = session.socket; - const remoteAddress = sessionSocket.remoteAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) - : null; - const localAddress = sessionSocket.localAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) - : null; - let tlsInfo; - if (session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && 'raw' in peerCertificate - ? peerCertificate.raw - : null, - }; - } - else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress: remoteAddress, - localAddress: localAddress, - security: tlsInfo, - remoteName: null, - streamsStarted: sessionInfo.streamTracker.callsStarted, - streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, - streamsFailed: sessionInfo.streamTracker.callsFailed, - messagesSent: sessionInfo.messagesSent, - messagesReceived: sessionInfo.messagesReceived, - keepAlivesSent: sessionInfo.keepAlivesSent, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, - lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, - localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null, - remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null, - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + this.channelzRef.id + ') ' + text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + this.channelzRef.id + ') ' + text); - } - addProtoService() { - throw new Error('Not implemented. Use addService() instead'); - } - addService(service, implementation) { - if (service === null || - typeof service !== 'object' || - implementation === null || - typeof implementation !== 'object') { - throw new Error('addService() requires two objects as arguments'); - } - const serviceKeys = Object.keys(service); - if (serviceKeys.length === 0) { - throw new Error('Cannot add an empty service to a server'); - } - serviceKeys.forEach(name => { - const attrs = service[name]; - let methodType; - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = 'bidi'; - } - else { - methodType = 'clientStream'; - } - } - else { - if (attrs.responseStream) { - methodType = 'serverStream'; - } - else { - methodType = 'unary'; - } - } - let implFn = implementation[name]; - let impl; - if (implFn === undefined && typeof attrs.originalName === 'string') { - implFn = implementation[attrs.originalName]; - } - if (implFn !== undefined) { - impl = implFn.bind(implementation); - } - else { - impl = getDefaultHandler(methodType, name); - } - const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); - if (success === false) { - throw new Error(`Method handler for ${attrs.path} already provided.`); - } - }); - } - removeService(service) { - if (service === null || typeof service !== 'object') { - throw new Error('removeService() requires object as argument'); - } - const serviceKeys = Object.keys(service); - serviceKeys.forEach(name => { - const attrs = service[name]; - this.unregister(attrs.path); - }); - } - bind(port, creds) { - throw new Error('Not implemented. Use bindAsync() instead'); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param boundAddress - * @returns - */ - experimentalRegisterListenerToChannelz(boundAddress) { - return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { - return { - localAddress: boundAddress, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null, - }; - }, this.channelzEnabled); - } - experimentalUnregisterListenerFromChannelz(channelzRef) { - (0, channelz_1.unregisterChannelzRef)(channelzRef); - } - createHttp2Server(credentials) { - let http2Server; - if (credentials._isSecure()) { - const constructorOptions = credentials._getConstructorOptions(); - const contextOptions = credentials._getSecureContextOptions(); - const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options['grpc-node.tls_enable_trace'] === 1 }); - let areCredentialsValid = contextOptions !== null; - this.trace('Initial credentials valid: ' + areCredentialsValid); - http2Server = http2.createSecureServer(secureServerOptions); - http2Server.prependListener('connection', (socket) => { - if (!areCredentialsValid) { - this.trace('Dropped connection from ' + JSON.stringify(socket.address()) + ' due to unloaded credentials'); - socket.destroy(); - } - }); - http2Server.on('secureConnection', (socket) => { - /* These errors need to be handled by the user of Http2SecureServer, - * according to https://github.com/nodejs/node/issues/35824 */ - socket.on('error', (e) => { - this.trace('An incoming TLS connection closed with error: ' + e.message); - }); - }); - const credsWatcher = options => { - if (options) { - const secureServer = http2Server; - try { - secureServer.setSecureContext(options); - } - catch (e) { - logging.log(constants_1.LogVerbosity.ERROR, 'Failed to set secure context with error ' + e.message); - options = null; - } - } - areCredentialsValid = options !== null; - this.trace('Post-update credentials valid: ' + areCredentialsValid); - }; - credentials._addWatcher(credsWatcher); - http2Server.on('close', () => { - credentials._removeWatcher(credsWatcher); - }); - } - else { - http2Server = http2.createServer(this.commonServerOptions); - } - http2Server.setTimeout(0, noop); - this._setupHandlers(http2Server, credentials._getInterceptors()); - return http2Server; - } - bindOneAddress(address, boundPortObject) { - this.trace('Attempting to bind ' + (0, subchannel_address_1.subchannelAddressToString)(address)); - const http2Server = this.createHttp2Server(boundPortObject.credentials); - return new Promise((resolve, reject) => { - const onError = (err) => { - this.trace('Failed to bind ' + - (0, subchannel_address_1.subchannelAddressToString)(address) + - ' with error ' + - err.message); - resolve({ - port: 'port' in address ? address.port : 1, - error: err.message, - }); - }; - http2Server.once('error', onError); - http2Server.listen(address, () => { - const boundAddress = http2Server.address(); - let boundSubchannelAddress; - if (typeof boundAddress === 'string') { - boundSubchannelAddress = { - path: boundAddress, - }; - } - else { - boundSubchannelAddress = { - host: boundAddress.address, - port: boundAddress.port, - }; - } - const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress); - this.listenerChildrenTracker.refChild(channelzRef); - this.http2Servers.set(http2Server, { - channelzRef: channelzRef, - sessions: new Set(), - ownsChannelzRef: true - }); - boundPortObject.listeningServers.add(http2Server); - this.trace('Successfully bound ' + - (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); - resolve({ - port: 'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1, - }); - http2Server.removeListener('error', onError); - }); - }); - } - async bindManyPorts(addressList, boundPortObject) { - if (addressList.length === 0) { - return { - count: 0, - port: 0, - errors: [], - }; - } - if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { - /* If binding to port 0, first try to bind the first address, then bind - * the rest of the address list to the specific port that it binds. */ - const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); - if (firstAddressResult.error) { - /* If the first address fails to bind, try the same operation starting - * from the second item in the list. */ - const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); - return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); - } - else { - const restAddresses = addressList - .slice(1) - .map(address => (0, subchannel_address_1.isTcpSubchannelAddress)(address) - ? { host: address.host, port: firstAddressResult.port } - : address); - const restAddressResult = await Promise.all(restAddresses.map(address => this.bindOneAddress(address, boundPortObject))); - const allResults = [firstAddressResult, ...restAddressResult]; - return { - count: allResults.filter(result => result.error === undefined).length, - port: firstAddressResult.port, - errors: allResults - .filter(result => result.error) - .map(result => result.error), - }; - } - } - else { - const allResults = await Promise.all(addressList.map(address => this.bindOneAddress(address, boundPortObject))); - return { - count: allResults.filter(result => result.error === undefined).length, - port: allResults[0].port, - errors: allResults - .filter(result => result.error) - .map(result => result.error), - }; - } - } - async bindAddressList(addressList, boundPortObject) { - const bindResult = await this.bindManyPorts(addressList, boundPortObject); - if (bindResult.count > 0) { - if (bindResult.count < addressList.length) { - logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); - } - return bindResult.port; - } - else { - const errorString = `No address added out of total ${addressList.length} resolved`; - logging.log(constants_1.LogVerbosity.ERROR, errorString); - throw new Error(`${errorString} errors: [${bindResult.errors.join(',')}]`); - } - } - resolvePort(port) { - return new Promise((resolve, reject) => { - let seenResolution = false; - const resolverListener = (endpointList, attributes, serviceConfig, resolutionNote) => { - if (seenResolution) { - return true; - } - seenResolution = true; - if (!endpointList.ok) { - reject(new Error(endpointList.error.details)); - return true; - } - const addressList = [].concat(...endpointList.value.map(endpoint => endpoint.addresses)); - if (addressList.length === 0) { - reject(new Error(`No addresses resolved for port ${port}`)); - return true; - } - resolve(addressList); - return true; - }; - const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); - resolver.updateResolution(); - }); - } - async bindPort(port, boundPortObject) { - const addressList = await this.resolvePort(port); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error('bindAsync operation cancelled by unbind call'); - } - const portNumber = await this.bindAddressList(addressList, boundPortObject); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error('bindAsync operation cancelled by unbind call'); - } - return portNumber; - } - normalizePort(port) { - const initialPortUri = (0, uri_parser_1.parseUri)(port); - if (initialPortUri === null) { - throw new Error(`Could not parse port "${port}"`); - } - const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); - if (portUri === null) { - throw new Error(`Could not get a default scheme for port "${port}"`); - } - return portUri; - } - bindAsync(port, creds, callback) { - if (this.shutdown) { - throw new Error('bindAsync called after shutdown'); - } - if (typeof port !== 'string') { - throw new TypeError('port must be a string'); - } - if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - if (typeof callback !== 'function') { - throw new TypeError('callback must be a function'); - } - this.trace('bindAsync port=' + port); - const portUri = this.normalizePort(port); - const deferredCallback = (error, port) => { - process.nextTick(() => callback(error, port)); - }; - /* First, if this port is already bound or that bind operation is in - * progress, use that result. */ - let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - if (!creds._equals(boundPortObject.credentials)) { - deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); - return; - } - /* If that operation has previously been cancelled by an unbind call, - * uncancel it. */ - boundPortObject.cancelled = false; - if (boundPortObject.completionPromise) { - boundPortObject.completionPromise.then(portNum => callback(null, portNum), error => callback(error, 0)); - } - else { - deferredCallback(null, boundPortObject.portNumber); - } - return; - } - boundPortObject = { - mapKey: (0, uri_parser_1.uriToString)(portUri), - originalUri: portUri, - completionPromise: null, - cancelled: false, - portNumber: 0, - credentials: creds, - listeningServers: new Set(), - }; - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - const completionPromise = this.bindPort(portUri, boundPortObject); - boundPortObject.completionPromise = completionPromise; - /* If the port number is 0, defer populating the map entry until after the - * bind operation completes and we have a specific port number. Otherwise, - * populate it immediately. */ - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - completionPromise.then(portNum => { - const finalUri = { - scheme: portUri.scheme, - authority: portUri.authority, - path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }), - }; - boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - callback(null, portNum); - }, error => { - callback(error, 0); - }); - } - else { - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - completionPromise.then(portNum => { - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - callback(null, portNum); - }, error => { - callback(error, 0); - }); - } - } - registerInjectorToChannelz() { - return (0, channelz_1.registerChannelzSocket)('injector', () => { - return { - localAddress: null, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null, - }; - }, this.channelzEnabled); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param credentials - * @param channelzRef - * @returns - */ - experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - if (this.channelzEnabled) { - this.listenerChildrenTracker.refChild(channelzRef); - } - const server = this.createHttp2Server(credentials); - const sessionsSet = new Set(); - this.http2Servers.set(server, { - channelzRef: channelzRef, - sessions: sessionsSet, - ownsChannelzRef - }); - return { - injectConnection: (connection) => { - server.emit('connection', connection); - }, - drain: (graceTimeMs) => { - var _b, _c; - for (const session of sessionsSet) { - this.closeSession(session); - } - (_c = (_b = setTimeout(() => { - for (const session of sessionsSet) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - }, - destroy: () => { - this.closeServer(server); - for (const session of sessionsSet) { - this.closeSession(session); - } - } - }; - } - createConnectionInjector(credentials) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - const channelzRef = this.registerInjectorToChannelz(); - return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); - } - closeServer(server, callback) { - this.trace('Closing server with address ' + JSON.stringify(server.address())); - const serverInfo = this.http2Servers.get(server); - server.close(() => { - if (serverInfo && serverInfo.ownsChannelzRef) { - this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); - (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); - } - this.http2Servers.delete(server); - callback === null || callback === void 0 ? void 0 : callback(); - }); - } - closeSession(session, callback) { - var _b; - this.trace('Closing session initiated by ' + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); - const sessionInfo = this.sessions.get(session); - const closeCallback = () => { - if (sessionInfo) { - this.sessionChildrenTracker.unrefChild(sessionInfo.ref); - (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); - } - callback === null || callback === void 0 ? void 0 : callback(); - }; - if (session.closed) { - queueMicrotask(closeCallback); - } - else { - session.close(closeCallback); - } - } - completeUnbind(boundPortObject) { - for (const server of boundPortObject.listeningServers) { - const serverInfo = this.http2Servers.get(server); - this.closeServer(server, () => { - boundPortObject.listeningServers.delete(server); - }); - if (serverInfo) { - for (const session of serverInfo.sessions) { - this.closeSession(session); - } - } - } - this.boundPorts.delete(boundPortObject.mapKey); - } - /** - * Unbind a previously bound port, or cancel an in-progress bindAsync - * operation. If port 0 was bound, only the actual bound port can be - * unbound. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be unbound as "localhost:54321". - * @param port - */ - unbind(port) { - this.trace('unbind port=' + port); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error('Cannot unbind port 0'); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - this.trace('unbinding ' + - boundPortObject.mapKey + - ' originally bound as ' + - (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); - /* If the bind operation is pending, the cancelled flag will trigger - * the unbind operation later. */ - if (boundPortObject.completionPromise) { - boundPortObject.cancelled = true; - } - else { - this.completeUnbind(boundPortObject); - } - } - } - /** - * Gracefully close all connections associated with a previously bound port. - * After the grace time, forcefully close all remaining open connections. - * - * If port 0 was bound, only the actual bound port can be - * drained. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be drained as "localhost:54321". - * @param port - * @param graceTimeMs - * @returns - */ - drain(port, graceTimeMs) { - var _b, _c; - this.trace('drain port=' + port + ' graceTimeMs=' + graceTimeMs); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error('Cannot drain port 0'); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (!boundPortObject) { - return; - } - const allSessions = new Set(); - for (const http2Server of boundPortObject.listeningServers) { - const serverEntry = this.http2Servers.get(http2Server); - if (serverEntry) { - for (const session of serverEntry.sessions) { - allSessions.add(session); - this.closeSession(session, () => { - allSessions.delete(session); - }); - } - } - } - /* After the grace time ends, send another goaway to all remaining sessions - * with the CANCEL code. */ - (_c = (_b = setTimeout(() => { - for (const session of allSessions) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - forceShutdown() { - for (const boundPortObject of this.boundPorts.values()) { - boundPortObject.cancelled = true; - } - this.boundPorts.clear(); - // Close the server if it is still running. - for (const server of this.http2Servers.keys()) { - this.closeServer(server); - } - // Always destroy any available sessions. It's possible that one or more - // tryShutdown() calls are in progress. Don't wait on them to finish. - this.sessions.forEach((channelzInfo, session) => { - this.closeSession(session); - // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to - // recognize destroy(code) as a valid signature. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - session.destroy(http2.constants.NGHTTP2_CANCEL); - }); - this.sessions.clear(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.shutdown = true; - } - register(name, handler, serialize, deserialize, type) { - if (this.handlers.has(name)) { - return false; - } - this.handlers.set(name, { - func: handler, - serialize, - deserialize, - type, - path: name, - }); - return true; - } - unregister(name) { - return this.handlers.delete(name); - } - /** - * @deprecated No longer needed as of version 1.10.x - */ - start() { - if (this.http2Servers.size === 0 || - [...this.http2Servers.keys()].every(server => !server.listening)) { - throw new Error('server must be bound in order to start'); - } - if (this.started === true) { - throw new Error('server is already started'); - } - this.started = true; - } - tryShutdown(callback) { - var _b; - const wrappedCallback = (error) => { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - callback(error); - }; - let pendingChecks = 0; - function maybeCallback() { - pendingChecks--; - if (pendingChecks === 0) { - wrappedCallback(); - } - } - this.shutdown = true; - for (const [serverKey, server] of this.http2Servers.entries()) { - pendingChecks++; - const serverString = server.channelzRef.name; - this.trace('Waiting for server ' + serverString + ' to close'); - this.closeServer(serverKey, () => { - this.trace('Server ' + serverString + ' finished closing'); - maybeCallback(); - }); - for (const session of server.sessions.keys()) { - pendingChecks++; - const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress; - this.trace('Waiting for session ' + sessionString + ' to close'); - this.closeSession(session, () => { - this.trace('Session ' + sessionString + ' finished closing'); - maybeCallback(); - }); - } - } - if (pendingChecks === 0) { - wrappedCallback(); - } - } - addHttp2Port() { - throw new Error('Not yet implemented'); - } - /** - * Get the channelz reference object for this server. The returned value is - * garbage if channelz is disabled for this server. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - _verifyContentType(stream, headers) { - const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; - if (typeof contentType !== 'string' || - !contentType.startsWith('application/grpc')) { - stream.respond({ - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, - }, { endStream: true }); - return false; - } - return true; - } - _retrieveHandler(path) { - serverCallTrace('Received call to method ' + - path + - ' at address ' + - this.serverAddressString); - const handler = this.handlers.get(path); - if (handler === undefined) { - serverCallTrace('No handler registered for method ' + - path + - '. Sending UNIMPLEMENTED status.'); - return null; - } - return handler; - } - _respondWithError(err, stream, channelzSessionInfo = null) { - var _b, _c; - const trailersToSend = Object.assign({ 'grpc-status': (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, 'grpc-message': err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto' }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers()); - stream.respond(trailersToSend, { endStream: true }); - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - } - _channelzHandler(extraInterceptors, stream, headers) { - // for handling idle timeout - this.onStreamOpened(stream); - const channelzSessionInfo = this.sessions.get(stream.session); - this.callTracker.addCallStarted(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); - if (!this._verifyContentType(stream, headers)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler = this._retrieveHandler(path); - if (!handler) { - this._respondWithError(getUnimplementedStatusResponse(path), stream, channelzSessionInfo); - return; - } - const callEventTracker = { - addMessageSent: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesSent += 1; - channelzSessionInfo.lastMessageSentTimestamp = new Date(); - } - }, - addMessageReceived: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesReceived += 1; - channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); - } - }, - onCallEnd: status => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } - else { - this.callTracker.addCallFailed(); - } - }, - onStreamEnd: success => { - if (channelzSessionInfo) { - if (success) { - channelzSessionInfo.streamTracker.addCallSucceeded(); - } - else { - channelzSessionInfo.streamTracker.addCallFailed(); - } - } - }, - }; - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, callEventTracker, handler, this.options); - if (!this._runHandlerForCall(call, handler)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler.type}`, - }); - } - } - _streamHandler(extraInterceptors, stream, headers) { - // for handling idle timeout - this.onStreamOpened(stream); - if (this._verifyContentType(stream, headers) !== true) { - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler = this._retrieveHandler(path); - if (!handler) { - this._respondWithError(getUnimplementedStatusResponse(path), stream, null); - return; - } - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, null, handler, this.options); - if (!this._runHandlerForCall(call, handler)) { - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler.type}`, - }); - } - } - _runHandlerForCall(call, handler) { - const { type } = handler; - if (type === 'unary') { - handleUnary(call, handler); - } - else if (type === 'clientStream') { - handleClientStreaming(call, handler); - } - else if (type === 'serverStream') { - handleServerStreaming(call, handler); - } - else if (type === 'bidi') { - handleBidiStreaming(call, handler); - } - else { - return false; - } - return true; - } - _setupHandlers(http2Server, extraInterceptors) { - if (http2Server === null) { - return; - } - const serverAddress = http2Server.address(); - let serverAddressString = 'null'; - if (serverAddress) { - if (typeof serverAddress === 'string') { - serverAddressString = serverAddress; - } - else { - serverAddressString = serverAddress.address + ':' + serverAddress.port; - } - } - this.serverAddressString = serverAddressString; - const handler = this.channelzEnabled - ? this._channelzHandler - : this._streamHandler; - const sessionHandler = this.channelzEnabled - ? this._channelzSessionHandler(http2Server) - : this._sessionHandler(http2Server); - http2Server.on('stream', handler.bind(this, extraInterceptors)); - http2Server.on('session', sessionHandler); - } - _sessionHandler(http2Server) { - return (session) => { - var _b, _c; - (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimer = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - // Apply a random jitter within a +/-10% range - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b, _c; - sessionClosedByServer = true; - this.trace('Connection dropped by max connection age: ' + - ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } - catch (e) { - // The goaway can't be sent because the session is already closed - session.destroy(); - return; - } - session.close(); - /* Allow a grace period after sending the GOAWAY before forcibly - * closing the connection. */ - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_c = connectionAgeGraceTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimer) { - clearTimeout(keepaliveTimer); - keepaliveTimer = null; - } - }; - const canSendPing = () => { - return (!session.destroyed && - this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && - this.keepaliveTimeMs > 0); - }; - /* eslint-disable-next-line prefer-const */ - let sendPing; // hoisted for use in maybeStartKeepalivePingTimer - const maybeStartKeepalivePingTimer = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); - }; - sendPing = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - let pingSendError = ''; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error: ' + err.message); - sessionClosedByServer = true; - session.close(); - } - else { - this.keepaliveTrace('Received ping response'); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = - (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.trace('Connection dropped due to ping send error: ' + pingSendError); - sessionClosedByServer = true; - session.close(); - return; - } - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace('Ping timeout passed without response'); - this.trace('Connection dropped by keepalive timeout'); - sessionClosedByServer = true; - session.close(); - }, this.keepaliveTimeoutMs); - (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); - }; - maybeStartKeepalivePingTimer(); - session.on('close', () => { - var _b, _c; - if (!sessionClosedByServer) { - this.trace(`Connection dropped by client ${(_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress}`); - } - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_c = this.http2Servers.get(http2Server)) === null || _c === void 0 ? void 0 : _c.sessions.delete(session); - }); - }; - } - _channelzSessionHandler(http2Server) { - return (session) => { - var _b, _c, _d, _e; - const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : 'unknown', this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); - const channelzSessionInfo = { - ref: channelzRef, - streamTracker: new channelz_1.ChannelzCallTracker(), - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - }; - (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session); - this.sessions.set(session, channelzSessionInfo); - const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; - this.channelzTrace.addTrace('CT_INFO', 'Connection established by client ' + clientAddress); - this.trace('Connection established by client ' + clientAddress); - this.sessionChildrenTracker.refChild(channelzRef); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimeout = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - // Apply a random jitter within a +/-10% range - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b; - sessionClosedByServer = true; - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by max connection age from ' + clientAddress); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } - catch (e) { - // The goaway can't be sent because the session is already closed - session.destroy(); - return; - } - session.close(); - /* Allow a grace period after sending the GOAWAY before forcibly - * closing the connection. */ - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_b = connectionAgeGraceTimer.unref) === null || _b === void 0 ? void 0 : _b.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimeout) { - clearTimeout(keepaliveTimeout); - keepaliveTimeout = null; - } - }; - const canSendPing = () => { - return (!session.destroyed && - this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && - this.keepaliveTimeMs > 0); - }; - /* eslint-disable-next-line prefer-const */ - let sendPing; // hoisted for use in maybeStartKeepalivePingTimer - const maybeStartKeepalivePingTimer = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); - }; - sendPing = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - let pingSendError = ''; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error: ' + err.message); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to error of a ping frame ' + - err.message + - ' return in ' + - duration); - sessionClosedByServer = true; - session.close(); - } - else { - this.keepaliveTrace('Received ping response'); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = - (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to ping send error: ' + pingSendError); - sessionClosedByServer = true; - session.close(); - return; - } - channelzSessionInfo.keepAlivesSent += 1; - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace('Ping timeout passed without response'); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by keepalive timeout from ' + clientAddress); - sessionClosedByServer = true; - session.close(); - }, this.keepaliveTimeoutMs); - (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); - }; - maybeStartKeepalivePingTimer(); - session.on('close', () => { - var _b; - if (!sessionClosedByServer) { - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by client ' + clientAddress); - } - this.sessionChildrenTracker.unrefChild(channelzRef); - (0, channelz_1.unregisterChannelzRef)(channelzRef); - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.delete(session); - this.sessions.delete(session); - }); - }; - } - enableIdleTimeout(session) { - var _b, _c; - if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { - return null; - } - const idleTimeoutObj = { - activeStreams: 0, - lastIdle: Date.now(), - onClose: this.onStreamClose.bind(this, session), - timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session), - }; - (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - this.sessionIdleTimeouts.set(session, idleTimeoutObj); - const { socket } = session; - this.trace('Enable idle timeout for ' + - socket.remoteAddress + - ':' + - socket.remotePort); - return idleTimeoutObj; - } - onIdleTimeout(ctx, session) { - const { socket } = session; - const sessionInfo = ctx.sessionIdleTimeouts.get(session); - // if it is called while we have activeStreams - timer will not be rescheduled - // until last active stream is closed, then it will call .refresh() on the timer - // important part is to not clearTimeout(timer) or it becomes unusable - // for future refreshes - if (sessionInfo !== undefined && - sessionInfo.activeStreams === 0) { - if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { - ctx.trace('Session idle timeout triggered for ' + - (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + - ':' + - (socket === null || socket === void 0 ? void 0 : socket.remotePort) + - ' last idle at ' + - sessionInfo.lastIdle); - ctx.closeSession(session); - } - else { - sessionInfo.timeout.refresh(); - } - } - } - onStreamOpened(stream) { - const session = stream.session; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams += 1; - stream.once('close', idleTimeoutObj.onClose); - } - } - onStreamClose(session) { - var _b, _c; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams -= 1; - if (idleTimeoutObj.activeStreams === 0) { - idleTimeoutObj.lastIdle = Date.now(); - idleTimeoutObj.timeout.refresh(); - this.trace('Session onStreamClose' + - ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + - ':' + - ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + - ' at ' + - idleTimeoutObj.lastIdle); - } - } - } - }, - (() => { - const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; - _start_decorators = [deprecate('Calling start() is no longer necessary. It can be safely omitted.')]; - __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: obj => "start" in obj, get: obj => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); - if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); - })(), - _a; -})(); -exports.Server = Server; -async function handleUnary(call, handler) { - let stream; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: 'OK', - metadata: trailer !== null && trailer !== void 0 ? trailer : null, - }); - }); - } - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); - try { - handler.func(stream, respond); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - } - }, - }); -} -function handleClientStreaming(call, handler) { - let stream; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: 'OK', - metadata: trailer !== null && trailer !== void 0 ? trailer : null, - }); - }); - } - call.start({ - onReceiveMetadata(metadata) { - stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); - try { - handler.func(stream, respond); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveHalfClose() { - stream.push(null); - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -function handleServerStreaming(call, handler) { - let stream; - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); - try { - handler.func(stream); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -function handleBidiStreaming(call, handler) { - let stream; - call.start({ - onReceiveMetadata(metadata) { - stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); - try { - handler.func(stream); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveHalfClose() { - stream.push(null); - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -//# sourceMappingURL=server.js.map - -/***/ }), - -/***/ 21761: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateRetryThrottling = validateRetryThrottling; -exports.validateServiceConfig = validateServiceConfig; -exports.extractAndSelectServiceConfig = extractAndSelectServiceConfig; -/* This file implements gRFC A2 and the service config spec: - * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md - * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each - * function here takes an object with unknown structure and returns its - * specific object type if the input has the right structure, and throws an - * error otherwise. */ -/* The any type is purposely used here. All functions validate their input at - * runtime */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -const os = __nccwpck_require__(22037); -const constants_1 = __nccwpck_require__(90634); -/** - * Recognizes a number with up to 9 digits after the decimal point, followed by - * an "s", representing a number of seconds. - */ -const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; -/** - * Client language name used for determining whether this client matches a - * `ServiceConfigCanaryConfig`'s `clientLanguage` list. - */ -const CLIENT_LANGUAGE_STRING = 'node'; -function validateName(obj) { - // In this context, and unset field and '' are considered the same - if ('service' in obj && obj.service !== '') { - if (typeof obj.service !== 'string') { - throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); - } - if ('method' in obj && obj.method !== '') { - if (typeof obj.method !== 'string') { - throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); - } - return { - service: obj.service, - method: obj.method, - }; - } - else { - return { - service: obj.service, - }; - } - } - else { - if ('method' in obj && obj.method !== undefined) { - throw new Error(`Invalid method config name: method set with empty or unset service`); - } - return {}; - } -} -function validateRetryPolicy(obj) { - if (!('maxAttempts' in obj) || - !Number.isInteger(obj.maxAttempts) || - obj.maxAttempts < 2) { - throw new Error('Invalid method config retry policy: maxAttempts must be an integer at least 2'); - } - if (!('initialBackoff' in obj) || - typeof obj.initialBackoff !== 'string' || - !DURATION_REGEX.test(obj.initialBackoff)) { - throw new Error('Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s'); - } - if (!('maxBackoff' in obj) || - typeof obj.maxBackoff !== 'string' || - !DURATION_REGEX.test(obj.maxBackoff)) { - throw new Error('Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s'); - } - if (!('backoffMultiplier' in obj) || - typeof obj.backoffMultiplier !== 'number' || - obj.backoffMultiplier <= 0) { - throw new Error('Invalid method config retry policy: backoffMultiplier must be a number greater than 0'); - } - if (!('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes))) { - throw new Error('Invalid method config retry policy: retryableStatusCodes is required'); - } - if (obj.retryableStatusCodes.length === 0) { - throw new Error('Invalid method config retry policy: retryableStatusCodes must be non-empty'); - } - for (const value of obj.retryableStatusCodes) { - if (typeof value === 'number') { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error('Invalid method config retry policy: retryableStatusCodes value not in status code range'); - } - } - else if (typeof value === 'string') { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error('Invalid method config retry policy: retryableStatusCodes value not a status code name'); - } - } - else { - throw new Error('Invalid method config retry policy: retryableStatusCodes value must be a string or number'); - } - } - return { - maxAttempts: obj.maxAttempts, - initialBackoff: obj.initialBackoff, - maxBackoff: obj.maxBackoff, - backoffMultiplier: obj.backoffMultiplier, - retryableStatusCodes: obj.retryableStatusCodes, - }; -} -function validateHedgingPolicy(obj) { - if (!('maxAttempts' in obj) || - !Number.isInteger(obj.maxAttempts) || - obj.maxAttempts < 2) { - throw new Error('Invalid method config hedging policy: maxAttempts must be an integer at least 2'); - } - if ('hedgingDelay' in obj && - (typeof obj.hedgingDelay !== 'string' || - !DURATION_REGEX.test(obj.hedgingDelay))) { - throw new Error('Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s'); - } - if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) { - for (const value of obj.nonFatalStatusCodes) { - if (typeof value === 'number') { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not in status code range'); - } - } - else if (typeof value === 'string') { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not a status code name'); - } - } - else { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number'); - } - } - } - const result = { - maxAttempts: obj.maxAttempts, - }; - if (obj.hedgingDelay) { - result.hedgingDelay = obj.hedgingDelay; - } - if (obj.nonFatalStatusCodes) { - result.nonFatalStatusCodes = obj.nonFatalStatusCodes; - } - return result; -} -function validateMethodConfig(obj) { - var _a; - const result = { - name: [], - }; - if (!('name' in obj) || !Array.isArray(obj.name)) { - throw new Error('Invalid method config: invalid name array'); - } - for (const name of obj.name) { - result.name.push(validateName(name)); - } - if ('waitForReady' in obj) { - if (typeof obj.waitForReady !== 'boolean') { - throw new Error('Invalid method config: invalid waitForReady'); - } - result.waitForReady = obj.waitForReady; - } - if ('timeout' in obj) { - if (typeof obj.timeout === 'object') { - if (!('seconds' in obj.timeout) || - !(typeof obj.timeout.seconds === 'number')) { - throw new Error('Invalid method config: invalid timeout.seconds'); - } - if (!('nanos' in obj.timeout) || - !(typeof obj.timeout.nanos === 'number')) { - throw new Error('Invalid method config: invalid timeout.nanos'); - } - result.timeout = obj.timeout; - } - else if (typeof obj.timeout === 'string' && - DURATION_REGEX.test(obj.timeout)) { - const timeoutParts = obj.timeout - .substring(0, obj.timeout.length - 1) - .split('.'); - result.timeout = { - seconds: timeoutParts[0] | 0, - nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0, - }; - } - else { - throw new Error('Invalid method config: invalid timeout'); - } - } - if ('maxRequestBytes' in obj) { - if (typeof obj.maxRequestBytes !== 'number') { - throw new Error('Invalid method config: invalid maxRequestBytes'); - } - result.maxRequestBytes = obj.maxRequestBytes; - } - if ('maxResponseBytes' in obj) { - if (typeof obj.maxResponseBytes !== 'number') { - throw new Error('Invalid method config: invalid maxRequestBytes'); - } - result.maxResponseBytes = obj.maxResponseBytes; - } - if ('retryPolicy' in obj) { - if ('hedgingPolicy' in obj) { - throw new Error('Invalid method config: retryPolicy and hedgingPolicy cannot both be specified'); - } - else { - result.retryPolicy = validateRetryPolicy(obj.retryPolicy); - } - } - else if ('hedgingPolicy' in obj) { - result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); - } - return result; -} -function validateRetryThrottling(obj) { - if (!('maxTokens' in obj) || - typeof obj.maxTokens !== 'number' || - obj.maxTokens <= 0 || - obj.maxTokens > 1000) { - throw new Error('Invalid retryThrottling: maxTokens must be a number in (0, 1000]'); - } - if (!('tokenRatio' in obj) || - typeof obj.tokenRatio !== 'number' || - obj.tokenRatio <= 0) { - throw new Error('Invalid retryThrottling: tokenRatio must be a number greater than 0'); - } - return { - maxTokens: +obj.maxTokens.toFixed(3), - tokenRatio: +obj.tokenRatio.toFixed(3), - }; -} -function validateLoadBalancingConfig(obj) { - if (!(typeof obj === 'object' && obj !== null)) { - throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); - } - const keys = Object.keys(obj); - if (keys.length > 1) { - throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); - } - if (keys.length === 0) { - throw new Error('Invalid loadBalancingConfig: load balancing policy name required'); - } - return { - [keys[0]]: obj[keys[0]], - }; -} -function validateServiceConfig(obj) { - const result = { - loadBalancingConfig: [], - methodConfig: [], - }; - if ('loadBalancingPolicy' in obj) { - if (typeof obj.loadBalancingPolicy === 'string') { - result.loadBalancingPolicy = obj.loadBalancingPolicy; - } - else { - throw new Error('Invalid service config: invalid loadBalancingPolicy'); - } - } - if ('loadBalancingConfig' in obj) { - if (Array.isArray(obj.loadBalancingConfig)) { - for (const config of obj.loadBalancingConfig) { - result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); - } - } - else { - throw new Error('Invalid service config: invalid loadBalancingConfig'); - } - } - if ('methodConfig' in obj) { - if (Array.isArray(obj.methodConfig)) { - for (const methodConfig of obj.methodConfig) { - result.methodConfig.push(validateMethodConfig(methodConfig)); - } - } - } - if ('retryThrottling' in obj) { - result.retryThrottling = validateRetryThrottling(obj.retryThrottling); - } - // Validate method name uniqueness - const seenMethodNames = []; - for (const methodConfig of result.methodConfig) { - for (const name of methodConfig.name) { - for (const seenName of seenMethodNames) { - if (name.service === seenName.service && - name.method === seenName.method) { - throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); - } - } - seenMethodNames.push(name); - } - } - return result; -} -function validateCanaryConfig(obj) { - if (!('serviceConfig' in obj)) { - throw new Error('Invalid service config choice: missing service config'); - } - const result = { - serviceConfig: validateServiceConfig(obj.serviceConfig), - }; - if ('clientLanguage' in obj) { - if (Array.isArray(obj.clientLanguage)) { - result.clientLanguage = []; - for (const lang of obj.clientLanguage) { - if (typeof lang === 'string') { - result.clientLanguage.push(lang); - } - else { - throw new Error('Invalid service config choice: invalid clientLanguage'); - } - } - } - else { - throw new Error('Invalid service config choice: invalid clientLanguage'); - } - } - if ('clientHostname' in obj) { - if (Array.isArray(obj.clientHostname)) { - result.clientHostname = []; - for (const lang of obj.clientHostname) { - if (typeof lang === 'string') { - result.clientHostname.push(lang); - } - else { - throw new Error('Invalid service config choice: invalid clientHostname'); - } - } - } - else { - throw new Error('Invalid service config choice: invalid clientHostname'); - } - } - if ('percentage' in obj) { - if (typeof obj.percentage === 'number' && - 0 <= obj.percentage && - obj.percentage <= 100) { - result.percentage = obj.percentage; - } - else { - throw new Error('Invalid service config choice: invalid percentage'); - } - } - // Validate that no unexpected fields are present - const allowedFields = [ - 'clientLanguage', - 'percentage', - 'clientHostname', - 'serviceConfig', - ]; - for (const field in obj) { - if (!allowedFields.includes(field)) { - throw new Error(`Invalid service config choice: unexpected field ${field}`); - } - } - return result; -} -function validateAndSelectCanaryConfig(obj, percentage) { - if (!Array.isArray(obj)) { - throw new Error('Invalid service config list'); - } - for (const config of obj) { - const validatedConfig = validateCanaryConfig(config); - /* For each field, we check if it is present, then only discard the - * config if the field value does not match the current client */ - if (typeof validatedConfig.percentage === 'number' && - percentage > validatedConfig.percentage) { - continue; - } - if (Array.isArray(validatedConfig.clientHostname)) { - let hostnameMatched = false; - for (const hostname of validatedConfig.clientHostname) { - if (hostname === os.hostname()) { - hostnameMatched = true; - } - } - if (!hostnameMatched) { - continue; - } - } - if (Array.isArray(validatedConfig.clientLanguage)) { - let languageMatched = false; - for (const language of validatedConfig.clientLanguage) { - if (language === CLIENT_LANGUAGE_STRING) { - languageMatched = true; - } - } - if (!languageMatched) { - continue; - } - } - return validatedConfig.serviceConfig; - } - throw new Error('No matching service config found'); -} -/** - * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, - * and select a service config with selection fields that all match this client. Most of these steps - * can fail with an error; the caller must handle any errors thrown this way. - * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt - * @param percentage A number chosen from the range [0, 100) that is used to select which config to use - * @return The service configuration to use, given the percentage value, or null if the service config - * data has a valid format but none of the options match the current client. - */ -function extractAndSelectServiceConfig(txtRecord, percentage) { - for (const record of txtRecord) { - if (record.length > 0 && record[0].startsWith('grpc_config=')) { - /* Treat the list of strings in this record as a single string and remove - * "grpc_config=" from the beginning. The rest should be a JSON string */ - const recordString = record.join('').substring('grpc_config='.length); - const recordJson = JSON.parse(recordString); - return validateAndSelectCanaryConfig(recordJson, percentage); - } - } - return null; -} -//# sourceMappingURL=service-config.js.map - -/***/ }), - -/***/ 28812: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2025 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SingleSubchannelChannel = void 0; -const call_number_1 = __nccwpck_require__(70380); -const channelz_1 = __nccwpck_require__(79975); -const compression_filter_1 = __nccwpck_require__(47616); -const connectivity_state_1 = __nccwpck_require__(80878); -const constants_1 = __nccwpck_require__(90634); -const control_plane_status_1 = __nccwpck_require__(39129); -const deadline_1 = __nccwpck_require__(511); -const filter_stack_1 = __nccwpck_require__(66450); -const metadata_1 = __nccwpck_require__(83665); -const resolver_1 = __nccwpck_require__(31594); -const uri_parser_1 = __nccwpck_require__(65974); -class SubchannelCallWrapper { - constructor(subchannel, method, filterStackFactory, options, callNumber) { - var _a, _b; - this.subchannel = subchannel; - this.method = method; - this.options = options; - this.callNumber = callNumber; - this.childCall = null; - this.pendingMessage = null; - this.readPending = false; - this.halfClosePending = false; - this.pendingStatus = null; - this.readFilterPending = false; - this.writeFilterPending = false; - const splitPath = this.method.split('/'); - let serviceName = ''; - /* The standard path format is "/{serviceName}/{methodName}", so if we split - * by '/', the first item should be empty and the second should be the - * service name */ - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; - /* Currently, call credentials are only allowed on HTTPS connections, so we - * can assume that the scheme is "https" */ - this.serviceUrl = `https://${hostname}/${serviceName}`; - const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); - if (timeout !== Infinity) { - if (timeout <= 0) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - } - else { - setTimeout(() => { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - }, timeout); - } - } - this.filterStack = filterStackFactory.createFilter(); - } - cancelWithStatus(status, details) { - if (this.childCall) { - this.childCall.cancelWithStatus(status, details); - } - else { - this.pendingStatus = { - code: status, - details: details, - metadata: new metadata_1.Metadata() - }; - } - } - getPeer() { - var _a, _b; - return (_b = (_a = this.childCall) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.subchannel.getAddress(); - } - async start(metadata, listener) { - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - return; - } - if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - listener.onReceiveStatus({ - code: constants_1.Status.UNAVAILABLE, - details: 'Subchannel not ready', - metadata: new metadata_1.Metadata() - }); - return; - } - const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); - let credsMetadata; - try { - credsMetadata = await this.subchannel.getCallCredentials() - .generateMetadata({ method_name: this.method, service_url: this.serviceUrl }); - } - catch (e) { - const error = e; - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); - listener.onReceiveStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }); - return; - } - credsMetadata.merge(filteredMetadata); - const childListener = { - onReceiveMetadata: async (metadata) => { - listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata)); - }, - onReceiveMessage: async (message) => { - this.readFilterPending = true; - const filteredMessage = await this.filterStack.receiveMessage(message); - this.readFilterPending = false; - listener.onReceiveMessage(filteredMessage); - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - } - }, - onReceiveStatus: async (status) => { - const filteredStatus = await this.filterStack.receiveTrailers(status); - if (this.readFilterPending) { - this.pendingStatus = filteredStatus; - } - else { - listener.onReceiveStatus(filteredStatus); - } - } - }; - this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); - if (this.readPending) { - this.childCall.startRead(); - } - if (this.pendingMessage) { - this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.halfClosePending && !this.writeFilterPending) { - this.childCall.halfClose(); - } - } - async sendMessageWithContext(context, message) { - this.writeFilterPending = true; - const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })); - this.writeFilterPending = false; - if (this.childCall) { - this.childCall.sendMessageWithContext(context, filteredMessage.message); - if (this.halfClosePending) { - this.childCall.halfClose(); - } - } - else { - this.pendingMessage = { context, message: filteredMessage.message }; - } - } - startRead() { - if (this.childCall) { - this.childCall.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - if (this.childCall && !this.writeFilterPending) { - this.childCall.halfClose(); - } - else { - this.halfClosePending = true; - } - } - getCallNumber() { - return this.callNumber; - } - setCredentials(credentials) { - throw new Error("Method not implemented."); - } - getAuthContext() { - if (this.childCall) { - return this.childCall.getAuthContext(); - } - else { - return null; - } - } -} -class SingleSubchannelChannel { - constructor(subchannel, target, options) { - this.subchannel = subchannel; - this.target = target; - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.channelzEnabled = options['grpc.enable_channelz'] !== 0; - this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({ - target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`, - state: this.subchannel.getConnectivityState(), - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }), this.channelzEnabled); - if (this.channelzEnabled) { - this.childrenTracker.refChild(subchannel.getChannelzRef()); - } - this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]); - } - close() { - if (this.channelzEnabled) { - this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); - } - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - throw new Error("Method not implemented."); - } - watchConnectivityState(currentState, deadline, callback) { - throw new Error("Method not implemented."); - } - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline) { - const callOptions = { - deadline: deadline, - host: (0, resolver_1.getDefaultAuthority)(this.target), - flags: constants_1.Propagate.DEFAULTS, - parentCall: null - }; - return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)()); - } -} -exports.SingleSubchannelChannel = SingleSubchannelChannel; -//# sourceMappingURL=single-subchannel-channel.js.map - -/***/ }), - -/***/ 73155: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StatusBuilder = void 0; -/** - * A builder for gRPC status objects. - */ -class StatusBuilder { - constructor() { - this.code = null; - this.details = null; - this.metadata = null; - } - /** - * Adds a status code to the builder. - */ - withCode(code) { - this.code = code; - return this; - } - /** - * Adds details to the builder. - */ - withDetails(details) { - this.details = details; - return this; - } - /** - * Adds metadata to the builder. - */ - withMetadata(metadata) { - this.metadata = metadata; - return this; - } - /** - * Builds the status object. - */ - build() { - const status = {}; - if (this.code !== null) { - status.code = this.code; - } - if (this.details !== null) { - status.details = this.details; - } - if (this.metadata !== null) { - status.metadata = this.metadata; - } - return status; - } -} -exports.StatusBuilder = StatusBuilder; -//# sourceMappingURL=status-builder.js.map - -/***/ }), - -/***/ 16575: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StreamDecoder = void 0; -var ReadState; -(function (ReadState) { - ReadState[ReadState["NO_DATA"] = 0] = "NO_DATA"; - ReadState[ReadState["READING_SIZE"] = 1] = "READING_SIZE"; - ReadState[ReadState["READING_MESSAGE"] = 2] = "READING_MESSAGE"; -})(ReadState || (ReadState = {})); -class StreamDecoder { - constructor(maxReadMessageLength) { - this.maxReadMessageLength = maxReadMessageLength; - this.readState = ReadState.NO_DATA; - this.readCompressFlag = Buffer.alloc(1); - this.readPartialSize = Buffer.alloc(4); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readPartialMessage = []; - this.readMessageRemaining = 0; - } - write(data) { - let readHead = 0; - let toRead; - const result = []; - while (readHead < data.length) { - switch (this.readState) { - case ReadState.NO_DATA: - this.readCompressFlag = data.slice(readHead, readHead + 1); - readHead += 1; - this.readState = ReadState.READING_SIZE; - this.readPartialSize.fill(0); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readMessageRemaining = 0; - this.readPartialMessage = []; - break; - case ReadState.READING_SIZE: - toRead = Math.min(data.length - readHead, this.readSizeRemaining); - data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); - this.readSizeRemaining -= toRead; - readHead += toRead; - // readSizeRemaining >=0 here - if (this.readSizeRemaining === 0) { - this.readMessageSize = this.readPartialSize.readUInt32BE(0); - if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { - throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); - } - this.readMessageRemaining = this.readMessageSize; - if (this.readMessageRemaining > 0) { - this.readState = ReadState.READING_MESSAGE; - } - else { - const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); - this.readState = ReadState.NO_DATA; - result.push(message); - } - } - break; - case ReadState.READING_MESSAGE: - toRead = Math.min(data.length - readHead, this.readMessageRemaining); - this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); - this.readMessageRemaining -= toRead; - readHead += toRead; - // readMessageRemaining >=0 here - if (this.readMessageRemaining === 0) { - // At this point, we have read a full message - const framedMessageBuffers = [ - this.readCompressFlag, - this.readPartialSize, - ].concat(this.readPartialMessage); - const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); - this.readState = ReadState.NO_DATA; - result.push(framedMessage); - } - break; - default: - throw new Error('Unexpected read state'); - } - } - return result; - } -} -exports.StreamDecoder = StreamDecoder; -//# sourceMappingURL=stream-decoder.js.map - -/***/ }), - -/***/ 99905: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2021 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.EndpointMap = void 0; -exports.isTcpSubchannelAddress = isTcpSubchannelAddress; -exports.subchannelAddressEqual = subchannelAddressEqual; -exports.subchannelAddressToString = subchannelAddressToString; -exports.stringToSubchannelAddress = stringToSubchannelAddress; -exports.endpointEqual = endpointEqual; -exports.endpointToString = endpointToString; -exports.endpointHasAddress = endpointHasAddress; -const net_1 = __nccwpck_require__(41808); -function isTcpSubchannelAddress(address) { - return 'port' in address; -} -function subchannelAddressEqual(address1, address2) { - if (!address1 && !address2) { - return true; - } - if (!address1 || !address2) { - return false; - } - if (isTcpSubchannelAddress(address1)) { - return (isTcpSubchannelAddress(address2) && - address1.host === address2.host && - address1.port === address2.port); - } - else { - return !isTcpSubchannelAddress(address2) && address1.path === address2.path; - } -} -function subchannelAddressToString(address) { - if (isTcpSubchannelAddress(address)) { - if ((0, net_1.isIPv6)(address.host)) { - return '[' + address.host + ']:' + address.port; - } - else { - return address.host + ':' + address.port; - } - } - else { - return address.path; - } -} -const DEFAULT_PORT = 443; -function stringToSubchannelAddress(addressString, port) { - if ((0, net_1.isIP)(addressString)) { - return { - host: addressString, - port: port !== null && port !== void 0 ? port : DEFAULT_PORT, - }; - } - else { - return { - path: addressString, - }; - } -} -function endpointEqual(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (let i = 0; i < endpoint1.addresses.length; i++) { - if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { - return false; - } - } - return true; -} -function endpointToString(endpoint) { - return ('[' + endpoint.addresses.map(subchannelAddressToString).join(', ') + ']'); -} -function endpointHasAddress(endpoint, expectedAddress) { - for (const address of endpoint.addresses) { - if (subchannelAddressEqual(address, expectedAddress)) { - return true; - } - } - return false; -} -function endpointEqualUnordered(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (const address1 of endpoint1.addresses) { - let matchFound = false; - for (const address2 of endpoint2.addresses) { - if (subchannelAddressEqual(address1, address2)) { - matchFound = true; - break; - } - } - if (!matchFound) { - return false; - } - } - return true; -} -class EndpointMap { - constructor() { - this.map = new Set(); - } - get size() { - return this.map.size; - } - getForSubchannelAddress(address) { - for (const entry of this.map) { - if (endpointHasAddress(entry.key, address)) { - return entry.value; - } - } - return undefined; - } - /** - * Delete any entries in this map with keys that are not in endpoints - * @param endpoints - */ - deleteMissing(endpoints) { - const removedValues = []; - for (const entry of this.map) { - let foundEntry = false; - for (const endpoint of endpoints) { - if (endpointEqualUnordered(endpoint, entry.key)) { - foundEntry = true; - } - } - if (!foundEntry) { - removedValues.push(entry.value); - this.map.delete(entry); - } - } - return removedValues; - } - get(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - return entry.value; - } - } - return undefined; - } - set(endpoint, mapEntry) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - entry.value = mapEntry; - return; - } - } - this.map.add({ key: endpoint, value: mapEntry }); - } - delete(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - this.map.delete(entry); - return; - } - } - } - has(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - return true; - } - } - return false; - } - clear() { - this.map.clear(); - } - *keys() { - for (const entry of this.map) { - yield entry.key; - } - } - *values() { - for (const entry of this.map) { - yield entry.value; - } - } - *entries() { - for (const entry of this.map) { - yield [entry.key, entry.value]; - } - } -} -exports.EndpointMap = EndpointMap; -//# sourceMappingURL=subchannel-address.js.map - -/***/ }), - -/***/ 86940: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Http2SubchannelCall = void 0; -const http2 = __nccwpck_require__(85158); -const os = __nccwpck_require__(22037); -const constants_1 = __nccwpck_require__(90634); -const metadata_1 = __nccwpck_require__(83665); -const stream_decoder_1 = __nccwpck_require__(16575); -const logging = __nccwpck_require__(35993); -const constants_2 = __nccwpck_require__(90634); -const TRACER_NAME = 'subchannel_call'; -/** - * Should do approximately the same thing as util.getSystemErrorName but the - * TypeScript types don't have that function for some reason so I just made my - * own. - * @param errno - */ -function getSystemErrorName(errno) { - for (const [name, num] of Object.entries(os.constants.errno)) { - if (num === errno) { - return name; - } - } - return 'Unknown system error ' + errno; -} -function mapHttpStatusCode(code) { - const details = `Received HTTP status code ${code}`; - let mappedStatusCode; - switch (code) { - // TODO(murgatroid99): handle 100 and 101 - case 400: - mappedStatusCode = constants_1.Status.INTERNAL; - break; - case 401: - mappedStatusCode = constants_1.Status.UNAUTHENTICATED; - break; - case 403: - mappedStatusCode = constants_1.Status.PERMISSION_DENIED; - break; - case 404: - mappedStatusCode = constants_1.Status.UNIMPLEMENTED; - break; - case 429: - case 502: - case 503: - case 504: - mappedStatusCode = constants_1.Status.UNAVAILABLE; - break; - default: - mappedStatusCode = constants_1.Status.UNKNOWN; - } - return { - code: mappedStatusCode, - details: details, - metadata: new metadata_1.Metadata() - }; -} -class Http2SubchannelCall { - constructor(http2Stream, callEventTracker, listener, transport, callId) { - var _a; - this.http2Stream = http2Stream; - this.callEventTracker = callEventTracker; - this.listener = listener; - this.transport = transport; - this.callId = callId; - this.isReadFilterPending = false; - this.isPushPending = false; - this.canPush = false; - /** - * Indicates that an 'end' event has come from the http2 stream, so there - * will be no more data events. - */ - this.readsClosed = false; - this.statusOutput = false; - this.unpushedReadMessages = []; - // This is populated (non-null) if and only if the call has ended - this.finalStatus = null; - this.internalError = null; - this.serverEndedCall = false; - this.connectionDropped = false; - const maxReceiveMessageLength = (_a = transport.getOptions()['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); - http2Stream.on('response', (headers, flags) => { - let headersString = ''; - for (const header of Object.keys(headers)) { - headersString += '\t\t' + header + ': ' + headers[header] + '\n'; - } - this.trace('Received server headers:\n' + headersString); - this.httpStatusCode = headers[':status']; - if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { - this.handleTrailers(headers); - } - else { - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } - catch (error) { - this.endCall({ - code: constants_1.Status.UNKNOWN, - details: error.message, - metadata: new metadata_1.Metadata(), - }); - return; - } - this.listener.onReceiveMetadata(metadata); - } - }); - http2Stream.on('trailers', (headers) => { - this.handleTrailers(headers); - }); - http2Stream.on('data', (data) => { - /* If the status has already been output, allow the http2 stream to - * drain without processing the data. */ - if (this.statusOutput) { - return; - } - this.trace('receive HTTP/2 data frame of length ' + data.length); - let messages; - try { - messages = this.decoder.write(data); - } - catch (e) { - /* Some servers send HTML error pages along with HTTP status codes. - * When the client attempts to parse this as a length-delimited - * message, the parsed message size is greater than the default limit, - * resulting in a message decoding error. In that situation, the HTTP - * error code information is more useful to the user than the - * RESOURCE_EXHAUSTED error is, so we report that instead. Normally, - * we delay processing the HTTP status until after the stream ends, to - * prioritize reporting the gRPC status from trailers if it is present, - * but when there is a message parsing error we end the stream early - * before processing trailers. */ - if (this.httpStatusCode !== undefined && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - this.cancelWithStatus(mappedStatus.code, mappedStatus.details); - } - else { - this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message); - } - return; - } - for (const message of messages) { - this.trace('parsed message of length ' + message.length); - this.callEventTracker.addMessageReceived(); - this.tryPush(message); - } - }); - http2Stream.on('end', () => { - this.readsClosed = true; - this.maybeOutputStatus(); - }); - http2Stream.on('close', () => { - this.serverEndedCall = true; - /* Use process.next tick to ensure that this code happens after any - * "error" event that may be emitted at about the same time, so that - * we can bubble up the error message from that event. */ - process.nextTick(() => { - var _a; - this.trace('HTTP/2 stream closed with code ' + http2Stream.rstCode); - /* If we have a final status with an OK status code, that means that - * we have received all of the messages and we have processed the - * trailers and the call completed successfully, so it doesn't matter - * how the stream ends after that */ - if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { - return; - } - let code; - let details = ''; - switch (http2Stream.rstCode) { - case http2.constants.NGHTTP2_NO_ERROR: - /* If we get a NO_ERROR code and we already have a status, the - * stream completed properly and we just haven't fully processed - * it yet */ - if (this.finalStatus !== null) { - return; - } - if (this.httpStatusCode && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - code = mappedStatus.code; - details = mappedStatus.details; - } - else { - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; - } - break; - case http2.constants.NGHTTP2_REFUSED_STREAM: - code = constants_1.Status.UNAVAILABLE; - details = 'Stream refused by server'; - break; - case http2.constants.NGHTTP2_CANCEL: - /* Bug reports indicate that Node synthesizes a NGHTTP2_CANCEL - * code from connection drops. We want to prioritize reporting - * an unavailable status when that happens. */ - if (this.connectionDropped) { - code = constants_1.Status.UNAVAILABLE; - details = 'Connection dropped'; - } - else { - code = constants_1.Status.CANCELLED; - details = 'Call cancelled'; - } - break; - case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: - code = constants_1.Status.RESOURCE_EXHAUSTED; - details = 'Bandwidth exhausted or memory limit exceeded'; - break; - case http2.constants.NGHTTP2_INADEQUATE_SECURITY: - code = constants_1.Status.PERMISSION_DENIED; - details = 'Protocol not secure enough'; - break; - case http2.constants.NGHTTP2_INTERNAL_ERROR: - code = constants_1.Status.INTERNAL; - if (this.internalError === null) { - /* This error code was previously handled in the default case, and - * there are several instances of it online, so I wanted to - * preserve the original error message so that people find existing - * information in searches, but also include the more recognizable - * "Internal server error" message. */ - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; - } - else { - if (this.internalError.code === 'ECONNRESET' || - this.internalError.code === 'ETIMEDOUT') { - code = constants_1.Status.UNAVAILABLE; - details = this.internalError.message; - } - else { - /* The "Received RST_STREAM with code ..." error is preserved - * here for continuity with errors reported online, but the - * error message at the end will probably be more relevant in - * most cases. */ - details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; - } - } - break; - default: - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode}`; - } - // This is a no-op if trailers were received at all. - // This is OK, because status codes emitted here correspond to more - // catastrophic issues that prevent us from receiving trailers in the - // first place. - this.endCall({ - code, - details, - metadata: new metadata_1.Metadata(), - rstCode: http2Stream.rstCode, - }); - }); - }); - http2Stream.on('error', (err) => { - /* We need an error handler here to stop "Uncaught Error" exceptions - * from bubbling up. However, errors here should all correspond to - * "close" events, where we will handle the error more granularly */ - /* Specifically looking for stream errors that were *not* constructed - * from a RST_STREAM response here: - * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267 - */ - if (err.code !== 'ERR_HTTP2_STREAM_ERROR') { - this.trace('Node error event: message=' + - err.message + - ' code=' + - err.code + - ' errno=' + - getSystemErrorName(err.errno) + - ' syscall=' + - err.syscall); - this.internalError = err; - } - this.callEventTracker.onStreamEnd(false); - }); - } - getDeadlineInfo() { - return [`remote_addr=${this.getPeer()}`]; - } - onDisconnect() { - this.connectionDropped = true; - /* Give the call an event loop cycle to finish naturally before reporting - * the disconnection as an error. */ - setImmediate(() => { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: 'Connection dropped', - metadata: new metadata_1.Metadata(), - }); - }); - } - outputStatus() { - /* Precondition: this.finalStatus !== null */ - if (!this.statusOutput) { - this.statusOutput = true; - this.trace('ended with status: code=' + - this.finalStatus.code + - ' details="' + - this.finalStatus.details + - '"'); - this.callEventTracker.onCallEnd(this.finalStatus); - /* We delay the actual action of bubbling up the status to insulate the - * cleanup code in this class from any errors that may be thrown in the - * upper layers as a result of bubbling up the status. In particular, - * if the status is not OK, the "error" event may be emitted - * synchronously at the top level, which will result in a thrown error if - * the user does not handle that event. */ - process.nextTick(() => { - this.listener.onReceiveStatus(this.finalStatus); - }); - /* Leave the http2 stream in flowing state to drain incoming messages, to - * ensure that the stream closure completes. The call stream already does - * not push more messages after the status is output, so the messages go - * nowhere either way. */ - this.http2Stream.resume(); - } - } - trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callId + '] ' + text); - } - /** - * On first call, emits a 'status' event with the given StatusObject. - * Subsequent calls are no-ops. - * @param status The status of the call. - */ - endCall(status) { - /* If the status is OK and a new status comes in (e.g. from a - * deserialization failure), that new status takes priority */ - if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { - this.finalStatus = status; - this.maybeOutputStatus(); - } - this.destroyHttp2Stream(); - } - maybeOutputStatus() { - if (this.finalStatus !== null) { - /* The combination check of readsClosed and that the two message buffer - * arrays are empty checks that there all incoming data has been fully - * processed */ - if (this.finalStatus.code !== constants_1.Status.OK || - (this.readsClosed && - this.unpushedReadMessages.length === 0 && - !this.isReadFilterPending && - !this.isPushPending)) { - this.outputStatus(); - } - } - } - push(message) { - this.trace('pushing to reader message of length ' + - (message instanceof Buffer ? message.length : null)); - this.canPush = false; - this.isPushPending = true; - process.nextTick(() => { - this.isPushPending = false; - /* If we have already output the status any later messages should be - * ignored, and can cause out-of-order operation errors higher up in the - * stack. Checking as late as possible here to avoid any race conditions. - */ - if (this.statusOutput) { - return; - } - this.listener.onReceiveMessage(message); - this.maybeOutputStatus(); - }); - } - tryPush(messageBytes) { - if (this.canPush) { - this.http2Stream.pause(); - this.push(messageBytes); - } - else { - this.trace('unpushedReadMessages.push message of length ' + messageBytes.length); - this.unpushedReadMessages.push(messageBytes); - } - } - handleTrailers(headers) { - this.serverEndedCall = true; - this.callEventTracker.onStreamEnd(true); - let headersString = ''; - for (const header of Object.keys(headers)) { - headersString += '\t\t' + header + ': ' + headers[header] + '\n'; - } - this.trace('Received server trailers:\n' + headersString); - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } - catch (e) { - metadata = new metadata_1.Metadata(); - } - const metadataMap = metadata.getMap(); - let status; - if (typeof metadataMap['grpc-status'] === 'string') { - const receivedStatus = Number(metadataMap['grpc-status']); - this.trace('received status code ' + receivedStatus + ' from server'); - metadata.remove('grpc-status'); - let details = ''; - if (typeof metadataMap['grpc-message'] === 'string') { - try { - details = decodeURI(metadataMap['grpc-message']); - } - catch (e) { - details = metadataMap['grpc-message']; - } - metadata.remove('grpc-message'); - this.trace('received status details string "' + details + '" from server'); - } - status = { - code: receivedStatus, - details: details, - metadata: metadata - }; - } - else if (this.httpStatusCode) { - status = mapHttpStatusCode(this.httpStatusCode); - status.metadata = metadata; - } - else { - status = { - code: constants_1.Status.UNKNOWN, - details: 'No status information received', - metadata: metadata - }; - } - // This is a no-op if the call was already ended when handling headers. - this.endCall(status); - } - destroyHttp2Stream() { - var _a; - // The http2 stream could already have been destroyed if cancelWithStatus - // is called in response to an internal http2 error. - if (this.http2Stream.destroyed) { - return; - } - /* If the server ended the call, sending an RST_STREAM is redundant, so we - * just half close on the client side instead to finish closing the stream. - */ - if (this.serverEndedCall) { - this.http2Stream.end(); - } - else { - /* If the call has ended with an OK status, communicate that when closing - * the stream, partly to avoid a situation in which we detect an error - * RST_STREAM as a result after we have the status */ - let code; - if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { - code = http2.constants.NGHTTP2_NO_ERROR; - } - else { - code = http2.constants.NGHTTP2_CANCEL; - } - this.trace('close http2 stream with code ' + code); - this.http2Stream.close(code); - } - } - cancelWithStatus(status, details) { - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); - } - getStatus() { - return this.finalStatus; - } - getPeer() { - return this.transport.getPeerName(); - } - getCallNumber() { - return this.callId; - } - getAuthContext() { - return this.transport.getAuthContext(); - } - startRead() { - /* If the stream has ended with an error, we should not emit any more - * messages and we should communicate that the stream has ended */ - if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { - this.readsClosed = true; - this.maybeOutputStatus(); - return; - } - this.canPush = true; - if (this.unpushedReadMessages.length > 0) { - const nextMessage = this.unpushedReadMessages.shift(); - this.push(nextMessage); - return; - } - /* Only resume reading from the http2Stream if we don't have any pending - * messages to emit */ - this.http2Stream.resume(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - const cb = (error) => { - /* nextTick here ensures that no stream action can be taken in the call - * stack of the write callback, in order to hopefully work around - * https://github.com/nodejs/node/issues/49147 */ - process.nextTick(() => { - var _a; - let code = constants_1.Status.UNAVAILABLE; - if ((error === null || error === void 0 ? void 0 : error.code) === - 'ERR_STREAM_WRITE_AFTER_END') { - code = constants_1.Status.INTERNAL; - } - if (error) { - this.cancelWithStatus(code, `Write error: ${error.message}`); - } - (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); - }); - }; - this.trace('sending data chunk of length ' + message.length); - this.callEventTracker.addMessageSent(); - try { - this.http2Stream.write(message, cb); - } - catch (error) { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: `Write failed with error ${error.message}`, - metadata: new metadata_1.Metadata(), - }); - } - } - halfClose() { - this.trace('end() called'); - this.trace('calling end() on HTTP/2 stream'); - this.http2Stream.end(); - } -} -exports.Http2SubchannelCall = Http2SubchannelCall; -//# sourceMappingURL=subchannel-call.js.map - -/***/ }), - -/***/ 12258: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2022 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseSubchannelWrapper = void 0; -class BaseSubchannelWrapper { - constructor(child) { - this.child = child; - this.healthy = true; - this.healthListeners = new Set(); - this.refcount = 0; - this.dataWatchers = new Set(); - child.addHealthStateWatcher(childHealthy => { - /* A change to the child health state only affects this wrapper's overall - * health state if this wrapper is reporting healthy. */ - if (this.healthy) { - this.updateHealthListeners(); - } - }); - } - updateHealthListeners() { - for (const listener of this.healthListeners) { - listener(this.isHealthy()); - } - } - getConnectivityState() { - return this.child.getConnectivityState(); - } - addConnectivityStateListener(listener) { - this.child.addConnectivityStateListener(listener); - } - removeConnectivityStateListener(listener) { - this.child.removeConnectivityStateListener(listener); - } - startConnecting() { - this.child.startConnecting(); - } - getAddress() { - return this.child.getAddress(); - } - throttleKeepalive(newKeepaliveTime) { - this.child.throttleKeepalive(newKeepaliveTime); - } - ref() { - this.child.ref(); - this.refcount += 1; - } - unref() { - this.child.unref(); - this.refcount -= 1; - if (this.refcount === 0) { - this.destroy(); - } - } - destroy() { - for (const watcher of this.dataWatchers) { - watcher.destroy(); - } - } - getChannelzRef() { - return this.child.getChannelzRef(); - } - isHealthy() { - return this.healthy && this.child.isHealthy(); - } - addHealthStateWatcher(listener) { - this.healthListeners.add(listener); - } - removeHealthStateWatcher(listener) { - this.healthListeners.delete(listener); - } - addDataWatcher(dataWatcher) { - dataWatcher.setSubchannel(this.getRealSubchannel()); - this.dataWatchers.add(dataWatcher); - } - setHealthy(healthy) { - if (healthy !== this.healthy) { - this.healthy = healthy; - /* A change to this wrapper's health state only affects the overall - * reported health state if the child is healthy. */ - if (this.child.isHealthy()) { - this.updateHealthListeners(); - } - } - } - getRealSubchannel() { - return this.child.getRealSubchannel(); - } - realSubchannelEquals(other) { - return this.getRealSubchannel() === other.getRealSubchannel(); - } - getCallCredentials() { - return this.child.getCallCredentials(); - } - getChannel() { - return this.child.getChannel(); - } -} -exports.BaseSubchannelWrapper = BaseSubchannelWrapper; -//# sourceMappingURL=subchannel-interface.js.map - -/***/ }), - -/***/ 87440: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SubchannelPool = void 0; -exports.getSubchannelPool = getSubchannelPool; -const channel_options_1 = __nccwpck_require__(99810); -const subchannel_1 = __nccwpck_require__(84764); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const transport_1 = __nccwpck_require__(46690); -// 10 seconds in milliseconds. This value is arbitrary. -/** - * The amount of time in between checks for dropping subchannels that have no - * other references - */ -const REF_CHECK_INTERVAL = 10000; -class SubchannelPool { - /** - * A pool of subchannels use for making connections. Subchannels with the - * exact same parameters will be reused. - */ - constructor() { - this.pool = Object.create(null); - /** - * A timer of a task performing a periodic subchannel cleanup. - */ - this.cleanupTimer = null; - } - /** - * Unrefs all unused subchannels and cancels the cleanup task if all - * subchannels have been unrefed. - */ - unrefUnusedSubchannels() { - let allSubchannelsUnrefed = true; - /* These objects are created with Object.create(null), so they do not - * have a prototype, which means that for (... in ...) loops over them - * do not need to be filtered */ - // eslint-disable-disable-next-line:forin - for (const channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - const refedSubchannels = subchannelObjArray.filter(value => !value.subchannel.unrefIfOneRef()); - if (refedSubchannels.length > 0) { - allSubchannelsUnrefed = false; - } - /* For each subchannel in the pool, try to unref it if it has - * exactly one ref (which is the ref from the pool itself). If that - * does happen, remove the subchannel from the pool */ - this.pool[channelTarget] = refedSubchannels; - } - /* Currently we do not delete keys with empty values. If that results - * in significant memory usage we should change it. */ - // Cancel the cleanup task if all subchannels have been unrefed. - if (allSubchannelsUnrefed && this.cleanupTimer !== null) { - clearInterval(this.cleanupTimer); - this.cleanupTimer = null; - } - } - /** - * Ensures that the cleanup task is spawned. - */ - ensureCleanupTask() { - var _a, _b; - if (this.cleanupTimer === null) { - this.cleanupTimer = setInterval(() => { - this.unrefUnusedSubchannels(); - }, REF_CHECK_INTERVAL); - // Unref because this timer should not keep the event loop running. - // Call unref only if it exists to address electron/electron#21162 - (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Get a subchannel if one already exists with exactly matching parameters. - * Otherwise, create and save a subchannel with those parameters. - * @param channelTarget - * @param subchannelTarget - * @param channelArguments - * @param channelCredentials - */ - getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { - this.ensureCleanupTask(); - const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); - if (channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - for (const subchannelObj of subchannelObjArray) { - if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && - (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && - channelCredentials._equals(subchannelObj.channelCredentials)) { - return subchannelObj.subchannel; - } - } - } - // If we get here, no matching subchannel was found - const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); - if (!(channelTarget in this.pool)) { - this.pool[channelTarget] = []; - } - this.pool[channelTarget].push({ - subchannelAddress: subchannelTarget, - channelArguments, - channelCredentials, - subchannel, - }); - subchannel.ref(); - return subchannel; - } -} -exports.SubchannelPool = SubchannelPool; -const globalSubchannelPool = new SubchannelPool(); -/** - * Get either the global subchannel pool, or a new subchannel pool. - * @param global - */ -function getSubchannelPool(global) { - if (global) { - return globalSubchannelPool; - } - else { - return new SubchannelPool(); - } -} -//# sourceMappingURL=subchannel-pool.js.map - -/***/ }), - -/***/ 84764: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Subchannel = void 0; -const connectivity_state_1 = __nccwpck_require__(80878); -const backoff_timeout_1 = __nccwpck_require__(34186); -const logging = __nccwpck_require__(35993); -const constants_1 = __nccwpck_require__(90634); -const uri_parser_1 = __nccwpck_require__(65974); -const subchannel_address_1 = __nccwpck_require__(99905); -const channelz_1 = __nccwpck_require__(79975); -const single_subchannel_channel_1 = __nccwpck_require__(28812); -const TRACER_NAME = 'subchannel'; -/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't - * have a constant for the max signed 32 bit integer, so this is a simple way - * to calculate it */ -const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); -class Subchannel { - /** - * A class representing a connection to a single backend. - * @param channelTarget The target string for the channel as a whole - * @param subchannelAddress The address for the backend that this subchannel - * will connect to - * @param options The channel options, plus any specific subchannel options - * for this subchannel - * @param credentials The channel credentials used to establish this - * connection - */ - constructor(channelTarget, subchannelAddress, options, credentials, connector) { - var _a; - this.channelTarget = channelTarget; - this.subchannelAddress = subchannelAddress; - this.options = options; - this.connector = connector; - /** - * The subchannel's current connectivity state. Invariant: `session` === `null` - * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. - */ - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The underlying http2 session used to make requests. - */ - this.transport = null; - /** - * Indicates that the subchannel should transition from TRANSIENT_FAILURE to - * CONNECTING instead of IDLE when the backoff timeout ends. - */ - this.continueConnecting = false; - /** - * A list of listener functions that will be called whenever the connectivity - * state changes. Will be modified by `addConnectivityStateListener` and - * `removeConnectivityStateListener` - */ - this.stateListeners = new Set(); - /** - * Tracks channels and subchannel pools with references to this subchannel - */ - this.refcount = 0; - // Channelz info - this.channelzEnabled = true; - this.dataProducers = new Map(); - this.subchannelChannel = null; - const backoffOptions = { - initialDelay: options['grpc.initial_reconnect_backoff_ms'], - maxDelay: options['grpc.max_reconnect_backoff_ms'], - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - this.handleBackoffTimer(); - }, backoffOptions); - this.backoffTimeout.unref(); - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - this.keepaliveTime = (_a = options['grpc.keepalive_time_ms']) !== null && _a !== void 0 ? _a : -1; - if (options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } - else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace('CT_INFO', 'Subchannel created'); - this.trace('Subchannel constructed with options ' + - JSON.stringify(options, undefined, 2)); - this.secureConnector = credentials._createSecureConnector(channelTarget, options); - } - getChannelzInfo() { - return { - state: this.connectivityState, - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists(), - target: this.subchannelAddressString, - }; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - refTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'subchannel_refcount', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - handleBackoffTimer() { - if (this.continueConnecting) { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - } - else { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); - } - } - /** - * Start a backoff timer with the current nextBackoff timeout - */ - startBackoff() { - this.backoffTimeout.runOnce(); - } - stopBackoff() { - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - } - startConnectingInternal() { - let options = this.options; - if (options['grpc.keepalive_time_ms']) { - const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); - options = Object.assign(Object.assign({}, options), { 'grpc.keepalive_time_ms': adjustedKeepaliveTime }); - } - this.connector - .connect(this.subchannelAddress, this.secureConnector, options) - .then(transport => { - if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { - this.transport = transport; - if (this.channelzEnabled) { - this.childrenTracker.refChild(transport.getChannelzRef()); - } - transport.addDisconnectListener(tooManyPings => { - this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - if (tooManyPings && this.keepaliveTime > 0) { - this.keepaliveTime *= 2; - logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); - } - }); - } - else { - /* If we can't transition from CONNECTING to READY here, we will - * not be using this transport, so release its resources. */ - transport.shutdown(); - } - }, error => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`); - }); - } - /** - * Initiate a state transition from any element of oldStates to the new - * state. If the current connectivityState is not in oldStates, do nothing. - * @param oldStates The set of states to transition from - * @param newState The state to transition to - * @returns True if the state changed, false otherwise - */ - transitionToState(oldStates, newState, errorMessage) { - var _a, _b; - if (oldStates.indexOf(this.connectivityState) === -1) { - return false; - } - if (errorMessage) { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState] + - ' with error "' + errorMessage + '"'); - } - else { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - } - if (this.channelzEnabled) { - this.channelzTrace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); - } - const previousState = this.connectivityState; - this.connectivityState = newState; - switch (newState) { - case connectivity_state_1.ConnectivityState.READY: - this.stopBackoff(); - break; - case connectivity_state_1.ConnectivityState.CONNECTING: - this.startBackoff(); - this.startConnectingInternal(); - this.continueConnecting = false; - break; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown(); - this.transport = null; - /* If the backoff timer has already ended by the time we get to the - * TRANSIENT_FAILURE state, we want to immediately transition out of - * TRANSIENT_FAILURE as though the backoff timer is ending right now */ - if (!this.backoffTimeout.isRunning()) { - process.nextTick(() => { - this.handleBackoffTimer(); - }); - } - break; - case connectivity_state_1.ConnectivityState.IDLE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown(); - this.transport = null; - break; - default: - throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); - } - for (const listener of this.stateListeners) { - listener(this, previousState, newState, this.keepaliveTime, errorMessage); - } - return true; - } - ref() { - this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount + 1)); - this.refcount += 1; - } - unref() { - this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount - 1)); - this.refcount -= 1; - if (this.refcount === 0) { - this.channelzTrace.addTrace('CT_INFO', 'Shutting down'); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.secureConnector.destroy(); - process.nextTick(() => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - }); - } - } - unrefIfOneRef() { - if (this.refcount === 1) { - this.unref(); - return true; - } - return false; - } - createCall(metadata, host, method, listener) { - if (!this.transport) { - throw new Error('Cannot create call, subchannel not READY'); - } - let statsTracker; - if (this.channelzEnabled) { - this.callTracker.addCallStarted(); - this.streamTracker.addCallStarted(); - statsTracker = { - onCallEnd: status => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } - else { - this.callTracker.addCallFailed(); - } - }, - }; - } - else { - statsTracker = {}; - } - return this.transport.createCall(metadata, host, method, listener, statsTracker); - } - /** - * If the subchannel is currently IDLE, start connecting and switch to the - * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, - * the next time it would transition to IDLE, start connecting again instead. - * Otherwise, do nothing. - */ - startConnecting() { - process.nextTick(() => { - /* First, try to transition from IDLE to connecting. If that doesn't happen - * because the state is not currently IDLE, check if it is - * TRANSIENT_FAILURE, and if so indicate that it should go back to - * connecting after the backoff timer ends. Otherwise do nothing */ - if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.continueConnecting = true; - } - } - }); - } - /** - * Get the subchannel's current connectivity state. - */ - getConnectivityState() { - return this.connectivityState; - } - /** - * Add a listener function to be called whenever the subchannel's - * connectivity state changes. - * @param listener - */ - addConnectivityStateListener(listener) { - this.stateListeners.add(listener); - } - /** - * Remove a listener previously added with `addConnectivityStateListener` - * @param listener A reference to a function previously passed to - * `addConnectivityStateListener` - */ - removeConnectivityStateListener(listener) { - this.stateListeners.delete(listener); - } - /** - * Reset the backoff timeout, and immediately start connecting if in backoff. - */ - resetBackoff() { - process.nextTick(() => { - this.backoffTimeout.reset(); - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - }); - } - getAddress() { - return this.subchannelAddressString; - } - getChannelzRef() { - return this.channelzRef; - } - isHealthy() { - return true; - } - addHealthStateWatcher(listener) { - // Do nothing with the listener - } - removeHealthStateWatcher(listener) { - // Do nothing with the listener - } - getRealSubchannel() { - return this; - } - realSubchannelEquals(other) { - return other.getRealSubchannel() === this; - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - } - } - getCallCredentials() { - return this.secureConnector.getCallCredentials(); - } - getChannel() { - if (!this.subchannelChannel) { - this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options); - } - return this.subchannelChannel; - } - addDataWatcher(dataWatcher) { - throw new Error('Not implemented'); - } - getOrCreateDataProducer(name, createDataProducer) { - const existingProducer = this.dataProducers.get(name); - if (existingProducer) { - return existingProducer; - } - const newProducer = createDataProducer(this); - this.dataProducers.set(name, newProducer); - return newProducer; - } - removeDataProducer(name) { - this.dataProducers.delete(name); - } -} -exports.Subchannel = Subchannel; -//# sourceMappingURL=subchannel.js.map - -/***/ }), - -/***/ 86581: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2019 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CIPHER_SUITES = void 0; -exports.getDefaultRootsData = getDefaultRootsData; -const fs = __nccwpck_require__(57147); -exports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; -const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; -let defaultRootsData = null; -function getDefaultRootsData() { - if (DEFAULT_ROOTS_FILE_PATH) { - if (defaultRootsData === null) { - defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); - } - return defaultRootsData; - } - return null; -} -//# sourceMappingURL=tls-helpers.js.map - -/***/ }), - -/***/ 46690: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* - * Copyright 2023 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Http2SubchannelConnector = void 0; -const http2 = __nccwpck_require__(85158); -const tls_1 = __nccwpck_require__(24404); -const channelz_1 = __nccwpck_require__(79975); -const constants_1 = __nccwpck_require__(90634); -const http_proxy_1 = __nccwpck_require__(24000); -const logging = __nccwpck_require__(35993); -const resolver_1 = __nccwpck_require__(31594); -const subchannel_address_1 = __nccwpck_require__(99905); -const uri_parser_1 = __nccwpck_require__(65974); -const net = __nccwpck_require__(41808); -const subchannel_call_1 = __nccwpck_require__(86940); -const call_number_1 = __nccwpck_require__(70380); -const TRACER_NAME = 'transport'; -const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; -const clientVersion = (__nccwpck_require__(56569)/* .version */ .i8); -const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT, } = http2.constants; -const KEEPALIVE_TIMEOUT_MS = 20000; -const tooManyPingsData = Buffer.from('too_many_pings', 'ascii'); -class Http2Transport { - constructor(session, subchannelAddress, options, - /** - * Name of the remote server, if it is not the same as the subchannel - * address, i.e. if connecting through an HTTP CONNECT proxy. - */ - remoteName) { - this.session = session; - this.options = options; - this.remoteName = remoteName; - /** - * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. - */ - this.keepaliveTimer = null; - /** - * Indicates that the keepalive timer ran out while there were no active - * calls, and a ping should be sent the next time a call starts. - */ - this.pendingSendKeepalivePing = false; - this.activeCalls = new Set(); - this.disconnectListeners = []; - this.disconnectHandled = false; - this.channelzEnabled = true; - this.keepalivesSent = 0; - this.messagesSent = 0; - this.messagesReceived = 0; - this.lastMessageSentTimestamp = null; - this.lastMessageReceivedTimestamp = null; - /* Populate subchannelAddressString and channelzRef before doing anything - * else, because they are used in the trace methods. */ - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - if (options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } - else { - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - // Build user-agent string. - this.userAgent = [ - options['grpc.primary_user_agent'], - `grpc-node-js/${clientVersion}`, - options['grpc.secondary_user_agent'], - ] - .filter(e => e) - .join(' '); // remove falsey values first - if ('grpc.keepalive_time_ms' in options) { - this.keepaliveTimeMs = options['grpc.keepalive_time_ms']; - } - else { - this.keepaliveTimeMs = -1; - } - if ('grpc.keepalive_timeout_ms' in options) { - this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']; - } - else { - this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; - } - if ('grpc.keepalive_permit_without_calls' in options) { - this.keepaliveWithoutCalls = - options['grpc.keepalive_permit_without_calls'] === 1; - } - else { - this.keepaliveWithoutCalls = false; - } - session.once('close', () => { - this.trace('session closed'); - this.handleDisconnect(); - }); - session.once('goaway', (errorCode, lastStreamID, opaqueData) => { - let tooManyPings = false; - /* See the last paragraph of - * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ - if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && - opaqueData && - opaqueData.equals(tooManyPingsData)) { - tooManyPings = true; - } - this.trace('connection closed by GOAWAY with code ' + - errorCode + - ' and data ' + - (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); - this.reportDisconnectToOwner(tooManyPings); - }); - session.once('error', error => { - this.trace('connection closed with error ' + error.message); - this.handleDisconnect(); - }); - session.socket.once('close', (hadError) => { - this.trace('connection closed. hadError=' + hadError); - this.handleDisconnect(); - }); - if (logging.isTracerEnabled(TRACER_NAME)) { - session.on('remoteSettings', (settings) => { - this.trace('new settings received' + - (this.session !== session ? ' on the old connection' : '') + - ': ' + - JSON.stringify(settings)); - }); - session.on('localSettings', (settings) => { - this.trace('local settings acknowledged by remote' + - (this.session !== session ? ' on the old connection' : '') + - ': ' + - JSON.stringify(settings)); - }); - } - /* Start the keepalive timer last, because this can trigger trace logs, - * which should only happen after everything else is set up. */ - if (this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - if (session.socket instanceof tls_1.TLSSocket) { - this.authContext = { - transportSecurityType: 'ssl', - sslPeerCertificate: session.socket.getPeerCertificate() - }; - } - else { - this.authContext = {}; - } - } - getChannelzInfo() { - var _a, _b, _c; - const sessionSocket = this.session.socket; - const remoteAddress = sessionSocket.remoteAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) - : null; - const localAddress = sessionSocket.localAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) - : null; - let tlsInfo; - if (this.session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && 'raw' in peerCertificate - ? peerCertificate.raw - : null, - }; - } - else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress: remoteAddress, - localAddress: localAddress, - security: tlsInfo, - remoteName: this.remoteName, - streamsStarted: this.streamTracker.callsStarted, - streamsSucceeded: this.streamTracker.callsSucceeded, - streamsFailed: this.streamTracker.callsFailed, - messagesSent: this.messagesSent, - messagesReceived: this.messagesReceived, - keepAlivesSent: this.keepalivesSent, - lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: this.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, - localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, - remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null, - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - flowControlTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - internalsTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'transport_internals', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - /** - * Indicate to the owner of this object that this transport should no longer - * be used. That happens if the connection drops, or if the server sends a - * GOAWAY. - * @param tooManyPings If true, this was triggered by a GOAWAY with data - * indicating that the session was closed becaues the client sent too many - * pings. - * @returns - */ - reportDisconnectToOwner(tooManyPings) { - if (this.disconnectHandled) { - return; - } - this.disconnectHandled = true; - this.disconnectListeners.forEach(listener => listener(tooManyPings)); - } - /** - * Handle connection drops, but not GOAWAYs. - */ - handleDisconnect() { - this.clearKeepaliveTimeout(); - this.reportDisconnectToOwner(false); - for (const call of this.activeCalls) { - call.onDisconnect(); - } - // Wait an event loop cycle before destroying the connection - setImmediate(() => { - this.session.destroy(); - }); - } - addDisconnectListener(listener) { - this.disconnectListeners.push(listener); - } - canSendPing() { - return (!this.session.destroyed && - this.keepaliveTimeMs > 0 && - (this.keepaliveWithoutCalls || this.activeCalls.size > 0)); - } - maybeSendPing() { - var _a, _b; - if (!this.canSendPing()) { - this.pendingSendKeepalivePing = true; - return; - } - if (this.keepaliveTimer) { - console.error('keepaliveTimeout is not null'); - return; - } - if (this.channelzEnabled) { - this.keepalivesSent += 1; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.keepaliveTrace('Ping timeout passed without response'); - this.handleDisconnect(); - }, this.keepaliveTimeoutMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - let pingSendError = ''; - try { - const pingSentSuccessfully = this.session.ping((err, duration, payload) => { - this.clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error ' + err.message); - this.handleDisconnect(); - } - else { - this.keepaliveTrace('Received ping response'); - this.maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.handleDisconnect(); - } - } - /** - * Starts the keepalive ping timer if appropriate. If the timer already ran - * out while there were no active requests, instead send a ping immediately. - * If the ping timer is already running or a ping is currently in flight, - * instead do nothing and wait for them to resolve. - */ - maybeStartKeepalivePingTimer() { - var _a, _b; - if (!this.canSendPing()) { - return; - } - if (this.pendingSendKeepalivePing) { - this.pendingSendKeepalivePing = false; - this.maybeSendPing(); - } - else if (!this.keepaliveTimer) { - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.maybeSendPing(); - }, this.keepaliveTimeMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /* Otherwise, there is already either a keepalive timer or a ping pending, - * wait for those to resolve. */ - } - /** - * Clears whichever keepalive timeout is currently active, if any. - */ - clearKeepaliveTimeout() { - if (this.keepaliveTimer) { - clearTimeout(this.keepaliveTimer); - this.keepaliveTimer = null; - } - } - removeActiveCall(call) { - this.activeCalls.delete(call); - if (this.activeCalls.size === 0) { - this.session.unref(); - } - } - addActiveCall(call) { - this.activeCalls.add(call); - if (this.activeCalls.size === 1) { - this.session.ref(); - if (!this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - } - } - createCall(metadata, host, method, listener, subchannelCallStatsTracker) { - const headers = metadata.toHttp2Headers(); - headers[HTTP2_HEADER_AUTHORITY] = host; - headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; - headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; - headers[HTTP2_HEADER_METHOD] = 'POST'; - headers[HTTP2_HEADER_PATH] = method; - headers[HTTP2_HEADER_TE] = 'trailers'; - let http2Stream; - /* In theory, if an error is thrown by session.request because session has - * become unusable (e.g. because it has received a goaway), this subchannel - * should soon see the corresponding close or goaway event anyway and leave - * READY. But we have seen reports that this does not happen - * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) - * so for defense in depth, we just discard the session when we see an - * error here. - */ - try { - http2Stream = this.session.request(headers); - } - catch (e) { - this.handleDisconnect(); - throw e; - } - this.flowControlTrace('local window size: ' + - this.session.state.localWindowSize + - ' remote window size: ' + - this.session.state.remoteWindowSize); - this.internalsTrace('session.closed=' + - this.session.closed + - ' session.destroyed=' + - this.session.destroyed + - ' session.socket.destroyed=' + - this.session.socket.destroyed); - let eventTracker; - // eslint-disable-next-line prefer-const - let call; - if (this.channelzEnabled) { - this.streamTracker.addCallStarted(); - eventTracker = { - addMessageSent: () => { - var _a; - this.messagesSent += 1; - this.lastMessageSentTimestamp = new Date(); - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - this.messagesReceived += 1; - this.lastMessageReceivedTimestamp = new Date(); - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: status => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: success => { - var _a; - if (success) { - this.streamTracker.addCallSucceeded(); - } - else { - this.streamTracker.addCallFailed(); - } - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - }, - }; - } - else { - eventTracker = { - addMessageSent: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: status => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: success => { - var _a; - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - }, - }; - } - call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); - this.addActiveCall(call); - return call; - } - getChannelzRef() { - return this.channelzRef; - } - getPeerName() { - return this.subchannelAddressString; - } - getOptions() { - return this.options; - } - getAuthContext() { - return this.authContext; - } - shutdown() { - this.session.close(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } -} -class Http2SubchannelConnector { - constructor(channelTarget) { - this.channelTarget = channelTarget; - this.session = null; - this.isShutdown = false; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + ' ' + text); - } - createSession(secureConnectResult, address, options) { - if (this.isShutdown) { - return Promise.reject(); - } - if (secureConnectResult.socket.closed) { - return Promise.reject('Connection closed before starting HTTP/2 handshake'); - } - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e, _f, _g; - let remoteName = null; - let realTarget = this.channelTarget; - if ('grpc.http_connect_target' in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); - if (parsedTarget) { - realTarget = parsedTarget; - remoteName = (0, uri_parser_1.uriToString)(parsedTarget); - } - } - const scheme = secureConnectResult.secure ? 'https' : 'http'; - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const closeHandler = () => { - var _a; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); - this.session = null; - // Leave time for error event to happen before rejecting - setImmediate(() => { - if (!reportedError) { - reportedError = true; - reject(`${errorMessage.trim()} (${new Date().toISOString()})`); - } - }); - }; - const errorHandler = (error) => { - var _a; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); - errorMessage = error.message; - this.trace('connection failed with error ' + errorMessage); - if (!reportedError) { - reportedError = true; - reject(`${errorMessage} (${new Date().toISOString()})`); - } - }; - const sessionOptions = { - createConnection: (authority, option) => { - return secureConnectResult.socket; - }, - settings: { - initialWindowSize: (_d = (_a = options['grpc-node.flow_control_window']) !== null && _a !== void 0 ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === void 0 ? void 0 : _b.call(http2)) === null || _c === void 0 ? void 0 : _c.initialWindowSize) !== null && _d !== void 0 ? _d : 65535, - } - }; - const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); - // Prepare window size configuration for remoteSettings handler - const defaultWin = (_g = (_f = (_e = http2.getDefaultSettings) === null || _e === void 0 ? void 0 : _e.call(http2)) === null || _f === void 0 ? void 0 : _f.initialWindowSize) !== null && _g !== void 0 ? _g : 65535; // 65 535 B - const connWin = options['grpc-node.flow_control_window']; - this.session = session; - let errorMessage = 'Failed to connect'; - let reportedError = false; - session.unref(); - session.once('remoteSettings', () => { - var _a; - // Send WINDOW_UPDATE now to avoid 65 KB start-window stall. - if (connWin && connWin > defaultWin) { - try { - // Node ≄ 14.18 - session.setLocalWindowSize(connWin); - } - catch (_b) { - // Older Node: bump by the delta - const delta = connWin - ((_a = session.state.localWindowSize) !== null && _a !== void 0 ? _a : defaultWin); - if (delta > 0) - session.incrementWindowSize(delta); - } - } - session.removeAllListeners(); - secureConnectResult.socket.removeListener('close', closeHandler); - secureConnectResult.socket.removeListener('error', errorHandler); - resolve(new Http2Transport(session, address, options, remoteName)); - this.session = null; - }); - session.once('close', closeHandler); - session.once('error', errorHandler); - secureConnectResult.socket.once('close', closeHandler); - secureConnectResult.socket.once('error', errorHandler); - }); - } - tcpConnect(address, options) { - return (0, http_proxy_1.getProxiedConnection)(address, options).then(proxiedSocket => { - if (proxiedSocket) { - return proxiedSocket; - } - else { - return new Promise((resolve, reject) => { - const closeCallback = () => { - reject(new Error('Socket closed')); - }; - const errorCallback = (error) => { - reject(error); - }; - const socket = net.connect(address, () => { - socket.removeListener('close', closeCallback); - socket.removeListener('error', errorCallback); - resolve(socket); - }); - socket.once('close', closeCallback); - socket.once('error', errorCallback); - }); - } - }); - } - async connect(address, secureConnector, options) { - if (this.isShutdown) { - return Promise.reject(); - } - let tcpConnection = null; - let secureConnectResult = null; - const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); - try { - this.trace(addressString + ' Waiting for secureConnector to be ready'); - await secureConnector.waitForReady(); - this.trace(addressString + ' secureConnector is ready'); - tcpConnection = await this.tcpConnect(address, options); - tcpConnection.setNoDelay(); - this.trace(addressString + ' Established TCP connection'); - secureConnectResult = await secureConnector.connect(tcpConnection); - this.trace(addressString + ' Established secure connection'); - return this.createSession(secureConnectResult, address, options); - } - catch (e) { - tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); - secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy(); - throw e; - } - } - shutdown() { - var _a; - this.isShutdown = true; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.close(); - this.session = null; - } -} -exports.Http2SubchannelConnector = Http2SubchannelConnector; -//# sourceMappingURL=transport.js.map - -/***/ }), - -/***/ 65974: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - * Copyright 2020 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.parseUri = parseUri; -exports.splitHostPort = splitHostPort; -exports.combineHostPort = combineHostPort; -exports.uriToString = uriToString; -/* - * The groups correspond to URI parts as follows: - * 1. scheme - * 2. authority - * 3. path - */ -const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; -function parseUri(uriString) { - const parsedUri = URI_REGEX.exec(uriString); - if (parsedUri === null) { - return null; - } - return { - scheme: parsedUri[1], - authority: parsedUri[2], - path: parsedUri[3], - }; -} -const NUMBER_REGEX = /^\d+$/; -function splitHostPort(path) { - if (path.startsWith('[')) { - const hostEnd = path.indexOf(']'); - if (hostEnd === -1) { - return null; - } - const host = path.substring(1, hostEnd); - /* Only an IPv6 address should be in bracketed notation, and an IPv6 - * address should have at least one colon */ - if (host.indexOf(':') === -1) { - return null; - } - if (path.length > hostEnd + 1) { - if (path[hostEnd + 1] === ':') { - const portString = path.substring(hostEnd + 2); - if (NUMBER_REGEX.test(portString)) { - return { - host: host, - port: +portString, - }; - } - else { - return null; - } - } - else { - return null; - } - } - else { - return { - host, - }; - } - } - else { - const splitPath = path.split(':'); - /* Exactly one colon means that this is host:port. Zero colons means that - * there is no port. And multiple colons means that this is a bare IPv6 - * address with no port */ - if (splitPath.length === 2) { - if (NUMBER_REGEX.test(splitPath[1])) { - return { - host: splitPath[0], - port: +splitPath[1], - }; - } - else { - return null; - } - } - else { - return { - host: path, - }; - } - } -} -function combineHostPort(hostPort) { - if (hostPort.port === undefined) { - return hostPort.host; - } - else { - // Only an IPv6 host should include a colon - if (hostPort.host.includes(':')) { - return `[${hostPort.host}]:${hostPort.port}`; - } - else { - return `${hostPort.host}:${hostPort.port}`; - } - } -} -function uriToString(uri) { - let result = ''; - if (uri.scheme !== undefined) { - result += uri.scheme + ':'; - } - if (uri.authority !== undefined) { - result += '//' + uri.authority + '/'; - } - result += uri.path; - return result; -} -//# sourceMappingURL=uri-parser.js.map - -/***/ }), - -/***/ 48934: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var __webpack_unused_export__; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -__webpack_unused_export__ = ({ value: true }); -__webpack_unused_export__ = __webpack_unused_export__ = __webpack_unused_export__ = exports.J_ = __webpack_unused_export__ = exports.Cp = __webpack_unused_export__ = __webpack_unused_export__ = void 0; -const camelCase = __nccwpck_require__(7994); -const Protobuf = __nccwpck_require__(85881); -const descriptor = __nccwpck_require__(21629); -const util_1 = __nccwpck_require__(32358); -const Long = __nccwpck_require__(52694); -__webpack_unused_export__ = Long; -function isAnyExtension(obj) { - return ('@type' in obj) && (typeof obj['@type'] === 'string'); -} -__webpack_unused_export__ = isAnyExtension; -var IdempotencyLevel; -(function (IdempotencyLevel) { - IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; -})(IdempotencyLevel = exports.Cp || (exports.Cp = {})); -const descriptorOptions = { - longs: String, - enums: String, - bytes: String, - defaults: true, - oneofs: true, - json: true, -}; -function joinName(baseName, name) { - if (baseName === '') { - return name; - } - else { - return baseName + '.' + name; - } -} -function isHandledReflectionObject(obj) { - return (obj instanceof Protobuf.Service || - obj instanceof Protobuf.Type || - obj instanceof Protobuf.Enum); -} -function isNamespaceBase(obj) { - return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; -} -function getAllHandledReflectionObjects(obj, parentName) { - const objName = joinName(parentName, obj.name); - if (isHandledReflectionObject(obj)) { - return [[objName, obj]]; - } - else { - if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { - return Object.keys(obj.nested) - .map(name => { - return getAllHandledReflectionObjects(obj.nested[name], objName); - }) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - } - } - return []; -} -function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; -} -function createSerializer(cls) { - return function serialize(arg) { - if (Array.isArray(arg)) { - throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); - } - const message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; -} -function mapMethodOptions(options) { - return (options || []).reduce((obj, item) => { - for (const [key, value] of Object.entries(item)) { - switch (key) { - case 'uninterpreted_option': - obj.uninterpreted_option.push(item.uninterpreted_option); - break; - default: - obj[key] = value; - } - } - return obj; - }, { - deprecated: false, - idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, - uninterpreted_option: [], - }); -} -function createMethodDefinition(method, serviceName, options, fileDescriptors) { - /* This is only ever called after the corresponding root.resolveAll(), so we - * can assume that the resolved request and response types are non-null */ - const requestType = method.resolvedRequestType; - const responseType = method.resolvedResponseType; - return { - path: '/' + serviceName + '/' + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(requestType), - requestDeserialize: createDeserializer(requestType, options), - responseSerialize: createSerializer(responseType), - responseDeserialize: createDeserializer(responseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: camelCase(method.name), - requestType: createMessageDefinition(requestType, options, fileDescriptors), - responseType: createMessageDefinition(responseType, options, fileDescriptors), - options: mapMethodOptions(method.parsedOptions), - }; -} -function createServiceDefinition(service, name, options, fileDescriptors) { - const def = {}; - for (const method of service.methodsArray) { - def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); - } - return def; -} -function createMessageDefinition(message, options, fileDescriptors) { - const messageDescriptor = message.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 DescriptorProto', - type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - serialize: createSerializer(message), - deserialize: createDeserializer(message, options) - }; -} -function createEnumDefinition(enumType, fileDescriptors) { - const enumDescriptor = enumType.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 EnumDescriptorProto', - type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - }; -} -/** - * function createDefinition(obj: Protobuf.Service, name: string, options: - * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, - * name: string, options: Options): MessageTypeDefinition; function - * createDefinition(obj: Protobuf.Enum, name: string, options: Options): - * EnumTypeDefinition; - */ -function createDefinition(obj, name, options, fileDescriptors) { - if (obj instanceof Protobuf.Service) { - return createServiceDefinition(obj, name, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Type) { - return createMessageDefinition(obj, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Enum) { - return createEnumDefinition(obj, fileDescriptors); - } - else { - throw new Error('Type mismatch in reflection object handling'); - } -} -function createPackageDefinition(root, options) { - const def = {}; - root.resolveAll(); - const descriptorList = root.toDescriptor('proto3').file; - const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); - for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { - def[name] = createDefinition(obj, name, options, bufferList); - } - return def; -} -function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { - options = options || {}; - const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); - root.resolveAll(); - return createPackageDefinition(root, options); -} -/** - * Load a .proto file with the specified options. - * @param filename One or multiple file paths to load. Can be an absolute path - * or relative to an include path. - * @param options.keepCase Preserve field names. The default is to change them - * to camel case. - * @param options.longs The type that should be used to represent `long` values. - * Valid options are `Number` and `String`. Defaults to a `Long` object type - * from a library. - * @param options.enums The type that should be used to represent `enum` values. - * The only valid option is `String`. Defaults to the numeric value. - * @param options.bytes The type that should be used to represent `bytes` - * values. Valid options are `Array` and `String`. The default is to use - * `Buffer`. - * @param options.defaults Set default values on output objects. Defaults to - * `false`. - * @param options.arrays Set empty arrays for missing array values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.objects Set empty objects for missing object values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.oneofs Set virtual oneof properties to the present field's - * name - * @param options.json Represent Infinity and NaN as strings in float fields, - * and automatically decode google.protobuf.Any values. - * @param options.includeDirs Paths to search for imported `.proto` files. - */ -function load(filename, options) { - return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { - return createPackageDefinition(loadedRoot, options); - }); -} -__webpack_unused_export__ = load; -function loadSync(filename, options) { - const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); - return createPackageDefinition(loadedRoot, options); -} -exports.J_ = loadSync; -function fromJSON(json, options) { - options = options || {}; - const loadedRoot = Protobuf.Root.fromJSON(json); - loadedRoot.resolveAll(); - return createPackageDefinition(loadedRoot, options); -} -__webpack_unused_export__ = fromJSON; -function loadFileDescriptorSetFromBuffer(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -__webpack_unused_export__ = loadFileDescriptorSetFromBuffer; -function loadFileDescriptorSetFromObject(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -__webpack_unused_export__ = loadFileDescriptorSetFromObject; -(0, util_1.addCommonProtos)(); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 32358: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; -const fs = __nccwpck_require__(57147); -const path = __nccwpck_require__(71017); -const Protobuf = __nccwpck_require__(85881); -function addIncludePathResolver(root, includePaths) { - const originalResolvePath = root.resolvePath; - root.resolvePath = (origin, target) => { - if (path.isAbsolute(target)) { - return target; - } - for (const directory of includePaths) { - const fullPath = path.join(directory, target); - try { - fs.accessSync(fullPath, fs.constants.R_OK); - return fullPath; - } - catch (err) { - continue; - } - } - process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); - return originalResolvePath(origin, target); - }; -} -async function loadProtosWithOptions(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - return Promise.reject(new Error('The includeDirs option must be an array')); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = await root.load(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptions = loadProtosWithOptions; -function loadProtosWithOptionsSync(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - throw new Error('The includeDirs option must be an array'); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; -/** - * Load Google's well-known proto files that aren't exposed by Protobuf.js. - */ -function addCommonProtos() { - // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, - // and wrappers. compiler/plugin is excluded in Protobuf.js and here. - // Using constant strings for compatibility with tools like Webpack - const apiDescriptor = __nccwpck_require__(44784); - const descriptorDescriptor = __nccwpck_require__(43571); - const sourceContextDescriptor = __nccwpck_require__(73342); - const typeDescriptor = __nccwpck_require__(58783); - Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); -} -exports.addCommonProtos = addCommonProtos; -//# sourceMappingURL=util.js.map - -/***/ }), - -/***/ 98171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = void 0; -const camelCase = __nccwpck_require__(7994); -const Protobuf = __nccwpck_require__(85881); -const descriptor = __nccwpck_require__(21629); -const util_1 = __nccwpck_require__(13245); -const Long = __nccwpck_require__(52694); -exports.Long = Long; -function isAnyExtension(obj) { - return ('@type' in obj) && (typeof obj['@type'] === 'string'); -} -exports.isAnyExtension = isAnyExtension; -var IdempotencyLevel; -(function (IdempotencyLevel) { - IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; -})(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {})); -const descriptorOptions = { - longs: String, - enums: String, - bytes: String, - defaults: true, - oneofs: true, - json: true, -}; -function joinName(baseName, name) { - if (baseName === '') { - return name; - } - else { - return baseName + '.' + name; - } -} -function isHandledReflectionObject(obj) { - return (obj instanceof Protobuf.Service || - obj instanceof Protobuf.Type || - obj instanceof Protobuf.Enum); -} -function isNamespaceBase(obj) { - return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; -} -function getAllHandledReflectionObjects(obj, parentName) { - const objName = joinName(parentName, obj.name); - if (isHandledReflectionObject(obj)) { - return [[objName, obj]]; - } - else { - if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { - return Object.keys(obj.nested) - .map(name => { - return getAllHandledReflectionObjects(obj.nested[name], objName); - }) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - } - } - return []; -} -function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; -} -function createSerializer(cls) { - return function serialize(arg) { - if (Array.isArray(arg)) { - throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); - } - const message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; -} -function mapMethodOptions(options) { - return (options || []).reduce((obj, item) => { - for (const [key, value] of Object.entries(item)) { - switch (key) { - case 'uninterpreted_option': - obj.uninterpreted_option.push(item.uninterpreted_option); - break; - default: - obj[key] = value; - } - } - return obj; - }, { - deprecated: false, - idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, - uninterpreted_option: [], - }); -} -function createMethodDefinition(method, serviceName, options, fileDescriptors) { - /* This is only ever called after the corresponding root.resolveAll(), so we - * can assume that the resolved request and response types are non-null */ - const requestType = method.resolvedRequestType; - const responseType = method.resolvedResponseType; - return { - path: '/' + serviceName + '/' + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(requestType), - requestDeserialize: createDeserializer(requestType, options), - responseSerialize: createSerializer(responseType), - responseDeserialize: createDeserializer(responseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: camelCase(method.name), - requestType: createMessageDefinition(requestType, fileDescriptors), - responseType: createMessageDefinition(responseType, fileDescriptors), - options: mapMethodOptions(method.parsedOptions), - }; -} -function createServiceDefinition(service, name, options, fileDescriptors) { - const def = {}; - for (const method of service.methodsArray) { - def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); - } - return def; -} -function createMessageDefinition(message, fileDescriptors) { - const messageDescriptor = message.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 DescriptorProto', - type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - }; -} -function createEnumDefinition(enumType, fileDescriptors) { - const enumDescriptor = enumType.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 EnumDescriptorProto', - type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - }; -} -/** - * function createDefinition(obj: Protobuf.Service, name: string, options: - * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, - * name: string, options: Options): MessageTypeDefinition; function - * createDefinition(obj: Protobuf.Enum, name: string, options: Options): - * EnumTypeDefinition; - */ -function createDefinition(obj, name, options, fileDescriptors) { - if (obj instanceof Protobuf.Service) { - return createServiceDefinition(obj, name, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Type) { - return createMessageDefinition(obj, fileDescriptors); - } - else if (obj instanceof Protobuf.Enum) { - return createEnumDefinition(obj, fileDescriptors); - } - else { - throw new Error('Type mismatch in reflection object handling'); - } -} -function createPackageDefinition(root, options) { - const def = {}; - root.resolveAll(); - const descriptorList = root.toDescriptor('proto3').file; - const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); - for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { - def[name] = createDefinition(obj, name, options, bufferList); - } - return def; -} -function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { - options = options || {}; - const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); - root.resolveAll(); - return createPackageDefinition(root, options); -} -/** - * Load a .proto file with the specified options. - * @param filename One or multiple file paths to load. Can be an absolute path - * or relative to an include path. - * @param options.keepCase Preserve field names. The default is to change them - * to camel case. - * @param options.longs The type that should be used to represent `long` values. - * Valid options are `Number` and `String`. Defaults to a `Long` object type - * from a library. - * @param options.enums The type that should be used to represent `enum` values. - * The only valid option is `String`. Defaults to the numeric value. - * @param options.bytes The type that should be used to represent `bytes` - * values. Valid options are `Array` and `String`. The default is to use - * `Buffer`. - * @param options.defaults Set default values on output objects. Defaults to - * `false`. - * @param options.arrays Set empty arrays for missing array values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.objects Set empty objects for missing object values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.oneofs Set virtual oneof properties to the present field's - * name - * @param options.json Represent Infinity and NaN as strings in float fields, - * and automatically decode google.protobuf.Any values. - * @param options.includeDirs Paths to search for imported `.proto` files. - */ -function load(filename, options) { - return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { - return createPackageDefinition(loadedRoot, options); - }); -} -exports.load = load; -function loadSync(filename, options) { - const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); - return createPackageDefinition(loadedRoot, options); -} -exports.loadSync = loadSync; -function fromJSON(json, options) { - options = options || {}; - const loadedRoot = Protobuf.Root.fromJSON(json); - loadedRoot.resolveAll(); - return createPackageDefinition(loadedRoot, options); -} -exports.fromJSON = fromJSON; -function loadFileDescriptorSetFromBuffer(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; -function loadFileDescriptorSetFromObject(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; -(0, util_1.addCommonProtos)(); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 13245: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * @license - * Copyright 2018 gRPC 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 - * - * 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. - * - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; -const fs = __nccwpck_require__(57147); -const path = __nccwpck_require__(71017); -const Protobuf = __nccwpck_require__(85881); -function addIncludePathResolver(root, includePaths) { - const originalResolvePath = root.resolvePath; - root.resolvePath = (origin, target) => { - if (path.isAbsolute(target)) { - return target; - } - for (const directory of includePaths) { - const fullPath = path.join(directory, target); - try { - fs.accessSync(fullPath, fs.constants.R_OK); - return fullPath; - } - catch (err) { - continue; - } - } - process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); - return originalResolvePath(origin, target); - }; -} -async function loadProtosWithOptions(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - return Promise.reject(new Error('The includeDirs option must be an array')); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = await root.load(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptions = loadProtosWithOptions; -function loadProtosWithOptionsSync(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - throw new Error('The includeDirs option must be an array'); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; -/** - * Load Google's well-known proto files that aren't exposed by Protobuf.js. - */ -function addCommonProtos() { - // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, - // and wrappers. compiler/plugin is excluded in Protobuf.js and here. - // Using constant strings for compatibility with tools like Webpack - const apiDescriptor = __nccwpck_require__(44784); - const descriptorDescriptor = __nccwpck_require__(43571); - const sourceContextDescriptor = __nccwpck_require__(73342); - const typeDescriptor = __nccwpck_require__(58783); - Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); -} -exports.addCommonProtos = addCommonProtos; -//# sourceMappingURL=util.js.map - -/***/ }), - -/***/ 12592: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "t", ({ - value: true -})); - -class TreeNode { - constructor(t, e, s = 1) { - this.i = undefined; - this.h = undefined; - this.o = undefined; - this.u = t; - this.l = e; - this.p = s; - } - I() { - let t = this; - const e = t.o.o === t; - if (e && t.p === 1) { - t = t.h; - } else if (t.i) { - t = t.i; - while (t.h) { - t = t.h; - } - } else { - if (e) { - return t.o; - } - let s = t.o; - while (s.i === t) { - t = s; - s = t.o; - } - t = s; - } - return t; - } - B() { - let t = this; - if (t.h) { - t = t.h; - while (t.i) { - t = t.i; - } - return t; - } else { - let e = t.o; - while (e.h === t) { - t = e; - e = t.o; - } - if (t.h !== e) { - return e; - } else return t; - } - } - _() { - const t = this.o; - const e = this.h; - const s = e.i; - if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; - e.o = t; - e.i = this; - this.o = e; - this.h = s; - if (s) s.o = this; - return e; - } - g() { - const t = this.o; - const e = this.i; - const s = e.h; - if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; - e.o = t; - e.h = this; - this.o = e; - this.i = s; - if (s) s.o = this; - return e; - } -} - -class TreeNodeEnableIndex extends TreeNode { - constructor() { - super(...arguments); - this.M = 1; - } - _() { - const t = super._(); - this.O(); - t.O(); - return t; - } - g() { - const t = super.g(); - this.O(); - t.O(); - return t; - } - O() { - this.M = 1; - if (this.i) { - this.M += this.i.M; - } - if (this.h) { - this.M += this.h.M; - } - } -} - -class ContainerIterator { - constructor(t = 0) { - this.iteratorType = t; - } - equals(t) { - return this.T === t.T; - } -} - -class Base { - constructor() { - this.m = 0; - } - get length() { - return this.m; - } - size() { - return this.m; - } - empty() { - return this.m === 0; - } -} - -class Container extends Base {} - -function throwIteratorAccessError() { - throw new RangeError("Iterator access denied!"); -} - -class TreeContainer extends Container { - constructor(t = function(t, e) { - if (t < e) return -1; - if (t > e) return 1; - return 0; - }, e = false) { - super(); - this.v = undefined; - this.A = t; - this.enableIndex = e; - this.N = e ? TreeNodeEnableIndex : TreeNode; - this.C = new this.N; - } - R(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - t = t.h; - } else if (i > 0) { - s = t; - t = t.i; - } else return t; - } - return s; - } - K(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i <= 0) { - t = t.h; - } else { - s = t; - t = t.i; - } - } - return s; - } - L(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else if (i > 0) { - t = t.i; - } else return t; - } - return s; - } - k(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else { - t = t.i; - } - } - return s; - } - P(t) { - while (true) { - const e = t.o; - if (e === this.C) return; - if (t.p === 1) { - t.p = 0; - return; - } - if (t === e.i) { - const s = e.h; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e._(); - } else e._(); - } else { - if (s.h && s.h.p === 1) { - s.p = e.p; - e.p = 0; - s.h.p = 0; - if (e === this.v) { - this.v = e._(); - } else e._(); - return; - } else if (s.i && s.i.p === 1) { - s.p = 1; - s.i.p = 0; - s.g(); - } else { - s.p = 1; - t = e; - } - } - } else { - const s = e.i; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - } else { - if (s.i && s.i.p === 1) { - s.p = e.p; - e.p = 0; - s.i.p = 0; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - return; - } else if (s.h && s.h.p === 1) { - s.p = 1; - s.h.p = 0; - s._(); - } else { - s.p = 1; - t = e; - } - } - } - } - } - S(t) { - if (this.m === 1) { - this.clear(); - return; - } - let e = t; - while (e.i || e.h) { - if (e.h) { - e = e.h; - while (e.i) e = e.i; - } else { - e = e.i; - } - const s = t.u; - t.u = e.u; - e.u = s; - const i = t.l; - t.l = e.l; - e.l = i; - t = e; - } - if (this.C.i === e) { - this.C.i = e.o; - } else if (this.C.h === e) { - this.C.h = e.o; - } - this.P(e); - let s = e.o; - if (e === s.i) { - s.i = undefined; - } else s.h = undefined; - this.m -= 1; - this.v.p = 0; - if (this.enableIndex) { - while (s !== this.C) { - s.M -= 1; - s = s.o; - } - } - } - U(t) { - const e = typeof t === "number" ? t : undefined; - const s = typeof t === "function" ? t : undefined; - const i = typeof t === "undefined" ? [] : undefined; - let r = 0; - let n = this.v; - const h = []; - while (h.length || n) { - if (n) { - h.push(n); - n = n.i; - } else { - n = h.pop(); - if (r === e) return n; - i && i.push(n); - s && s(n, r, this); - r += 1; - n = n.h; - } - } - return i; - } - j(t) { - while (true) { - const e = t.o; - if (e.p === 0) return; - const s = e.o; - if (e === s.i) { - const i = s.h; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.h) { - t.p = 0; - if (t.i) { - t.i.o = e; - } - if (t.h) { - t.h.o = s; - } - e.h = t.i; - s.i = t.h; - t.i = e; - t.h = s; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e = s.o; - if (e.i === s) { - e.i = t; - } else e.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s.g(); - } else s.g(); - s.p = 1; - return; - } - } else { - const i = s.i; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.i) { - t.p = 0; - if (t.i) { - t.i.o = s; - } - if (t.h) { - t.h.o = e; - } - s.h = t.i; - e.i = t.h; - t.i = s; - t.h = e; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e = s.o; - if (e.i === s) { - e.i = t; - } else e.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s._(); - } else s._(); - s.p = 1; - return; - } - } - if (this.enableIndex) { - e.O(); - s.O(); - t.O(); - } - return; - } - } - q(t, e, s) { - if (this.v === undefined) { - this.m += 1; - this.v = new this.N(t, e, 0); - this.v.o = this.C; - this.C.o = this.C.i = this.C.h = this.v; - return this.m; - } - let i; - const r = this.C.i; - const n = this.A(r.u, t); - if (n === 0) { - r.l = e; - return this.m; - } else if (n > 0) { - r.i = new this.N(t, e); - r.i.o = r; - i = r.i; - this.C.i = i; - } else { - const r = this.C.h; - const n = this.A(r.u, t); - if (n === 0) { - r.l = e; - return this.m; - } else if (n < 0) { - r.h = new this.N(t, e); - r.h.o = r; - i = r.h; - this.C.h = i; - } else { - if (s !== undefined) { - const r = s.T; - if (r !== this.C) { - const s = this.A(r.u, t); - if (s === 0) { - r.l = e; - return this.m; - } else if (s > 0) { - const s = r.I(); - const n = this.A(s.u, t); - if (n === 0) { - s.l = e; - return this.m; - } else if (n < 0) { - i = new this.N(t, e); - if (s.h === undefined) { - s.h = i; - i.o = s; - } else { - r.i = i; - i.o = r; - } - } - } - } - } - if (i === undefined) { - i = this.v; - while (true) { - const s = this.A(i.u, t); - if (s > 0) { - if (i.i === undefined) { - i.i = new this.N(t, e); - i.i.o = i; - i = i.i; - break; - } - i = i.i; - } else if (s < 0) { - if (i.h === undefined) { - i.h = new this.N(t, e); - i.h.o = i; - i = i.h; - break; - } - i = i.h; - } else { - i.l = e; - return this.m; - } - } - } - } - } - if (this.enableIndex) { - let t = i.o; - while (t !== this.C) { - t.M += 1; - t = t.o; - } - } - this.j(i); - this.m += 1; - return this.m; - } - H(t, e) { - while (t) { - const s = this.A(t.u, e); - if (s < 0) { - t = t.h; - } else if (s > 0) { - t = t.i; - } else return t; - } - return t || this.C; - } - clear() { - this.m = 0; - this.v = undefined; - this.C.o = undefined; - this.C.i = this.C.h = undefined; - } - updateKeyByIterator(t, e) { - const s = t.T; - if (s === this.C) { - throwIteratorAccessError(); - } - if (this.m === 1) { - s.u = e; - return true; - } - const i = s.B().u; - if (s === this.C.i) { - if (this.A(i, e) > 0) { - s.u = e; - return true; - } - return false; - } - const r = s.I().u; - if (s === this.C.h) { - if (this.A(r, e) < 0) { - s.u = e; - return true; - } - return false; - } - if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; - s.u = e; - return true; - } - eraseElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError; - } - const e = this.U(t); - this.S(e); - return this.m; - } - eraseElementByKey(t) { - if (this.m === 0) return false; - const e = this.H(this.v, t); - if (e === this.C) return false; - this.S(e); - return true; - } - eraseElementByIterator(t) { - const e = t.T; - if (e === this.C) { - throwIteratorAccessError(); - } - const s = e.h === undefined; - const i = t.iteratorType === 0; - if (i) { - if (s) t.next(); - } else { - if (!s || e.i === undefined) t.next(); - } - this.S(e); - return t; - } - getHeight() { - if (this.m === 0) return 0; - function traversal(t) { - if (!t) return 0; - return Math.max(traversal(t.i), traversal(t.h)) + 1; - } - return traversal(this.v); - } -} - -class TreeIterator extends ContainerIterator { - constructor(t, e, s) { - super(s); - this.T = t; - this.C = e; - if (this.iteratorType === 0) { - this.pre = function() { - if (this.T === this.C.i) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - } else { - this.pre = function() { - if (this.T === this.C.h) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - } - } - get index() { - let t = this.T; - const e = this.C.o; - if (t === this.C) { - if (e) { - return e.M - 1; - } - return 0; - } - let s = 0; - if (t.i) { - s += t.i.M; - } - while (t !== e) { - const e = t.o; - if (t === e.h) { - s += 1; - if (e.i) { - s += e.i.M; - } - } - t = e; - } - return s; - } - isAccessible() { - return this.T !== this.C; - } -} - -class OrderedMapIterator extends TreeIterator { - constructor(t, e, s, i) { - super(t, e, i); - this.container = s; - } - get pointer() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - const t = this; - return new Proxy([], { - get(e, s) { - if (s === "0") return t.T.u; else if (s === "1") return t.T.l; - e[0] = t.T.u; - e[1] = t.T.l; - return e[s]; - }, - set(e, s, i) { - if (s !== "1") { - throw new TypeError("prop must be 1"); - } - t.T.l = i; - return true; - } - }); - } - copy() { - return new OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); - } -} - -class OrderedMap extends TreeContainer { - constructor(t = [], e, s) { - super(e, s); - const i = this; - t.forEach((function(t) { - i.setElement(t[0], t[1]); - })); - } - begin() { - return new OrderedMapIterator(this.C.i || this.C, this.C, this); - } - end() { - return new OrderedMapIterator(this.C, this.C, this); - } - rBegin() { - return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); - } - rEnd() { - return new OrderedMapIterator(this.C, this.C, this, 1); - } - front() { - if (this.m === 0) return; - const t = this.C.i; - return [ t.u, t.l ]; - } - back() { - if (this.m === 0) return; - const t = this.C.h; - return [ t.u, t.l ]; - } - lowerBound(t) { - const e = this.R(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - upperBound(t) { - const e = this.K(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseLowerBound(t) { - const e = this.L(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseUpperBound(t) { - const e = this.k(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - forEach(t) { - this.U((function(e, s, i) { - t([ e.u, e.l ], s, i); - })); - } - setElement(t, e, s) { - return this.q(t, e, s); - } - getElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError; - } - const e = this.U(t); - return [ e.u, e.l ]; - } - find(t) { - const e = this.H(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - getElementByKey(t) { - const e = this.H(this.v, t); - return e.l; - } - union(t) { - const e = this; - t.forEach((function(t) { - e.setElement(t[0], t[1]); - })); - return this.m; - } - * [Symbol.iterator]() { - const t = this.m; - const e = this.U(); - for (let s = 0; s < t; ++s) { - const t = e[s]; - yield [ t.u, t.l ]; - } - } -} - -exports.OrderedMap = OrderedMap; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 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 index_exports = {}; -__export(index_exports, { - Octokit: () => Octokit -}); -module.exports = __toCommonJS(index_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.2.2"; - -// pkg/dist-src/index.js -var noop = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop; - } - if (typeof logger.info !== "function") { - logger.info = noop; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; -} -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 = createLogger(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.6"; - -// 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+)|(?:(? 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(/(? { - 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 index_exports = {}; -__export(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest -}); -module.exports = __toCommonJS(index_exports); -var import_request3 = __nccwpck_require__(36234); -var import_universal_user_agent = __nccwpck_require__(45030); - -// pkg/dist-src/version.js -var VERSION = "7.1.1"; - -// 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); - - -/***/ }), - -/***/ 64193: -/***/ ((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, { - composePaginateRest: () => composePaginateRest, - isPaginatingEndpoint: () => isPaginatingEndpoint, - paginateRest: () => paginateRest, - paginatingEndpoints: () => paginatingEndpoints -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "9.2.2"; - -// pkg/dist-src/normalize-paginated-list-response.js -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) - return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - return response; -} - -// pkg/dist-src/iterator.js -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) - return { done: true }; - try { - const response = await requestMethod({ method, url, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - return { value: normalizedResponse }; - } catch (error) { - if (error.status !== 409) - throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - }) - }; -} - -// pkg/dist-src/paginate.js -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); -} -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); -} - -// pkg/dist-src/compose-paginate.js -var composePaginateRest = Object.assign(paginate, { - iterator -}); - -// pkg/dist-src/generated/paginating-endpoints.js -var paginatingEndpoints = [ - "GET /advisories", - "GET /app/hook/deliveries", - "GET /app/installation-requests", - "GET /app/installations", - "GET /assignments/{assignment_id}/accepted_assignments", - "GET /classrooms", - "GET /classrooms/{classroom_id}/assignments", - "GET /enterprises/{enterprise}/dependabot/alerts", - "GET /enterprises/{enterprise}/secret-scanning/alerts", - "GET /events", - "GET /gists", - "GET /gists/public", - "GET /gists/starred", - "GET /gists/{gist_id}/comments", - "GET /gists/{gist_id}/commits", - "GET /gists/{gist_id}/forks", - "GET /installation/repositories", - "GET /issues", - "GET /licenses", - "GET /marketplace_listing/plans", - "GET /marketplace_listing/plans/{plan_id}/accounts", - "GET /marketplace_listing/stubbed/plans", - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", - "GET /networks/{owner}/{repo}/events", - "GET /notifications", - "GET /organizations", - "GET /orgs/{org}/actions/cache/usage-by-repository", - "GET /orgs/{org}/actions/permissions/repositories", - "GET /orgs/{org}/actions/runners", - "GET /orgs/{org}/actions/secrets", - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", - "GET /orgs/{org}/actions/variables", - "GET /orgs/{org}/actions/variables/{name}/repositories", - "GET /orgs/{org}/blocks", - "GET /orgs/{org}/code-scanning/alerts", - "GET /orgs/{org}/codespaces", - "GET /orgs/{org}/codespaces/secrets", - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", - "GET /orgs/{org}/copilot/billing/seats", - "GET /orgs/{org}/dependabot/alerts", - "GET /orgs/{org}/dependabot/secrets", - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", - "GET /orgs/{org}/events", - "GET /orgs/{org}/failed_invitations", - "GET /orgs/{org}/hooks", - "GET /orgs/{org}/hooks/{hook_id}/deliveries", - "GET /orgs/{org}/installations", - "GET /orgs/{org}/invitations", - "GET /orgs/{org}/invitations/{invitation_id}/teams", - "GET /orgs/{org}/issues", - "GET /orgs/{org}/members", - "GET /orgs/{org}/members/{username}/codespaces", - "GET /orgs/{org}/migrations", - "GET /orgs/{org}/migrations/{migration_id}/repositories", - "GET /orgs/{org}/organization-roles/{role_id}/teams", - "GET /orgs/{org}/organization-roles/{role_id}/users", - "GET /orgs/{org}/outside_collaborators", - "GET /orgs/{org}/packages", - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - "GET /orgs/{org}/personal-access-token-requests", - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", - "GET /orgs/{org}/personal-access-tokens", - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", - "GET /orgs/{org}/projects", - "GET /orgs/{org}/properties/values", - "GET /orgs/{org}/public_members", - "GET /orgs/{org}/repos", - "GET /orgs/{org}/rulesets", - "GET /orgs/{org}/rulesets/rule-suites", - "GET /orgs/{org}/secret-scanning/alerts", - "GET /orgs/{org}/security-advisories", - "GET /orgs/{org}/teams", - "GET /orgs/{org}/teams/{team_slug}/discussions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/invitations", - "GET /orgs/{org}/teams/{team_slug}/members", - "GET /orgs/{org}/teams/{team_slug}/projects", - "GET /orgs/{org}/teams/{team_slug}/repos", - "GET /orgs/{org}/teams/{team_slug}/teams", - "GET /projects/columns/{column_id}/cards", - "GET /projects/{project_id}/collaborators", - "GET /projects/{project_id}/columns", - "GET /repos/{owner}/{repo}/actions/artifacts", - "GET /repos/{owner}/{repo}/actions/caches", - "GET /repos/{owner}/{repo}/actions/organization-secrets", - "GET /repos/{owner}/{repo}/actions/organization-variables", - "GET /repos/{owner}/{repo}/actions/runners", - "GET /repos/{owner}/{repo}/actions/runs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", - "GET /repos/{owner}/{repo}/actions/secrets", - "GET /repos/{owner}/{repo}/actions/variables", - "GET /repos/{owner}/{repo}/actions/workflows", - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", - "GET /repos/{owner}/{repo}/activity", - "GET /repos/{owner}/{repo}/assignees", - "GET /repos/{owner}/{repo}/branches", - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", - "GET /repos/{owner}/{repo}/code-scanning/alerts", - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - "GET /repos/{owner}/{repo}/code-scanning/analyses", - "GET /repos/{owner}/{repo}/codespaces", - "GET /repos/{owner}/{repo}/codespaces/devcontainers", - "GET /repos/{owner}/{repo}/codespaces/secrets", - "GET /repos/{owner}/{repo}/collaborators", - "GET /repos/{owner}/{repo}/comments", - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/commits", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", - "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", - "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", - "GET /repos/{owner}/{repo}/commits/{ref}/status", - "GET /repos/{owner}/{repo}/commits/{ref}/statuses", - "GET /repos/{owner}/{repo}/contributors", - "GET /repos/{owner}/{repo}/dependabot/alerts", - "GET /repos/{owner}/{repo}/dependabot/secrets", - "GET /repos/{owner}/{repo}/deployments", - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", - "GET /repos/{owner}/{repo}/environments", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", - "GET /repos/{owner}/{repo}/events", - "GET /repos/{owner}/{repo}/forks", - "GET /repos/{owner}/{repo}/hooks", - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", - "GET /repos/{owner}/{repo}/invitations", - "GET /repos/{owner}/{repo}/issues", - "GET /repos/{owner}/{repo}/issues/comments", - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/issues/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", - "GET /repos/{owner}/{repo}/issues/{issue_number}/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", - "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", - "GET /repos/{owner}/{repo}/keys", - "GET /repos/{owner}/{repo}/labels", - "GET /repos/{owner}/{repo}/milestones", - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", - "GET /repos/{owner}/{repo}/notifications", - "GET /repos/{owner}/{repo}/pages/builds", - "GET /repos/{owner}/{repo}/projects", - "GET /repos/{owner}/{repo}/pulls", - "GET /repos/{owner}/{repo}/pulls/comments", - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", - "GET /repos/{owner}/{repo}/releases", - "GET /repos/{owner}/{repo}/releases/{release_id}/assets", - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", - "GET /repos/{owner}/{repo}/rules/branches/{branch}", - "GET /repos/{owner}/{repo}/rulesets", - "GET /repos/{owner}/{repo}/rulesets/rule-suites", - "GET /repos/{owner}/{repo}/secret-scanning/alerts", - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", - "GET /repos/{owner}/{repo}/security-advisories", - "GET /repos/{owner}/{repo}/stargazers", - "GET /repos/{owner}/{repo}/subscribers", - "GET /repos/{owner}/{repo}/tags", - "GET /repos/{owner}/{repo}/teams", - "GET /repos/{owner}/{repo}/topics", - "GET /repositories", - "GET /repositories/{repository_id}/environments/{environment_name}/secrets", - "GET /repositories/{repository_id}/environments/{environment_name}/variables", - "GET /search/code", - "GET /search/commits", - "GET /search/issues", - "GET /search/labels", - "GET /search/repositories", - "GET /search/topics", - "GET /search/users", - "GET /teams/{team_id}/discussions", - "GET /teams/{team_id}/discussions/{discussion_number}/comments", - "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /teams/{team_id}/discussions/{discussion_number}/reactions", - "GET /teams/{team_id}/invitations", - "GET /teams/{team_id}/members", - "GET /teams/{team_id}/projects", - "GET /teams/{team_id}/repos", - "GET /teams/{team_id}/teams", - "GET /user/blocks", - "GET /user/codespaces", - "GET /user/codespaces/secrets", - "GET /user/emails", - "GET /user/followers", - "GET /user/following", - "GET /user/gpg_keys", - "GET /user/installations", - "GET /user/installations/{installation_id}/repositories", - "GET /user/issues", - "GET /user/keys", - "GET /user/marketplace_purchases", - "GET /user/marketplace_purchases/stubbed", - "GET /user/memberships/orgs", - "GET /user/migrations", - "GET /user/migrations/{migration_id}/repositories", - "GET /user/orgs", - "GET /user/packages", - "GET /user/packages/{package_type}/{package_name}/versions", - "GET /user/public_emails", - "GET /user/repos", - "GET /user/repository_invitations", - "GET /user/social_accounts", - "GET /user/ssh_signing_keys", - "GET /user/starred", - "GET /user/subscriptions", - "GET /user/teams", - "GET /users", - "GET /users/{username}/events", - "GET /users/{username}/events/orgs/{org}", - "GET /users/{username}/events/public", - "GET /users/{username}/followers", - "GET /users/{username}/following", - "GET /users/{username}/gists", - "GET /users/{username}/gpg_keys", - "GET /users/{username}/keys", - "GET /users/{username}/orgs", - "GET /users/{username}/packages", - "GET /users/{username}/projects", - "GET /users/{username}/received_events", - "GET /users/{username}/received_events/public", - "GET /users/{username}/repos", - "GET /users/{username}/social_accounts", - "GET /users/{username}/ssh_signing_keys", - "GET /users/{username}/starred", - "GET /users/{username}/subscriptions" -]; - -// pkg/dist-src/paginating-endpoints.js -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } -} - -// pkg/dist-src/index.js -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 83044: -/***/ ((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, { - legacyRestEndpointMethods: () => legacyRestEndpointMethods, - restEndpointMethods: () => restEndpointMethods -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "10.4.1"; - -// pkg/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repositories/{repository_id}/environments/{environment_name}/variables" - ], - createOrUpdateEnvironmentSecret: [ - "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteEnvironmentSecret: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables" - ], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: [ - "DELETE /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" - } - ], - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getCommitAuthors: [ - "GET /repos/{owner}/{repo}/import/authors", - {}, - { - deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" - } - ], - getImportStatus: [ - "GET /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" - } - ], - getLargeFiles: [ - "GET /repos/{owner}/{repo}/import/large_files", - {}, - { - deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" - } - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - mapCommitAuthor: [ - "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", - {}, - { - deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" - } - ], - setLfsPreference: [ - "PATCH /repos/{owner}/{repo}/import/lfs", - {}, - { - deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" - } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: [ - "PUT /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" - } - ], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ], - updateImport: [ - "PATCH /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" - } - ] - }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] - }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}" - ], - assignTeamToOrgRole: [ - "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - assignUserToOrgRole: [ - "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], - createInvitation: ["POST /orgs/{org}/invitations"], - createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], - createOrUpdateCustomPropertiesValuesForRepos: [ - "PATCH /orgs/{org}/properties/values" - ], - createOrUpdateCustomProperty: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - createWebhook: ["POST /orgs/{org}/hooks"], - delete: ["DELETE /orgs/{org}"], - deleteCustomOrganizationRole: [ - "DELETE /orgs/{org}/organization-roles/{role_id}" - ], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - enableOrDisableSecurityProductOnAllOrgRepos: [ - "POST /orgs/{org}/{security_product}/{enablement}" - ], - get: ["GET /orgs/{org}"], - getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], - getCustomProperty: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], - listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], - listOrgRoles: ["GET /orgs/{org}/organization-roles"], - listOrganizationFineGrainedPermissions: [ - "GET /orgs/{org}/organization-fine-grained-permissions" - ], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - patchCustomOrganizationRole: [ - "PATCH /orgs/{org}/organization-roles/{role_id}" - ], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeCustomProperty: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}" - ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - revokeAllOrgRolesTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" - ], - revokeAllOrgRolesUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}" - ], - revokeOrgRoleTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - revokeOrgRoleUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" - ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" - ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" - ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" - ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } - ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } - ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" - ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" - ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" - ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" - ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" - ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], - createCard: ["POST /projects/columns/{column_id}/cards"], - createColumn: ["POST /projects/{project_id}/columns"], - createForAuthenticatedUser: ["POST /user/projects"], - createForOrg: ["POST /orgs/{org}/projects"], - createForRepo: ["POST /repos/{owner}/{repo}/projects"], - delete: ["DELETE /projects/{project_id}"], - deleteCard: ["DELETE /projects/columns/cards/{card_id}"], - deleteColumn: ["DELETE /projects/columns/{column_id}"], - get: ["GET /projects/{project_id}"], - getCard: ["GET /projects/columns/cards/{card_id}"], - getColumn: ["GET /projects/columns/{column_id}"], - getPermissionForUser: [ - "GET /projects/{project_id}/collaborators/{username}/permission" - ], - listCards: ["GET /projects/columns/{column_id}/cards"], - listCollaborators: ["GET /projects/{project_id}/collaborators"], - listColumns: ["GET /projects/{project_id}/columns"], - listForOrg: ["GET /orgs/{org}/projects"], - listForRepo: ["GET /repos/{owner}/{repo}/projects"], - listForUser: ["GET /users/{username}/projects"], - moveCard: ["POST /projects/columns/cards/{card_id}/moves"], - moveColumn: ["POST /projects/columns/{column_id}/moves"], - removeCollaborator: [ - "DELETE /projects/{project_id}/collaborators/{username}" - ], - update: ["PATCH /projects/{project_id}"], - updateCard: ["PATCH /projects/columns/cards/{card_id}"], - updateColumn: ["PATCH /projects/columns/{column_id}"] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" - ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" - ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" - ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" - ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" - ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" - ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" - ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" - ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" - ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" - ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } - ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" - ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - cancelPagesDeployment: [ - "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" - ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" - ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" - ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" - ], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateCustomPropertiesValues: [ - "PATCH /repos/{owner}/{repo}/properties/values" - ], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" - ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" - ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } - ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" - ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" - ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" - ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" - ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteTagProtection: [ - "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" - ], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" - ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" - ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } - ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" - ], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" - ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" - ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" - ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" - ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" - ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" - ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" - ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" - ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesDeployment: [ - "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" - ], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" - ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" - ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" - ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" - ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" - ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" - ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" - ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" - ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" - ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" - ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" - ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } - ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/secret-scanning/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ] - }, - securityAdvisories: { - createFork: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" - ], - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" - ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" - ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" - ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - addOrUpdateProjectPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - checkPermissionsForProjectInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" - ], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - removeProjectInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", - {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } - ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } - ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } - ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } - ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } - ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } - ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } - ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } - ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - list: ["GET /users"], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } - ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } - ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } - ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } - ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } - ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } - ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } - ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" - ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// pkg/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url - }, - defaults - ); - if (!endpointMethodsMap.has(scope)) { - endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope).set(methodName, { - scope, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope }, methodName) { - return endpointMethodsMap.get(scope).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope }) { - return [...endpointMethodsMap.get(scope).keys()]; - }, - set(target, methodName, value) { - return target.cache[methodName] = value; - }, - get({ octokit, scope, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args) { - let options = requestWithDefaults.endpoint.merge(...args); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// pkg/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION; -// 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( - /(? { - -"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.4.1"; - -// 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, _d; - 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, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.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); - - -/***/ }), - -/***/ 252: -/***/ ((module) => { - -"use strict"; - -module.exports = asPromise; - -/** - * Callback as used by {@link util.asPromise}. - * @typedef asPromiseCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {...*} params Additional arguments - * @returns {undefined} - */ - -/** - * Returns a promise from a node-style callback function. - * @memberof util - * @param {asPromiseCallback} fn Function to call - * @param {*} ctx Function context - * @param {...*} params Function arguments - * @returns {Promise<*>} Promisified function - */ -function asPromise(fn, ctx/*, varargs */) { - var params = new Array(arguments.length - 1), - offset = 0, - index = 2, - pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err/*, varargs */) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params = new Array(arguments.length - 1), - offset = 0; - while (offset < params.length) - params[offset++] = arguments[offset]; - resolve.apply(null, params); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } - } - }); -} - - -/***/ }), - -/***/ 26718: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal base64 implementation for number arrays. - * @memberof util - * @namespace - */ -var base64 = exports; - -/** - * Calculates the byte length of a base64 encoded string. - * @param {string} string Base64 encoded string - * @returns {number} Byte length - */ -base64.length = function length(string) { - var p = string.length; - if (!p) - return 0; - var n = 0; - while (--p % 4 > 1 && string.charAt(p) === "=") - ++n; - return Math.ceil(string.length * 3) / 4 - n; -}; - -// Base64 encoding table -var b64 = new Array(64); - -// Base64 decoding table -var s64 = new Array(123); - -// 65..90, 97..122, 48..57, 43, 47 -for (var i = 0; i < 64;) - s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; - -/** - * Encodes a buffer to a base64 encoded string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} Base64 encoded string - */ -base64.encode = function encode(buffer, start, end) { - var parts = null, - chunk = []; - var i = 0, // output index - j = 0, // goto index - t; // temporary - while (start < end) { - var b = buffer[start++]; - switch (j) { - case 0: - chunk[i++] = b64[b >> 2]; - t = (b & 3) << 4; - j = 1; - break; - case 1: - chunk[i++] = b64[t | b >> 4]; - t = (b & 15) << 2; - j = 2; - break; - case 2: - chunk[i++] = b64[t | b >> 6]; - chunk[i++] = b64[b & 63]; - j = 0; - break; - } - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (j) { - chunk[i++] = b64[t]; - chunk[i++] = 61; - if (j === 1) - chunk[i++] = 61; - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -var invalidEncoding = "invalid encoding"; - -/** - * Decodes a base64 encoded string to a buffer. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Number of bytes written - * @throws {Error} If encoding is invalid - */ -base64.decode = function decode(string, buffer, offset) { - var start = offset; - var j = 0, // goto index - t; // temporary - for (var i = 0; i < string.length;) { - var c = string.charCodeAt(i++); - if (c === 61 && j > 1) - break; - if ((c = s64[c]) === undefined) - throw Error(invalidEncoding); - switch (j) { - case 0: - t = c; - j = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c & 48) >> 4; - t = c; - j = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; - t = c; - j = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c; - j = 0; - break; - } - } - if (j === 1) - throw Error(invalidEncoding); - return offset - start; -}; - -/** - * Tests if the specified string appears to be base64 encoded. - * @param {string} string String to test - * @returns {boolean} `true` if probably base64 encoded, otherwise false - */ -base64.test = function test(string) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); -}; - - -/***/ }), - -/***/ 58882: -/***/ ((module) => { - -"use strict"; - -module.exports = codegen; - -/** - * Begins generating a function. - * @memberof util - * @param {string[]} functionParams Function parameter names - * @param {string} [functionName] Function name if not anonymous - * @returns {Codegen} Appender that appends code to the function's body - */ -function codegen(functionParams, functionName) { - - /* istanbul ignore if */ - if (typeof functionParams === "string") { - functionName = functionParams; - functionParams = undefined; - } - - var body = []; - - /** - * Appends code to the function's body or finishes generation. - * @typedef Codegen - * @type {function} - * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any - * @param {...*} [formatParams] Format parameters - * @returns {Codegen|Function} Itself or the generated function if finished - * @throws {Error} If format parameter counts do not match - */ - - function Codegen(formatStringOrScope) { - // note that explicit array handling below makes this ~50% faster - - // finish the function - if (typeof formatStringOrScope !== "string") { - var source = toString(); - if (codegen.verbose) - console.log("codegen: " + source); // eslint-disable-line no-console - source = "return " + source; - if (formatStringOrScope) { - var scopeKeys = Object.keys(formatStringOrScope), - scopeParams = new Array(scopeKeys.length + 1), - scopeValues = new Array(scopeKeys.length), - scopeOffset = 0; - while (scopeOffset < scopeKeys.length) { - scopeParams[scopeOffset] = scopeKeys[scopeOffset]; - scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; - } - scopeParams[scopeOffset] = source; - return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func - } - return Function(source)(); // eslint-disable-line no-new-func - } - - // otherwise append to body - var formatParams = new Array(arguments.length - 1), - formatOffset = 0; - while (formatOffset < formatParams.length) - formatParams[formatOffset] = arguments[++formatOffset]; - formatOffset = 0; - formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { - var value = formatParams[formatOffset++]; - switch ($1) { - case "d": case "f": return String(Number(value)); - case "i": return String(Math.floor(value)); - case "j": return JSON.stringify(value); - case "s": return String(value); - } - return "%"; - }); - if (formatOffset !== formatParams.length) - throw Error("parameter count mismatch"); - body.push(formatStringOrScope); - return Codegen; - } - - function toString(functionNameOverride) { - return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; - } - - Codegen.toString = toString; - return Codegen; -} - -/** - * Begins generating a function. - * @memberof util - * @function codegen - * @param {string} [functionName] Function name if not anonymous - * @returns {Codegen} Appender that appends code to the function's body - * @variation 2 - */ - -/** - * When set to `true`, codegen will log generated code to console. Useful for debugging. - * @name util.codegen.verbose - * @type {boolean} - */ -codegen.verbose = false; - - -/***/ }), - -/***/ 86850: -/***/ ((module) => { - -"use strict"; - -module.exports = EventEmitter; - -/** - * Constructs a new event emitter instance. - * @classdesc A minimal event emitter. - * @memberof util - * @constructor - */ -function EventEmitter() { - - /** - * Registered listeners. - * @type {Object.} - * @private - */ - this._listeners = {}; -} - -/** - * Registers an event listener. - * @param {string} evt Event name - * @param {function} fn Listener - * @param {*} [ctx] Listener context - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn : fn, - ctx : ctx || this - }); - return this; -}; - -/** - * Removes an event listener or any matching listeners if arguments are omitted. - * @param {string} [evt] Event name. Removes all listeners if omitted. - * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.off = function off(evt, fn) { - if (evt === undefined) - this._listeners = {}; - else { - if (fn === undefined) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i = 0; i < listeners.length;) - if (listeners[i].fn === fn) - listeners.splice(i, 1); - else - ++i; - } - } - return this; -}; - -/** - * Emits an event by calling its listeners with the specified arguments. - * @param {string} evt Event name - * @param {...*} args Arguments - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], - i = 1; - for (; i < arguments.length;) - args.push(arguments[i++]); - for (i = 0; i < listeners.length;) - listeners[i].fn.apply(listeners[i++].ctx, args); - } - return this; -}; - - -/***/ }), - -/***/ 50663: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = fetch; - -var asPromise = __nccwpck_require__(252), - inquire = __nccwpck_require__(60094); - -var fs = inquire("fs"); - -/** - * Node-style callback as used by {@link util.fetch}. - * @typedef FetchCallback - * @type {function} - * @param {?Error} error Error, if any, otherwise `null` - * @param {string} [contents] File contents, if there hasn't been an error - * @returns {undefined} - */ - -/** - * Options as used by {@link util.fetch}. - * @typedef FetchOptions - * @type {Object} - * @property {boolean} [binary=false] Whether expecting a binary response - * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest - */ - -/** - * Fetches the contents of a file. - * @memberof util - * @param {string} filename File path or url - * @param {FetchOptions} options Fetch options - * @param {FetchCallback} callback Callback function - * @returns {undefined} - */ -function fetch(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } else if (!options) - options = {}; - - if (!callback) - return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this - - // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. - if (!options.xhr && fs && fs.readFile) - return fs.readFile(filename, function fetchReadFileCallback(err, contents) { - return err && typeof XMLHttpRequest !== "undefined" - ? fetch.xhr(filename, options, callback) - : err - ? callback(err) - : callback(null, options.binary ? contents : contents.toString("utf8")); - }); - - // use the XHR version otherwise. - return fetch.xhr(filename, options, callback); -} - -/** - * Fetches the contents of a file. - * @name util.fetch - * @function - * @param {string} path File path or url - * @param {FetchCallback} callback Callback function - * @returns {undefined} - * @variation 2 - */ - -/** - * Fetches the contents of a file. - * @name util.fetch - * @function - * @param {string} path File path or url - * @param {FetchOptions} [options] Fetch options - * @returns {Promise} Promise - * @variation 3 - */ - -/**/ -fetch.xhr = function fetch_xhr(filename, options, callback) { - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { - - if (xhr.readyState !== 4) - return undefined; - - // local cors security errors return status 0 / empty string, too. afaik this cannot be - // reliably distinguished from an actually empty file for security reasons. feel free - // to send a pull request if you are aware of a solution. - if (xhr.status !== 0 && xhr.status !== 200) - return callback(Error("status " + xhr.status)); - - // if binary data is expected, make sure that some sort of array is returned, even if - // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. - if (options.binary) { - var buffer = xhr.response; - if (!buffer) { - buffer = []; - for (var i = 0; i < xhr.responseText.length; ++i) - buffer.push(xhr.responseText.charCodeAt(i) & 255); - } - return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); - } - return callback(null, xhr.responseText); - }; - - if (options.binary) { - // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers - if ("overrideMimeType" in xhr) - xhr.overrideMimeType("text/plain; charset=x-user-defined"); - xhr.responseType = "arraybuffer"; - } - - xhr.open("GET", filename); - xhr.send(); -}; - - -/***/ }), - -/***/ 21843: -/***/ ((module) => { - -"use strict"; - - -module.exports = factory(factory); - -/** - * Reads / writes floats / doubles from / to buffers. - * @name util.float - * @namespace - */ - -/** - * Writes a 32 bit float to a buffer using little endian byte order. - * @name util.float.writeFloatLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 32 bit float to a buffer using big endian byte order. - * @name util.float.writeFloatBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 32 bit float from a buffer using little endian byte order. - * @name util.float.readFloatLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 32 bit float from a buffer using big endian byte order. - * @name util.float.readFloatBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Writes a 64 bit double to a buffer using little endian byte order. - * @name util.float.writeDoubleLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 64 bit double to a buffer using big endian byte order. - * @name util.float.writeDoubleBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 64 bit double from a buffer using little endian byte order. - * @name util.float.readDoubleLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 64 bit double from a buffer using big endian byte order. - * @name util.float.readDoubleBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -// Factory function for the purpose of node-based testing in modified global environments -function factory(exports) { - - // float: typed array - if (typeof Float32Array !== "undefined") (function() { - - var f32 = new Float32Array([ -0 ]), - f8b = new Uint8Array(f32.buffer), - le = f8b[3] === 128; - - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - /* istanbul ignore next */ - exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos ]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - - /* istanbul ignore next */ - exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - /* istanbul ignore next */ - exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - - // float: ieee754 - })(); else (function() { - - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 3.4028234663852886e+38) // +-Infinity - writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 1.1754943508222875e-38) // denormal - writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), - mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } - } - - exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), - sign = (uint >> 31) * 2 + 1, - exponent = uint >>> 23 & 255, - mantissa = uint & 8388607; - return exponent === 255 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 1.401298464324817e-45 * mantissa - : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); - } - - exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - - })(); - - // double: typed array - if (typeof Float64Array !== "undefined") (function() { - - var f64 = new Float64Array([-0]), - f8b = new Uint8Array(f64.buffer), - le = f8b[7] === 128; - - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - /* istanbul ignore next */ - exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos ]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - - /* istanbul ignore next */ - exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - /* istanbul ignore next */ - exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - - // double: ieee754 - })(); else (function() { - - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 1.7976931348623157e+308) { // +-Infinity - writeUint(0, buf, pos + off0); - writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 2.2250738585072014e-308) { // denormal - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - - exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), - hi = readUint(buf, pos + off1); - var sign = (hi >> 31) * 2 + 1, - exponent = hi >>> 20 & 2047, - mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 5e-324 * mantissa - : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - - exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - - })(); - - return exports; -} - -// uint helpers - -function writeUintLE(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; -} - -function writeUintBE(val, buf, pos) { - buf[pos ] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; -} - -function readUintLE(buf, pos) { - return (buf[pos ] - | buf[pos + 1] << 8 - | buf[pos + 2] << 16 - | buf[pos + 3] << 24) >>> 0; -} - -function readUintBE(buf, pos) { - return (buf[pos ] << 24 - | buf[pos + 1] << 16 - | buf[pos + 2] << 8 - | buf[pos + 3]) >>> 0; -} - - -/***/ }), - -/***/ 60094: -/***/ ((module) => { - -"use strict"; - -module.exports = inquire; - -/** - * Requires a module only if available. - * @memberof util - * @param {string} moduleName Module to require - * @returns {?Object} Required module if available and not empty, otherwise `null` - */ -function inquire(moduleName) { - try { - var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval - if (mod && (mod.length || Object.keys(mod).length)) - return mod; - } catch (e) {} // eslint-disable-line no-empty - return null; -} - - -/***/ }), - -/***/ 24761: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal path module to resolve Unix, Windows and URL paths alike. - * @memberof util - * @namespace - */ -var path = exports; - -var isAbsolute = -/** - * Tests if the specified path is absolute. - * @param {string} path Path to test - * @returns {boolean} `true` if path is absolute - */ -path.isAbsolute = function isAbsolute(path) { - return /^(?:\/|\w+:)/.test(path); -}; - -var normalize = -/** - * Normalizes the specified path. - * @param {string} path Path to normalize - * @returns {string} Normalized path - */ -path.normalize = function normalize(path) { - path = path.replace(/\\/g, "/") - .replace(/\/{2,}/g, "/"); - var parts = path.split("/"), - absolute = isAbsolute(path), - prefix = ""; - if (absolute) - prefix = parts.shift() + "/"; - for (var i = 0; i < parts.length;) { - if (parts[i] === "..") { - if (i > 0 && parts[i - 1] !== "..") - parts.splice(--i, 2); - else if (absolute) - parts.splice(i, 1); - else - ++i; - } else if (parts[i] === ".") - parts.splice(i, 1); - else - ++i; - } - return prefix + parts.join("/"); -}; - -/** - * Resolves the specified include path against the specified origin path. - * @param {string} originPath Path to the origin file - * @param {string} includePath Include path relative to origin path - * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized - * @returns {string} Path to the include file - */ -path.resolve = function resolve(originPath, includePath, alreadyNormalized) { - if (!alreadyNormalized) - includePath = normalize(includePath); - if (isAbsolute(includePath)) - return includePath; - if (!alreadyNormalized) - originPath = normalize(originPath); - return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; -}; - - -/***/ }), - -/***/ 47743: -/***/ ((module) => { - -"use strict"; - -module.exports = pool; - -/** - * An allocator as used by {@link util.pool}. - * @typedef PoolAllocator - * @type {function} - * @param {number} size Buffer size - * @returns {Uint8Array} Buffer - */ - -/** - * A slicer as used by {@link util.pool}. - * @typedef PoolSlicer - * @type {function} - * @param {number} start Start offset - * @param {number} end End offset - * @returns {Uint8Array} Buffer slice - * @this {Uint8Array} - */ - -/** - * A general purpose buffer pool. - * @memberof util - * @function - * @param {PoolAllocator} alloc Allocator - * @param {PoolSlicer} slice Slicer - * @param {number} [size=8192] Slab size - * @returns {PoolAllocator} Pooled allocator - */ -function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size) { - if (size < 1 || size > MAX) - return alloc(size); - if (offset + size > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size); - if (offset & 7) // align to 32 bit - offset = (offset | 7) + 1; - return buf; - }; -} - - -/***/ }), - -/***/ 99049: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * A minimal UTF8 implementation for number arrays. - * @memberof util - * @namespace - */ -var utf8 = exports; - -/** - * Calculates the UTF8 byte length of a string. - * @param {string} string String - * @returns {number} Byte length - */ -utf8.length = function utf8_length(string) { - var len = 0, - c = 0; - for (var i = 0; i < string.length; ++i) { - c = string.charCodeAt(i); - if (c < 128) - len += 1; - else if (c < 2048) - len += 2; - else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { - ++i; - len += 4; - } else - len += 3; - } - return len; -}; - -/** - * Reads UTF8 bytes as a string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} String read - */ -utf8.read = function utf8_read(buffer, start, end) { - var len = end - start; - if (len < 1) - return ""; - var parts = null, - chunk = [], - i = 0, // char offset - t; // temporary - while (start < end) { - t = buffer[start++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; - chunk[i++] = 0xD800 + (t >> 10); - chunk[i++] = 0xDC00 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -/** - * Writes a string as UTF8 bytes. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Bytes written - */ -utf8.write = function utf8_write(string, buffer, offset) { - var start = offset, - c1, // character 1 - c2; // character 2 - for (var i = 0; i < string.length; ++i) { - c1 = string.charCodeAt(i); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { - c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); - ++i; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } - } - return offset - start; -}; - - -/***/ }), - -/***/ 79809: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(96575)); -const AuthAdminApi = GoTrueAdminApi_1.default; -exports["default"] = AuthAdminApi; -//# sourceMappingURL=AuthAdminApi.js.map - -/***/ }), - -/***/ 34525: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(20313)); -const AuthClient = GoTrueClient_1.default; -exports["default"] = AuthClient; -//# sourceMappingURL=AuthClient.js.map - -/***/ }), - -/***/ 96575: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const fetch_1 = __nccwpck_require__(17072); -const helpers_1 = __nccwpck_require__(54044); -const types_1 = __nccwpck_require__(1852); -const errors_1 = __nccwpck_require__(99938); -class GoTrueAdminApi { - constructor({ url = '', headers = {}, fetch, }) { - this.url = url; - this.headers = headers; - this.fetch = (0, helpers_1.resolveFetch)(fetch); - this.mfa = { - listFactors: this._listFactors.bind(this), - deleteFactor: this._deleteFactor.bind(this), - }; - this.oauth = { - listClients: this._listOAuthClients.bind(this), - createClient: this._createOAuthClient.bind(this), - getClient: this._getOAuthClient.bind(this), - updateClient: this._updateOAuthClient.bind(this), - deleteClient: this._deleteOAuthClient.bind(this), - regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this), - }; - } - /** - * Removes a logged-in session. - * @param jwt A valid, logged-in JWT. - * @param scope The logout sope. - */ - async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) { - if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) { - throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`); - } - try { - await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { - headers: this.headers, - jwt, - noResolveJson: true, - }); - return { data: null, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Sends an invite link to an email address. - * @param email The email address of the user. - * @param options Additional options to be included when inviting. - */ - async inviteUserByEmail(email, options = {}) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, { - body: { email, data: options.data }, - headers: this.headers, - redirectTo: options.redirectTo, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Generates email links and OTPs to be sent via a custom email provider. - * @param email The user's email. - * @param options.password User password. For signup only. - * @param options.data Optional user metadata. For signup only. - * @param options.redirectTo The redirect url which should be appended to the generated link - */ - async generateLink(params) { - try { - const { options } = params, rest = tslib_1.__rest(params, ["options"]); - const body = Object.assign(Object.assign({}, rest), options); - if ('newEmail' in rest) { - // replace newEmail with new_email in request body - body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; - delete body['newEmail']; - } - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, { - body: body, - headers: this.headers, - xform: fetch_1._generateLinkResponse, - redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { - data: { - properties: null, - user: null, - }, - error, - }; - } - throw error; - } - } - // User Admin API - /** - * Creates a new user. - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async createUser(attributes) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, { - body: attributes, - headers: this.headers, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Get a list of users. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. - */ - async listUsers(params) { - var _a, _b, _c, _d, _e, _f, _g; - try { - const pagination = { nextPage: null, lastPage: 0, total: 0 }; - const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, { - headers: this.headers, - noResolveJson: true, - query: { - page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', - per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', - }, - xform: fetch_1._noResolveJsonResponse, - }); - if (response.error) - throw response.error; - const users = await response.json(); - const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; - const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; - if (links.length > 0) { - links.forEach((link) => { - const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); - const rel = JSON.parse(link.split(';')[1].split('=')[1]); - pagination[`${rel}Page`] = page; - }); - pagination.total = parseInt(total); - } - return { data: Object.assign(Object.assign({}, users), pagination), error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { users: [] }, error }; - } - throw error; - } - } - /** - * Get user by id. - * - * @param uid The user's unique identifier - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async getUserById(uid) { - (0, helpers_1.validateUUID)(uid); - try { - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { - headers: this.headers, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Updates the user data. - * - * @param attributes The data you want to update. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async updateUserById(uid, attributes) { - (0, helpers_1.validateUUID)(uid); - try { - return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { - body: attributes, - headers: this.headers, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Delete a user. Requires a `service_role` key. - * - * @param id The user id you want to remove. - * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. - * Defaults to false for backward compatibility. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async deleteUser(id, shouldSoftDelete = false) { - (0, helpers_1.validateUUID)(id); - try { - return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { - headers: this.headers, - body: { - should_soft_delete: shouldSoftDelete, - }, - xform: fetch_1._userResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - async _listFactors(params) { - (0, helpers_1.validateUUID)(params.userId); - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { - headers: this.headers, - xform: (factors) => { - return { data: { factors }, error: null }; - }, - }); - return { data, error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async _deleteFactor(params) { - (0, helpers_1.validateUUID)(params.userId); - (0, helpers_1.validateUUID)(params.id); - try { - const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Lists all OAuth clients with optional pagination. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _listOAuthClients(params) { - var _a, _b, _c, _d, _e, _f, _g; - try { - const pagination = { nextPage: null, lastPage: 0, total: 0 }; - const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, { - headers: this.headers, - noResolveJson: true, - query: { - page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', - per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', - }, - xform: fetch_1._noResolveJsonResponse, - }); - if (response.error) - throw response.error; - const clients = await response.json(); - const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; - const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; - if (links.length > 0) { - links.forEach((link) => { - const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); - const rel = JSON.parse(link.split(';')[1].split('=')[1]); - pagination[`${rel}Page`] = page; - }); - pagination.total = parseInt(total); - } - return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { clients: [] }, error }; - } - throw error; - } - } - /** - * Creates a new OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _createOAuthClient(params) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, { - body: params, - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Gets details of a specific OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _getOAuthClient(clientId) { - try { - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, { - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Updates an existing OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _updateOAuthClient(clientId, params) { - try { - return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, { - body: params, - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Deletes an OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _deleteOAuthClient(clientId) { - try { - await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, { - headers: this.headers, - noResolveJson: true, - }); - return { data: null, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Regenerates the secret for an OAuth client. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * This function should only be called on a server. Never expose your `service_role` key in the browser. - */ - async _regenerateOAuthClientSecret(clientId) { - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { - headers: this.headers, - xform: (client) => { - return { data: client, error: null }; - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } -} -exports["default"] = GoTrueAdminApi; -//# sourceMappingURL=GoTrueAdminApi.js.map - -/***/ }), - -/***/ 20313: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(96575)); -const constants_1 = __nccwpck_require__(90518); -const errors_1 = __nccwpck_require__(99938); -const fetch_1 = __nccwpck_require__(17072); -const helpers_1 = __nccwpck_require__(54044); -const local_storage_1 = __nccwpck_require__(81479); -const locks_1 = __nccwpck_require__(60163); -const polyfills_1 = __nccwpck_require__(81897); -const version_1 = __nccwpck_require__(86677); -const base64url_1 = __nccwpck_require__(6677); -const ethereum_1 = __nccwpck_require__(51418); -const webauthn_1 = __nccwpck_require__(59451); -(0, polyfills_1.polyfillGlobalThis)(); // Make "globalThis" available -const DEFAULT_OPTIONS = { - url: constants_1.GOTRUE_URL, - storageKey: constants_1.STORAGE_KEY, - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true, - headers: constants_1.DEFAULT_HEADERS, - flowType: 'implicit', - debug: false, - hasCustomAuthorizationHeader: false, -}; -async function lockNoOp(name, acquireTimeout, fn) { - return await fn(); -} -/** - * Caches JWKS values for all clients created in the same environment. This is - * especially useful for shared-memory execution environments such as Vercel's - * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how - * many clients are created, if they share the same storage key they will use - * the same JWKS cache, significantly speeding up getClaims() with asymmetric - * JWTs. - */ -const GLOBAL_JWKS = {}; -class GoTrueClient { - /** - * The JWKS used for verifying asymmetric JWTs - */ - get jwks() { - var _a, _b; - return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; - } - set jwks(value) { - GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); - } - get jwks_cached_at() { - var _a, _b; - return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; - } - set jwks_cached_at(value) { - GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); - } - /** - * Create a new client for use in the browser. - */ - constructor(options) { - var _a, _b; - /** - * @experimental - */ - this.userStorage = null; - this.memoryStorage = null; - this.stateChangeEmitters = new Map(); - this.autoRefreshTicker = null; - this.visibilityChangedCallback = null; - this.refreshingDeferred = null; - /** - * Keeps track of the async client initialization. - * When null or not yet resolved the auth state is `unknown` - * Once resolved the auth state is known and it's safe to call any further client methods. - * Keep extra care to never reject or throw uncaught errors - */ - this.initializePromise = null; - this.detectSessionInUrl = true; - this.hasCustomAuthorizationHeader = false; - this.suppressGetSessionWarning = false; - this.lockAcquired = false; - this.pendingInLock = []; - /** - * Used to broadcast state change events to other tabs listening. - */ - this.broadcastChannel = null; - this.logger = console.log; - this.instanceID = GoTrueClient.nextInstanceID; - GoTrueClient.nextInstanceID += 1; - if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { - console.warn('Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.'); - } - const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); - this.logDebugMessages = !!settings.debug; - if (typeof settings.debug === 'function') { - this.logger = settings.debug; - } - this.persistSession = settings.persistSession; - this.storageKey = settings.storageKey; - this.autoRefreshToken = settings.autoRefreshToken; - this.admin = new GoTrueAdminApi_1.default({ - url: settings.url, - headers: settings.headers, - fetch: settings.fetch, - }); - this.url = settings.url; - this.headers = settings.headers; - this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); - this.lock = settings.lock || lockNoOp; - this.detectSessionInUrl = settings.detectSessionInUrl; - this.flowType = settings.flowType; - this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; - if (settings.lock) { - this.lock = settings.lock; - } - else if ((0, helpers_1.isBrowser)() && ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _a === void 0 ? void 0 : _a.locks)) { - this.lock = locks_1.navigatorLock; - } - else { - this.lock = lockNoOp; - } - if (!this.jwks) { - this.jwks = { keys: [] }; - this.jwks_cached_at = Number.MIN_SAFE_INTEGER; - } - this.mfa = { - verify: this._verify.bind(this), - enroll: this._enroll.bind(this), - unenroll: this._unenroll.bind(this), - challenge: this._challenge.bind(this), - listFactors: this._listFactors.bind(this), - challengeAndVerify: this._challengeAndVerify.bind(this), - getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), - webauthn: new webauthn_1.WebAuthnApi(this), - }; - this.oauth = { - getAuthorizationDetails: this._getAuthorizationDetails.bind(this), - approveAuthorization: this._approveAuthorization.bind(this), - denyAuthorization: this._denyAuthorization.bind(this), - }; - if (this.persistSession) { - if (settings.storage) { - this.storage = settings.storage; - } - else { - if ((0, helpers_1.supportsLocalStorage)()) { - this.storage = globalThis.localStorage; - } - else { - this.memoryStorage = {}; - this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); - } - } - if (settings.userStorage) { - this.userStorage = settings.userStorage; - } - } - else { - this.memoryStorage = {}; - this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); - } - if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { - try { - this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); - } - catch (e) { - console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); - } - (_b = this.broadcastChannel) === null || _b === void 0 ? void 0 : _b.addEventListener('message', async (event) => { - this._debug('received broadcast notification from other tab or client', event); - await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages - }); - } - this.initialize(); - } - _debug(...args) { - if (this.logDebugMessages) { - this.logger(`GoTrueClient@${this.instanceID} (${version_1.version}) ${new Date().toISOString()}`, ...args); - } - return this; - } - /** - * Initializes the client session either from the url or from storage. - * This method is automatically called when instantiating the client, but should also be called - * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). - */ - async initialize() { - if (this.initializePromise) { - return await this.initializePromise; - } - this.initializePromise = (async () => { - return await this._acquireLock(-1, async () => { - return await this._initialize(); - }); - })(); - return await this.initializePromise; - } - /** - * IMPORTANT: - * 1. Never throw in this method, as it is called from the constructor - * 2. Never return a session from this method as it would be cached over - * the whole lifetime of the client - */ - async _initialize() { - var _a; - try { - const params = (0, helpers_1.parseParametersFromURL)(window.location.href); - let callbackUrlType = 'none'; - if (this._isImplicitGrantCallback(params)) { - callbackUrlType = 'implicit'; - } - else if (await this._isPKCECallback(params)) { - callbackUrlType = 'pkce'; - } - /** - * Attempt to get the session from the URL only if these conditions are fulfilled - * - * Note: If the URL isn't one of the callback url types (implicit or pkce), - * then there could be an existing session so we don't want to prematurely remove it - */ - if ((0, helpers_1.isBrowser)() && this.detectSessionInUrl && callbackUrlType !== 'none') { - const { data, error } = await this._getSessionFromURL(params, callbackUrlType); - if (error) { - this._debug('#_initialize()', 'error detecting session from URL', error); - if ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) { - const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; - if (errorCode === 'identity_already_exists' || - errorCode === 'identity_not_found' || - errorCode === 'single_identity_not_deletable') { - return { error }; - } - } - // failed login attempt via url, - // remove old session as in verifyOtp, signUp and signInWith* - await this._removeSession(); - return { error }; - } - const { session, redirectType } = data; - this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); - await this._saveSession(session); - setTimeout(async () => { - if (redirectType === 'recovery') { - await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); - } - else { - await this._notifyAllSubscribers('SIGNED_IN', session); - } - }, 0); - return { error: null }; - } - // no login attempt via callback url try to recover session from storage - await this._recoverAndRefresh(); - return { error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { error }; - } - return { - error: new errors_1.AuthUnknownError('Unexpected error during initialization', error), - }; - } - finally { - await this._handleVisibilityChange(); - this._debug('#_initialize()', 'end'); - } - } - /** - * Creates a new anonymous user. - * - * @returns A session where the is_anonymous claim in the access token JWT set to true - */ - async signInAnonymously(credentials) { - var _a, _b, _c; - try { - const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - body: { - data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, - gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - const { data, error } = res; - if (error || !data) { - return { data: { user: null, session: null }, error: error }; - } - const session = data.session; - const user = data.user; - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Creates a new user. - * - * Be aware that if a user account exists in the system you may get back an - * error message that attempts to hide this information from the user. - * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. - * - * @returns A logged-in session if the server has "autoconfirm" ON - * @returns A user if the server has "autoconfirm" OFF - */ - async signUp(credentials) { - var _a, _b, _c; - try { - let res; - if ('email' in credentials) { - const { email, password, options } = credentials; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - body: { - email, - password, - data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - }, - xform: fetch_1._sessionResponse, - }); - } - else if ('phone' in credentials) { - const { phone, password, options } = credentials; - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { - headers: this.headers, - body: { - phone, - password, - data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, - channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - } - else { - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); - } - const { data, error } = res; - if (error || !data) { - return { data: { user: null, session: null }, error: error }; - } - const session = data.session; - const user = data.user; - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in an existing user with an email and password or phone and password. - * - * Be aware that you may get back an error message that will not distinguish - * between the cases where the account does not exist or that the - * email/phone and password combination is wrong or that the account can only - * be accessed via social login. - */ - async signInWithPassword(credentials) { - try { - let res; - if ('email' in credentials) { - const { email, password, options } = credentials; - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { - headers: this.headers, - body: { - email, - password, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponsePassword, - }); - } - else if ('phone' in credentials) { - const { phone, password, options } = credentials; - res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { - headers: this.headers, - body: { - phone, - password, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponsePassword, - }); - } - else { - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); - } - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { data: { user: null, session: null }, error: new errors_1.AuthInvalidTokenResponseError() }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { - data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), - error, - }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in an existing user via a third-party provider. - * This method supports the PKCE flow. - */ - async signInWithOAuth(credentials) { - var _a, _b, _c, _d; - return await this._handleProviderSignIn(credentials.provider, { - redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, - scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, - queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, - skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, - }); - } - /** - * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. - */ - async exchangeCodeForSession(authCode) { - await this.initializePromise; - return this._acquireLock(-1, async () => { - return this._exchangeCodeForSession(authCode); - }); - } - /** - * Signs in a user by verifying a message signed by the user's private key. - * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, - * both of which derive from the EIP-4361 standard - * With slight variation on Solana's side. - * @reference https://eips.ethereum.org/EIPS/eip-4361 - */ - async signInWithWeb3(credentials) { - const { chain } = credentials; - switch (chain) { - case 'ethereum': - return await this.signInWithEthereum(credentials); - case 'solana': - return await this.signInWithSolana(credentials); - default: - throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); - } - } - async signInWithEthereum(credentials) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; - // TODO: flatten type - let message; - let signature; - if ('message' in credentials) { - message = credentials.message; - signature = credentials.signature; - } - else { - const { chain, wallet, statement, options } = credentials; - let resolvedWallet; - if (!(0, helpers_1.isBrowser)()) { - if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { - throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); - } - resolvedWallet = wallet; - } - else if (typeof wallet === 'object') { - resolvedWallet = wallet; - } - else { - const windowAny = window; - if ('ethereum' in windowAny && - typeof windowAny.ethereum === 'object' && - 'request' in windowAny.ethereum && - typeof windowAny.ethereum.request === 'function') { - resolvedWallet = windowAny.ethereum; - } - else { - throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); - } - } - const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); - const accounts = await resolvedWallet - .request({ - method: 'eth_requestAccounts', - }) - .then((accs) => accs) - .catch(() => { - throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); - }); - if (!accounts || accounts.length === 0) { - throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); - } - const address = (0, ethereum_1.getAddress)(accounts[0]); - let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; - if (!chainId) { - const chainIdHex = await resolvedWallet.request({ - method: 'eth_chainId', - }); - chainId = (0, ethereum_1.fromHex)(chainIdHex); - } - const siweMessage = { - domain: url.host, - address: address, - statement: statement, - uri: url.href, - version: '1', - chainId: chainId, - nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, - issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : new Date(), - expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, - notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, - requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, - resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources, - }; - message = (0, ethereum_1.createSiweMessage)(siweMessage); - // Sign message - signature = (await resolvedWallet.request({ - method: 'personal_sign', - params: [(0, ethereum_1.toHex)(message), address], - })); - } - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { - headers: this.headers, - body: Object.assign({ chain: 'ethereum', message, - signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) - ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } - : null)), - xform: fetch_1._sessionResponse, - }); - if (error) { - throw error; - } - if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data: Object.assign({}, data), error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - async signInWithSolana(credentials) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; - let message; - let signature; - if ('message' in credentials) { - message = credentials.message; - signature = credentials.signature; - } - else { - const { chain, wallet, statement, options } = credentials; - let resolvedWallet; - if (!(0, helpers_1.isBrowser)()) { - if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { - throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); - } - resolvedWallet = wallet; - } - else if (typeof wallet === 'object') { - resolvedWallet = wallet; - } - else { - const windowAny = window; - if ('solana' in windowAny && - typeof windowAny.solana === 'object' && - (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || - ('signMessage' in windowAny.solana && - typeof windowAny.solana.signMessage === 'function'))) { - resolvedWallet = windowAny.solana; - } - else { - throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); - } - } - const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); - if ('signIn' in resolvedWallet && resolvedWallet.signIn) { - const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { - // non-overridable properties - version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null))); - let outputToProcess; - if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { - outputToProcess = output[0]; - } - else if (output && - typeof output === 'object' && - 'signedMessage' in output && - 'signature' in output) { - outputToProcess = output; - } - else { - throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value'); - } - if ('signedMessage' in outputToProcess && - 'signature' in outputToProcess && - (typeof outputToProcess.signedMessage === 'string' || - outputToProcess.signedMessage instanceof Uint8Array) && - outputToProcess.signature instanceof Uint8Array) { - message = - typeof outputToProcess.signedMessage === 'string' - ? outputToProcess.signedMessage - : new TextDecoder().decode(outputToProcess.signedMessage); - signature = outputToProcess.signature; - } - else { - throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'); - } - } - else { - if (!('signMessage' in resolvedWallet) || - typeof resolvedWallet.signMessage !== 'function' || - !('publicKey' in resolvedWallet) || - typeof resolvedWallet !== 'object' || - !resolvedWallet.publicKey || - !('toBase58' in resolvedWallet.publicKey) || - typeof resolvedWallet.publicKey.toBase58 !== 'function') { - throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'); - } - message = [ - `${url.host} wants you to sign in with your Solana account:`, - resolvedWallet.publicKey.toBase58(), - ...(statement ? ['', statement, ''] : ['']), - 'Version: 1', - `URI: ${url.href}`, - `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`, - ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) - ? [`Not Before: ${options.signInWithSolana.notBefore}`] - : []), - ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) - ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] - : []), - ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) - ? [`Chain ID: ${options.signInWithSolana.chainId}`] - : []), - ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), - ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) - ? [`Request ID: ${options.signInWithSolana.requestId}`] - : []), - ...(((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) - ? [ - 'Resources', - ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), - ] - : []), - ].join('\n'); - const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8'); - if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { - throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value'); - } - signature = maybeSignature; - } - } - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { - headers: this.headers, - body: Object.assign({ chain: 'solana', message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) - ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } - : null)), - xform: fetch_1._sessionResponse, - }); - if (error) { - throw error; - } - if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data: Object.assign({}, data), error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - async _exchangeCodeForSession(authCode) { - const storageItem = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); - try { - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { - headers: this.headers, - body: { - auth_code: authCode, - code_verifier: codeVerifier, - }, - xform: fetch_1._sessionResponse, - }); - await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - if (error) { - throw error; - } - if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null, redirectType: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null, redirectType: null }, error }; - } - throw error; - } - } - /** - * Allows signing in with an OIDC ID token. The authentication provider used - * should be enabled and configured. - */ - async signInWithIdToken(credentials) { - try { - const { options, provider, token, access_token, nonce } = credentials; - const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { - headers: this.headers, - body: { - provider, - id_token: token, - access_token, - nonce, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('SIGNED_IN', data.session); - } - return { data, error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in a user using magiclink or a one-time password (OTP). - * - * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. - * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. - * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. - * - * Be aware that you may get back an error message that will not distinguish - * between the cases where the account does not exist or, that the account - * can only be accessed via social login. - * - * Do note that you will need to configure a Whatsapp sender on Twilio - * if you are using phone sign in with the 'whatsapp' channel. The whatsapp - * channel is not supported on other providers - * at this time. - * This method supports PKCE when an email is passed. - */ - async signInWithOtp(credentials) { - var _a, _b, _c, _d, _e; - try { - if ('email' in credentials) { - const { email, options } = credentials; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - const { error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { - headers: this.headers, - body: { - email, - data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, - create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - }, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - }); - return { data: { user: null, session: null }, error }; - } - if ('phone' in credentials) { - const { phone, options } = credentials; - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { - headers: this.headers, - body: { - phone, - data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, - create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', - }, - }); - return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; - } - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number.'); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Log in a user given a User supplied OTP or TokenHash received through mobile or email. - */ - async verifyOtp(params) { - var _a, _b; - try { - let redirectTo = undefined; - let captchaToken = undefined; - if ('options' in params) { - redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; - captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; - } - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/verify`, { - headers: this.headers, - body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), - redirectTo, - xform: fetch_1._sessionResponse, - }); - if (error) { - throw error; - } - if (!data) { - throw new Error('An error occurred on token verification.'); - } - const session = data.session; - const user = data.user; - if (session === null || session === void 0 ? void 0 : session.access_token) { - await this._saveSession(session); - await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); - } - return { data: { user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Attempts a single-sign on using an enterprise Identity Provider. A - * successful SSO attempt will redirect the current page to the identity - * provider authorization page. The redirect URL is implementation and SSO - * protocol specific. - * - * You can use it by providing a SSO domain. Typically you can extract this - * domain by asking users for their email address. If this domain is - * registered on the Auth instance the redirect will use that organization's - * currently active SSO Identity Provider for the login. - * - * If you have built an organization-specific login page, you can use the - * organization's SSO Identity Provider UUID directly instead. - */ - async signInWithSSO(params) { - var _a, _b, _c; - try { - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/sso`, { - body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) - ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } - : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), - headers: this.headers, - xform: fetch_1._ssoResponse, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Sends a reauthentication OTP to the user's email or phone number. - * Requires the user to be signed-in. - */ - async reauthenticate() { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._reauthenticate(); - }); - } - async _reauthenticate() { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) - throw sessionError; - if (!session) - throw new errors_1.AuthSessionMissingError(); - const { error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/reauthenticate`, { - headers: this.headers, - jwt: session.access_token, - }); - return { data: { user: null, session: null }, error }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. - */ - async resend(credentials) { - try { - const endpoint = `${this.url}/resend`; - if ('email' in credentials) { - const { email, type, options } = credentials; - const { error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { - headers: this.headers, - body: { - email, - type, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - }); - return { data: { user: null, session: null }, error }; - } - else if ('phone' in credentials) { - const { phone, type, options } = credentials; - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { - headers: this.headers, - body: { - phone, - type, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - }); - return { data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, error }; - } - throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Returns the session, refreshing it if necessary. - * - * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. - * - * **IMPORTANT:** This method loads values directly from the storage attached - * to the client. If that storage is based on request cookies for example, - * the values in it may not be authentic and therefore it's strongly advised - * against using this method and its results in such circumstances. A warning - * will be emitted if this is detected. Use {@link #getUser()} instead. - */ - async getSession() { - await this.initializePromise; - const result = await this._acquireLock(-1, async () => { - return this._useSession(async (result) => { - return result; - }); - }); - return result; - } - /** - * Acquires a global lock based on the storage key. - */ - async _acquireLock(acquireTimeout, fn) { - this._debug('#_acquireLock', 'begin', acquireTimeout); - try { - if (this.lockAcquired) { - const last = this.pendingInLock.length - ? this.pendingInLock[this.pendingInLock.length - 1] - : Promise.resolve(); - const result = (async () => { - await last; - return await fn(); - })(); - this.pendingInLock.push((async () => { - try { - await result; - } - catch (e) { - // we just care if it finished - } - })()); - return result; - } - return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { - this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); - try { - this.lockAcquired = true; - const result = fn(); - this.pendingInLock.push((async () => { - try { - await result; - } - catch (e) { - // we just care if it finished - } - })()); - await result; - // keep draining the queue until there's nothing to wait on - while (this.pendingInLock.length) { - const waitOn = [...this.pendingInLock]; - await Promise.all(waitOn); - this.pendingInLock.splice(0, waitOn.length); - } - return await result; - } - finally { - this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); - this.lockAcquired = false; - } - }); - } - finally { - this._debug('#_acquireLock', 'end'); - } - } - /** - * Use instead of {@link #getSession} inside the library. It is - * semantically usually what you want, as getting a session involves some - * processing afterwards that requires only one client operating on the - * session at once across multiple tabs or processes. - */ - async _useSession(fn) { - this._debug('#_useSession', 'begin'); - try { - // the use of __loadSession here is the only correct use of the function! - const result = await this.__loadSession(); - return await fn(result); - } - finally { - this._debug('#_useSession', 'end'); - } - } - /** - * NEVER USE DIRECTLY! - * - * Always use {@link #_useSession}. - */ - async __loadSession() { - this._debug('#__loadSession()', 'begin'); - if (!this.lockAcquired) { - this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); - } - try { - let currentSession = null; - const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); - this._debug('#getSession()', 'session from storage', maybeSession); - if (maybeSession !== null) { - if (this._isValidSession(maybeSession)) { - currentSession = maybeSession; - } - else { - this._debug('#getSession()', 'session from storage is not valid'); - await this._removeSession(); - } - } - if (!currentSession) { - return { data: { session: null }, error: null }; - } - // A session is considered expired before the access token _actually_ - // expires. When the autoRefreshToken option is off (or when the tab is - // in the background), very eager users of getSession() -- like - // realtime-js -- might send a valid JWT which will expire by the time it - // reaches the server. - const hasExpired = currentSession.expires_at - ? currentSession.expires_at * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS - : false; - this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); - if (!hasExpired) { - if (this.userStorage) { - const maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); - if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { - currentSession.user = maybeUser.user; - } - else { - currentSession.user = (0, helpers_1.userNotAvailableProxy)(); - } - } - // Wrap the user object with a warning proxy on the server - // This warns when properties of the user are accessed, not when session.user itself is accessed - if (this.storage.isServer && - currentSession.user && - !currentSession.user.__isUserNotAvailableProxy) { - const suppressWarningRef = { value: this.suppressGetSessionWarning }; - currentSession.user = (0, helpers_1.insecureUserWarningProxy)(currentSession.user, suppressWarningRef); - // Update the client-level suppression flag when the proxy suppresses the warning - if (suppressWarningRef.value) { - this.suppressGetSessionWarning = true; - } - } - return { data: { session: currentSession }, error: null }; - } - const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { session: null }, error }; - } - return { data: { session }, error: null }; - } - finally { - this._debug('#__loadSession()', 'end'); - } - } - /** - * Gets the current user details if there is an existing session. This method - * performs a network request to the Supabase Auth server, so the returned - * value is authentic and can be used to base authorization rules on. - * - * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. - */ - async getUser(jwt) { - if (jwt) { - return await this._getUser(jwt); - } - await this.initializePromise; - const result = await this._acquireLock(-1, async () => { - return await this._getUser(); - }); - return result; - } - async _getUser(jwt) { - try { - if (jwt) { - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { - headers: this.headers, - jwt: jwt, - xform: fetch_1._userResponse, - }); - } - return await this._useSession(async (result) => { - var _a, _b, _c; - const { data, error } = result; - if (error) { - throw error; - } - // returns an error if there is no access_token or custom authorization header - if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { - return { data: { user: null }, error: new errors_1.AuthSessionMissingError() }; - } - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { - headers: this.headers, - jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, - xform: fetch_1._userResponse, - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - if ((0, errors_1.isAuthSessionMissingError)(error)) { - // JWT contains a `session_id` which does not correspond to an active - // session in the database, indicating the user is signed out. - await this._removeSession(); - await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - } - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Updates user data for a logged in user. - */ - async updateUser(attributes, options = {}) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._updateUser(attributes, options); - }); - } - async _updateUser(attributes, options = {}) { - try { - return await this._useSession(async (result) => { - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - throw sessionError; - } - if (!sessionData.session) { - throw new errors_1.AuthSessionMissingError(); - } - const session = sessionData.session; - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce' && attributes.email != null) { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - } - const { data, error: userError } = await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/user`, { - headers: this.headers, - redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, - body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), - jwt: session.access_token, - xform: fetch_1._userResponse, - }); - if (userError) - throw userError; - session.user = data.user; - await this._saveSession(session); - await this._notifyAllSubscribers('USER_UPDATED', session); - return { data: { user: session.user }, error: null }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null }, error }; - } - throw error; - } - } - /** - * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. - * If the refresh token or access token in the current session is invalid, an error will be thrown. - * @param currentSession The current session that minimally contains an access token and refresh token. - */ - async setSession(currentSession) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._setSession(currentSession); - }); - } - async _setSession(currentSession) { - try { - if (!currentSession.access_token || !currentSession.refresh_token) { - throw new errors_1.AuthSessionMissingError(); - } - const timeNow = Date.now() / 1000; - let expiresAt = timeNow; - let hasExpired = true; - let session = null; - const { payload } = (0, helpers_1.decodeJWT)(currentSession.access_token); - if (payload.exp) { - expiresAt = payload.exp; - hasExpired = expiresAt <= timeNow; - } - if (hasExpired) { - const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { user: null, session: null }, error: error }; - } - if (!refreshedSession) { - return { data: { user: null, session: null }, error: null }; - } - session = refreshedSession; - } - else { - const { data, error } = await this._getUser(currentSession.access_token); - if (error) { - throw error; - } - session = { - access_token: currentSession.access_token, - refresh_token: currentSession.refresh_token, - user: data.user, - token_type: 'bearer', - expires_in: expiresAt - timeNow, - expires_at: expiresAt, - }; - await this._saveSession(session); - await this._notifyAllSubscribers('SIGNED_IN', session); - } - return { data: { user: session.user, session }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { session: null, user: null }, error }; - } - throw error; - } - } - /** - * Returns a new session, regardless of expiry status. - * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). - * If the current session's refresh token is invalid, an error will be thrown. - * @param currentSession The current session. If passed in, it must contain a refresh token. - */ - async refreshSession(currentSession) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._refreshSession(currentSession); - }); - } - async _refreshSession(currentSession) { - try { - return await this._useSession(async (result) => { - var _a; - if (!currentSession) { - const { data, error } = result; - if (error) { - throw error; - } - currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; - } - if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { - throw new errors_1.AuthSessionMissingError(); - } - const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - return { data: { user: null, session: null }, error: error }; - } - if (!session) { - return { data: { user: null, session: null }, error: null }; - } - return { data: { user: session.user, session }, error: null }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - } - /** - * Gets the session data from a URL string - */ - async _getSessionFromURL(params, callbackUrlType) { - try { - if (!(0, helpers_1.isBrowser)()) - throw new errors_1.AuthImplicitGrantRedirectError('No browser detected.'); - // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. - if (params.error || params.error_description || params.error_code) { - // The error class returned implies that the redirect is from an implicit grant flow - // but it could also be from a redirect error from a PKCE flow. - throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { - error: params.error || 'unspecified_error', - code: params.error_code || 'unspecified_code', - }); - } - // Checks for mismatches between the flowType initialised in the client and the URL parameters - switch (callbackUrlType) { - case 'implicit': - if (this.flowType === 'pkce') { - throw new errors_1.AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); - } - break; - case 'pkce': - if (this.flowType === 'implicit') { - throw new errors_1.AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); - } - break; - default: - // there's no mismatch so we continue - } - // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange - if (callbackUrlType === 'pkce') { - this._debug('#_initialize()', 'begin', 'is PKCE flow', true); - if (!params.code) - throw new errors_1.AuthPKCEGrantCodeExchangeError('No code detected.'); - const { data, error } = await this._exchangeCodeForSession(params.code); - if (error) - throw error; - const url = new URL(window.location.href); - url.searchParams.delete('code'); - window.history.replaceState(window.history.state, '', url.toString()); - return { data: { session: data.session, redirectType: null }, error: null }; - } - const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; - if (!access_token || !expires_in || !refresh_token || !token_type) { - throw new errors_1.AuthImplicitGrantRedirectError('No session defined in URL'); - } - const timeNow = Math.round(Date.now() / 1000); - const expiresIn = parseInt(expires_in); - let expiresAt = timeNow + expiresIn; - if (expires_at) { - expiresAt = parseInt(expires_at); - } - const actuallyExpiresIn = expiresAt - timeNow; - if (actuallyExpiresIn * 1000 <= constants_1.AUTO_REFRESH_TICK_DURATION_MS) { - console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); - } - const issuedAt = expiresAt - expiresIn; - if (timeNow - issuedAt >= 120) { - console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); - } - else if (timeNow - issuedAt < 0) { - console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); - } - const { data, error } = await this._getUser(access_token); - if (error) - throw error; - const session = { - provider_token, - provider_refresh_token, - access_token, - expires_in: expiresIn, - expires_at: expiresAt, - refresh_token, - token_type: token_type, - user: data.user, - }; - // Remove tokens from URL - window.location.hash = ''; - this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); - return { data: { session, redirectType: params.type }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { session: null, redirectType: null }, error }; - } - throw error; - } - } - /** - * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) - */ - _isImplicitGrantCallback(params) { - return Boolean(params.access_token || params.error_description); - } - /** - * Checks if the current URL and backing storage contain parameters given by a PKCE flow - */ - async _isPKCECallback(params) { - const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - return !!(params.code && currentStorageContent); - } - /** - * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. - * - * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. - * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. - * - * If using `others` scope, no `SIGNED_OUT` event is fired! - */ - async signOut(options = { scope: 'global' }) { - await this.initializePromise; - return await this._acquireLock(-1, async () => { - return await this._signOut(options); - }); - } - async _signOut({ scope } = { scope: 'global' }) { - return await this._useSession(async (result) => { - var _a; - const { data, error: sessionError } = result; - if (sessionError) { - return { error: sessionError }; - } - const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; - if (accessToken) { - const { error } = await this.admin.signOut(accessToken, scope); - if (error) { - // ignore 404s since user might not exist anymore - // ignore 401s since an invalid or expired JWT should sign out the current session - if (!((0, errors_1.isAuthApiError)(error) && - (error.status === 404 || error.status === 401 || error.status === 403))) { - return { error }; - } - } - } - if (scope !== 'others') { - await this._removeSession(); - await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); - } - return { error: null }; - }); - } - onAuthStateChange(callback) { - const id = (0, helpers_1.uuid)(); - const subscription = { - id, - callback, - unsubscribe: () => { - this._debug('#unsubscribe()', 'state change callback with id removed', id); - this.stateChangeEmitters.delete(id); - }, - }; - this._debug('#onAuthStateChange()', 'registered callback with id', id); - this.stateChangeEmitters.set(id, subscription); - (async () => { - await this.initializePromise; - await this._acquireLock(-1, async () => { - this._emitInitialSession(id); - }); - })(); - return { data: { subscription } }; - } - async _emitInitialSession(id) { - return await this._useSession(async (result) => { - var _a, _b; - try { - const { data: { session }, error, } = result; - if (error) - throw error; - await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); - this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); - } - catch (err) { - await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); - this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); - console.error(err); - } - }); - } - /** - * Sends a password reset request to an email address. This method supports the PKCE flow. - * - * @param email The email address of the user. - * @param options.redirectTo The URL to send the user to after they click the password reset link. - * @param options.captchaToken Verification token received when the user completes the captcha on the site. - */ - async resetPasswordForEmail(email, options = {}) { - let codeChallenge = null; - let codeChallengeMethod = null; - if (this.flowType === 'pkce') { - ; - [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey, true // isPasswordRecovery - ); - } - try { - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/recover`, { - body: { - email, - code_challenge: codeChallenge, - code_challenge_method: codeChallengeMethod, - gotrue_meta_security: { captcha_token: options.captchaToken }, - }, - headers: this.headers, - redirectTo: options.redirectTo, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Gets all the identities linked to a user. - */ - async getUserIdentities() { - var _a; - try { - const { data, error } = await this.getUser(); - if (error) - throw error; - return { data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async linkIdentity(credentials) { - if ('token' in credentials) { - return this.linkIdentityIdToken(credentials); - } - return this.linkIdentityOAuth(credentials); - } - async linkIdentityOAuth(credentials) { - var _a; - try { - const { data, error } = await this._useSession(async (result) => { - var _a, _b, _c, _d, _e; - const { data, error } = result; - if (error) - throw error; - const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { - redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, - scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, - queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, - skipBrowserRedirect: true, - }); - return await (0, fetch_1._request)(this.fetch, 'GET', url, { - headers: this.headers, - jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, - }); - }); - if (error) - throw error; - if ((0, helpers_1.isBrowser)() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { - window.location.assign(data === null || data === void 0 ? void 0 : data.url); - } - return { data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, error: null }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { provider: credentials.provider, url: null }, error }; - } - throw error; - } - } - async linkIdentityIdToken(credentials) { - return await this._useSession(async (result) => { - var _a; - try { - const { error: sessionError, data: { session }, } = result; - if (sessionError) - throw sessionError; - const { options, provider, token, access_token, nonce } = credentials; - const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { - headers: this.headers, - jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined, - body: { - provider, - id_token: token, - access_token, - nonce, - link_identity: true, - gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, - }, - xform: fetch_1._sessionResponse, - }); - const { data, error } = res; - if (error) { - return { data: { user: null, session: null }, error }; - } - else if (!data || !data.session || !data.user) { - return { - data: { user: null, session: null }, - error: new errors_1.AuthInvalidTokenResponseError(), - }; - } - if (data.session) { - await this._saveSession(data.session); - await this._notifyAllSubscribers('USER_UPDATED', data.session); - } - return { data, error }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: { user: null, session: null }, error }; - } - throw error; - } - }); - } - /** - * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. - */ - async unlinkIdentity(identity) { - try { - return await this._useSession(async (result) => { - var _a, _b; - const { data, error } = result; - if (error) { - throw error; - } - return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { - headers: this.headers, - jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Generates a new JWT. - * @param refreshToken A valid refresh token that was returned on login. - */ - async _refreshAccessToken(refreshToken) { - const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; - this._debug(debugName, 'begin'); - try { - const startedAt = Date.now(); - // will attempt to refresh the token with exponential backoff - return await (0, helpers_1.retryable)(async (attempt) => { - if (attempt > 0) { - await (0, helpers_1.sleep)(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... - } - this._debug(debugName, 'refreshing attempt', attempt); - return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { - body: { refresh_token: refreshToken }, - headers: this.headers, - xform: fetch_1._sessionResponse, - }); - }, (attempt, error) => { - const nextBackOffInterval = 200 * Math.pow(2, attempt); - return (error && - (0, errors_1.isAuthRetryableFetchError)(error) && - // retryable only if the request can be sent before the backoff overflows the tick duration - Date.now() + nextBackOffInterval - startedAt < constants_1.AUTO_REFRESH_TICK_DURATION_MS); - }); - } - catch (error) { - this._debug(debugName, 'error', error); - if ((0, errors_1.isAuthError)(error)) { - return { data: { session: null, user: null }, error }; - } - throw error; - } - finally { - this._debug(debugName, 'end'); - } - } - _isValidSession(maybeSession) { - const isValidSession = typeof maybeSession === 'object' && - maybeSession !== null && - 'access_token' in maybeSession && - 'refresh_token' in maybeSession && - 'expires_at' in maybeSession; - return isValidSession; - } - async _handleProviderSignIn(provider, options) { - const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { - redirectTo: options.redirectTo, - scopes: options.scopes, - queryParams: options.queryParams, - }); - this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); - // try to open on the browser - if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { - window.location.assign(url); - } - return { data: { provider, url }, error: null }; - } - /** - * Recovers the session from LocalStorage and refreshes the token - * Note: this method is async to accommodate for AsyncStorage e.g. in React native. - */ - async _recoverAndRefresh() { - var _a, _b; - const debugName = '#_recoverAndRefresh()'; - this._debug(debugName, 'begin'); - try { - const currentSession = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey)); - if (currentSession && this.userStorage) { - let maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); - if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { - // storage and userStorage are the same storage medium, for example - // window.localStorage if userStorage does not have the user from - // storage stored, store it first thereby migrating the user object - // from storage -> userStorage - maybeUser = { user: currentSession.user }; - await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', maybeUser); - } - currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : (0, helpers_1.userNotAvailableProxy)(); - } - else if (currentSession && !currentSession.user) { - // user storage is not set, let's check if it was previously enabled so - // we bring back the storage as it should be - if (!currentSession.user) { - // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key - const separateUser = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey + '-user')); - if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { - currentSession.user = separateUser.user; - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); - await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); - } - else { - currentSession.user = (0, helpers_1.userNotAvailableProxy)(); - } - } - } - this._debug(debugName, 'session from storage', currentSession); - if (!this._isValidSession(currentSession)) { - this._debug(debugName, 'session is not valid'); - if (currentSession !== null) { - await this._removeSession(); - } - return; - } - const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS; - this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${constants_1.EXPIRY_MARGIN_MS}s`); - if (expiresWithMargin) { - if (this.autoRefreshToken && currentSession.refresh_token) { - const { error } = await this._callRefreshToken(currentSession.refresh_token); - if (error) { - console.error(error); - if (!(0, errors_1.isAuthRetryableFetchError)(error)) { - this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); - await this._removeSession(); - } - } - } - } - else if (currentSession.user && - currentSession.user.__isUserNotAvailableProxy === true) { - // If we have a proxy user, try to get the real user data - try { - const { data, error: userError } = await this._getUser(currentSession.access_token); - if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { - currentSession.user = data.user; - await this._saveSession(currentSession); - await this._notifyAllSubscribers('SIGNED_IN', currentSession); - } - else { - this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification'); - } - } - catch (getUserError) { - console.error('Error getting user data:', getUserError); - this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError); - } - } - else { - // no need to persist currentSession again, as we just loaded it from - // local storage; persisting it again may overwrite a value saved by - // another client with access to the same local storage - await this._notifyAllSubscribers('SIGNED_IN', currentSession); - } - } - catch (err) { - this._debug(debugName, 'error', err); - console.error(err); - return; - } - finally { - this._debug(debugName, 'end'); - } - } - async _callRefreshToken(refreshToken) { - var _a, _b; - if (!refreshToken) { - throw new errors_1.AuthSessionMissingError(); - } - // refreshing is already in progress - if (this.refreshingDeferred) { - return this.refreshingDeferred.promise; - } - const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; - this._debug(debugName, 'begin'); - try { - this.refreshingDeferred = new helpers_1.Deferred(); - const { data, error } = await this._refreshAccessToken(refreshToken); - if (error) - throw error; - if (!data.session) - throw new errors_1.AuthSessionMissingError(); - await this._saveSession(data.session); - await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); - const result = { data: data.session, error: null }; - this.refreshingDeferred.resolve(result); - return result; - } - catch (error) { - this._debug(debugName, 'error', error); - if ((0, errors_1.isAuthError)(error)) { - const result = { data: null, error }; - if (!(0, errors_1.isAuthRetryableFetchError)(error)) { - await this._removeSession(); - } - (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); - return result; - } - (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); - throw error; - } - finally { - this.refreshingDeferred = null; - this._debug(debugName, 'end'); - } - } - async _notifyAllSubscribers(event, session, broadcast = true) { - const debugName = `#_notifyAllSubscribers(${event})`; - this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); - try { - if (this.broadcastChannel && broadcast) { - this.broadcastChannel.postMessage({ event, session }); - } - const errors = []; - const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { - try { - await x.callback(event, session); - } - catch (e) { - errors.push(e); - } - }); - await Promise.all(promises); - if (errors.length > 0) { - for (let i = 0; i < errors.length; i += 1) { - console.error(errors[i]); - } - throw errors[0]; - } - } - finally { - this._debug(debugName, 'end'); - } - } - /** - * set currentSession and currentUser - * process to _startAutoRefreshToken if possible - */ - async _saveSession(session) { - this._debug('#_saveSession()', session); - // _saveSession is always called whenever a new session has been acquired - // so we can safely suppress the warning returned by future getSession calls - this.suppressGetSessionWarning = true; - // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere - const sessionToProcess = Object.assign({}, session); - const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; - if (this.userStorage) { - if (!userIsProxy && sessionToProcess.user) { - // If it's a real user object, save it to userStorage. - await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', { - user: sessionToProcess.user, - }); - } - else if (userIsProxy) { - // If it's the proxy, it means user was not found in userStorage. - // We should ensure no stale user data for this key exists in userStorage if we were to save null, - // or simply not save the proxy. For now, we don't save the proxy here. - // If there's a need to clear userStorage if user becomes proxy, that logic would go here. - } - // Prepare the main session data for primary storage: remove the user property before cloning - // This is important because the original session.user might be the proxy - const mainSessionData = Object.assign({}, sessionToProcess); - delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage - const clonedMainSessionData = (0, helpers_1.deepClone)(mainSessionData); - await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedMainSessionData); - } - else { - // No userStorage is configured. - // In this case, session.user should ideally not be a proxy. - // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here - const clonedSession = (0, helpers_1.deepClone)(sessionToProcess); // sessionToProcess still has its original user property - await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedSession); - } - } - async _removeSession() { - this._debug('#_removeSession()'); - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-code-verifier'); - await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); - if (this.userStorage) { - await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + '-user'); - } - await this._notifyAllSubscribers('SIGNED_OUT', null); - } - /** - * Removes any registered visibilitychange callback. - * - * {@see #startAutoRefresh} - * {@see #stopAutoRefresh} - */ - _removeVisibilityChangedCallback() { - this._debug('#_removeVisibilityChangedCallback()'); - const callback = this.visibilityChangedCallback; - this.visibilityChangedCallback = null; - try { - if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { - window.removeEventListener('visibilitychange', callback); - } - } - catch (e) { - console.error('removing visibilitychange callback failed', e); - } - } - /** - * This is the private implementation of {@link #startAutoRefresh}. Use this - * within the library. - */ - async _startAutoRefresh() { - await this._stopAutoRefresh(); - this._debug('#_startAutoRefresh()'); - const ticker = setInterval(() => this._autoRefreshTokenTick(), constants_1.AUTO_REFRESH_TICK_DURATION_MS); - this.autoRefreshTicker = ticker; - if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { - // ticker is a NodeJS Timeout object that has an `unref` method - // https://nodejs.org/api/timers.html#timeoutunref - // When auto refresh is used in NodeJS (like for testing) the - // `setInterval` is preventing the process from being marked as - // finished and tests run endlessly. This can be prevented by calling - // `unref()` on the returned object. - ticker.unref(); - // @ts-expect-error TS has no context of Deno - } - else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { - // similar like for NodeJS, but with the Deno API - // https://deno.land/api@latest?unstable&s=Deno.unrefTimer - // @ts-expect-error TS has no context of Deno - Deno.unrefTimer(ticker); - } - // run the tick immediately, but in the next pass of the event loop so that - // #_initialize can be allowed to complete without recursively waiting on - // itself - setTimeout(async () => { - await this.initializePromise; - await this._autoRefreshTokenTick(); - }, 0); - } - /** - * This is the private implementation of {@link #stopAutoRefresh}. Use this - * within the library. - */ - async _stopAutoRefresh() { - this._debug('#_stopAutoRefresh()'); - const ticker = this.autoRefreshTicker; - this.autoRefreshTicker = null; - if (ticker) { - clearInterval(ticker); - } - } - /** - * Starts an auto-refresh process in the background. The session is checked - * every few seconds. Close to the time of expiration a process is started to - * refresh the session. If refreshing fails it will be retried for as long as - * necessary. - * - * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need - * to call this function, it will be called for you. - * - * On browsers the refresh process works only when the tab/window is in the - * foreground to conserve resources as well as prevent race conditions and - * flooding auth with requests. If you call this method any managed - * visibility change callback will be removed and you must manage visibility - * changes on your own. - * - * On non-browser platforms the refresh process works *continuously* in the - * background, which may not be desirable. You should hook into your - * platform's foreground indication mechanism and call these methods - * appropriately to conserve resources. - * - * {@see #stopAutoRefresh} - */ - async startAutoRefresh() { - this._removeVisibilityChangedCallback(); - await this._startAutoRefresh(); - } - /** - * Stops an active auto refresh process running in the background (if any). - * - * If you call this method any managed visibility change callback will be - * removed and you must manage visibility changes on your own. - * - * See {@link #startAutoRefresh} for more details. - */ - async stopAutoRefresh() { - this._removeVisibilityChangedCallback(); - await this._stopAutoRefresh(); - } - /** - * Runs the auto refresh token tick. - */ - async _autoRefreshTokenTick() { - this._debug('#_autoRefreshTokenTick()', 'begin'); - try { - await this._acquireLock(0, async () => { - try { - const now = Date.now(); - try { - return await this._useSession(async (result) => { - const { data: { session }, } = result; - if (!session || !session.refresh_token || !session.expires_at) { - this._debug('#_autoRefreshTokenTick()', 'no session'); - return; - } - // session will expire in this many ticks (or has already expired if <= 0) - const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS); - this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`); - if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) { - await this._callRefreshToken(session.refresh_token); - } - }); - } - catch (e) { - console.error('Auto refresh tick failed with error. This is likely a transient error.', e); - } - } - finally { - this._debug('#_autoRefreshTokenTick()', 'end'); - } - }); - } - catch (e) { - if (e.isAcquireTimeout || e instanceof locks_1.LockAcquireTimeoutError) { - this._debug('auto refresh token tick lock not available'); - } - else { - throw e; - } - } - } - /** - * Registers callbacks on the browser / platform, which in-turn run - * algorithms when the browser window/tab are in foreground. On non-browser - * platforms it assumes always foreground. - */ - async _handleVisibilityChange() { - this._debug('#_handleVisibilityChange()'); - if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { - if (this.autoRefreshToken) { - // in non-browser environments the refresh token ticker runs always - this.startAutoRefresh(); - } - return false; - } - try { - this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); - window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); - // now immediately call the visbility changed callback to setup with the - // current visbility state - await this._onVisibilityChanged(true); // initial call - } - catch (error) { - console.error('_handleVisibilityChange', error); - } - } - /** - * Callback registered with `window.addEventListener('visibilitychange')`. - */ - async _onVisibilityChanged(calledFromInitialize) { - const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; - this._debug(methodName, 'visibilityState', document.visibilityState); - if (document.visibilityState === 'visible') { - if (this.autoRefreshToken) { - // in browser environments the refresh token ticker runs only on focused tabs - // which prevents race conditions - this._startAutoRefresh(); - } - if (!calledFromInitialize) { - // called when the visibility has changed, i.e. the browser - // transitioned from hidden -> visible so we need to see if the session - // should be recovered immediately... but to do that we need to acquire - // the lock first asynchronously - await this.initializePromise; - await this._acquireLock(-1, async () => { - if (document.visibilityState !== 'visible') { - this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); - // visibility has changed while waiting for the lock, abort - return; - } - // recover the session - await this._recoverAndRefresh(); - }); - } - } - else if (document.visibilityState === 'hidden') { - if (this.autoRefreshToken) { - this._stopAutoRefresh(); - } - } - } - /** - * Generates the relevant login URL for a third-party provider. - * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. - * @param options.scopes A space-separated list of scopes granted to the OAuth application. - * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. - */ - async _getUrlForProvider(url, provider, options) { - const urlParams = [`provider=${encodeURIComponent(provider)}`]; - if (options === null || options === void 0 ? void 0 : options.redirectTo) { - urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); - } - if (options === null || options === void 0 ? void 0 : options.scopes) { - urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); - } - if (this.flowType === 'pkce') { - const [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); - const flowParams = new URLSearchParams({ - code_challenge: `${encodeURIComponent(codeChallenge)}`, - code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, - }); - urlParams.push(flowParams.toString()); - } - if (options === null || options === void 0 ? void 0 : options.queryParams) { - const query = new URLSearchParams(options.queryParams); - urlParams.push(query.toString()); - } - if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { - urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); - } - return `${url}?${urlParams.join('&')}`; - } - async _unenroll(params) { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async _enroll(params) { - try { - return await this._useSession(async (result) => { - var _a, _b; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' - ? { phone: params.phone } - : params.factorType === 'totp' - ? { issuer: params.issuer } - : {})); - const { data, error } = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors`, { - body, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - })); - if (error) { - return { data: null, error }; - } - if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { - data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; - } - return { data, error: null }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async _verify(params) { - return this._acquireLock(-1, async () => { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params - ? { - webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create' - ? (0, webauthn_1.serializeCredentialCreationResponse)(params.webauthn.credential_response) - : (0, webauthn_1.serializeCredentialRequestResponse)(params.webauthn.credential_response) }), - } - : { code: params.code })); - const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { - body, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - }); - if (error) { - return { data: null, error }; - } - await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); - await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); - return { data, error }; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - async _challenge(params) { - return this._acquireLock(-1, async () => { - try { - return await this._useSession(async (result) => { - var _a; - const { data: sessionData, error: sessionError } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - const response = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { - body: params, - headers: this.headers, - jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, - })); - if (response.error) { - return response; - } - const { data } = response; - if (data.type !== 'webauthn') { - return { data, error: null }; - } - switch (data.webauthn.type) { - case 'create': - return { - data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialCreationOptions)(data.webauthn.credential_options.publicKey) }) }) }), - error: null, - }; - case 'request': - return { - data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialRequestOptions)(data.webauthn.credential_options.publicKey) }) }) }), - error: null, - }; - } - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * {@see GoTrueMFAApi#challengeAndVerify} - */ - async _challengeAndVerify(params) { - // both _challenge and _verify independently acquire the lock, so no need - // to acquire it here - const { data: challengeData, error: challengeError } = await this._challenge({ - factorId: params.factorId, - }); - if (challengeError) { - return { data: null, error: challengeError }; - } - return await this._verify({ - factorId: params.factorId, - challengeId: challengeData.id, - code: params.code, - }); - } - /** - * {@see GoTrueMFAApi#listFactors} - */ - async _listFactors() { - var _a; - // use #getUser instead of #_getUser as the former acquires a lock - const { data: { user }, error: userError, } = await this.getUser(); - if (userError) { - return { data: null, error: userError }; - } - const data = { - all: [], - phone: [], - totp: [], - webauthn: [], - }; - // loop over the factors ONCE - for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) { - data.all.push(factor); - if (factor.status === 'verified') { - ; - data[factor.factor_type].push(factor); - } - } - return { - data, - error: null, - }; - } - /** - * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} - */ - async _getAuthenticatorAssuranceLevel() { - var _a, _b; - const { data: { session }, error: sessionError, } = await this.getSession(); - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { - data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, - error: null, - }; - } - const { payload } = (0, helpers_1.decodeJWT)(session.access_token); - let currentLevel = null; - if (payload.aal) { - currentLevel = payload.aal; - } - let nextLevel = currentLevel; - const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; - if (verifiedFactors.length > 0) { - nextLevel = 'aal2'; - } - const currentAuthenticationMethods = payload.amr || []; - return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; - } - /** - * Retrieves details about an OAuth authorization request. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - * - * Returns authorization details including client info, scopes, and user information. - * If the API returns a redirect_uri, it means consent was already given - the caller - * should handle the redirect manually if needed. - */ - async _getAuthorizationDetails(authorizationId) { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { data: null, error: new errors_1.AuthSessionMissingError() }; - } - return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, { - headers: this.headers, - jwt: session.access_token, - xform: (data) => ({ data, error: null }), - }); - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Approves an OAuth authorization request. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - */ - async _approveAuthorization(authorizationId, options) { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { data: null, error: new errors_1.AuthSessionMissingError() }; - } - const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { - headers: this.headers, - jwt: session.access_token, - body: { action: 'approve' }, - xform: (data) => ({ data, error: null }), - }); - if (response.data && response.data.redirect_url) { - // Automatically redirect in browser unless skipBrowserRedirect is true - if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { - window.location.assign(response.data.redirect_url); - } - } - return response; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - /** - * Denies an OAuth authorization request. - * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. - */ - async _denyAuthorization(authorizationId, options) { - try { - return await this._useSession(async (result) => { - const { data: { session }, error: sessionError, } = result; - if (sessionError) { - return { data: null, error: sessionError }; - } - if (!session) { - return { data: null, error: new errors_1.AuthSessionMissingError() }; - } - const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { - headers: this.headers, - jwt: session.access_token, - body: { action: 'deny' }, - xform: (data) => ({ data, error: null }), - }); - if (response.data && response.data.redirect_url) { - // Automatically redirect in browser unless skipBrowserRedirect is true - if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { - window.location.assign(response.data.redirect_url); - } - } - return response; - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } - async fetchJwk(kid, jwks = { keys: [] }) { - // try fetching from the supplied jwks - let jwk = jwks.keys.find((key) => key.kid === kid); - if (jwk) { - return jwk; - } - const now = Date.now(); - // try fetching from cache - jwk = this.jwks.keys.find((key) => key.kid === kid); - // jwk exists and jwks isn't stale - if (jwk && this.jwks_cached_at + constants_1.JWKS_TTL > now) { - return jwk; - } - // jwk isn't cached in memory so we need to fetch it from the well-known endpoint - const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, { - headers: this.headers, - }); - if (error) { - throw error; - } - if (!data.keys || data.keys.length === 0) { - return null; - } - this.jwks = data; - this.jwks_cached_at = now; - // Find the signing key - jwk = data.keys.find((key) => key.kid === kid); - if (!jwk) { - return null; - } - return jwk; - } - /** - * Extracts the JWT claims present in the access token by first verifying the - * JWT against the server's JSON Web Key Set endpoint - * `/.well-known/jwks.json` which is often cached, resulting in significantly - * faster responses. Prefer this method over {@link #getUser} which always - * sends a request to the Auth server for each JWT. - * - * If the project is not using an asymmetric JWT signing key (like ECC or - * RSA) it always sends a request to the Auth server (similar to {@link - * #getUser}) to verify the JWT. - * - * @param jwt An optional specific JWT you wish to verify, not the one you - * can obtain from {@link #getSession}. - * @param options Various additional options that allow you to customize the - * behavior of this method. - */ - async getClaims(jwt, options = {}) { - try { - let token = jwt; - if (!token) { - const { data, error } = await this.getSession(); - if (error || !data.session) { - return { data: null, error }; - } - token = data.session.access_token; - } - const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = (0, helpers_1.decodeJWT)(token); - if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { - // Reject expired JWTs should only happen if jwt argument was passed - (0, helpers_1.validateExp)(payload.exp); - } - const signingKey = !header.alg || - header.alg.startsWith('HS') || - !header.kid || - !('crypto' in globalThis && 'subtle' in globalThis.crypto) - ? null - : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); - // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser() - if (!signingKey) { - const { error } = await this.getUser(token); - if (error) { - throw error; - } - // getUser succeeds so the claims in the JWT can be trusted - return { - data: { - claims: payload, - header, - signature, - }, - error: null, - }; - } - const algorithm = (0, helpers_1.getAlgorithm)(header.alg); - // Convert JWK to CryptoKey - const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [ - 'verify', - ]); - // Verify the signature - const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, (0, base64url_1.stringToUint8Array)(`${rawHeader}.${rawPayload}`)); - if (!isValid) { - throw new errors_1.AuthInvalidJwtError('Invalid JWT signature'); - } - // If verification succeeds, decode and return claims - return { - data: { - claims: payload, - header, - signature, - }, - error: null, - }; - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - throw error; - } - } -} -GoTrueClient.nextInstanceID = 0; -exports["default"] = GoTrueClient; -//# sourceMappingURL=GoTrueClient.js.map - -/***/ }), - -/***/ 66748: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; -const tslib_1 = __nccwpck_require__(4351); -const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(96575)); -exports.GoTrueAdminApi = GoTrueAdminApi_1.default; -const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(20313)); -exports.GoTrueClient = GoTrueClient_1.default; -const AuthAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(79809)); -exports.AuthAdminApi = AuthAdminApi_1.default; -const AuthClient_1 = tslib_1.__importDefault(__nccwpck_require__(34525)); -exports.AuthClient = AuthClient_1.default; -tslib_1.__exportStar(__nccwpck_require__(1852), exports); -tslib_1.__exportStar(__nccwpck_require__(99938), exports); -var locks_1 = __nccwpck_require__(60163); -Object.defineProperty(exports, "navigatorLock", ({ enumerable: true, get: function () { return locks_1.navigatorLock; } })); -Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", ({ enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } })); -Object.defineProperty(exports, "lockInternals", ({ enumerable: true, get: function () { return locks_1.internals; } })); -Object.defineProperty(exports, "processLock", ({ enumerable: true, get: function () { return locks_1.processLock; } })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 6677: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/** - * Avoid modifying this file. It's part of - * https://github.com/supabase-community/base64url-js. Submit all fixes on - * that repo! - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.byteToBase64URL = byteToBase64URL; -exports.byteFromBase64URL = byteFromBase64URL; -exports.stringToBase64URL = stringToBase64URL; -exports.stringFromBase64URL = stringFromBase64URL; -exports.codepointToUTF8 = codepointToUTF8; -exports.stringToUTF8 = stringToUTF8; -exports.stringFromUTF8 = stringFromUTF8; -exports.base64UrlToUint8Array = base64UrlToUint8Array; -exports.stringToUint8Array = stringToUint8Array; -exports.bytesToBase64URL = bytesToBase64URL; -/** - * An array of characters that encode 6 bits into a Base64-URL alphabet - * character. - */ -const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split(''); -/** - * An array of characters that can appear in a Base64-URL encoded string but - * should be ignored. - */ -const IGNORE_BASE64URL = ' \t\n\r='.split(''); -/** - * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2 - * used to skip the character, or if -1 used to error out. - */ -const FROM_BASE64URL = (() => { - const charMap = new Array(128); - for (let i = 0; i < charMap.length; i += 1) { - charMap[i] = -1; - } - for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { - charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2; - } - for (let i = 0; i < TO_BASE64URL.length; i += 1) { - charMap[TO_BASE64URL[i].charCodeAt(0)] = i; - } - return charMap; -})(); -/** - * Converts a byte to a Base64-URL string. - * - * @param byte The byte to convert, or null to flush at the end of the byte sequence. - * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. - * @param emit A function called with the next Base64 character when ready. - */ -function byteToBase64URL(byte, state, emit) { - if (byte !== null) { - state.queue = (state.queue << 8) | byte; - state.queuedBits += 8; - while (state.queuedBits >= 6) { - const pos = (state.queue >> (state.queuedBits - 6)) & 63; - emit(TO_BASE64URL[pos]); - state.queuedBits -= 6; - } - } - else if (state.queuedBits > 0) { - state.queue = state.queue << (6 - state.queuedBits); - state.queuedBits = 6; - while (state.queuedBits >= 6) { - const pos = (state.queue >> (state.queuedBits - 6)) & 63; - emit(TO_BASE64URL[pos]); - state.queuedBits -= 6; - } - } -} -/** - * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. - * - * @param charCode The char code of the JavaScript string. - * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. - * @param emit A function called with the next byte. - */ -function byteFromBase64URL(charCode, state, emit) { - const bits = FROM_BASE64URL[charCode]; - if (bits > -1) { - // valid Base64-URL character - state.queue = (state.queue << 6) | bits; - state.queuedBits += 6; - while (state.queuedBits >= 8) { - emit((state.queue >> (state.queuedBits - 8)) & 0xff); - state.queuedBits -= 8; - } - } - else if (bits === -2) { - // ignore spaces, tabs, newlines, = - return; - } - else { - throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); - } -} -/** - * Converts a JavaScript string (which may include any valid character) into a - * Base64-URL encoded string. The string is first encoded in UTF-8 which is - * then encoded as Base64-URL. - * - * @param str The string to convert. - */ -function stringToBase64URL(str) { - const base64 = []; - const emitter = (char) => { - base64.push(char); - }; - const state = { queue: 0, queuedBits: 0 }; - stringToUTF8(str, (byte) => { - byteToBase64URL(byte, state, emitter); - }); - byteToBase64URL(null, state, emitter); - return base64.join(''); -} -/** - * Converts a Base64-URL encoded string into a JavaScript string. It is assumed - * that the underlying string has been encoded as UTF-8. - * - * @param str The Base64-URL encoded string. - */ -function stringFromBase64URL(str) { - const conv = []; - const utf8Emit = (codepoint) => { - conv.push(String.fromCodePoint(codepoint)); - }; - const utf8State = { - utf8seq: 0, - codepoint: 0, - }; - const b64State = { queue: 0, queuedBits: 0 }; - const byteEmit = (byte) => { - stringFromUTF8(byte, utf8State, utf8Emit); - }; - for (let i = 0; i < str.length; i += 1) { - byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit); - } - return conv.join(''); -} -/** - * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. - * - * @param codepoint The Unicode codepoint. - * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. - */ -function codepointToUTF8(codepoint, emit) { - if (codepoint <= 0x7f) { - emit(codepoint); - return; - } - else if (codepoint <= 0x7ff) { - emit(0xc0 | (codepoint >> 6)); - emit(0x80 | (codepoint & 0x3f)); - return; - } - else if (codepoint <= 0xffff) { - emit(0xe0 | (codepoint >> 12)); - emit(0x80 | ((codepoint >> 6) & 0x3f)); - emit(0x80 | (codepoint & 0x3f)); - return; - } - else if (codepoint <= 0x10ffff) { - emit(0xf0 | (codepoint >> 18)); - emit(0x80 | ((codepoint >> 12) & 0x3f)); - emit(0x80 | ((codepoint >> 6) & 0x3f)); - emit(0x80 | (codepoint & 0x3f)); - return; - } - throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); -} -/** - * Converts a JavaScript string to a sequence of UTF-8 bytes. - * - * @param str The string to convert to UTF-8. - * @param emit Function which will be called for each UTF-8 byte of the string. - */ -function stringToUTF8(str, emit) { - for (let i = 0; i < str.length; i += 1) { - let codepoint = str.charCodeAt(i); - if (codepoint > 0xd7ff && codepoint <= 0xdbff) { - // most UTF-16 codepoints are Unicode codepoints, except values in this - // range where the next UTF-16 codepoint needs to be combined with the - // current one to get the Unicode codepoint - const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff; - const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff; - codepoint = (lowSurrogate | highSurrogate) + 0x10000; - i += 1; - } - codepointToUTF8(codepoint, emit); - } -} -/** - * Converts a UTF-8 byte to a Unicode codepoint. - * - * @param byte The UTF-8 byte next in the sequence. - * @param state The shared state between consecutive UTF-8 bytes in the - * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. - * @param emit Function which will be called for each codepoint. - */ -function stringFromUTF8(byte, state, emit) { - if (state.utf8seq === 0) { - if (byte <= 0x7f) { - emit(byte); - return; - } - // count the number of 1 leading bits until you reach 0 - for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { - if (((byte >> (7 - leadingBit)) & 1) === 0) { - state.utf8seq = leadingBit; - break; - } - } - if (state.utf8seq === 2) { - state.codepoint = byte & 31; - } - else if (state.utf8seq === 3) { - state.codepoint = byte & 15; - } - else if (state.utf8seq === 4) { - state.codepoint = byte & 7; - } - else { - throw new Error('Invalid UTF-8 sequence'); - } - state.utf8seq -= 1; - } - else if (state.utf8seq > 0) { - if (byte <= 0x7f) { - throw new Error('Invalid UTF-8 sequence'); - } - state.codepoint = (state.codepoint << 6) | (byte & 63); - state.utf8seq -= 1; - if (state.utf8seq === 0) { - emit(state.codepoint); - } - } -} -/** - * Helper functions to convert different types of strings to Uint8Array - */ -function base64UrlToUint8Array(str) { - const result = []; - const state = { queue: 0, queuedBits: 0 }; - const onByte = (byte) => { - result.push(byte); - }; - for (let i = 0; i < str.length; i += 1) { - byteFromBase64URL(str.charCodeAt(i), state, onByte); - } - return new Uint8Array(result); -} -function stringToUint8Array(str) { - const result = []; - stringToUTF8(str, (byte) => result.push(byte)); - return new Uint8Array(result); -} -function bytesToBase64URL(bytes) { - const result = []; - const state = { queue: 0, queuedBits: 0 }; - const onChar = (char) => { - result.push(char); - }; - bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); - // always call with `null` after processing all bytes - byteToBase64URL(null, state, onChar); - return result.join(''); -} -//# sourceMappingURL=base64url.js.map - -/***/ }), - -/***/ 90518: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0; -const version_1 = __nccwpck_require__(86677); -/** Current session will be checked for refresh at this interval. */ -exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000; -/** - * A token refresh will be attempted this many ticks before the current session expires. */ -exports.AUTO_REFRESH_TICK_THRESHOLD = 3; -/* - * Earliest time before an access token expires that the session should be refreshed. - */ -exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS; -exports.GOTRUE_URL = 'http://localhost:9999'; -exports.STORAGE_KEY = 'supabase.auth.token'; -exports.AUDIENCE = ''; -exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` }; -exports.NETWORK_FAILURE = { - MAX_RETRIES: 10, - RETRY_INTERVAL: 2, // in deciseconds -}; -exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; -exports.API_VERSIONS = { - '2024-01-01': { - timestamp: Date.parse('2024-01-01T00:00:00.0Z'), - name: '2024-01-01', - }, -}; -exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; -exports.JWKS_TTL = 10 * 60 * 1000; // 10 minutes -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 99938: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0; -exports.isAuthError = isAuthError; -exports.isAuthApiError = isAuthApiError; -exports.isAuthSessionMissingError = isAuthSessionMissingError; -exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError; -exports.isAuthRetryableFetchError = isAuthRetryableFetchError; -exports.isAuthWeakPasswordError = isAuthWeakPasswordError; -class AuthError extends Error { - constructor(message, status, code) { - super(message); - this.__isAuthError = true; - this.name = 'AuthError'; - this.status = status; - this.code = code; - } -} -exports.AuthError = AuthError; -function isAuthError(error) { - return typeof error === 'object' && error !== null && '__isAuthError' in error; -} -class AuthApiError extends AuthError { - constructor(message, status, code) { - super(message, status, code); - this.name = 'AuthApiError'; - this.status = status; - this.code = code; - } -} -exports.AuthApiError = AuthApiError; -function isAuthApiError(error) { - return isAuthError(error) && error.name === 'AuthApiError'; -} -class AuthUnknownError extends AuthError { - constructor(message, originalError) { - super(message); - this.name = 'AuthUnknownError'; - this.originalError = originalError; - } -} -exports.AuthUnknownError = AuthUnknownError; -class CustomAuthError extends AuthError { - constructor(message, name, status, code) { - super(message, status, code); - this.name = name; - this.status = status; - } -} -exports.CustomAuthError = CustomAuthError; -class AuthSessionMissingError extends CustomAuthError { - constructor() { - super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); - } -} -exports.AuthSessionMissingError = AuthSessionMissingError; -function isAuthSessionMissingError(error) { - return isAuthError(error) && error.name === 'AuthSessionMissingError'; -} -class AuthInvalidTokenResponseError extends CustomAuthError { - constructor() { - super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); - } -} -exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; -class AuthInvalidCredentialsError extends CustomAuthError { - constructor(message) { - super(message, 'AuthInvalidCredentialsError', 400, undefined); - } -} -exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; -class AuthImplicitGrantRedirectError extends CustomAuthError { - constructor(message, details = null) { - super(message, 'AuthImplicitGrantRedirectError', 500, undefined); - this.details = null; - this.details = details; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - details: this.details, - }; - } -} -exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; -function isAuthImplicitGrantRedirectError(error) { - return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError'; -} -class AuthPKCEGrantCodeExchangeError extends CustomAuthError { - constructor(message, details = null) { - super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); - this.details = null; - this.details = details; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - details: this.details, - }; - } -} -exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; -class AuthRetryableFetchError extends CustomAuthError { - constructor(message, status) { - super(message, 'AuthRetryableFetchError', status, undefined); - } -} -exports.AuthRetryableFetchError = AuthRetryableFetchError; -function isAuthRetryableFetchError(error) { - return isAuthError(error) && error.name === 'AuthRetryableFetchError'; -} -/** - * This error is thrown on certain methods when the password used is deemed - * weak. Inspect the reasons to identify what password strength rules are - * inadequate. - */ -class AuthWeakPasswordError extends CustomAuthError { - constructor(message, status, reasons) { - super(message, 'AuthWeakPasswordError', status, 'weak_password'); - this.reasons = reasons; - } -} -exports.AuthWeakPasswordError = AuthWeakPasswordError; -function isAuthWeakPasswordError(error) { - return isAuthError(error) && error.name === 'AuthWeakPasswordError'; -} -class AuthInvalidJwtError extends CustomAuthError { - constructor(message) { - super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt'); - } -} -exports.AuthInvalidJwtError = AuthInvalidJwtError; -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 17072: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.handleError = handleError; -exports._request = _request; -exports._sessionResponse = _sessionResponse; -exports._sessionResponsePassword = _sessionResponsePassword; -exports._userResponse = _userResponse; -exports._ssoResponse = _ssoResponse; -exports._generateLinkResponse = _generateLinkResponse; -exports._noResolveJsonResponse = _noResolveJsonResponse; -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(90518); -const helpers_1 = __nccwpck_require__(54044); -const errors_1 = __nccwpck_require__(99938); -const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); -const NETWORK_ERROR_CODES = [502, 503, 504]; -async function handleError(error) { - var _a; - if (!(0, helpers_1.looksLikeFetchResponse)(error)) { - throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); - } - if (NETWORK_ERROR_CODES.includes(error.status)) { - // status in 500...599 range - server had an error, request might be retryed. - throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); - } - let data; - try { - data = await error.json(); - } - catch (e) { - throw new errors_1.AuthUnknownError(_getErrorMessage(e), e); - } - let errorCode = undefined; - const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error); - if (responseAPIVersion && - responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp && - typeof data === 'object' && - data && - typeof data.code === 'string') { - errorCode = data.code; - } - else if (typeof data === 'object' && data && typeof data.error_code === 'string') { - errorCode = data.error_code; - } - if (!errorCode) { - // Legacy support for weak password errors, when there were no error codes - if (typeof data === 'object' && - data && - typeof data.weak_password === 'object' && - data.weak_password && - Array.isArray(data.weak_password.reasons) && - data.weak_password.reasons.length && - data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { - throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); - } - } - else if (errorCode === 'weak_password') { - throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); - } - else if (errorCode === 'session_not_found') { - // The `session_id` inside the JWT does not correspond to a row in the - // `sessions` table. This usually means the user has signed out, has been - // deleted, or their session has somehow been terminated. - throw new errors_1.AuthSessionMissingError(); - } - throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); -} -const _getRequestParams = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET') { - return params; - } - params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); - params.body = JSON.stringify(body); - return Object.assign(Object.assign({}, params), parameters); -}; -async function _request(fetcher, method, url, options) { - var _a; - const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); - if (!headers[constants_1.API_VERSION_HEADER_NAME]) { - headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name; - } - if (options === null || options === void 0 ? void 0 : options.jwt) { - headers['Authorization'] = `Bearer ${options.jwt}`; - } - const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; - if (options === null || options === void 0 ? void 0 : options.redirectTo) { - qs['redirect_to'] = options.redirectTo; - } - const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; - const data = await _handleRequest(fetcher, method, url + queryString, { - headers, - noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, - }, {}, options === null || options === void 0 ? void 0 : options.body); - return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; -} -async function _handleRequest(fetcher, method, url, options, parameters, body) { - const requestParams = _getRequestParams(method, options, parameters, body); - let result; - try { - result = await fetcher(url, Object.assign({}, requestParams)); - } - catch (e) { - console.error(e); - // fetch failed, likely due to a network or CORS error - throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0); - } - if (!result.ok) { - await handleError(result); - } - if (options === null || options === void 0 ? void 0 : options.noResolveJson) { - return result; - } - try { - return await result.json(); - } - catch (e) { - await handleError(e); - } -} -function _sessionResponse(data) { - var _a; - let session = null; - if (hasSession(data)) { - session = Object.assign({}, data); - if (!data.expires_at) { - session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); - } - } - const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; - return { data: { session, user }, error: null }; -} -function _sessionResponsePassword(data) { - const response = _sessionResponse(data); - if (!response.error && - data.weak_password && - typeof data.weak_password === 'object' && - Array.isArray(data.weak_password.reasons) && - data.weak_password.reasons.length && - data.weak_password.message && - typeof data.weak_password.message === 'string' && - data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { - response.data.weak_password = data.weak_password; - } - return response; -} -function _userResponse(data) { - var _a; - const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; - return { data: { user }, error: null }; -} -function _ssoResponse(data) { - return { data, error: null }; -} -function _generateLinkResponse(data) { - const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); - const properties = { - action_link, - email_otp, - hashed_token, - redirect_to, - verification_type, - }; - const user = Object.assign({}, rest); - return { - data: { - properties, - user, - }, - error: null, - }; -} -function _noResolveJsonResponse(data) { - return data; -} -/** - * hasSession checks if the response object contains a valid session - * @param data A response object - * @returns true if a session is in the response - */ -function hasSession(data) { - return data.access_token && data.refresh_token && data.expires_in; -} -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 54044: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0; -exports.expiresAt = expiresAt; -exports.uuid = uuid; -exports.parseParametersFromURL = parseParametersFromURL; -exports.decodeJWT = decodeJWT; -exports.sleep = sleep; -exports.retryable = retryable; -exports.generatePKCEVerifier = generatePKCEVerifier; -exports.generatePKCEChallenge = generatePKCEChallenge; -exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod; -exports.parseResponseAPIVersion = parseResponseAPIVersion; -exports.validateExp = validateExp; -exports.getAlgorithm = getAlgorithm; -exports.validateUUID = validateUUID; -exports.userNotAvailableProxy = userNotAvailableProxy; -exports.insecureUserWarningProxy = insecureUserWarningProxy; -exports.deepClone = deepClone; -const constants_1 = __nccwpck_require__(90518); -const errors_1 = __nccwpck_require__(99938); -const base64url_1 = __nccwpck_require__(6677); -function expiresAt(expiresIn) { - const timeNow = Math.round(Date.now() / 1000); - return timeNow + expiresIn; -} -function uuid() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -} -const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'; -exports.isBrowser = isBrowser; -const localStorageWriteTests = { - tested: false, - writable: false, -}; -/** - * Checks whether localStorage is supported on this browser. - */ -const supportsLocalStorage = () => { - if (!(0, exports.isBrowser)()) { - return false; - } - try { - if (typeof globalThis.localStorage !== 'object') { - return false; - } - } - catch (e) { - // DOM exception when accessing `localStorage` - return false; - } - if (localStorageWriteTests.tested) { - return localStorageWriteTests.writable; - } - const randomKey = `lswt-${Math.random()}${Math.random()}`; - try { - globalThis.localStorage.setItem(randomKey, randomKey); - globalThis.localStorage.removeItem(randomKey); - localStorageWriteTests.tested = true; - localStorageWriteTests.writable = true; - } - catch (e) { - // localStorage can't be written to - // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document - localStorageWriteTests.tested = true; - localStorageWriteTests.writable = false; - } - return localStorageWriteTests.writable; -}; -exports.supportsLocalStorage = supportsLocalStorage; -/** - * Extracts parameters encoded in the URL both in the query and fragment. - */ -function parseParametersFromURL(href) { - const result = {}; - const url = new URL(href); - if (url.hash && url.hash[0] === '#') { - try { - const hashSearchParams = new URLSearchParams(url.hash.substring(1)); - hashSearchParams.forEach((value, key) => { - result[key] = value; - }); - } - catch (e) { - // hash is not a query string - } - } - // search parameters take precedence over hash parameters - url.searchParams.forEach((value, key) => { - result[key] = value; - }); - return result; -} -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => __importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -const looksLikeFetchResponse = (maybeResponse) => { - return (typeof maybeResponse === 'object' && - maybeResponse !== null && - 'status' in maybeResponse && - 'ok' in maybeResponse && - 'json' in maybeResponse && - typeof maybeResponse.json === 'function'); -}; -exports.looksLikeFetchResponse = looksLikeFetchResponse; -// Storage helpers -const setItemAsync = async (storage, key, data) => { - await storage.setItem(key, JSON.stringify(data)); -}; -exports.setItemAsync = setItemAsync; -const getItemAsync = async (storage, key) => { - const value = await storage.getItem(key); - if (!value) { - return null; - } - try { - return JSON.parse(value); - } - catch (_a) { - return value; - } -}; -exports.getItemAsync = getItemAsync; -const removeItemAsync = async (storage, key) => { - await storage.removeItem(key); -}; -exports.removeItemAsync = removeItemAsync; -/** - * A deferred represents some asynchronous work that is not yet finished, which - * may or may not culminate in a value. - * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts - */ -class Deferred { - constructor() { - // eslint-disable-next-line @typescript-eslint/no-extra-semi - ; - this.promise = new Deferred.promiseConstructor((res, rej) => { - // eslint-disable-next-line @typescript-eslint/no-extra-semi - ; - this.resolve = res; - this.reject = rej; - }); - } -} -exports.Deferred = Deferred; -Deferred.promiseConstructor = Promise; -function decodeJWT(token) { - const parts = token.split('.'); - if (parts.length !== 3) { - throw new errors_1.AuthInvalidJwtError('Invalid JWT structure'); - } - // Regex checks for base64url format - for (let i = 0; i < parts.length; i++) { - if (!constants_1.BASE64URL_REGEX.test(parts[i])) { - throw new errors_1.AuthInvalidJwtError('JWT not in base64url format'); - } - } - const data = { - // using base64url lib - header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])), - payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])), - signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]), - raw: { - header: parts[0], - payload: parts[1], - }, - }; - return data; -} -/** - * Creates a promise that resolves to null after some time. - */ -async function sleep(time) { - return await new Promise((accept) => { - setTimeout(() => accept(null), time); - }); -} -/** - * Converts the provided async function into a retryable function. Each result - * or thrown error is sent to the isRetryable function which should return true - * if the function should run again. - */ -function retryable(fn, isRetryable) { - const promise = new Promise((accept, reject) => { - // eslint-disable-next-line @typescript-eslint/no-extra-semi - ; - (async () => { - for (let attempt = 0; attempt < Infinity; attempt++) { - try { - const result = await fn(attempt); - if (!isRetryable(attempt, null, result)) { - accept(result); - return; - } - } - catch (e) { - if (!isRetryable(attempt, e)) { - reject(e); - return; - } - } - } - })(); - }); - return promise; -} -function dec2hex(dec) { - return ('0' + dec.toString(16)).substr(-2); -} -// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs -function generatePKCEVerifier() { - const verifierLength = 56; - const array = new Uint32Array(verifierLength); - if (typeof crypto === 'undefined') { - const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; - const charSetLen = charSet.length; - let verifier = ''; - for (let i = 0; i < verifierLength; i++) { - verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); - } - return verifier; - } - crypto.getRandomValues(array); - return Array.from(array, dec2hex).join(''); -} -async function sha256(randomString) { - const encoder = new TextEncoder(); - const encodedData = encoder.encode(randomString); - const hash = await crypto.subtle.digest('SHA-256', encodedData); - const bytes = new Uint8Array(hash); - return Array.from(bytes) - .map((c) => String.fromCharCode(c)) - .join(''); -} -async function generatePKCEChallenge(verifier) { - const hasCryptoSupport = typeof crypto !== 'undefined' && - typeof crypto.subtle !== 'undefined' && - typeof TextEncoder !== 'undefined'; - if (!hasCryptoSupport) { - console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); - return verifier; - } - const hashed = await sha256(verifier); - return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); -} -async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { - const codeVerifier = generatePKCEVerifier(); - let storedCodeVerifier = codeVerifier; - if (isPasswordRecovery) { - storedCodeVerifier += '/PASSWORD_RECOVERY'; - } - await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier); - const codeChallenge = await generatePKCEChallenge(codeVerifier); - const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; - return [codeChallenge, codeChallengeMethod]; -} -/** Parses the API version which is 2YYY-MM-DD. */ -const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; -function parseResponseAPIVersion(response) { - const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME); - if (!apiVersion) { - return null; - } - if (!apiVersion.match(API_VERSION_REGEX)) { - return null; - } - try { - const date = new Date(`${apiVersion}T00:00:00.0Z`); - return date; - } - catch (e) { - return null; - } -} -function validateExp(exp) { - if (!exp) { - throw new Error('Missing exp claim'); - } - const timeNow = Math.floor(Date.now() / 1000); - if (exp <= timeNow) { - throw new Error('JWT has expired'); - } -} -function getAlgorithm(alg) { - switch (alg) { - case 'RS256': - return { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: 'SHA-256' }, - }; - case 'ES256': - return { - name: 'ECDSA', - namedCurve: 'P-256', - hash: { name: 'SHA-256' }, - }; - default: - throw new Error('Invalid alg claim'); - } -} -const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; -function validateUUID(str) { - if (!UUID_REGEX.test(str)) { - throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not'); - } -} -function userNotAvailableProxy() { - const proxyTarget = {}; - return new Proxy(proxyTarget, { - get: (target, prop) => { - if (prop === '__isUserNotAvailableProxy') { - return true; - } - // Preventative check for common problematic symbols during cloning/inspection - // These symbols might be accessed by structuredClone or other internal mechanisms. - if (typeof prop === 'symbol') { - const sProp = prop.toString(); - if (sProp === 'Symbol(Symbol.toPrimitive)' || - sProp === 'Symbol(Symbol.toStringTag)' || - sProp === 'Symbol(util.inspect.custom)') { - // Node.js util.inspect - return undefined; - } - } - throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); - }, - set: (_target, prop) => { - throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); - }, - deleteProperty: (_target, prop) => { - throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); - }, - }); -} -/** - * Creates a proxy around a user object that warns when properties are accessed on the server. - * This is used to alert developers that using user data from getSession() on the server is insecure. - * - * @param user The actual user object to wrap - * @param suppressWarningRef An object with a 'value' property that controls warning suppression - * @returns A proxied user object that warns on property access - */ -function insecureUserWarningProxy(user, suppressWarningRef) { - return new Proxy(user, { - get: (target, prop, receiver) => { - // Allow internal checks without warning - if (prop === '__isInsecureUserWarningProxy') { - return true; - } - // Preventative check for common problematic symbols during cloning/inspection - // These symbols might be accessed by structuredClone or other internal mechanisms - if (typeof prop === 'symbol') { - const sProp = prop.toString(); - if (sProp === 'Symbol(Symbol.toPrimitive)' || - sProp === 'Symbol(Symbol.toStringTag)' || - sProp === 'Symbol(util.inspect.custom)' || - sProp === 'Symbol(nodejs.util.inspect.custom)') { - // Return the actual value for these symbols to allow proper inspection - return Reflect.get(target, prop, receiver); - } - } - // Emit warning on first property access - if (!suppressWarningRef.value && typeof prop === 'string') { - console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); - suppressWarningRef.value = true; - } - return Reflect.get(target, prop, receiver); - }, - }); -} -/** - * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). - * Note: Only works for JSON-safe data. - */ -function deepClone(obj) { - return JSON.parse(JSON.stringify(obj)); -} -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 81479: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter; -/** - * Returns a localStorage-like object that stores the key-value pairs in - * memory. - */ -function memoryLocalStorageAdapter(store = {}) { - return { - getItem: (key) => { - return store[key] || null; - }, - setItem: (key, value) => { - store[key] = value; - }, - removeItem: (key) => { - delete store[key]; - }, - }; -} -//# sourceMappingURL=local-storage.js.map - -/***/ }), - -/***/ 60163: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0; -exports.navigatorLock = navigatorLock; -exports.processLock = processLock; -const helpers_1 = __nccwpck_require__(54044); -/** - * @experimental - */ -exports.internals = { - /** - * @experimental - */ - debug: !!(globalThis && - (0, helpers_1.supportsLocalStorage)() && - globalThis.localStorage && - globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), -}; -/** - * An error thrown when a lock cannot be acquired after some amount of time. - * - * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. - */ -class LockAcquireTimeoutError extends Error { - constructor(message) { - super(message); - this.isAcquireTimeout = true; - } -} -exports.LockAcquireTimeoutError = LockAcquireTimeoutError; -class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { -} -exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; -class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { -} -exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError; -/** - * Implements a global exclusive lock using the Navigator LockManager API. It - * is available on all browsers released after 2022-03-15 with Safari being the - * last one to release support. If the API is not available, this function will - * throw. Make sure you check availablility before configuring {@link - * GoTrueClient}. - * - * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` - * local storage item to `true`. - * - * Internals: - * - * Since the LockManager API does not preserve stack traces for the async - * function passed in the `request` method, a trick is used where acquiring the - * lock releases a previously started promise to run the operation in the `fn` - * function. The lock waits for that promise to finish (with or without error), - * while the function will finally wait for the result anyway. - * - * @param name Name of the lock to be acquired. - * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if - * the lock can't be acquired without waiting. If positive, the lock acquire - * will time out after so many milliseconds. An error is - * a timeout if it has `isAcquireTimeout` set to true. - * @param fn The operation to run once the lock is acquired. - */ -async function navigatorLock(name, acquireTimeout, fn) { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); - } - const abortController = new globalThis.AbortController(); - if (acquireTimeout > 0) { - setTimeout(() => { - abortController.abort(); - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); - } - }, acquireTimeout); - } - // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request - // Wrapping navigator.locks.request() with a plain Promise is done as some - // libraries like zone.js patch the Promise object to track the execution - // context. However, it appears that most browsers use an internal promise - // implementation when using the navigator.locks.request() API causing them - // to lose context and emit confusing log messages or break certain features. - // This wrapping is believed to help zone.js track the execution context - // better. - return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 - ? { - mode: 'exclusive', - ifAvailable: true, - } - : { - mode: 'exclusive', - signal: abortController.signal, - }, async (lock) => { - if (lock) { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); - } - try { - return await fn(); - } - finally { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); - } - } - } - else { - if (acquireTimeout === 0) { - if (exports.internals.debug) { - console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); - } - throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); - } - else { - if (exports.internals.debug) { - try { - const result = await globalThis.navigator.locks.query(); - console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); - } - catch (e) { - console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); - } - } - // Browser is not following the Navigator LockManager spec, it - // returned a null lock when we didn't use ifAvailable. So we can - // pretend the lock is acquired in the name of backward compatibility - // and user experience and just run the function. - console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); - return await fn(); - } - } - })); -} -const PROCESS_LOCKS = {}; -/** - * Implements a global exclusive lock that works only in the current process. - * Useful for environments like React Native or other non-browser - * single-process (i.e. no concept of "tabs") environments. - * - * Use {@link #navigatorLock} in browser environments. - * - * @param name Name of the lock to be acquired. - * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if - * the lock can't be acquired without waiting. If positive, the lock acquire - * will time out after so many milliseconds. An error is - * a timeout if it has `isAcquireTimeout` set to true. - * @param fn The operation to run once the lock is acquired. - */ -async function processLock(name, acquireTimeout, fn) { - var _a; - const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve(); - const currentOperation = Promise.race([ - previousOperation.catch(() => { - // ignore error of previous operation that we're waiting to finish - return null; - }), - acquireTimeout >= 0 - ? new Promise((_, reject) => { - setTimeout(() => { - reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); - }, acquireTimeout); - }) - : null, - ].filter((x) => x)) - .catch((e) => { - if (e && e.isAcquireTimeout) { - throw e; - } - return null; - }) - .then(async () => { - // previous operations finished and we didn't get a race on the acquire - // timeout, so the current operation can finally start - return await fn(); - }); - PROCESS_LOCKS[name] = currentOperation.catch(async (e) => { - if (e && e.isAcquireTimeout) { - // if the current operation timed out, it doesn't mean that the previous - // operation finished, so we need contnue waiting for it to finish - await previousOperation; - return null; - } - throw e; - }); - // finally wait for the current operation to finish successfully, with an - // error or with an acquire timeout error - return await currentOperation; -} -//# sourceMappingURL=locks.js.map - -/***/ }), - -/***/ 81897: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.polyfillGlobalThis = polyfillGlobalThis; -/** - * https://mathiasbynens.be/notes/globalthis - */ -function polyfillGlobalThis() { - if (typeof globalThis === 'object') - return; - try { - Object.defineProperty(Object.prototype, '__magic__', { - get: function () { - return this; - }, - configurable: true, - }); - // @ts-expect-error 'Allow access to magic' - __magic__.globalThis = __magic__; - // @ts-expect-error 'Allow access to magic' - delete Object.prototype.__magic__; - } - catch (e) { - if (typeof self !== 'undefined') { - // @ts-expect-error 'Allow access to globals' - self.globalThis = self; - } - } -} -//# sourceMappingURL=polyfills.js.map - -/***/ }), - -/***/ 1852: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SIGN_OUT_SCOPES = void 0; -const WeakPasswordReasons = (/* unused pure expression or super */ null && (['length', 'characters', 'pwned'])); -const AMRMethods = (/* unused pure expression or super */ null && ([ - 'password', - 'otp', - 'oauth', - 'totp', - 'mfa/totp', - 'mfa/phone', - 'mfa/webauthn', - 'anonymous', - 'sso/saml', - 'magiclink', - 'web3', -])); -const FactorTypes = (/* unused pure expression or super */ null && (['totp', 'phone', 'webauthn'])); -const FactorVerificationStatuses = (/* unused pure expression or super */ null && (['verified', 'unverified'])); -const MFATOTPChannels = (/* unused pure expression or super */ null && (['sms', 'whatsapp'])); -exports.SIGN_OUT_SCOPES = ['global', 'local', 'others']; -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 86677: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 51418: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// types and functions copied over from viem so this library doesn't depend on it -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getAddress = getAddress; -exports.fromHex = fromHex; -exports.toHex = toHex; -exports.createSiweMessage = createSiweMessage; -function getAddress(address) { - if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { - throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); - } - return address.toLowerCase(); -} -function fromHex(hex) { - return parseInt(hex, 16); -} -function toHex(value) { - const bytes = new TextEncoder().encode(value); - const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); - return ('0x' + hex); -} -/** - * Creates EIP-4361 formatted message. - */ -function createSiweMessage(parameters) { - var _a; - const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters; - // Validate fields - { - if (!Number.isInteger(chainId)) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); - if (!domain) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); - if (nonce && nonce.length < 8) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); - if (!uri) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); - if (version !== '1') - throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`); - if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n')) - throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); - } - // Construct message - const address = getAddress(parameters.address); - const origin = scheme ? `${scheme}://${domain}` : domain; - const statement = parameters.statement ? `${parameters.statement}\n` : ''; - const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`; - let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`; - if (expirationTime) - suffix += `\nExpiration Time: ${expirationTime.toISOString()}`; - if (notBefore) - suffix += `\nNot Before: ${notBefore.toISOString()}`; - if (requestId) - suffix += `\nRequest ID: ${requestId}`; - if (resources) { - let content = '\nResources:'; - for (const resource of resources) { - if (!resource || typeof resource !== 'string') - throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); - content += `\n- ${resource}`; - } - suffix += content; - } - return `${prefix}\n${suffix}`; -} -//# sourceMappingURL=ethereum.js.map - -/***/ }), - -/***/ 97906: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/* eslint-disable @typescript-eslint/ban-ts-comment */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebAuthnUnknownError = exports.WebAuthnError = void 0; -exports.isWebAuthnError = isWebAuthnError; -exports.identifyRegistrationError = identifyRegistrationError; -exports.identifyAuthenticationError = identifyAuthenticationError; -const webauthn_1 = __nccwpck_require__(59451); -/** - * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented - * errors in the spec was raised after calling `navigator.credentials.create()` or - * `navigator.credentials.get()`: - * - * - `AbortError` - * - `ConstraintError` - * - `InvalidStateError` - * - `NotAllowedError` - * - `NotSupportedError` - * - `SecurityError` - * - `TypeError` - * - `UnknownError` - * - * Error messages were determined through investigation of the spec to determine under which - * scenarios a given error would be raised. - */ -class WebAuthnError extends Error { - constructor({ message, code, cause, name, }) { - var _a; - // @ts-ignore: help Rollup understand that `cause` is okay to set - super(message, { cause }); - this.__isWebAuthnError = true; - this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error'; - this.code = code; - } -} -exports.WebAuthnError = WebAuthnError; -/** - * Error class for unknown WebAuthn errors. - * Wraps unexpected errors that don't match known WebAuthn error conditions. - */ -class WebAuthnUnknownError extends WebAuthnError { - constructor(message, originalError) { - super({ - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: originalError, - message, - }); - this.name = 'WebAuthnUnknownError'; - this.originalError = originalError; - } -} -exports.WebAuthnUnknownError = WebAuthnUnknownError; -/** - * Type guard to check if an error is a WebAuthnError. - * @param {unknown} error - The error to check - * @returns {boolean} True if the error is a WebAuthnError - */ -function isWebAuthnError(error) { - return typeof error === 'object' && error !== null && '__isWebAuthnError' in error; -} -/** - * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. - * Maps browser errors to specific WebAuthn error codes for better debugging. - * @param {Object} params - Error identification parameters - * @param {Error} params.error - The error thrown by the browser - * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() - * @returns {WebAuthnError} A WebAuthnError with a specific error code - * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} - */ -function identifyRegistrationError({ error, options, }) { - var _a, _b, _c; - const { publicKey } = options; - if (!publicKey) { - throw Error('options was missing required publicKey property'); - } - if (error.name === 'AbortError') { - if (options.signal instanceof AbortSignal) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) - return new WebAuthnError({ - message: 'Registration ceremony was sent an abort signal', - code: 'ERROR_CEREMONY_ABORTED', - cause: error, - }); - } - } - else if (error.name === 'ConstraintError') { - if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) { - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) - return new WebAuthnError({ - message: 'Discoverable credentials were required but no available authenticator supported it', - code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', - cause: error, - }); - } - else if ( - // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 - options.mediation === 'conditional' && - ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') { - // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4) - return new WebAuthnError({ - message: 'User verification was required during automatic registration but it could not be performed', - code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE', - cause: error, - }); - } - else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') { - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) - return new WebAuthnError({ - message: 'User verification was required but no available authenticator supported it', - code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', - cause: error, - }); - } - } - else if (error.name === 'InvalidStateError') { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) - return new WebAuthnError({ - message: 'The authenticator was previously registered', - code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', - cause: error, - }); - } - else if (error.name === 'NotAllowedError') { - /** - * Pass the error directly through. Platforms are overloading this error beyond what the spec - * defines and we don't want to overwrite potentially useful error messages. - */ - return new WebAuthnError({ - message: error.message, - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); - } - else if (error.name === 'NotSupportedError') { - const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key'); - if (validPubKeyCredParams.length === 0) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) - return new WebAuthnError({ - message: 'No entry in pubKeyCredParams was of type "public-key"', - code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', - cause: error, - }); - } - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) - return new WebAuthnError({ - message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms', - code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', - cause: error, - }); - } - else if (error.name === 'SecurityError') { - const effectiveDomain = window.location.hostname; - if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) - return new WebAuthnError({ - message: `${window.location.hostname} is an invalid domain`, - code: 'ERROR_INVALID_DOMAIN', - cause: error, - }); - } - else if (publicKey.rp.id !== effectiveDomain) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) - return new WebAuthnError({ - message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, - code: 'ERROR_INVALID_RP_ID', - cause: error, - }); - } - } - else if (error.name === 'TypeError') { - if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) - return new WebAuthnError({ - message: 'User ID was not between 1 and 64 characters', - code: 'ERROR_INVALID_USER_ID_LENGTH', - cause: error, - }); - } - } - else if (error.name === 'UnknownError') { - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) - // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) - return new WebAuthnError({ - message: 'The authenticator was unable to process the specified options, or could not create a new credential', - code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', - cause: error, - }); - } - return new WebAuthnError({ - message: 'a Non-Webauthn related error has occurred', - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); -} -/** - * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. - * Maps browser errors to specific WebAuthn error codes for better debugging. - * @param {Object} params - Error identification parameters - * @param {Error} params.error - The error thrown by the browser - * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() - * @returns {WebAuthnError} A WebAuthnError with a specific error code - * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} - */ -function identifyAuthenticationError({ error, options, }) { - const { publicKey } = options; - if (!publicKey) { - throw Error('options was missing required publicKey property'); - } - if (error.name === 'AbortError') { - if (options.signal instanceof AbortSignal) { - // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) - return new WebAuthnError({ - message: 'Authentication ceremony was sent an abort signal', - code: 'ERROR_CEREMONY_ABORTED', - cause: error, - }); - } - } - else if (error.name === 'NotAllowedError') { - /** - * Pass the error directly through. Platforms are overloading this error beyond what the spec - * defines and we don't want to overwrite potentially useful error messages. - */ - return new WebAuthnError({ - message: error.message, - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); - } - else if (error.name === 'SecurityError') { - const effectiveDomain = window.location.hostname; - if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { - // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) - return new WebAuthnError({ - message: `${window.location.hostname} is an invalid domain`, - code: 'ERROR_INVALID_DOMAIN', - cause: error, - }); - } - else if (publicKey.rpId !== effectiveDomain) { - // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) - return new WebAuthnError({ - message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, - code: 'ERROR_INVALID_RP_ID', - cause: error, - }); - } - } - else if (error.name === 'UnknownError') { - // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) - // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) - return new WebAuthnError({ - message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature', - code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', - cause: error, - }); - } - return new WebAuthnError({ - message: 'a Non-Webauthn related error has occurred', - code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', - cause: error, - }); -} -//# sourceMappingURL=webauthn.errors.js.map - -/***/ }), - -/***/ 59451: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0; -exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions; -exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions; -exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse; -exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse; -exports.isValidDomain = isValidDomain; -exports.createCredential = createCredential; -exports.getCredential = getCredential; -exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions; -exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions; -const tslib_1 = __nccwpck_require__(4351); -const base64url_1 = __nccwpck_require__(6677); -const errors_1 = __nccwpck_require__(99938); -const helpers_1 = __nccwpck_require__(54044); -const webauthn_errors_1 = __nccwpck_require__(97906); -Object.defineProperty(exports, "identifyAuthenticationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } })); -Object.defineProperty(exports, "identifyRegistrationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } })); -Object.defineProperty(exports, "isWebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } })); -Object.defineProperty(exports, "WebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } })); -/** - * WebAuthn abort service to manage ceremony cancellation. - * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. - * - * @experimental This class is experimental and may change in future releases - * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} - */ -class WebAuthnAbortService { - /** - * Create an abort signal for a new WebAuthn operation. - * Automatically cancels any existing operation. - * - * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} - */ - createNewAbortSignal() { - // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() - if (this.controller) { - const abortError = new Error('Cancelling existing WebAuthn API call for new one'); - abortError.name = 'AbortError'; - this.controller.abort(abortError); - } - const newController = new AbortController(); - this.controller = newController; - return newController.signal; - } - /** - * Manually cancel the current WebAuthn operation. - * Useful for cleaning up when user cancels or navigates away. - * - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} - */ - cancelCeremony() { - if (this.controller) { - const abortError = new Error('Manually cancelling existing WebAuthn API call'); - abortError.name = 'AbortError'; - this.controller.abort(abortError); - this.controller = undefined; - } - } -} -exports.WebAuthnAbortService = WebAuthnAbortService; -/** - * Singleton instance to ensure only one WebAuthn ceremony is active at a time. - * This prevents "operation already in progress" errors when retrying WebAuthn operations. - * - * @experimental This instance is experimental and may change in future releases - */ -exports.webAuthnAbortService = new WebAuthnAbortService(); -/** - * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers - * as required by the WebAuthn browser API. - * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. - * - * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields - * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() - * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} - */ -function deserializeCredentialCreationOptions(options) { - if (!options) { - throw new Error('Credential creation options are required'); - } - // Check if the native parseCreationOptionsFromJSON method is available - if (typeof PublicKeyCredential !== 'undefined' && - 'parseCreationOptionsFromJSON' in PublicKeyCredential && - typeof PublicKeyCredential - .parseCreationOptionsFromJSON === 'function') { - // Use the native WebAuthn Level 3 method - return PublicKeyCredential.parseCreationOptionsFromJSON( - /** we assert the options here as typescript still doesn't know about future webauthn types */ - options); - } - // Fallback to manual parsing for browsers that don't support the native method - // Destructure to separate fields that need transformation - const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest(options - // Convert challenge from base64url to ArrayBuffer - , ["challenge", "user", "excludeCredentials"]); - // Convert challenge from base64url to ArrayBuffer - const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; - // Convert user.id from base64url to ArrayBuffer - const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer }); - // Build the result object - const result = Object.assign(Object.assign({}, restOptions), { challenge, - user }); - // Only add excludeCredentials if it exists - if (excludeCredentials && excludeCredentials.length > 0) { - result.excludeCredentials = new Array(excludeCredentials.length); - for (let i = 0; i < excludeCredentials.length; i++) { - const cred = excludeCredentials[i]; - result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', - // Cast transports to handle future transport types like "cable" - transports: cred.transports }); - } - } - return result; -} -/** - * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers - * as required by the WebAuthn browser API. - * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. - * - * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields - * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() - * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} - */ -function deserializeCredentialRequestOptions(options) { - if (!options) { - throw new Error('Credential request options are required'); - } - // Check if the native parseRequestOptionsFromJSON method is available - if (typeof PublicKeyCredential !== 'undefined' && - 'parseRequestOptionsFromJSON' in PublicKeyCredential && - typeof PublicKeyCredential - .parseRequestOptionsFromJSON === 'function') { - // Use the native WebAuthn Level 3 method - return PublicKeyCredential.parseRequestOptionsFromJSON(options); - } - // Fallback to manual parsing for browsers that don't support the native method - // Destructure to separate fields that need transformation - const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest(options - // Convert challenge from base64url to ArrayBuffer - , ["challenge", "allowCredentials"]); - // Convert challenge from base64url to ArrayBuffer - const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; - // Build the result object - const result = Object.assign(Object.assign({}, restOptions), { challenge }); - // Only add allowCredentials if it exists - if (allowCredentials && allowCredentials.length > 0) { - result.allowCredentials = new Array(allowCredentials.length); - for (let i = 0; i < allowCredentials.length; i++) { - const cred = allowCredentials[i]; - result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', - // Cast transports to handle future transport types like "cable" - transports: cred.transports }); - } - } - return result; -} -/** - * Convert a registration/enrollment credential response to server format. - * Serializes binary fields to base64url for JSON transmission. - * Supports both native WebAuthn Level 3 toJSON and manual fallback. - * - * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() - * @returns {RegistrationResponseJSON} JSON-serializable credential for server - * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} - */ -function serializeCredentialCreationResponse(credential) { - var _a; - // Check if the credential instance has the toJSON method - if ('toJSON' in credential && typeof credential.toJSON === 'function') { - // Use the native WebAuthn Level 3 method - return credential.toJSON(); - } - const credentialWithAttachment = credential; - return { - id: credential.id, - rawId: credential.id, - response: { - attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)), - clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)), - }, - type: 'public-key', - clientExtensionResults: credential.getClientExtensionResults(), - // Convert null to undefined and cast to AuthenticatorAttachment type - authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), - }; -} -/** - * Convert an authentication/verification credential response to server format. - * Serializes binary fields to base64url for JSON transmission. - * Supports both native WebAuthn Level 3 toJSON and manual fallback. - * - * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() - * @returns {AuthenticationResponseJSON} JSON-serializable credential for server - * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} - */ -function serializeCredentialRequestResponse(credential) { - var _a; - // Check if the credential instance has the toJSON method - if ('toJSON' in credential && typeof credential.toJSON === 'function') { - // Use the native WebAuthn Level 3 method - return credential.toJSON(); - } - // Fallback to manual conversion for browsers that don't support toJSON - // Access authenticatorAttachment via type assertion to handle TypeScript version differences - // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't - const credentialWithAttachment = credential; - const clientExtensionResults = credential.getClientExtensionResults(); - const assertionResponse = credential.response; - return { - id: credential.id, - rawId: credential.id, // W3C spec expects rawId to match id for JSON format - response: { - authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)), - clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)), - signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)), - userHandle: assertionResponse.userHandle - ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle)) - : undefined, - }, - type: 'public-key', - clientExtensionResults, - // Convert null to undefined and cast to AuthenticatorAttachment type - authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), - }; -} -/** - * A simple test to determine if a hostname is a properly-formatted domain name. - * Considers localhost valid for development environments. - * - * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain - * - * Regex sourced from here: - * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html - * - * @param {string} hostname - The hostname to validate - * @returns {boolean} True if valid domain or localhost - * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} - */ -function isValidDomain(hostname) { - return ( - // Consider localhost valid as well since it's okay wrt Secure Contexts - hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname)); -} -/** - * Determine if the browser is capable of WebAuthn. - * Checks for necessary Web APIs: PublicKeyCredential and Credential Management. - * - * @returns {boolean} True if browser supports WebAuthn - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility} - */ -function browserSupportsWebAuthn() { - var _a, _b; - return !!((0, helpers_1.isBrowser)() && - 'PublicKeyCredential' in window && - window.PublicKeyCredential && - 'credentials' in navigator && - typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' && - typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function'); -} -/** - * Create a WebAuthn credential using the browser's credentials API. - * Wraps navigator.credentials.create() with error handling. - * - * @param {CredentialCreationOptions} options - Options including publicKey parameters - * @returns {Promise>} Created credential or error - * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} - */ -async function createCredential(options) { - try { - const response = await navigator.credentials.create( - /** we assert the type here until typescript types are updated */ - options); - if (!response) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), - }; - } - if (!(response instanceof PublicKeyCredential)) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), - }; - } - return { data: response, error: null }; - } - catch (err) { - return { - data: null, - error: (0, webauthn_errors_1.identifyRegistrationError)({ - error: err, - options, - }), - }; - } -} -/** - * Get a WebAuthn credential using the browser's credentials API. - * Wraps navigator.credentials.get() with error handling. - * - * @param {CredentialRequestOptions} options - Options including publicKey parameters - * @returns {Promise>} Retrieved credential or error - * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} - */ -async function getCredential(options) { - try { - const response = await navigator.credentials.get( - /** we assert the type here until typescript types are updated */ - options); - if (!response) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), - }; - } - if (!(response instanceof PublicKeyCredential)) { - return { - data: null, - error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), - }; - } - return { data: response, error: null }; - } - catch (err) { - return { - data: null, - error: (0, webauthn_errors_1.identifyAuthenticationError)({ - error: err, - options, - }), - }; - } -} -exports.DEFAULT_CREATION_OPTIONS = { - hints: ['security-key'], - authenticatorSelection: { - authenticatorAttachment: 'cross-platform', - requireResidentKey: false, - /** set to preferred because older yubikeys don't have PIN/Biometric */ - userVerification: 'preferred', - residentKey: 'discouraged', - }, - attestation: 'none', -}; -exports.DEFAULT_REQUEST_OPTIONS = { - /** set to preferred because older yubikeys don't have PIN/Biometric */ - userVerification: 'preferred', - hints: ['security-key'], -}; -function deepMerge(...sources) { - const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val); - const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); - const result = {}; - for (const source of sources) { - if (!source) - continue; - for (const key in source) { - const value = source[key]; - if (value === undefined) - continue; - if (Array.isArray(value)) { - // preserve array reference, including unions like AuthenticatorTransport[] - result[key] = value; - } - else if (isArrayBufferLike(value)) { - result[key] = value; - } - else if (isObject(value)) { - const existing = result[key]; - if (isObject(existing)) { - result[key] = deepMerge(existing, value); - } - else { - result[key] = deepMerge(value); - } - } - else { - result[key] = value; - } - } - } - return result; -} -/** - * Merges WebAuthn credential creation options with overrides. - * Sets sensible defaults for authenticator selection and extensions. - * - * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server - * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply - * @param {string} friendlyName - Optional friendly name for the credential - * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options - * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} - */ -function mergeCredentialCreationOptions(baseOptions, overrides) { - return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); -} -/** - * Merges WebAuthn credential request options with overrides. - * Sets sensible defaults for user verification and hints. - * - * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server - * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply - * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options - * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} - */ -function mergeCredentialRequestOptions(baseOptions, overrides) { - return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); -} -/** - * WebAuthn API wrapper for Supabase Auth. - * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. - * - * @experimental This API is experimental and may change in future releases - * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} - */ -class WebAuthnApi { - constructor(client) { - this.client = client; - // Bind all methods so they can be destructured - this.enroll = this._enroll.bind(this); - this.challenge = this._challenge.bind(this); - this.verify = this._verify.bind(this); - this.authenticate = this._authenticate.bind(this); - this.register = this._register.bind(this); - } - /** - * Enroll a new WebAuthn factor. - * Creates an unverified WebAuthn factor that must be verified with a credential. - * - * @experimental This method is experimental and may change in future releases - * @param {Omit} params - Enrollment parameters (friendlyName required) - * @returns {Promise} Enrolled factor details or error - * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} - */ - async _enroll(params) { - return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' })); - } - /** - * Challenge for WebAuthn credential creation or authentication. - * Combines server challenge with browser credential operations. - * Handles both registration (create) and authentication (request) flows. - * - * @experimental This method is experimental and may change in future releases - * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId - * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials - * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation - * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request - * @returns {Promise} Challenge response with credential or error - * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} - * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} - */ - async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) { - try { - // Get challenge from server using the client's MFA methods - const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ - factorId, - webauthn, - }); - if (!challengeResponse) { - return { data: null, error: challengeError }; - } - const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal(); - /** webauthn will fail if either of the name/displayname are blank */ - if (challengeResponse.webauthn.type === 'create') { - const { user } = challengeResponse.webauthn.credential_options.publicKey; - if (!user.name) { - user.name = `${user.id}:${friendlyName}`; - } - if (!user.displayName) { - user.displayName = user.name; - } - } - switch (challengeResponse.webauthn.type) { - case 'create': { - const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); - const { data, error } = await createCredential({ - publicKey: options, - signal: abortSignal, - }); - if (data) { - return { - data: { - factorId, - challengeId: challengeResponse.id, - webauthn: { - type: challengeResponse.webauthn.type, - credential_response: data, - }, - }, - error: null, - }; - } - return { data: null, error }; - } - case 'request': { - const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); - const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); - if (data) { - return { - data: { - factorId, - challengeId: challengeResponse.id, - webauthn: { - type: challengeResponse.webauthn.type, - credential_response: data, - }, - }, - error: null, - }; - } - return { data: null, error }; - } - } - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - return { - data: null, - error: new errors_1.AuthUnknownError('Unexpected error in challenge', error), - }; - } - } - /** - * Verify a WebAuthn credential with the server. - * Completes the WebAuthn ceremony by sending the credential to the server for verification. - * - * @experimental This method is experimental and may change in future releases - * @param {Object} params - Verification parameters - * @param {string} params.challengeId - ID of the challenge being verified - * @param {string} params.factorId - ID of the WebAuthn factor - * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response - * @returns {Promise} Verification result with session or error - * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} - * */ - async _verify({ challengeId, factorId, webauthn, }) { - return this.client.mfa.verify({ - factorId, - challengeId, - webauthn: webauthn, - }); - } - /** - * Complete WebAuthn authentication flow. - * Performs challenge and verification in a single operation for existing credentials. - * - * @experimental This method is experimental and may change in future releases - * @param {Object} params - Authentication parameters - * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with - * @param {Object} params.webauthn - WebAuthn configuration - * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) - * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) - * @param {AbortSignal} params.webauthn.signal - Optional abort signal - * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get - * @returns {Promise>} Authentication result - * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} - */ - async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, }, overrides) { - if (!rpId) { - return { - data: null, - error: new errors_1.AuthError('rpId is required for WebAuthn authentication'), - }; - } - try { - if (!browserSupportsWebAuthn()) { - return { - data: null, - error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), - }; - } - // Get challenge and credential - const { data: challengeResponse, error: challengeError } = await this.challenge({ - factorId, - webauthn: { rpId, rpOrigins }, - signal, - }, { request: overrides }); - if (!challengeResponse) { - return { data: null, error: challengeError }; - } - const { webauthn } = challengeResponse; - // Verify credential - return this._verify({ - factorId, - challengeId: challengeResponse.challengeId, - webauthn: { - type: webauthn.type, - rpId, - rpOrigins, - credential_response: webauthn.credential_response, - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - return { - data: null, - error: new errors_1.AuthUnknownError('Unexpected error in authenticate', error), - }; - } - } - /** - * Complete WebAuthn registration flow. - * Performs enrollment, challenge, and verification in a single operation for new credentials. - * - * @experimental This method is experimental and may change in future releases - * @param {Object} params - Registration parameters - * @param {string} params.friendlyName - User-friendly name for the credential - * @param {string} params.rpId - Relying Party ID (defaults to current hostname) - * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) - * @param {AbortSignal} params.signal - Optional abort signal - * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create - * @returns {Promise>} Registration result - * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} - */ - async _register({ friendlyName, rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, overrides) { - if (!rpId) { - return { - data: null, - error: new errors_1.AuthError('rpId is required for WebAuthn registration'), - }; - } - try { - if (!browserSupportsWebAuthn()) { - return { - data: null, - error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), - }; - } - // Enroll factor - const { data: factor, error: enrollError } = await this._enroll({ - friendlyName, - }); - if (!factor) { - await this.client.mfa - .listFactors() - .then((factors) => { - var _a; - return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' && - v.friendly_name === friendlyName && - v.status !== 'unverified'); - }) - .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0)); - return { data: null, error: enrollError }; - } - // Get challenge and create credential - const { data: challengeResponse, error: challengeError } = await this._challenge({ - factorId: factor.id, - friendlyName: factor.friendly_name, - webauthn: { rpId, rpOrigins }, - signal, - }, { - create: overrides, - }); - if (!challengeResponse) { - return { data: null, error: challengeError }; - } - return this._verify({ - factorId: factor.id, - challengeId: challengeResponse.challengeId, - webauthn: { - rpId, - rpOrigins, - type: challengeResponse.webauthn.type, - credential_response: challengeResponse.webauthn.credential_response, - }, - }); - } - catch (error) { - if ((0, errors_1.isAuthError)(error)) { - return { data: null, error }; - } - return { - data: null, - error: new errors_1.AuthUnknownError('Unexpected error in register', error), - }; - } - } -} -exports.WebAuthnApi = WebAuthnApi; -//# sourceMappingURL=webauthn.js.map - -/***/ }), - -/***/ 89904: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FunctionsClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -const helper_1 = __nccwpck_require__(90618); -const types_1 = __nccwpck_require__(93136); -class FunctionsClient { - constructor(url, { headers = {}, customFetch, region = types_1.FunctionRegion.Any, } = {}) { - this.url = url; - this.headers = headers; - this.region = region; - this.fetch = (0, helper_1.resolveFetch)(customFetch); - } - /** - * Updates the authorization header - * @param token - the new jwt token sent in the authorisation header - */ - setAuth(token) { - this.headers.Authorization = `Bearer ${token}`; - } - /** - * Invokes a function - * @param functionName - The name of the Function to invoke. - * @param options - Options for invoking the Function. - */ - invoke(functionName_1) { - return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) { - var _a; - try { - const { headers, method, body: functionArgs, signal } = options; - let _headers = {}; - let { region } = options; - if (!region) { - region = this.region; - } - // Add region as query parameter using URL API - const url = new URL(`${this.url}/${functionName}`); - if (region && region !== 'any') { - _headers['x-region'] = region; - url.searchParams.set('forceFunctionRegion', region); - } - let body; - if (functionArgs && - ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { - if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || - functionArgs instanceof ArrayBuffer) { - // will work for File as File inherits Blob - // also works for ArrayBuffer as it is the same underlying structure as a Blob - _headers['Content-Type'] = 'application/octet-stream'; - body = functionArgs; - } - else if (typeof functionArgs === 'string') { - // plain string - _headers['Content-Type'] = 'text/plain'; - body = functionArgs; - } - else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { - // don't set content-type headers - // Request will automatically add the right boundary value - body = functionArgs; - } - else { - // default, assume this is JSON - _headers['Content-Type'] = 'application/json'; - body = JSON.stringify(functionArgs); - } - } - else { - // if the Content-Type was supplied, simply set the body - body = functionArgs; - } - const response = yield this.fetch(url.toString(), { - method: method || 'POST', - // headers priority is (high to low): - // 1. invoke-level headers - // 2. client-level headers - // 3. default Content-Type header - headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), - body, - signal, - }).catch((fetchError) => { - if (fetchError.name === 'AbortError') { - throw fetchError; - } - throw new types_1.FunctionsFetchError(fetchError); - }); - const isRelayError = response.headers.get('x-relay-error'); - if (isRelayError && isRelayError === 'true') { - throw new types_1.FunctionsRelayError(response); - } - if (!response.ok) { - throw new types_1.FunctionsHttpError(response); - } - let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); - let data; - if (responseType === 'application/json') { - data = yield response.json(); - } - else if (responseType === 'application/octet-stream' || - responseType === 'application/pdf') { - data = yield response.blob(); - } - else if (responseType === 'text/event-stream') { - data = response; - } - else if (responseType === 'multipart/form-data') { - data = yield response.formData(); - } - else { - // default to text - data = yield response.text(); - } - return { data, error: null, response }; - } - catch (error) { - if (error instanceof Error && error.name === 'AbortError') { - return { data: null, error: new types_1.FunctionsFetchError(error) }; - } - return { - data: null, - error, - response: error instanceof types_1.FunctionsHttpError || error instanceof types_1.FunctionsRelayError - ? error.context - : undefined, - }; - } - }); - } -} -exports.FunctionsClient = FunctionsClient; -//# sourceMappingURL=FunctionsClient.js.map - -/***/ }), - -/***/ 90618: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.resolveFetch = void 0; -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => __importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -//# sourceMappingURL=helper.js.map - -/***/ }), - -/***/ 38519: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FunctionRegion = exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; -var FunctionsClient_1 = __nccwpck_require__(89904); -Object.defineProperty(exports, "FunctionsClient", ({ enumerable: true, get: function () { return FunctionsClient_1.FunctionsClient; } })); -var types_1 = __nccwpck_require__(93136); -Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return types_1.FunctionsError; } })); -Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return types_1.FunctionsFetchError; } })); -Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return types_1.FunctionsHttpError; } })); -Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return types_1.FunctionsRelayError; } })); -Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return types_1.FunctionRegion; } })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 93136: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; -class FunctionsError extends Error { - constructor(message, name = 'FunctionsError', context) { - super(message); - this.name = name; - this.context = context; - } -} -exports.FunctionsError = FunctionsError; -class FunctionsFetchError extends FunctionsError { - constructor(context) { - super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); - } -} -exports.FunctionsFetchError = FunctionsFetchError; -class FunctionsRelayError extends FunctionsError { - constructor(context) { - super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); - } -} -exports.FunctionsRelayError = FunctionsRelayError; -class FunctionsHttpError extends FunctionsError { - constructor(context) { - super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); - } -} -exports.FunctionsHttpError = FunctionsHttpError; -// Define the enum for the 'region' property -var FunctionRegion; -(function (FunctionRegion) { - FunctionRegion["Any"] = "any"; - FunctionRegion["ApNortheast1"] = "ap-northeast-1"; - FunctionRegion["ApNortheast2"] = "ap-northeast-2"; - FunctionRegion["ApSouth1"] = "ap-south-1"; - FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; - FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; - FunctionRegion["CaCentral1"] = "ca-central-1"; - FunctionRegion["EuCentral1"] = "eu-central-1"; - FunctionRegion["EuWest1"] = "eu-west-1"; - FunctionRegion["EuWest2"] = "eu-west-2"; - FunctionRegion["EuWest3"] = "eu-west-3"; - FunctionRegion["SaEast1"] = "sa-east-1"; - FunctionRegion["UsEast1"] = "us-east-1"; - FunctionRegion["UsWest1"] = "us-west-1"; - FunctionRegion["UsWest2"] = "us-west-2"; -})(FunctionRegion || (exports.FunctionRegion = FunctionRegion = {})); -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 93149: -/***/ ((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__(28665)); -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; - -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) { - { - 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; - - -/***/ }), - -/***/ 91049: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -// @ts-ignore -const node_fetch_1 = tslib_1.__importDefault(__nccwpck_require__(93149)); -const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(47317)); -class PostgrestBuilder { - constructor(builder) { - var _a, _b; - this.shouldThrowOnError = false; - this.method = builder.method; - this.url = builder.url; - this.headers = new Headers(builder.headers); - this.schema = builder.schema; - this.body = builder.body; - this.shouldThrowOnError = (_a = builder.shouldThrowOnError) !== null && _a !== void 0 ? _a : false; - this.signal = builder.signal; - this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false; - if (builder.fetch) { - this.fetch = builder.fetch; - } - else if (typeof fetch === 'undefined') { - this.fetch = node_fetch_1.default; - } - else { - this.fetch = fetch; - } - } - /** - * If there's an error with the query, throwOnError will reject the promise by - * throwing the error instead of returning it as part of a successful response. - * - * {@link https://github.com/supabase/supabase-js/issues/92} - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Set an HTTP header for the request. - */ - setHeader(name, value) { - this.headers = new Headers(this.headers); - this.headers.set(name, value); - return this; - } - then(onfulfilled, onrejected) { - // https://postgrest.org/en/stable/api.html#switching-schemas - if (this.schema === undefined) { - // skip - } - else if (['GET', 'HEAD'].includes(this.method)) { - this.headers.set('Accept-Profile', this.schema); - } - else { - this.headers.set('Content-Profile', this.schema); - } - if (this.method !== 'GET' && this.method !== 'HEAD') { - this.headers.set('Content-Type', 'application/json'); - } - // NOTE: Invoke w/o `this` to avoid illegal invocation error. - // https://github.com/supabase/postgrest-js/pull/247 - const _fetch = this.fetch; - let res = _fetch(this.url.toString(), { - method: this.method, - headers: this.headers, - body: JSON.stringify(this.body), - signal: this.signal, - }).then(async (res) => { - var _a, _b, _c, _d; - let error = null; - let data = null; - let count = null; - let status = res.status; - let statusText = res.statusText; - if (res.ok) { - if (this.method !== 'HEAD') { - const body = await res.text(); - if (body === '') { - // Prefer: return=minimal - } - else if (this.headers.get('Accept') === 'text/csv') { - data = body; - } - else if (this.headers.get('Accept') && - ((_a = this.headers.get('Accept')) === null || _a === void 0 ? void 0 : _a.includes('application/vnd.pgrst.plan+text'))) { - data = body; - } - else { - data = JSON.parse(body); - } - } - const countHeader = (_b = this.headers.get('Prefer')) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/); - const contentRange = (_c = res.headers.get('content-range')) === null || _c === void 0 ? void 0 : _c.split('/'); - if (countHeader && contentRange && contentRange.length > 1) { - count = parseInt(contentRange[1]); - } - // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 - // Issue persists e.g. for `.insert([...]).select().maybeSingle()` - if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { - if (data.length > 1) { - error = { - // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 - code: 'PGRST116', - details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, - hint: null, - message: 'JSON object requested, multiple (or no) rows returned', - }; - data = null; - count = null; - status = 406; - statusText = 'Not Acceptable'; - } - else if (data.length === 1) { - data = data[0]; - } - else { - data = null; - } - } - } - else { - const body = await res.text(); - try { - error = JSON.parse(body); - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (Array.isArray(error) && res.status === 404) { - data = []; - error = null; - status = 200; - statusText = 'OK'; - } - } - catch (_e) { - // Workaround for https://github.com/supabase/postgrest-js/issues/295 - if (res.status === 404 && body === '') { - status = 204; - statusText = 'No Content'; - } - else { - error = { - message: body, - }; - } - } - if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes('0 rows'))) { - error = null; - status = 200; - statusText = 'OK'; - } - if (error && this.shouldThrowOnError) { - throw new PostgrestError_1.default(error); - } - } - const postgrestResponse = { - error, - data, - count, - status, - statusText, - }; - return postgrestResponse; - }); - if (!this.shouldThrowOnError) { - res = res.catch((fetchError) => { - var _a, _b, _c; - return ({ - error: { - message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, - details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, - hint: '', - code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, - }, - data: null, - count: null, - status: 0, - statusText: '', - }); - }); - } - return res.then(onfulfilled, onrejected); - } - /** - * Override the type of the returned `data`. - * - * @typeParam NewResult - The new result type to override with - * @deprecated Use overrideTypes() method at the end of your call chain instead - */ - returns() { - /* istanbul ignore next */ - return this; - } - /** - * Override the type of the returned `data` field in the response. - * - * @typeParam NewResult - The new type to cast the response data to - * @typeParam Options - Optional type configuration (defaults to { merge: true }) - * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) - * @example - * ```typescript - * // Merge with existing types (default behavior) - * const query = supabase - * .from('users') - * .select() - * .overrideTypes<{ custom_field: string }>() - * - * // Replace existing types completely - * const replaceQuery = supabase - * .from('users') - * .select() - * .overrideTypes<{ id: number; name: string }, { merge: false }>() - * ``` - * @returns A PostgrestBuilder instance with the new type - */ - overrideTypes() { - return this; - } -} -exports["default"] = PostgrestBuilder; -//# sourceMappingURL=PostgrestBuilder.js.map - -/***/ }), - -/***/ 11526: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50050)); -const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); -/** - * PostgREST client. - * - * @typeParam Database - Types for the schema from the [type - * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) - * - * @typeParam SchemaName - Postgres schema to switch to. Must be a string - * literal, the same one passed to the constructor. If the schema is not - * `"public"`, this must be supplied manually. - */ -class PostgrestClient { - // TODO: Add back shouldThrowOnError once we figure out the typings - /** - * Creates a PostgREST client. - * - * @param url - URL of the PostgREST endpoint - * @param options - Named parameters - * @param options.headers - Custom headers - * @param options.schema - Postgres schema to switch to - * @param options.fetch - Custom fetch - */ - constructor(url, { headers = {}, schema, fetch, } = {}) { - this.url = url; - this.headers = new Headers(headers); - this.schemaName = schema; - this.fetch = fetch; - } - /** - * Perform a query on a table or a view. - * - * @param relation - The table or view name to query - */ - from(relation) { - const url = new URL(`${this.url}/${relation}`); - return new PostgrestQueryBuilder_1.default(url, { - headers: new Headers(this.headers), - schema: this.schemaName, - fetch: this.fetch, - }); - } - /** - * Select a schema to query or perform an function (rpc) call. - * - * The schema needs to be on the list of exposed schemas inside Supabase. - * - * @param schema - The schema to query - */ - schema(schema) { - return new PostgrestClient(this.url, { - headers: this.headers, - schema, - fetch: this.fetch, - }); - } - /** - * Perform a function call. - * - * @param fn - The function name to call - * @param args - The arguments to pass to the function call - * @param options - Named parameters - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * @param options.get - When set to `true`, the function will be called with - * read-only access mode. - * @param options.count - Count algorithm to use to count rows returned by the - * function. Only applicable for [set-returning - * functions](https://www.postgresql.org/docs/current/functions-srf.html). - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - rpc(fn, args = {}, { head = false, get = false, count, } = {}) { - var _a; - let method; - const url = new URL(`${this.url}/rpc/${fn}`); - let body; - if (head || get) { - method = head ? 'HEAD' : 'GET'; - Object.entries(args) - // params with undefined value needs to be filtered out, otherwise it'll - // show up as `?param=undefined` - .filter(([_, value]) => value !== undefined) - // array values need special syntax - .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) - .forEach(([name, value]) => { - url.searchParams.append(name, value); - }); - } - else { - method = 'POST'; - body = args; - } - const headers = new Headers(this.headers); - if (count) { - headers.set('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url, - headers, - schema: this.schemaName, - body, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } -} -exports["default"] = PostgrestClient; -//# sourceMappingURL=PostgrestClient.js.map - -/***/ }), - -/***/ 47317: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Error format - * - * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} - */ -class PostgrestError extends Error { - constructor(context) { - super(context.message); - this.name = 'PostgrestError'; - this.details = context.details; - this.hint = context.hint; - this.code = context.code; - } -} -exports["default"] = PostgrestError; -//# sourceMappingURL=PostgrestError.js.map - -/***/ }), - -/***/ 6671: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(81566)); -const PostgrestReservedCharsRegexp = new RegExp('[,()]'); -class PostgrestFilterBuilder extends PostgrestTransformBuilder_1.default { - /** - * Match only rows where `column` is equal to `value`. - * - * To check if the value of `column` is NULL, you should use `.is()` instead. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - eq(column, value) { - this.url.searchParams.append(column, `eq.${value}`); - return this; - } - /** - * Match only rows where `column` is not equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - neq(column, value) { - this.url.searchParams.append(column, `neq.${value}`); - return this; - } - /** - * Match only rows where `column` is greater than `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - gt(column, value) { - this.url.searchParams.append(column, `gt.${value}`); - return this; - } - /** - * Match only rows where `column` is greater than or equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - gte(column, value) { - this.url.searchParams.append(column, `gte.${value}`); - return this; - } - /** - * Match only rows where `column` is less than `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - lt(column, value) { - this.url.searchParams.append(column, `lt.${value}`); - return this; - } - /** - * Match only rows where `column` is less than or equal to `value`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - lte(column, value) { - this.url.searchParams.append(column, `lte.${value}`); - return this; - } - /** - * Match only rows where `column` matches `pattern` case-sensitively. - * - * @param column - The column to filter on - * @param pattern - The pattern to match with - */ - like(column, pattern) { - this.url.searchParams.append(column, `like.${pattern}`); - return this; - } - /** - * Match only rows where `column` matches all of `patterns` case-sensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - likeAllOf(column, patterns) { - this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches any of `patterns` case-sensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - likeAnyOf(column, patterns) { - this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches `pattern` case-insensitively. - * - * @param column - The column to filter on - * @param pattern - The pattern to match with - */ - ilike(column, pattern) { - this.url.searchParams.append(column, `ilike.${pattern}`); - return this; - } - /** - * Match only rows where `column` matches all of `patterns` case-insensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - ilikeAllOf(column, patterns) { - this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` matches any of `patterns` case-insensitively. - * - * @param column - The column to filter on - * @param patterns - The patterns to match with - */ - ilikeAnyOf(column, patterns) { - this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); - return this; - } - /** - * Match only rows where `column` IS `value`. - * - * For non-boolean columns, this is only relevant for checking if the value of - * `column` is NULL by setting `value` to `null`. - * - * For boolean columns, you can also set `value` to `true` or `false` and it - * will behave the same way as `.eq()`. - * - * @param column - The column to filter on - * @param value - The value to filter with - */ - is(column, value) { - this.url.searchParams.append(column, `is.${value}`); - return this; - } - /** - * Match only rows where `column` is included in the `values` array. - * - * @param column - The column to filter on - * @param values - The values array to filter with - */ - in(column, values) { - const cleanedValues = Array.from(new Set(values)) - .map((s) => { - // handle postgrest reserved characters - // https://postgrest.org/en/v7.0.0/api.html#reserved-characters - if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) - return `"${s}"`; - else - return `${s}`; - }) - .join(','); - this.url.searchParams.append(column, `in.(${cleanedValues})`); - return this; - } - /** - * Only relevant for jsonb, array, and range columns. Match only rows where - * `column` contains every element appearing in `value`. - * - * @param column - The jsonb, array, or range column to filter on - * @param value - The jsonb, array, or range value to filter with - */ - contains(column, value) { - if (typeof value === 'string') { - // range types can be inclusive '[', ']' or exclusive '(', ')' so just - // keep it simple and accept a string - this.url.searchParams.append(column, `cs.${value}`); - } - else if (Array.isArray(value)) { - // array - this.url.searchParams.append(column, `cs.{${value.join(',')}}`); - } - else { - // json - this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); - } - return this; - } - /** - * Only relevant for jsonb, array, and range columns. Match only rows where - * every element appearing in `column` is contained by `value`. - * - * @param column - The jsonb, array, or range column to filter on - * @param value - The jsonb, array, or range value to filter with - */ - containedBy(column, value) { - if (typeof value === 'string') { - // range - this.url.searchParams.append(column, `cd.${value}`); - } - else if (Array.isArray(value)) { - // array - this.url.searchParams.append(column, `cd.{${value.join(',')}}`); - } - else { - // json - this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); - } - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is greater than any element in `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeGt(column, range) { - this.url.searchParams.append(column, `sr.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is either contained in `range` or greater than any element in - * `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeGte(column, range) { - this.url.searchParams.append(column, `nxl.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is less than any element in `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeLt(column, range) { - this.url.searchParams.append(column, `sl.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where every element in - * `column` is either contained in `range` or less than any element in - * `range`. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeLte(column, range) { - this.url.searchParams.append(column, `nxr.${range}`); - return this; - } - /** - * Only relevant for range columns. Match only rows where `column` is - * mutually exclusive to `range` and there can be no element between the two - * ranges. - * - * @param column - The range column to filter on - * @param range - The range to filter with - */ - rangeAdjacent(column, range) { - this.url.searchParams.append(column, `adj.${range}`); - return this; - } - /** - * Only relevant for array and range columns. Match only rows where - * `column` and `value` have an element in common. - * - * @param column - The array or range column to filter on - * @param value - The array or range value to filter with - */ - overlaps(column, value) { - if (typeof value === 'string') { - // range - this.url.searchParams.append(column, `ov.${value}`); - } - else { - // array - this.url.searchParams.append(column, `ov.{${value.join(',')}}`); - } - return this; - } - /** - * Only relevant for text and tsvector columns. Match only rows where - * `column` matches the query string in `query`. - * - * @param column - The text or tsvector column to filter on - * @param query - The query text to match with - * @param options - Named parameters - * @param options.config - The text search configuration to use - * @param options.type - Change how the `query` text is interpreted - */ - textSearch(column, query, { config, type } = {}) { - let typePart = ''; - if (type === 'plain') { - typePart = 'pl'; - } - else if (type === 'phrase') { - typePart = 'ph'; - } - else if (type === 'websearch') { - typePart = 'w'; - } - const configPart = config === undefined ? '' : `(${config})`; - this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); - return this; - } - /** - * Match only rows where each column in `query` keys is equal to its - * associated value. Shorthand for multiple `.eq()`s. - * - * @param query - The object to filter with, with column names as keys mapped - * to their filter values - */ - match(query) { - Object.entries(query).forEach(([column, value]) => { - this.url.searchParams.append(column, `eq.${value}`); - }); - return this; - } - /** - * Match only rows which doesn't satisfy the filter. - * - * Unlike most filters, `opearator` and `value` are used as-is and need to - * follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure they are properly sanitized. - * - * @param column - The column to filter on - * @param operator - The operator to be negated to filter with, following - * PostgREST syntax - * @param value - The value to filter with, following PostgREST syntax - */ - not(column, operator, value) { - this.url.searchParams.append(column, `not.${operator}.${value}`); - return this; - } - /** - * Match only rows which satisfy at least one of the filters. - * - * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure it's properly sanitized. - * - * It's currently not possible to do an `.or()` filter across multiple tables. - * - * @param filters - The filters to use, following PostgREST syntax - * @param options - Named parameters - * @param options.referencedTable - Set this to filter on referenced tables - * instead of the parent table - * @param options.foreignTable - Deprecated, use `referencedTable` instead - */ - or(filters, { foreignTable, referencedTable = foreignTable, } = {}) { - const key = referencedTable ? `${referencedTable}.or` : 'or'; - this.url.searchParams.append(key, `(${filters})`); - return this; - } - /** - * Match only rows which satisfy the filter. This is an escape hatch - you - * should use the specific filter methods wherever possible. - * - * Unlike most filters, `opearator` and `value` are used as-is and need to - * follow [PostgREST - * syntax](https://postgrest.org/en/stable/api.html#operators). You also need - * to make sure they are properly sanitized. - * - * @param column - The column to filter on - * @param operator - The operator to filter with, following PostgREST syntax - * @param value - The value to filter with, following PostgREST syntax - */ - filter(column, operator, value) { - this.url.searchParams.append(column, `${operator}.${value}`); - return this; - } -} -exports["default"] = PostgrestFilterBuilder; -//# sourceMappingURL=PostgrestFilterBuilder.js.map - -/***/ }), - -/***/ 50050: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); -class PostgrestQueryBuilder { - constructor(url, { headers = {}, schema, fetch, }) { - this.url = url; - this.headers = new Headers(headers); - this.schema = schema; - this.fetch = fetch; - } - /** - * Perform a SELECT query on the table or view. - * - * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` - * - * @param options - Named parameters - * - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * - * @param options.count - Count algorithm to use to count rows in the table or view. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - select(columns, options) { - const { head = false, count } = options !== null && options !== void 0 ? options : {}; - const method = head ? 'HEAD' : 'GET'; - // Remove whitespaces except when quoted - let quoted = false; - const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') - .split('') - .map((c) => { - if (/\s/.test(c) && !quoted) { - return ''; - } - if (c === '"') { - quoted = !quoted; - } - return c; - }) - .join(''); - this.url.searchParams.set('select', cleanedColumns); - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - fetch: this.fetch, - }); - } - /** - * Perform an INSERT into the table or view. - * - * By default, inserted rows are not returned. To return it, chain the call - * with `.select()`. - * - * @param values - The values to insert. Pass an object to insert a single row - * or an array to insert multiple rows. - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count inserted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - * - * @param options.defaultToNull - Make missing fields default to `null`. - * Otherwise, use the default value for the column. Only applies for bulk - * inserts. - */ - insert(values, { count, defaultToNull = true, } = {}) { - var _a; - const method = 'POST'; - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - if (!defaultToNull) { - this.headers.append('Prefer', `missing=default`); - } - if (Array.isArray(values)) { - const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); - if (columns.length > 0) { - const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); - this.url.searchParams.set('columns', uniqueColumns.join(',')); - } - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } - /** - * Perform an UPSERT on the table or view. Depending on the column(s) passed - * to `onConflict`, `.upsert()` allows you to perform the equivalent of - * `.insert()` if a row with the corresponding `onConflict` columns doesn't - * exist, or if it does exist, perform an alternative action depending on - * `ignoreDuplicates`. - * - * By default, upserted rows are not returned. To return it, chain the call - * with `.select()`. - * - * @param values - The values to upsert with. Pass an object to upsert a - * single row or an array to upsert multiple rows. - * - * @param options - Named parameters - * - * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how - * duplicate rows are determined. Two rows are duplicates if all the - * `onConflict` columns are equal. - * - * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If - * `false`, duplicate rows are merged with existing rows. - * - * @param options.count - Count algorithm to use to count upserted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - * - * @param options.defaultToNull - Make missing fields default to `null`. - * Otherwise, use the default value for the column. This only applies when - * inserting new rows, not when merging with existing rows under - * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. - */ - upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { - var _a; - const method = 'POST'; - this.headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`); - if (onConflict !== undefined) - this.url.searchParams.set('on_conflict', onConflict); - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - if (!defaultToNull) { - this.headers.append('Prefer', 'missing=default'); - } - if (Array.isArray(values)) { - const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); - if (columns.length > 0) { - const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); - this.url.searchParams.set('columns', uniqueColumns.join(',')); - } - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } - /** - * Perform an UPDATE on the table or view. - * - * By default, updated rows are not returned. To return it, chain the call - * with `.select()` after filters. - * - * @param values - The values to update with - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count updated rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - update(values, { count, } = {}) { - var _a; - const method = 'PATCH'; - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - body: values, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } - /** - * Perform a DELETE on the table or view. - * - * By default, deleted rows are not returned. To return it, chain the call - * with `.select()` after filters. - * - * @param options - Named parameters - * - * @param options.count - Count algorithm to use to count deleted rows. - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - delete({ count, } = {}) { - var _a; - const method = 'DELETE'; - if (count) { - this.headers.append('Prefer', `count=${count}`); - } - return new PostgrestFilterBuilder_1.default({ - method, - url: this.url, - headers: this.headers, - schema: this.schema, - fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, - }); - } -} -exports["default"] = PostgrestQueryBuilder; -//# sourceMappingURL=PostgrestQueryBuilder.js.map - -/***/ }), - -/***/ 81566: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(91049)); -class PostgrestTransformBuilder extends PostgrestBuilder_1.default { - /** - * Perform a SELECT on the query result. - * - * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not - * return modified rows. By calling this method, modified rows are returned in - * `data`. - * - * @param columns - The columns to retrieve, separated by commas - */ - select(columns) { - // Remove whitespaces except when quoted - let quoted = false; - const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') - .split('') - .map((c) => { - if (/\s/.test(c) && !quoted) { - return ''; - } - if (c === '"') { - quoted = !quoted; - } - return c; - }) - .join(''); - this.url.searchParams.set('select', cleanedColumns); - this.headers.append('Prefer', 'return=representation'); - return this; - } - /** - * Order the query result by `column`. - * - * You can call this method multiple times to order by multiple columns. - * - * You can order referenced tables, but it only affects the ordering of the - * parent table if you use `!inner` in the query. - * - * @param column - The column to order by - * @param options - Named parameters - * @param options.ascending - If `true`, the result will be in ascending order - * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, - * `null`s appear last. - * @param options.referencedTable - Set this to order a referenced table by - * its columns - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) { - const key = referencedTable ? `${referencedTable}.order` : 'order'; - const existingOrder = this.url.searchParams.get(key); - this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); - return this; - } - /** - * Limit the query result by `count`. - * - * @param count - The maximum number of rows to return - * @param options - Named parameters - * @param options.referencedTable - Set this to limit rows of referenced - * tables instead of the parent table - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - limit(count, { foreignTable, referencedTable = foreignTable, } = {}) { - const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; - this.url.searchParams.set(key, `${count}`); - return this; - } - /** - * Limit the query result by starting at an offset `from` and ending at the offset `to`. - * Only records within this range are returned. - * This respects the query order and if there is no order clause the range could behave unexpectedly. - * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third - * and fourth rows of the query. - * - * @param from - The starting index from which to limit the result - * @param to - The last index to which to limit the result - * @param options - Named parameters - * @param options.referencedTable - Set this to limit rows of referenced - * tables instead of the parent table - * @param options.foreignTable - Deprecated, use `options.referencedTable` - * instead - */ - range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) { - const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`; - const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; - this.url.searchParams.set(keyOffset, `${from}`); - // Range is inclusive, so add 1 - this.url.searchParams.set(keyLimit, `${to - from + 1}`); - return this; - } - /** - * Set the AbortSignal for the fetch request. - * - * @param signal - The AbortSignal to use for the fetch request - */ - abortSignal(signal) { - this.signal = signal; - return this; - } - /** - * Return `data` as a single object instead of an array of objects. - * - * Query result must be one row (e.g. using `.limit(1)`), otherwise this - * returns an error. - */ - single() { - this.headers.set('Accept', 'application/vnd.pgrst.object+json'); - return this; - } - /** - * Return `data` as a single object instead of an array of objects. - * - * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise - * this returns an error. - */ - maybeSingle() { - // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 - // Issue persists e.g. for `.insert([...]).select().maybeSingle()` - if (this.method === 'GET') { - this.headers.set('Accept', 'application/json'); - } - else { - this.headers.set('Accept', 'application/vnd.pgrst.object+json'); - } - this.isMaybeSingle = true; - return this; - } - /** - * Return `data` as a string in CSV format. - */ - csv() { - this.headers.set('Accept', 'text/csv'); - return this; - } - /** - * Return `data` as an object in [GeoJSON](https://geojson.org) format. - */ - geojson() { - this.headers.set('Accept', 'application/geo+json'); - return this; - } - /** - * Return `data` as the EXPLAIN plan for the query. - * - * You need to enable the - * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) - * setting before using this method. - * - * @param options - Named parameters - * - * @param options.analyze - If `true`, the query will be executed and the - * actual run time will be returned - * - * @param options.verbose - If `true`, the query identifier will be returned - * and `data` will include the output columns of the query - * - * @param options.settings - If `true`, include information on configuration - * parameters that affect query planning - * - * @param options.buffers - If `true`, include information on buffer usage - * - * @param options.wal - If `true`, include information on WAL record generation - * - * @param options.format - The format of the output, can be `"text"` (default) - * or `"json"` - */ - explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { - var _a; - const options = [ - analyze ? 'analyze' : null, - verbose ? 'verbose' : null, - settings ? 'settings' : null, - buffers ? 'buffers' : null, - wal ? 'wal' : null, - ] - .filter(Boolean) - .join('|'); - // An Accept header can carry multiple media types but postgrest-js always sends one - const forMediatype = (_a = this.headers.get('Accept')) !== null && _a !== void 0 ? _a : 'application/json'; - this.headers.set('Accept', `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`); - if (format === 'json') { - return this; - } - else { - return this; - } - } - /** - * Rollback the query. - * - * `data` will still be returned, but the query is not committed. - */ - rollback() { - this.headers.append('Prefer', 'tx=rollback'); - return this; - } - /** - * Override the type of the returned `data`. - * - * @typeParam NewResult - The new result type to override with - * @deprecated Use overrideTypes() method at the end of your call chain instead - */ - returns() { - return this; - } - /** - * Set the maximum number of rows that can be affected by the query. - * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. - * - * @param value - The maximum number of rows that can be affected - */ - maxAffected(value) { - this.headers.append('Prefer', 'handling=strict'); - this.headers.append('Prefer', `max-affected=${value}`); - return this; - } -} -exports["default"] = PostgrestTransformBuilder; -//# sourceMappingURL=PostgrestTransformBuilder.js.map - -/***/ }), - -/***/ 31178: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -// Always update wrapper.mjs when updating this file. -const PostgrestClient_1 = tslib_1.__importDefault(__nccwpck_require__(11526)); -exports.PostgrestClient = PostgrestClient_1.default; -const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50050)); -exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; -const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); -exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; -const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(81566)); -exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; -const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(91049)); -exports.PostgrestBuilder = PostgrestBuilder_1.default; -const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(47317)); -exports.PostgrestError = PostgrestError_1.default; -exports["default"] = { - PostgrestClient: PostgrestClient_1.default, - PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, - PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, - PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, - PostgrestBuilder: PostgrestBuilder_1.default, - PostgrestError: PostgrestError_1.default, -}; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 39911: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(50088); -const push_1 = tslib_1.__importDefault(__nccwpck_require__(82292)); -const timer_1 = tslib_1.__importDefault(__nccwpck_require__(12983)); -const RealtimePresence_1 = tslib_1.__importDefault(__nccwpck_require__(75583)); -const Transformers = tslib_1.__importStar(__nccwpck_require__(1140)); -const transformers_1 = __nccwpck_require__(1140); -var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; -(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; - REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; -})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); -var REALTIME_LISTEN_TYPES; -(function (REALTIME_LISTEN_TYPES) { - REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; - REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; - REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; - REALTIME_LISTEN_TYPES["SYSTEM"] = "system"; -})(REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = REALTIME_LISTEN_TYPES = {})); -var REALTIME_SUBSCRIBE_STATES; -(function (REALTIME_SUBSCRIBE_STATES) { - REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; - REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; - REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; - REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; -})(REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = REALTIME_SUBSCRIBE_STATES = {})); -exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES; -/** A channel is the basic building block of Realtime - * and narrows the scope of data flow to subscribed clients. - * You can think of a channel as a chatroom where participants are able to see who's online - * and send and receive messages. - */ -class RealtimeChannel { - constructor( - /** Topic name can be any string. */ - topic, params = { config: {} }, socket) { - var _a, _b; - this.topic = topic; - this.params = params; - this.socket = socket; - this.bindings = {}; - this.state = constants_1.CHANNEL_STATES.closed; - this.joinedOnce = false; - this.pushBuffer = []; - this.subTopic = topic.replace(/^realtime:/i, ''); - this.params.config = Object.assign({ - broadcast: { ack: false, self: false }, - presence: { key: '', enabled: false }, - private: false, - }, params.config); - this.timeout = this.socket.timeout; - this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); - this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); - this.joinPush.receive('ok', () => { - this.state = constants_1.CHANNEL_STATES.joined; - this.rejoinTimer.reset(); - this.pushBuffer.forEach((pushEvent) => pushEvent.send()); - this.pushBuffer = []; - }); - this._onClose(() => { - this.rejoinTimer.reset(); - this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); - this.state = constants_1.CHANNEL_STATES.closed; - this.socket._remove(this); - }); - this._onError((reason) => { - if (this._isLeaving() || this._isClosed()) { - return; - } - this.socket.log('channel', `error ${this.topic}`, reason); - this.state = constants_1.CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this.joinPush.receive('timeout', () => { - if (!this._isJoining()) { - return; - } - this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); - this.state = constants_1.CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this.joinPush.receive('error', (reason) => { - if (this._isLeaving() || this._isClosed()) { - return; - } - this.socket.log('channel', `error ${this.topic}`, reason); - this.state = constants_1.CHANNEL_STATES.errored; - this.rejoinTimer.scheduleTimeout(); - }); - this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { - this._trigger(this._replyEventName(ref), payload); - }); - this.presence = new RealtimePresence_1.default(this); - this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint); - this.private = this.params.config.private || false; - if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { - throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; - } - } - /** Subscribe registers your client with the server */ - subscribe(callback, timeout = this.timeout) { - var _a, _b, _c; - if (!this.socket.isConnected()) { - this.socket.connect(); - } - if (this.state == constants_1.CHANNEL_STATES.closed) { - const { config: { broadcast, presence, private: isPrivate }, } = this.params; - const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []; - const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && - this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) || - ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; - const accessTokenPayload = {}; - const config = { - broadcast, - presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), - postgres_changes, - private: isPrivate, - }; - if (this.socket.accessTokenValue) { - accessTokenPayload.access_token = this.socket.accessTokenValue; - } - this._onError((e) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, e)); - this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CLOSED)); - this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); - this.joinedOnce = true; - this._rejoin(timeout); - this.joinPush - .receive('ok', async ({ postgres_changes }) => { - var _a; - this.socket.setAuth(); - if (postgres_changes === undefined) { - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); - return; - } - else { - const clientPostgresBindings = this.bindings.postgres_changes; - const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; - const newPostgresBindings = []; - for (let i = 0; i < bindingsLen; i++) { - const clientPostgresBinding = clientPostgresBindings[i]; - const { filter: { event, schema, table, filter }, } = clientPostgresBinding; - const serverPostgresFilter = postgres_changes && postgres_changes[i]; - if (serverPostgresFilter && - serverPostgresFilter.event === event && - serverPostgresFilter.schema === schema && - serverPostgresFilter.table === table && - serverPostgresFilter.filter === filter) { - newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); - } - else { - this.unsubscribe(); - this.state = constants_1.CHANNEL_STATES.errored; - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error('mismatch between server and client bindings for postgres changes')); - return; - } - } - this.bindings.postgres_changes = newPostgresBindings; - callback && callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); - return; - } - }) - .receive('error', (error) => { - this.state = constants_1.CHANNEL_STATES.errored; - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); - return; - }) - .receive('timeout', () => { - callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.TIMED_OUT); - return; - }); - } - return this; - } - presenceState() { - return this.presence.state; - } - async track(payload, opts = {}) { - return await this.send({ - type: 'presence', - event: 'track', - payload, - }, opts.timeout || this.timeout); - } - async untrack(opts = {}) { - return await this.send({ - type: 'presence', - event: 'untrack', - }, opts); - } - on(type, filter, callback) { - if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) { - this.socket.log('channel', `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); - this.unsubscribe().then(() => this.subscribe()); - } - return this._on(type, filter, callback); - } - /** - * Sends a broadcast message explicitly via REST API. - * - * This method always uses the REST API endpoint regardless of WebSocket connection state. - * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. - * - * @param event The name of the broadcast event - * @param payload Payload to be sent (required) - * @param opts Options including timeout - * @returns Promise resolving to object with success status, and error details if failed - */ - async httpSend(event, payload, opts = {}) { - var _a; - const authorization = this.socket.accessTokenValue - ? `Bearer ${this.socket.accessTokenValue}` - : ''; - if (payload === undefined || payload === null) { - return Promise.reject('Payload is required for httpSend()'); - } - const options = { - method: 'POST', - headers: { - Authorization: authorization, - apikey: this.socket.apiKey ? this.socket.apiKey : '', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - messages: [ - { - topic: this.subTopic, - event, - payload: payload, - private: this.private, - }, - ], - }), - }; - const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); - if (response.status === 202) { - return { success: true }; - } - let errorMessage = response.statusText; - try { - const errorBody = await response.json(); - errorMessage = errorBody.error || errorBody.message || errorMessage; - } - catch (_b) { } - return Promise.reject(new Error(errorMessage)); - } - /** - * Sends a message into the channel. - * - * @param args Arguments to send to channel - * @param args.type The type of event to send - * @param args.event The name of the event being sent - * @param args.payload Payload to be sent - * @param opts Options to be used during the send process - */ - async send(args, opts = {}) { - var _a, _b; - if (!this._canPush() && args.type === 'broadcast') { - console.warn('Realtime send() is automatically falling back to REST API. ' + - 'This behavior will be deprecated in the future. ' + - 'Please use httpSend() explicitly for REST delivery.'); - const { event, payload: endpoint_payload } = args; - const authorization = this.socket.accessTokenValue - ? `Bearer ${this.socket.accessTokenValue}` - : ''; - const options = { - method: 'POST', - headers: { - Authorization: authorization, - apikey: this.socket.apiKey ? this.socket.apiKey : '', - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - messages: [ - { - topic: this.subTopic, - event, - payload: endpoint_payload, - private: this.private, - }, - ], - }), - }; - try { - const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); - await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); - return response.ok ? 'ok' : 'error'; - } - catch (error) { - if (error.name === 'AbortError') { - return 'timed out'; - } - else { - return 'error'; - } - } - } - else { - return new Promise((resolve) => { - var _a, _b, _c; - const push = this._push(args.type, args, opts.timeout || this.timeout); - if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { - resolve('ok'); - } - push.receive('ok', () => resolve('ok')); - push.receive('error', () => resolve('error')); - push.receive('timeout', () => resolve('timed out')); - }); - } - } - updateJoinPayload(payload) { - this.joinPush.updatePayload(payload); - } - /** - * Leaves the channel. - * - * Unsubscribes from server events, and instructs channel to terminate on server. - * Triggers onClose() hooks. - * - * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: - * channel.unsubscribe().receive("ok", () => alert("left!") ) - */ - unsubscribe(timeout = this.timeout) { - this.state = constants_1.CHANNEL_STATES.leaving; - const onClose = () => { - this.socket.log('channel', `leave ${this.topic}`); - this._trigger(constants_1.CHANNEL_EVENTS.close, 'leave', this._joinRef()); - }; - this.joinPush.destroy(); - let leavePush = null; - return new Promise((resolve) => { - leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); - leavePush - .receive('ok', () => { - onClose(); - resolve('ok'); - }) - .receive('timeout', () => { - onClose(); - resolve('timed out'); - }) - .receive('error', () => { - resolve('error'); - }); - leavePush.send(); - if (!this._canPush()) { - leavePush.trigger('ok', {}); - } - }).finally(() => { - leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); - }); - } - /** - * Teardown the channel. - * - * Destroys and stops related timers. - */ - teardown() { - this.pushBuffer.forEach((push) => push.destroy()); - this.pushBuffer = []; - this.rejoinTimer.reset(); - this.joinPush.destroy(); - this.state = constants_1.CHANNEL_STATES.closed; - this.bindings = {}; - } - /** @internal */ - async _fetchWithTimeout(url, options, timeout) { - const controller = new AbortController(); - const id = setTimeout(() => controller.abort(), timeout); - const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); - clearTimeout(id); - return response; - } - /** @internal */ - _push(event, payload, timeout = this.timeout) { - if (!this.joinedOnce) { - throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; - } - let pushEvent = new push_1.default(this, event, payload, timeout); - if (this._canPush()) { - pushEvent.send(); - } - else { - this._addToPushBuffer(pushEvent); - } - return pushEvent; - } - /** @internal */ - _addToPushBuffer(pushEvent) { - pushEvent.startTimeout(); - this.pushBuffer.push(pushEvent); - // Enforce buffer size limit - if (this.pushBuffer.length > constants_1.MAX_PUSH_BUFFER_SIZE) { - const removedPush = this.pushBuffer.shift(); - if (removedPush) { - removedPush.destroy(); - this.socket.log('channel', `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); - } - } - } - /** - * Overridable message hook - * - * Receives all events for specialized message handling before dispatching to the channel callbacks. - * Must return the payload, modified or unmodified. - * - * @internal - */ - _onMessage(_event, payload, _ref) { - return payload; - } - /** @internal */ - _isMember(topic) { - return this.topic === topic; - } - /** @internal */ - _joinRef() { - return this.joinPush.ref; - } - /** @internal */ - _trigger(type, payload, ref) { - var _a, _b; - const typeLower = type.toLocaleLowerCase(); - const { close, error, leave, join } = constants_1.CHANNEL_EVENTS; - const events = [close, error, leave, join]; - if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { - return; - } - let handledPayload = this._onMessage(typeLower, payload, ref); - if (payload && !handledPayload) { - throw 'channel onMessage callbacks must return the payload, modified or unmodified'; - } - if (['insert', 'update', 'delete'].includes(typeLower)) { - (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { - var _a, _b, _c; - return ((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; - }).map((bind) => bind.callback(handledPayload, ref)); - } - else { - (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { - var _a, _b, _c, _d, _e, _f; - if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { - if ('id' in bind) { - const bindId = bind.id; - const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; - return (bindId && - ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && - (bindEvent === '*' || - (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); - } - else { - const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); - return bindEvent === '*' || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); - } - } - else { - return bind.type.toLocaleLowerCase() === typeLower; - } - }).map((bind) => { - if (typeof handledPayload === 'object' && 'ids' in handledPayload) { - const postgresChanges = handledPayload.data; - const { schema, table, commit_timestamp, type, errors } = postgresChanges; - const enrichedPayload = { - schema: schema, - table: table, - commit_timestamp: commit_timestamp, - eventType: type, - new: {}, - old: {}, - errors: errors, - }; - handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); - } - bind.callback(handledPayload, ref); - }); - } - } - /** @internal */ - _isClosed() { - return this.state === constants_1.CHANNEL_STATES.closed; - } - /** @internal */ - _isJoined() { - return this.state === constants_1.CHANNEL_STATES.joined; - } - /** @internal */ - _isJoining() { - return this.state === constants_1.CHANNEL_STATES.joining; - } - /** @internal */ - _isLeaving() { - return this.state === constants_1.CHANNEL_STATES.leaving; - } - /** @internal */ - _replyEventName(ref) { - return `chan_reply_${ref}`; - } - /** @internal */ - _on(type, filter, callback) { - const typeLower = type.toLocaleLowerCase(); - const binding = { - type: typeLower, - filter: filter, - callback: callback, - }; - if (this.bindings[typeLower]) { - this.bindings[typeLower].push(binding); - } - else { - this.bindings[typeLower] = [binding]; - } - return this; - } - /** @internal */ - _off(type, filter) { - const typeLower = type.toLocaleLowerCase(); - if (this.bindings[typeLower]) { - this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { - var _a; - return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && - RealtimeChannel.isEqual(bind.filter, filter)); - }); - } - return this; - } - /** @internal */ - static isEqual(obj1, obj2) { - if (Object.keys(obj1).length !== Object.keys(obj2).length) { - return false; - } - for (const k in obj1) { - if (obj1[k] !== obj2[k]) { - return false; - } - } - return true; - } - /** @internal */ - _rejoinUntilConnected() { - this.rejoinTimer.scheduleTimeout(); - if (this.socket.isConnected()) { - this._rejoin(); - } - } - /** - * Registers a callback that will be executed when the channel closes. - * - * @internal - */ - _onClose(callback) { - this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); - } - /** - * Registers a callback that will be executed when the channel encounteres an error. - * - * @internal - */ - _onError(callback) { - this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); - } - /** - * Returns `true` if the socket is connected and the channel has been joined. - * - * @internal - */ - _canPush() { - return this.socket.isConnected() && this._isJoined(); - } - /** @internal */ - _rejoin(timeout = this.timeout) { - if (this._isLeaving()) { - return; - } - this.socket._leaveOpenTopic(this.topic); - this.state = constants_1.CHANNEL_STATES.joining; - this.joinPush.resend(timeout); - } - /** @internal */ - _getPayloadRecords(payload) { - const records = { - new: {}, - old: {}, - }; - if (payload.type === 'INSERT' || payload.type === 'UPDATE') { - records.new = Transformers.convertChangeData(payload.columns, payload.record); - } - if (payload.type === 'UPDATE' || payload.type === 'DELETE') { - records.old = Transformers.convertChangeData(payload.columns, payload.old_record); - } - return records; - } -} -exports["default"] = RealtimeChannel; -//# sourceMappingURL=RealtimeChannel.js.map - -/***/ }), - -/***/ 9103: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(43478)); -const constants_1 = __nccwpck_require__(50088); -const serializer_1 = tslib_1.__importDefault(__nccwpck_require__(25360)); -const timer_1 = tslib_1.__importDefault(__nccwpck_require__(12983)); -const transformers_1 = __nccwpck_require__(1140); -const RealtimeChannel_1 = tslib_1.__importDefault(__nccwpck_require__(39911)); -const noop = () => { }; -// Connection-related constants -const CONNECTION_TIMEOUTS = { - HEARTBEAT_INTERVAL: 25000, - RECONNECT_DELAY: 10, - HEARTBEAT_TIMEOUT_FALLBACK: 100, -}; -const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000]; -const DEFAULT_RECONNECT_FALLBACK = 10000; -const WORKER_SCRIPT = ` - addEventListener("message", (e) => { - if (e.data.event === "start") { - setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); - } - });`; -class RealtimeClient { - /** - * Initializes the Socket. - * - * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) - * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) - * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation - * @param options.timeout The default timeout in milliseconds to trigger push timeouts. - * @param options.params The optional params to pass when connecting. - * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. - * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. - * @param options.heartbeatCallback The optional function to handle heartbeat status. - * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } - * @param options.logLevel Sets the log level for Realtime - * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) - * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. - * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. - * @param options.worker Use Web Worker to set a side flow. Defaults to false. - * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. - */ - constructor(endPoint, options) { - var _a; - this.accessTokenValue = null; - this.apiKey = null; - this.channels = new Array(); - this.endPoint = ''; - this.httpEndpoint = ''; - /** @deprecated headers cannot be set on websocket connections */ - this.headers = {}; - this.params = {}; - this.timeout = constants_1.DEFAULT_TIMEOUT; - this.transport = null; - this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; - this.heartbeatTimer = undefined; - this.pendingHeartbeatRef = null; - this.heartbeatCallback = noop; - this.ref = 0; - this.reconnectTimer = null; - this.logger = noop; - this.conn = null; - this.sendBuffer = []; - this.serializer = new serializer_1.default(); - this.stateChangeCallbacks = { - open: [], - close: [], - error: [], - message: [], - }; - this.accessToken = null; - this._connectionState = 'disconnected'; - this._wasManualDisconnect = false; - this._authPromise = null; - /** - * Use either custom fetch, if provided, or default fetch to make HTTP requests - * - * @internal - */ - this._resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - // Node.js environment without native fetch - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s))).then(({ default: fetch }) => fetch(...args)) - .catch((error) => { - throw new Error(`Failed to load @supabase/node-fetch: ${error.message}. ` + - `This is required for HTTP requests in Node.js environments without native fetch.`); - }); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); - }; - // Validate required parameters - if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) { - throw new Error('API key is required to connect to Realtime'); - } - this.apiKey = options.params.apikey; - // Initialize endpoint URLs - this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; - this.httpEndpoint = (0, transformers_1.httpEndpointURL)(endPoint); - this._initializeOptions(options); - this._setupReconnectionTimer(); - this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); - } - /** - * Connects the socket, unless already connected. - */ - connect() { - // Skip if already connecting, disconnecting, or connected - if (this.isConnecting() || - this.isDisconnecting() || - (this.conn !== null && this.isConnected())) { - return; - } - this._setConnectionState('connecting'); - this._setAuthSafely('connect'); - // Establish WebSocket connection - if (this.transport) { - // Use custom transport if provided - this.conn = new this.transport(this.endpointURL()); - } - else { - // Try to use native WebSocket - try { - this.conn = websocket_factory_1.default.createWebSocket(this.endpointURL()); - } - catch (error) { - this._setConnectionState('disconnected'); - const errorMessage = error.message; - // Provide helpful error message based on environment - if (errorMessage.includes('Node.js')) { - throw new Error(`${errorMessage}\n\n` + - 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' + - 'Option 1: Use Node.js 22+ which has native WebSocket support\n' + - 'Option 2: Install and provide the "ws" package:\n\n' + - ' npm install ws\n\n' + - ' import ws from "ws"\n' + - ' const client = new RealtimeClient(url, {\n' + - ' ...options,\n' + - ' transport: ws\n' + - ' })'); - } - throw new Error(`WebSocket not available: ${errorMessage}`); - } - } - this._setupConnectionHandlers(); - } - /** - * Returns the URL of the websocket. - * @returns string The URL of the websocket. - */ - endpointURL() { - return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: constants_1.VSN })); - } - /** - * Disconnects the socket. - * - * @param code A numeric status code to send on disconnect. - * @param reason A custom reason for the disconnect. - */ - disconnect(code, reason) { - if (this.isDisconnecting()) { - return; - } - this._setConnectionState('disconnecting', true); - if (this.conn) { - // Setup fallback timer to prevent hanging in disconnecting state - const fallbackTimer = setTimeout(() => { - this._setConnectionState('disconnected'); - }, 100); - this.conn.onclose = () => { - clearTimeout(fallbackTimer); - this._setConnectionState('disconnected'); - }; - // Close the WebSocket connection - if (code) { - this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); - } - else { - this.conn.close(); - } - this._teardownConnection(); - } - else { - this._setConnectionState('disconnected'); - } - } - /** - * Returns all created channels - */ - getChannels() { - return this.channels; - } - /** - * Unsubscribes and removes a single channel - * @param channel A RealtimeChannel instance - */ - async removeChannel(channel) { - const status = await channel.unsubscribe(); - if (this.channels.length === 0) { - this.disconnect(); - } - return status; - } - /** - * Unsubscribes and removes all channels - */ - async removeAllChannels() { - const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); - this.channels = []; - this.disconnect(); - return values_1; - } - /** - * Logs the message. - * - * For customized logging, `this.logger` can be overridden. - */ - log(kind, msg, data) { - this.logger(kind, msg, data); - } - /** - * Returns the current state of the socket. - */ - connectionState() { - switch (this.conn && this.conn.readyState) { - case constants_1.SOCKET_STATES.connecting: - return constants_1.CONNECTION_STATE.Connecting; - case constants_1.SOCKET_STATES.open: - return constants_1.CONNECTION_STATE.Open; - case constants_1.SOCKET_STATES.closing: - return constants_1.CONNECTION_STATE.Closing; - default: - return constants_1.CONNECTION_STATE.Closed; - } - } - /** - * Returns `true` is the connection is open. - */ - isConnected() { - return this.connectionState() === constants_1.CONNECTION_STATE.Open; - } - /** - * Returns `true` if the connection is currently connecting. - */ - isConnecting() { - return this._connectionState === 'connecting'; - } - /** - * Returns `true` if the connection is currently disconnecting. - */ - isDisconnecting() { - return this._connectionState === 'disconnecting'; - } - channel(topic, params = { config: {} }) { - const realtimeTopic = `realtime:${topic}`; - const exists = this.getChannels().find((c) => c.topic === realtimeTopic); - if (!exists) { - const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); - this.channels.push(chan); - return chan; - } - else { - return exists; - } - } - /** - * Push out a message if the socket is connected. - * - * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. - */ - push(data) { - const { topic, event, payload, ref } = data; - const callback = () => { - this.encode(data, (result) => { - var _a; - (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); - }); - }; - this.log('push', `${topic} ${event} (${ref})`, payload); - if (this.isConnected()) { - callback(); - } - else { - this.sendBuffer.push(callback); - } - } - /** - * Sets the JWT access token used for channel subscription authorization and Realtime RLS. - * - * If param is null it will use the `accessToken` callback function or the token set on the client. - * - * On callback used, it will set the value of the token internal to the client. - * - * @param token A JWT string to override the token set on the client. - */ - async setAuth(token = null) { - this._authPromise = this._performAuth(token); - try { - await this._authPromise; - } - finally { - this._authPromise = null; - } - } - /** - * Sends a heartbeat message if the socket is connected. - */ - async sendHeartbeat() { - var _a; - if (!this.isConnected()) { - try { - this.heartbeatCallback('disconnected'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - return; - } - // Handle heartbeat timeout and force reconnection if needed - if (this.pendingHeartbeatRef) { - this.pendingHeartbeatRef = null; - this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); - try { - this.heartbeatCallback('timeout'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - // Force reconnection after heartbeat timeout - this._wasManualDisconnect = false; - (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, 'heartbeat timeout'); - setTimeout(() => { - var _a; - if (!this.isConnected()) { - (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); - } - }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); - return; - } - // Send heartbeat message to server - this.pendingHeartbeatRef = this._makeRef(); - this.push({ - topic: 'phoenix', - event: 'heartbeat', - payload: {}, - ref: this.pendingHeartbeatRef, - }); - try { - this.heartbeatCallback('sent'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - this._setAuthSafely('heartbeat'); - } - onHeartbeat(callback) { - this.heartbeatCallback = callback; - } - /** - * Flushes send buffer - */ - flushSendBuffer() { - if (this.isConnected() && this.sendBuffer.length > 0) { - this.sendBuffer.forEach((callback) => callback()); - this.sendBuffer = []; - } - } - /** - * Return the next message ref, accounting for overflows - * - * @internal - */ - _makeRef() { - let newRef = this.ref + 1; - if (newRef === this.ref) { - this.ref = 0; - } - else { - this.ref = newRef; - } - return this.ref.toString(); - } - /** - * Unsubscribe from channels with the specified topic. - * - * @internal - */ - _leaveOpenTopic(topic) { - let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); - if (dupChannel) { - this.log('transport', `leaving duplicate topic "${topic}"`); - dupChannel.unsubscribe(); - } - } - /** - * Removes a subscription from the socket. - * - * @param channel An open subscription. - * - * @internal - */ - _remove(channel) { - this.channels = this.channels.filter((c) => c.topic !== channel.topic); - } - /** @internal */ - _onConnMessage(rawMessage) { - this.decode(rawMessage.data, (msg) => { - // Handle heartbeat responses - if (msg.topic === 'phoenix' && msg.event === 'phx_reply') { - try { - this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error'); - } - catch (e) { - this.log('error', 'error in heartbeat callback', e); - } - } - // Handle pending heartbeat reference cleanup - if (msg.ref && msg.ref === this.pendingHeartbeatRef) { - this.pendingHeartbeatRef = null; - } - // Log incoming message - const { topic, event, payload, ref } = msg; - const refString = ref ? `(${ref})` : ''; - const status = payload.status || ''; - this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload); - // Route message to appropriate channels - this.channels - .filter((channel) => channel._isMember(topic)) - .forEach((channel) => channel._trigger(event, payload, ref)); - this._triggerStateCallbacks('message', msg); - }); - } - /** - * Clear specific timer - * @internal - */ - _clearTimer(timer) { - var _a; - if (timer === 'heartbeat' && this.heartbeatTimer) { - clearInterval(this.heartbeatTimer); - this.heartbeatTimer = undefined; - } - else if (timer === 'reconnect') { - (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset(); - } - } - /** - * Clear all timers - * @internal - */ - _clearAllTimers() { - this._clearTimer('heartbeat'); - this._clearTimer('reconnect'); - } - /** - * Setup connection handlers for WebSocket events - * @internal - */ - _setupConnectionHandlers() { - if (!this.conn) - return; - // Set binary type if supported (browsers and most WebSocket implementations) - if ('binaryType' in this.conn) { - ; - this.conn.binaryType = 'arraybuffer'; - } - this.conn.onopen = () => this._onConnOpen(); - this.conn.onerror = (error) => this._onConnError(error); - this.conn.onmessage = (event) => this._onConnMessage(event); - this.conn.onclose = (event) => this._onConnClose(event); - } - /** - * Teardown connection and cleanup resources - * @internal - */ - _teardownConnection() { - if (this.conn) { - this.conn.onopen = null; - this.conn.onerror = null; - this.conn.onmessage = null; - this.conn.onclose = null; - this.conn = null; - } - this._clearAllTimers(); - this.channels.forEach((channel) => channel.teardown()); - } - /** @internal */ - _onConnOpen() { - this._setConnectionState('connected'); - this.log('transport', `connected to ${this.endpointURL()}`); - this.flushSendBuffer(); - this._clearTimer('reconnect'); - if (!this.worker) { - this._startHeartbeat(); - } - else { - if (!this.workerRef) { - this._startWorkerHeartbeat(); - } - } - this._triggerStateCallbacks('open'); - } - /** @internal */ - _startHeartbeat() { - this.heartbeatTimer && clearInterval(this.heartbeatTimer); - this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); - } - /** @internal */ - _startWorkerHeartbeat() { - if (this.workerUrl) { - this.log('worker', `starting worker for from ${this.workerUrl}`); - } - else { - this.log('worker', `starting default worker`); - } - const objectUrl = this._workerObjectUrl(this.workerUrl); - this.workerRef = new Worker(objectUrl); - this.workerRef.onerror = (error) => { - this.log('worker', 'worker error', error.message); - this.workerRef.terminate(); - }; - this.workerRef.onmessage = (event) => { - if (event.data.event === 'keepAlive') { - this.sendHeartbeat(); - } - }; - this.workerRef.postMessage({ - event: 'start', - interval: this.heartbeatIntervalMs, - }); - } - /** @internal */ - _onConnClose(event) { - var _a; - this._setConnectionState('disconnected'); - this.log('transport', 'close', event); - this._triggerChanError(); - this._clearTimer('heartbeat'); - // Only schedule reconnection if it wasn't a manual disconnect - if (!this._wasManualDisconnect) { - (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); - } - this._triggerStateCallbacks('close', event); - } - /** @internal */ - _onConnError(error) { - this._setConnectionState('disconnected'); - this.log('transport', `${error}`); - this._triggerChanError(); - this._triggerStateCallbacks('error', error); - } - /** @internal */ - _triggerChanError() { - this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); - } - /** @internal */ - _appendParams(url, params) { - if (Object.keys(params).length === 0) { - return url; - } - const prefix = url.match(/\?/) ? '&' : '?'; - const query = new URLSearchParams(params); - return `${url}${prefix}${query}`; - } - _workerObjectUrl(url) { - let result_url; - if (url) { - result_url = url; - } - else { - const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' }); - result_url = URL.createObjectURL(blob); - } - return result_url; - } - /** - * Set connection state with proper state management - * @internal - */ - _setConnectionState(state, manual = false) { - this._connectionState = state; - if (state === 'connecting') { - this._wasManualDisconnect = false; - } - else if (state === 'disconnecting') { - this._wasManualDisconnect = manual; - } - } - /** - * Perform the actual auth operation - * @internal - */ - async _performAuth(token = null) { - let tokenToSend; - if (token) { - tokenToSend = token; - } - else if (this.accessToken) { - // Always call the accessToken callback to get fresh token - tokenToSend = await this.accessToken(); - } - else { - tokenToSend = this.accessTokenValue; - } - if (this.accessTokenValue != tokenToSend) { - this.accessTokenValue = tokenToSend; - this.channels.forEach((channel) => { - const payload = { - access_token: tokenToSend, - version: constants_1.DEFAULT_VERSION, - }; - tokenToSend && channel.updateJoinPayload(payload); - if (channel.joinedOnce && channel._isJoined()) { - channel._push(constants_1.CHANNEL_EVENTS.access_token, { - access_token: tokenToSend, - }); - } - }); - } - } - /** - * Wait for any in-flight auth operations to complete - * @internal - */ - async _waitForAuthIfNeeded() { - if (this._authPromise) { - await this._authPromise; - } - } - /** - * Safely call setAuth with standardized error handling - * @internal - */ - _setAuthSafely(context = 'general') { - this.setAuth().catch((e) => { - this.log('error', `error setting auth in ${context}`, e); - }); - } - /** - * Trigger state change callbacks with proper error handling - * @internal - */ - _triggerStateCallbacks(event, data) { - try { - this.stateChangeCallbacks[event].forEach((callback) => { - try { - callback(data); - } - catch (e) { - this.log('error', `error in ${event} callback`, e); - } - }); - } - catch (e) { - this.log('error', `error triggering ${event} callbacks`, e); - } - } - /** - * Setup reconnection timer with proper configuration - * @internal - */ - _setupReconnectionTimer() { - this.reconnectTimer = new timer_1.default(async () => { - setTimeout(async () => { - await this._waitForAuthIfNeeded(); - if (!this.isConnected()) { - this.connect(); - } - }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); - }, this.reconnectAfterMs); - } - /** - * Initialize client options with defaults - * @internal - */ - _initializeOptions(options) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j; - // Set defaults - this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null; - this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT; - this.heartbeatIntervalMs = - (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; - this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; - this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null; - this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; - // Handle special cases - if (options === null || options === void 0 ? void 0 : options.params) - this.params = options.params; - if (options === null || options === void 0 ? void 0 : options.logger) - this.logger = options.logger; - if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { - this.logLevel = options.logLevel || options.log_level; - this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); - } - // Set up functions with defaults - this.reconnectAfterMs = - (_g = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _g !== void 0 ? _g : ((tries) => { - return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; - }); - this.encode = - (_h = options === null || options === void 0 ? void 0 : options.encode) !== null && _h !== void 0 ? _h : ((payload, callback) => { - return callback(JSON.stringify(payload)); - }); - this.decode = (_j = options === null || options === void 0 ? void 0 : options.decode) !== null && _j !== void 0 ? _j : this.serializer.decode.bind(this.serializer); - // Handle worker setup - if (this.worker) { - if (typeof window !== 'undefined' && !window.Worker) { - throw new Error('Web Worker is not supported'); - } - this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; - } - } -} -exports["default"] = RealtimeClient; -//# sourceMappingURL=RealtimeClient.js.map - -/***/ }), - -/***/ 75583: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/* - This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js - License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md -*/ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; -var REALTIME_PRESENCE_LISTEN_EVENTS; -(function (REALTIME_PRESENCE_LISTEN_EVENTS) { - REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; - REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; - REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; -})(REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS = {})); -class RealtimePresence { - /** - * Initializes the Presence. - * - * @param channel - The RealtimeChannel - * @param opts - The options, - * for example `{events: {state: 'state', diff: 'diff'}}` - */ - constructor(channel, opts) { - this.channel = channel; - this.state = {}; - this.pendingDiffs = []; - this.joinRef = null; - this.enabled = false; - this.caller = { - onJoin: () => { }, - onLeave: () => { }, - onSync: () => { }, - }; - const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { - state: 'presence_state', - diff: 'presence_diff', - }; - this.channel._on(events.state, {}, (newState) => { - const { onJoin, onLeave, onSync } = this.caller; - this.joinRef = this.channel._joinRef(); - this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); - this.pendingDiffs.forEach((diff) => { - this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); - }); - this.pendingDiffs = []; - onSync(); - }); - this.channel._on(events.diff, {}, (diff) => { - const { onJoin, onLeave, onSync } = this.caller; - if (this.inPendingSyncState()) { - this.pendingDiffs.push(diff); - } - else { - this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); - onSync(); - } - }); - this.onJoin((key, currentPresences, newPresences) => { - this.channel._trigger('presence', { - event: 'join', - key, - currentPresences, - newPresences, - }); - }); - this.onLeave((key, currentPresences, leftPresences) => { - this.channel._trigger('presence', { - event: 'leave', - key, - currentPresences, - leftPresences, - }); - }); - this.onSync(() => { - this.channel._trigger('presence', { event: 'sync' }); - }); - } - /** - * Used to sync the list of presences on the server with the - * client's state. - * - * An optional `onJoin` and `onLeave` callback can be provided to - * react to changes in the client's local presences across - * disconnects and reconnects with the server. - * - * @internal - */ - static syncState(currentState, newState, onJoin, onLeave) { - const state = this.cloneDeep(currentState); - const transformedState = this.transformState(newState); - const joins = {}; - const leaves = {}; - this.map(state, (key, presences) => { - if (!transformedState[key]) { - leaves[key] = presences; - } - }); - this.map(transformedState, (key, newPresences) => { - const currentPresences = state[key]; - if (currentPresences) { - const newPresenceRefs = newPresences.map((m) => m.presence_ref); - const curPresenceRefs = currentPresences.map((m) => m.presence_ref); - const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); - const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); - if (joinedPresences.length > 0) { - joins[key] = joinedPresences; - } - if (leftPresences.length > 0) { - leaves[key] = leftPresences; - } - } - else { - joins[key] = newPresences; - } - }); - return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); - } - /** - * Used to sync a diff of presence join and leave events from the - * server, as they happen. - * - * Like `syncState`, `syncDiff` accepts optional `onJoin` and - * `onLeave` callbacks to react to a user joining or leaving from a - * device. - * - * @internal - */ - static syncDiff(state, diff, onJoin, onLeave) { - const { joins, leaves } = { - joins: this.transformState(diff.joins), - leaves: this.transformState(diff.leaves), - }; - if (!onJoin) { - onJoin = () => { }; - } - if (!onLeave) { - onLeave = () => { }; - } - this.map(joins, (key, newPresences) => { - var _a; - const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; - state[key] = this.cloneDeep(newPresences); - if (currentPresences.length > 0) { - const joinedPresenceRefs = state[key].map((m) => m.presence_ref); - const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); - state[key].unshift(...curPresences); - } - onJoin(key, currentPresences, newPresences); - }); - this.map(leaves, (key, leftPresences) => { - let currentPresences = state[key]; - if (!currentPresences) - return; - const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); - currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); - state[key] = currentPresences; - onLeave(key, currentPresences, leftPresences); - if (currentPresences.length === 0) - delete state[key]; - }); - return state; - } - /** @internal */ - static map(obj, func) { - return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); - } - /** - * Remove 'metas' key - * Change 'phx_ref' to 'presence_ref' - * Remove 'phx_ref' and 'phx_ref_prev' - * - * @example - * // returns { - * abc123: [ - * { presence_ref: '2', user_id: 1 }, - * { presence_ref: '3', user_id: 2 } - * ] - * } - * RealtimePresence.transformState({ - * abc123: { - * metas: [ - * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, - * { phx_ref: '3', user_id: 2 } - * ] - * } - * }) - * - * @internal - */ - static transformState(state) { - state = this.cloneDeep(state); - return Object.getOwnPropertyNames(state).reduce((newState, key) => { - const presences = state[key]; - if ('metas' in presences) { - newState[key] = presences.metas.map((presence) => { - presence['presence_ref'] = presence['phx_ref']; - delete presence['phx_ref']; - delete presence['phx_ref_prev']; - return presence; - }); - } - else { - newState[key] = presences; - } - return newState; - }, {}); - } - /** @internal */ - static cloneDeep(obj) { - return JSON.parse(JSON.stringify(obj)); - } - /** @internal */ - onJoin(callback) { - this.caller.onJoin = callback; - } - /** @internal */ - onLeave(callback) { - this.caller.onLeave = callback; - } - /** @internal */ - onSync(callback) { - this.caller.onSync = callback; - } - /** @internal */ - inPendingSyncState() { - return !this.joinRef || this.joinRef !== this.channel._joinRef(); - } -} -exports["default"] = RealtimePresence; -//# sourceMappingURL=RealtimePresence.js.map - -/***/ }), - -/***/ 60442: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; -const tslib_1 = __nccwpck_require__(4351); -const RealtimeClient_1 = tslib_1.__importDefault(__nccwpck_require__(9103)); -exports.RealtimeClient = RealtimeClient_1.default; -const RealtimeChannel_1 = tslib_1.__importStar(__nccwpck_require__(39911)); -exports.RealtimeChannel = RealtimeChannel_1.default; -Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_LISTEN_TYPES; } })); -Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } })); -Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; } })); -Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_CHANNEL_STATES; } })); -const RealtimePresence_1 = tslib_1.__importStar(__nccwpck_require__(75583)); -exports.RealtimePresence = RealtimePresence_1.default; -Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", ({ enumerable: true, get: function () { return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; } })); -const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(43478)); -exports.WebSocketFactory = websocket_factory_1.default; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 50088: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.VSN = exports.DEFAULT_VERSION = void 0; -const version_1 = __nccwpck_require__(50318); -exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`; -exports.VSN = '1.0.0'; -exports.VERSION = version_1.version; -exports.DEFAULT_TIMEOUT = 10000; -exports.WS_CLOSE_NORMAL = 1000; -exports.MAX_PUSH_BUFFER_SIZE = 100; -var SOCKET_STATES; -(function (SOCKET_STATES) { - SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; - SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; - SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; - SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; -})(SOCKET_STATES || (exports.SOCKET_STATES = SOCKET_STATES = {})); -var CHANNEL_STATES; -(function (CHANNEL_STATES) { - CHANNEL_STATES["closed"] = "closed"; - CHANNEL_STATES["errored"] = "errored"; - CHANNEL_STATES["joined"] = "joined"; - CHANNEL_STATES["joining"] = "joining"; - CHANNEL_STATES["leaving"] = "leaving"; -})(CHANNEL_STATES || (exports.CHANNEL_STATES = CHANNEL_STATES = {})); -var CHANNEL_EVENTS; -(function (CHANNEL_EVENTS) { - CHANNEL_EVENTS["close"] = "phx_close"; - CHANNEL_EVENTS["error"] = "phx_error"; - CHANNEL_EVENTS["join"] = "phx_join"; - CHANNEL_EVENTS["reply"] = "phx_reply"; - CHANNEL_EVENTS["leave"] = "phx_leave"; - CHANNEL_EVENTS["access_token"] = "access_token"; -})(CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = CHANNEL_EVENTS = {})); -var TRANSPORTS; -(function (TRANSPORTS) { - TRANSPORTS["websocket"] = "websocket"; -})(TRANSPORTS || (exports.TRANSPORTS = TRANSPORTS = {})); -var CONNECTION_STATE; -(function (CONNECTION_STATE) { - CONNECTION_STATE["Connecting"] = "connecting"; - CONNECTION_STATE["Open"] = "open"; - CONNECTION_STATE["Closing"] = "closing"; - CONNECTION_STATE["Closed"] = "closed"; -})(CONNECTION_STATE || (exports.CONNECTION_STATE = CONNECTION_STATE = {})); -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 82292: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const constants_1 = __nccwpck_require__(50088); -class Push { - /** - * Initializes the Push - * - * @param channel The Channel - * @param event The event, for example `"phx_join"` - * @param payload The payload, for example `{user_id: 123}` - * @param timeout The push timeout in milliseconds - */ - constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { - this.channel = channel; - this.event = event; - this.payload = payload; - this.timeout = timeout; - this.sent = false; - this.timeoutTimer = undefined; - this.ref = ''; - this.receivedResp = null; - this.recHooks = []; - this.refEvent = null; - } - resend(timeout) { - this.timeout = timeout; - this._cancelRefEvent(); - this.ref = ''; - this.refEvent = null; - this.receivedResp = null; - this.sent = false; - this.send(); - } - send() { - if (this._hasReceived('timeout')) { - return; - } - this.startTimeout(); - this.sent = true; - this.channel.socket.push({ - topic: this.channel.topic, - event: this.event, - payload: this.payload, - ref: this.ref, - join_ref: this.channel._joinRef(), - }); - } - updatePayload(payload) { - this.payload = Object.assign(Object.assign({}, this.payload), payload); - } - receive(status, callback) { - var _a; - if (this._hasReceived(status)) { - callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); - } - this.recHooks.push({ status, callback }); - return this; - } - startTimeout() { - if (this.timeoutTimer) { - return; - } - this.ref = this.channel.socket._makeRef(); - this.refEvent = this.channel._replyEventName(this.ref); - const callback = (payload) => { - this._cancelRefEvent(); - this._cancelTimeout(); - this.receivedResp = payload; - this._matchReceive(payload); - }; - this.channel._on(this.refEvent, {}, callback); - this.timeoutTimer = setTimeout(() => { - this.trigger('timeout', {}); - }, this.timeout); - } - trigger(status, response) { - if (this.refEvent) - this.channel._trigger(this.refEvent, { status, response }); - } - destroy() { - this._cancelRefEvent(); - this._cancelTimeout(); - } - _cancelRefEvent() { - if (!this.refEvent) { - return; - } - this.channel._off(this.refEvent, {}); - } - _cancelTimeout() { - clearTimeout(this.timeoutTimer); - this.timeoutTimer = undefined; - } - _matchReceive({ status, response }) { - this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)); - } - _hasReceived(status) { - return this.receivedResp && this.receivedResp.status === status; - } -} -exports["default"] = Push; -//# sourceMappingURL=push.js.map - -/***/ }), - -/***/ 25360: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe -// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md -Object.defineProperty(exports, "__esModule", ({ value: true })); -class Serializer { - constructor() { - this.HEADER_LENGTH = 1; - } - decode(rawPayload, callback) { - if (rawPayload.constructor === ArrayBuffer) { - return callback(this._binaryDecode(rawPayload)); - } - if (typeof rawPayload === 'string') { - return callback(JSON.parse(rawPayload)); - } - return callback({}); - } - _binaryDecode(buffer) { - const view = new DataView(buffer); - const decoder = new TextDecoder(); - return this._decodeBroadcast(buffer, view, decoder); - } - _decodeBroadcast(buffer, view, decoder) { - const topicSize = view.getUint8(1); - const eventSize = view.getUint8(2); - let offset = this.HEADER_LENGTH + 2; - const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); - offset = offset + topicSize; - const event = decoder.decode(buffer.slice(offset, offset + eventSize)); - offset = offset + eventSize; - const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength))); - return { ref: null, topic: topic, event: event, payload: data }; - } -} -exports["default"] = Serializer; -//# sourceMappingURL=serializer.js.map - -/***/ }), - -/***/ 12983: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. - * - * @example - * let reconnectTimer = new Timer(() => this.connect(), function(tries){ - * return [1000, 5000, 10000][tries - 1] || 10000 - * }) - * reconnectTimer.scheduleTimeout() // fires after 1000 - * reconnectTimer.scheduleTimeout() // fires after 5000 - * reconnectTimer.reset() - * reconnectTimer.scheduleTimeout() // fires after 1000 - */ -class Timer { - constructor(callback, timerCalc) { - this.callback = callback; - this.timerCalc = timerCalc; - this.timer = undefined; - this.tries = 0; - this.callback = callback; - this.timerCalc = timerCalc; - } - reset() { - this.tries = 0; - clearTimeout(this.timer); - this.timer = undefined; - } - // Cancels any previous scheduleTimeout and schedules callback - scheduleTimeout() { - clearTimeout(this.timer); - this.timer = setTimeout(() => { - this.tries = this.tries + 1; - this.callback(); - }, this.timerCalc(this.tries + 1)); - } -} -exports["default"] = Timer; -//# sourceMappingURL=timer.js.map - -/***/ }), - -/***/ 1140: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -/** - * Helpers to convert the change Payload into native JS types. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.httpEndpointURL = exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; -// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under -// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE -var PostgresTypes; -(function (PostgresTypes) { - PostgresTypes["abstime"] = "abstime"; - PostgresTypes["bool"] = "bool"; - PostgresTypes["date"] = "date"; - PostgresTypes["daterange"] = "daterange"; - PostgresTypes["float4"] = "float4"; - PostgresTypes["float8"] = "float8"; - PostgresTypes["int2"] = "int2"; - PostgresTypes["int4"] = "int4"; - PostgresTypes["int4range"] = "int4range"; - PostgresTypes["int8"] = "int8"; - PostgresTypes["int8range"] = "int8range"; - PostgresTypes["json"] = "json"; - PostgresTypes["jsonb"] = "jsonb"; - PostgresTypes["money"] = "money"; - PostgresTypes["numeric"] = "numeric"; - PostgresTypes["oid"] = "oid"; - PostgresTypes["reltime"] = "reltime"; - PostgresTypes["text"] = "text"; - PostgresTypes["time"] = "time"; - PostgresTypes["timestamp"] = "timestamp"; - PostgresTypes["timestamptz"] = "timestamptz"; - PostgresTypes["timetz"] = "timetz"; - PostgresTypes["tsrange"] = "tsrange"; - PostgresTypes["tstzrange"] = "tstzrange"; -})(PostgresTypes || (exports.PostgresTypes = PostgresTypes = {})); -/** - * Takes an array of columns and an object of string values then converts each string value - * to its mapped type. - * - * @param {{name: String, type: String}[]} columns - * @param {Object} record - * @param {Object} options The map of various options that can be applied to the mapper - * @param {Array} options.skipTypes The array of types that should not be converted - * - * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) - * //=>{ first_name: 'Paul', age: 33 } - */ -const convertChangeData = (columns, record, options = {}) => { - var _a; - const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; - if (!record) { - return {}; - } - return Object.keys(record).reduce((acc, rec_key) => { - acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); - return acc; - }, {}); -}; -exports.convertChangeData = convertChangeData; -/** - * Converts the value of an individual column. - * - * @param {String} columnName The column that you want to convert - * @param {{name: String, type: String}[]} columns All of the columns - * @param {Object} record The map of string values - * @param {Array} skipTypes An array of types that should not be converted - * @return {object} Useless information - * - * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) - * //=> 33 - * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) - * //=> "33" - */ -const convertColumn = (columnName, columns, record, skipTypes) => { - const column = columns.find((x) => x.name === columnName); - const colType = column === null || column === void 0 ? void 0 : column.type; - const value = record[columnName]; - if (colType && !skipTypes.includes(colType)) { - return (0, exports.convertCell)(colType, value); - } - return noop(value); -}; -exports.convertColumn = convertColumn; -/** - * If the value of the cell is `null`, returns null. - * Otherwise converts the string value to the correct type. - * @param {String} type A postgres column type - * @param {String} value The cell value - * - * @example convertCell('bool', 't') - * //=> true - * @example convertCell('int8', '10') - * //=> 10 - * @example convertCell('_int4', '{1,2,3,4}') - * //=> [1,2,3,4] - */ -const convertCell = (type, value) => { - // if data type is an array - if (type.charAt(0) === '_') { - const dataType = type.slice(1, type.length); - return (0, exports.toArray)(value, dataType); - } - // If not null, convert to correct type. - switch (type) { - case PostgresTypes.bool: - return (0, exports.toBoolean)(value); - case PostgresTypes.float4: - case PostgresTypes.float8: - case PostgresTypes.int2: - case PostgresTypes.int4: - case PostgresTypes.int8: - case PostgresTypes.numeric: - case PostgresTypes.oid: - return (0, exports.toNumber)(value); - case PostgresTypes.json: - case PostgresTypes.jsonb: - return (0, exports.toJson)(value); - case PostgresTypes.timestamp: - return (0, exports.toTimestampString)(value); // Format to be consistent with PostgREST - case PostgresTypes.abstime: // To allow users to cast it based on Timezone - case PostgresTypes.date: // To allow users to cast it based on Timezone - case PostgresTypes.daterange: - case PostgresTypes.int4range: - case PostgresTypes.int8range: - case PostgresTypes.money: - case PostgresTypes.reltime: // To allow users to cast it based on Timezone - case PostgresTypes.text: - case PostgresTypes.time: // To allow users to cast it based on Timezone - case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone - case PostgresTypes.timetz: // To allow users to cast it based on Timezone - case PostgresTypes.tsrange: - case PostgresTypes.tstzrange: - return noop(value); - default: - // Return the value for remaining types - return noop(value); - } -}; -exports.convertCell = convertCell; -const noop = (value) => { - return value; -}; -const toBoolean = (value) => { - switch (value) { - case 't': - return true; - case 'f': - return false; - default: - return value; - } -}; -exports.toBoolean = toBoolean; -const toNumber = (value) => { - if (typeof value === 'string') { - const parsedValue = parseFloat(value); - if (!Number.isNaN(parsedValue)) { - return parsedValue; - } - } - return value; -}; -exports.toNumber = toNumber; -const toJson = (value) => { - if (typeof value === 'string') { - try { - return JSON.parse(value); - } - catch (error) { - console.log(`JSON parse error: ${error}`); - return value; - } - } - return value; -}; -exports.toJson = toJson; -/** - * Converts a Postgres Array into a native JS array - * - * @example toArray('{}', 'int4') - * //=> [] - * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') - * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] - * @example toArray([1,2,3,4], 'int4') - * //=> [1,2,3,4] - */ -const toArray = (value, type) => { - if (typeof value !== 'string') { - return value; - } - const lastIdx = value.length - 1; - const closeBrace = value[lastIdx]; - const openBrace = value[0]; - // Confirm value is a Postgres array by checking curly brackets - if (openBrace === '{' && closeBrace === '}') { - let arr; - const valTrim = value.slice(1, lastIdx); - // TODO: find a better solution to separate Postgres array data - try { - arr = JSON.parse('[' + valTrim + ']'); - } - catch (_) { - // WARNING: splitting on comma does not cover all edge cases - arr = valTrim ? valTrim.split(',') : []; - } - return arr.map((val) => (0, exports.convertCell)(type, val)); - } - return value; -}; -exports.toArray = toArray; -/** - * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' - * See https://github.com/supabase/supabase/issues/18 - * - * @example toTimestampString('2019-09-10 00:00:00') - * //=> '2019-09-10T00:00:00' - */ -const toTimestampString = (value) => { - if (typeof value === 'string') { - return value.replace(' ', 'T'); - } - return value; -}; -exports.toTimestampString = toTimestampString; -const httpEndpointURL = (socketUrl) => { - const wsUrl = new URL(socketUrl); - wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http'); - wsUrl.pathname = wsUrl.pathname - .replace(/\/+$/, '') // remove all trailing slashes - .replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path - .replace(/\/socket$/i, '') // remove the socket path - .replace(/\/websocket$/i, ''); // remove the websocket path - if (wsUrl.pathname === '' || wsUrl.pathname === '/') { - wsUrl.pathname = '/api/broadcast'; - } - else { - wsUrl.pathname = wsUrl.pathname + '/api/broadcast'; - } - return wsUrl.href; -}; -exports.httpEndpointURL = httpEndpointURL; -//# sourceMappingURL=transformers.js.map - -/***/ }), - -/***/ 50318: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 43478: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WebSocketFactory = void 0; -class WebSocketFactory { - static detectEnvironment() { - var _a; - if (typeof WebSocket !== 'undefined') { - return { type: 'native', constructor: WebSocket }; - } - if (typeof globalThis !== 'undefined' && typeof globalThis.WebSocket !== 'undefined') { - return { type: 'native', constructor: globalThis.WebSocket }; - } - if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') { - return { type: 'native', constructor: global.WebSocket }; - } - if (typeof globalThis !== 'undefined' && - typeof globalThis.WebSocketPair !== 'undefined' && - typeof globalThis.WebSocket === 'undefined') { - return { - type: 'cloudflare', - error: 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.', - workaround: 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.', - }; - } - if ((typeof globalThis !== 'undefined' && globalThis.EdgeRuntime) || - (typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) { - return { - type: 'unsupported', - error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.', - workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.', - }; - } - if (typeof process !== 'undefined') { - // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings - const processVersions = process['versions']; - if (processVersions && processVersions['node']) { - // Remove 'v' prefix if present and parse the major version - const versionString = processVersions['node']; - const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]); - // Node.js 22+ should have native WebSocket - if (nodeVersion >= 22) { - // Check if native WebSocket is available (should be in Node.js 22+) - if (typeof globalThis.WebSocket !== 'undefined') { - return { type: 'native', constructor: globalThis.WebSocket }; - } - // If not available, user needs to provide it - return { - type: 'unsupported', - error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, - workaround: 'Provide a WebSocket implementation via the transport option.', - }; - } - // Node.js < 22 doesn't have native WebSocket - return { - type: 'unsupported', - error: `Node.js ${nodeVersion} detected without native WebSocket support.`, - workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' + - 'import ws from "ws"\n' + - 'new RealtimeClient(url, { transport: ws })', - }; - } - } - return { - type: 'unsupported', - error: 'Unknown JavaScript runtime without WebSocket support.', - workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.", - }; - } - static getWebSocketConstructor() { - const env = this.detectEnvironment(); - if (env.constructor) { - return env.constructor; - } - let errorMessage = env.error || 'WebSocket not supported in this environment.'; - if (env.workaround) { - errorMessage += `\n\nSuggested solution: ${env.workaround}`; - } - throw new Error(errorMessage); - } - static createWebSocket(url, protocols) { - const WS = this.getWebSocketConstructor(); - return new WS(url, protocols); - } - static isWebSocketSupported() { - try { - const env = this.detectEnvironment(); - return env.type === 'native' || env.type === 'ws'; - } - catch (_a) { - return false; - } - } -} -exports.WebSocketFactory = WebSocketFactory; -exports["default"] = WebSocketFactory; -//# sourceMappingURL=websocket-factory.js.map - -/***/ }), - -/***/ 44249: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -const StorageFileApi_1 = tslib_1.__importDefault(__nccwpck_require__(80710)); -const StorageBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(33528)); -const StorageAnalyticsApi_1 = tslib_1.__importDefault(__nccwpck_require__(27339)); -const vectors_1 = __nccwpck_require__(99380); -class StorageClient extends StorageBucketApi_1.default { - constructor(url, headers = {}, fetch, opts) { - super(url, headers, fetch, opts); - } - /** - * Perform file operation in a bucket. - * - * @param id The bucket id to operate on. - */ - from(id) { - return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch); - } - /** - * Access vector storage operations. - * - * @returns A StorageVectorsClient instance configured with the current storage settings. - */ - get vectors() { - return new vectors_1.StorageVectorsClient(this.url + '/vector', { - headers: this.headers, - fetch: this.fetch, - }); - } - /** - * Access analytics storage operations using Iceberg tables. - * - * @returns A StorageAnalyticsApi instance configured with the current storage settings. - * @example - * ```typescript - * const client = createClient(url, key) - * const analytics = client.storage.analytics - * - * // Create an analytics bucket - * await analytics.createBucket('my-analytics-bucket') - * - * // List all analytics buckets - * const { data: buckets } = await analytics.listBuckets() - * - * // Delete an analytics bucket - * await analytics.deleteBucket('old-analytics-bucket') - * ``` - */ - get analytics() { - return new StorageAnalyticsApi_1.default(this.url + '/iceberg', this.headers, this.fetch); - } -} -exports.StorageClient = StorageClient; -//# sourceMappingURL=StorageClient.js.map - -/***/ }), - -/***/ 45852: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageAnalyticsApi = exports.StorageClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -var StorageClient_1 = __nccwpck_require__(44249); -Object.defineProperty(exports, "StorageClient", ({ enumerable: true, get: function () { return StorageClient_1.StorageClient; } })); -var StorageAnalyticsApi_1 = __nccwpck_require__(27339); -Object.defineProperty(exports, "StorageAnalyticsApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(StorageAnalyticsApi_1).default; } })); -tslib_1.__exportStar(__nccwpck_require__(57222), exports); -tslib_1.__exportStar(__nccwpck_require__(42758), exports); -tslib_1.__exportStar(__nccwpck_require__(99380), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 79754: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_HEADERS = void 0; -const version_1 = __nccwpck_require__(54499); -exports.DEFAULT_HEADERS = { - 'X-Client-Info': `storage-js/${version_1.version}`, -}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 42758: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageUnknownError = exports.StorageApiError = exports.StorageError = void 0; -exports.isStorageError = isStorageError; -class StorageError extends Error { - constructor(message) { - super(message); - this.__isStorageError = true; - this.name = 'StorageError'; - } -} -exports.StorageError = StorageError; -function isStorageError(error) { - return typeof error === 'object' && error !== null && '__isStorageError' in error; -} -class StorageApiError extends StorageError { - constructor(message, status, statusCode) { - super(message); - this.name = 'StorageApiError'; - this.status = status; - this.statusCode = statusCode; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - statusCode: this.statusCode, - }; - } -} -exports.StorageApiError = StorageApiError; -class StorageUnknownError extends StorageError { - constructor(message, originalError) { - super(message); - this.name = 'StorageUnknownError'; - this.originalError = originalError; - } -} -exports.StorageUnknownError = StorageUnknownError; -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 73146: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.get = get; -exports.post = post; -exports.put = put; -exports.head = head; -exports.remove = remove; -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -const helpers_1 = __nccwpck_require__(5430); -const _getErrorMessage = (err) => { - var _a; - return err.msg || - err.message || - err.error_description || - (typeof err.error === 'string' ? err.error : (_a = err.error) === null || _a === void 0 ? void 0 : _a.message) || - JSON.stringify(err); -}; -const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - const Res = yield (0, helpers_1.resolveResponse)(); - if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { - error - .json() - .then((err) => { - const status = error.status || 500; - const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || status + ''; - reject(new errors_1.StorageApiError(_getErrorMessage(err), status, statusCode)); - }) - .catch((err) => { - reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err)); - }); - } - else { - reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error)); - } -}); -const _getRequestParams = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET' || !body) { - return params; - } - if ((0, helpers_1.isPlainObject)(body)) { - params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); - params.body = JSON.stringify(body); - } - else { - params.body = body; - } - if (options === null || options === void 0 ? void 0 : options.duplex) { - params.duplex = options.duplex; - } - return Object.assign(Object.assign({}, params), parameters); -}; -function _handleRequest(fetcher, method, url, options, parameters, body) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - fetcher(url, _getRequestParams(method, options, parameters, body)) - .then((result) => { - if (!result.ok) - throw result; - if (options === null || options === void 0 ? void 0 : options.noResolveJson) - return result; - return result.json(); - }) - .then((data) => resolve(data)) - .catch((error) => handleError(error, reject, options)); - }); - }); -} -function get(fetcher, url, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'GET', url, options, parameters); - }); -} -function post(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'POST', url, options, parameters, body); - }); -} -function put(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'PUT', url, options, parameters, body); - }); -} -function head(fetcher, url, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); - }); -} -function remove(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); - }); -} -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 5430: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isPlainObject = exports.recursiveToCamel = exports.resolveResponse = exports.resolveFetch = void 0; -const tslib_1 = __nccwpck_require__(4351); -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -const resolveResponse = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - if (typeof Response === 'undefined') { - // @ts-ignore - return (yield Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s)))).Response; - } - return Response; -}); -exports.resolveResponse = resolveResponse; -const recursiveToCamel = (item) => { - if (Array.isArray(item)) { - return item.map((el) => (0, exports.recursiveToCamel)(el)); - } - else if (typeof item === 'function' || item !== Object(item)) { - return item; - } - const result = {}; - Object.entries(item).forEach(([key, value]) => { - const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, '')); - result[newKey] = (0, exports.recursiveToCamel)(value); - }); - return result; -}; -exports.recursiveToCamel = recursiveToCamel; -/** - * Determine if input is a plain object - * An object is plain if it's created by either {}, new Object(), or Object.create(null) - * source: https://github.com/sindresorhus/is-plain-obj - */ -const isPlainObject = (value) => { - if (typeof value !== 'object' || value === null) { - return false; - } - const prototype = Object.getPrototypeOf(value); - return ((prototype === null || - prototype === Object.prototype || - Object.getPrototypeOf(prototype) === null) && - !(Symbol.toStringTag in value) && - !(Symbol.iterator in value)); -}; -exports.isPlainObject = isPlainObject; -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 57222: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -//# sourceMappingURL=types.js.map - -/***/ }), - -/***/ 59403: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -const VectorIndexApi_1 = tslib_1.__importDefault(__nccwpck_require__(79623)); -const VectorDataApi_1 = tslib_1.__importDefault(__nccwpck_require__(93073)); -const VectorBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(44268)); -/** - * Main client for interacting with S3 Vectors API - * Provides access to bucket, index, and vector data operations - * - * **Usage Patterns:** - * - * 1. **Via StorageClient (recommended for most use cases):** - * ```typescript - * import { StorageClient } from '@supabase/storage-js' - * - * const storageClient = new StorageClient(url, headers) - * const vectors = storageClient.vectors - * - * // Use vector operations - * await vectors.createBucket('embeddings-prod') - * const bucket = vectors.from('embeddings-prod') - * await bucket.createIndex({ ... }) - * ``` - * - * 2. **Standalone (for vector-only applications):** - * ```typescript - * import { StorageVectorsClient } from '@supabase/storage-js' - * - * const vectorsClient = new StorageVectorsClient('https://api.example.com', { - * headers: { 'Authorization': 'Bearer token' } - * }) - * - * // Access bucket operations - * await vectorsClient.createBucket('embeddings-prod') - * - * // Access index operations via buckets - * const bucket = vectorsClient.from('embeddings-prod') - * await bucket.createIndex({ - * indexName: 'documents', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine' - * }) - * - * // Access vector operations via index - * const index = bucket.index('documents') - * await index.putVectors({ - * vectors: [ - * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } - * ] - * }) - * - * // Query similar vectors - * const { data } = await index.queryVectors({ - * queryVector: { float32: [...] }, - * topK: 5, - * returnDistance: true - * }) - * ``` - */ -class StorageVectorsClient extends VectorBucketApi_1.default { - constructor(url, options = {}) { - super(url, options.headers || {}, options.fetch); - } - /** - * Access operations for a specific vector bucket - * Returns a scoped client for index and vector operations within the bucket - * - * @param vectorBucketName - Name of the vector bucket - * @returns Bucket-scoped client with index and vector operations - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * - * // Create an index in this bucket - * await bucket.createIndex({ - * indexName: 'documents-openai', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine' - * }) - * - * // List indexes in this bucket - * const { data } = await bucket.listIndexes() - * ``` - */ - from(vectorBucketName) { - return new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch); - } -} -exports.StorageVectorsClient = StorageVectorsClient; -/** - * Scoped client for operations within a specific vector bucket - * Provides index management and access to vector operations - */ -class VectorBucketScope extends VectorIndexApi_1.default { - constructor(url, headers, vectorBucketName, fetch) { - super(url, headers, fetch); - this.vectorBucketName = vectorBucketName; - } - /** - * Creates a new vector index in this bucket - * Convenience method that automatically includes the bucket name - * - * @param options - Index configuration (vectorBucketName is automatically set) - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * await bucket.createIndex({ - * indexName: 'documents-openai', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine', - * metadataConfiguration: { - * nonFilterableMetadataKeys: ['raw_text'] - * } - * }) - * ``` - */ - createIndex(options) { - const _super = Object.create(null, { - createIndex: { get: () => super.createIndex } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.createIndex.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); - }); - } - /** - * Lists indexes in this bucket - * Convenience method that automatically includes the bucket name - * - * @param options - Listing options (vectorBucketName is automatically set) - * @returns Promise with list of indexes or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * const { data } = await bucket.listIndexes({ prefix: 'documents-' }) - * ``` - */ - listIndexes() { - const _super = Object.create(null, { - listIndexes: { get: () => super.listIndexes } - }); - return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { - return _super.listIndexes.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); - }); - } - /** - * Retrieves metadata for a specific index in this bucket - * Convenience method that automatically includes the bucket name - * - * @param indexName - Name of the index to retrieve - * @returns Promise with index metadata or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * const { data } = await bucket.getIndex('documents-openai') - * console.log('Dimension:', data?.index.dimension) - * ``` - */ - getIndex(indexName) { - const _super = Object.create(null, { - getIndex: { get: () => super.getIndex } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.getIndex.call(this, this.vectorBucketName, indexName); - }); - } - /** - * Deletes an index from this bucket - * Convenience method that automatically includes the bucket name - * - * @param indexName - Name of the index to delete - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const bucket = client.bucket('embeddings-prod') - * await bucket.deleteIndex('old-index') - * ``` - */ - deleteIndex(indexName) { - const _super = Object.create(null, { - deleteIndex: { get: () => super.deleteIndex } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.deleteIndex.call(this, this.vectorBucketName, indexName); - }); - } - /** - * Access operations for a specific index within this bucket - * Returns a scoped client for vector data operations - * - * @param indexName - Name of the index - * @returns Index-scoped client with vector data operations - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * - * // Insert vectors - * await index.putVectors({ - * vectors: [ - * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } - * ] - * }) - * - * // Query similar vectors - * const { data } = await index.queryVectors({ - * queryVector: { float32: [...] }, - * topK: 5 - * }) - * ``` - */ - index(indexName) { - return new VectorIndexScope(this.url, this.headers, this.vectorBucketName, indexName, this.fetch); - } -} -exports.VectorBucketScope = VectorBucketScope; -/** - * Scoped client for operations within a specific vector index - * Provides vector data operations (put, get, list, query, delete) - */ -class VectorIndexScope extends VectorDataApi_1.default { - constructor(url, headers, vectorBucketName, indexName, fetch) { - super(url, headers, fetch); - this.vectorBucketName = vectorBucketName; - this.indexName = indexName; - } - /** - * Inserts or updates vectors in this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Vector insertion options (bucket and index names automatically set) - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * await index.putVectors({ - * vectors: [ - * { - * key: 'doc-1', - * data: { float32: [0.1, 0.2, ...] }, - * metadata: { title: 'Introduction', page: 1 } - * } - * ] - * }) - * ``` - */ - putVectors(options) { - const _super = Object.create(null, { - putVectors: { get: () => super.putVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.putVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Retrieves vectors by keys from this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Vector retrieval options (bucket and index names automatically set) - * @returns Promise with array of vectors or error - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * const { data } = await index.getVectors({ - * keys: ['doc-1', 'doc-2'], - * returnMetadata: true - * }) - * ``` - */ - getVectors(options) { - const _super = Object.create(null, { - getVectors: { get: () => super.getVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.getVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Lists vectors in this index with pagination - * Convenience method that automatically includes bucket and index names - * - * @param options - Listing options (bucket and index names automatically set) - * @returns Promise with array of vectors and pagination token - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * const { data } = await index.listVectors({ - * maxResults: 500, - * returnMetadata: true - * }) - * ``` - */ - listVectors() { - const _super = Object.create(null, { - listVectors: { get: () => super.listVectors } - }); - return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { - return _super.listVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Queries for similar vectors in this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Query options (bucket and index names automatically set) - * @returns Promise with array of similar vectors ordered by distance - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * const { data } = await index.queryVectors({ - * queryVector: { float32: [0.1, 0.2, ...] }, - * topK: 5, - * filter: { category: 'technical' }, - * returnDistance: true, - * returnMetadata: true - * }) - * ``` - */ - queryVectors(options) { - const _super = Object.create(null, { - queryVectors: { get: () => super.queryVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.queryVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } - /** - * Deletes vectors by keys from this index - * Convenience method that automatically includes bucket and index names - * - * @param options - Deletion options (bucket and index names automatically set) - * @returns Promise with empty response on success or error - * - * @example - * ```typescript - * const index = client.bucket('embeddings-prod').index('documents-openai') - * await index.deleteVectors({ - * keys: ['doc-1', 'doc-2', 'doc-3'] - * }) - * ``` - */ - deleteVectors(options) { - const _super = Object.create(null, { - deleteVectors: { get: () => super.deleteVectors } - }); - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _super.deleteVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); - }); - } -} -exports.VectorIndexScope = VectorIndexScope; -//# sourceMappingURL=StorageVectorsClient.js.map - -/***/ }), - -/***/ 44268: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(36876); -const errors_1 = __nccwpck_require__(93071); -const fetch_1 = __nccwpck_require__(2593); -const helpers_1 = __nccwpck_require__(21176); -/** - * API class for managing Vector Buckets - * Provides methods for creating, reading, listing, and deleting vector buckets - */ -class VectorBucketApi { - /** - * Creates a new VectorBucketApi instance - * @param url - The base URL for the storage vectors API - * @param headers - HTTP headers to include in requests - * @param fetch - Optional custom fetch implementation - */ - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - * @example - * ```typescript - * const client = new VectorBucketApi(url, headers) - * client.throwOnError() - * const { data } = await client.createBucket('my-bucket') // throws on error - * ``` - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Creates a new vector bucket - * Vector buckets are containers for vector indexes and their data - * - * @param vectorBucketName - Unique name for the vector bucket - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorConflictException` if bucket already exists (HTTP 409) - * - `S3VectorMaxBucketsExceeded` if quota exceeded (HTTP 400) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.createBucket('embeddings-prod') - * if (error) { - * console.error('Failed to create bucket:', error.message) - * } - * ``` - */ - createBucket(vectorBucketName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateVectorBucket`, { vectorBucketName }, { headers: this.headers }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves metadata for a specific vector bucket - * Returns bucket configuration including encryption settings and creation time - * - * @param vectorBucketName - Name of the vector bucket to retrieve - * @returns Promise with bucket metadata or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.getBucket('embeddings-prod') - * if (data) { - * console.log('Bucket created at:', new Date(data.vectorBucket.creationTime! * 1000)) - * } - * ``` - */ - getBucket(vectorBucketName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectorBucket`, { vectorBucketName }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Lists vector buckets with optional filtering and pagination - * Supports prefix-based filtering and paginated results - * - * @param options - Listing options - * @param options.prefix - Filter buckets by name prefix - * @param options.maxResults - Maximum results per page (default: 100) - * @param options.nextToken - Pagination token from previous response - * @returns Promise with list of buckets and pagination token - * - * @throws {StorageVectorsApiError} With code: - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // List all buckets with prefix 'prod-' - * const { data, error } = await client.listBuckets({ prefix: 'prod-' }) - * if (data) { - * console.log('Found buckets:', data.buckets.length) - * // Fetch next page if available - * if (data.nextToken) { - * const next = await client.listBuckets({ nextToken: data.nextToken }) - * } - * } - * ``` - */ - listBuckets() { - return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectorBuckets`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes a vector bucket - * Bucket must be empty before deletion (all indexes must be removed first) - * - * @param vectorBucketName - Name of the vector bucket to delete - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorBucketNotEmpty` if bucket contains indexes (HTTP 400) - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Delete all indexes first, then delete bucket - * const { error } = await client.deleteBucket('old-bucket') - * if (error?.statusCode === 'S3VectorBucketNotEmpty') { - * console.error('Must delete all indexes first') - * } - * ``` - */ - deleteBucket(vectorBucketName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectorBucket`, { vectorBucketName }, { headers: this.headers }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = VectorBucketApi; -//# sourceMappingURL=VectorBucketApi.js.map - -/***/ }), - -/***/ 93073: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(36876); -const errors_1 = __nccwpck_require__(93071); -const fetch_1 = __nccwpck_require__(2593); -const helpers_1 = __nccwpck_require__(21176); -/** - * API class for managing Vector Data within Vector Indexes - * Provides methods for inserting, querying, listing, and deleting vector embeddings - */ -class VectorDataApi { - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - * @example - * ```typescript - * const client = new VectorDataApi(url, headers) - * client.throwOnError() - * const { data } = await client.putVectors(options) // throws on error - * ``` - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Inserts or updates vectors in batch (upsert operation) - * Accepts 1-500 vectors per request. Larger batches should be split - * - * @param options - Vector insertion options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the target index - * @param options.vectors - Array of vectors to insert/update (1-500 items) - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorConflictException` if duplicate key conflict occurs (HTTP 409) - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.putVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * vectors: [ - * { - * key: 'doc-1', - * data: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions - * metadata: { title: 'Introduction', page: 1 } - * }, - * { - * key: 'doc-2', - * data: { float32: [0.4, 0.5, 0.6, ...] }, - * metadata: { title: 'Conclusion', page: 42 } - * } - * ] - * }) - * ``` - */ - putVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Validate batch size - if (options.vectors.length < 1 || options.vectors.length > 500) { - throw new Error('Vector batch size must be between 1 and 500 items'); - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/PutVectors`, options, { - headers: this.headers, - }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves vectors by their keys in batch - * Optionally includes vector data and/or metadata in response - * Additional permissions required when returning data or metadata - * - * @param options - Vector retrieval options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.keys - Array of vector keys to retrieve - * @param options.returnData - Whether to include vector embeddings (requires permission) - * @param options.returnMetadata - Whether to include metadata (requires permission) - * @returns Promise with array of vectors or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.getVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * keys: ['doc-1', 'doc-2', 'doc-3'], - * returnData: false, // Don't return embeddings - * returnMetadata: true // Return metadata only - * }) - * if (data) { - * data.vectors.forEach(v => console.log(v.key, v.metadata)) - * } - * ``` - */ - getVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectors`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Lists/scans vectors in an index with pagination - * Supports parallel scanning via segment configuration for high-throughput scenarios - * Additional permissions required when returning data or metadata - * - * @param options - Vector listing options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.maxResults - Maximum results per page (default: 500, max: 1000) - * @param options.nextToken - Pagination token from previous response - * @param options.returnData - Whether to include vector embeddings (requires permission) - * @param options.returnMetadata - Whether to include metadata (requires permission) - * @param options.segmentCount - Total parallel segments (1-16) for distributed scanning - * @param options.segmentIndex - Zero-based segment index (0 to segmentCount-1) - * @returns Promise with array of vectors, pagination token, or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Simple pagination - * let nextToken: string | undefined - * do { - * const { data, error } = await client.listVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * maxResults: 500, - * nextToken, - * returnMetadata: true - * }) - * if (error) break - * console.log('Batch:', data.vectors.length) - * nextToken = data.nextToken - * } while (nextToken) - * - * // Parallel scanning (4 concurrent workers) - * const workers = [0, 1, 2, 3].map(async (segmentIndex) => { - * const { data } = await client.listVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * segmentCount: 4, - * segmentIndex, - * returnMetadata: true - * }) - * return data?.vectors || [] - * }) - * const results = await Promise.all(workers) - * ``` - */ - listVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Validate segment configuration - if (options.segmentCount !== undefined) { - if (options.segmentCount < 1 || options.segmentCount > 16) { - throw new Error('segmentCount must be between 1 and 16'); - } - if (options.segmentIndex !== undefined) { - if (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) { - throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`); - } - } - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectors`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Queries for similar vectors using approximate nearest neighbor (ANN) search - * Returns top-K most similar vectors based on the configured distance metric - * Supports optional metadata filtering (requires GetVectors permission) - * - * @param options - Query options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.queryVector - Query embedding to find similar vectors - * @param options.topK - Number of nearest neighbors to return (default: 10) - * @param options.filter - Optional JSON filter for metadata (requires GetVectors permission) - * @param options.returnDistance - Whether to include similarity distances - * @param options.returnMetadata - Whether to include metadata (requires GetVectors permission) - * @returns Promise with array of similar vectors ordered by distance - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Semantic search with filtering - * const { data, error } = await client.queryVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * queryVector: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions - * topK: 5, - * filter: { - * category: 'technical', - * published: true - * }, - * returnDistance: true, - * returnMetadata: true - * }) - * if (data) { - * data.matches.forEach(match => { - * console.log(`${match.key}: distance=${match.distance}`) - * console.log('Metadata:', match.metadata) - * }) - * } - * ``` - */ - queryVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/QueryVectors`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes vectors by their keys in batch - * Accepts 1-500 keys per request - * - * @param options - Vector deletion options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Name of the index - * @param options.keys - Array of vector keys to delete (1-500 items) - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { error } = await client.deleteVectors({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * keys: ['doc-1', 'doc-2', 'doc-3'] - * }) - * if (!error) { - * console.log('Vectors deleted successfully') - * } - * ``` - */ - deleteVectors(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Validate batch size - if (options.keys.length < 1 || options.keys.length > 500) { - throw new Error('Keys batch size must be between 1 and 500 items'); - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectors`, options, { - headers: this.headers, - }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = VectorDataApi; -//# sourceMappingURL=VectorDataApi.js.map - -/***/ }), - -/***/ 79623: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(36876); -const errors_1 = __nccwpck_require__(93071); -const fetch_1 = __nccwpck_require__(2593); -const helpers_1 = __nccwpck_require__(21176); -/** - * API class for managing Vector Indexes within Vector Buckets - * Provides methods for creating, reading, listing, and deleting vector indexes - */ -class VectorIndexApi { - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - * @example - * ```typescript - * const client = new VectorIndexApi(url, headers) - * client.throwOnError() - * const { data } = await client.createIndex(options) // throws on error - * ``` - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Creates a new vector index within a bucket - * Defines the schema for vectors including dimensionality, distance metric, and metadata config - * - * @param options - Index configuration - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.indexName - Unique name for the index within the bucket - * @param options.dataType - Data type for vector components (currently only 'float32') - * @param options.dimension - Dimensionality of vectors (e.g., 384, 768, 1536) - * @param options.distanceMetric - Similarity metric ('cosine', 'euclidean', 'dotproduct') - * @param options.metadataConfiguration - Optional config for non-filterable metadata keys - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorConflictException` if index already exists (HTTP 409) - * - `S3VectorMaxIndexesExceeded` if quota exceeded (HTTP 400) - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.createIndex({ - * vectorBucketName: 'embeddings-prod', - * indexName: 'documents-openai-small', - * dataType: 'float32', - * dimension: 1536, - * distanceMetric: 'cosine', - * metadataConfiguration: { - * nonFilterableMetadataKeys: ['raw_text', 'internal_id'] - * } - * }) - * ``` - */ - createIndex(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateIndex`, options, { - headers: this.headers, - }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves metadata for a specific vector index - * Returns index configuration including dimension, distance metric, and metadata settings - * - * @param vectorBucketName - Name of the parent vector bucket - * @param indexName - Name of the index to retrieve - * @returns Promise with index metadata or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * const { data, error } = await client.getIndex('embeddings-prod', 'documents-openai-small') - * if (data) { - * console.log('Index dimension:', data.index.dimension) - * console.log('Distance metric:', data.index.distanceMetric) - * } - * ``` - */ - getIndex(vectorBucketName, indexName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetIndex`, { vectorBucketName, indexName }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Lists vector indexes within a bucket with optional filtering and pagination - * Supports prefix-based filtering and paginated results - * - * @param options - Listing options - * @param options.vectorBucketName - Name of the parent vector bucket - * @param options.prefix - Filter indexes by name prefix - * @param options.maxResults - Maximum results per page (default: 100) - * @param options.nextToken - Pagination token from previous response - * @returns Promise with list of indexes and pagination token - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // List all indexes in a bucket - * const { data, error } = await client.listIndexes({ - * vectorBucketName: 'embeddings-prod', - * prefix: 'documents-' - * }) - * if (data) { - * console.log('Found indexes:', data.indexes.map(i => i.indexName)) - * // Fetch next page if available - * if (data.nextToken) { - * const next = await client.listIndexes({ - * vectorBucketName: 'embeddings-prod', - * nextToken: data.nextToken - * }) - * } - * } - * ``` - */ - listIndexes(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListIndexes`, options, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes a vector index and all its data - * This operation removes the index schema and all vectors stored in the index - * - * @param vectorBucketName - Name of the parent vector bucket - * @param indexName - Name of the index to delete - * @returns Promise with empty response on success or error - * - * @throws {StorageVectorsApiError} With code: - * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) - * - `InternalError` for server errors (HTTP 500) - * - * @example - * ```typescript - * // Delete an index and all its vectors - * const { error } = await client.deleteIndex('embeddings-prod', 'old-index') - * if (!error) { - * console.log('Index deleted successfully') - * } - * ``` - */ - deleteIndex(vectorBucketName, indexName) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteIndex`, { vectorBucketName, indexName }, { headers: this.headers }); - return { data: data || {}, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageVectorsError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = VectorIndexApi; -//# sourceMappingURL=VectorIndexApi.js.map - -/***/ }), - -/***/ 36876: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_HEADERS = void 0; -const version_1 = __nccwpck_require__(54499); -exports.DEFAULT_HEADERS = { - 'X-Client-Info': `storage-js/${version_1.version}`, - 'Content-Type': 'application/json', -}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 93071: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = void 0; -exports.isStorageVectorsError = isStorageVectorsError; -/** - * Base error class for all Storage Vectors errors - */ -class StorageVectorsError extends Error { - constructor(message) { - super(message); - this.__isStorageVectorsError = true; - this.name = 'StorageVectorsError'; - } -} -exports.StorageVectorsError = StorageVectorsError; -/** - * Type guard to check if an error is a StorageVectorsError - * @param error - The error to check - * @returns True if the error is a StorageVectorsError - */ -function isStorageVectorsError(error) { - return typeof error === 'object' && error !== null && '__isStorageVectorsError' in error; -} -/** - * API error returned from S3 Vectors service - * Includes HTTP status code and service-specific error code - */ -class StorageVectorsApiError extends StorageVectorsError { - constructor(message, status, statusCode) { - super(message); - this.name = 'StorageVectorsApiError'; - this.status = status; - this.statusCode = statusCode; - } - toJSON() { - return { - name: this.name, - message: this.message, - status: this.status, - statusCode: this.statusCode, - }; - } -} -exports.StorageVectorsApiError = StorageVectorsApiError; -/** - * Unknown error that doesn't match expected error patterns - * Wraps the original error for debugging - */ -class StorageVectorsUnknownError extends StorageVectorsError { - constructor(message, originalError) { - super(message); - this.name = 'StorageVectorsUnknownError'; - this.originalError = originalError; - } -} -exports.StorageVectorsUnknownError = StorageVectorsUnknownError; -/** - * Error codes specific to S3 Vectors API - * Maps AWS service errors to application-friendly error codes - */ -var StorageVectorsErrorCode; -(function (StorageVectorsErrorCode) { - /** Internal server fault (HTTP 500) */ - StorageVectorsErrorCode["InternalError"] = "InternalError"; - /** Resource already exists / conflict (HTTP 409) */ - StorageVectorsErrorCode["S3VectorConflictException"] = "S3VectorConflictException"; - /** Resource not found (HTTP 404) */ - StorageVectorsErrorCode["S3VectorNotFoundException"] = "S3VectorNotFoundException"; - /** Delete bucket while not empty (HTTP 400) */ - StorageVectorsErrorCode["S3VectorBucketNotEmpty"] = "S3VectorBucketNotEmpty"; - /** Exceeds bucket quota/limit (HTTP 400) */ - StorageVectorsErrorCode["S3VectorMaxBucketsExceeded"] = "S3VectorMaxBucketsExceeded"; - /** Exceeds index quota/limit (HTTP 400) */ - StorageVectorsErrorCode["S3VectorMaxIndexesExceeded"] = "S3VectorMaxIndexesExceeded"; -})(StorageVectorsErrorCode || (exports.StorageVectorsErrorCode = StorageVectorsErrorCode = {})); -//# sourceMappingURL=errors.js.map - -/***/ }), - -/***/ 2593: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.get = get; -exports.post = post; -exports.put = put; -exports.remove = remove; -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(93071); -const helpers_1 = __nccwpck_require__(21176); -/** - * Extracts error message from various error response formats - * @param err - Error object from API - * @returns Human-readable error message - */ -const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); -/** - * Handles fetch errors and converts them to StorageVectors error types - * @param error - The error caught from fetch - * @param reject - Promise rejection function - * @param options - Fetch options that may affect error handling - */ -const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - // Check if error is a Response-like object (has status and ok properties) - // This is more reliable than instanceof which can fail across realms - const isResponseLike = error && - typeof error === 'object' && - 'status' in error && - 'ok' in error && - typeof error.status === 'number'; - if (isResponseLike && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { - const status = error.status || 500; - const responseError = error; - // Try to parse JSON body if available - if (typeof responseError.json === 'function') { - responseError - .json() - .then((err) => { - const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || (err === null || err === void 0 ? void 0 : err.code) || status + ''; - reject(new errors_1.StorageVectorsApiError(_getErrorMessage(err), status, statusCode)); - }) - .catch(() => { - // If JSON parsing fails, create an ApiError with the HTTP status code - const statusCode = status + ''; - const message = responseError.statusText || `HTTP ${status} error`; - reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); - }); - } - else { - // No json() method available, create error from status - const statusCode = status + ''; - const message = responseError.statusText || `HTTP ${status} error`; - reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); - } - } - else { - reject(new errors_1.StorageVectorsUnknownError(_getErrorMessage(error), error)); - } -}); -/** - * Builds request parameters for fetch calls - * @param method - HTTP method - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters like AbortSignal - * @param body - Request body (will be JSON stringified if plain object) - * @returns Complete fetch request parameters - */ -const _getRequestParams = (method, options, parameters, body) => { - const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; - if (method === 'GET' || !body) { - return params; - } - if ((0, helpers_1.isPlainObject)(body)) { - params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); - params.body = JSON.stringify(body); - } - else { - params.body = body; - } - return Object.assign(Object.assign({}, params), parameters); -}; -/** - * Internal request handler that wraps fetch with error handling - * @param fetcher - Fetch function to use - * @param method - HTTP method - * @param url - Request URL - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @param body - Request body - * @returns Promise with parsed response or error - */ -function _handleRequest(fetcher, method, url, options, parameters, body) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - fetcher(url, _getRequestParams(method, options, parameters, body)) - .then((result) => { - if (!result.ok) - throw result; - if (options === null || options === void 0 ? void 0 : options.noResolveJson) - return result; - // Handle empty responses (204, empty body) - const contentType = result.headers.get('content-type'); - if (!contentType || !contentType.includes('application/json')) { - return {}; - } - return result.json(); - }) - .then((data) => resolve(data)) - .catch((error) => handleError(error, reject, options)); - }); - }); -} -/** - * Performs a GET request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function get(fetcher, url, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'GET', url, options, parameters); - }); -} -/** - * Performs a POST request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param body - Request body to be JSON stringified - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function post(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'POST', url, options, parameters, body); - }); -} -/** - * Performs a PUT request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param body - Request body to be JSON stringified - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function put(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'PUT', url, options, parameters, body); - }); -} -/** - * Performs a DELETE request - * @param fetcher - Fetch function to use - * @param url - Request URL - * @param body - Request body to be JSON stringified - * @param options - Custom fetch options - * @param parameters - Additional fetch parameters - * @returns Promise with parsed response - */ -function remove(fetcher, url, body, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); - }); -} -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 21176: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = void 0; -const tslib_1 = __nccwpck_require__(4351); -/** - * Resolves the fetch implementation to use - * Uses custom fetch if provided, otherwise falls back to: - * - Native fetch in browser/modern environments - * - @supabase/node-fetch polyfill in Node.js environments without fetch - * - * @param customFetch - Optional custom fetch implementation - * @returns Resolved fetch function - */ -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = (...args) => Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s))).then(({ default: fetch }) => fetch(...args)); - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -/** - * Resolves the Response constructor to use - * Uses native Response in browser/modern environments - * Falls back to @supabase/node-fetch polyfill in Node.js environments - * - * @returns Response constructor - */ -const resolveResponse = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () { - if (typeof Response === 'undefined') { - // @ts-ignore - return (yield Promise.resolve(`${'@supabase/node-fetch'}`).then(s => tslib_1.__importStar(require(s)))).Response; - } - return Response; -}); -exports.resolveResponse = resolveResponse; -/** - * Determine if input is a plain object - * An object is plain if it's created by either {}, new Object(), or Object.create(null) - * - * @param value - Value to check - * @returns True if value is a plain object - * @source https://github.com/sindresorhus/is-plain-obj - */ -const isPlainObject = (value) => { - if (typeof value !== 'object' || value === null) { - return false; - } - const prototype = Object.getPrototypeOf(value); - return ((prototype === null || - prototype === Object.prototype || - Object.getPrototypeOf(prototype) === null) && - !(Symbol.toStringTag in value) && - !(Symbol.iterator in value)); -}; -exports.isPlainObject = isPlainObject; -/** - * Normalizes a number array to float32 format - * Ensures all vector values are valid 32-bit floats - * - * @param values - Array of numbers to normalize - * @returns Normalized float32 array - */ -const normalizeToFloat32 = (values) => { - // Use Float32Array to ensure proper precision - return Array.from(new Float32Array(values)); -}; -exports.normalizeToFloat32 = normalizeToFloat32; -/** - * Validates vector dimensions match expected dimension - * Throws error if dimensions don't match - * - * @param vector - Vector data to validate - * @param expectedDimension - Expected vector dimension - * @throws Error if dimensions don't match - */ -const validateVectorDimension = (vector, expectedDimension) => { - if (expectedDimension !== undefined && vector.float32.length !== expectedDimension) { - throw new Error(`Vector dimension mismatch: expected ${expectedDimension}, got ${vector.float32.length}`); - } -}; -exports.validateVectorDimension = validateVectorDimension; -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 99380: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = exports.isStorageVectorsError = exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = exports.VectorDataApi = exports.VectorIndexApi = exports.VectorBucketApi = exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; -const tslib_1 = __nccwpck_require__(4351); -// Main client -var StorageVectorsClient_1 = __nccwpck_require__(59403); -Object.defineProperty(exports, "StorageVectorsClient", ({ enumerable: true, get: function () { return StorageVectorsClient_1.StorageVectorsClient; } })); -Object.defineProperty(exports, "VectorBucketScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorBucketScope; } })); -Object.defineProperty(exports, "VectorIndexScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorIndexScope; } })); -// API classes (for advanced usage) -var VectorBucketApi_1 = __nccwpck_require__(44268); -Object.defineProperty(exports, "VectorBucketApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorBucketApi_1).default; } })); -var VectorIndexApi_1 = __nccwpck_require__(79623); -Object.defineProperty(exports, "VectorIndexApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorIndexApi_1).default; } })); -var VectorDataApi_1 = __nccwpck_require__(93073); -Object.defineProperty(exports, "VectorDataApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorDataApi_1).default; } })); -// Errors -var errors_1 = __nccwpck_require__(93071); -Object.defineProperty(exports, "StorageVectorsError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsError; } })); -Object.defineProperty(exports, "StorageVectorsApiError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsApiError; } })); -Object.defineProperty(exports, "StorageVectorsUnknownError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsUnknownError; } })); -Object.defineProperty(exports, "StorageVectorsErrorCode", ({ enumerable: true, get: function () { return errors_1.StorageVectorsErrorCode; } })); -Object.defineProperty(exports, "isStorageVectorsError", ({ enumerable: true, get: function () { return errors_1.isStorageVectorsError; } })); -// Helper utilities -var helpers_1 = __nccwpck_require__(21176); -Object.defineProperty(exports, "resolveFetch", ({ enumerable: true, get: function () { return helpers_1.resolveFetch; } })); -Object.defineProperty(exports, "resolveResponse", ({ enumerable: true, get: function () { return helpers_1.resolveResponse; } })); -Object.defineProperty(exports, "isPlainObject", ({ enumerable: true, get: function () { return helpers_1.isPlainObject; } })); -Object.defineProperty(exports, "normalizeToFloat32", ({ enumerable: true, get: function () { return helpers_1.normalizeToFloat32; } })); -Object.defineProperty(exports, "validateVectorDimension", ({ enumerable: true, get: function () { return helpers_1.validateVectorDimension; } })); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 54499: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 98475: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -const StreamDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(7023)); -class BlobDownloadBuilder { - constructor(downloadFn, shouldThrowOnError) { - this.downloadFn = downloadFn; - this.shouldThrowOnError = shouldThrowOnError; - this[_a] = 'BlobDownloadBuilder'; - this.promise = null; - } - asStream() { - return new StreamDownloadBuilder_1.default(this.downloadFn, this.shouldThrowOnError); - } - then(onfulfilled, onrejected) { - return this.getPromise().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.getPromise().catch(onrejected); - } - finally(onfinally) { - return this.getPromise().finally(onfinally); - } - getPromise() { - if (!this.promise) { - this.promise = this.execute(); - } - return this.promise; - } - execute() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const result = yield this.downloadFn(); - return { - data: yield result.blob(), - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -_a = Symbol.toStringTag; -exports["default"] = BlobDownloadBuilder; -//# sourceMappingURL=BlobDownloadBuilder.js.map - -/***/ }), - -/***/ 27339: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(79754); -const errors_1 = __nccwpck_require__(42758); -const fetch_1 = __nccwpck_require__(73146); -const helpers_1 = __nccwpck_require__(5430); -/** - * API class for managing Analytics Buckets using Iceberg tables - * Provides methods for creating, listing, and deleting analytics buckets - */ -class StorageAnalyticsApi { - /** - * Creates a new StorageAnalyticsApi instance - * @param url - The base URL for the storage API - * @param headers - HTTP headers to include in requests - * @param fetch - Optional custom fetch implementation - */ - constructor(url, headers = {}, fetch) { - this.shouldThrowOnError = false; - this.url = url.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them in the response - * When enabled, failed operations will throw instead of returning { data: null, error } - * - * @returns This instance for method chaining - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Creates a new analytics bucket using Iceberg tables - * Analytics buckets are optimized for analytical queries and data processing - * - * @param name A unique name for the bucket you are creating - * @returns Promise with newly created bucket name or error - * - * @example - * ```typescript - * const { data, error } = await storage.analytics.createBucket('analytics-data') - * if (error) { - * console.error('Failed to create analytics bucket:', error.message) - * } else { - * console.log('Created bucket:', data.name) - * } - * ``` - */ - createBucket(name) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { name }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves the details of all Analytics Storage buckets within an existing project - * Only returns buckets of type 'ANALYTICS' - * - * @param options Query parameters for listing buckets - * @param options.limit Maximum number of buckets to return - * @param options.offset Number of buckets to skip - * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at') - * @param options.sortOrder Sort order ('asc' or 'desc') - * @param options.search Search term to filter bucket names - * @returns Promise with list of analytics buckets or error - * - * @example - * ```typescript - * const { data, error } = await storage.analytics.listBuckets({ - * limit: 10, - * offset: 0, - * sortColumn: 'created_at', - * sortOrder: 'desc', - * search: 'analytics' - * }) - * if (data) { - * console.log('Found analytics buckets:', data.length) - * data.forEach(bucket => console.log(`- ${bucket.name}`)) - * } - * ``` - */ - listBuckets(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - // Build query string from options - const queryParams = new URLSearchParams(); - if ((options === null || options === void 0 ? void 0 : options.limit) !== undefined) - queryParams.set('limit', options.limit.toString()); - if ((options === null || options === void 0 ? void 0 : options.offset) !== undefined) - queryParams.set('offset', options.offset.toString()); - if (options === null || options === void 0 ? void 0 : options.sortColumn) - queryParams.set('sortColumn', options.sortColumn); - if (options === null || options === void 0 ? void 0 : options.sortOrder) - queryParams.set('sortOrder', options.sortOrder); - if (options === null || options === void 0 ? void 0 : options.search) - queryParams.set('search', options.search); - const queryString = queryParams.toString(); - const url = queryString ? `${this.url}/bucket?${queryString}` : `${this.url}/bucket`; - const data = yield (0, fetch_1.get)(this.fetch, url, { headers: this.headers }); - return { data: data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes an existing analytics bucket - * A bucket can't be deleted with existing objects inside it - * You must first empty the bucket before deletion - * - * @param bucketId The unique identifier of the bucket you would like to delete - * @returns Promise with success message or error - * - * @example - * ```typescript - * const { data, error } = await analyticsApi.deleteBucket('old-analytics-bucket') - * if (error) { - * console.error('Failed to delete bucket:', error.message) - * } else { - * console.log('Bucket deleted successfully:', data.message) - * } - * ``` - */ - deleteBucket(bucketId) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${bucketId}`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = StorageAnalyticsApi; -//# sourceMappingURL=StorageAnalyticsApi.js.map - -/***/ }), - -/***/ 33528: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const constants_1 = __nccwpck_require__(79754); -const errors_1 = __nccwpck_require__(42758); -const fetch_1 = __nccwpck_require__(73146); -const helpers_1 = __nccwpck_require__(5430); -class StorageBucketApi { - constructor(url, headers = {}, fetch, opts) { - this.shouldThrowOnError = false; - const baseUrl = new URL(url); - // if legacy uri is used, replace with new storage host (disables request buffering to allow > 50GB uploads) - // "project-ref.supabase.co" becomes "project-ref.storage.supabase.co" - if (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) { - const isSupabaseHost = /supabase\.(co|in|red)$/.test(baseUrl.hostname); - if (isSupabaseHost && !baseUrl.hostname.includes('storage.supabase.')) { - baseUrl.hostname = baseUrl.hostname.replace('supabase.', 'storage.supabase.'); - } - } - this.url = baseUrl.href.replace(/\/$/, ''); - this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them. - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Retrieves the details of all Storage buckets within an existing project. - */ - listBuckets(options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const queryString = this.listBucketOptionsToQueryString(options); - const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket${queryString}`, { - headers: this.headers, - }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Retrieves the details of an existing Storage bucket. - * - * @param id The unique identifier of the bucket you would like to retrieve. - */ - getBucket(id) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a new Storage bucket - * - * @param id A unique identifier for the bucket you are creating. - * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. - * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. - * The global file size limit takes precedence over this value. - * The default value is null, which doesn't set a per bucket file size limit. - * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. - * The default value is null, which allows files with all mime types to be uploaded. - * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. - * @returns newly created bucket id - * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details. - * - default bucket type is `STANDARD` - */ - createBucket(id_1) { - return tslib_1.__awaiter(this, arguments, void 0, function* (id, options = { - public: false, - }) { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { - id, - name: id, - type: options.type, - public: options.public, - file_size_limit: options.fileSizeLimit, - allowed_mime_types: options.allowedMimeTypes, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Updates a Storage bucket - * - * @param id A unique identifier for the bucket you are updating. - * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. - * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. - * The global file size limit takes precedence over this value. - * The default value is null, which doesn't set a per bucket file size limit. - * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. - * The default value is null, which allows files with all mime types to be uploaded. - * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. - */ - updateBucket(id, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, { - id, - name: id, - public: options.public, - file_size_limit: options.fileSizeLimit, - allowed_mime_types: options.allowedMimeTypes, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Removes all objects inside a single bucket. - * - * @param id The unique identifier of the bucket you would like to empty. - */ - emptyBucket(id) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. - * You must first `empty()` the bucket. - * - * @param id The unique identifier of the bucket you would like to delete. - */ - deleteBucket(id) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - listBucketOptionsToQueryString(options) { - const params = {}; - if (options) { - if ('limit' in options) { - params.limit = String(options.limit); - } - if ('offset' in options) { - params.offset = String(options.offset); - } - if (options.search) { - params.search = options.search; - } - if (options.sortColumn) { - params.sortColumn = options.sortColumn; - } - if (options.sortOrder) { - params.sortOrder = options.sortOrder; - } - } - return Object.keys(params).length > 0 ? '?' + new URLSearchParams(params).toString() : ''; - } -} -exports["default"] = StorageBucketApi; -//# sourceMappingURL=StorageBucketApi.js.map - -/***/ }), - -/***/ 80710: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -const fetch_1 = __nccwpck_require__(73146); -const helpers_1 = __nccwpck_require__(5430); -const BlobDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(98475)); -const DEFAULT_SEARCH_OPTIONS = { - limit: 100, - offset: 0, - sortBy: { - column: 'name', - order: 'asc', - }, -}; -const DEFAULT_FILE_OPTIONS = { - cacheControl: '3600', - contentType: 'text/plain;charset=UTF-8', - upsert: false, -}; -class StorageFileApi { - constructor(url, headers = {}, bucketId, fetch) { - this.shouldThrowOnError = false; - this.url = url; - this.headers = headers; - this.bucketId = bucketId; - this.fetch = (0, helpers_1.resolveFetch)(fetch); - } - /** - * Enable throwing errors instead of returning them. - */ - throwOnError() { - this.shouldThrowOnError = true; - return this; - } - /** - * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. - * - * @param method HTTP method. - * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param fileBody The body of the file to be stored in the bucket. - */ - uploadOrUpdate(method, path, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - let body; - const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); - let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); - const metadata = options.metadata; - if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { - body = new FormData(); - body.append('cacheControl', options.cacheControl); - if (metadata) { - body.append('metadata', this.encodeMetadata(metadata)); - } - body.append('', fileBody); - } - else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { - body = fileBody; - body.append('cacheControl', options.cacheControl); - if (metadata) { - body.append('metadata', this.encodeMetadata(metadata)); - } - } - else { - body = fileBody; - headers['cache-control'] = `max-age=${options.cacheControl}`; - headers['content-type'] = options.contentType; - if (metadata) { - headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata)); - } - } - if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { - headers = Object.assign(Object.assign({}, headers), fileOptions.headers); - } - const cleanPath = this._removeEmptyFolders(path); - const _path = this._getFinalPath(cleanPath); - const data = yield (method == 'PUT' ? fetch_1.put : fetch_1.post)(this.fetch, `${this.url}/object/${_path}`, body, Object.assign({ headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); - return { - data: { path: cleanPath, id: data.Id, fullPath: data.Key }, - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Uploads a file to an existing bucket. - * - * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param fileBody The body of the file to be stored in the bucket. - */ - upload(path, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return this.uploadOrUpdate('POST', path, fileBody, fileOptions); - }); - } - /** - * Upload a file with a token generated from `createSignedUploadUrl`. - * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. - * @param token The token generated from `createSignedUploadUrl` - * @param fileBody The body of the file to be stored in the bucket. - */ - uploadToSignedUrl(path, token, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const cleanPath = this._removeEmptyFolders(path); - const _path = this._getFinalPath(cleanPath); - const url = new URL(this.url + `/object/upload/sign/${_path}`); - url.searchParams.set('token', token); - try { - let body; - const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); - const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); - if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { - body = new FormData(); - body.append('cacheControl', options.cacheControl); - body.append('', fileBody); - } - else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { - body = fileBody; - body.append('cacheControl', options.cacheControl); - } - else { - body = fileBody; - headers['cache-control'] = `max-age=${options.cacheControl}`; - headers['content-type'] = options.contentType; - } - const data = yield (0, fetch_1.put)(this.fetch, url.toString(), body, { headers }); - return { - data: { path: cleanPath, fullPath: data.Key }, - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a signed upload URL. - * Signed upload URLs can be used to upload files to the bucket without further authentication. - * They are valid for 2 hours. - * @param path The file path, including the current file name. For example `folder/image.png`. - * @param options.upsert If set to true, allows the file to be overwritten if it already exists. - */ - createSignedUploadUrl(path, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - let _path = this._getFinalPath(path); - const headers = Object.assign({}, this.headers); - if (options === null || options === void 0 ? void 0 : options.upsert) { - headers['x-upsert'] = 'true'; - } - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); - const url = new URL(this.url + data.url); - const token = url.searchParams.get('token'); - if (!token) { - throw new errors_1.StorageError('No token returned by API'); - } - return { data: { signedUrl: url.toString(), path, token }, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Replaces an existing file at the specified path with a new one. - * - * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. - * @param fileBody The body of the file to be stored in the bucket. - */ - update(path, fileBody, fileOptions) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); - }); - } - /** - * Moves an existing file to a new path in the same bucket. - * - * @param fromPath The original file path, including the current file name. For example `folder/image.png`. - * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. - * @param options The destination options. - */ - move(fromPath, toPath, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, { - bucketId: this.bucketId, - sourceKey: fromPath, - destinationKey: toPath, - destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, - }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Copies an existing file to a new path in the same bucket. - * - * @param fromPath The original file path, including the current file name. For example `folder/image.png`. - * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. - * @param options The destination options. - */ - copy(fromPath, toPath, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, { - bucketId: this.bucketId, - sourceKey: fromPath, - destinationKey: toPath, - destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, - }, { headers: this.headers }); - return { data: { path: data.Key }, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. - * - * @param path The file path, including the current file name. For example `folder/image.png`. - * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. - * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - * @param options.transform Transform the asset before serving it to the client. - */ - createSignedUrl(path, expiresIn, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - let _path = this._getFinalPath(path); - let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `&download=${options.download === true ? '' : options.download}` - : ''; - const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); - data = { signedUrl }; - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. - * - * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. - * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. - * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - */ - createSignedUrls(paths, expiresIn, options) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `&download=${options.download === true ? '' : options.download}` - : ''; - return { - data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL - ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) - : null }))), - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. - * - * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. - * @param options.transform Transform the asset before serving it to the client. - */ - download(path, options) { - const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; - const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; - const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); - const queryString = transformationQuery ? `?${transformationQuery}` : ''; - const _path = this._getFinalPath(path); - const downloadFn = () => (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { - headers: this.headers, - noResolveJson: true, - }); - return new BlobDownloadBuilder_1.default(downloadFn, this.shouldThrowOnError); - } - /** - * Retrieves the details of an existing file. - * @param path - */ - info(path) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const _path = this._getFinalPath(path); - try { - const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, { - headers: this.headers, - }); - return { data: (0, helpers_1.recursiveToCamel)(data), error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Checks the existence of a file. - * @param path - */ - exists(path) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - const _path = this._getFinalPath(path); - try { - yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, { - headers: this.headers, - }); - return { data: true, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) { - const originalError = error.originalError; - if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { - return { data: false, error }; - } - } - throw error; - } - }); - } - /** - * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. - * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. - * - * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. - * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. - * @param options.transform Transform the asset before serving it to the client. - */ - getPublicUrl(path, options) { - const _path = this._getFinalPath(path); - const _queryString = []; - const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) - ? `download=${options.download === true ? '' : options.download}` - : ''; - if (downloadQueryParam !== '') { - _queryString.push(downloadQueryParam); - } - const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; - const renderPath = wantsTransformation ? 'render/image' : 'object'; - const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); - if (transformationQuery !== '') { - _queryString.push(transformationQuery); - } - let queryString = _queryString.join('&'); - if (queryString !== '') { - queryString = `?${queryString}`; - } - return { - data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, - }; - } - /** - * Deletes files within the same bucket - * - * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. - */ - remove(paths) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * Get file metadata - * @param id the file id to retrieve metadata - */ - // async getMetadata( - // id: string - // ): Promise< - // | { - // data: Metadata - // error: null - // } - // | { - // data: null - // error: StorageError - // } - // > { - // try { - // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) - // return { data, error: null } - // } catch (error) { - // if (isStorageError(error)) { - // return { data: null, error } - // } - // throw error - // } - // } - /** - * Update file metadata - * @param id the file id to update metadata - * @param meta the new file metadata - */ - // async updateMetadata( - // id: string, - // meta: Metadata - // ): Promise< - // | { - // data: Metadata - // error: null - // } - // | { - // data: null - // error: StorageError - // } - // > { - // try { - // const data = await post( - // this.fetch, - // `${this.url}/metadata/${id}`, - // { ...meta }, - // { headers: this.headers } - // ) - // return { data, error: null } - // } catch (error) { - // if (isStorageError(error)) { - // return { data: null, error } - // } - // throw error - // } - // } - /** - * Lists all the files and folders within a path of the bucket. - * @param path The folder path. - * @param options Search options including limit (defaults to 100), offset, sortBy, and search - */ - list(path, options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - /** - * @experimental this method signature might change in the future - * @param options search options - * @param parameters - */ - listV2(options, parameters) { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const body = Object.assign({}, options); - const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list-v2/${this.bucketId}`, body, { headers: this.headers }, parameters); - return { data, error: null }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } - encodeMetadata(metadata) { - return JSON.stringify(metadata); - } - toBase64(data) { - if (typeof Buffer !== 'undefined') { - return Buffer.from(data).toString('base64'); - } - return btoa(data); - } - _getFinalPath(path) { - return `${this.bucketId}/${path.replace(/^\/+/, '')}`; - } - _removeEmptyFolders(path) { - return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); - } - transformOptsToQueryString(transform) { - const params = []; - if (transform.width) { - params.push(`width=${transform.width}`); - } - if (transform.height) { - params.push(`height=${transform.height}`); - } - if (transform.resize) { - params.push(`resize=${transform.resize}`); - } - if (transform.format) { - params.push(`format=${transform.format}`); - } - if (transform.quality) { - params.push(`quality=${transform.quality}`); - } - return params.join('&'); - } -} -exports["default"] = StorageFileApi; -//# sourceMappingURL=StorageFileApi.js.map - -/***/ }), - -/***/ 7023: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const tslib_1 = __nccwpck_require__(4351); -const errors_1 = __nccwpck_require__(42758); -class StreamDownloadBuilder { - constructor(downloadFn, shouldThrowOnError) { - this.downloadFn = downloadFn; - this.shouldThrowOnError = shouldThrowOnError; - } - then(onfulfilled, onrejected) { - return this.execute().then(onfulfilled, onrejected); - } - execute() { - return tslib_1.__awaiter(this, void 0, void 0, function* () { - try { - const result = yield this.downloadFn(); - return { - data: result.body, - error: null, - }; - } - catch (error) { - if (this.shouldThrowOnError) { - throw error; - } - if ((0, errors_1.isStorageError)(error)) { - return { data: null, error }; - } - throw error; - } - }); - } -} -exports["default"] = StreamDownloadBuilder; -//# sourceMappingURL=StreamDownloadBuilder.js.map - -/***/ }), - -/***/ 71807: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const functions_js_1 = __nccwpck_require__(38519); -const postgrest_js_1 = __nccwpck_require__(31178); -const realtime_js_1 = __nccwpck_require__(60442); -const storage_js_1 = __nccwpck_require__(45852); -const constants_1 = __nccwpck_require__(94868); -const fetch_1 = __nccwpck_require__(50785); -const helpers_1 = __nccwpck_require__(3575); -const SupabaseAuthClient_1 = __nccwpck_require__(87620); -/** - * Supabase Client. - * - * An isomorphic Javascript client for interacting with Postgres. - */ -class SupabaseClient { - /** - * Create a new client for use in the browser. - * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. - * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. - * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. - * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. - * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. - * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. - * @param options.realtime Options passed along to realtime-js constructor. - * @param options.storage Options passed along to the storage-js constructor. - * @param options.global.fetch A custom fetch implementation. - * @param options.global.headers Any additional headers to send with each network request. - */ - constructor(supabaseUrl, supabaseKey, options) { - var _a, _b, _c; - this.supabaseUrl = supabaseUrl; - this.supabaseKey = supabaseKey; - const baseUrl = (0, helpers_1.validateSupabaseUrl)(supabaseUrl); - if (!supabaseKey) - throw new Error('supabaseKey is required.'); - this.realtimeUrl = new URL('realtime/v1', baseUrl); - this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws'); - this.authUrl = new URL('auth/v1', baseUrl); - this.storageUrl = new URL('storage/v1', baseUrl); - this.functionsUrl = new URL('functions/v1', baseUrl); - // default storage key uses the supabase project ref as a namespace - const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`; - const DEFAULTS = { - db: constants_1.DEFAULT_DB_OPTIONS, - realtime: constants_1.DEFAULT_REALTIME_OPTIONS, - auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), - global: constants_1.DEFAULT_GLOBAL_OPTIONS, - }; - const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); - this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; - this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; - if (!settings.accessToken) { - this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); - } - else { - this.accessToken = settings.accessToken; - this.auth = new Proxy({}, { - get: (_, prop) => { - throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); - }, - }); - } - this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); - this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); - this.rest = new postgrest_js_1.PostgrestClient(new URL('rest/v1', baseUrl).href, { - headers: this.headers, - schema: settings.db.schema, - fetch: this.fetch, - }); - this.storage = new storage_js_1.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); - if (!settings.accessToken) { - this._listenForAuthEvents(); - } - } - /** - * Supabase Functions allows you to deploy and invoke edge functions. - */ - get functions() { - return new functions_js_1.FunctionsClient(this.functionsUrl.href, { - headers: this.headers, - customFetch: this.fetch, - }); - } - /** - * Perform a query on a table or a view. - * - * @param relation - The table or view name to query - */ - from(relation) { - return this.rest.from(relation); - } - // NOTE: signatures must be kept in sync with PostgrestClient.schema - /** - * Select a schema to query or perform an function (rpc) call. - * - * The schema needs to be on the list of exposed schemas inside Supabase. - * - * @param schema - The schema to query - */ - schema(schema) { - return this.rest.schema(schema); - } - // NOTE: signatures must be kept in sync with PostgrestClient.rpc - /** - * Perform a function call. - * - * @param fn - The function name to call - * @param args - The arguments to pass to the function call - * @param options - Named parameters - * @param options.head - When set to `true`, `data` will not be returned. - * Useful if you only need the count. - * @param options.get - When set to `true`, the function will be called with - * read-only access mode. - * @param options.count - Count algorithm to use to count rows returned by the - * function. Only applicable for [set-returning - * functions](https://www.postgresql.org/docs/current/functions-srf.html). - * - * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the - * hood. - * - * `"planned"`: Approximated but fast count algorithm. Uses the Postgres - * statistics under the hood. - * - * `"estimated"`: Uses exact count for low numbers and planned count for high - * numbers. - */ - rpc(fn, args = {}, options = { - head: false, - get: false, - count: undefined, - }) { - return this.rest.rpc(fn, args, options); - } - /** - * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. - * - * @param {string} name - The name of the Realtime channel. - * @param {Object} opts - The options to pass to the Realtime channel. - * - */ - channel(name, opts = { config: {} }) { - return this.realtime.channel(name, opts); - } - /** - * Returns all Realtime channels. - */ - getChannels() { - return this.realtime.getChannels(); - } - /** - * Unsubscribes and removes Realtime channel from Realtime client. - * - * @param {RealtimeChannel} channel - The name of the Realtime channel. - * - */ - removeChannel(channel) { - return this.realtime.removeChannel(channel); - } - /** - * Unsubscribes and removes all Realtime channels from Realtime client. - */ - removeAllChannels() { - return this.realtime.removeAllChannels(); - } - async _getAccessToken() { - var _a, _b; - if (this.accessToken) { - return await this.accessToken(); - } - const { data } = await this.auth.getSession(); - return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; - } - _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, }, headers, fetch) { - const authHeaders = { - Authorization: `Bearer ${this.supabaseKey}`, - apikey: `${this.supabaseKey}`, - }; - return new SupabaseAuthClient_1.SupabaseAuthClient({ - url: this.authUrl.href, - headers: Object.assign(Object.assign({}, authHeaders), headers), - storageKey: storageKey, - autoRefreshToken, - persistSession, - detectSessionInUrl, - storage, - userStorage, - flowType, - lock, - debug, - fetch, - // auth checks if there is a custom authorizaiton header using this flag - // so it knows whether to return an error when getUser is called with no session - hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === 'authorization'), - }); - } - _initRealtimeClient(options) { - return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); - } - _listenForAuthEvents() { - const data = this.auth.onAuthStateChange((event, session) => { - this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); - }); - return data; - } - _handleTokenChanged(event, source, token) { - if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && - this.changedAccessToken !== token) { - this.changedAccessToken = token; - this.realtime.setAuth(token); - } - else if (event === 'SIGNED_OUT') { - this.realtime.setAuth(); - if (source == 'STORAGE') - this.auth.signOut(); - this.changedAccessToken = undefined; - } - } -} -exports["default"] = SupabaseClient; -//# sourceMappingURL=SupabaseClient.js.map - -/***/ }), - -/***/ 91206: -/***/ (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 __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); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0; -const SupabaseClient_1 = __importDefault(__nccwpck_require__(71807)); -__exportStar(__nccwpck_require__(66748), exports); -var postgrest_js_1 = __nccwpck_require__(31178); -Object.defineProperty(exports, "PostgrestError", ({ enumerable: true, get: function () { return postgrest_js_1.PostgrestError; } })); -var functions_js_1 = __nccwpck_require__(38519); -Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsHttpError; } })); -Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsFetchError; } })); -Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsRelayError; } })); -Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsError; } })); -Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return functions_js_1.FunctionRegion; } })); -__exportStar(__nccwpck_require__(60442), exports); -var SupabaseClient_2 = __nccwpck_require__(71807); -Object.defineProperty(exports, "SupabaseClient", ({ enumerable: true, get: function () { return __importDefault(SupabaseClient_2).default; } })); -/** - * Creates a new Supabase Client. - */ -const createClient = (supabaseUrl, supabaseKey, options) => { - return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); -}; -exports.createClient = createClient; -// Check for Node.js <= 18 deprecation -function shouldShowDeprecationWarning() { - // Skip in browser environments - if (typeof window !== 'undefined') { - return false; - } - // Skip if process is not available (e.g., Edge Runtime) - if (typeof process === 'undefined') { - return false; - } - // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings - const processVersion = process['version']; - if (processVersion === undefined || processVersion === null) { - return false; - } - const versionMatch = processVersion.match(/^v(\d+)\./); - if (!versionMatch) { - return false; - } - const majorVersion = parseInt(versionMatch[1], 10); - return majorVersion <= 18; -} -if (shouldShowDeprecationWarning()) { - console.warn(`āš ļø Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` + - `Please upgrade to Node.js 20 or later. ` + - `For more information, visit: https://github.com/orgs/supabase/discussions/37217`); -} -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 87620: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SupabaseAuthClient = void 0; -const auth_js_1 = __nccwpck_require__(66748); -class SupabaseAuthClient extends auth_js_1.AuthClient { - constructor(options) { - super(options); - } -} -exports.SupabaseAuthClient = SupabaseAuthClient; -//# sourceMappingURL=SupabaseAuthClient.js.map - -/***/ }), - -/***/ 94868: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0; -const version_1 = __nccwpck_require__(86136); -let JS_ENV = ''; -// @ts-ignore -if (typeof Deno !== 'undefined') { - JS_ENV = 'deno'; -} -else if (typeof document !== 'undefined') { - JS_ENV = 'web'; -} -else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { - JS_ENV = 'react-native'; -} -else { - JS_ENV = 'node'; -} -exports.DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version_1.version}` }; -exports.DEFAULT_GLOBAL_OPTIONS = { - headers: exports.DEFAULT_HEADERS, -}; -exports.DEFAULT_DB_OPTIONS = { - schema: 'public', -}; -exports.DEFAULT_AUTH_OPTIONS = { - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true, - flowType: 'implicit', -}; -exports.DEFAULT_REALTIME_OPTIONS = {}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 50785: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; -// @ts-ignore -const node_fetch_1 = __importStar(__nccwpck_require__(93149)); -const resolveFetch = (customFetch) => { - let _fetch; - if (customFetch) { - _fetch = customFetch; - } - else if (typeof fetch === 'undefined') { - _fetch = node_fetch_1.default; - } - else { - _fetch = fetch; - } - return (...args) => _fetch(...args); -}; -exports.resolveFetch = resolveFetch; -const resolveHeadersConstructor = () => { - if (typeof Headers === 'undefined') { - return node_fetch_1.Headers; - } - return Headers; -}; -exports.resolveHeadersConstructor = resolveHeadersConstructor; -const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { - const fetch = (0, exports.resolveFetch)(customFetch); - const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); - return async (input, init) => { - var _a; - const accessToken = (_a = (await getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; - let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); - if (!headers.has('apikey')) { - headers.set('apikey', supabaseKey); - } - if (!headers.has('Authorization')) { - headers.set('Authorization', `Bearer ${accessToken}`); - } - return fetch(input, Object.assign(Object.assign({}, init), { headers })); - }; -}; -exports.fetchWithAuth = fetchWithAuth; -//# sourceMappingURL=fetch.js.map - -/***/ }), - -/***/ 3575: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isBrowser = void 0; -exports.uuid = uuid; -exports.ensureTrailingSlash = ensureTrailingSlash; -exports.applySettingDefaults = applySettingDefaults; -exports.validateSupabaseUrl = validateSupabaseUrl; -function uuid() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -} -function ensureTrailingSlash(url) { - return url.endsWith('/') ? url : url + '/'; -} -const isBrowser = () => typeof window !== 'undefined'; -exports.isBrowser = isBrowser; -function applySettingDefaults(options, defaults) { - var _a, _b; - const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; - const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; - const result = { - db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), - auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), - realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), - storage: {}, - global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, ((_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {})), ((_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {})) }), - accessToken: async () => '', - }; - if (options.accessToken) { - result.accessToken = options.accessToken; - } - else { - // hack around Required<> - delete result.accessToken; - } - return result; -} -/** - * Validates a Supabase client URL - * - * @param {string} supabaseUrl - The Supabase client URL string. - * @returns {URL} - The validated base URL. - * @throws {Error} - */ -function validateSupabaseUrl(supabaseUrl) { - const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); - if (!trimmedUrl) { - throw new Error('supabaseUrl is required.'); - } - if (!trimmedUrl.match(/^https?:\/\//i)) { - throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.'); - } - try { - return new URL(ensureTrailingSlash(trimmedUrl)); - } - catch (_a) { - throw Error('Invalid supabaseUrl: Provided URL is malformed.'); - } -} -//# sourceMappingURL=helpers.js.map - -/***/ }), - -/***/ 86136: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.version = void 0; -// Generated automatically during releases by scripts/update-version-files.ts -// This file provides runtime access to the package version for: -// - HTTP request headers (e.g., X-Client-Info header for API requests) -// - Debugging and support (identifying which version is running) -// - Telemetry and logging (version reporting in errors/analytics) -// - Ensuring build artifacts match the published package version -exports.version = '2.78.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ 22225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const stringWidth = __nccwpck_require__(95537) - -function ansiAlign (text, opts) { - if (!text) return text - - opts = opts || {} - const align = opts.align || 'center' - - // short-circuit `align: 'left'` as no-op - if (align === 'left') return text - - const split = opts.split || '\n' - const pad = opts.pad || ' ' - const widthDiffFn = align !== 'right' ? halfDiff : fullDiff - - let returnString = false - if (!Array.isArray(text)) { - returnString = true - text = String(text).split(split) - } - - let width - let maxWidth = 0 - text = text.map(function (str) { - str = String(str) - width = stringWidth(str) - maxWidth = Math.max(width, maxWidth) - return { - str, - width - } - }).map(function (obj) { - return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str - }) - - return returnString ? text.join(split) : text -} - -ansiAlign.left = function left (text) { - return ansiAlign(text, { align: 'left' }) -} - -ansiAlign.center = function center (text) { - return ansiAlign(text, { align: 'center' }) -} - -ansiAlign.right = function right (text) { - return ansiAlign(text, { align: 'right' }) -} - -module.exports = ansiAlign - -function halfDiff (maxWidth, curWidth) { - return Math.floor((maxWidth - curWidth) / 2) -} - -function fullDiff (maxWidth, curWidth) { - return maxWidth - curWidth -} - - -/***/ }), - -/***/ 50140: -/***/ ((module) => { - -"use strict"; - - -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; - - -/***/ }), - -/***/ 13652: -/***/ ((module) => { - -"use strict"; - - -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; -}; - - -/***/ }), - -/***/ 95537: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const stripAnsi = __nccwpck_require__(91411); -const isFullwidthCodePoint = __nccwpck_require__(64882); -const emojiRegex = __nccwpck_require__(13652); - -const stringWidth = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; -}; - -module.exports = stringWidth; -// TODO: remove this in the next major version -module.exports["default"] = stringWidth; - - -/***/ }), - -/***/ 91411: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const ansiRegex = __nccwpck_require__(50140); - -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; - - -/***/ }), - -/***/ 99348: -/***/ ((module) => { - -// 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 - -}; - - -/***/ }), - -/***/ 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); -} - - -/***/ }), - -/***/ 91403: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -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 Stream = (__nccwpck_require__(12781).Stream); -var crypto = __nccwpck_require__(6113); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var setToStringTag = __nccwpck_require__(11770); -var hasOwn = __nccwpck_require__(62157); -var populate = __nccwpck_require__(47027); - -/** - * 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(options); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); - - options = options || {}; // eslint-disable-line no-param-reassign - for (var option in options) { // eslint-disable-line no-restricted-syntax - this[option] = options[option]; - } -} - -// make it a Stream -util.inherits(FormData, CombinedStream); - -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function (field, value, options) { - options = options || {}; // eslint-disable-line no-param-reassign - - // allow filename as single option - if (typeof options === 'string') { - options = { filename: options }; // eslint-disable-line no-param-reassign - } - - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value === 'number' || value == null) { - value = String(value); // eslint-disable-line no-param-reassign - } - - // https://github.com/felixge/node-form-data/issues/38 - if (Array.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 += Number(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 or not a stream - if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')) && !(value instanceof Stream))) { - return; - } - - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; - -FormData.prototype._lengthRetriever = function (value, callback) { - if (hasOwn(value, '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)); // eslint-disable-line callback-return - - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function (err, stat) { - if (err) { - callback(err); - return; - } - - // update final size based on the range options - var fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - - // or http response - } else if (hasOwn(value, 'httpVersion')) { - callback(null, Number(value.headers['content-length'])); // eslint-disable-line callback-return - - // or request stream http://github.com/mikeal/request - } else if (hasOwn(value, 'httpModule')) { - // wait till response come back - value.on('response', function (response) { - value.pause(); - callback(null, Number(response.headers['content-length'])); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); // eslint-disable-line callback-return - } -}; - -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) { // eslint-disable-line no-restricted-syntax - if (hasOwn(headers, prop)) { - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; // eslint-disable-line no-restricted-syntax, no-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) { // eslint-disable-line consistent-return - var filename; - - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || (value && (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 && (value.name || value.path))); - } else if (value && value.readable && hasOwn(value, 'httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } - - if (filename) { - return 'filename="' + filename + '"'; - } -}; - -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 && value.name) { - contentType = mime.lookup(value.name); - } - - // or try `path` from fs-, request- streams - if (!contentType && value && value.path) { - contentType = mime.lookup(value.path); - } - - // or if it's http-reponse - if (!contentType && value && value.readable && hasOwn(value, '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 && value && 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) { // eslint-disable-line no-restricted-syntax - if (hasOwn(userHeaders, header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - - return formHeaders; -}; - -FormData.prototype.setBoundary = function (boundary) { - if (typeof boundary !== 'string') { - throw new TypeError('FormData boundary must be a string'); - } - this._boundary = boundary; -}; - -FormData.prototype.getBoundary = function () { - if (!this._boundary) { - this._generateBoundary(); - } - - return this._boundary; -}; - -FormData.prototype.getBuffer = function () { - var dataBuffer = new Buffer.alloc(0); // eslint-disable-line new-cap - var boundary = this.getBoundary(); - - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - // Add content to the buffer. - if (Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); - } else { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); - } - - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData.LINE_BREAK)]); - } - } - } - - // Add the footer and return the Buffer object. - return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); -}; - -FormData.prototype._generateBoundary = function () { - // This generates a 50 character boundary similar to those used by Firefox. - - // They are optimized for boyer-moore parsing. - this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); -}; - -// 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; - var options; - var defaults = { method: 'post' }; - - // parse provided url if it's string or treat it as options object - if (typeof params === 'string') { - params = parseUrl(params); // eslint-disable-line no-param-reassign - /* eslint sort-keys: 0 */ - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - } else { // use custom params - 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 && err !== 'Unknown stream') { - this._error(err); - return; - } - - // add content length - if (length) { - request.setHeader('Content-Length', length); - } - - this.pipe(request); - if (cb) { - var onResponse; - - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); - - return cb.call(this, error, responce); // eslint-disable-line no-invalid-this - }; - - onResponse = callback.bind(this, null); - - request.on('error', callback); - request.on('response', onResponse); - } - }.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]'; -}; -setToStringTag(FormData, 'FormData'); - -// Public API -module.exports = FormData; - - -/***/ }), - -/***/ 47027: -/***/ ((module) => { - -"use strict"; - - -// populates missing values -module.exports = function (dst, src) { - Object.keys(src).forEach(function (prop) { - dst[prop] = dst[prop] || src[prop]; // eslint-disable-line no-param-reassign - }); - - return dst; -}; - - -/***/ }), - -/***/ 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); -} - - -/***/ }), - -/***/ 23664: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Buffer } = __nccwpck_require__(14300) -const symbol = Symbol.for('BufferList') - -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) - } - - BufferList._init.call(this, buf) -} - -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) - - this._bufs = [] - this.length = 0 - - if (buf) { - this.append(buf) - } -} - -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) -} - -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] - } - - let tot = 0 - - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] - } - tot = _t - } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] - - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - - return offset -} - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - - const offset = this._offset(index) - - return this._bufs[offset[0]][offset[1]] -} - -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length - } - - if (typeof end === 'number' && end < 0) { - end += this.length - } - - return this.copy(null, 0, start, end) -} - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } - - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } - - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } - - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } - - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] - - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } - - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } - - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start - - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } - - bytes -= l - - if (start) { - start = 0 - } - } - - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) - - return dst -} - -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - - if (start < 0) { - start += this.length - } - - if (end < 0) { - end += this.length - } - - if (start === end) { - return this._new() - } - - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - - if (endOffset[1] === 0) { - buffers.pop() - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) - } - - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } - - return this._new(buffers) -} - -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} - -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this - - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } - - return this -} - -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() - - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) - } - - return copy -} - -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this - } - - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() - } - - this._appendBuffer(Buffer.from(buf)) - } - - return this -} - -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} - -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } - - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - - offset = Number(offset || 0) - - if (isNaN(offset)) { - offset = 0 - } - - if (offset < 0) { - offset = this.length + offset - } - - if (offset < 0) { - offset = 0 - } - - if (search.length === 0) { - return offset > this.length ? this.length : offset - } - - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on - - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] - - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset - - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) - - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } - - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) - - if (this._match(revOffset, search)) { - return revOffset - } - - buffOffset++ - } - } - - buffOffset = 0 - } - - return -1 -} - -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } - - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false - } - } - return true -} - -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - } - - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) - -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) -} - -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] -} - -module.exports = BufferList - - -/***/ }), - -/***/ 20336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const DuplexStream = (__nccwpck_require__(51642).Duplex) -const inherits = __nccwpck_require__(44124) -const BufferList = __nccwpck_require__(23664) - -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) - } - - if (typeof callback === 'function') { - this._callback = callback - - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) - - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - - callback = null - } - - BufferList._init.call(this, callback) - DuplexStream.call(this) -} - -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) - -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) -} - -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback === 'function') { - callback() - } -} - -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } - - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} - -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} - -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) -} - -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} - -BufferListStream.isBufferList = BufferList.isBufferList - -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList - - -/***/ }), - -/***/ 19227: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var bind = __nccwpck_require__(88334); - -var $apply = __nccwpck_require__(54177); -var $call = __nccwpck_require__(2808); -var $reflectApply = __nccwpck_require__(48309); - -/** @type {import('./actualApply')} */ -module.exports = $reflectApply || bind.call($call, $apply); - - -/***/ }), - -/***/ 54177: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./functionApply')} */ -module.exports = Function.prototype.apply; - - -/***/ }), - -/***/ 2808: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./functionCall')} */ -module.exports = Function.prototype.call; - - -/***/ }), - -/***/ 86815: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var bind = __nccwpck_require__(88334); -var $TypeError = __nccwpck_require__(6361); - -var $call = __nccwpck_require__(2808); -var $actualApply = __nccwpck_require__(19227); - -/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ -module.exports = function callBindBasic(args) { - if (args.length < 1 || typeof args[0] !== 'function') { - throw new $TypeError('a function is required'); - } - return $actualApply(bind, $call, args); -}; - - -/***/ }), - -/***/ 48309: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./reflectApply')} */ -module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; - - -/***/ }), - -/***/ 82983: -/***/ ((module, exports) => { - -// Chance.js 1.1.12 -// https://chancejs.com -// (c) 2013 Victor Quinn -// Chance may be freely distributed or modified under the MIT license. - -(function () { - - // Constants - var MAX_INT = 9007199254740992; - var MIN_INT = -MAX_INT; - var NUMBERS = '0123456789'; - var CHARS_LOWER = 'abcdefghijklmnopqrstuvwxyz'; - var CHARS_UPPER = CHARS_LOWER.toUpperCase(); - var HEX_POOL = NUMBERS + "abcdef"; - - // Errors - function UnsupportedError(message) { - this.name = 'UnsupportedError'; - this.message = message || 'This feature is not supported on this platform'; - } - - UnsupportedError.prototype = new Error(); - UnsupportedError.prototype.constructor = UnsupportedError; - - // Cached array helpers - var slice = Array.prototype.slice; - - // Constructor - function Chance (seed) { - if (!(this instanceof Chance)) { - if (!seed) { seed = null; } // handle other non-truthy seeds, as described in issue #322 - return seed === null ? new Chance() : new Chance(seed); - } - - // if user has provided a function, use that as the generator - if (typeof seed === 'function') { - this.random = seed; - return this; - } - - if (arguments.length) { - // set a starting value of zero so we can add to it - this.seed = 0; - } - - // otherwise, leave this.seed blank so that MT will receive a blank - - for (var i = 0; i < arguments.length; i++) { - var seedling = 0; - if (Object.prototype.toString.call(arguments[i]) === '[object String]') { - for (var j = 0; j < arguments[i].length; j++) { - // create a numeric hash for each argument, add to seedling - var hash = 0; - for (var k = 0; k < arguments[i].length; k++) { - hash = arguments[i].charCodeAt(k) + (hash << 6) + (hash << 16) - hash; - } - seedling += hash; - } - } else { - seedling = arguments[i]; - } - this.seed += (arguments.length - i) * seedling; - } - - // If no generator function was provided, use our MT - this.mt = this.mersenne_twister(this.seed); - this.bimd5 = this.blueimp_md5(); - this.random = function () { - return this.mt.random(this.seed); - }; - - return this; - } - - Chance.prototype.VERSION = "1.1.13"; - - // Random helper functions - function initOptions(options, defaults) { - options = options || {}; - - if (defaults) { - for (var i in defaults) { - if (typeof options[i] === 'undefined') { - options[i] = defaults[i]; - } - } - } - - return options; - } - - function range(size) { - return Array.apply(null, Array(size)).map(function (_, i) {return i;}); - } - - function testRange(test, errorMessage) { - if (test) { - throw new RangeError(errorMessage); - } - } - - /** - * Encode the input string with Base64. - */ - var base64 = function() { - throw new Error('No Base64 encoder available.'); - }; - - // Select proper Base64 encoder. - (function determineBase64Encoder() { - if (typeof btoa === 'function') { - base64 = btoa; - } else if (typeof Buffer === 'function') { - base64 = function(input) { - return new Buffer(input).toString('base64'); - }; - } - })(); - - // -- Basics -- - - /** - * Return a random bool, either true or false - * - * @param {Object} [options={ likelihood: 50 }] alter the likelihood of - * receiving a true or false value back. - * @throws {RangeError} if the likelihood is out of bounds - * @returns {Bool} either true or false - */ - Chance.prototype.bool = function (options) { - // likelihood of success (true) - options = initOptions(options, {likelihood : 50}); - - // Note, we could get some minor perf optimizations by checking range - // prior to initializing defaults, but that makes code a bit messier - // and the check more complicated as we have to check existence of - // the object then existence of the key before checking constraints. - // Since the options initialization should be minor computationally, - // decision made for code cleanliness intentionally. This is mentioned - // here as it's the first occurrence, will not be mentioned again. - testRange( - options.likelihood < 0 || options.likelihood > 100, - "Chance: Likelihood accepts values from 0 to 100." - ); - - return this.random() * 100 < options.likelihood; - }; - - Chance.prototype.falsy = function (options) { - // return a random falsy value - options = initOptions(options, {pool: [false, null, 0, NaN, '', undefined]}) - var pool = options.pool, - index = this.integer({min: 0, max: pool.length - 1}), - value = pool[index]; - - return value; - } - - Chance.prototype.animal = function (options){ - //returns a random animal - options = initOptions(options); - - if(typeof options.type !== 'undefined'){ - //if user does not put in a valid animal type, user will get an error - testRange( - !this.get("animals")[options.type.toLowerCase()], - "Please pick from desert, ocean, grassland, forest, zoo, pets, farm." - ); - //if user does put in valid animal type, will return a random animal of that type - return this.pick(this.get("animals")[options.type.toLowerCase()]); - } - //if user does not put in any animal type, will return a random animal regardless - var animalTypeArray = ["desert","forest","ocean","zoo","farm","pet","grassland"]; - return this.pick(this.get("animals")[this.pick(animalTypeArray)]); - }; - - /** - * Return a random character. - * - * @param {Object} [options={}] can specify a character pool or alpha, - * numeric, symbols and casing (lower or upper) - * @returns {String} a single random character - */ - Chance.prototype.character = function (options) { - options = initOptions(options); - - var symbols = "!@#$%^&*()[]", - letters, pool; - - if (options.casing === 'lower') { - letters = CHARS_LOWER; - } else if (options.casing === 'upper') { - letters = CHARS_UPPER; - } else { - letters = CHARS_LOWER + CHARS_UPPER; - } - - if (options.pool) { - pool = options.pool; - } else { - pool = ''; - if (options.alpha) { - pool += letters; - } - if (options.numeric) { - pool += NUMBERS; - } - if (options.symbols) { - pool += symbols; - } - if (!pool) { - pool = letters + NUMBERS + symbols; - } - } - - return pool.charAt(this.natural({max: (pool.length - 1)})); - }; - - // Note, wanted to use "float" or "double" but those are both JS reserved words. - - // Note, fixed means N OR LESS digits after the decimal. This because - // It could be 14.9000 but in JavaScript, when this is cast as a number, - // the trailing zeroes are dropped. Left to the consumer if trailing zeroes are - // needed - /** - * Return a random floating point number - * - * @param {Object} [options={}] can specify a fixed precision, min, max - * @returns {Number} a single floating point number - * @throws {RangeError} Can only specify fixed or precision, not both. Also - * min cannot be greater than max - */ - Chance.prototype.floating = function (options) { - options = initOptions(options, {fixed : 4}); - testRange( - options.fixed && options.precision, - "Chance: Cannot specify both fixed and precision." - ); - - var num; - var fixed = Math.pow(10, options.fixed); - - var max = MAX_INT / fixed; - var min = -max; - - testRange( - options.min && options.fixed && options.min < min, - "Chance: Min specified is out of range with fixed. Min should be, at least, " + min - ); - testRange( - options.max && options.fixed && options.max > max, - "Chance: Max specified is out of range with fixed. Max should be, at most, " + max - ); - - options = initOptions(options, { min : min, max : max }); - - // Todo - Make this work! - // options.precision = (typeof options.precision !== "undefined") ? options.precision : false; - - num = this.integer({min: options.min * fixed, max: options.max * fixed}); - var num_fixed = (num / fixed).toFixed(options.fixed); - - return parseFloat(num_fixed); - }; - - /** - * Return a random integer - * - * NOTE the max and min are INCLUDED in the range. So: - * chance.integer({min: 1, max: 3}); - * would return either 1, 2, or 3. - * - * @param {Object} [options={}] can specify a min and/or max - * @returns {Number} a single random integer number - * @throws {RangeError} min cannot be greater than max - */ - Chance.prototype.integer = function (options) { - // 9007199254740992 (2^53) is the max integer number in JavaScript - // See: http://vq.io/132sa2j - options = initOptions(options, {min: MIN_INT, max: MAX_INT}); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - return Math.floor(this.random() * (options.max - options.min + 1) + options.min); - }; - - /** - * Return a random natural - * - * NOTE the max and min are INCLUDED in the range. So: - * chance.natural({min: 1, max: 3}); - * would return either 1, 2, or 3. - * - * @param {Object} [options={}] can specify a min and/or max or a numerals count. - * @returns {Number} a single random integer number - * @throws {RangeError} min cannot be greater than max - */ - Chance.prototype.natural = function (options) { - options = initOptions(options, {min: 0, max: MAX_INT}); - if (typeof options.numerals === 'number'){ - testRange(options.numerals < 1, "Chance: Numerals cannot be less than one."); - options.min = Math.pow(10, options.numerals - 1); - options.max = Math.pow(10, options.numerals) - 1; - } - testRange(options.min < 0, "Chance: Min cannot be less than zero."); - - if (options.exclude) { - testRange(!Array.isArray(options.exclude), "Chance: exclude must be an array.") - - for (var exclusionIndex in options.exclude) { - testRange(!Number.isInteger(options.exclude[exclusionIndex]), "Chance: exclude must be numbers.") - } - - var random = options.min + this.natural({max: options.max - options.min - options.exclude.length}) - var sortedExclusions = options.exclude.sort((a, b) => a - b); - for (var sortedExclusionIndex in sortedExclusions) { - if (random < sortedExclusions[sortedExclusionIndex]) { - break - } - random++ - } - return random - } - return this.integer(options); - }; - - /** - * Return a random prime number - * - * NOTE the max and min are INCLUDED in the range. - * - * @param {Object} [options={}] can specify a min and/or max - * @returns {Number} a single random prime number - * @throws {RangeError} min cannot be greater than max nor negative - */ - Chance.prototype.prime = function (options) { - options = initOptions(options, {min: 0, max: 10000}); - testRange(options.min < 0, "Chance: Min cannot be less than zero."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - var lastPrime = data.primes[data.primes.length - 1]; - if (options.max > lastPrime) { - for (var i = lastPrime + 2; i <= options.max; ++i) { - if (this.is_prime(i)) { - data.primes.push(i); - } - } - } - var targetPrimes = data.primes.filter(function (prime) { - return prime >= options.min && prime <= options.max; - }); - return this.pick(targetPrimes); - }; - - /** - * Determine whether a given number is prime or not. - */ - Chance.prototype.is_prime = function (n) { - if (n % 1 || n < 2) { - return false; - } - if (n % 2 === 0) { - return n === 2; - } - if (n % 3 === 0) { - return n === 3; - } - var m = Math.sqrt(n); - for (var i = 5; i <= m; i += 6) { - if (n % i === 0 || n % (i + 2) === 0) { - return false; - } - } - return true; - }; - - /** - * Return a random hex number as string - * - * NOTE the max and min are INCLUDED in the range. So: - * chance.hex({min: '9', max: 'B'}); - * would return either '9', 'A' or 'B'. - * - * @param {Object} [options={}] can specify a min and/or max and/or casing - * @returns {String} a single random string hex number - * @throws {RangeError} min cannot be greater than max - */ - Chance.prototype.hex = function (options) { - options = initOptions(options, {min: 0, max: MAX_INT, casing: 'lower'}); - testRange(options.min < 0, "Chance: Min cannot be less than zero."); - var integer = this.natural({min: options.min, max: options.max}); - if (options.casing === 'upper') { - return integer.toString(16).toUpperCase(); - } - return integer.toString(16); - }; - - Chance.prototype.letter = function(options) { - options = initOptions(options, {casing: 'lower'}); - var pool = "abcdefghijklmnopqrstuvwxyz"; - var letter = this.character({pool: pool}); - if (options.casing === 'upper') { - letter = letter.toUpperCase(); - } - return letter; - } - - /** - * Return a random string - * - * @param {Object} [options={}] can specify a length or min and max - * @returns {String} a string of random length - * @throws {RangeError} length cannot be less than zero - */ - Chance.prototype.string = function (options) { - options = initOptions(options, { min: 5, max: 20 }); - - if (options.length !== 0 && !options.length) { - options.length = this.natural({ min: options.min, max: options.max }) - } - - testRange(options.length < 0, "Chance: Length cannot be less than zero."); - var length = options.length, - text = this.n(this.character, length, options); - - return text.join(""); - }; - - function CopyToken(c) { - this.c = c - } - - CopyToken.prototype = { - substitute: function () { - return this.c - } - } - - function EscapeToken(c) { - this.c = c - } - - EscapeToken.prototype = { - substitute: function () { - if (!/[{}\\]/.test(this.c)) { - throw new Error('Invalid escape sequence: "\\' + this.c + '".') - } - return this.c - } - } - - function ReplaceToken(c) { - this.c = c - } - - ReplaceToken.prototype = { - replacers: { - '#': function (chance) { return chance.character({ pool: NUMBERS }) }, - 'A': function (chance) { return chance.character({ pool: CHARS_UPPER }) }, - 'a': function (chance) { return chance.character({ pool: CHARS_LOWER }) }, - }, - - substitute: function (chance) { - var replacer = this.replacers[this.c] - if (!replacer) { - throw new Error('Invalid replacement character: "' + this.c + '".') - } - return replacer(chance) - } - } - - function parseTemplate(template) { - var tokens = [] - var mode = 'identity' - for (var i = 0; i MAX_DUPLICATES) { - throw new RangeError("Chance: num is likely too large for sample set"); - } - } - return arr; - }; - - /** - * Gives an array of n random terms - * - * @param {Function} fn the function that generates something random - * @param {Number} n number of terms to generate - * @returns {Array} an array of length `n` with items generated by `fn` - * - * There can be more parameters after these. All additional parameters are provided to the given function - */ - Chance.prototype.n = function(fn, n) { - testRange( - typeof fn !== "function", - "Chance: The first argument must be a function." - ); - - if (typeof n === 'undefined') { - n = 1; - } - var i = n, arr = [], params = slice.call(arguments, 2); - - // Providing a negative count should result in a noop. - i = Math.max( 0, i ); - - for (null; i--; null) { - arr.push(fn.apply(this, params)); - } - - return arr; - }; - - // H/T to SO for this one: http://vq.io/OtUrZ5 - Chance.prototype.pad = function (number, width, pad) { - // Default pad to 0 if none provided - pad = pad || '0'; - // Convert number to a string - number = number + ''; - return number.length >= width ? number : new Array(width - number.length + 1).join(pad) + number; - }; - - // DEPRECATED on 2015-10-01 - Chance.prototype.pick = function (arr, count) { - if (arr.length === 0) { - throw new RangeError("Chance: Cannot pick() from an empty array"); - } - if (!count || count === 1) { - return arr[this.natural({max: arr.length - 1})]; - } else { - return this.shuffle(arr).slice(0, count); - } - }; - - // Given an array, returns a single random element - Chance.prototype.pickone = function (arr) { - if (arr.length === 0) { - throw new RangeError("Chance: Cannot pickone() from an empty array"); - } - return arr[this.natural({max: arr.length - 1})]; - }; - - // Given an array, returns a random set with 'count' elements - Chance.prototype.pickset = function (arr, count) { - if (count === 0) { - return []; - } - if (arr.length === 0) { - throw new RangeError("Chance: Cannot pickset() from an empty array"); - } - if (count < 0) { - throw new RangeError("Chance: Count must be a positive number"); - } - if (!count || count === 1) { - return [ this.pickone(arr) ]; - } else { - var array = arr.slice(0); - var end = array.length; - - return this.n(function () { - var index = this.natural({max: --end}); - var value = array[index]; - array[index] = array[end]; - return value; - }, Math.min(end, count)); - } - }; - - Chance.prototype.shuffle = function (arr) { - var new_array = [], - j = 0, - length = Number(arr.length), - source_indexes = range(length), - last_source_index = length - 1, - selected_source_index; - - for (var i = 0; i < length; i++) { - // Pick a random index from the array - selected_source_index = this.natural({max: last_source_index}); - j = source_indexes[selected_source_index]; - - // Add it to the new array - new_array[i] = arr[j]; - - // Mark the source index as used - source_indexes[selected_source_index] = source_indexes[last_source_index]; - last_source_index -= 1; - } - - return new_array; - }; - - // Returns a single item from an array with relative weighting of odds - Chance.prototype.weighted = function (arr, weights, trim) { - if (arr.length !== weights.length) { - throw new RangeError("Chance: Length of array and weights must match"); - } - - // scan weights array and sum valid entries - var sum = 0; - var val; - for (var weightIndex = 0; weightIndex < weights.length; ++weightIndex) { - val = weights[weightIndex]; - if (isNaN(val)) { - throw new RangeError("Chance: All weights must be numbers"); - } - - if (val > 0) { - sum += val; - } - } - - if (sum === 0) { - throw new RangeError("Chance: No valid entries in array weights"); - } - - // select a value within range - var selected = this.random() * sum; - - // find array entry corresponding to selected value - var total = 0; - var lastGoodIdx = -1; - var chosenIdx; - for (weightIndex = 0; weightIndex < weights.length; ++weightIndex) { - val = weights[weightIndex]; - total += val; - if (val > 0) { - if (selected <= total) { - chosenIdx = weightIndex; - break; - } - lastGoodIdx = weightIndex; - } - - // handle any possible rounding error comparison to ensure something is picked - if (weightIndex === (weights.length - 1)) { - chosenIdx = lastGoodIdx; - } - } - - var chosen = arr[chosenIdx]; - trim = (typeof trim === 'undefined') ? false : trim; - if (trim) { - arr.splice(chosenIdx, 1); - weights.splice(chosenIdx, 1); - } - - return chosen; - }; - - // -- End Helpers -- - - // -- Text -- - - Chance.prototype.paragraph = function (options) { - options = initOptions(options); - - var sentences = options.sentences || this.natural({min: 3, max: 7}), - sentence_array = this.n(this.sentence, sentences), - separator = options.linebreak === true ? '\n' : ' '; - - return sentence_array.join(separator); - }; - - // Could get smarter about this than generating random words and - // chaining them together. Such as: http://vq.io/1a5ceOh - Chance.prototype.sentence = function (options) { - options = initOptions(options); - - var words = options.words || this.natural({min: 12, max: 18}), - punctuation = options.punctuation, - text, word_array = this.n(this.word, words); - - text = word_array.join(' '); - - // Capitalize first letter of sentence - text = this.capitalize(text); - - // Make sure punctuation has a usable value - if (punctuation !== false && !/^[.?;!:]$/.test(punctuation)) { - punctuation = '.'; - } - - // Add punctuation mark - if (punctuation) { - text += punctuation; - } - - return text; - }; - - Chance.prototype.syllable = function (options) { - options = initOptions(options); - - var length = options.length || this.natural({min: 2, max: 3}), - consonants = 'bcdfghjklmnprstvwz', // consonants except hard to speak ones - vowels = 'aeiou', // vowels - all = consonants + vowels, // all - text = '', - chr; - - // I'm sure there's a more elegant way to do this, but this works - // decently well. - for (var i = 0; i < length; i++) { - if (i === 0) { - // First character can be anything - chr = this.character({pool: all}); - } else if (consonants.indexOf(chr) === -1) { - // Last character was a vowel, now we want a consonant - chr = this.character({pool: consonants}); - } else { - // Last character was a consonant, now we want a vowel - chr = this.character({pool: vowels}); - } - - text += chr; - } - - if (options.capitalize) { - text = this.capitalize(text); - } - - return text; - }; - - Chance.prototype.word = function (options) { - options = initOptions(options); - - testRange( - options.syllables && options.length, - "Chance: Cannot specify both syllables AND length." - ); - - var syllables = options.syllables || this.natural({min: 1, max: 3}), - text = ''; - - if (options.length) { - // Either bound word by length - do { - text += this.syllable(); - } while (text.length < options.length); - text = text.substring(0, options.length); - } else { - // Or by number of syllables - for (var i = 0; i < syllables; i++) { - text += this.syllable(); - } - } - - if (options.capitalize) { - text = this.capitalize(text); - } - - return text; - }; - - Chance.prototype.emoji = function (options) { - options = initOptions(options, { category: "all", length: 1 }); - - testRange( - options.length < 1 || BigInt(options.length) > BigInt(MAX_INT), - "Chance: length must be between 1 and " + String(MAX_INT) - ); - - var emojis = this.get("emojis"); - - if (options.category === "all") { - options.category = this.pickone(Object.keys(emojis)); - } - - var emojisForCategory = emojis[options.category]; - - testRange( - emojisForCategory === undefined, - "Chance: Unrecognised emoji category: [" + options.category + "]." - ); - - return this.pickset(emojisForCategory, options.length) - .map(function (codePoint) { - return String.fromCodePoint(codePoint); - }).join(""); - }; - - // -- End Text -- - - // -- Person -- - - Chance.prototype.age = function (options) { - options = initOptions(options); - var ageRange; - - switch (options.type) { - case 'child': - ageRange = {min: 0, max: 12}; - break; - case 'teen': - ageRange = {min: 13, max: 19}; - break; - case 'adult': - ageRange = {min: 18, max: 65}; - break; - case 'senior': - ageRange = {min: 65, max: 100}; - break; - case 'all': - ageRange = {min: 0, max: 100}; - break; - default: - ageRange = {min: 18, max: 65}; - break; - } - - return this.natural(ageRange); - }; - - Chance.prototype.birthday = function (options) { - var age = this.age(options); - var now = new Date() - var currentYear = now.getFullYear(); - - if (options && options.type) { - var min = new Date(); - var max = new Date(); - min.setFullYear(currentYear - age - 1); - max.setFullYear(currentYear - age); - - options = initOptions(options, { - min: min, - max: max - }); - } else if (options && ((options.minAge !== undefined) || (options.maxAge !== undefined))) { - testRange(options.minAge < 0, "Chance: MinAge cannot be less than zero."); - testRange(options.minAge > options.maxAge, "Chance: MinAge cannot be greater than MaxAge."); - - var minAge = options.minAge !== undefined ? options.minAge : 0; - var maxAge = options.maxAge !== undefined ? options.maxAge : 100; - - var minDate = new Date(currentYear - maxAge - 1, now.getMonth(), now.getDate()); - var maxDate = new Date(currentYear - minAge, now.getMonth(), now.getDate()); - - minDate.setDate(minDate.getDate() +1); - - maxDate.setDate(maxDate.getDate() +1); - maxDate.setMilliseconds(maxDate.getMilliseconds() -1); - - options = initOptions(options, { - min: minDate, - max: maxDate - }); - } else { - options = initOptions(options, { - year: currentYear - age - }); - } - - return this.date(options); - }; - - // CPF; ID to identify taxpayers in Brazil - Chance.prototype.cpf = function (options) { - options = initOptions(options, { - formatted: true - }); - - var n = this.n(this.natural, 9, { max: 9 }); - var d1 = n[8]*2+n[7]*3+n[6]*4+n[5]*5+n[4]*6+n[3]*7+n[2]*8+n[1]*9+n[0]*10; - d1 = 11 - (d1 % 11); - if (d1>=10) { - d1 = 0; - } - var d2 = d1*2+n[8]*3+n[7]*4+n[6]*5+n[5]*6+n[4]*7+n[3]*8+n[2]*9+n[1]*10+n[0]*11; - d2 = 11 - (d2 % 11); - if (d2>=10) { - d2 = 0; - } - var cpf = ''+n[0]+n[1]+n[2]+'.'+n[3]+n[4]+n[5]+'.'+n[6]+n[7]+n[8]+'-'+d1+d2; - return options.formatted ? cpf : cpf.replace(/\D/g,''); - }; - - // CNPJ: ID to identify companies in Brazil - Chance.prototype.cnpj = function (options) { - options = initOptions(options, { - formatted: true - }); - - var n = this.n(this.natural, 12, { max: 12 }); - var d1 = n[11]*2+n[10]*3+n[9]*4+n[8]*5+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; - d1 = 11 - (d1 % 11); - if (d1<2) { - d1 = 0; - } - var d2 = d1*2+n[11]*3+n[10]*4+n[9]*5+n[8]*6+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; - d2 = 11 - (d2 % 11); - if (d2<2) { - d2 = 0; - } - var cnpj = ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/'+n[8]+n[9]+n[10]+n[11]+'-'+d1+d2; - return options.formatted ? cnpj : cnpj.replace(/\D/g,''); - }; - - Chance.prototype.first = function (options) { - options = initOptions(options, {gender: this.gender(), nationality: 'en'}); - return this.pick(this.get("firstNames")[options.gender.toLowerCase()][options.nationality.toLowerCase()]); - }; - - Chance.prototype.profession = function (options) { - options = initOptions(options); - if(options.rank){ - return this.pick(['Apprentice ', 'Junior ', 'Senior ', 'Lead ']) + this.pick(this.get("profession")); - } else{ - return this.pick(this.get("profession")); - } - }; - - Chance.prototype.company = function (){ - return this.pick(this.get("company")); - }; - - Chance.prototype.gender = function (options) { - options = initOptions(options, {extraGenders: []}); - return this.pick(['Male', 'Female'].concat(options.extraGenders)); - }; - - Chance.prototype.last = function (options) { - options = initOptions(options, {nationality: '*'}); - if (options.nationality === "*") { - var allLastNames = [] - var lastNames = this.get("lastNames") - Object.keys(lastNames).forEach(function(key){ - allLastNames = allLastNames.concat(lastNames[key]) - }) - return this.pick(allLastNames) - } - else { - return this.pick(this.get("lastNames")[options.nationality.toLowerCase()]); - } - - }; - - Chance.prototype.israelId=function(){ - var x=this.string({pool: '0123456789',length:8}); - var y=0; - for (var i=0;i hex - * -> rgb - * -> rgba - * -> 0x - * -> named color - * - * #Examples: - * =============================================== - * * Geerate random hex color - * chance.color() => '#79c157' / 'rgb(110,52,164)' / '0x67ae0b' / '#e2e2e2' / '#29CFA7' - * - * * Generate Hex based color value - * chance.color({format: 'hex'}) => '#d67118' - * - * * Generate simple rgb value - * chance.color({format: 'rgb'}) => 'rgb(110,52,164)' - * - * * Generate Ox based color value - * chance.color({format: '0x'}) => '0x67ae0b' - * - * * Generate graiscale based value - * chance.color({grayscale: true}) => '#e2e2e2' - * - * * Return valide color name - * chance.color({format: 'name'}) => 'red' - * - * * Make color uppercase - * chance.color({casing: 'upper'}) => '#29CFA7' - * - * * Min Max values for RGBA - * var light_red = chance.color({format: 'hex', min_red: 200, max_red: 255, max_green: 0, max_blue: 0, min_alpha: .2, max_alpha: .3}); - * - * @param [object] options - * @return [string] color value - */ - Chance.prototype.color = function (options) { - function gray(value, delimiter) { - return [value, value, value].join(delimiter || ''); - } - - function rgb(hasAlpha) { - var rgbValue = (hasAlpha) ? 'rgba' : 'rgb'; - var alphaChannel = (hasAlpha) ? (',' + this.floating({min:min_alpha, max:max_alpha})) : ""; - var colorValue = (isGrayscale) ? (gray(this.natural({min: min_rgb, max: max_rgb}), ',')) : (this.natural({min: min_green, max: max_green}) + ',' + this.natural({min: min_blue, max: max_blue}) + ',' + this.natural({max: 255})); - return rgbValue + '(' + colorValue + alphaChannel + ')'; - } - - function hex(start, end, withHash) { - var symbol = (withHash) ? "#" : ""; - var hexstring = ""; - - if (isGrayscale) { - hexstring = gray(this.pad(this.hex({min: min_rgb, max: max_rgb}), 2)); - if (options.format === "shorthex") { - hexstring = gray(this.hex({min: 0, max: 15})); - } - } - else { - if (options.format === "shorthex") { - hexstring = this.pad(this.hex({min: Math.floor(min_red / 16), max: Math.floor(max_red / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_green / 16), max: Math.floor(max_green / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_blue / 16), max: Math.floor(max_blue / 16)}), 1); - } - else if (min_red !== undefined || max_red !== undefined || min_green !== undefined || max_green !== undefined || min_blue !== undefined || max_blue !== undefined) { - hexstring = this.pad(this.hex({min: min_red, max: max_red}), 2) + this.pad(this.hex({min: min_green, max: max_green}), 2) + this.pad(this.hex({min: min_blue, max: max_blue}), 2); - } - else { - hexstring = this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2); - } - } - - return symbol + hexstring; - } - - options = initOptions(options, { - format: this.pick(['hex', 'shorthex', 'rgb', 'rgba', '0x', 'name']), - grayscale: false, - casing: 'lower', - min: 0, - max: 255, - min_red: undefined, - max_red: undefined, - min_green: undefined, - max_green: undefined, - min_blue: undefined, - max_blue: undefined, - min_alpha: 0, - max_alpha: 1 - }); - - var isGrayscale = options.grayscale; - var min_rgb = options.min; - var max_rgb = options.max; - var min_red = options.min_red; - var max_red = options.max_red; - var min_green = options.min_green; - var max_green = options.max_green; - var min_blue = options.min_blue; - var max_blue = options.max_blue; - var min_alpha = options.min_alpha; - var max_alpha = options.max_alpha; - if (options.min_red === undefined) { min_red = min_rgb; } - if (options.max_red === undefined) { max_red = max_rgb; } - if (options.min_green === undefined) { min_green = min_rgb; } - if (options.max_green === undefined) { max_green = max_rgb; } - if (options.min_blue === undefined) { min_blue = min_rgb; } - if (options.max_blue === undefined) { max_blue = max_rgb; } - if (options.min_alpha === undefined) { min_alpha = 0; } - if (options.max_alpha === undefined) { max_alpha = 1; } - if (isGrayscale && min_rgb === 0 && max_rgb === 255 && min_red !== undefined && max_red !== undefined) { - min_rgb = ((min_red + min_green + min_blue) / 3); - max_rgb = ((max_red + max_green + max_blue) / 3); - } - var colorValue; - - if (options.format === 'hex') { - colorValue = hex.call(this, 2, 6, true); - } - else if (options.format === 'shorthex') { - colorValue = hex.call(this, 1, 3, true); - } - else if (options.format === 'rgb') { - colorValue = rgb.call(this, false); - } - else if (options.format === 'rgba') { - colorValue = rgb.call(this, true); - } - else if (options.format === '0x') { - colorValue = '0x' + hex.call(this, 2, 6); - } - else if(options.format === 'name') { - return this.pick(this.get("colorNames")); - } - else { - throw new RangeError('Invalid format provided. Please provide one of "hex", "shorthex", "rgb", "rgba", "0x" or "name".'); - } - - if (options.casing === 'upper' ) { - colorValue = colorValue.toUpperCase(); - } - - return colorValue; - }; - - Chance.prototype.domain = function (options) { - options = initOptions(options); - return this.word() + '.' + (options.tld || this.tld()); - }; - - Chance.prototype.email = function (options) { - options = initOptions(options); - return this.word({length: options.length}) + '@' + (options.domain || this.domain()); - }; - - /** - * #Description: - * =============================================== - * Generate a random Facebook id, aka fbid. - * - * NOTE: At the moment (Sep 2017), Facebook ids are - * "numeric strings" of length 16. - * However, Facebook Graph API documentation states that - * "it is extremely likely to change over time". - * @see https://developers.facebook.com/docs/graph-api/overview/ - * - * #Examples: - * =============================================== - * chance.fbid() => '1000035231661304' - * - * @return [string] facebook id - */ - Chance.prototype.fbid = function () { - return '10000' + this.string({pool: "1234567890", length: 11}); - }; - - Chance.prototype.google_analytics = function () { - var account = this.pad(this.natural({max: 999999}), 6); - var property = this.pad(this.natural({max: 99}), 2); - - return 'UA-' + account + '-' + property; - }; - - Chance.prototype.hashtag = function () { - return '#' + this.word(); - }; - - Chance.prototype.ip = function () { - // Todo: This could return some reserved IPs. See http://vq.io/137dgYy - // this should probably be updated to account for that rare as it may be - return this.natural({min: 1, max: 254}) + '.' + - this.natural({max: 255}) + '.' + - this.natural({max: 255}) + '.' + - this.natural({min: 1, max: 254}); - }; - - Chance.prototype.ipv6 = function () { - var ip_addr = this.n(this.hash, 8, {length: 4}); - - return ip_addr.join(":"); - }; - - Chance.prototype.klout = function () { - return this.natural({min: 1, max: 99}); - }; - - Chance.prototype.mac = function (options) { - // Todo: This could also be extended to EUI-64 based MACs - // (https://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml#ethernet-numbers-4) - // Todo: This can return some reserved MACs (similar to IP function) - // this should probably be updated to account for that rare as it may be - options = initOptions(options, { delimiter: ':' }); - return this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + - this.pad(this.natural({max: 255}).toString(16),2); - }; - - Chance.prototype.semver = function (options) { - options = initOptions(options, { include_prerelease: true }); - - var range = this.pickone(["^", "~", "<", ">", "<=", ">=", "="]); - if (options.range) { - range = options.range; - } - - var prerelease = ""; - if (options.include_prerelease) { - prerelease = this.weighted(["", "-dev", "-beta", "-alpha"], [50, 10, 5, 1]); - } - return range + this.rpg('3d10').join('.') + prerelease; - }; - - Chance.prototype.tlds = function () { - return ['com', 'org', 'edu', 'gov', 'co.uk', 'net', 'io', 'ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as', 'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bv', 'bw', 'by', 'bz', 'ca', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr', 'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'ee', 'eg', 'eh', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo', 'fr', 'ga', 'gb', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht', 'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je', 'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw', 'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv', 'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo', 'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om', 'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt', 'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sj', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st', 'su', 'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us', 'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye', 'yt', 'za', 'zm', 'zw']; - }; - - Chance.prototype.tld = function () { - return this.pick(this.tlds()); - }; - - Chance.prototype.twitter = function () { - return '@' + this.word(); - }; - - Chance.prototype.url = function (options) { - options = initOptions(options, { protocol: "http", domain: this.domain(options), domain_prefix: "", path: this.word(), extensions: []}); - - var extension = options.extensions.length > 0 ? "." + this.pick(options.extensions) : ""; - var domain = options.domain_prefix ? options.domain_prefix + "." + options.domain : options.domain; - - return options.protocol + "://" + domain + "/" + options.path + extension; - }; - - Chance.prototype.port = function() { - return this.integer({min: 0, max: 65535}); - }; - - Chance.prototype.locale = function (options) { - options = initOptions(options); - if (options.region){ - return this.pick(this.get("locale_regions")); - } else { - return this.pick(this.get("locale_languages")); - } - }; - - Chance.prototype.locales = function (options) { - options = initOptions(options); - if (options.region){ - return this.get("locale_regions"); - } else { - return this.get("locale_languages"); - } - }; - - Chance.prototype.loremPicsum = function (options) { - options = initOptions(options, { width: 500, height: 500, greyscale: false, blurred: false }); - - var greyscale = options.greyscale ? 'g/' : ''; - var query = options.blurred ? '/?blur' : '/?random'; - - return 'https://picsum.photos/' + greyscale + options.width + '/' + options.height + query; - } - - // -- End Web -- - - // -- Location -- - - Chance.prototype.address = function (options) { - options = initOptions(options); - return this.natural({min: 5, max: 2000}) + ' ' + this.street(options); - }; - - Chance.prototype.altitude = function (options) { - options = initOptions(options, {fixed: 5, min: 0, max: 8848}); - return this.floating({ - min: options.min, - max: options.max, - fixed: options.fixed - }); - }; - - Chance.prototype.areacode = function (options) { - options = initOptions(options, {parens : true}); - // Don't want area codes to start with 1, or have a 9 as the second digit - var areacode = options.exampleNumber ? - "555" : - this.natural({min: 2, max: 9}).toString() + - this.natural({min: 0, max: 8}).toString() + - this.natural({min: 0, max: 9}).toString(); - - return options.parens ? '(' + areacode + ')' : areacode; - }; - - Chance.prototype.city = function () { - return this.capitalize(this.word({syllables: 3})); - }; - - Chance.prototype.coordinates = function (options) { - return this.latitude(options) + ', ' + this.longitude(options); - }; - - Chance.prototype.countries = function () { - return this.get("countries"); - }; - - Chance.prototype.country = function (options) { - options = initOptions(options); - var country = this.pick(this.countries()); - return options.raw ? country : options.full ? country.name : country.abbreviation; - }; - - Chance.prototype.depth = function (options) { - options = initOptions(options, {fixed: 5, min: -10994, max: 0}); - return this.floating({ - min: options.min, - max: options.max, - fixed: options.fixed - }); - }; - - Chance.prototype.geohash = function (options) { - options = initOptions(options, { length: 7 }); - return this.string({ length: options.length, pool: '0123456789bcdefghjkmnpqrstuvwxyz' }); - }; - - Chance.prototype.geojson = function (options) { - return this.latitude(options) + ', ' + this.longitude(options) + ', ' + this.altitude(options); - }; - - Chance.prototype.latitude = function (options) { - // Constants - Formats - var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; - - options = initOptions( -options, - options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? - {min: 0, max: 89, fixed: 4} : - {fixed: 5, min: -90, max: 90, format: DD} -); - - var format = options.format.toLowerCase(); - - if (format === DDM || format === DMS) { - testRange(options.min < 0 || options.min > 89, "Chance: Min specified is out of range. Should be between 0 - 89"); - testRange(options.max < 0 || options.max > 89, "Chance: Max specified is out of range. Should be between 0 - 89"); - testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); - } - - switch (format) { - case DDM: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.floating({min: 0, max: 59, fixed: options.fixed}); - } - case DMS: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.integer({min: 0, max: 59}) + '’' + - this.floating({min: 0, max: 59, fixed: options.fixed}) + 'ā€'; - } - case DD: - default: { - return this.floating({min: options.min, max: options.max, fixed: options.fixed}); - } - } - }; - - Chance.prototype.longitude = function (options) { - // Constants - Formats - var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; - - options = initOptions( -options, - options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? - {min: 0, max: 179, fixed: 4} : - {fixed: 5, min: -180, max: 180, format: DD} -); - - var format = options.format.toLowerCase(); - - if (format === DDM || format === DMS) { - testRange(options.min < 0 || options.min > 179, "Chance: Min specified is out of range. Should be between 0 - 179"); - testRange(options.max < 0 || options.max > 179, "Chance: Max specified is out of range. Should be between 0 - 179"); - testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); - } - - switch (format) { - case DDM: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.floating({min: 0, max: 59.9999, fixed: options.fixed}) - } - case DMS: { - return this.integer({min: options.min, max: options.max}) + '°' + - this.integer({min: 0, max: 59}) + '’' + - this.floating({min: 0, max: 59.9999, fixed: options.fixed}) + 'ā€'; - } - case DD: - default: { - return this.floating({min: options.min, max: options.max, fixed: options.fixed}); - } - } - }; - - Chance.prototype.phone = function (options) { - var self = this, - numPick, - ukNum = function (parts) { - var section = []; - //fills the section part of the phone number with random numbers. - parts.sections.forEach(function(n) { - section.push(self.string({ pool: '0123456789', length: n})); - }); - return parts.area + section.join(' '); - }; - options = initOptions(options, { - formatted: true, - country: 'us', - mobile: false, - exampleNumber: false, - }); - if (!options.formatted) { - options.parens = false; - } - var phone; - switch (options.country) { - case 'fr': - if (!options.mobile) { - numPick = this.pick([ - // Valid zone and dĆ©partement codes. - '01' + this.pick(['30', '34', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '53', '55', '56', '58', '60', '64', '69', '70', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83']) + self.string({ pool: '0123456789', length: 6}), - '02' + this.pick(['14', '18', '22', '23', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '40', '41', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '56', '57', '61', '62', '69', '72', '76', '77', '78', '85', '90', '96', '97', '98', '99']) + self.string({ pool: '0123456789', length: 6}), - '03' + this.pick(['10', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '39', '44', '45', '51', '52', '54', '55', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90']) + self.string({ pool: '0123456789', length: 6}), - '04' + this.pick(['11', '13', '15', '20', '22', '26', '27', '30', '32', '34', '37', '42', '43', '44', '50', '56', '57', '63', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '88', '89', '90', '91', '92', '93', '94', '95', '97', '98']) + self.string({ pool: '0123456789', length: 6}), - '05' + this.pick(['08', '16', '17', '19', '24', '31', '32', '33', '34', '35', '40', '45', '46', '47', '49', '53', '55', '56', '57', '58', '59', '61', '62', '63', '64', '65', '67', '79', '81', '82', '86', '87', '90', '94']) + self.string({ pool: '0123456789', length: 6}), - '09' + self.string({ pool: '0123456789', length: 8}), - ]); - phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; - } else { - numPick = this.pick(['06', '07']) + self.string({ pool: '0123456789', length: 8}); - phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; - } - break; - case 'uk': - if (!options.mobile) { - numPick = this.pick([ - //valid area codes of major cities/counties followed by random numbers in required format. - - { area: '01' + this.character({ pool: '234569' }) + '1 ', sections: [3,4] }, - { area: '020 ' + this.character({ pool: '378' }), sections: [3,4] }, - { area: '023 ' + this.character({ pool: '89' }), sections: [3,4] }, - { area: '024 7', sections: [3,4] }, - { area: '028 ' + this.pick(['25','28','37','71','82','90','92','95']), sections: [2,4] }, - { area: '012' + this.pick(['04','08','54','76','97','98']) + ' ', sections: [6] }, - { area: '013' + this.pick(['63','64','84','86']) + ' ', sections: [6] }, - { area: '014' + this.pick(['04','20','60','61','80','88']) + ' ', sections: [6] }, - { area: '015' + this.pick(['24','27','62','66']) + ' ', sections: [6] }, - { area: '016' + this.pick(['06','29','35','47','59','95']) + ' ', sections: [6] }, - { area: '017' + this.pick(['26','44','50','68']) + ' ', sections: [6] }, - { area: '018' + this.pick(['27','37','84','97']) + ' ', sections: [6] }, - { area: '019' + this.pick(['00','05','35','46','49','63','95']) + ' ', sections: [6] } - ]); - phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', '', 'g'); - } else { - numPick = this.pick([ - { area: '07' + this.pick(['4','5','7','8','9']), sections: [2,6] }, - { area: '07624 ', sections: [6] } - ]); - phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', ''); - } - break; - case 'za': - if (!options.mobile) { - numPick = this.pick([ - '01' + this.pick(['0', '1', '2', '3', '4', '5', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), - '02' + this.pick(['1', '2', '3', '4', '7', '8']) + self.string({ pool: '0123456789', length: 7}), - '03' + this.pick(['1', '2', '3', '5', '6', '9']) + self.string({ pool: '0123456789', length: 7}), - '04' + this.pick(['1', '2', '3', '4', '5','6','7', '8','9']) + self.string({ pool: '0123456789', length: 7}), - '05' + this.pick(['1', '3', '4', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), - ]); - phone = options.formatted || numPick; - } else { - numPick = this.pick([ - '060' + this.pick(['3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), - '061' + this.pick(['0','1','2','3','4','5','8']) + self.string({ pool: '0123456789', length: 6}), - '06' + self.string({ pool: '0123456789', length: 7}), - '071' + this.pick(['0','1','2','3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), - '07' + this.pick(['2','3','4','6','7','8','9']) + self.string({ pool: '0123456789', length: 7}), - '08' + this.pick(['0','1','2','3','4','5']) + self.string({ pool: '0123456789', length: 7}), - ]); - phone = options.formatted || numPick; - } - break; - case 'us': - var areacode = this.areacode(options).toString(); - var exchange = this.natural({ min: 2, max: 9 }).toString() + - this.natural({ min: 0, max: 9 }).toString() + - this.natural({ min: 0, max: 9 }).toString(); - var subscriber = this.natural({ min: 1000, max: 9999 }).toString(); // this could be random [0-9]{4} - phone = options.formatted ? areacode + ' ' + exchange + '-' + subscriber : areacode + exchange + subscriber; - break; - case 'br': - var areaCode = this.pick(["11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "24", "27", "28", "31", "32", "33", "34", "35", "37", "38", "41", "42", "43", "44", "45", "46", "47", "48", "49", "51", "53", "54", "55", "61", "62", "63", "64", "65", "66", "67", "68", "69", "71", "73", "74", "75", "77", "79", "81", "82", "83", "84", "85", "86", "87", "88", "89", "91", "92", "93", "94", "95", "96", "97", "98", "99"]); - var prefix; - if (options.mobile) { - // Brasilian official reference (mobile): http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=330 - prefix = '9' + self.string({ pool: '0123456789', length: 4}); - } else { - // Brasilian official reference: http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=331 - prefix = this.natural({ min: 2000, max: 5999 }).toString(); - } - var mcdu = self.string({ pool: '0123456789', length: 4}); - phone = options.formatted ? '(' + areaCode + ') ' + prefix + '-' + mcdu : areaCode + prefix + mcdu; - break; - } - return phone; - }; - - Chance.prototype.postal = function () { - // Postal District - var pd = this.character({pool: "XVTSRPNKLMHJGECBA"}); - // Forward Sortation Area (FSA) - var fsa = pd + this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}); - // Local Delivery Unut (LDU) - var ldu = this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}) + this.natural({max: 9}); - - return fsa + " " + ldu; - }; - - Chance.prototype.postcode = function () { - // Area - var area = this.pick(this.get("postcodeAreas")).code; - // District - var district = this.natural({max: 9}); - // Sub-District - var subDistrict = this.bool() ? this.character({alpha: true, casing: "upper"}) : ""; - // Outward Code - var outward = area + district + subDistrict; - // Sector - var sector = this.natural({max: 9}); - // Unit - var unit = this.character({alpha: true, casing: "upper"}) + this.character({alpha: true, casing: "upper"}); - // Inward Code - var inward = sector + unit; - - return outward + " " + inward; - }; - - Chance.prototype.counties = function (options) { - options = initOptions(options, { country: 'uk' }); - return this.get("counties")[options.country.toLowerCase()]; - }; - - Chance.prototype.county = function (options) { - return this.pick(this.counties(options)).name; - }; - - Chance.prototype.provinces = function (options) { - options = initOptions(options, { country: 'ca' }); - return this.get("provinces")[options.country.toLowerCase()]; - }; - - Chance.prototype.province = function (options) { - return (options && options.full) ? - this.pick(this.provinces(options)).name : - this.pick(this.provinces(options)).abbreviation; - }; - - Chance.prototype.state = function (options) { - return (options && options.full) ? - this.pick(this.states(options)).name : - this.pick(this.states(options)).abbreviation; - }; - - Chance.prototype.states = function (options) { - options = initOptions(options, { country: 'us', us_states_and_dc: true } ); - - var states; - - switch (options.country.toLowerCase()) { - case 'us': - var us_states_and_dc = this.get("us_states_and_dc"), - territories = this.get("territories"), - armed_forces = this.get("armed_forces"); - - states = []; - - if (options.us_states_and_dc) { - states = states.concat(us_states_and_dc); - } - if (options.territories) { - states = states.concat(territories); - } - if (options.armed_forces) { - states = states.concat(armed_forces); - } - break; - case 'it': - case 'mx': - states = this.get("country_regions")[options.country.toLowerCase()]; - break; - case 'uk': - states = this.get("counties")[options.country.toLowerCase()]; - break; - } - - return states; - }; - - Chance.prototype.street = function (options) { - options = initOptions(options, { country: 'us', syllables: 2 }); - var street; - - switch (options.country.toLowerCase()) { - case 'us': - street = this.word({ syllables: options.syllables }); - street = this.capitalize(street); - street += ' '; - street += options.short_suffix ? - this.street_suffix(options).abbreviation : - this.street_suffix(options).name; - break; - case 'it': - street = this.word({ syllables: options.syllables }); - street = this.capitalize(street); - street = (options.short_suffix ? - this.street_suffix(options).abbreviation : - this.street_suffix(options).name) + " " + street; - break; - } - return street; - }; - - Chance.prototype.street_suffix = function (options) { - options = initOptions(options, { country: 'us' }); - return this.pick(this.street_suffixes(options)); - }; - - Chance.prototype.street_suffixes = function (options) { - options = initOptions(options, { country: 'us' }); - // These are the most common suffixes. - return this.get("street_suffixes")[options.country.toLowerCase()]; - }; - - // Note: only returning US zip codes, internationalization will be a whole - // other beast to tackle at some point. - Chance.prototype.zip = function (options) { - var zip = this.n(this.natural, 5, {max: 9}); - - if (options && options.plusfour === true) { - zip.push('-'); - zip = zip.concat(this.n(this.natural, 4, {max: 9})); - } - - return zip.join(""); - }; - - // -- End Location -- - - // -- Time - - Chance.prototype.ampm = function () { - return this.bool() ? 'am' : 'pm'; - }; - - Chance.prototype.date = function (options) { - var date_string, date; - - // If interval is specified we ignore preset - if(options && (options.min || options.max)) { - options = initOptions(options, { - american: true, - string: false - }); - var min = typeof options.min !== "undefined" ? options.min.getTime() : 1; - // 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. http://es5.github.io/#x15.9.1.1 - var max = typeof options.max !== "undefined" ? options.max.getTime() : 8640000000000000; - - date = new Date(this.integer({min: min, max: max})); - } else { - var m = this.month({raw: true}); - var daysInMonth = m.days; - - if(options && options.month) { - // Mod 12 to allow months outside range of 0-11 (not encouraged, but also not prevented). - daysInMonth = this.get('months')[((options.month % 12) + 12) % 12].days; - } - - options = initOptions(options, { - year: parseInt(this.year(), 10), - // Necessary to subtract 1 because Date() 0-indexes month but not day or year - // for some reason. - month: m.numeric - 1, - day: this.natural({min: 1, max: daysInMonth}), - hour: this.hour({twentyfour: true}), - minute: this.minute(), - second: this.second(), - millisecond: this.millisecond(), - american: true, - string: false - }); - - date = new Date(options.year, options.month, options.day, options.hour, options.minute, options.second, options.millisecond); - } - - if (options.american) { - // Adding 1 to the month is necessary because Date() 0-indexes - // months but not day for some odd reason. - date_string = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); - } else { - date_string = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); - } - - return options.string ? date_string : date; - }; - - Chance.prototype.hammertime = function (options) { - return this.date(options).getTime(); - }; - - Chance.prototype.hour = function (options) { - options = initOptions(options, { - min: options && options.twentyfour ? 0 : 1, - max: options && options.twentyfour ? 23 : 12 - }); - - testRange(options.min < 0, "Chance: Min cannot be less than 0."); - testRange(options.twentyfour && options.max > 23, "Chance: Max cannot be greater than 23 for twentyfour option."); - testRange(!options.twentyfour && options.max > 12, "Chance: Max cannot be greater than 12."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - return this.natural({min: options.min, max: options.max}); - }; - - Chance.prototype.millisecond = function () { - return this.natural({max: 999}); - }; - - Chance.prototype.minute = Chance.prototype.second = function (options) { - options = initOptions(options, {min: 0, max: 59}); - - testRange(options.min < 0, "Chance: Min cannot be less than 0."); - testRange(options.max > 59, "Chance: Max cannot be greater than 59."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - return this.natural({min: options.min, max: options.max}); - }; - - Chance.prototype.month = function (options) { - options = initOptions(options, {min: 1, max: 12}); - - testRange(options.min < 1, "Chance: Min cannot be less than 1."); - testRange(options.max > 12, "Chance: Max cannot be greater than 12."); - testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - - var month = this.pick(this.months().slice(options.min - 1, options.max)); - return options.raw ? month : month.name; - }; - - Chance.prototype.months = function () { - return this.get("months"); - }; - - Chance.prototype.second = function () { - return this.natural({max: 59}); - }; - - Chance.prototype.timestamp = function () { - return this.natural({min: 1, max: parseInt(new Date().getTime() / 1000, 10)}); - }; - - Chance.prototype.weekday = function (options) { - options = initOptions(options, {weekday_only: false}); - var weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; - if (!options.weekday_only) { - weekdays.push("Saturday"); - weekdays.push("Sunday"); - } - return this.pickone(weekdays); - }; - - Chance.prototype.year = function (options) { - // Default to current year as min if none specified - options = initOptions(options, {min: new Date().getFullYear()}); - - // Default to one century after current year as max if none specified - options.max = (typeof options.max !== "undefined") ? options.max : options.min + 100; - - return this.natural(options).toString(); - }; - - // -- End Time - - // -- Finance -- - - Chance.prototype.cc = function (options) { - options = initOptions(options); - - var type, number, to_generate; - - type = (options.type) ? - this.cc_type({ name: options.type, raw: true }) : - this.cc_type({ raw: true }); - - number = type.prefix.split(""); - to_generate = type.length - type.prefix.length - 1; - - // Generates n - 1 digits - number = number.concat(this.n(this.integer, to_generate, {min: 0, max: 9})); - - // Generates the last digit according to Luhn algorithm - number.push(this.luhn_calculate(number.join(""))); - - return number.join(""); - }; - - Chance.prototype.cc_types = function () { - // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 - return this.get("cc_types"); - }; - - Chance.prototype.cc_type = function (options) { - options = initOptions(options); - var types = this.cc_types(), - type = null; - - if (options.name) { - for (var i = 0; i < types.length; i++) { - // Accept either name or short_name to specify card type - if (types[i].name === options.name || types[i].short_name === options.name) { - type = types[i]; - break; - } - } - if (type === null) { - throw new RangeError("Chance: Credit card type '" + options.name + "' is not supported"); - } - } else { - type = this.pick(types); - } - - return options.raw ? type : type.name; - }; - - // return all world currency by ISO 4217 - Chance.prototype.currency_types = function () { - return this.get("currency_types"); - }; - - // return random world currency by ISO 4217 - Chance.prototype.currency = function () { - return this.pick(this.currency_types()); - }; - - // return all timezones available - Chance.prototype.timezones = function () { - return this.get("timezones"); - }; - - // return random timezone - Chance.prototype.timezone = function () { - return this.pick(this.timezones()); - }; - - //Return random correct currency exchange pair (e.g. EUR/USD) or array of currency code - Chance.prototype.currency_pair = function (returnAsString) { - var currencies = this.unique(this.currency, 2, { - comparator: function(arr, val) { - - return arr.reduce(function(acc, item) { - // If a match has been found, short circuit check and just return - return acc || (item.code === val.code); - }, false); - } - }); - - if (returnAsString) { - return currencies[0].code + '/' + currencies[1].code; - } else { - return currencies; - } - }; - - Chance.prototype.dollar = function (options) { - // By default, a somewhat more sane max for dollar than all available numbers - options = initOptions(options, {max : 10000, min : 0}); - - var dollar = this.floating({min: options.min, max: options.max, fixed: 2}).toString(), - cents = dollar.split('.')[1]; - - if (cents === undefined) { - dollar += '.00'; - } else if (cents.length < 2) { - dollar = dollar + '0'; - } - - if (dollar < 0) { - return '-$' + dollar.replace('-', ''); - } else { - return '$' + dollar; - } - }; - - Chance.prototype.euro = function (options) { - return Number(this.dollar(options).replace("$", "")).toLocaleString() + "€"; - }; - - Chance.prototype.exp = function (options) { - options = initOptions(options); - var exp = {}; - - exp.year = this.exp_year(); - - // If the year is this year, need to ensure month is greater than the - // current month or this expiration will not be valid - if (exp.year === (new Date().getFullYear()).toString()) { - exp.month = this.exp_month({future: true}); - } else { - exp.month = this.exp_month(); - } - - return options.raw ? exp : exp.month + '/' + exp.year; - }; - - Chance.prototype.exp_month = function (options) { - options = initOptions(options); - var month, month_int, - // Date object months are 0 indexed - curMonth = new Date().getMonth() + 1; - - if (options.future && (curMonth !== 12)) { - do { - month = this.month({raw: true}).numeric; - month_int = parseInt(month, 10); - } while (month_int <= curMonth); - } else { - month = this.month({raw: true}).numeric; - } - - return month; - }; - - Chance.prototype.exp_year = function () { - var curMonth = new Date().getMonth() + 1, - curYear = new Date().getFullYear(); - - return this.year({min: ((curMonth === 12) ? (curYear + 1) : curYear), max: (curYear + 10)}); - }; - - Chance.prototype.vat = function (options) { - options = initOptions(options, { country: 'it' }); - switch (options.country.toLowerCase()) { - case 'it': - return this.it_vat(); - } - }; - - /** - * Generate a string matching IBAN pattern (https://en.wikipedia.org/wiki/International_Bank_Account_Number). - * No country-specific formats support (yet) - */ - Chance.prototype.iban = function () { - var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - var alphanum = alpha + '0123456789'; - var iban = - this.string({ length: 2, pool: alpha }) + - this.pad(this.integer({ min: 0, max: 99 }), 2) + - this.string({ length: 4, pool: alphanum }) + - this.pad(this.natural(), this.natural({ min: 6, max: 26 })); - return iban; - }; - - // -- End Finance - - // -- Regional - - Chance.prototype.it_vat = function () { - var it_vat = this.natural({min: 1, max: 1800000}); - - it_vat = this.pad(it_vat, 7) + this.pad(this.pick(this.provinces({ country: 'it' })).code, 3); - return it_vat + this.luhn_calculate(it_vat); - }; - - /* - * this generator is written following the official algorithm - * all data can be passed explicitely or randomized by calling chance.cf() without options - * the code does not check that the input data is valid (it goes beyond the scope of the generator) - * - * @param [Object] options = { first: first name, - * last: last name, - * gender: female|male, - birthday: JavaScript date object, - city: string(4), 1 letter + 3 numbers - } - * @return [string] codice fiscale - * - */ - Chance.prototype.cf = function (options) { - options = options || {}; - var gender = !!options.gender ? options.gender : this.gender(), - first = !!options.first ? options.first : this.first( { gender: gender, nationality: 'it'} ), - last = !!options.last ? options.last : this.last( { nationality: 'it'} ), - birthday = !!options.birthday ? options.birthday : this.birthday(), - city = !!options.city ? options.city : this.pickone(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L', 'M', 'Z']) + this.pad(this.natural({max:999}), 3), - cf = [], - name_generator = function(name, isLast) { - var temp, - return_value = []; - - if (name.length < 3) { - return_value = name.split("").concat("XXX".split("")).splice(0,3); - } - else { - temp = name.toUpperCase().split('').map(function(c){ - return ("BCDFGHJKLMNPRSTVWZ".indexOf(c) !== -1) ? c : undefined; - }).join(''); - if (temp.length > 3) { - if (isLast) { - temp = temp.substr(0,3); - } else { - temp = temp[0] + temp.substr(2,2); - } - } - if (temp.length < 3) { - return_value = temp; - temp = name.toUpperCase().split('').map(function(c){ - return ("AEIOU".indexOf(c) !== -1) ? c : undefined; - }).join('').substr(0, 3 - return_value.length); - } - return_value = return_value + temp; - } - - return return_value; - }, - date_generator = function(birthday, gender, that) { - var lettermonths = ['A', 'B', 'C', 'D', 'E', 'H', 'L', 'M', 'P', 'R', 'S', 'T']; - - return birthday.getFullYear().toString().substr(2) + - lettermonths[birthday.getMonth()] + - that.pad(birthday.getDate() + ((gender.toLowerCase() === "female") ? 40 : 0), 2); - }, - checkdigit_generator = function(cf) { - var range1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", - range2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ", - evens = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - odds = "BAKPLCQDREVOSFTGUHMINJWZYX", - digit = 0; - - - for(var i = 0; i < 15; i++) { - if (i % 2 !== 0) { - digit += evens.indexOf(range2[range1.indexOf(cf[i])]); - } - else { - digit += odds.indexOf(range2[range1.indexOf(cf[i])]); - } - } - return evens[digit % 26]; - }; - - cf = cf.concat(name_generator(last, true), name_generator(first), date_generator(birthday, gender, this), city.toUpperCase().split("")).join(""); - cf += checkdigit_generator(cf.toUpperCase(), this); - - return cf.toUpperCase(); - }; - - Chance.prototype.pl_pesel = function () { - var number = this.natural({min: 1, max: 9999999999}); - var arr = this.pad(number, 10).split(''); - for (var i = 0; i < arr.length; i++) { - arr[i] = parseInt(arr[i]); - } - - var controlNumber = (1 * arr[0] + 3 * arr[1] + 7 * arr[2] + 9 * arr[3] + 1 * arr[4] + 3 * arr[5] + 7 * arr[6] + 9 * arr[7] + 1 * arr[8] + 3 * arr[9]) % 10; - if(controlNumber !== 0) { - controlNumber = 10 - controlNumber; - } - - return arr.join('') + controlNumber; - }; - - Chance.prototype.pl_nip = function () { - var number = this.natural({min: 1, max: 999999999}); - var arr = this.pad(number, 9).split(''); - for (var i = 0; i < arr.length; i++) { - arr[i] = parseInt(arr[i]); - } - - var controlNumber = (6 * arr[0] + 5 * arr[1] + 7 * arr[2] + 2 * arr[3] + 3 * arr[4] + 4 * arr[5] + 5 * arr[6] + 6 * arr[7] + 7 * arr[8]) % 11; - if(controlNumber === 10) { - return this.pl_nip(); - } - - return arr.join('') + controlNumber; - }; - - Chance.prototype.pl_regon = function () { - var number = this.natural({min: 1, max: 99999999}); - var arr = this.pad(number, 8).split(''); - for (var i = 0; i < arr.length; i++) { - arr[i] = parseInt(arr[i]); - } - - var controlNumber = (8 * arr[0] + 9 * arr[1] + 2 * arr[2] + 3 * arr[3] + 4 * arr[4] + 5 * arr[5] + 6 * arr[6] + 7 * arr[7]) % 11; - if(controlNumber === 10) { - controlNumber = 0; - } - - return arr.join('') + controlNumber; - }; - - // -- End Regional - - // -- Music -- - - // Genre choices: - // Rock,Pop,Hip-Hop,Jazz,Classical,Electronic,Country,R&B,Reggae, - // Blues,Metal,Folk,Alternative,Punk,Disco,Funk,Techno, - // Indie,Gospel,Dance,Children's,World - - Chance.prototype.music_genre = function (genre = 'general') { - if (!(genre.toLowerCase() in data.music_genres)) { - throw new Error(`Unsupported genre: ${genre}`); - } - - const genres = data.music_genres[genre.toLowerCase()]; - const randomIndex = this.integer({ min: 0, max: genres.length - 1 }); - - return genres[randomIndex]; - }; - - Chance.prototype.note = function(options) { - // choices for 'notes' option: - // flatKey - chromatic scale with flat notes (default) - // sharpKey - chromatic scale with sharp notes - // flats - just flat notes - // sharps - just sharp notes - // naturals - just natural notes - // all - naturals, sharps and flats - options = initOptions(options, { notes : 'flatKey'}); - var scales = { - naturals: ['C', 'D', 'E', 'F', 'G', 'A', 'B'], - flats: ['Dā™­', 'Eā™­', 'Gā™­', 'Aā™­', 'Bā™­'], - sharps: ['C♯', 'D♯', 'F♯', 'G♯', 'A♯'] - }; - scales.all = scales.naturals.concat(scales.flats.concat(scales.sharps)) - scales.flatKey = scales.naturals.concat(scales.flats) - scales.sharpKey = scales.naturals.concat(scales.sharps) - return this.pickone(scales[options.notes]); - } - - Chance.prototype.midi_note = function(options) { - var min = 0; - var max = 127; - options = initOptions(options, { min : min, max : max }); - return this.integer({min: options.min, max: options.max}); - } - - Chance.prototype.chord_quality = function(options) { - options = initOptions(options, { jazz: true }); - var chord_qualities = ['maj', 'min', 'aug', 'dim']; - if (options.jazz){ - chord_qualities = [ - 'maj7', - 'min7', - '7', - 'sus', - 'dim', - 'Ćø' - ]; - } - return this.pickone(chord_qualities); - } - - Chance.prototype.chord = function (options) { - options = initOptions(options); - return this.note(options) + this.chord_quality(options); - } - - Chance.prototype.tempo = function (options) { - var min = 40; - var max = 320; - options = initOptions(options, {min: min, max: max}); - return this.integer({min: options.min, max: options.max}); - } - - // -- End Music - - // -- Miscellaneous -- - - // Coin - Flip, flip, flipadelphia - Chance.prototype.coin = function() { - return this.bool() ? "heads" : "tails"; - } - - // Dice - For all the board game geeks out there, myself included ;) - function diceFn (range) { - return function () { - return this.natural(range); - }; - } - Chance.prototype.d4 = diceFn({min: 1, max: 4}); - Chance.prototype.d6 = diceFn({min: 1, max: 6}); - Chance.prototype.d8 = diceFn({min: 1, max: 8}); - Chance.prototype.d10 = diceFn({min: 1, max: 10}); - Chance.prototype.d12 = diceFn({min: 1, max: 12}); - Chance.prototype.d20 = diceFn({min: 1, max: 20}); - Chance.prototype.d30 = diceFn({min: 1, max: 30}); - Chance.prototype.d100 = diceFn({min: 1, max: 100}); - - Chance.prototype.rpg = function (thrown, options) { - options = initOptions(options); - if (!thrown) { - throw new RangeError("Chance: A type of die roll must be included"); - } else { - var bits = thrown.toLowerCase().split("d"), - rolls = []; - - if (bits.length !== 2 || !parseInt(bits[0], 10) || !parseInt(bits[1], 10)) { - throw new Error("Chance: Invalid format provided. Please provide #d# where the first # is the number of dice to roll, the second # is the max of each die"); - } - for (var i = bits[0]; i > 0; i--) { - rolls[i - 1] = this.natural({min: 1, max: bits[1]}); - } - return (typeof options.sum !== 'undefined' && options.sum) ? rolls.reduce(function (p, c) { return p + c; }) : rolls; - } - }; - - // Guid - Chance.prototype.guid = function (options) { - options = initOptions(options, { version: 5 }); - - var guid_pool = "abcdef1234567890", - variant_pool = "ab89", - guid = this.string({ pool: guid_pool, length: 8 }) + '-' + - this.string({ pool: guid_pool, length: 4 }) + '-' + - // The Version - options.version + - this.string({ pool: guid_pool, length: 3 }) + '-' + - // The Variant - this.string({ pool: variant_pool, length: 1 }) + - this.string({ pool: guid_pool, length: 3 }) + '-' + - this.string({ pool: guid_pool, length: 12 }); - return guid; - }; - - // Hash - Chance.prototype.hash = function (options) { - options = initOptions(options, {length : 40, casing: 'lower'}); - var pool = options.casing === 'upper' ? HEX_POOL.toUpperCase() : HEX_POOL; - return this.string({pool: pool, length: options.length}); - }; - - Chance.prototype.luhn_check = function (num) { - var str = num.toString(); - var checkDigit = +str.substring(str.length - 1); - return checkDigit === this.luhn_calculate(+str.substring(0, str.length - 1)); - }; - - Chance.prototype.luhn_calculate = function (num) { - var digits = num.toString().split("").reverse(); - var sum = 0; - var digit; - - for (var i = 0, l = digits.length; l > i; ++i) { - digit = +digits[i]; - if (i % 2 === 0) { - digit *= 2; - if (digit > 9) { - digit -= 9; - } - } - sum += digit; - } - return (sum * 9) % 10; - }; - - // MD5 Hash - Chance.prototype.md5 = function(options) { - var opts = { str: '', key: null, raw: false }; - - if (!options) { - opts.str = this.string(); - options = {}; - } - else if (typeof options === 'string') { - opts.str = options; - options = {}; - } - else if (typeof options !== 'object') { - return null; - } - else if(options.constructor === 'Array') { - return null; - } - - opts = initOptions(options, opts); - - if(!opts.str){ - throw new Error('A parameter is required to return an md5 hash.'); - } - - return this.bimd5.md5(opts.str, opts.key, opts.raw); - }; - - /** - * #Description: - * ===================================================== - * Generate random file name with extension - * - * The argument provide extension type - * -> raster - * -> vector - * -> 3d - * -> document - * - * If nothing is provided the function return random file name with random - * extension type of any kind - * - * The user can validate the file name length range - * If nothing provided the generated file name is random - * - * #Extension Pool : - * * Currently the supported extensions are - * -> some of the most popular raster image extensions - * -> some of the most popular vector image extensions - * -> some of the most popular 3d image extensions - * -> some of the most popular document extensions - * - * #Examples : - * ===================================================== - * - * Return random file name with random extension. The file extension - * is provided by a predefined collection of extensions. More about the extension - * pool can be found in #Extension Pool section - * - * chance.file() - * => dsfsdhjf.xml - * - * In order to generate a file name with specific length, specify the - * length property and integer value. The extension is going to be random - * - * chance.file({length : 10}) - * => asrtineqos.pdf - * - * In order to generate file with extension from some of the predefined groups - * of the extension pool just specify the extension pool category in fileType property - * - * chance.file({fileType : 'raster'}) - * => dshgssds.psd - * - * You can provide specific extension for your files - * chance.file({extension : 'html'}) - * => djfsd.html - * - * Or you could pass custom collection of extensions by array or by object - * chance.file({extensions : [...]}) - * => dhgsdsd.psd - * - * chance.file({extensions : { key : [...], key : [...]}}) - * => djsfksdjsd.xml - * - * @param [collection] options - * @return [string] - * - */ - Chance.prototype.file = function(options) { - - var fileOptions = options || {}; - var poolCollectionKey = "fileExtension"; - var typeRange = Object.keys(this.get("fileExtension"));//['raster', 'vector', '3d', 'document']; - var fileName; - var fileExtension; - - // Generate random file name - fileName = this.word({length : fileOptions.length}); - - // Generate file by specific extension provided by the user - if(fileOptions.extension) { - - fileExtension = fileOptions.extension; - return (fileName + '.' + fileExtension); - } - - // Generate file by specific extension collection - if(fileOptions.extensions) { - - if(Array.isArray(fileOptions.extensions)) { - - fileExtension = this.pickone(fileOptions.extensions); - return (fileName + '.' + fileExtension); - } - else if(fileOptions.extensions.constructor === Object) { - - var extensionObjectCollection = fileOptions.extensions; - var keys = Object.keys(extensionObjectCollection); - - fileExtension = this.pickone(extensionObjectCollection[this.pickone(keys)]); - return (fileName + '.' + fileExtension); - } - - throw new Error("Chance: Extensions must be an Array or Object"); - } - - // Generate file extension based on specific file type - if(fileOptions.fileType) { - - var fileType = fileOptions.fileType; - if(typeRange.indexOf(fileType) !== -1) { - - fileExtension = this.pickone(this.get(poolCollectionKey)[fileType]); - return (fileName + '.' + fileExtension); - } - - throw new RangeError("Chance: Expect file type value to be 'raster', 'vector', '3d' or 'document'"); - } - - // Generate random file name if no extension options are passed - fileExtension = this.pickone(this.get(poolCollectionKey)[this.pickone(typeRange)]); - return (fileName + '.' + fileExtension); - }; - - /** - * Generates file data of random bytes using the chance.file method for the file name - * - * @param {object} - * fileName: String - * fileExtention: String - * fileSize: Number <- in bytes - * @returns {object} fileName: String, fileData: Buffer - */ - Chance.prototype.fileWithContent = function (options){ - var fileOptions = options || {}; - var fileName = 'fileName' in fileOptions ? fileOptions.fileName : this.file().split(".")[0]; - fileName += "." + ('fileExtension' in fileOptions ? fileOptions.fileExtension : this.file().split(".")[1]); - - - if (typeof fileOptions.fileSize !== "number") { - throw new Error('File size must be an integer') - } - var file = { - fileData: this.buffer({length: fileOptions.fileSize}), - fileName: fileName, - }; - return file; - } - - var data = { - - firstNames: { - "male": { - "en": ["James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "George", "Donald", "Anthony", "Paul", "Mark", "Edward", "Steven", "Kenneth", "Andrew", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Frank", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Jonathan", "Scott", "Raymond", "Justin", "Brandon", "Gregory", "Samuel", "Benjamin", "Patrick", "Jack", "Henry", "Walter", "Dennis", "Jerry", "Alexander", "Peter", "Tyler", "Douglas", "Harold", "Aaron", "Jose", "Adam", "Arthur", "Zachary", "Carl", "Nathan", "Albert", "Kyle", "Lawrence", "Joe", "Willie", "Gerald", "Roger", "Keith", "Jeremy", "Terry", "Harry", "Ralph", "Sean", "Jesse", "Roy", "Louis", "Billy", "Austin", "Bruce", "Eugene", "Christian", "Bryan", "Wayne", "Russell", "Howard", "Fred", "Ethan", "Jordan", "Philip", "Alan", "Juan", "Randy", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Victor", "Clarence", "Ernest", "Martin", "Craig", "Stanley", "Shawn", "Travis", "Bradley", "Leonard", "Earl", "Gabriel", "Jimmy", "Francis", "Todd", "Noah", "Danny", "Dale", "Cody", "Carlos", "Allen", "Frederick", "Logan", "Curtis", "Alex", "Joel", "Luis", "Norman", "Marvin", "Glenn", "Tony", "Nathaniel", "Rodney", "Melvin", "Alfred", "Steve", "Cameron", "Chad", "Edwin", "Caleb", "Evan", "Antonio", "Lee", "Herbert", "Jeffery", "Isaac", "Derek", "Ricky", "Marcus", "Theodore", "Elijah", "Luke", "Jesus", "Eddie", "Troy", "Mike", "Dustin", "Ray", "Adrian", "Bernard", "Leroy", "Angel", "Randall", "Wesley", "Ian", "Jared", "Mason", "Hunter", "Calvin", "Oscar", "Clifford", "Jay", "Shane", "Ronnie", "Barry", "Lucas", "Corey", "Manuel", "Leo", "Tommy", "Warren", "Jackson", "Isaiah", "Connor", "Don", "Dean", "Jon", "Julian", "Miguel", "Bill", "Lloyd", "Charlie", "Mitchell", "Leon", "Jerome", "Darrell", "Jeremiah", "Alvin", "Brett", "Seth", "Floyd", "Jim", "Blake", "Micheal", "Gordon", "Trevor", "Lewis", "Erik", "Edgar", "Vernon", "Devin", "Gavin", "Jayden", "Chris", "Clyde", "Tom", "Derrick", "Mario", "Brent", "Marc", "Herman", "Chase", "Dominic", "Ricardo", "Franklin", "Maurice", "Max", "Aiden", "Owen", "Lester", "Gilbert", "Elmer", "Gene", "Francisco", "Glen", "Cory", "Garrett", "Clayton", "Sam", "Jorge", "Chester", "Alejandro", "Jeff", "Harvey", "Milton", "Cole", "Ivan", "Andre", "Duane", "Landon"], - // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0163 - "it": ["Adolfo", "Alberto", "Aldo", "Alessandro", "Alessio", "Alfredo", "Alvaro", "Andrea", "Angelo", "Angiolo", "Antonino", "Antonio", "Attilio", "Benito", "Bernardo", "Bruno", "Carlo", "Cesare", "Christian", "Claudio", "Corrado", "Cosimo", "Cristian", "Cristiano", "Daniele", "Dario", "David", "Davide", "Diego", "Dino", "Domenico", "Duccio", "Edoardo", "Elia", "Elio", "Emanuele", "Emiliano", "Emilio", "Enrico", "Enzo", "Ettore", "Fabio", "Fabrizio", "Federico", "Ferdinando", "Fernando", "Filippo", "Francesco", "Franco", "Gabriele", "Giacomo", "Giampaolo", "Giampiero", "Giancarlo", "Gianfranco", "Gianluca", "Gianmarco", "Gianni", "Gino", "Giorgio", "Giovanni", "Giuliano", "Giulio", "Giuseppe", "Graziano", "Gregorio", "Guido", "Iacopo", "Jacopo", "Lapo", "Leonardo", "Lorenzo", "Luca", "Luciano", "Luigi", "Manuel", "Marcello", "Marco", "Marino", "Mario", "Massimiliano", "Massimo", "Matteo", "Mattia", "Maurizio", "Mauro", "Michele", "Mirko", "Mohamed", "Nello", "Neri", "Niccolò", "Nicola", "Osvaldo", "Otello", "Paolo", "Pier Luigi", "Piero", "Pietro", "Raffaele", "Remo", "Renato", "Renzo", "Riccardo", "Roberto", "Rolando", "Romano", "Salvatore", "Samuele", "Sandro", "Sergio", "Silvano", "Simone", "Stefano", "Thomas", "Tommaso", "Ubaldo", "Ugo", "Umberto", "Valerio", "Valter", "Vasco", "Vincenzo", "Vittorio"], - // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html - "nl": ["Aaron","Abel","Adam","Adriaan","Albert","Alexander","Ali","Arjen","Arno","Bart","Bas","Bastiaan","Benjamin","Bob", "Boris","Bram","Brent","Cas","Casper","Chris","Christiaan","Cornelis","Daan","Daley","Damian","Dani","Daniel","DaniĆ«l","David","Dean","Dirk","Dylan","Egbert","Elijah","Erik","Erwin","Evert","Ezra","Fabian","Fedde","Finn","Florian","Floris","Frank","Frans","Frederik","Freek","Geert","Gerard","Gerben","Gerrit","Gijs","Guus","Hans","Hendrik","Henk","Herman","Hidde","Hugo","Jaap","Jan Jaap","Jan-Willem","Jack","Jacob","Jan","Jason","Jasper","Jayden","Jelle","Jelte","Jens","Jeroen","Jesse","Jim","Job","Joep","Johannes","John","Jonathan","Joris","Joshua","JoĆ«l","Julian","Kees","Kevin","Koen","Lars","Laurens","Leendert","Lennard","Lodewijk","Luc","Luca","Lucas","Lukas","Luuk","Maarten","Marcus","Martijn","Martin","Matthijs","Maurits","Max","Mees","Melle","Mick","Mika","Milan","Mohamed","Mohammed","Morris","Muhammed","Nathan","Nick","Nico","Niek","Niels","Noah","Noud","Olivier","Oscar","Owen","Paul","Pepijn","Peter","Pieter","Pim","Quinten","Reinier","Rens","Robin","Ruben","Sam","Samuel","Sander","Sebastiaan","Sem","Sep","Sepp","Siem","Simon","Stan","Stef","Steven","Stijn","Sven","Teun","Thijmen","Thijs","Thomas","Tijn","Tim","Timo","Tobias","Tom","Victor","Vince","Willem","Wim","Wouter","Yusuf"], - // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie - "fr": ["Aaron","Abdon","Abel","AbĆ©lard","Abelin","Abondance","Abraham","Absalon","Acace","Achaire","Achille","Adalard","Adalbald","AdalbĆ©ron","Adalbert","Adalric","Adam","Adegrin","Adel","Adelin","Andelin","Adelphe","Adam","AdĆ©odat","AdhĆ©mar","Adjutor","Adolphe","Adonis","Adon","Adrien","Agapet","Agathange","Agathon","Agilbert","AgĆ©nor","Agnan","Aignan","Agrippin","Aimable","AimĆ©","Alain","Alban","Albin","Aubin","AlbĆ©ric","Albert","Albertet","Alcibiade","Alcide","AlcĆ©e","Alcime","Aldonce","Aldric","AldĆ©ric","Aleaume","Alexandre","Alexis","Alix","Alliaume","Aleaume","Almine","Almire","AloĆÆs","AlphĆ©e","Alphonse","Alpinien","AlverĆØde","Amalric","Amaury","Amandin","Amant","Ambroise","AmĆ©dĆ©e","AmĆ©lien","Amiel","Amour","AnaĆ«l","Anastase","Anatole","Ancelin","AndĆ©ol","Andoche","AndrĆ©","Andoche","Ange","Angelin","Angilbe","Anglebert","Angoustan","Anicet","Anne","Annibal","Ansbert","Anselme","Anthelme","Antheaume","Anthime","Antide","Antoine","Antonius","Antonin","Apollinaire","Apollon","Aquilin","Arcade","Archambaud","Archambeau","Archange","Archibald","Arian","Ariel","Ariste","Aristide","Armand","Armel","Armin","Arnould","Arnaud","Arolde","ArsĆØne","ArsinoĆ©","Arthaud","ArthĆØme","Arthur","Ascelin","Athanase","Aubry","Audebert","Audouin","Audran","Audric","Auguste","Augustin","AurĆØle","AurĆ©lien","Aurian","Auxence","Axel","Aymard","Aymeric","Aymon","Aymond","Balthazar","Baptiste","BarnabĆ©","BarthĆ©lemy","BartimĆ©e","Basile","Bastien","Baudouin","BĆ©nigne","Benjamin","BenoĆ®t","BĆ©renger","BĆ©rard","Bernard","Bertrand","Blaise","Bon","Boniface","Bouchard","Brice","Brieuc","Bruno","Brunon","Calixte","Calliste","CamĆ©lien","Camille","Camillien","Candide","Caribert","Carloman","Cassandre","Cassien","CĆ©dric","CĆ©leste","CĆ©lestin","CĆ©lien","CĆ©saire","CĆ©sar","Charles","Charlemagne","Childebert","ChilpĆ©ric","ChrĆ©tien","Christian","Christodule","Christophe","Chrysostome","Clarence","Claude","Claudien","ClĆ©andre","ClĆ©ment","Clotaire","CĆ“me","Constance","Constant","Constantin","Corentin","Cyprien","Cyriaque","Cyrille","Cyril","Damien","Daniel","David","Delphin","Denis","DĆ©sirĆ©","Didier","DieudonnĆ©","Dimitri","Dominique","Dorian","DorothĆ©e","Edgard","Edmond","Ɖdouard","ƉleuthĆØre","Ɖlie","ƉlisĆ©e","Ɖmeric","Ɖmile","Ɖmilien","Emmanuel","Enguerrand","Ɖpiphane","Ɖric","Esprit","Ernest","Ɖtienne","Eubert","Eudes","Eudoxe","EugĆØne","EusĆØbe","Eustache","Ɖvariste","Ɖvrard","Fabien","Fabrice","Falba","FĆ©licitĆ©","FĆ©lix","Ferdinand","Fiacre","FidĆØle","Firmin","Flavien","Flodoard","Florent","Florentin","Florestan","Florian","FortunĆ©","Foulques","Francisque","FranƧois","FranƧais","Franciscus","Francs","FrĆ©dĆ©ric","Fulbert","Fulcran","Fulgence","Gabin","Gabriel","GaĆ«l","Garnier","Gaston","Gaspard","Gatien","Gaud","Gautier","GĆ©dĆ©on","Geoffroy","Georges","GĆ©raud","GĆ©rard","Gerbert","Germain","Gervais","Ghislain","Gilbert","Gilles","Girart","Gislebert","Gondebaud","Gonthier","Gontran","Gonzague","GrĆ©goire","GuĆ©rin","Gui","Guillaume","Gustave","Guy","Guyot","Hardouin","Hector","HĆ©delin","HĆ©lier","Henri","Herbert","Herluin","HervĆ©","Hilaire","Hildebert","Hincmar","Hippolyte","HonorĆ©","Hubert","Hugues","Innocent","Isabeau","Isidore","Jacques","Japhet","Jason","Jean","Jeannel","Jeannot","JĆ©rĆ©mie","JĆ©rĆ“me","Joachim","Joanny","Job","Jocelyn","JoĆ«l","Johan","Jonas","Jonathan","Joseph","Josse","Josselin","Jourdain","Jude","JudicaĆ«l","Jules","Julien","Juste","Justin","Lambert","Landry","Laurent","Lazare","LĆ©andre","LĆ©on","LĆ©onard","LĆ©opold","Leu","Loup","Leufroy","LibĆØre","LiĆ©tald","Lionel","LoĆÆc","Longin","Lorrain","Lorraine","Lothaire","Louis","Loup","Luc","Lucas","Lucien","Ludolphe","Ludovic","Macaire","Malo","Mamert","ManassĆ©","Marc","Marceau","Marcel","Marcelin","Marius","Marseille","Martial","Martin","Mathurin","Matthias","Mathias","Matthieu","Maugis","Maurice","Mauricet","Maxence","Maxime","Maximilien","Mayeul","MĆ©dĆ©ric","Melchior","Mence","Merlin","MĆ©rovĆ©e","MichaĆ«l","Michel","MoĆÆse","Morgan","Nathan","NathanaĆ«l","Narcisse","NĆ©hĆ©mie","Nestor","Nestor","NicĆ©phore","Nicolas","NoĆ©","NoĆ«l","Norbert","Normand","Normands","Octave","Odilon","Odon","Oger","Olivier","Oury","PacĆ“me","PalĆ©mon","Parfait","Pascal","Paterne","Patrice","Paul","PĆ©pin","Perceval","PhilĆ©mon","Philibert","Philippe","PhilothĆ©e","Pie","Pierre","Pierrick","Prosper","Quentin","Raoul","RaphaĆ«l","Raymond","RĆ©gis","RĆ©jean","RĆ©mi","Renaud","RenĆ©","Reybaud","Richard","Robert","Roch","Rodolphe","Rodrigue","Roger","Roland","Romain","Romuald","RomĆ©o","Rome","Ronan","Roselin","Salomon","Samuel","Savin","Savinien","Scholastique","SĆ©bastien","SĆ©raphin","Serge","SĆ©verin","Sidoine","Sigebert","Sigismond","SilvĆØre","Simon","SimĆ©on","Sixte","Stanislas","StĆ©phane","Stephan","Sylvain","Sylvestre","TancrĆØde","Tanguy","Taurin","ThĆ©odore","ThĆ©odose","ThĆ©ophile","ThĆ©ophraste","Thibault","Thibert","Thierry","Thomas","TimolĆ©on","TimothĆ©e","Titien","Tonnin","Toussaint","Trajan","Tristan","Turold","Tim","Ulysse","Urbain","Valentin","ValĆØre","ValĆ©ry","Venance","Venant","Venceslas","Vianney","Victor","Victorien","Victorin","Vigile","Vincent","Vital","Vitalien","Vivien","Waleran","Wandrille","Xavier","XĆ©nophon","Yves","Zacharie","ZachĆ©","ZĆ©phirin"] - }, - - "female": { - "en": ["Mary", "Emma", "Elizabeth", "Minnie", "Margaret", "Ida", "Alice", "Bertha", "Sarah", "Annie", "Clara", "Ella", "Florence", "Cora", "Martha", "Laura", "Nellie", "Grace", "Carrie", "Maude", "Mabel", "Bessie", "Jennie", "Gertrude", "Julia", "Hattie", "Edith", "Mattie", "Rose", "Catherine", "Lillian", "Ada", "Lillie", "Helen", "Jessie", "Louise", "Ethel", "Lula", "Myrtle", "Eva", "Frances", "Lena", "Lucy", "Edna", "Maggie", "Pearl", "Daisy", "Fannie", "Josephine", "Dora", "Rosa", "Katherine", "Agnes", "Marie", "Nora", "May", "Mamie", "Blanche", "Stella", "Ellen", "Nancy", "Effie", "Sallie", "Nettie", "Della", "Lizzie", "Flora", "Susie", "Maud", "Mae", "Etta", "Harriet", "Sadie", "Caroline", "Katie", "Lydia", "Elsie", "Kate", "Susan", "Mollie", "Alma", "Addie", "Georgia", "Eliza", "Lulu", "Nannie", "Lottie", "Amanda", "Belle", "Charlotte", "Rebecca", "Ruth", "Viola", "Olive", "Amelia", "Hannah", "Jane", "Virginia", "Emily", "Matilda", "Irene", "Kathryn", "Esther", "Willie", "Henrietta", "Ollie", "Amy", "Rachel", "Sara", "Estella", "Theresa", "Augusta", "Ora", "Pauline", "Josie", "Lola", "Sophia", "Leona", "Anne", "Mildred", "Ann", "Beulah", "Callie", "Lou", "Delia", "Eleanor", "Barbara", "Iva", "Louisa", "Maria", "Mayme", "Evelyn", "Estelle", "Nina", "Betty", "Marion", "Bettie", "Dorothy", "Luella", "Inez", "Lela", "Rosie", "Allie", "Millie", "Janie", "Cornelia", "Victoria", "Ruby", "Winifred", "Alta", "Celia", "Christine", "Beatrice", "Birdie", "Harriett", "Mable", "Myra", "Sophie", "Tillie", "Isabel", "Sylvia", "Carolyn", "Isabelle", "Leila", "Sally", "Ina", "Essie", "Bertie", "Nell", "Alberta", "Katharine", "Lora", "Rena", "Mina", "Rhoda", "Mathilda", "Abbie", "Eula", "Dollie", "Hettie", "Eunice", "Fanny", "Ola", "Lenora", "Adelaide", "Christina", "Lelia", "Nelle", "Sue", "Johanna", "Lilly", "Lucinda", "Minerva", "Lettie", "Roxie", "Cynthia", "Helena", "Hilda", "Hulda", "Bernice", "Genevieve", "Jean", "Cordelia", "Marian", "Francis", "Jeanette", "Adeline", "Gussie", "Leah", "Lois", "Lura", "Mittie", "Hallie", "Isabella", "Olga", "Phoebe", "Teresa", "Hester", "Lida", "Lina", "Winnie", "Claudia", "Marguerite", "Vera", "Cecelia", "Bess", "Emilie", "Rosetta", "Verna", "Myrtie", "Cecilia", "Elva", "Olivia", "Ophelia", "Georgie", "Elnora", "Violet", "Adele", "Lily", "Linnie", "Loretta", "Madge", "Polly", "Virgie", "Eugenia", "Lucile", "Lucille", "Mabelle", "Rosalie"], - // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0162 - "it": ["Ada", "Adriana", "Alessandra", "Alessia", "Alice", "Angela", "Anna", "Anna Maria", "Annalisa", "Annita", "Annunziata", "Antonella", "Arianna", "Asia", "Assunta", "Aurora", "Barbara", "Beatrice", "Benedetta", "Bianca", "Bruna", "Camilla", "Carla", "Carlotta", "Carmela", "Carolina", "Caterina", "Catia", "Cecilia", "Chiara", "Cinzia", "Clara", "Claudia", "Costanza", "Cristina", "Daniela", "Debora", "Diletta", "Dina", "Donatella", "Elena", "Eleonora", "Elisa", "Elisabetta", "Emanuela", "Emma", "Eva", "Federica", "Fernanda", "Fiorella", "Fiorenza", "Flora", "Franca", "Francesca", "Gabriella", "Gaia", "Gemma", "Giada", "Gianna", "Gina", "Ginevra", "Giorgia", "Giovanna", "Giulia", "Giuliana", "Giuseppa", "Giuseppina", "Grazia", "Graziella", "Greta", "Ida", "Ilaria", "Ines", "Iolanda", "Irene", "Irma", "Isabella", "Jessica", "Laura", "Lea", "Letizia", "Licia", "Lidia", "Liliana", "Lina", "Linda", "Lisa", "Livia", "Loretta", "Luana", "Lucia", "Luciana", "Lucrezia", "Luisa", "Manuela", "Mara", "Marcella", "Margherita", "Maria", "Maria Cristina", "Maria Grazia", "Maria Luisa", "Maria Pia", "Maria Teresa", "Marina", "Marisa", "Marta", "Martina", "Marzia", "Matilde", "Melissa", "Michela", "Milena", "Mirella", "Monica", "Natalina", "Nella", "Nicoletta", "Noemi", "Olga", "Paola", "Patrizia", "Piera", "Pierina", "Raffaella", "Rebecca", "Renata", "Rina", "Rita", "Roberta", "Rosa", "Rosanna", "Rossana", "Rossella", "Sabrina", "Sandra", "Sara", "Serena", "Silvana", "Silvia", "Simona", "Simonetta", "Sofia", "Sonia", "Stefania", "Susanna", "Teresa", "Tina", "Tiziana", "Tosca", "Valentina", "Valeria", "Vanda", "Vanessa", "Vanna", "Vera", "Veronica", "Vilma", "Viola", "Virginia", "Vittoria"], - // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html - "nl": ["Ada", "Arianne", "Afke", "Amanda", "Amber", "Amy", "Aniek", "Anita", "Anja", "Anna", "Anne", "Annelies", "Annemarie", "Annette", "Anouk", "Astrid", "Aukje", "Barbara", "Bianca", "Carla", "Carlijn", "Carolien", "Chantal", "Charlotte", "Claudia", "DaniĆ«lle", "Debora", "Diane", "Dora", "Eline", "Elise", "Ella", "Ellen", "Emma", "Esmee", "Evelien", "Esther", "Erica", "Eva", "Femke", "Fleur", "Floor", "Froukje", "Gea", "Gerda", "Hanna", "Hanneke", "Heleen", "Hilde", "Ilona", "Ina", "Inge", "Ingrid", "Iris", "Isabel", "Isabelle", "Janneke", "Jasmijn", "Jeanine", "Jennifer", "Jessica", "Johanna", "Joke", "Julia", "Julie", "Karen", "Karin", "Katja", "Kim", "Lara", "Laura", "Lena", "Lianne", "Lieke", "Lilian", "Linda", "Lisa", "Lisanne", "Lotte", "Louise", "Maaike", "Manon", "Marga", "Maria", "Marissa", "Marit", "Marjolein", "Martine", "Marleen", "Melissa", "Merel", "Miranda", "Michelle", "Mirjam", "Mirthe", "Naomi", "Natalie", 'Nienke', "Nina", "Noortje", "Olivia", "Patricia", "Paula", "Paulien", "Ramona", "Ria", "Rianne", "Roos", "Rosanne", "Ruth", "Sabrina", "Sandra", "Sanne", "Sara", "Saskia", "Silvia", "Sofia", "Sophie", "Sonja", "Suzanne", "Tamara", "Tess", "Tessa", "Tineke", "Valerie", "Vanessa", "Veerle", "Vera", "Victoria", "Wendy", "Willeke", "Yvonne", "ZoĆ«"], - // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie - "fr": ["Abdon","Abel","AbigaĆ«lle","AbigaĆÆl","Acacius","Acanthe","Adalbert","Adalsinde","Adegrine","AdĆ©laĆÆde","AdĆØle","AdĆ©lie","Adeline","Adeltrude","Adolphe","Adonis","AdrastĆ©e","Adrehilde","Adrienne","Agathe","Agilbert","AglaĆ©","Aignan","AgneflĆØte","AgnĆØs","Agrippine","AimĆ©","Alaine","AlaĆÆs","Albane","AlbĆ©rade","Alberte","Alcide","Alcine","Alcyone","Aldegonde","Aleth","Alexandrine","Alexine","Alice","AliĆ©nor","Aliette","Aline","Alix","AlizĆ©","AloĆÆse","Aloyse","Alphonsine","AlthĆ©e","Amaliane","AmalthĆ©e","Amande","Amandine","Amant","Amarande","Amaranthe","Amaryllis","Ambre","Ambroisie","AmĆ©lie","AmĆ©thyste","Aminte","AnaĆ«l","AnaĆÆs","Anastasie","Anatole","Ancelin","AndrĆ©e","AnĆ©mone","AngadrĆŖme","AngĆØle","Angeline","AngĆ©lique","Angilbert","Anicet","Annabelle","Anne","Annette","Annick","Annie","Annonciade","Ansbert","Anstrudie","Anthelme","Antigone","Antoinette","Antonine","AphĆ©lie","Apolline","Apollonie","Aquiline","Arabelle","Arcadie","Archange","Argine","Ariane","Aricie","Ariel","Arielle","Arlette","Armance","Armande","Armandine","Armelle","Armide","Armelle","Armin","Arnaud","ArsĆØne","ArsinoĆ©","ArtĆ©mis","Arthur","Ascelin","Ascension","Assomption","AstartĆ©","AstĆ©rie","AstrĆ©e","Astrid","Athalie","Athanasie","Athina","Aube","Albert","Aude","Audrey","Augustine","Aure","AurĆ©lie","AurĆ©lien","AurĆØle","Aurore","Auxence","Aveline","AbigaĆ«lle","Avoye","Axelle","Aymard","AzalĆ©e","AdĆØle","Adeline","Barbe","Basilisse","Bathilde","BĆ©atrice","BĆ©atrix","BĆ©nĆ©dicte","BĆ©rengĆØre","Bernadette","Berthe","Bertille","Beuve","Blanche","Blanc","Blandine","Brigitte","Brune","Brunehilde","Callista","Camille","Capucine","Carine","Caroline","Cassandre","Catherine","CĆ©cile","CĆ©leste","CĆ©lestine","CĆ©line","Chantal","CharlĆØne","Charline","Charlotte","ChloĆ©","Christelle","Christiane","Christine","Claire","Clara","Claude","Claudine","Clarisse","ClĆ©mence","ClĆ©mentine","ClĆ©o","Clio","Clotilde","Coline","Conception","Constance","Coralie","Coraline","Corentine","Corinne","Cyrielle","Daniel","Daniel","DaphnĆ©","DĆ©bora","Delphine","Denise","Diane","DieudonnĆ©","Dominique","Doriane","DorothĆ©e","Douce","Ɖdith","EdmĆ©e","ƉlĆ©onore","Ɖliane","Ɖlia","Ɖliette","Ɖlisabeth","Ɖlise","Ella","Ɖlodie","ƉloĆÆse","Elsa","Ɖmeline","ƉmĆ©rance","ƉmĆ©rentienne","ƉmĆ©rencie","Ɖmilie","Emma","Emmanuelle","Emmelie","Ernestine","Esther","Estelle","Eudoxie","EugĆ©nie","Eulalie","Euphrasie","EusĆ©bie","ƉvangĆ©line","Eva","ƈve","Ɖvelyne","Fanny","Fantine","Faustine","FĆ©licie","Fernande","Flavie","Fleur","Flore","Florence","Florie","FortunĆ©","France","Francia","FranƧoise","Francine","Gabrielle","GaĆ«lle","Garance","GeneviĆØve","Georgette","Gerberge","Germaine","Gertrude","GisĆØle","GueniĆØvre","Guilhemine","Guillemette","Gustave","Gwenael","HĆ©lĆØne","HĆ©loĆÆse","Henriette","Hermine","Hermione","Hippolyte","Honorine","Hortense","Huguette","Ines","IrĆØne","Irina","Iris","Isabeau","Isabelle","Iseult","Isolde","IsmĆ©rie","Jacinthe","Jacqueline","Jade","Janine","Jeanne","Jocelyne","JoĆ«lle","JosĆ©phine","Judith","Julia","Julie","Jules","Juliette","Justine","Katy","Kathy","Katie","Laura","Laure","Laureline","Laurence","Laurene","Lauriane","Laurianne","Laurine","LĆ©a","LĆ©na","LĆ©onie","LĆ©on","LĆ©ontine","Lorraine","Lucie","Lucienne","Lucille","Ludivine","Lydie","Lydie","Megane","Madeleine","Magali","Maguelone","Mallaury","Manon","Marceline","Margot","Marguerite","Marianne","Marie","Myriam","Marie","Marine","Marion","MarlĆØne","Marthe","Martine","Mathilde","Maud","Maureen","Mauricette","Maxime","MĆ©lanie","Melissa","MĆ©lissandre","MĆ©lisande","MĆ©lodie","Michel","Micheline","Mireille","Miriam","MoĆÆse","Monique","Morgane","Muriel","MylĆØne","NadĆØge","Nadine","Nathalie","Nicole","Nicolette","Nine","NoĆ«l","NoĆ©mie","OcĆ©ane","Odette","Odile","Olive","Olivia","Olympe","Ombline","Ombeline","OphĆ©lie","Oriande","Oriane","Ozanne","Pascale","Pascaline","Paule","Paulette","Pauline","Priscille","Prisca","Prisque","PĆ©cine","PĆ©lagie","PĆ©nĆ©lope","Perrine","PĆ©tronille","Philippine","PhilomĆØne","PhilothĆ©e","Primerose","Prudence","PulchĆ©rie","Quentine","QuiĆ©ta","Quintia","Quintilla","Rachel","RaphaĆ«lle","Raymonde","Rebecca","RĆ©gine","RĆ©jeanne","RenĆ©","Rita","Rita","Rolande","Romane","Rosalie","Rose","Roseline","Sabine","SalomĆ©","Sandra","Sandrine","Sarah","SĆ©golĆØne","SĆ©verine","Sibylle","Simone","Sixt","Solange","Soline","SolĆØne","Sophie","StĆ©phanie","Suzanne","Sylvain","Sylvie","Tatiana","ThaĆÆs","ThĆ©odora","ThĆ©rĆØse","Tiphaine","Ursule","Valentine","ValĆ©rie","VĆ©ronique","Victoire","Victorine","Vinciane","Violette","Virginie","Viviane","XaviĆØre","Yolande","Ysaline","Yvette","Yvonne","ZĆ©lie","Zita","ZoĆ©"] - } - }, - - lastNames: { - "en": ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis', 'Miller', 'Wilson', 'Moore', 'Taylor', 'Anderson', 'Thomas', 'Jackson', 'White', 'Harris', 'Martin', 'Thompson', 'Garcia', 'Martinez', 'Robinson', 'Clark', 'Rodriguez', 'Lewis', 'Lee', 'Walker', 'Hall', 'Allen', 'Young', 'Hernandez', 'King', 'Wright', 'Lopez', 'Hill', 'Scott', 'Green', 'Adams', 'Baker', 'Gonzalez', 'Nelson', 'Carter', 'Mitchell', 'Perez', 'Roberts', 'Turner', 'Phillips', 'Campbell', 'Parker', 'Evans', 'Edwards', 'Collins', 'Stewart', 'Sanchez', 'Morris', 'Rogers', 'Reed', 'Cook', 'Morgan', 'Bell', 'Murphy', 'Bailey', 'Rivera', 'Cooper', 'Richardson', 'Cox', 'Howard', 'Ward', 'Torres', 'Peterson', 'Gray', 'Ramirez', 'James', 'Watson', 'Brooks', 'Kelly', 'Sanders', 'Price', 'Bennett', 'Wood', 'Barnes', 'Ross', 'Henderson', 'Coleman', 'Jenkins', 'Perry', 'Powell', 'Long', 'Patterson', 'Hughes', 'Flores', 'Washington', 'Butler', 'Simmons', 'Foster', 'Gonzales', 'Bryant', 'Alexander', 'Russell', 'Griffin', 'Diaz', 'Hayes', 'Myers', 'Ford', 'Hamilton', 'Graham', 'Sullivan', 'Wallace', 'Woods', 'Cole', 'West', 'Jordan', 'Owens', 'Reynolds', 'Fisher', 'Ellis', 'Harrison', 'Gibson', 'McDonald', 'Cruz', 'Marshall', 'Ortiz', 'Gomez', 'Murray', 'Freeman', 'Wells', 'Webb', 'Simpson', 'Stevens', 'Tucker', 'Porter', 'Hunter', 'Hicks', 'Crawford', 'Henry', 'Boyd', 'Mason', 'Morales', 'Kennedy', 'Warren', 'Dixon', 'Ramos', 'Reyes', 'Burns', 'Gordon', 'Shaw', 'Holmes', 'Rice', 'Robertson', 'Hunt', 'Black', 'Daniels', 'Palmer', 'Mills', 'Nichols', 'Grant', 'Knight', 'Ferguson', 'Rose', 'Stone', 'Hawkins', 'Dunn', 'Perkins', 'Hudson', 'Spencer', 'Gardner', 'Stephens', 'Payne', 'Pierce', 'Berry', 'Matthews', 'Arnold', 'Wagner', 'Willis', 'Ray', 'Watkins', 'Olson', 'Carroll', 'Duncan', 'Snyder', 'Hart', 'Cunningham', 'Bradley', 'Lane', 'Andrews', 'Ruiz', 'Harper', 'Fox', 'Riley', 'Armstrong', 'Carpenter', 'Weaver', 'Greene', 'Lawrence', 'Elliott', 'Chavez', 'Sims', 'Austin', 'Peters', 'Kelley', 'Franklin', 'Lawson', 'Fields', 'Gutierrez', 'Ryan', 'Schmidt', 'Carr', 'Vasquez', 'Castillo', 'Wheeler', 'Chapman', 'Oliver', 'Montgomery', 'Richards', 'Williamson', 'Johnston', 'Banks', 'Meyer', 'Bishop', 'McCoy', 'Howell', 'Alvarez', 'Morrison', 'Hansen', 'Fernandez', 'Garza', 'Harvey', 'Little', 'Burton', 'Stanley', 'Nguyen', 'George', 'Jacobs', 'Reid', 'Kim', 'Fuller', 'Lynch', 'Dean', 'Gilbert', 'Garrett', 'Romero', 'Welch', 'Larson', 'Frazier', 'Burke', 'Hanson', 'Day', 'Mendoza', 'Moreno', 'Bowman', 'Medina', 'Fowler', 'Brewer', 'Hoffman', 'Carlson', 'Silva', 'Pearson', 'Holland', 'Douglas', 'Fleming', 'Jensen', 'Vargas', 'Byrd', 'Davidson', 'Hopkins', 'May', 'Terry', 'Herrera', 'Wade', 'Soto', 'Walters', 'Curtis', 'Neal', 'Caldwell', 'Lowe', 'Jennings', 'Barnett', 'Graves', 'Jimenez', 'Horton', 'Shelton', 'Barrett', 'Obrien', 'Castro', 'Sutton', 'Gregory', 'McKinney', 'Lucas', 'Miles', 'Craig', 'Rodriquez', 'Chambers', 'Holt', 'Lambert', 'Fletcher', 'Watts', 'Bates', 'Hale', 'Rhodes', 'Pena', 'Beck', 'Newman', 'Haynes', 'McDaniel', 'Mendez', 'Bush', 'Vaughn', 'Parks', 'Dawson', 'Santiago', 'Norris', 'Hardy', 'Love', 'Steele', 'Curry', 'Powers', 'Schultz', 'Barker', 'Guzman', 'Page', 'Munoz', 'Ball', 'Keller', 'Chandler', 'Weber', 'Leonard', 'Walsh', 'Lyons', 'Ramsey', 'Wolfe', 'Schneider', 'Mullins', 'Benson', 'Sharp', 'Bowen', 'Daniel', 'Barber', 'Cummings', 'Hines', 'Baldwin', 'Griffith', 'Valdez', 'Hubbard', 'Salazar', 'Reeves', 'Warner', 'Stevenson', 'Burgess', 'Santos', 'Tate', 'Cross', 'Garner', 'Mann', 'Mack', 'Moss', 'Thornton', 'Dennis', 'McGee', 'Farmer', 'Delgado', 'Aguilar', 'Vega', 'Glover', 'Manning', 'Cohen', 'Harmon', 'Rodgers', 'Robbins', 'Newton', 'Todd', 'Blair', 'Higgins', 'Ingram', 'Reese', 'Cannon', 'Strickland', 'Townsend', 'Potter', 'Goodwin', 'Walton', 'Rowe', 'Hampton', 'Ortega', 'Patton', 'Swanson', 'Joseph', 'Francis', 'Goodman', 'Maldonado', 'Yates', 'Becker', 'Erickson', 'Hodges', 'Rios', 'Conner', 'Adkins', 'Webster', 'Norman', 'Malone', 'Hammond', 'Flowers', 'Cobb', 'Moody', 'Quinn', 'Blake', 'Maxwell', 'Pope', 'Floyd', 'Osborne', 'Paul', 'McCarthy', 'Guerrero', 'Lindsey', 'Estrada', 'Sandoval', 'Gibbs', 'Tyler', 'Gross', 'Fitzgerald', 'Stokes', 'Doyle', 'Sherman', 'Saunders', 'Wise', 'Colon', 'Gill', 'Alvarado', 'Greer', 'Padilla', 'Simon', 'Waters', 'Nunez', 'Ballard', 'Schwartz', 'McBride', 'Houston', 'Christensen', 'Klein', 'Pratt', 'Briggs', 'Parsons', 'McLaughlin', 'Zimmerman', 'French', 'Buchanan', 'Moran', 'Copeland', 'Roy', 'Pittman', 'Brady', 'McCormick', 'Holloway', 'Brock', 'Poole', 'Frank', 'Logan', 'Owen', 'Bass', 'Marsh', 'Drake', 'Wong', 'Jefferson', 'Park', 'Morton', 'Abbott', 'Sparks', 'Patrick', 'Norton', 'Huff', 'Clayton', 'Massey', 'Lloyd', 'Figueroa', 'Carson', 'Bowers', 'Roberson', 'Barton', 'Tran', 'Lamb', 'Harrington', 'Casey', 'Boone', 'Cortez', 'Clarke', 'Mathis', 'Singleton', 'Wilkins', 'Cain', 'Bryan', 'Underwood', 'Hogan', 'McKenzie', 'Collier', 'Luna', 'Phelps', 'McGuire', 'Allison', 'Bridges', 'Wilkerson', 'Nash', 'Summers', 'Atkins'], - // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0164 (first 1000) - "it": ["Acciai", "Aglietti", "Agostini", "Agresti", "Ahmed", "Aiazzi", "Albanese", "Alberti", "Alessi", "Alfani", "Alinari", "Alterini", "Amato", "Ammannati", "Ancillotti", "Andrei", "Andreini", "Andreoni", "Angeli", "Anichini", "Antonelli", "Antonini", "Arena", "Ariani", "Arnetoli", "Arrighi", "Baccani", "Baccetti", "Bacci", "Bacherini", "Badii", "Baggiani", "Baglioni", "Bagni", "Bagnoli", "Baldassini", "Baldi", "Baldini", "Ballerini", "Balli", "Ballini", "Balloni", "Bambi", "Banchi", "Bandinelli", "Bandini", "Bani", "Barbetti", "Barbieri", "Barchielli", "Bardazzi", "Bardelli", "Bardi", "Barducci", "Bargellini", "Bargiacchi", "Barni", "Baroncelli", "Baroncini", "Barone", "Baroni", "Baronti", "Bartalesi", "Bartoletti", "Bartoli", "Bartolini", "Bartoloni", "Bartolozzi", "Basagni", "Basile", "Bassi", "Batacchi", "Battaglia", "Battaglini", "Bausi", "Becagli", "Becattini", "Becchi", "Becucci", "Bellandi", "Bellesi", "Belli", "Bellini", "Bellucci", "Bencini", "Benedetti", "Benelli", "Beni", "Benini", "Bensi", "Benucci", "Benvenuti", "Berlincioni", "Bernacchioni", "Bernardi", "Bernardini", "Berni", "Bernini", "Bertelli", "Berti", "Bertini", "Bessi", "Betti", "Bettini", "Biagi", "Biagini", "Biagioni", "Biagiotti", "Biancalani", "Bianchi", "Bianchini", "Bianco", "Biffoli", "Bigazzi", "Bigi", "Biliotti", "Billi", "Binazzi", "Bindi", "Bini", "Biondi", "Bizzarri", "Bocci", "Bogani", "Bolognesi", "Bonaiuti", "Bonanni", "Bonciani", "Boncinelli", "Bondi", "Bonechi", "Bongini", "Boni", "Bonini", "Borchi", "Boretti", "Borghi", "Borghini", "Borgioli", "Borri", "Borselli", "Boschi", "Bottai", "Bracci", "Braccini", "Brandi", "Braschi", "Bravi", "Brazzini", "Breschi", "Brilli", "Brizzi", "Brogelli", "Brogi", "Brogioni", "Brunelli", "Brunetti", "Bruni", "Bruno", "Brunori", "Bruschi", "Bucci", "Bucciarelli", "Buccioni", "Bucelli", "Bulli", "Burberi", "Burchi", "Burgassi", "Burroni", "Bussotti", "Buti", "Caciolli", "Caiani", "Calabrese", "Calamai", "Calamandrei", "Caldini", "Calo'", "Calonaci", "Calosi", "Calvelli", "Cambi", "Camiciottoli", "Cammelli", "Cammilli", "Campolmi", "Cantini", "Capanni", "Capecchi", "Caponi", "Cappelletti", "Cappelli", "Cappellini", "Cappugi", "Capretti", "Caputo", "Carbone", "Carboni", "Cardini", "Carlesi", "Carletti", "Carli", "Caroti", "Carotti", "Carrai", "Carraresi", "Carta", "Caruso", "Casalini", "Casati", "Caselli", "Casini", "Castagnoli", "Castellani", "Castelli", "Castellucci", "Catalano", "Catarzi", "Catelani", "Cavaciocchi", "Cavallaro", "Cavallini", "Cavicchi", "Cavini", "Ceccarelli", "Ceccatelli", "Ceccherelli", "Ceccherini", "Cecchi", "Cecchini", "Cecconi", "Cei", "Cellai", "Celli", "Cellini", "Cencetti", "Ceni", "Cenni", "Cerbai", "Cesari", "Ceseri", "Checcacci", "Checchi", "Checcucci", "Cheli", "Chellini", "Chen", "Cheng", "Cherici", "Cherubini", "Chiaramonti", "Chiarantini", "Chiarelli", "Chiari", "Chiarini", "Chiarugi", "Chiavacci", "Chiesi", "Chimenti", "Chini", "Chirici", "Chiti", "Ciabatti", "Ciampi", "Cianchi", "Cianfanelli", "Cianferoni", "Ciani", "Ciapetti", "Ciappi", "Ciardi", "Ciatti", "Cicali", "Ciccone", "Cinelli", "Cini", "Ciobanu", "Ciolli", "Cioni", "Cipriani", "Cirillo", "Cirri", "Ciucchi", "Ciuffi", "Ciulli", "Ciullini", "Clemente", "Cocchi", "Cognome", "Coli", "Collini", "Colombo", "Colzi", "Comparini", "Conforti", "Consigli", "Conte", "Conti", "Contini", "Coppini", "Coppola", "Corsi", "Corsini", "Corti", "Cortini", "Cosi", "Costa", "Costantini", "Costantino", "Cozzi", "Cresci", "Crescioli", "Cresti", "Crini", "Curradi", "D'Agostino", "D'Alessandro", "D'Amico", "D'Angelo", "Daddi", "Dainelli", "Dallai", "Danti", "Davitti", "De Angelis", "De Luca", "De Marco", "De Rosa", "De Santis", "De Simone", "De Vita", "Degl'Innocenti", "Degli Innocenti", "Dei", "Del Lungo", "Del Re", "Di Marco", "Di Stefano", "Dini", "Diop", "Dobre", "Dolfi", "Donati", "Dondoli", "Dong", "Donnini", "Ducci", "Dumitru", "Ermini", "Esposito", "Evangelisti", "Fabbri", "Fabbrini", "Fabbrizzi", "Fabbroni", "Fabbrucci", "Fabiani", "Facchini", "Faggi", "Fagioli", "Failli", "Faini", "Falciani", "Falcini", "Falcone", "Fallani", "Falorni", "Falsini", "Falugiani", "Fancelli", "Fanelli", "Fanetti", "Fanfani", "Fani", "Fantappie'", "Fantechi", "Fanti", "Fantini", "Fantoni", "Farina", "Fattori", "Favilli", "Fedi", "Fei", "Ferrante", "Ferrara", "Ferrari", "Ferraro", "Ferretti", "Ferri", "Ferrini", "Ferroni", "Fiaschi", "Fibbi", "Fiesoli", "Filippi", "Filippini", "Fini", "Fioravanti", "Fiore", "Fiorentini", "Fiorini", "Fissi", "Focardi", "Foggi", "Fontana", "Fontanelli", "Fontani", "Forconi", "Formigli", "Forte", "Forti", "Fortini", "Fossati", "Fossi", "Francalanci", "Franceschi", "Franceschini", "Franchi", "Franchini", "Franci", "Francini", "Francioni", "Franco", "Frassineti", "Frati", "Fratini", "Frilli", "Frizzi", "Frosali", "Frosini", "Frullini", "Fusco", "Fusi", "Gabbrielli", "Gabellini", "Gagliardi", "Galanti", "Galardi", "Galeotti", "Galletti", "Galli", "Gallo", "Gallori", "Gambacciani", "Gargani", "Garofalo", "Garuglieri", "Gashi", "Gasperini", "Gatti", "Gelli", "Gensini", "Gentile", "Gentili", "Geri", "Gerini", "Gheri", "Ghini", "Giachetti", "Giachi", "Giacomelli", "Gianassi", "Giani", "Giannelli", "Giannetti", "Gianni", "Giannini", "Giannoni", "Giannotti", "Giannozzi", "Gigli", "Giordano", "Giorgetti", "Giorgi", "Giovacchini", "Giovannelli", "Giovannetti", "Giovannini", "Giovannoni", "Giuliani", "Giunti", "Giuntini", "Giusti", "Gonnelli", "Goretti", "Gori", "Gradi", "Gramigni", "Grassi", "Grasso", "Graziani", "Grazzini", "Greco", "Grifoni", "Grillo", "Grimaldi", "Grossi", "Gualtieri", "Guarducci", "Guarino", "Guarnieri", "Guasti", "Guerra", "Guerri", "Guerrini", "Guidi", "Guidotti", "He", "Hoxha", "Hu", "Huang", "Iandelli", "Ignesti", "Innocenti", "Jin", "La Rosa", "Lai", "Landi", "Landini", "Lanini", "Lapi", "Lapini", "Lari", "Lascialfari", "Lastrucci", "Latini", "Lazzeri", "Lazzerini", "Lelli", "Lenzi", "Leonardi", "Leoncini", "Leone", "Leoni", "Lepri", "Li", "Liao", "Lin", "Linari", "Lippi", "Lisi", "Livi", "Lombardi", "Lombardini", "Lombardo", "Longo", "Lopez", "Lorenzi", "Lorenzini", "Lorini", "Lotti", "Lu", "Lucchesi", "Lucherini", "Lunghi", "Lupi", "Madiai", "Maestrini", "Maffei", "Maggi", "Maggini", "Magherini", "Magini", "Magnani", "Magnelli", "Magni", "Magnolfi", "Magrini", "Malavolti", "Malevolti", "Manca", "Mancini", "Manetti", "Manfredi", "Mangani", "Mannelli", "Manni", "Mannini", "Mannucci", "Manuelli", "Manzini", "Marcelli", "Marchese", "Marchetti", "Marchi", "Marchiani", "Marchionni", "Marconi", "Marcucci", "Margheri", "Mari", "Mariani", "Marilli", "Marinai", "Marinari", "Marinelli", "Marini", "Marino", "Mariotti", "Marsili", "Martelli", "Martinelli", "Martini", "Martino", "Marzi", "Masi", "Masini", "Masoni", "Massai", "Materassi", "Mattei", "Matteini", "Matteucci", "Matteuzzi", "Mattioli", "Mattolini", "Matucci", "Mauro", "Mazzanti", "Mazzei", "Mazzetti", "Mazzi", "Mazzini", "Mazzocchi", "Mazzoli", "Mazzoni", "Mazzuoli", "Meacci", "Mecocci", "Meini", "Melani", "Mele", "Meli", "Mengoni", "Menichetti", "Meoni", "Merlini", "Messeri", "Messina", "Meucci", "Miccinesi", "Miceli", "Micheli", "Michelini", "Michelozzi", "Migliori", "Migliorini", "Milani", "Miniati", "Misuri", "Monaco", "Montagnani", "Montagni", "Montanari", "Montelatici", "Monti", "Montigiani", "Montini", "Morandi", "Morandini", "Morelli", "Moretti", "Morganti", "Mori", "Morini", "Moroni", "Morozzi", "Mugnai", "Mugnaini", "Mustafa", "Naldi", "Naldini", "Nannelli", "Nanni", "Nannini", "Nannucci", "Nardi", "Nardini", "Nardoni", "Natali", "Ndiaye", "Nencetti", "Nencini", "Nencioni", "Neri", "Nesi", "Nesti", "Niccolai", "Niccoli", "Niccolini", "Nigi", "Nistri", "Nocentini", "Noferini", "Novelli", "Nucci", "Nuti", "Nutini", "Oliva", "Olivieri", "Olmi", "Orlandi", "Orlandini", "Orlando", "Orsini", "Ortolani", "Ottanelli", "Pacciani", "Pace", "Paci", "Pacini", "Pagani", "Pagano", "Paggetti", "Pagliai", "Pagni", "Pagnini", "Paladini", "Palagi", "Palchetti", "Palloni", "Palmieri", "Palumbo", "Pampaloni", "Pancani", "Pandolfi", "Pandolfini", "Panerai", "Panichi", "Paoletti", "Paoli", "Paolini", "Papi", "Papini", "Papucci", "Parenti", "Parigi", "Parisi", "Parri", "Parrini", "Pasquini", "Passeri", "Pecchioli", "Pecorini", "Pellegrini", "Pepi", "Perini", "Perrone", "Peruzzi", "Pesci", "Pestelli", "Petri", "Petrini", "Petrucci", "Pettini", "Pezzati", "Pezzatini", "Piani", "Piazza", "Piazzesi", "Piazzini", "Piccardi", "Picchi", "Piccini", "Piccioli", "Pieraccini", "Pieraccioni", "Pieralli", "Pierattini", "Pieri", "Pierini", "Pieroni", "Pietrini", "Pini", "Pinna", "Pinto", "Pinzani", "Pinzauti", "Piras", "Pisani", "Pistolesi", "Poggesi", "Poggi", "Poggiali", "Poggiolini", "Poli", "Pollastri", "Porciani", "Pozzi", "Pratellesi", "Pratesi", "Prosperi", "Pruneti", "Pucci", "Puccini", "Puccioni", "Pugi", "Pugliese", "Puliti", "Querci", "Quercioli", "Raddi", "Radu", "Raffaelli", "Ragazzini", "Ranfagni", "Ranieri", "Rastrelli", "Raugei", "Raveggi", "Renai", "Renzi", "Rettori", "Ricci", "Ricciardi", "Ridi", "Ridolfi", "Rigacci", "Righi", "Righini", "Rinaldi", "Risaliti", "Ristori", "Rizzo", "Rocchi", "Rocchini", "Rogai", "Romagnoli", "Romanelli", "Romani", "Romano", "Romei", "Romeo", "Romiti", "Romoli", "Romolini", "Rontini", "Rosati", "Roselli", "Rosi", "Rossetti", "Rossi", "Rossini", "Rovai", "Ruggeri", "Ruggiero", "Russo", "Sabatini", "Saccardi", "Sacchetti", "Sacchi", "Sacco", "Salerno", "Salimbeni", "Salucci", "Salvadori", "Salvestrini", "Salvi", "Salvini", "Sanesi", "Sani", "Sanna", "Santi", "Santini", "Santoni", "Santoro", "Santucci", "Sardi", "Sarri", "Sarti", "Sassi", "Sbolci", "Scali", "Scarpelli", "Scarselli", "Scopetani", "Secci", "Selvi", "Senatori", "Senesi", "Serafini", "Sereni", "Serra", "Sestini", "Sguanci", "Sieni", "Signorini", "Silvestri", "Simoncini", "Simonetti", "Simoni", "Singh", "Sodi", "Soldi", "Somigli", "Sorbi", "Sorelli", "Sorrentino", "Sottili", "Spina", "Spinelli", "Staccioli", "Staderini", "Stefanelli", "Stefani", "Stefanini", "Stella", "Susini", "Tacchi", "Tacconi", "Taddei", "Tagliaferri", "Tamburini", "Tanganelli", "Tani", "Tanini", "Tapinassi", "Tarchi", "Tarchiani", "Targioni", "Tassi", "Tassini", "Tempesti", "Terzani", "Tesi", "Testa", "Testi", "Tilli", "Tinti", "Tirinnanzi", "Toccafondi", "Tofanari", "Tofani", "Tognaccini", "Tonelli", "Tonini", "Torelli", "Torrini", "Tosi", "Toti", "Tozzi", "Trambusti", "Trapani", "Tucci", "Turchi", "Ugolini", "Ulivi", "Valente", "Valenti", "Valentini", "Vangelisti", "Vanni", "Vannini", "Vannoni", "Vannozzi", "Vannucchi", "Vannucci", "Ventura", "Venturi", "Venturini", "Vestri", "Vettori", "Vichi", "Viciani", "Vieri", "Vigiani", "Vignoli", "Vignolini", "Vignozzi", "Villani", "Vinci", "Visani", "Vitale", "Vitali", "Viti", "Viviani", "Vivoli", "Volpe", "Volpi", "Wang", "Wu", "Xu", "Yang", "Ye", "Zagli", "Zani", "Zanieri", "Zanobini", "Zecchi", "Zetti", "Zhang", "Zheng", "Zhou", "Zhu", "Zingoni", "Zini", "Zoppi"], - // http://www.voornamelijk.nl/meest-voorkomende-achternamen-in-nederland-en-amsterdam/ - "nl":["Albers", "Alblas", "Appelman", "Baars", "Baas", "Bakker", "Blank", "Bleeker", "Blok", "Blom", "Boer", "Boers", "Boldewijn", "Boon", "Boot", "Bos", "Bosch", "Bosma", "Bosman", "Bouma", "Bouman", "Bouwman", "Brands", "Brouwer", "Burger", "Buijs", "Buitenhuis", "Ceder", "Cohen", "Dekker", "Dekkers", "Dijkman", "Dijkstra", "Driessen", "Drost", "Engel", "Evers", "Faber", "Franke", "Gerritsen", "Goedhart", "Goossens", "Groen", "Groenenberg", "Groot", "Haan", "Hart", "Heemskerk", "Hendriks", "Hermans", "Hoekstra", "Hofman", "Hopman", "Huisman", "Jacobs", "Jansen", "Janssen", "Jonker", "Jaspers", "Keijzer", "Klaassen", "Klein", "Koek", "Koenders", "Kok", "Kool", "Koopman", "Koopmans", "Koning", "Koster", "Kramer", "Kroon", "Kuijpers", "Kuiper", "Kuipers", "Kurt", "Koster", "Kwakman", "Los", "Lubbers", "Maas", "Markus", "Martens", "Meijer", "Mol", "Molenaar", "Mulder", "Nieuwenhuis", "Peeters", "Peters", "Pengel", "Pieters", "Pool", "Post", "Postma", "Prins", "Pronk", "Reijnders", "Rietveld", "Roest", "Roos", "Sanders", "Schaap", "Scheffer", "Schenk", "Schilder", "Schipper", "Schmidt", "Scholten", "Schouten", "Schut", "Schutte", "Schuurman", "Simons", "Smeets", "Smit", "Smits", "Snel", "Swinkels", "Tas", "Terpstra", "Timmermans", "Tol", "Tromp", "Troost", "Valk", "Veenstra", "Veldkamp", "Verbeek", "Verheul", "Verhoeven", "Vermeer", "Vermeulen", "Verweij", "Vink", "Visser", "Voorn", "Vos", "Wagenaar", "Wiersema", "Willems", "Willemsen", "Witteveen", "Wolff", "Wolters", "Zijlstra", "Zwart", "de Beer", "de Boer", "de Bruijn", "de Bruin", "de Graaf", "de Groot", "de Haan", "de Haas", "de Jager", "de Jong", "de Jonge", "de Koning", "de Lange", "de Leeuw", "de Ridder", "de Rooij", "de Ruiter", "de Vos", "de Vries", "de Waal", "de Wit", "de Zwart", "van Beek", "van Boven", "van Dam", "van Dijk", "van Dongen", "van Doorn", "van Egmond", "van Eijk", "van Es", "van Gelder", "van Gelderen", "van Houten", "van Hulst", "van Kempen", "van Kesteren", "van Leeuwen", "van Loon", "van Mill", "van Noord", "van Ommen", "van Ommeren", "van Oosten", "van Oostveen", "van Rijn", "van Schaik", "van Veen", "van Vliet", "van Wijk", "van Wijngaarden", "van den Poel", "van de Pol", "van den Ploeg", "van de Ven", "van den Berg", "van den Bosch", "van den Brink", "van den Broek", "van den Heuvel", "van der Heijden", "van der Horst", "van der Hulst", "van der Kroon", "van der Laan", "van der Linden", "van der Meer", "van der Meij", "van der Meulen", "van der Molen", "van der Sluis", "van der Spek", "van der Veen", "van der Velde", "van der Velden", "van der Vliet", "van der Wal"], - // https://surnames.behindthename.com/top/lists/england-wales/1991 - "uk":["Smith","Jones","Williams","Taylor","Brown","Davies","Evans","Wilson","Thomas","Johnson","Roberts","Robinson","Thompson","Wright","Walker","White","Edwards","Hughes","Green","Hall","Lewis","Harris","Clarke","Patel","Jackson","Wood","Turner","Martin","Cooper","Hill","Ward","Morris","Moore","Clark","Lee","King","Baker","Harrison","Morgan","Allen","James","Scott","Phillips","Watson","Davis","Parker","Price","Bennett","Young","Griffiths","Mitchell","Kelly","Cook","Carter","Richardson","Bailey","Collins","Bell","Shaw","Murphy","Miller","Cox","Richards","Khan","Marshall","Anderson","Simpson","Ellis","Adams","Singh","Begum","Wilkinson","Foster","Chapman","Powell","Webb","Rogers","Gray","Mason","Ali","Hunt","Hussain","Campbell","Matthews","Owen","Palmer","Holmes","Mills","Barnes","Knight","Lloyd","Butler","Russell","Barker","Fisher","Stevens","Jenkins","Murray","Dixon","Harvey","Graham","Pearson","Ahmed","Fletcher","Walsh","Kaur","Gibson","Howard","Andrews","Stewart","Elliott","Reynolds","Saunders","Payne","Fox","Ford","Pearce","Day","Brooks","West","Lawrence","Cole","Atkinson","Bradley","Spencer","Gill","Dawson","Ball","Burton","O'brien","Watts","Rose","Booth","Perry","Ryan","Grant","Wells","Armstrong","Francis","Rees","Hayes","Hart","Hudson","Newman","Barrett","Webster","Hunter","Gregory","Carr","Lowe","Page","Marsh","Riley","Dunn","Woods","Parsons","Berry","Stone","Reid","Holland","Hawkins","Harding","Porter","Robertson","Newton","Oliver","Reed","Kennedy","Williamson","Bird","Gardner","Shah","Dean","Lane","Cooke","Bates","Henderson","Parry","Burgess","Bishop","Walton","Burns","Nicholson","Shepherd","Ross","Cross","Long","Freeman","Warren","Nicholls","Hamilton","Byrne","Sutton","Mcdonald","Yates","Hodgson","Robson","Curtis","Hopkins","O'connor","Harper","Coleman","Watkins","Moss","Mccarthy","Chambers","O'neill","Griffin","Sharp","Hardy","Wheeler","Potter","Osborne","Johnston","Gordon","Doyle","Wallace","George","Jordan","Hutchinson","Rowe","Burke","May","Pritchard","Gilbert","Willis","Higgins","Read","Miles","Stevenson","Stephenson","Hammond","Arnold","Buckley","Walters","Hewitt","Barber","Nelson","Slater","Austin","Sullivan","Whitehead","Mann","Frost","Lambert","Stephens","Blake","Akhtar","Lynch","Goodwin","Barton","Woodward","Thomson","Cunningham","Quinn","Barnett","Baxter","Bibi","Clayton","Nash","Greenwood","Jennings","Holt","Kemp","Poole","Gallagher","Bond","Stokes","Tucker","Davidson","Fowler","Heath","Norman","Middleton","Lawson","Banks","French","Stanley","Jarvis","Gibbs","Ferguson","Hayward","Carroll","Douglas","Dickinson","Todd","Barlow","Peters","Lucas","Knowles","Hartley","Miah","Simmons","Morton","Alexander","Field","Morrison","Norris","Townsend","Preston","Hancock","Thornton","Baldwin","Burrows","Briggs","Parkinson","Reeves","Macdonald","Lamb","Black","Abbott","Sanders","Thorpe","Holden","Tomlinson","Perkins","Ashton","Rhodes","Fuller","Howe","Bryant","Vaughan","Dale","Davey","Weston","Bartlett","Whittaker","Davison","Kent","Skinner","Birch","Morley","Daniels","Glover","Howell","Cartwright","Pugh","Humphreys","Goddard","Brennan","Wall","Kirby","Bowen","Savage","Bull","Wong","Dobson","Smart","Wilkins","Kirk","Fraser","Duffy","Hicks","Patterson","Bradshaw","Little","Archer","Warner","Waters","O'sullivan","Farrell","Brookes","Atkins","Kay","Dodd","Bentley","Flynn","John","Schofield","Short","Haynes","Wade","Butcher","Henry","Sanderson","Crawford","Sheppard","Bolton","Coates","Giles","Gould","Houghton","Gibbons","Pratt","Manning","Law","Hooper","Noble","Dyer","Rahman","Clements","Moran","Sykes","Chan","Doherty","Connolly","Joyce","Franklin","Hobbs","Coles","Herbert","Steele","Kerr","Leach","Winter","Owens","Duncan","Naylor","Fleming","Horton","Finch","Fitzgerald","Randall","Carpenter","Marsden","Browne","Garner","Pickering","Hale","Dennis","Vincent","Chadwick","Chandler","Sharpe","Nolan","Lyons","Hurst","Collier","Peacock","Howarth","Faulkner","Rice","Pollard","Welch","Norton","Gough","Sinclair","Blackburn","Bryan","Conway","Power","Cameron","Daly","Allan","Hanson","Gardiner","Boyle","Myers","Turnbull","Wallis","Mahmood","Sims","Swift","Iqbal","Pope","Brady","Chamberlain","Rowley","Tyler","Farmer","Metcalfe","Hilton","Godfrey","Holloway","Parkin","Bray","Talbot","Donnelly","Nixon","Charlton","Benson","Whitehouse","Barry","Hope","Lord","North","Storey","Connor","Potts","Bevan","Hargreaves","Mclean","Mistry","Bruce","Howells","Hyde","Parkes","Wyatt","Fry","Lees","O'donnell","Craig","Forster","Mckenzie","Humphries","Mellor","Carey","Ingram","Summers","Leonard"], - // https://surnames.behindthename.com/top/lists/germany/2017 - "de": ["Müller","Schmidt","Schneider","Fischer","Weber","Meyer","Wagner","Becker","Schulz","Hoffmann","SchƤfer","Koch","Bauer","Richter","Klein","Wolf","Schrƶder","Neumann","Schwarz","Zimmermann","Braun","Krüger","Hofmann","Hartmann","Lange","Schmitt","Werner","Schmitz","Krause","Meier","Lehmann","Schmid","Schulze","Maier","Kƶhler","Herrmann","Kƶnig","Walter","Mayer","Huber","Kaiser","Fuchs","Peters","Lang","Scholz","Mƶller","Weiß","Jung","Hahn","Schubert","Vogel","Friedrich","Keller","Günther","Frank","Berger","Winkler","Roth","Beck","Lorenz","Baumann","Franke","Albrecht","Schuster","Simon","Ludwig","Bƶhm","Winter","Kraus","Martin","Schumacher","KrƤmer","Vogt","Stein","JƤger","Otto","Sommer","Groß","Seidel","Heinrich","Brandt","Haas","Schreiber","Graf","Schulte","Dietrich","Ziegler","Kuhn","Kühn","Pohl","Engel","Horn","Busch","Bergmann","Thomas","Voigt","Sauer","Arnold","Wolff","Pfeiffer"], - // http://www.japantimes.co.jp/life/2009/10/11/lifestyle/japans-top-100-most-common-family-names/ - "jp": ["Sato","Suzuki","Takahashi","Tanaka","Watanabe","Ito","Yamamoto","Nakamura","Kobayashi","Kato","Yoshida","Yamada","Sasaki","Yamaguchi","Saito","Matsumoto","Inoue","Kimura","Hayashi","Shimizu","Yamazaki","Mori","Abe","Ikeda","Hashimoto","Yamashita","Ishikawa","Nakajima","Maeda","Fujita","Ogawa","Goto","Okada","Hasegawa","Murakami","Kondo","Ishii","Saito","Sakamoto","Endo","Aoki","Fujii","Nishimura","Fukuda","Ota","Miura","Fujiwara","Okamoto","Matsuda","Nakagawa","Nakano","Harada","Ono","Tamura","Takeuchi","Kaneko","Wada","Nakayama","Ishida","Ueda","Morita","Hara","Shibata","Sakai","Kudo","Yokoyama","Miyazaki","Miyamoto","Uchida","Takagi","Ando","Taniguchi","Ohno","Maruyama","Imai","Takada","Fujimoto","Takeda","Murata","Ueno","Sugiyama","Masuda","Sugawara","Hirano","Kojima","Otsuka","Chiba","Kubo","Matsui","Iwasaki","Sakurai","Kinoshita","Noguchi","Matsuo","Nomura","Kikuchi","Sano","Onishi","Sugimoto","Arai"], - // http://www.lowchensaustralia.com/names/popular-spanish-names.htm - "es": ["Garcia","Fernandez","Lopez","Martinez","Gonzalez","Rodriguez","Sanchez","Perez","Martin","Gomez","Ruiz","Diaz","Hernandez","Alvarez","Jimenez","Moreno","Munoz","Alonso","Romero","Navarro","Gutierrez","Torres","Dominguez","Gil","Vazquez","Blanco","Serrano","Ramos","Castro","Suarez","Sanz","Rubio","Ortega","Molina","Delgado","Ortiz","Morales","Ramirez","Marin","Iglesias","Santos","Castillo","Garrido","Calvo","Pena","Cruz","Cano","Nunez","Prieto","Diez","Lozano","Vidal","Pascual","Ferrer","Medina","Vega","Leon","Herrero","Vicente","Mendez","Guerrero","Fuentes","Campos","Nieto","Cortes","Caballero","Ibanez","Lorenzo","Pastor","Gimenez","Saez","Soler","Marquez","Carrasco","Herrera","Montero","Arias","Crespo","Flores","Andres","Aguilar","Hidalgo","Cabrera","Mora","Duran","Velasco","Rey","Pardo","Roman","Vila","Bravo","Merino","Moya","Soto","Izquierdo","Reyes","Redondo","Marcos","Carmona","Menendez"], - // Data taken from https://fr.wikipedia.org/wiki/Liste_des_noms_de_famille_les_plus_courants_en_France - "fr": ["Martin","Bernard","Thomas","Petit","Robert","Richard","Durand","Dubois","Moreau","Laurent","Simon","Michel","LefĆØvre","Leroy","Roux","David","Bertrand","Morel","Fournier","Girard","Bonnet","Dupont","Lambert","Fontaine","Rousseau","Vincent","Müller","LefĆØvre","Faure","AndrĆ©","Mercier","Blanc","GuĆ©rin","Boyer","Garnier","Chevalier","FranƧois","Legrand","Gauthier","Garcia","Perrin","Robin","ClĆ©ment","Morin","Nicolas","Henry","Roussel","Matthieu","Gautier","Masson","Marchand","Duval","Denis","Dumont","Marie","Lemaire","NoĆ«l","Meyer","Dufour","Meunier","Brun","Blanchard","Giraud","Joly","RiviĆØre","Lucas","Brunet","Gaillard","Barbier","Arnaud","MartĆ­nez","GĆ©rard","Roche","Renard","Schmitt","Roy","Leroux","Colin","Vidal","Caron","Picard","Roger","Fabre","Aubert","Lemoine","Renaud","Dumas","Lacroix","Olivier","Philippe","Bourgeois","Pierre","BenoĆ®t","Rey","Leclerc","Payet","Rolland","Leclercq","Guillaume","Lecomte","López","Jean","Dupuy","Guillot","Hubert","Berger","Carpentier","SĆ”nchez","Dupuis","Moulin","Louis","Deschamps","Huet","Vasseur","Perez","Boucher","Fleury","Royer","Klein","Jacquet","Adam","Paris","Poirier","Marty","Aubry","Guyot","CarrĆ©","Charles","Renault","Charpentier","MĆ©nard","Maillard","Baron","Bertin","Bailly","HervĆ©","Schneider","FernĆ”ndez","Le GallGall","Collet","LĆ©ger","Bouvier","Julien","PrĆ©vost","Millet","Perrot","Daniel","Le RouxRoux","Cousin","Germain","Breton","Besson","Langlois","RĆ©mi","Le GoffGoff","Pelletier","LĆ©vĆŖque","Perrier","Leblanc","BarrĆ©","Lebrun","Marchal","Weber","Mallet","Hamon","Boulanger","Jacob","Monnier","Michaud","RodrĆ­guez","Guichard","Gillet","Ɖtienne","Grondin","Poulain","Tessier","Chevallier","Collin","Chauvin","Da SilvaSilva","Bouchet","Gay","LemaĆ®tre","BĆ©nard","MarĆ©chal","Humbert","Reynaud","Antoine","Hoarau","Perret","BarthĆ©lemy","Cordier","Pichon","Lejeune","Gilbert","Lamy","Delaunay","Pasquier","Carlier","LaporteLaporte"] - }, - - // Data taken from http://geoportal.statistics.gov.uk/datasets/ons-postcode-directory-latest-centroids - postcodeAreas: [{code: 'AB'}, {code: 'AL'}, {code: 'B'}, {code: 'BA'}, {code: 'BB'}, {code: 'BD'}, {code: 'BH'}, {code: 'BL'}, {code: 'BN'}, {code: 'BR'}, {code: 'BS'}, {code: 'BT'}, {code: 'CA'}, {code: 'CB'}, {code: 'CF'}, {code: 'CH'}, {code: 'CM'}, {code: 'CO'}, {code: 'CR'}, {code: 'CT'}, {code: 'CV'}, {code: 'CW'}, {code: 'DA'}, {code: 'DD'}, {code: 'DE'}, {code: 'DG'}, {code: 'DH'}, {code: 'DL'}, {code: 'DN'}, {code: 'DT'}, {code: 'DY'}, {code: 'E'}, {code: 'EC'}, {code: 'EH'}, {code: 'EN'}, {code: 'EX'}, {code: 'FK'}, {code: 'FY'}, {code: 'G'}, {code: 'GL'}, {code: 'GU'}, {code: 'GY'}, {code: 'HA'}, {code: 'HD'}, {code: 'HG'}, {code: 'HP'}, {code: 'HR'}, {code: 'HS'}, {code: 'HU'}, {code: 'HX'}, {code: 'IG'}, {code: 'IM'}, {code: 'IP'}, {code: 'IV'}, {code: 'JE'}, {code: 'KA'}, {code: 'KT'}, {code: 'KW'}, {code: 'KY'}, {code: 'L'}, {code: 'LA'}, {code: 'LD'}, {code: 'LE'}, {code: 'LL'}, {code: 'LN'}, {code: 'LS'}, {code: 'LU'}, {code: 'M'}, {code: 'ME'}, {code: 'MK'}, {code: 'ML'}, {code: 'N'}, {code: 'NE'}, {code: 'NG'}, {code: 'NN'}, {code: 'NP'}, {code: 'NR'}, {code: 'NW'}, {code: 'OL'}, {code: 'OX'}, {code: 'PA'}, {code: 'PE'}, {code: 'PH'}, {code: 'PL'}, {code: 'PO'}, {code: 'PR'}, {code: 'RG'}, {code: 'RH'}, {code: 'RM'}, {code: 'S'}, {code: 'SA'}, {code: 'SE'}, {code: 'SG'}, {code: 'SK'}, {code: 'SL'}, {code: 'SM'}, {code: 'SN'}, {code: 'SO'}, {code: 'SP'}, {code: 'SR'}, {code: 'SS'}, {code: 'ST'}, {code: 'SW'}, {code: 'SY'}, {code: 'TA'}, {code: 'TD'}, {code: 'TF'}, {code: 'TN'}, {code: 'TQ'}, {code: 'TR'}, {code: 'TS'}, {code: 'TW'}, {code: 'UB'}, {code: 'W'}, {code: 'WA'}, {code: 'WC'}, {code: 'WD'}, {code: 'WF'}, {code: 'WN'}, {code: 'WR'}, {code: 'WS'}, {code: 'WV'}, {code: 'YO'}, {code: 'ZE'}], - - // Data taken from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 - countries: [{"name":"Afghanistan","abbreviation":"AF"},{"name":"ƅland Islands","abbreviation":"AX"},{"name":"Albania","abbreviation":"AL"},{"name":"Algeria","abbreviation":"DZ"},{"name":"American Samoa","abbreviation":"AS"},{"name":"Andorra","abbreviation":"AD"},{"name":"Angola","abbreviation":"AO"},{"name":"Anguilla","abbreviation":"AI"},{"name":"Antarctica","abbreviation":"AQ"},{"name":"Antigua and Barbuda","abbreviation":"AG"},{"name":"Argentina","abbreviation":"AR"},{"name":"Armenia","abbreviation":"AM"},{"name":"Aruba","abbreviation":"AW"},{"name":"Australia","abbreviation":"AU"},{"name":"Austria","abbreviation":"AT"},{"name":"Azerbaijan","abbreviation":"AZ"},{"name":"Bahamas","abbreviation":"BS"},{"name":"Bahrain","abbreviation":"BH"},{"name":"Bangladesh","abbreviation":"BD"},{"name":"Barbados","abbreviation":"BB"},{"name":"Belarus","abbreviation":"BY"},{"name":"Belgium","abbreviation":"BE"},{"name":"Belize","abbreviation":"BZ"},{"name":"Benin","abbreviation":"BJ"},{"name":"Bermuda","abbreviation":"BM"},{"name":"Bhutan","abbreviation":"BT"},{"name":"Plurinational State of Bolivia","abbreviation":"BO"},{"name":"Bonaire, Sint Eustatius and Saba","abbreviation":"BQ"},{"name":"Bosnia and Herzegovina","abbreviation":"BA"},{"name":"Botswana","abbreviation":"BW"},{"name":"Bouvet Island","abbreviation":"BV"},{"name":"Brazil","abbreviation":"BR"},{"name":"British Indian Ocean Territory","abbreviation":"IO"},{"name":"Brunei Darussalam","abbreviation":"BN"},{"name":"Bulgaria","abbreviation":"BG"},{"name":"Burkina Faso","abbreviation":"BF"},{"name":"Burundi","abbreviation":"BI"},{"name":"Cabo Verde","abbreviation":"CV"},{"name":"Cambodia","abbreviation":"KH"},{"name":"Cameroon","abbreviation":"CM"},{"name":"Canada","abbreviation":"CA"},{"name":"Cayman Islands","abbreviation":"KY"},{"name":"Central African Republic","abbreviation":"CF"},{"name":"Chad","abbreviation":"TD"},{"name":"Chile","abbreviation":"CL"},{"name":"China","abbreviation":"CN"},{"name":"Christmas Island","abbreviation":"CX"},{"name":"Cocos (Keeling) Islands","abbreviation":"CC"},{"name":"Colombia","abbreviation":"CO"},{"name":"Comoros","abbreviation":"KM"},{"name":"Congo","abbreviation":"CG"},{"name":"Democratic Republic of the Congo","abbreviation":"CD"},{"name":"Cook Islands","abbreviation":"CK"},{"name":"Costa Rica","abbreviation":"CR"},{"name":"CĆ“te d'Ivoire","abbreviation":"CI"},{"name":"Croatia","abbreviation":"HR"},{"name":"Cuba","abbreviation":"CU"},{"name":"CuraƧao","abbreviation":"CW"},{"name":"Cyprus","abbreviation":"CY"},{"name":"Czechia","abbreviation":"CZ"},{"name":"Denmark","abbreviation":"DK"},{"name":"Djibouti","abbreviation":"DJ"},{"name":"Dominica","abbreviation":"DM"},{"name":"Dominican Republic","abbreviation":"DO"},{"name":"Ecuador","abbreviation":"EC"},{"name":"Egypt","abbreviation":"EG"},{"name":"El Salvador","abbreviation":"SV"},{"name":"Equatorial Guinea","abbreviation":"GQ"},{"name":"Eritrea","abbreviation":"ER"},{"name":"Estonia","abbreviation":"EE"},{"name":"Eswatini","abbreviation":"SZ"},{"name":"Ethiopia","abbreviation":"ET"},{"name":"Falkland Islands (Malvinas)","abbreviation":"FK"},{"name":"Faroe Islands","abbreviation":"FO"},{"name":"Fiji","abbreviation":"FJ"},{"name":"Finland","abbreviation":"FI"},{"name":"France","abbreviation":"FR"},{"name":"French Guiana","abbreviation":"GF"},{"name":"French Polynesia","abbreviation":"PF"},{"name":"French Southern Territories","abbreviation":"TF"},{"name":"Gabon","abbreviation":"GA"},{"name":"Gambia","abbreviation":"GM"},{"name":"Georgia","abbreviation":"GE"},{"name":"Germany","abbreviation":"DE"},{"name":"Ghana","abbreviation":"GH"},{"name":"Gibraltar","abbreviation":"GI"},{"name":"Greece","abbreviation":"GR"},{"name":"Greenland","abbreviation":"GL"},{"name":"Grenada","abbreviation":"GD"},{"name":"Guadeloupe","abbreviation":"GP"},{"name":"Guam","abbreviation":"GU"},{"name":"Guatemala","abbreviation":"GT"},{"name":"Guernsey","abbreviation":"GG"},{"name":"Guinea","abbreviation":"GN"},{"name":"Guinea-Bissau","abbreviation":"GW"},{"name":"Guyana","abbreviation":"GY"},{"name":"Haiti","abbreviation":"HT"},{"name":"Heard Island and McDonald Islands","abbreviation":"HM"},{"name":"Holy See","abbreviation":"VA"},{"name":"Honduras","abbreviation":"HN"},{"name":"Hong Kong","abbreviation":"HK"},{"name":"Hungary","abbreviation":"HU"},{"name":"Iceland","abbreviation":"IS"},{"name":"India","abbreviation":"IN"},{"name":"Indonesia","abbreviation":"ID"},{"name":"Islamic Republic of Iran","abbreviation":"IR"},{"name":"Iraq","abbreviation":"IQ"},{"name":"Ireland","abbreviation":"IE"},{"name":"Isle of Man","abbreviation":"IM"},{"name":"Israel","abbreviation":"IL"},{"name":"Italy","abbreviation":"IT"},{"name":"Jamaica","abbreviation":"JM"},{"name":"Japan","abbreviation":"JP"},{"name":"Jersey","abbreviation":"JE"},{"name":"Jordan","abbreviation":"JO"},{"name":"Kazakhstan","abbreviation":"KZ"},{"name":"Kenya","abbreviation":"KE"},{"name":"Kiribati","abbreviation":"KI"},{"name":"Democratic People's Republic of Korea","abbreviation":"KP"},{"name":"Republic of Korea","abbreviation":"KR"},{"name":"Kuwait","abbreviation":"KW"},{"name":"Kyrgyzstan","abbreviation":"KG"},{"name":"Lao People's Democratic Republic","abbreviation":"LA"},{"name":"Latvia","abbreviation":"LV"},{"name":"Lebanon","abbreviation":"LB"},{"name":"Lesotho","abbreviation":"LS"},{"name":"Liberia","abbreviation":"LR"},{"name":"Libya","abbreviation":"LY"},{"name":"Liechtenstein","abbreviation":"LI"},{"name":"Lithuania","abbreviation":"LT"},{"name":"Luxembourg","abbreviation":"LU"},{"name":"Macao","abbreviation":"MO"},{"name":"Madagascar","abbreviation":"MG"},{"name":"Malawi","abbreviation":"MW"},{"name":"Malaysia","abbreviation":"MY"},{"name":"Maldives","abbreviation":"MV"},{"name":"Mali","abbreviation":"ML"},{"name":"Malta","abbreviation":"MT"},{"name":"Marshall Islands","abbreviation":"MH"},{"name":"Martinique","abbreviation":"MQ"},{"name":"Mauritania","abbreviation":"MR"},{"name":"Mauritius","abbreviation":"MU"},{"name":"Mayotte","abbreviation":"YT"},{"name":"Mexico","abbreviation":"MX"},{"name":"Federated States of Micronesia","abbreviation":"FM"},{"name":"Republic of Moldova","abbreviation":"MD"},{"name":"Monaco","abbreviation":"MC"},{"name":"Mongolia","abbreviation":"MN"},{"name":"Montenegro","abbreviation":"ME"},{"name":"Montserrat","abbreviation":"MS"},{"name":"Morocco","abbreviation":"MA"},{"name":"Mozambique","abbreviation":"MZ"},{"name":"Myanmar","abbreviation":"MM"},{"name":"Namibia","abbreviation":"NA"},{"name":"Nauru","abbreviation":"NR"},{"name":"Nepal","abbreviation":"NP"},{"name":"Kingdom of the Netherlands","abbreviation":"NL"},{"name":"New Caledonia","abbreviation":"NC"},{"name":"New Zealand","abbreviation":"NZ"},{"name":"Nicaragua","abbreviation":"NI"},{"name":"Niger","abbreviation":"NE"},{"name":"Nigeria","abbreviation":"NG"},{"name":"Niue","abbreviation":"NU"},{"name":"Norfolk Island","abbreviation":"NF"},{"name":"North Macedonia","abbreviation":"MK"},{"name":"Northern Mariana Islands","abbreviation":"MP"},{"name":"Norway","abbreviation":"NO"},{"name":"Oman","abbreviation":"OM"},{"name":"Pakistan","abbreviation":"PK"},{"name":"Palau","abbreviation":"PW"},{"name":"State of Palestine","abbreviation":"PS"},{"name":"Panama","abbreviation":"PA"},{"name":"Papua New Guinea","abbreviation":"PG"},{"name":"Paraguay","abbreviation":"PY"},{"name":"Peru","abbreviation":"PE"},{"name":"Philippines","abbreviation":"PH"},{"name":"Pitcairn","abbreviation":"PN"},{"name":"Poland","abbreviation":"PL"},{"name":"Portugal","abbreviation":"PT"},{"name":"Puerto Rico","abbreviation":"PR"},{"name":"Qatar","abbreviation":"QA"},{"name":"RĆ©union","abbreviation":"RE"},{"name":"Romania","abbreviation":"RO"},{"name":"Russian Federation","abbreviation":"RU"},{"name":"Rwanda","abbreviation":"RW"},{"name":"Saint BarthĆ©lemy","abbreviation":"BL"},{"name":"Saint Helena, Ascension and Tristan da Cunha","abbreviation":"SH"},{"name":"Saint Kitts and Nevis","abbreviation":"KN"},{"name":"Saint Lucia","abbreviation":"LC"},{"name":"Saint Martin (French part)","abbreviation":"MF"},{"name":"Saint Pierre and Miquelon","abbreviation":"PM"},{"name":"Saint Vincent and the Grenadines","abbreviation":"VC"},{"name":"Samoa","abbreviation":"WS"},{"name":"San Marino","abbreviation":"SM"},{"name":"Sao Tome and Principe","abbreviation":"ST"},{"name":"Saudi Arabia","abbreviation":"SA"},{"name":"Senegal","abbreviation":"SN"},{"name":"Serbia","abbreviation":"RS"},{"name":"Seychelles","abbreviation":"SC"},{"name":"Sierra Leone","abbreviation":"SL"},{"name":"Singapore","abbreviation":"SG"},{"name":"Sint Maarten (Dutch part)","abbreviation":"SX"},{"name":"Slovakia","abbreviation":"SK"},{"name":"Slovenia","abbreviation":"SI"},{"name":"Solomon Islands","abbreviation":"SB"},{"name":"Somalia","abbreviation":"SO"},{"name":"South Africa","abbreviation":"ZA"},{"name":"South Georgia and the South Sandwich Islands","abbreviation":"GS"},{"name":"South Sudan","abbreviation":"SS"},{"name":"Spain","abbreviation":"ES"},{"name":"Sri Lanka","abbreviation":"LK"},{"name":"Sudan","abbreviation":"SD"},{"name":"Suriname","abbreviation":"SR"},{"name":"Svalbard and Jan Mayen","abbreviation":"SJ"},{"name":"Sweden","abbreviation":"SE"},{"name":"Switzerland","abbreviation":"CH"},{"name":"Syrian Arab Republic","abbreviation":"SY"},{"name":"Taiwan, Province of China","abbreviation":"TW"},{"name":"Tajikistan","abbreviation":"TJ"},{"name":"United Republic of Tanzania","abbreviation":"TZ"},{"name":"Thailand","abbreviation":"TH"},{"name":"Timor-Leste","abbreviation":"TL"},{"name":"Togo","abbreviation":"TG"},{"name":"Tokelau","abbreviation":"TK"},{"name":"Tonga","abbreviation":"TO"},{"name":"Trinidad and Tobago","abbreviation":"TT"},{"name":"Tunisia","abbreviation":"TN"},{"name":"Türkiye","abbreviation":"TR"},{"name":"Turkmenistan","abbreviation":"TM"},{"name":"Turks and Caicos Islands","abbreviation":"TC"},{"name":"Tuvalu","abbreviation":"TV"},{"name":"Uganda","abbreviation":"UG"},{"name":"Ukraine","abbreviation":"UA"},{"name":"United Arab Emirates","abbreviation":"AE"},{"name":"United Kingdom of Great Britain and Northern Ireland","abbreviation":"GB"},{"name":"United States Minor Outlying Islands","abbreviation":"UM"},{"name":"United States of America","abbreviation":"US"},{"name":"Uruguay","abbreviation":"UY"},{"name":"Uzbekistan","abbreviation":"UZ"},{"name":"Vanuatu","abbreviation":"VU"},{"name":"Bolivarian Republic of Venezuela","abbreviation":"VE"},{"name":"Viet Nam","abbreviation":"VN"},{"name":"Virgin Islands (British)","abbreviation":"VG"},{"name":"Virgin Islands (U.S.)","abbreviation":"VI"},{"name":"Wallis and Futuna","abbreviation":"WF"},{"name":"Western Sahara","abbreviation":"EH"},{"name":"Yemen","abbreviation":"YE"},{"name":"Zambia","abbreviation":"ZM"},{"name":"Zimbabwe","abbreviation":"ZW"}], - - counties: { - // Data taken from http://www.downloadexcelfiles.com/gb_en/download-excel-file-list-counties-uk - "uk": [ - {name: 'Bath and North East Somerset'}, - {name: 'Aberdeenshire'}, - {name: 'Anglesey'}, - {name: 'Angus'}, - {name: 'Bedford'}, - {name: 'Blackburn with Darwen'}, - {name: 'Blackpool'}, - {name: 'Bournemouth'}, - {name: 'Bracknell Forest'}, - {name: 'Brighton & Hove'}, - {name: 'Bristol'}, - {name: 'Buckinghamshire'}, - {name: 'Cambridgeshire'}, - {name: 'Carmarthenshire'}, - {name: 'Central Bedfordshire'}, - {name: 'Ceredigion'}, - {name: 'Cheshire East'}, - {name: 'Cheshire West and Chester'}, - {name: 'Clackmannanshire'}, - {name: 'Conwy'}, - {name: 'Cornwall'}, - {name: 'County Antrim'}, - {name: 'County Armagh'}, - {name: 'County Down'}, - {name: 'County Durham'}, - {name: 'County Fermanagh'}, - {name: 'County Londonderry'}, - {name: 'County Tyrone'}, - {name: 'Cumbria'}, - {name: 'Darlington'}, - {name: 'Denbighshire'}, - {name: 'Derby'}, - {name: 'Derbyshire'}, - {name: 'Devon'}, - {name: 'Dorset'}, - {name: 'Dumfries and Galloway'}, - {name: 'Dundee'}, - {name: 'East Lothian'}, - {name: 'East Riding of Yorkshire'}, - {name: 'East Sussex'}, - {name: 'Edinburgh?'}, - {name: 'Essex'}, - {name: 'Falkirk'}, - {name: 'Fife'}, - {name: 'Flintshire'}, - {name: 'Gloucestershire'}, - {name: 'Greater London'}, - {name: 'Greater Manchester'}, - {name: 'Gwent'}, - {name: 'Gwynedd'}, - {name: 'Halton'}, - {name: 'Hampshire'}, - {name: 'Hartlepool'}, - {name: 'Herefordshire'}, - {name: 'Hertfordshire'}, - {name: 'Highlands'}, - {name: 'Hull'}, - {name: 'Isle of Wight'}, - {name: 'Isles of Scilly'}, - {name: 'Kent'}, - {name: 'Lancashire'}, - {name: 'Leicester'}, - {name: 'Leicestershire'}, - {name: 'Lincolnshire'}, - {name: 'Lothian'}, - {name: 'Luton'}, - {name: 'Medway'}, - {name: 'Merseyside'}, - {name: 'Mid Glamorgan'}, - {name: 'Middlesbrough'}, - {name: 'Milton Keynes'}, - {name: 'Monmouthshire'}, - {name: 'Moray'}, - {name: 'Norfolk'}, - {name: 'North East Lincolnshire'}, - {name: 'North Lincolnshire'}, - {name: 'North Somerset'}, - {name: 'North Yorkshire'}, - {name: 'Northamptonshire'}, - {name: 'Northumberland'}, - {name: 'Nottingham'}, - {name: 'Nottinghamshire'}, - {name: 'Oxfordshire'}, - {name: 'Pembrokeshire'}, - {name: 'Perth and Kinross'}, - {name: 'Peterborough'}, - {name: 'Plymouth'}, - {name: 'Poole'}, - {name: 'Portsmouth'}, - {name: 'Powys'}, - {name: 'Reading'}, - {name: 'Redcar and Cleveland'}, - {name: 'Rutland'}, - {name: 'Scottish Borders'}, - {name: 'Shropshire'}, - {name: 'Slough'}, - {name: 'Somerset'}, - {name: 'South Glamorgan'}, - {name: 'South Gloucestershire'}, - {name: 'South Yorkshire'}, - {name: 'Southampton'}, - {name: 'Southend-on-Sea'}, - {name: 'Staffordshire'}, - {name: 'Stirlingshire'}, - {name: 'Stockton-on-Tees'}, - {name: 'Stoke-on-Trent'}, - {name: 'Strathclyde'}, - {name: 'Suffolk'}, - {name: 'Surrey'}, - {name: 'Swindon'}, - {name: 'Telford and Wrekin'}, - {name: 'Thurrock'}, - {name: 'Torbay'}, - {name: 'Tyne and Wear'}, - {name: 'Warrington'}, - {name: 'Warwickshire'}, - {name: 'West Berkshire'}, - {name: 'West Glamorgan'}, - {name: 'West Lothian'}, - {name: 'West Midlands'}, - {name: 'West Sussex'}, - {name: 'West Yorkshire'}, - {name: 'Western Isles'}, - {name: 'Wiltshire'}, - {name: 'Windsor and Maidenhead'}, - {name: 'Wokingham'}, - {name: 'Worcestershire'}, - {name: 'Wrexham'}, - {name: 'York'}] - }, - provinces: { - "ca": [ - {name: 'Alberta', abbreviation: 'AB'}, - {name: 'British Columbia', abbreviation: 'BC'}, - {name: 'Manitoba', abbreviation: 'MB'}, - {name: 'New Brunswick', abbreviation: 'NB'}, - {name: 'Newfoundland and Labrador', abbreviation: 'NL'}, - {name: 'Nova Scotia', abbreviation: 'NS'}, - {name: 'Ontario', abbreviation: 'ON'}, - {name: 'Prince Edward Island', abbreviation: 'PE'}, - {name: 'Quebec', abbreviation: 'QC'}, - {name: 'Saskatchewan', abbreviation: 'SK'}, - - // The case could be made that the following are not actually provinces - // since they are technically considered "territories" however they all - // look the same on an envelope! - {name: 'Northwest Territories', abbreviation: 'NT'}, - {name: 'Nunavut', abbreviation: 'NU'}, - {name: 'Yukon', abbreviation: 'YT'} - ], - "it": [ - { name: "Agrigento", abbreviation: "AG", code: 84 }, - { name: "Alessandria", abbreviation: "AL", code: 6 }, - { name: "Ancona", abbreviation: "AN", code: 42 }, - { name: "Aosta", abbreviation: "AO", code: 7 }, - { name: "L'Aquila", abbreviation: "AQ", code: 66 }, - { name: "Arezzo", abbreviation: "AR", code: 51 }, - { name: "Ascoli-Piceno", abbreviation: "AP", code: 44 }, - { name: "Asti", abbreviation: "AT", code: 5 }, - { name: "Avellino", abbreviation: "AV", code: 64 }, - { name: "Bari", abbreviation: "BA", code: 72 }, - { name: "Barletta-Andria-Trani", abbreviation: "BT", code: 72 }, - { name: "Belluno", abbreviation: "BL", code: 25 }, - { name: "Benevento", abbreviation: "BN", code: 62 }, - { name: "Bergamo", abbreviation: "BG", code: 16 }, - { name: "Biella", abbreviation: "BI", code: 96 }, - { name: "Bologna", abbreviation: "BO", code: 37 }, - { name: "Bolzano", abbreviation: "BZ", code: 21 }, - { name: "Brescia", abbreviation: "BS", code: 17 }, - { name: "Brindisi", abbreviation: "BR", code: 74 }, - { name: "Cagliari", abbreviation: "CA", code: 92 }, - { name: "Caltanissetta", abbreviation: "CL", code: 85 }, - { name: "Campobasso", abbreviation: "CB", code: 70 }, - { name: "Carbonia Iglesias", abbreviation: "CI", code: 70 }, - { name: "Caserta", abbreviation: "CE", code: 61 }, - { name: "Catania", abbreviation: "CT", code: 87 }, - { name: "Catanzaro", abbreviation: "CZ", code: 79 }, - { name: "Chieti", abbreviation: "CH", code: 69 }, - { name: "Como", abbreviation: "CO", code: 13 }, - { name: "Cosenza", abbreviation: "CS", code: 78 }, - { name: "Cremona", abbreviation: "CR", code: 19 }, - { name: "Crotone", abbreviation: "KR", code: 101 }, - { name: "Cuneo", abbreviation: "CN", code: 4 }, - { name: "Enna", abbreviation: "EN", code: 86 }, - { name: "Fermo", abbreviation: "FM", code: 86 }, - { name: "Ferrara", abbreviation: "FE", code: 38 }, - { name: "Firenze", abbreviation: "FI", code: 48 }, - { name: "Foggia", abbreviation: "FG", code: 71 }, - { name: "Forli-Cesena", abbreviation: "FC", code: 71 }, - { name: "Frosinone", abbreviation: "FR", code: 60 }, - { name: "Genova", abbreviation: "GE", code: 10 }, - { name: "Gorizia", abbreviation: "GO", code: 31 }, - { name: "Grosseto", abbreviation: "GR", code: 53 }, - { name: "Imperia", abbreviation: "IM", code: 8 }, - { name: "Isernia", abbreviation: "IS", code: 94 }, - { name: "La-Spezia", abbreviation: "SP", code: 66 }, - { name: "Latina", abbreviation: "LT", code: 59 }, - { name: "Lecce", abbreviation: "LE", code: 75 }, - { name: "Lecco", abbreviation: "LC", code: 97 }, - { name: "Livorno", abbreviation: "LI", code: 49 }, - { name: "Lodi", abbreviation: "LO", code: 98 }, - { name: "Lucca", abbreviation: "LU", code: 46 }, - { name: "Macerata", abbreviation: "MC", code: 43 }, - { name: "Mantova", abbreviation: "MN", code: 20 }, - { name: "Massa-Carrara", abbreviation: "MS", code: 45 }, - { name: "Matera", abbreviation: "MT", code: 77 }, - { name: "Medio Campidano", abbreviation: "VS", code: 77 }, - { name: "Messina", abbreviation: "ME", code: 83 }, - { name: "Milano", abbreviation: "MI", code: 15 }, - { name: "Modena", abbreviation: "MO", code: 36 }, - { name: "Monza-Brianza", abbreviation: "MB", code: 36 }, - { name: "Napoli", abbreviation: "NA", code: 63 }, - { name: "Novara", abbreviation: "NO", code: 3 }, - { name: "Nuoro", abbreviation: "NU", code: 91 }, - { name: "Ogliastra", abbreviation: "OG", code: 91 }, - { name: "Olbia Tempio", abbreviation: "OT", code: 91 }, - { name: "Oristano", abbreviation: "OR", code: 95 }, - { name: "Padova", abbreviation: "PD", code: 28 }, - { name: "Palermo", abbreviation: "PA", code: 82 }, - { name: "Parma", abbreviation: "PR", code: 34 }, - { name: "Pavia", abbreviation: "PV", code: 18 }, - { name: "Perugia", abbreviation: "PG", code: 54 }, - { name: "Pesaro-Urbino", abbreviation: "PU", code: 41 }, - { name: "Pescara", abbreviation: "PE", code: 68 }, - { name: "Piacenza", abbreviation: "PC", code: 33 }, - { name: "Pisa", abbreviation: "PI", code: 50 }, - { name: "Pistoia", abbreviation: "PT", code: 47 }, - { name: "Pordenone", abbreviation: "PN", code: 93 }, - { name: "Potenza", abbreviation: "PZ", code: 76 }, - { name: "Prato", abbreviation: "PO", code: 100 }, - { name: "Ragusa", abbreviation: "RG", code: 88 }, - { name: "Ravenna", abbreviation: "RA", code: 39 }, - { name: "Reggio-Calabria", abbreviation: "RC", code: 35 }, - { name: "Reggio-Emilia", abbreviation: "RE", code: 35 }, - { name: "Rieti", abbreviation: "RI", code: 57 }, - { name: "Rimini", abbreviation: "RN", code: 99 }, - { name: "Roma", abbreviation: "Roma", code: 58 }, - { name: "Rovigo", abbreviation: "RO", code: 29 }, - { name: "Salerno", abbreviation: "SA", code: 65 }, - { name: "Sassari", abbreviation: "SS", code: 90 }, - { name: "Savona", abbreviation: "SV", code: 9 }, - { name: "Siena", abbreviation: "SI", code: 52 }, - { name: "Siracusa", abbreviation: "SR", code: 89 }, - { name: "Sondrio", abbreviation: "SO", code: 14 }, - { name: "Taranto", abbreviation: "TA", code: 73 }, - { name: "Teramo", abbreviation: "TE", code: 67 }, - { name: "Terni", abbreviation: "TR", code: 55 }, - { name: "Torino", abbreviation: "TO", code: 1 }, - { name: "Trapani", abbreviation: "TP", code: 81 }, - { name: "Trento", abbreviation: "TN", code: 22 }, - { name: "Treviso", abbreviation: "TV", code: 26 }, - { name: "Trieste", abbreviation: "TS", code: 32 }, - { name: "Udine", abbreviation: "UD", code: 30 }, - { name: "Varese", abbreviation: "VA", code: 12 }, - { name: "Venezia", abbreviation: "VE", code: 27 }, - { name: "Verbania", abbreviation: "VB", code: 27 }, - { name: "Vercelli", abbreviation: "VC", code: 2 }, - { name: "Verona", abbreviation: "VR", code: 23 }, - { name: "Vibo-Valentia", abbreviation: "VV", code: 102 }, - { name: "Vicenza", abbreviation: "VI", code: 24 }, - { name: "Viterbo", abbreviation: "VT", code: 56 } - ] - }, - - // from: https://github.com/samsargent/Useful-Autocomplete-Data/blob/master/data/nationalities.json - nationalities: [ - {name: 'Afghan'}, - {name: 'Albanian'}, - {name: 'Algerian'}, - {name: 'American'}, - {name: 'Andorran'}, - {name: 'Angolan'}, - {name: 'Antiguans'}, - {name: 'Argentinean'}, - {name: 'Armenian'}, - {name: 'Australian'}, - {name: 'Austrian'}, - {name: 'Azerbaijani'}, - {name: 'Bahami'}, - {name: 'Bahraini'}, - {name: 'Bangladeshi'}, - {name: 'Barbadian'}, - {name: 'Barbudans'}, - {name: 'Batswana'}, - {name: 'Belarusian'}, - {name: 'Belgian'}, - {name: 'Belizean'}, - {name: 'Beninese'}, - {name: 'Bhutanese'}, - {name: 'Bolivian'}, - {name: 'Bosnian'}, - {name: 'Brazilian'}, - {name: 'British'}, - {name: 'Bruneian'}, - {name: 'Bulgarian'}, - {name: 'Burkinabe'}, - {name: 'Burmese'}, - {name: 'Burundian'}, - {name: 'Cambodian'}, - {name: 'Cameroonian'}, - {name: 'Canadian'}, - {name: 'Cape Verdean'}, - {name: 'Central African'}, - {name: 'Chadian'}, - {name: 'Chilean'}, - {name: 'Chinese'}, - {name: 'Colombian'}, - {name: 'Comoran'}, - {name: 'Congolese'}, - {name: 'Costa Rican'}, - {name: 'Croatian'}, - {name: 'Cuban'}, - {name: 'Cypriot'}, - {name: 'Czech'}, - {name: 'Danish'}, - {name: 'Djibouti'}, - {name: 'Dominican'}, - {name: 'Dutch'}, - {name: 'East Timorese'}, - {name: 'Ecuadorean'}, - {name: 'Egyptian'}, - {name: 'Emirian'}, - {name: 'Equatorial Guinean'}, - {name: 'Eritrean'}, - {name: 'Estonian'}, - {name: 'Ethiopian'}, - {name: 'Fijian'}, - {name: 'Filipino'}, - {name: 'Finnish'}, - {name: 'French'}, - {name: 'Gabonese'}, - {name: 'Gambian'}, - {name: 'Georgian'}, - {name: 'German'}, - {name: 'Ghanaian'}, - {name: 'Greek'}, - {name: 'Grenadian'}, - {name: 'Guatemalan'}, - {name: 'Guinea-Bissauan'}, - {name: 'Guinean'}, - {name: 'Guyanese'}, - {name: 'Haitian'}, - {name: 'Herzegovinian'}, - {name: 'Honduran'}, - {name: 'Hungarian'}, - {name: 'I-Kiribati'}, - {name: 'Icelander'}, - {name: 'Indian'}, - {name: 'Indonesian'}, - {name: 'Iranian'}, - {name: 'Iraqi'}, - {name: 'Irish'}, - {name: 'Israeli'}, - {name: 'Italian'}, - {name: 'Ivorian'}, - {name: 'Jamaican'}, - {name: 'Japanese'}, - {name: 'Jordanian'}, - {name: 'Kazakhstani'}, - {name: 'Kenyan'}, - {name: 'Kittian and Nevisian'}, - {name: 'Kuwaiti'}, - {name: 'Kyrgyz'}, - {name: 'Laotian'}, - {name: 'Latvian'}, - {name: 'Lebanese'}, - {name: 'Liberian'}, - {name: 'Libyan'}, - {name: 'Liechtensteiner'}, - {name: 'Lithuanian'}, - {name: 'Luxembourger'}, - {name: 'Macedonian'}, - {name: 'Malagasy'}, - {name: 'Malawian'}, - {name: 'Malaysian'}, - {name: 'Maldivan'}, - {name: 'Malian'}, - {name: 'Maltese'}, - {name: 'Marshallese'}, - {name: 'Mauritanian'}, - {name: 'Mauritian'}, - {name: 'Mexican'}, - {name: 'Micronesian'}, - {name: 'Moldovan'}, - {name: 'Monacan'}, - {name: 'Mongolian'}, - {name: 'Moroccan'}, - {name: 'Mosotho'}, - {name: 'Motswana'}, - {name: 'Mozambican'}, - {name: 'Namibian'}, - {name: 'Nauruan'}, - {name: 'Nepalese'}, - {name: 'New Zealander'}, - {name: 'Nicaraguan'}, - {name: 'Nigerian'}, - {name: 'Nigerien'}, - {name: 'North Korean'}, - {name: 'Northern Irish'}, - {name: 'Norwegian'}, - {name: 'Omani'}, - {name: 'Pakistani'}, - {name: 'Palauan'}, - {name: 'Panamanian'}, - {name: 'Papua New Guinean'}, - {name: 'Paraguayan'}, - {name: 'Peruvian'}, - {name: 'Polish'}, - {name: 'Portuguese'}, - {name: 'Qatari'}, - {name: 'Romani'}, - {name: 'Russian'}, - {name: 'Rwandan'}, - {name: 'Saint Lucian'}, - {name: 'Salvadoran'}, - {name: 'Samoan'}, - {name: 'San Marinese'}, - {name: 'Sao Tomean'}, - {name: 'Saudi'}, - {name: 'Scottish'}, - {name: 'Senegalese'}, - {name: 'Serbian'}, - {name: 'Seychellois'}, - {name: 'Sierra Leonean'}, - {name: 'Singaporean'}, - {name: 'Slovakian'}, - {name: 'Slovenian'}, - {name: 'Solomon Islander'}, - {name: 'Somali'}, - {name: 'South African'}, - {name: 'South Korean'}, - {name: 'Spanish'}, - {name: 'Sri Lankan'}, - {name: 'Sudanese'}, - {name: 'Surinamer'}, - {name: 'Swazi'}, - {name: 'Swedish'}, - {name: 'Swiss'}, - {name: 'Syrian'}, - {name: 'Taiwanese'}, - {name: 'Tajik'}, - {name: 'Tanzanian'}, - {name: 'Thai'}, - {name: 'Togolese'}, - {name: 'Tongan'}, - {name: 'Trinidadian or Tobagonian'}, - {name: 'Tunisian'}, - {name: 'Turkish'}, - {name: 'Tuvaluan'}, - {name: 'Ugandan'}, - {name: 'Ukrainian'}, - {name: 'Uruguaya'}, - {name: 'Uzbekistani'}, - {name: 'Venezuela'}, - {name: 'Vietnamese'}, - {name: 'Wels'}, - {name: 'Yemenit'}, - {name: 'Zambia'}, - {name: 'Zimbabwe'}, - ], - // http://www.loc.gov/standards/iso639-2/php/code_list.php (ISO-639-1 codes) - locale_languages: [ - "aa", - "ab", - "ae", - "af", - "ak", - "am", - "an", - "ar", - "as", - "av", - "ay", - "az", - "ba", - "be", - "bg", - "bh", - "bi", - "bm", - "bn", - "bo", - "br", - "bs", - "ca", - "ce", - "ch", - "co", - "cr", - "cs", - "cu", - "cv", - "cy", - "da", - "de", - "dv", - "dz", - "ee", - "el", - "en", - "eo", - "es", - "et", - "eu", - "fa", - "ff", - "fi", - "fj", - "fo", - "fr", - "fy", - "ga", - "gd", - "gl", - "gn", - "gu", - "gv", - "ha", - "he", - "hi", - "ho", - "hr", - "ht", - "hu", - "hy", - "hz", - "ia", - "id", - "ie", - "ig", - "ii", - "ik", - "io", - "is", - "it", - "iu", - "ja", - "jv", - "ka", - "kg", - "ki", - "kj", - "kk", - "kl", - "km", - "kn", - "ko", - "kr", - "ks", - "ku", - "kv", - "kw", - "ky", - "la", - "lb", - "lg", - "li", - "ln", - "lo", - "lt", - "lu", - "lv", - "mg", - "mh", - "mi", - "mk", - "ml", - "mn", - "mr", - "ms", - "mt", - "my", - "na", - "nb", - "nd", - "ne", - "ng", - "nl", - "nn", - "no", - "nr", - "nv", - "ny", - "oc", - "oj", - "om", - "or", - "os", - "pa", - "pi", - "pl", - "ps", - "pt", - "qu", - "rm", - "rn", - "ro", - "ru", - "rw", - "sa", - "sc", - "sd", - "se", - "sg", - "si", - "sk", - "sl", - "sm", - "sn", - "so", - "sq", - "sr", - "ss", - "st", - "su", - "sv", - "sw", - "ta", - "te", - "tg", - "th", - "ti", - "tk", - "tl", - "tn", - "to", - "tr", - "ts", - "tt", - "tw", - "ty", - "ug", - "uk", - "ur", - "uz", - "ve", - "vi", - "vo", - "wa", - "wo", - "xh", - "yi", - "yo", - "za", - "zh", - "zu" - ], - - // From http://data.okfn.org/data/core/language-codes#resource-language-codes-full (IETF language tags) - locale_regions: [ - "agq-CM", - "asa-TZ", - "ast-ES", - "bas-CM", - "bem-ZM", - "bez-TZ", - "brx-IN", - "cgg-UG", - "chr-US", - "dav-KE", - "dje-NE", - "dsb-DE", - "dua-CM", - "dyo-SN", - "ebu-KE", - "ewo-CM", - "fil-PH", - "fur-IT", - "gsw-CH", - "gsw-FR", - "gsw-LI", - "guz-KE", - "haw-US", - "hsb-DE", - "jgo-CM", - "jmc-TZ", - "kab-DZ", - "kam-KE", - "kde-TZ", - "kea-CV", - "khq-ML", - "kkj-CM", - "kln-KE", - "kok-IN", - "ksb-TZ", - "ksf-CM", - "ksh-DE", - "lag-TZ", - "lkt-US", - "luo-KE", - "luy-KE", - "mas-KE", - "mas-TZ", - "mer-KE", - "mfe-MU", - "mgh-MZ", - "mgo-CM", - "mua-CM", - "naq-NA", - "nmg-CM", - "nnh-CM", - "nus-SD", - "nyn-UG", - "rof-TZ", - "rwk-TZ", - "sah-RU", - "saq-KE", - "sbp-TZ", - "seh-MZ", - "ses-ML", - "shi-Latn", - "shi-Latn-MA", - "shi-Tfng", - "shi-Tfng-MA", - "smn-FI", - "teo-KE", - "teo-UG", - "twq-NE", - "tzm-Latn", - "tzm-Latn-MA", - "vai-Latn", - "vai-Latn-LR", - "vai-Vaii", - "vai-Vaii-LR", - "vun-TZ", - "wae-CH", - "xog-UG", - "yav-CM", - "zgh-MA", - "af-NA", - "af-ZA", - "ak-GH", - "am-ET", - "ar-001", - "ar-AE", - "ar-BH", - "ar-DJ", - "ar-DZ", - "ar-EG", - "ar-EH", - "ar-ER", - "ar-IL", - "ar-IQ", - "ar-JO", - "ar-KM", - "ar-KW", - "ar-LB", - "ar-LY", - "ar-MA", - "ar-MR", - "ar-OM", - "ar-PS", - "ar-QA", - "ar-SA", - "ar-SD", - "ar-SO", - "ar-SS", - "ar-SY", - "ar-TD", - "ar-TN", - "ar-YE", - "as-IN", - "az-Cyrl", - "az-Cyrl-AZ", - "az-Latn", - "az-Latn-AZ", - "be-BY", - "bg-BG", - "bm-Latn", - "bm-Latn-ML", - "bn-BD", - "bn-IN", - "bo-CN", - "bo-IN", - "br-FR", - "bs-Cyrl", - "bs-Cyrl-BA", - "bs-Latn", - "bs-Latn-BA", - "ca-AD", - "ca-ES", - "ca-ES-VALENCIA", - "ca-FR", - "ca-IT", - "cs-CZ", - "cy-GB", - "da-DK", - "da-GL", - "de-AT", - "de-BE", - "de-CH", - "de-DE", - "de-LI", - "de-LU", - "dz-BT", - "ee-GH", - "ee-TG", - "el-CY", - "el-GR", - "en-001", - "en-150", - "en-AG", - "en-AI", - "en-AS", - "en-AU", - "en-BB", - "en-BE", - "en-BM", - "en-BS", - "en-BW", - "en-BZ", - "en-CA", - "en-CC", - "en-CK", - "en-CM", - "en-CX", - "en-DG", - "en-DM", - "en-ER", - "en-FJ", - "en-FK", - "en-FM", - "en-GB", - "en-GD", - "en-GG", - "en-GH", - "en-GI", - "en-GM", - "en-GU", - "en-GY", - "en-HK", - "en-IE", - "en-IM", - "en-IN", - "en-IO", - "en-JE", - "en-JM", - "en-KE", - "en-KI", - "en-KN", - "en-KY", - "en-LC", - "en-LR", - "en-LS", - "en-MG", - "en-MH", - "en-MO", - "en-MP", - "en-MS", - "en-MT", - "en-MU", - "en-MW", - "en-MY", - "en-NA", - "en-NF", - "en-NG", - "en-NR", - "en-NU", - "en-NZ", - "en-PG", - "en-PH", - "en-PK", - "en-PN", - "en-PR", - "en-PW", - "en-RW", - "en-SB", - "en-SC", - "en-SD", - "en-SG", - "en-SH", - "en-SL", - "en-SS", - "en-SX", - "en-SZ", - "en-TC", - "en-TK", - "en-TO", - "en-TT", - "en-TV", - "en-TZ", - "en-UG", - "en-UM", - "en-US", - "en-US-POSIX", - "en-VC", - "en-VG", - "en-VI", - "en-VU", - "en-WS", - "en-ZA", - "en-ZM", - "en-ZW", - "eo-001", - "es-419", - "es-AR", - "es-BO", - "es-CL", - "es-CO", - "es-CR", - "es-CU", - "es-DO", - "es-EA", - "es-EC", - "es-ES", - "es-GQ", - "es-GT", - "es-HN", - "es-IC", - "es-MX", - "es-NI", - "es-PA", - "es-PE", - "es-PH", - "es-PR", - "es-PY", - "es-SV", - "es-US", - "es-UY", - "es-VE", - "et-EE", - "eu-ES", - "fa-AF", - "fa-IR", - "ff-CM", - "ff-GN", - "ff-MR", - "ff-SN", - "fi-FI", - "fo-FO", - "fr-BE", - "fr-BF", - "fr-BI", - "fr-BJ", - "fr-BL", - "fr-CA", - "fr-CD", - "fr-CF", - "fr-CG", - "fr-CH", - "fr-CI", - "fr-CM", - "fr-DJ", - "fr-DZ", - "fr-FR", - "fr-GA", - "fr-GF", - "fr-GN", - "fr-GP", - "fr-GQ", - "fr-HT", - "fr-KM", - "fr-LU", - "fr-MA", - "fr-MC", - "fr-MF", - "fr-MG", - "fr-ML", - "fr-MQ", - "fr-MR", - "fr-MU", - "fr-NC", - "fr-NE", - "fr-PF", - "fr-PM", - "fr-RE", - "fr-RW", - "fr-SC", - "fr-SN", - "fr-SY", - "fr-TD", - "fr-TG", - "fr-TN", - "fr-VU", - "fr-WF", - "fr-YT", - "fy-NL", - "ga-IE", - "gd-GB", - "gl-ES", - "gu-IN", - "gv-IM", - "ha-Latn", - "ha-Latn-GH", - "ha-Latn-NE", - "ha-Latn-NG", - "he-IL", - "hi-IN", - "hr-BA", - "hr-HR", - "hu-HU", - "hy-AM", - "id-ID", - "ig-NG", - "ii-CN", - "is-IS", - "it-CH", - "it-IT", - "it-SM", - "ja-JP", - "ka-GE", - "ki-KE", - "kk-Cyrl", - "kk-Cyrl-KZ", - "kl-GL", - "km-KH", - "kn-IN", - "ko-KP", - "ko-KR", - "ks-Arab", - "ks-Arab-IN", - "kw-GB", - "ky-Cyrl", - "ky-Cyrl-KG", - "lb-LU", - "lg-UG", - "ln-AO", - "ln-CD", - "ln-CF", - "ln-CG", - "lo-LA", - "lt-LT", - "lu-CD", - "lv-LV", - "mg-MG", - "mk-MK", - "ml-IN", - "mn-Cyrl", - "mn-Cyrl-MN", - "mr-IN", - "ms-Latn", - "ms-Latn-BN", - "ms-Latn-MY", - "ms-Latn-SG", - "mt-MT", - "my-MM", - "nb-NO", - "nb-SJ", - "nd-ZW", - "ne-IN", - "ne-NP", - "nl-AW", - "nl-BE", - "nl-BQ", - "nl-CW", - "nl-NL", - "nl-SR", - "nl-SX", - "nn-NO", - "om-ET", - "om-KE", - "or-IN", - "os-GE", - "os-RU", - "pa-Arab", - "pa-Arab-PK", - "pa-Guru", - "pa-Guru-IN", - "pl-PL", - "ps-AF", - "pt-AO", - "pt-BR", - "pt-CV", - "pt-GW", - "pt-MO", - "pt-MZ", - "pt-PT", - "pt-ST", - "pt-TL", - "qu-BO", - "qu-EC", - "qu-PE", - "rm-CH", - "rn-BI", - "ro-MD", - "ro-RO", - "ru-BY", - "ru-KG", - "ru-KZ", - "ru-MD", - "ru-RU", - "ru-UA", - "rw-RW", - "se-FI", - "se-NO", - "se-SE", - "sg-CF", - "si-LK", - "sk-SK", - "sl-SI", - "sn-ZW", - "so-DJ", - "so-ET", - "so-KE", - "so-SO", - "sq-AL", - "sq-MK", - "sq-XK", - "sr-Cyrl", - "sr-Cyrl-BA", - "sr-Cyrl-ME", - "sr-Cyrl-RS", - "sr-Cyrl-XK", - "sr-Latn", - "sr-Latn-BA", - "sr-Latn-ME", - "sr-Latn-RS", - "sr-Latn-XK", - "sv-AX", - "sv-FI", - "sv-SE", - "sw-CD", - "sw-KE", - "sw-TZ", - "sw-UG", - "ta-IN", - "ta-LK", - "ta-MY", - "ta-SG", - "te-IN", - "th-TH", - "ti-ER", - "ti-ET", - "to-TO", - "tr-CY", - "tr-TR", - "ug-Arab", - "ug-Arab-CN", - "uk-UA", - "ur-IN", - "ur-PK", - "uz-Arab", - "uz-Arab-AF", - "uz-Cyrl", - "uz-Cyrl-UZ", - "uz-Latn", - "uz-Latn-UZ", - "vi-VN", - "yi-001", - "yo-BJ", - "yo-NG", - "zh-Hans", - "zh-Hans-CN", - "zh-Hans-HK", - "zh-Hans-MO", - "zh-Hans-SG", - "zh-Hant", - "zh-Hant-HK", - "zh-Hant-MO", - "zh-Hant-TW", - "zu-ZA" - ], - - us_states_and_dc: [ - {name: 'Alabama', abbreviation: 'AL'}, - {name: 'Alaska', abbreviation: 'AK'}, - {name: 'Arizona', abbreviation: 'AZ'}, - {name: 'Arkansas', abbreviation: 'AR'}, - {name: 'California', abbreviation: 'CA'}, - {name: 'Colorado', abbreviation: 'CO'}, - {name: 'Connecticut', abbreviation: 'CT'}, - {name: 'Delaware', abbreviation: 'DE'}, - {name: 'District of Columbia', abbreviation: 'DC'}, - {name: 'Florida', abbreviation: 'FL'}, - {name: 'Georgia', abbreviation: 'GA'}, - {name: 'Hawaii', abbreviation: 'HI'}, - {name: 'Idaho', abbreviation: 'ID'}, - {name: 'Illinois', abbreviation: 'IL'}, - {name: 'Indiana', abbreviation: 'IN'}, - {name: 'Iowa', abbreviation: 'IA'}, - {name: 'Kansas', abbreviation: 'KS'}, - {name: 'Kentucky', abbreviation: 'KY'}, - {name: 'Louisiana', abbreviation: 'LA'}, - {name: 'Maine', abbreviation: 'ME'}, - {name: 'Maryland', abbreviation: 'MD'}, - {name: 'Massachusetts', abbreviation: 'MA'}, - {name: 'Michigan', abbreviation: 'MI'}, - {name: 'Minnesota', abbreviation: 'MN'}, - {name: 'Mississippi', abbreviation: 'MS'}, - {name: 'Missouri', abbreviation: 'MO'}, - {name: 'Montana', abbreviation: 'MT'}, - {name: 'Nebraska', abbreviation: 'NE'}, - {name: 'Nevada', abbreviation: 'NV'}, - {name: 'New Hampshire', abbreviation: 'NH'}, - {name: 'New Jersey', abbreviation: 'NJ'}, - {name: 'New Mexico', abbreviation: 'NM'}, - {name: 'New York', abbreviation: 'NY'}, - {name: 'North Carolina', abbreviation: 'NC'}, - {name: 'North Dakota', abbreviation: 'ND'}, - {name: 'Ohio', abbreviation: 'OH'}, - {name: 'Oklahoma', abbreviation: 'OK'}, - {name: 'Oregon', abbreviation: 'OR'}, - {name: 'Pennsylvania', abbreviation: 'PA'}, - {name: 'Rhode Island', abbreviation: 'RI'}, - {name: 'South Carolina', abbreviation: 'SC'}, - {name: 'South Dakota', abbreviation: 'SD'}, - {name: 'Tennessee', abbreviation: 'TN'}, - {name: 'Texas', abbreviation: 'TX'}, - {name: 'Utah', abbreviation: 'UT'}, - {name: 'Vermont', abbreviation: 'VT'}, - {name: 'Virginia', abbreviation: 'VA'}, - {name: 'Washington', abbreviation: 'WA'}, - {name: 'West Virginia', abbreviation: 'WV'}, - {name: 'Wisconsin', abbreviation: 'WI'}, - {name: 'Wyoming', abbreviation: 'WY'} - ], - - territories: [ - {name: 'American Samoa', abbreviation: 'AS'}, - {name: 'Federated States of Micronesia', abbreviation: 'FM'}, - {name: 'Guam', abbreviation: 'GU'}, - {name: 'Marshall Islands', abbreviation: 'MH'}, - {name: 'Northern Mariana Islands', abbreviation: 'MP'}, - {name: 'Puerto Rico', abbreviation: 'PR'}, - {name: 'Virgin Islands, U.S.', abbreviation: 'VI'} - ], - - armed_forces: [ - {name: 'Armed Forces Europe', abbreviation: 'AE'}, - {name: 'Armed Forces Pacific', abbreviation: 'AP'}, - {name: 'Armed Forces the Americas', abbreviation: 'AA'} - ], - - country_regions: { - it: [ - { name: "Valle d'Aosta", abbreviation: "VDA" }, - { name: "Piemonte", abbreviation: "PIE" }, - { name: "Lombardia", abbreviation: "LOM" }, - { name: "Veneto", abbreviation: "VEN" }, - { name: "Trentino Alto Adige", abbreviation: "TAA" }, - { name: "Friuli Venezia Giulia", abbreviation: "FVG" }, - { name: "Liguria", abbreviation: "LIG" }, - { name: "Emilia Romagna", abbreviation: "EMR" }, - { name: "Toscana", abbreviation: "TOS" }, - { name: "Umbria", abbreviation: "UMB" }, - { name: "Marche", abbreviation: "MAR" }, - { name: "Abruzzo", abbreviation: "ABR" }, - { name: "Lazio", abbreviation: "LAZ" }, - { name: "Campania", abbreviation: "CAM" }, - { name: "Puglia", abbreviation: "PUG" }, - { name: "Basilicata", abbreviation: "BAS" }, - { name: "Molise", abbreviation: "MOL" }, - { name: "Calabria", abbreviation: "CAL" }, - { name: "Sicilia", abbreviation: "SIC" }, - { name: "Sardegna", abbreviation: "SAR" } - ], - mx: [ - { name: 'Aguascalientes', abbreviation: 'AGU' }, - { name: 'Baja California', abbreviation: 'BCN' }, - { name: 'Baja California Sur', abbreviation: 'BCS' }, - { name: 'Campeche', abbreviation: 'CAM' }, - { name: 'Chiapas', abbreviation: 'CHP' }, - { name: 'Chihuahua', abbreviation: 'CHH' }, - { name: 'Ciudad de MĆ©xico', abbreviation: 'DIF' }, - { name: 'Coahuila', abbreviation: 'COA' }, - { name: 'Colima', abbreviation: 'COL' }, - { name: 'Durango', abbreviation: 'DUR' }, - { name: 'Guanajuato', abbreviation: 'GUA' }, - { name: 'Guerrero', abbreviation: 'GRO' }, - { name: 'Hidalgo', abbreviation: 'HID' }, - { name: 'Jalisco', abbreviation: 'JAL' }, - { name: 'MĆ©xico', abbreviation: 'MEX' }, - { name: 'MichoacĆ”n', abbreviation: 'MIC' }, - { name: 'Morelos', abbreviation: 'MOR' }, - { name: 'Nayarit', abbreviation: 'NAY' }, - { name: 'Nuevo León', abbreviation: 'NLE' }, - { name: 'Oaxaca', abbreviation: 'OAX' }, - { name: 'Puebla', abbreviation: 'PUE' }, - { name: 'QuerĆ©taro', abbreviation: 'QUE' }, - { name: 'Quintana Roo', abbreviation: 'ROO' }, - { name: 'San Luis PotosĆ­', abbreviation: 'SLP' }, - { name: 'Sinaloa', abbreviation: 'SIN' }, - { name: 'Sonora', abbreviation: 'SON' }, - { name: 'Tabasco', abbreviation: 'TAB' }, - { name: 'Tamaulipas', abbreviation: 'TAM' }, - { name: 'Tlaxcala', abbreviation: 'TLA' }, - { name: 'Veracruz', abbreviation: 'VER' }, - { name: 'YucatĆ”n', abbreviation: 'YUC' }, - { name: 'Zacatecas', abbreviation: 'ZAC' } - ] - }, - - street_suffixes: { - 'us': [ - {name: 'Avenue', abbreviation: 'Ave'}, - {name: 'Boulevard', abbreviation: 'Blvd'}, - {name: 'Center', abbreviation: 'Ctr'}, - {name: 'Circle', abbreviation: 'Cir'}, - {name: 'Court', abbreviation: 'Ct'}, - {name: 'Drive', abbreviation: 'Dr'}, - {name: 'Extension', abbreviation: 'Ext'}, - {name: 'Glen', abbreviation: 'Gln'}, - {name: 'Grove', abbreviation: 'Grv'}, - {name: 'Heights', abbreviation: 'Hts'}, - {name: 'Highway', abbreviation: 'Hwy'}, - {name: 'Junction', abbreviation: 'Jct'}, - {name: 'Key', abbreviation: 'Key'}, - {name: 'Lane', abbreviation: 'Ln'}, - {name: 'Loop', abbreviation: 'Loop'}, - {name: 'Manor', abbreviation: 'Mnr'}, - {name: 'Mill', abbreviation: 'Mill'}, - {name: 'Park', abbreviation: 'Park'}, - {name: 'Parkway', abbreviation: 'Pkwy'}, - {name: 'Pass', abbreviation: 'Pass'}, - {name: 'Path', abbreviation: 'Path'}, - {name: 'Pike', abbreviation: 'Pike'}, - {name: 'Place', abbreviation: 'Pl'}, - {name: 'Plaza', abbreviation: 'Plz'}, - {name: 'Point', abbreviation: 'Pt'}, - {name: 'Ridge', abbreviation: 'Rdg'}, - {name: 'River', abbreviation: 'Riv'}, - {name: 'Road', abbreviation: 'Rd'}, - {name: 'Square', abbreviation: 'Sq'}, - {name: 'Street', abbreviation: 'St'}, - {name: 'Terrace', abbreviation: 'Ter'}, - {name: 'Trail', abbreviation: 'Trl'}, - {name: 'Turnpike', abbreviation: 'Tpke'}, - {name: 'View', abbreviation: 'Vw'}, - {name: 'Way', abbreviation: 'Way'} - ], - 'it': [ - { name: 'Accesso', abbreviation: 'Acc.' }, - { name: 'Alzaia', abbreviation: 'Alz.' }, - { name: 'Arco', abbreviation: 'Arco' }, - { name: 'Archivolto', abbreviation: 'Acv.' }, - { name: 'Arena', abbreviation: 'Arena' }, - { name: 'Argine', abbreviation: 'Argine' }, - { name: 'Bacino', abbreviation: 'Bacino' }, - { name: 'Banchi', abbreviation: 'Banchi' }, - { name: 'Banchina', abbreviation: 'Ban.' }, - { name: 'Bastioni', abbreviation: 'Bas.' }, - { name: 'Belvedere', abbreviation: 'Belv.' }, - { name: 'Borgata', abbreviation: 'B.ta' }, - { name: 'Borgo', abbreviation: 'B.go' }, - { name: 'Calata', abbreviation: 'Cal.' }, - { name: 'Calle', abbreviation: 'Calle' }, - { name: 'Campiello', abbreviation: 'Cam.' }, - { name: 'Campo', abbreviation: 'Cam.' }, - { name: 'Canale', abbreviation: 'Can.' }, - { name: 'Carraia', abbreviation: 'Carr.' }, - { name: 'Cascina', abbreviation: 'Cascina' }, - { name: 'Case sparse', abbreviation: 'c.s.' }, - { name: 'Cavalcavia', abbreviation: 'Cv.' }, - { name: 'Circonvallazione', abbreviation: 'Cv.' }, - { name: 'Complanare', abbreviation: 'C.re' }, - { name: 'Contrada', abbreviation: 'C.da' }, - { name: 'Corso', abbreviation: 'C.so' }, - { name: 'Corte', abbreviation: 'C.te' }, - { name: 'Cortile', abbreviation: 'C.le' }, - { name: 'Diramazione', abbreviation: 'Dir.' }, - { name: 'Fondaco', abbreviation: 'F.co' }, - { name: 'Fondamenta', abbreviation: 'F.ta' }, - { name: 'Fondo', abbreviation: 'F.do' }, - { name: 'Frazione', abbreviation: 'Fr.' }, - { name: 'Isola', abbreviation: 'Is.' }, - { name: 'Largo', abbreviation: 'L.go' }, - { name: 'Litoranea', abbreviation: 'Lit.' }, - { name: 'Lungolago', abbreviation: 'L.go lago' }, - { name: 'Lungo Po', abbreviation: 'l.go Po' }, - { name: 'Molo', abbreviation: 'Molo' }, - { name: 'Mura', abbreviation: 'Mura' }, - { name: 'Passaggio privato', abbreviation: 'pass. priv.' }, - { name: 'Passeggiata', abbreviation: 'Pass.' }, - { name: 'Piazza', abbreviation: 'P.zza' }, - { name: 'Piazzale', abbreviation: 'P.le' }, - { name: 'Ponte', abbreviation: 'P.te' }, - { name: 'Portico', abbreviation: 'P.co' }, - { name: 'Rampa', abbreviation: 'Rampa' }, - { name: 'Regione', abbreviation: 'Reg.' }, - { name: 'Rione', abbreviation: 'R.ne' }, - { name: 'Rio', abbreviation: 'Rio' }, - { name: 'Ripa', abbreviation: 'Ripa' }, - { name: 'Riva', abbreviation: 'Riva' }, - { name: 'Rondò', abbreviation: 'Rondò' }, - { name: 'Rotonda', abbreviation: 'Rot.' }, - { name: 'Sagrato', abbreviation: 'Sagr.' }, - { name: 'Salita', abbreviation: 'Sal.' }, - { name: 'Scalinata', abbreviation: 'Scal.' }, - { name: 'Scalone', abbreviation: 'Scal.' }, - { name: 'Slargo', abbreviation: 'Sl.' }, - { name: 'Sottoportico', abbreviation: 'Sott.' }, - { name: 'Strada', abbreviation: 'Str.' }, - { name: 'Stradale', abbreviation: 'Str.le' }, - { name: 'Strettoia', abbreviation: 'Strett.' }, - { name: 'Traversa', abbreviation: 'Trav.' }, - { name: 'Via', abbreviation: 'V.' }, - { name: 'Viale', abbreviation: 'V.le' }, - { name: 'Vicinale', abbreviation: 'Vic.le' }, - { name: 'Vicolo', abbreviation: 'Vic.' } - ], - 'uk' : [ - {name: 'Avenue', abbreviation: 'Ave'}, - {name: 'Close', abbreviation: 'Cl'}, - {name: 'Court', abbreviation: 'Ct'}, - {name: 'Crescent', abbreviation: 'Cr'}, - {name: 'Drive', abbreviation: 'Dr'}, - {name: 'Garden', abbreviation: 'Gdn'}, - {name: 'Gardens', abbreviation: 'Gdns'}, - {name: 'Green', abbreviation: 'Gn'}, - {name: 'Grove', abbreviation: 'Gr'}, - {name: 'Lane', abbreviation: 'Ln'}, - {name: 'Mount', abbreviation: 'Mt'}, - {name: 'Place', abbreviation: 'Pl'}, - {name: 'Park', abbreviation: 'Pk'}, - {name: 'Ridge', abbreviation: 'Rdg'}, - {name: 'Road', abbreviation: 'Rd'}, - {name: 'Square', abbreviation: 'Sq'}, - {name: 'Street', abbreviation: 'St'}, - {name: 'Terrace', abbreviation: 'Ter'}, - {name: 'Valley', abbreviation: 'Val'} - ] - }, - - months: [ - {name: 'January', short_name: 'Jan', numeric: '01', days: 31}, - // Not messing with leap years... - {name: 'February', short_name: 'Feb', numeric: '02', days: 28}, - {name: 'March', short_name: 'Mar', numeric: '03', days: 31}, - {name: 'April', short_name: 'Apr', numeric: '04', days: 30}, - {name: 'May', short_name: 'May', numeric: '05', days: 31}, - {name: 'June', short_name: 'Jun', numeric: '06', days: 30}, - {name: 'July', short_name: 'Jul', numeric: '07', days: 31}, - {name: 'August', short_name: 'Aug', numeric: '08', days: 31}, - {name: 'September', short_name: 'Sep', numeric: '09', days: 30}, - {name: 'October', short_name: 'Oct', numeric: '10', days: 31}, - {name: 'November', short_name: 'Nov', numeric: '11', days: 30}, - {name: 'December', short_name: 'Dec', numeric: '12', days: 31} - ], - - // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 - cc_types: [ - {name: "American Express", short_name: 'amex', prefix: '34', length: 15}, - {name: "Bankcard", short_name: 'bankcard', prefix: '5610', length: 16}, - {name: "China UnionPay", short_name: 'chinaunion', prefix: '62', length: 16}, - {name: "Diners Club Carte Blanche", short_name: 'dccarte', prefix: '300', length: 14}, - {name: "Diners Club enRoute", short_name: 'dcenroute', prefix: '2014', length: 15}, - {name: "Diners Club International", short_name: 'dcintl', prefix: '36', length: 14}, - {name: "Diners Club United States & Canada", short_name: 'dcusc', prefix: '54', length: 16}, - {name: "Discover Card", short_name: 'discover', prefix: '6011', length: 16}, - {name: "InstaPayment", short_name: 'instapay', prefix: '637', length: 16}, - {name: "JCB", short_name: 'jcb', prefix: '3528', length: 16}, - {name: "Laser", short_name: 'laser', prefix: '6304', length: 16}, - {name: "Maestro", short_name: 'maestro', prefix: '5018', length: 16}, - {name: "Mastercard", short_name: 'mc', prefix: '51', length: 16}, - {name: "Solo", short_name: 'solo', prefix: '6334', length: 16}, - {name: "Switch", short_name: 'switch', prefix: '4903', length: 16}, - {name: "Visa", short_name: 'visa', prefix: '4', length: 16}, - {name: "Visa Electron", short_name: 'electron', prefix: '4026', length: 16} - ], - - //return all world currency by ISO 4217 - currency_types: [ - {'code' : 'AED', 'name' : 'United Arab Emirates Dirham'}, - {'code' : 'AFN', 'name' : 'Afghanistan Afghani'}, - {'code' : 'ALL', 'name' : 'Albania Lek'}, - {'code' : 'AMD', 'name' : 'Armenia Dram'}, - {'code' : 'ANG', 'name' : 'Netherlands Antilles Guilder'}, - {'code' : 'AOA', 'name' : 'Angola Kwanza'}, - {'code' : 'ARS', 'name' : 'Argentina Peso'}, - {'code' : 'AUD', 'name' : 'Australia Dollar'}, - {'code' : 'AWG', 'name' : 'Aruba Guilder'}, - {'code' : 'AZN', 'name' : 'Azerbaijan New Manat'}, - {'code' : 'BAM', 'name' : 'Bosnia and Herzegovina Convertible Marka'}, - {'code' : 'BBD', 'name' : 'Barbados Dollar'}, - {'code' : 'BDT', 'name' : 'Bangladesh Taka'}, - {'code' : 'BGN', 'name' : 'Bulgaria Lev'}, - {'code' : 'BHD', 'name' : 'Bahrain Dinar'}, - {'code' : 'BIF', 'name' : 'Burundi Franc'}, - {'code' : 'BMD', 'name' : 'Bermuda Dollar'}, - {'code' : 'BND', 'name' : 'Brunei Darussalam Dollar'}, - {'code' : 'BOB', 'name' : 'Bolivia Boliviano'}, - {'code' : 'BRL', 'name' : 'Brazil Real'}, - {'code' : 'BSD', 'name' : 'Bahamas Dollar'}, - {'code' : 'BTN', 'name' : 'Bhutan Ngultrum'}, - {'code' : 'BWP', 'name' : 'Botswana Pula'}, - {'code' : 'BYR', 'name' : 'Belarus Ruble'}, - {'code' : 'BZD', 'name' : 'Belize Dollar'}, - {'code' : 'CAD', 'name' : 'Canada Dollar'}, - {'code' : 'CDF', 'name' : 'Congo/Kinshasa Franc'}, - {'code' : 'CHF', 'name' : 'Switzerland Franc'}, - {'code' : 'CLP', 'name' : 'Chile Peso'}, - {'code' : 'CNY', 'name' : 'China Yuan Renminbi'}, - {'code' : 'COP', 'name' : 'Colombia Peso'}, - {'code' : 'CRC', 'name' : 'Costa Rica Colon'}, - {'code' : 'CUC', 'name' : 'Cuba Convertible Peso'}, - {'code' : 'CUP', 'name' : 'Cuba Peso'}, - {'code' : 'CVE', 'name' : 'Cape Verde Escudo'}, - {'code' : 'CZK', 'name' : 'Czech Republic Koruna'}, - {'code' : 'DJF', 'name' : 'Djibouti Franc'}, - {'code' : 'DKK', 'name' : 'Denmark Krone'}, - {'code' : 'DOP', 'name' : 'Dominican Republic Peso'}, - {'code' : 'DZD', 'name' : 'Algeria Dinar'}, - {'code' : 'EGP', 'name' : 'Egypt Pound'}, - {'code' : 'ERN', 'name' : 'Eritrea Nakfa'}, - {'code' : 'ETB', 'name' : 'Ethiopia Birr'}, - {'code' : 'EUR', 'name' : 'Euro Member Countries'}, - {'code' : 'FJD', 'name' : 'Fiji Dollar'}, - {'code' : 'FKP', 'name' : 'Falkland Islands (Malvinas) Pound'}, - {'code' : 'GBP', 'name' : 'United Kingdom Pound'}, - {'code' : 'GEL', 'name' : 'Georgia Lari'}, - {'code' : 'GGP', 'name' : 'Guernsey Pound'}, - {'code' : 'GHS', 'name' : 'Ghana Cedi'}, - {'code' : 'GIP', 'name' : 'Gibraltar Pound'}, - {'code' : 'GMD', 'name' : 'Gambia Dalasi'}, - {'code' : 'GNF', 'name' : 'Guinea Franc'}, - {'code' : 'GTQ', 'name' : 'Guatemala Quetzal'}, - {'code' : 'GYD', 'name' : 'Guyana Dollar'}, - {'code' : 'HKD', 'name' : 'Hong Kong Dollar'}, - {'code' : 'HNL', 'name' : 'Honduras Lempira'}, - {'code' : 'HRK', 'name' : 'Croatia Kuna'}, - {'code' : 'HTG', 'name' : 'Haiti Gourde'}, - {'code' : 'HUF', 'name' : 'Hungary Forint'}, - {'code' : 'IDR', 'name' : 'Indonesia Rupiah'}, - {'code' : 'ILS', 'name' : 'Israel Shekel'}, - {'code' : 'IMP', 'name' : 'Isle of Man Pound'}, - {'code' : 'INR', 'name' : 'India Rupee'}, - {'code' : 'IQD', 'name' : 'Iraq Dinar'}, - {'code' : 'IRR', 'name' : 'Iran Rial'}, - {'code' : 'ISK', 'name' : 'Iceland Krona'}, - {'code' : 'JEP', 'name' : 'Jersey Pound'}, - {'code' : 'JMD', 'name' : 'Jamaica Dollar'}, - {'code' : 'JOD', 'name' : 'Jordan Dinar'}, - {'code' : 'JPY', 'name' : 'Japan Yen'}, - {'code' : 'KES', 'name' : 'Kenya Shilling'}, - {'code' : 'KGS', 'name' : 'Kyrgyzstan Som'}, - {'code' : 'KHR', 'name' : 'Cambodia Riel'}, - {'code' : 'KMF', 'name' : 'Comoros Franc'}, - {'code' : 'KPW', 'name' : 'Korea (North) Won'}, - {'code' : 'KRW', 'name' : 'Korea (South) Won'}, - {'code' : 'KWD', 'name' : 'Kuwait Dinar'}, - {'code' : 'KYD', 'name' : 'Cayman Islands Dollar'}, - {'code' : 'KZT', 'name' : 'Kazakhstan Tenge'}, - {'code' : 'LAK', 'name' : 'Laos Kip'}, - {'code' : 'LBP', 'name' : 'Lebanon Pound'}, - {'code' : 'LKR', 'name' : 'Sri Lanka Rupee'}, - {'code' : 'LRD', 'name' : 'Liberia Dollar'}, - {'code' : 'LSL', 'name' : 'Lesotho Loti'}, - {'code' : 'LTL', 'name' : 'Lithuania Litas'}, - {'code' : 'LYD', 'name' : 'Libya Dinar'}, - {'code' : 'MAD', 'name' : 'Morocco Dirham'}, - {'code' : 'MDL', 'name' : 'Moldova Leu'}, - {'code' : 'MGA', 'name' : 'Madagascar Ariary'}, - {'code' : 'MKD', 'name' : 'Macedonia Denar'}, - {'code' : 'MMK', 'name' : 'Myanmar (Burma) Kyat'}, - {'code' : 'MNT', 'name' : 'Mongolia Tughrik'}, - {'code' : 'MOP', 'name' : 'Macau Pataca'}, - {'code' : 'MRO', 'name' : 'Mauritania Ouguiya'}, - {'code' : 'MUR', 'name' : 'Mauritius Rupee'}, - {'code' : 'MVR', 'name' : 'Maldives (Maldive Islands) Rufiyaa'}, - {'code' : 'MWK', 'name' : 'Malawi Kwacha'}, - {'code' : 'MXN', 'name' : 'Mexico Peso'}, - {'code' : 'MYR', 'name' : 'Malaysia Ringgit'}, - {'code' : 'MZN', 'name' : 'Mozambique Metical'}, - {'code' : 'NAD', 'name' : 'Namibia Dollar'}, - {'code' : 'NGN', 'name' : 'Nigeria Naira'}, - {'code' : 'NIO', 'name' : 'Nicaragua Cordoba'}, - {'code' : 'NOK', 'name' : 'Norway Krone'}, - {'code' : 'NPR', 'name' : 'Nepal Rupee'}, - {'code' : 'NZD', 'name' : 'New Zealand Dollar'}, - {'code' : 'OMR', 'name' : 'Oman Rial'}, - {'code' : 'PAB', 'name' : 'Panama Balboa'}, - {'code' : 'PEN', 'name' : 'Peru Nuevo Sol'}, - {'code' : 'PGK', 'name' : 'Papua New Guinea Kina'}, - {'code' : 'PHP', 'name' : 'Philippines Peso'}, - {'code' : 'PKR', 'name' : 'Pakistan Rupee'}, - {'code' : 'PLN', 'name' : 'Poland Zloty'}, - {'code' : 'PYG', 'name' : 'Paraguay Guarani'}, - {'code' : 'QAR', 'name' : 'Qatar Riyal'}, - {'code' : 'RON', 'name' : 'Romania New Leu'}, - {'code' : 'RSD', 'name' : 'Serbia Dinar'}, - {'code' : 'RUB', 'name' : 'Russia Ruble'}, - {'code' : 'RWF', 'name' : 'Rwanda Franc'}, - {'code' : 'SAR', 'name' : 'Saudi Arabia Riyal'}, - {'code' : 'SBD', 'name' : 'Solomon Islands Dollar'}, - {'code' : 'SCR', 'name' : 'Seychelles Rupee'}, - {'code' : 'SDG', 'name' : 'Sudan Pound'}, - {'code' : 'SEK', 'name' : 'Sweden Krona'}, - {'code' : 'SGD', 'name' : 'Singapore Dollar'}, - {'code' : 'SHP', 'name' : 'Saint Helena Pound'}, - {'code' : 'SLL', 'name' : 'Sierra Leone Leone'}, - {'code' : 'SOS', 'name' : 'Somalia Shilling'}, - {'code' : 'SPL', 'name' : 'Seborga Luigino'}, - {'code' : 'SRD', 'name' : 'Suriname Dollar'}, - {'code' : 'STD', 'name' : 'SĆ£o TomĆ© and PrĆ­ncipe Dobra'}, - {'code' : 'SVC', 'name' : 'El Salvador Colon'}, - {'code' : 'SYP', 'name' : 'Syria Pound'}, - {'code' : 'SZL', 'name' : 'Swaziland Lilangeni'}, - {'code' : 'THB', 'name' : 'Thailand Baht'}, - {'code' : 'TJS', 'name' : 'Tajikistan Somoni'}, - {'code' : 'TMT', 'name' : 'Turkmenistan Manat'}, - {'code' : 'TND', 'name' : 'Tunisia Dinar'}, - {'code' : 'TOP', 'name' : 'Tonga Pa\'anga'}, - {'code' : 'TRY', 'name' : 'Turkey Lira'}, - {'code' : 'TTD', 'name' : 'Trinidad and Tobago Dollar'}, - {'code' : 'TVD', 'name' : 'Tuvalu Dollar'}, - {'code' : 'TWD', 'name' : 'Taiwan New Dollar'}, - {'code' : 'TZS', 'name' : 'Tanzania Shilling'}, - {'code' : 'UAH', 'name' : 'Ukraine Hryvnia'}, - {'code' : 'UGX', 'name' : 'Uganda Shilling'}, - {'code' : 'USD', 'name' : 'United States Dollar'}, - {'code' : 'UYU', 'name' : 'Uruguay Peso'}, - {'code' : 'UZS', 'name' : 'Uzbekistan Som'}, - {'code' : 'VEF', 'name' : 'Venezuela Bolivar'}, - {'code' : 'VND', 'name' : 'Viet Nam Dong'}, - {'code' : 'VUV', 'name' : 'Vanuatu Vatu'}, - {'code' : 'WST', 'name' : 'Samoa Tala'}, - {'code' : 'XAF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BEAC) CFA Franc BEAC'}, - {'code' : 'XCD', 'name' : 'East Caribbean Dollar'}, - {'code' : 'XDR', 'name' : 'International Monetary Fund (IMF) Special Drawing Rights'}, - {'code' : 'XOF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BCEAO) Franc'}, - {'code' : 'XPF', 'name' : 'Comptoirs FranƧais du Pacifique (CFP) Franc'}, - {'code' : 'YER', 'name' : 'Yemen Rial'}, - {'code' : 'ZAR', 'name' : 'South Africa Rand'}, - {'code' : 'ZMW', 'name' : 'Zambia Kwacha'}, - {'code' : 'ZWD', 'name' : 'Zimbabwe Dollar'} - ], - - // return the names of all valide colors - colorNames : [ "AliceBlue", "Black", "Navy", "DarkBlue", "MediumBlue", "Blue", "DarkGreen", "Green", "Teal", "DarkCyan", "DeepSkyBlue", "DarkTurquoise", "MediumSpringGreen", "Lime", "SpringGreen", - "Aqua", "Cyan", "MidnightBlue", "DodgerBlue", "LightSeaGreen", "ForestGreen", "SeaGreen", "DarkSlateGray", "LimeGreen", "MediumSeaGreen", "Turquoise", "RoyalBlue", "SteelBlue", "DarkSlateBlue", "MediumTurquoise", - "Indigo", "DarkOliveGreen", "CadetBlue", "CornflowerBlue", "RebeccaPurple", "MediumAquaMarine", "DimGray", "SlateBlue", "OliveDrab", "SlateGray", "LightSlateGray", "MediumSlateBlue", "LawnGreen", "Chartreuse", - "Aquamarine", "Maroon", "Purple", "Olive", "Gray", "SkyBlue", "LightSkyBlue", "BlueViolet", "DarkRed", "DarkMagenta", "SaddleBrown", "Ivory", "White", - "DarkSeaGreen", "LightGreen", "MediumPurple", "DarkViolet", "PaleGreen", "DarkOrchid", "YellowGreen", "Sienna", "Brown", "DarkGray", "LightBlue", "GreenYellow", "PaleTurquoise", "LightSteelBlue", "PowderBlue", - "FireBrick", "DarkGoldenRod", "MediumOrchid", "RosyBrown", "DarkKhaki", "Silver", "MediumVioletRed", "IndianRed", "Peru", "Chocolate", "Tan", "LightGray", "Thistle", "Orchid", "GoldenRod", "PaleVioletRed", - "Crimson", "Gainsboro", "Plum", "BurlyWood", "LightCyan", "Lavender", "DarkSalmon", "Violet", "PaleGoldenRod", "LightCoral", "Khaki", "AliceBlue", "HoneyDew", "Azure", "SandyBrown", "Wheat", "Beige", "WhiteSmoke", - "MintCream", "GhostWhite", "Salmon", "AntiqueWhite", "Linen", "LightGoldenRodYellow", "OldLace", "Red", "Fuchsia", "Magenta", "DeepPink", "OrangeRed", "Tomato", "HotPink", "Coral", "DarkOrange", "LightSalmon", "Orange", - "LightPink", "Pink", "Gold", "PeachPuff", "NavajoWhite", "Moccasin", "Bisque", "MistyRose", "BlanchedAlmond", "PapayaWhip", "LavenderBlush", "SeaShell", "Cornsilk", "LemonChiffon", "FloralWhite", "Snow", "Yellow", "LightYellow" - ], - - // Data taken from https://www.sec.gov/rules/other/4-460list.htm - company: [ "3Com Corp", - "3M Company", - "A.G. Edwards Inc.", - "Abbott Laboratories", - "Abercrombie & Fitch Co.", - "ABM Industries Incorporated", - "Ace Hardware Corporation", - "ACT Manufacturing Inc.", - "Acterna Corp.", - "Adams Resources & Energy, Inc.", - "ADC Telecommunications, Inc.", - "Adelphia Communications Corporation", - "Administaff, Inc.", - "Adobe Systems Incorporated", - "Adolph Coors Company", - "Advance Auto Parts, Inc.", - "Advanced Micro Devices, Inc.", - "AdvancePCS, Inc.", - "Advantica Restaurant Group, Inc.", - "The AES Corporation", - "Aetna Inc.", - "Affiliated Computer Services, Inc.", - "AFLAC Incorporated", - "AGCO Corporation", - "Agilent Technologies, Inc.", - "Agway Inc.", - "Apartment Investment and Management Company", - "Air Products and Chemicals, Inc.", - "Airborne, Inc.", - "Airgas, Inc.", - "AK Steel Holding Corporation", - "Alaska Air Group, Inc.", - "Alberto-Culver Company", - "Albertson's, Inc.", - "Alcoa Inc.", - "Alleghany Corporation", - "Allegheny Energy, Inc.", - "Allegheny Technologies Incorporated", - "Allergan, Inc.", - "ALLETE, Inc.", - "Alliant Energy Corporation", - "Allied Waste Industries, Inc.", - "Allmerica Financial Corporation", - "The Allstate Corporation", - "ALLTEL Corporation", - "The Alpine Group, Inc.", - "Amazon.com, Inc.", - "AMC Entertainment Inc.", - "American Power Conversion Corporation", - "Amerada Hess Corporation", - "AMERCO", - "Ameren Corporation", - "America West Holdings Corporation", - "American Axle & Manufacturing Holdings, Inc.", - "American Eagle Outfitters, Inc.", - "American Electric Power Company, Inc.", - "American Express Company", - "American Financial Group, Inc.", - "American Greetings Corporation", - "American International Group, Inc.", - "American Standard Companies Inc.", - "American Water Works Company, Inc.", - "AmerisourceBergen Corporation", - "Ames Department Stores, Inc.", - "Amgen Inc.", - "Amkor Technology, Inc.", - "AMR Corporation", - "AmSouth Bancorp.", - "Amtran, Inc.", - "Anadarko Petroleum Corporation", - "Analog Devices, Inc.", - "Anheuser-Busch Companies, Inc.", - "Anixter International Inc.", - "AnnTaylor Inc.", - "Anthem, Inc.", - "AOL Time Warner Inc.", - "Aon Corporation", - "Apache Corporation", - "Apple Computer, Inc.", - "Applera Corporation", - "Applied Industrial Technologies, Inc.", - "Applied Materials, Inc.", - "Aquila, Inc.", - "ARAMARK Corporation", - "Arch Coal, Inc.", - "Archer Daniels Midland Company", - "Arkansas Best Corporation", - "Armstrong Holdings, Inc.", - "Arrow Electronics, Inc.", - "ArvinMeritor, Inc.", - "Ashland Inc.", - "Astoria Financial Corporation", - "AT&T Corp.", - "Atmel Corporation", - "Atmos Energy Corporation", - "Audiovox Corporation", - "Autoliv, Inc.", - "Automatic Data Processing, Inc.", - "AutoNation, Inc.", - "AutoZone, Inc.", - "Avaya Inc.", - "Avery Dennison Corporation", - "Avista Corporation", - "Avnet, Inc.", - "Avon Products, Inc.", - "Baker Hughes Incorporated", - "Ball Corporation", - "Bank of America Corporation", - "The Bank of New York Company, Inc.", - "Bank One Corporation", - "Banknorth Group, Inc.", - "Banta Corporation", - "Barnes & Noble, Inc.", - "Bausch & Lomb Incorporated", - "Baxter International Inc.", - "BB&T Corporation", - "The Bear Stearns Companies Inc.", - "Beazer Homes USA, Inc.", - "Beckman Coulter, Inc.", - "Becton, Dickinson and Company", - "Bed Bath & Beyond Inc.", - "Belk, Inc.", - "Bell Microproducts Inc.", - "BellSouth Corporation", - "Belo Corp.", - "Bemis Company, Inc.", - "Benchmark Electronics, Inc.", - "Berkshire Hathaway Inc.", - "Best Buy Co., Inc.", - "Bethlehem Steel Corporation", - "Beverly Enterprises, Inc.", - "Big Lots, Inc.", - "BJ Services Company", - "BJ's Wholesale Club, Inc.", - "The Black & Decker Corporation", - "Black Hills Corporation", - "BMC Software, Inc.", - "The Boeing Company", - "Boise Cascade Corporation", - "Borders Group, Inc.", - "BorgWarner Inc.", - "Boston Scientific Corporation", - "Bowater Incorporated", - "Briggs & Stratton Corporation", - "Brightpoint, Inc.", - "Brinker International, Inc.", - "Bristol-Myers Squibb Company", - "Broadwing, Inc.", - "Brown Shoe Company, Inc.", - "Brown-Forman Corporation", - "Brunswick Corporation", - "Budget Group, Inc.", - "Burlington Coat Factory Warehouse Corporation", - "Burlington Industries, Inc.", - "Burlington Northern Santa Fe Corporation", - "Burlington Resources Inc.", - "C. H. Robinson Worldwide Inc.", - "Cablevision Systems Corp", - "Cabot Corp", - "Cadence Design Systems, Inc.", - "Calpine Corp.", - "Campbell Soup Co.", - "Capital One Financial Corp.", - "Cardinal Health Inc.", - "Caremark Rx Inc.", - "Carlisle Cos. Inc.", - "Carpenter Technology Corp.", - "Casey's General Stores Inc.", - "Caterpillar Inc.", - "CBRL Group Inc.", - "CDI Corp.", - "CDW Computer Centers Inc.", - "CellStar Corp.", - "Cendant Corp", - "Cenex Harvest States Cooperatives", - "Centex Corp.", - "CenturyTel Inc.", - "Ceridian Corp.", - "CH2M Hill Cos. Ltd.", - "Champion Enterprises Inc.", - "Charles Schwab Corp.", - "Charming Shoppes Inc.", - "Charter Communications Inc.", - "Charter One Financial Inc.", - "ChevronTexaco Corp.", - "Chiquita Brands International Inc.", - "Chubb Corp", - "Ciena Corp.", - "Cigna Corp", - "Cincinnati Financial Corp.", - "Cinergy Corp.", - "Cintas Corp.", - "Circuit City Stores Inc.", - "Cisco Systems Inc.", - "Citigroup, Inc", - "Citizens Communications Co.", - "CKE Restaurants Inc.", - "Clear Channel Communications Inc.", - "The Clorox Co.", - "CMGI Inc.", - "CMS Energy Corp.", - "CNF Inc.", - "Coca-Cola Co.", - "Coca-Cola Enterprises Inc.", - "Colgate-Palmolive Co.", - "Collins & Aikman Corp.", - "Comcast Corp.", - "Comdisco Inc.", - "Comerica Inc.", - "Comfort Systems USA Inc.", - "Commercial Metals Co.", - "Community Health Systems Inc.", - "Compass Bancshares Inc", - "Computer Associates International Inc.", - "Computer Sciences Corp.", - "Compuware Corp.", - "Comverse Technology Inc.", - "ConAgra Foods Inc.", - "Concord EFS Inc.", - "Conectiv, Inc", - "Conoco Inc", - "Conseco Inc.", - "Consolidated Freightways Corp.", - "Consolidated Edison Inc.", - "Constellation Brands Inc.", - "Constellation Emergy Group Inc.", - "Continental Airlines Inc.", - "Convergys Corp.", - "Cooper Cameron Corp.", - "Cooper Industries Ltd.", - "Cooper Tire & Rubber Co.", - "Corn Products International Inc.", - "Corning Inc.", - "Costco Wholesale Corp.", - "Countrywide Credit Industries Inc.", - "Coventry Health Care Inc.", - "Cox Communications Inc.", - "Crane Co.", - "Crompton Corp.", - "Crown Cork & Seal Co. Inc.", - "CSK Auto Corp.", - "CSX Corp.", - "Cummins Inc.", - "CVS Corp.", - "Cytec Industries Inc.", - "D&K Healthcare Resources, Inc.", - "D.R. Horton Inc.", - "Dana Corporation", - "Danaher Corporation", - "Darden Restaurants Inc.", - "DaVita Inc.", - "Dean Foods Company", - "Deere & Company", - "Del Monte Foods Co", - "Dell Computer Corporation", - "Delphi Corp.", - "Delta Air Lines Inc.", - "Deluxe Corporation", - "Devon Energy Corporation", - "Di Giorgio Corporation", - "Dial Corporation", - "Diebold Incorporated", - "Dillard's Inc.", - "DIMON Incorporated", - "Dole Food Company, Inc.", - "Dollar General Corporation", - "Dollar Tree Stores, Inc.", - "Dominion Resources, Inc.", - "Domino's Pizza LLC", - "Dover Corporation, Inc.", - "Dow Chemical Company", - "Dow Jones & Company, Inc.", - "DPL Inc.", - "DQE Inc.", - "Dreyer's Grand Ice Cream, Inc.", - "DST Systems, Inc.", - "DTE Energy Co.", - "E.I. Du Pont de Nemours and Company", - "Duke Energy Corp", - "Dun & Bradstreet Inc.", - "DURA Automotive Systems Inc.", - "DynCorp", - "Dynegy Inc.", - "E*Trade Group, Inc.", - "E.W. Scripps Company", - "Earthlink, Inc.", - "Eastman Chemical Company", - "Eastman Kodak Company", - "Eaton Corporation", - "Echostar Communications Corporation", - "Ecolab Inc.", - "Edison International", - "EGL Inc.", - "El Paso Corporation", - "Electronic Arts Inc.", - "Electronic Data Systems Corp.", - "Eli Lilly and Company", - "EMC Corporation", - "Emcor Group Inc.", - "Emerson Electric Co.", - "Encompass Services Corporation", - "Energizer Holdings Inc.", - "Energy East Corporation", - "Engelhard Corporation", - "Enron Corp.", - "Entergy Corporation", - "Enterprise Products Partners L.P.", - "EOG Resources, Inc.", - "Equifax Inc.", - "Equitable Resources Inc.", - "Equity Office Properties Trust", - "Equity Residential Properties Trust", - "Estee Lauder Companies Inc.", - "Exelon Corporation", - "Exide Technologies", - "Expeditors International of Washington Inc.", - "Express Scripts Inc.", - "ExxonMobil Corporation", - "Fairchild Semiconductor International Inc.", - "Family Dollar Stores Inc.", - "Farmland Industries Inc.", - "Federal Mogul Corp.", - "Federated Department Stores Inc.", - "Federal Express Corp.", - "Felcor Lodging Trust Inc.", - "Ferro Corp.", - "Fidelity National Financial Inc.", - "Fifth Third Bancorp", - "First American Financial Corp.", - "First Data Corp.", - "First National of Nebraska Inc.", - "First Tennessee National Corp.", - "FirstEnergy Corp.", - "Fiserv Inc.", - "Fisher Scientific International Inc.", - "FleetBoston Financial Co.", - "Fleetwood Enterprises Inc.", - "Fleming Companies Inc.", - "Flowers Foods Inc.", - "Flowserv Corp", - "Fluor Corp", - "FMC Corp", - "Foamex International Inc", - "Foot Locker Inc", - "Footstar Inc.", - "Ford Motor Co", - "Forest Laboratories Inc.", - "Fortune Brands Inc.", - "Foster Wheeler Ltd.", - "FPL Group Inc.", - "Franklin Resources Inc.", - "Freeport McMoran Copper & Gold Inc.", - "Frontier Oil Corp", - "Furniture Brands International Inc.", - "Gannett Co., Inc.", - "Gap Inc.", - "Gateway Inc.", - "GATX Corporation", - "Gemstar-TV Guide International Inc.", - "GenCorp Inc.", - "General Cable Corporation", - "General Dynamics Corporation", - "General Electric Company", - "General Mills Inc", - "General Motors Corporation", - "Genesis Health Ventures Inc.", - "Gentek Inc.", - "Gentiva Health Services Inc.", - "Genuine Parts Company", - "Genuity Inc.", - "Genzyme Corporation", - "Georgia Gulf Corporation", - "Georgia-Pacific Corporation", - "Gillette Company", - "Gold Kist Inc.", - "Golden State Bancorp Inc.", - "Golden West Financial Corporation", - "Goldman Sachs Group Inc.", - "Goodrich Corporation", - "The Goodyear Tire & Rubber Company", - "Granite Construction Incorporated", - "Graybar Electric Company Inc.", - "Great Lakes Chemical Corporation", - "Great Plains Energy Inc.", - "GreenPoint Financial Corp.", - "Greif Bros. Corporation", - "Grey Global Group Inc.", - "Group 1 Automotive Inc.", - "Guidant Corporation", - "H&R Block Inc.", - "H.B. Fuller Company", - "H.J. Heinz Company", - "Halliburton Co.", - "Harley-Davidson Inc.", - "Harman International Industries Inc.", - "Harrah's Entertainment Inc.", - "Harris Corp.", - "Harsco Corp.", - "Hartford Financial Services Group Inc.", - "Hasbro Inc.", - "Hawaiian Electric Industries Inc.", - "HCA Inc.", - "Health Management Associates Inc.", - "Health Net Inc.", - "Healthsouth Corp", - "Henry Schein Inc.", - "Hercules Inc.", - "Herman Miller Inc.", - "Hershey Foods Corp.", - "Hewlett-Packard Company", - "Hibernia Corp.", - "Hillenbrand Industries Inc.", - "Hilton Hotels Corp.", - "Hollywood Entertainment Corp.", - "Home Depot Inc.", - "Hon Industries Inc.", - "Honeywell International Inc.", - "Hormel Foods Corp.", - "Host Marriott Corp.", - "Household International Corp.", - "Hovnanian Enterprises Inc.", - "Hub Group Inc.", - "Hubbell Inc.", - "Hughes Supply Inc.", - "Humana Inc.", - "Huntington Bancshares Inc.", - "Idacorp Inc.", - "IDT Corporation", - "IKON Office Solutions Inc.", - "Illinois Tool Works Inc.", - "IMC Global Inc.", - "Imperial Sugar Company", - "IMS Health Inc.", - "Ingles Market Inc", - "Ingram Micro Inc.", - "Insight Enterprises Inc.", - "Integrated Electrical Services Inc.", - "Intel Corporation", - "International Paper Co.", - "Interpublic Group of Companies Inc.", - "Interstate Bakeries Corporation", - "International Business Machines Corp.", - "International Flavors & Fragrances Inc.", - "International Multifoods Corporation", - "Intuit Inc.", - "IT Group Inc.", - "ITT Industries Inc.", - "Ivax Corp.", - "J.B. Hunt Transport Services Inc.", - "J.C. Penny Co.", - "J.P. Morgan Chase & Co.", - "Jabil Circuit Inc.", - "Jack In The Box Inc.", - "Jacobs Engineering Group Inc.", - "JDS Uniphase Corp.", - "Jefferson-Pilot Co.", - "John Hancock Financial Services Inc.", - "Johnson & Johnson", - "Johnson Controls Inc.", - "Jones Apparel Group Inc.", - "KB Home", - "Kellogg Company", - "Kellwood Company", - "Kelly Services Inc.", - "Kemet Corp.", - "Kennametal Inc.", - "Kerr-McGee Corporation", - "KeyCorp", - "KeySpan Corp.", - "Kimball International Inc.", - "Kimberly-Clark Corporation", - "Kindred Healthcare Inc.", - "KLA-Tencor Corporation", - "K-Mart Corp.", - "Knight-Ridder Inc.", - "Kohl's Corp.", - "KPMG Consulting Inc.", - "Kroger Co.", - "L-3 Communications Holdings Inc.", - "Laboratory Corporation of America Holdings", - "Lam Research Corporation", - "LandAmerica Financial Group Inc.", - "Lands' End Inc.", - "Landstar System Inc.", - "La-Z-Boy Inc.", - "Lear Corporation", - "Legg Mason Inc.", - "Leggett & Platt Inc.", - "Lehman Brothers Holdings Inc.", - "Lennar Corporation", - "Lennox International Inc.", - "Level 3 Communications Inc.", - "Levi Strauss & Co.", - "Lexmark International Inc.", - "Limited Inc.", - "Lincoln National Corporation", - "Linens 'n Things Inc.", - "Lithia Motors Inc.", - "Liz Claiborne Inc.", - "Lockheed Martin Corporation", - "Loews Corporation", - "Longs Drug Stores Corporation", - "Louisiana-Pacific Corporation", - "Lowe's Companies Inc.", - "LSI Logic Corporation", - "The LTV Corporation", - "The Lubrizol Corporation", - "Lucent Technologies Inc.", - "Lyondell Chemical Company", - "M & T Bank Corporation", - "Magellan Health Services Inc.", - "Mail-Well Inc.", - "Mandalay Resort Group", - "Manor Care Inc.", - "Manpower Inc.", - "Marathon Oil Corporation", - "Mariner Health Care Inc.", - "Markel Corporation", - "Marriott International Inc.", - "Marsh & McLennan Companies Inc.", - "Marsh Supermarkets Inc.", - "Marshall & Ilsley Corporation", - "Martin Marietta Materials Inc.", - "Masco Corporation", - "Massey Energy Company", - "MasTec Inc.", - "Mattel Inc.", - "Maxim Integrated Products Inc.", - "Maxtor Corporation", - "Maxxam Inc.", - "The May Department Stores Company", - "Maytag Corporation", - "MBNA Corporation", - "McCormick & Company Incorporated", - "McDonald's Corporation", - "The McGraw-Hill Companies Inc.", - "McKesson Corporation", - "McLeodUSA Incorporated", - "M.D.C. Holdings Inc.", - "MDU Resources Group Inc.", - "MeadWestvaco Corporation", - "Medtronic Inc.", - "Mellon Financial Corporation", - "The Men's Wearhouse Inc.", - "Merck & Co., Inc.", - "Mercury General Corporation", - "Merrill Lynch & Co. Inc.", - "Metaldyne Corporation", - "Metals USA Inc.", - "MetLife Inc.", - "Metris Companies Inc", - "MGIC Investment Corporation", - "MGM Mirage", - "Michaels Stores Inc.", - "Micron Technology Inc.", - "Microsoft Corporation", - "Milacron Inc.", - "Millennium Chemicals Inc.", - "Mirant Corporation", - "Mohawk Industries Inc.", - "Molex Incorporated", - "The MONY Group Inc.", - "Morgan Stanley Dean Witter & Co.", - "Motorola Inc.", - "MPS Group Inc.", - "Murphy Oil Corporation", - "Nabors Industries Inc", - "Nacco Industries Inc", - "Nash Finch Company", - "National City Corp.", - "National Commerce Financial Corporation", - "National Fuel Gas Company", - "National Oilwell Inc", - "National Rural Utilities Cooperative Finance Corporation", - "National Semiconductor Corporation", - "National Service Industries Inc", - "Navistar International Corporation", - "NCR Corporation", - "The Neiman Marcus Group Inc.", - "New Jersey Resources Corporation", - "New York Times Company", - "Newell Rubbermaid Inc", - "Newmont Mining Corporation", - "Nextel Communications Inc", - "Nicor Inc", - "Nike Inc", - "NiSource Inc", - "Noble Energy Inc", - "Nordstrom Inc", - "Norfolk Southern Corporation", - "Nortek Inc", - "North Fork Bancorporation Inc", - "Northeast Utilities System", - "Northern Trust Corporation", - "Northrop Grumman Corporation", - "NorthWestern Corporation", - "Novellus Systems Inc", - "NSTAR", - "NTL Incorporated", - "Nucor Corp", - "Nvidia Corp", - "NVR Inc", - "Northwest Airlines Corp", - "Occidental Petroleum Corp", - "Ocean Energy Inc", - "Office Depot Inc.", - "OfficeMax Inc", - "OGE Energy Corp", - "Oglethorpe Power Corp.", - "Ohio Casualty Corp.", - "Old Republic International Corp.", - "Olin Corp.", - "OM Group Inc", - "Omnicare Inc", - "Omnicom Group", - "On Semiconductor Corp", - "ONEOK Inc", - "Oracle Corp", - "Oshkosh Truck Corp", - "Outback Steakhouse Inc.", - "Owens & Minor Inc.", - "Owens Corning", - "Owens-Illinois Inc", - "Oxford Health Plans Inc", - "Paccar Inc", - "PacifiCare Health Systems Inc", - "Packaging Corp. of America", - "Pactiv Corp", - "Pall Corp", - "Pantry Inc", - "Park Place Entertainment Corp", - "Parker Hannifin Corp.", - "Pathmark Stores Inc.", - "Paychex Inc", - "Payless Shoesource Inc", - "Penn Traffic Co.", - "Pennzoil-Quaker State Company", - "Pentair Inc", - "Peoples Energy Corp.", - "PeopleSoft Inc", - "Pep Boys Manny, Moe & Jack", - "Potomac Electric Power Co.", - "Pepsi Bottling Group Inc.", - "PepsiAmericas Inc.", - "PepsiCo Inc.", - "Performance Food Group Co.", - "Perini Corp", - "PerkinElmer Inc", - "Perot Systems Corp", - "Petco Animal Supplies Inc.", - "Peter Kiewit Sons', Inc.", - "PETsMART Inc", - "Pfizer Inc", - "Pacific Gas & Electric Corp.", - "Pharmacia Corp", - "Phar Mor Inc.", - "Phelps Dodge Corp.", - "Philip Morris Companies Inc.", - "Phillips Petroleum Co", - "Phillips Van Heusen Corp.", - "Phoenix Companies Inc", - "Pier 1 Imports Inc.", - "Pilgrim's Pride Corporation", - "Pinnacle West Capital Corp", - "Pioneer-Standard Electronics Inc.", - "Pitney Bowes Inc.", - "Pittston Brinks Group", - "Plains All American Pipeline LP", - "PNC Financial Services Group Inc.", - "PNM Resources Inc", - "Polaris Industries Inc.", - "Polo Ralph Lauren Corp", - "PolyOne Corp", - "Popular Inc", - "Potlatch Corp", - "PPG Industries Inc", - "PPL Corp", - "Praxair Inc", - "Precision Castparts Corp", - "Premcor Inc.", - "Pride International Inc", - "Primedia Inc", - "Principal Financial Group Inc.", - "Procter & Gamble Co.", - "Pro-Fac Cooperative Inc.", - "Progress Energy Inc", - "Progressive Corporation", - "Protective Life Corp", - "Provident Financial Group", - "Providian Financial Corp.", - "Prudential Financial Inc.", - "PSS World Medical Inc", - "Public Service Enterprise Group Inc.", - "Publix Super Markets Inc.", - "Puget Energy Inc.", - "Pulte Homes Inc", - "Qualcomm Inc", - "Quanta Services Inc.", - "Quantum Corp", - "Quest Diagnostics Inc.", - "Questar Corp", - "Quintiles Transnational", - "Qwest Communications Intl Inc", - "R.J. Reynolds Tobacco Company", - "R.R. Donnelley & Sons Company", - "Radio Shack Corporation", - "Raymond James Financial Inc.", - "Raytheon Company", - "Reader's Digest Association Inc.", - "Reebok International Ltd.", - "Regions Financial Corp.", - "Regis Corporation", - "Reliance Steel & Aluminum Co.", - "Reliant Energy Inc.", - "Rent A Center Inc", - "Republic Services Inc", - "Revlon Inc", - "RGS Energy Group Inc", - "Rite Aid Corp", - "Riverwood Holding Inc.", - "RoadwayCorp", - "Robert Half International Inc.", - "Rock-Tenn Co", - "Rockwell Automation Inc", - "Rockwell Collins Inc", - "Rohm & Haas Co.", - "Ross Stores Inc", - "RPM Inc.", - "Ruddick Corp", - "Ryder System Inc", - "Ryerson Tull Inc", - "Ryland Group Inc.", - "Sabre Holdings Corp", - "Safeco Corp", - "Safeguard Scientifics Inc.", - "Safeway Inc", - "Saks Inc", - "Sanmina-SCI Inc", - "Sara Lee Corp", - "SBC Communications Inc", - "Scana Corp.", - "Schering-Plough Corp", - "Scholastic Corp", - "SCI Systems Onc.", - "Science Applications Intl. Inc.", - "Scientific-Atlanta Inc", - "Scotts Company", - "Seaboard Corp", - "Sealed Air Corp", - "Sears Roebuck & Co", - "Sempra Energy", - "Sequa Corp", - "Service Corp. International", - "ServiceMaster Co", - "Shaw Group Inc", - "Sherwin-Williams Company", - "Shopko Stores Inc", - "Siebel Systems Inc", - "Sierra Health Services Inc", - "Sierra Pacific Resources", - "Silgan Holdings Inc.", - "Silicon Graphics Inc", - "Simon Property Group Inc", - "SLM Corporation", - "Smith International Inc", - "Smithfield Foods Inc", - "Smurfit-Stone Container Corp", - "Snap-On Inc", - "Solectron Corp", - "Solutia Inc", - "Sonic Automotive Inc.", - "Sonoco Products Co.", - "Southern Company", - "Southern Union Company", - "SouthTrust Corp.", - "Southwest Airlines Co", - "Southwest Gas Corp", - "Sovereign Bancorp Inc.", - "Spartan Stores Inc", - "Spherion Corp", - "Sports Authority Inc", - "Sprint Corp.", - "SPX Corp", - "St. Jude Medical Inc", - "St. Paul Cos.", - "Staff Leasing Inc.", - "StanCorp Financial Group Inc", - "Standard Pacific Corp.", - "Stanley Works", - "Staples Inc", - "Starbucks Corp", - "Starwood Hotels & Resorts Worldwide Inc", - "State Street Corp.", - "Stater Bros. Holdings Inc.", - "Steelcase Inc", - "Stein Mart Inc", - "Stewart & Stevenson Services Inc", - "Stewart Information Services Corp", - "Stilwell Financial Inc", - "Storage Technology Corporation", - "Stryker Corp", - "Sun Healthcare Group Inc.", - "Sun Microsystems Inc.", - "SunGard Data Systems Inc.", - "Sunoco Inc.", - "SunTrust Banks Inc", - "Supervalu Inc", - "Swift Transportation, Co., Inc", - "Symbol Technologies Inc", - "Synovus Financial Corp.", - "Sysco Corp", - "Systemax Inc.", - "Target Corp.", - "Tech Data Corporation", - "TECO Energy Inc", - "Tecumseh Products Company", - "Tektronix Inc", - "Teleflex Incorporated", - "Telephone & Data Systems Inc", - "Tellabs Inc.", - "Temple-Inland Inc", - "Tenet Healthcare Corporation", - "Tenneco Automotive Inc.", - "Teradyne Inc", - "Terex Corp", - "Tesoro Petroleum Corp.", - "Texas Industries Inc.", - "Texas Instruments Incorporated", - "Textron Inc", - "Thermo Electron Corporation", - "Thomas & Betts Corporation", - "Tiffany & Co", - "Timken Company", - "TJX Companies Inc", - "TMP Worldwide Inc", - "Toll Brothers Inc", - "Torchmark Corporation", - "Toro Company", - "Tower Automotive Inc.", - "Toys 'R' Us Inc", - "Trans World Entertainment Corp.", - "TransMontaigne Inc", - "Transocean Inc", - "TravelCenters of America Inc.", - "Triad Hospitals Inc", - "Tribune Company", - "Trigon Healthcare Inc.", - "Trinity Industries Inc", - "Trump Hotels & Casino Resorts Inc.", - "TruServ Corporation", - "TRW Inc", - "TXU Corp", - "Tyson Foods Inc", - "U.S. Bancorp", - "U.S. Industries Inc.", - "UAL Corporation", - "UGI Corporation", - "Unified Western Grocers Inc", - "Union Pacific Corporation", - "Union Planters Corp", - "Unisource Energy Corp", - "Unisys Corporation", - "United Auto Group Inc", - "United Defense Industries Inc.", - "United Parcel Service Inc", - "United Rentals Inc", - "United Stationers Inc", - "United Technologies Corporation", - "UnitedHealth Group Incorporated", - "Unitrin Inc", - "Universal Corporation", - "Universal Forest Products Inc", - "Universal Health Services Inc", - "Unocal Corporation", - "Unova Inc", - "UnumProvident Corporation", - "URS Corporation", - "US Airways Group Inc", - "US Oncology Inc", - "USA Interactive", - "USFreighways Corporation", - "USG Corporation", - "UST Inc", - "Valero Energy Corporation", - "Valspar Corporation", - "Value City Department Stores Inc", - "Varco International Inc", - "Vectren Corporation", - "Veritas Software Corporation", - "Verizon Communications Inc", - "VF Corporation", - "Viacom Inc", - "Viad Corp", - "Viasystems Group Inc", - "Vishay Intertechnology Inc", - "Visteon Corporation", - "Volt Information Sciences Inc", - "Vulcan Materials Company", - "W.R. Berkley Corporation", - "W.R. Grace & Co", - "W.W. Grainger Inc", - "Wachovia Corporation", - "Wakenhut Corporation", - "Walgreen Co", - "Wallace Computer Services Inc", - "Wal-Mart Stores Inc", - "Walt Disney Co", - "Walter Industries Inc", - "Washington Mutual Inc", - "Washington Post Co.", - "Waste Management Inc", - "Watsco Inc", - "Weatherford International Inc", - "Weis Markets Inc.", - "Wellpoint Health Networks Inc", - "Wells Fargo & Company", - "Wendy's International Inc", - "Werner Enterprises Inc", - "WESCO International Inc", - "Western Digital Inc", - "Western Gas Resources Inc", - "WestPoint Stevens Inc", - "Weyerhauser Company", - "WGL Holdings Inc", - "Whirlpool Corporation", - "Whole Foods Market Inc", - "Willamette Industries Inc.", - "Williams Companies Inc", - "Williams Sonoma Inc", - "Winn Dixie Stores Inc", - "Wisconsin Energy Corporation", - "Wm Wrigley Jr Company", - "World Fuel Services Corporation", - "WorldCom Inc", - "Worthington Industries Inc", - "WPS Resources Corporation", - "Wyeth", - "Wyndham International Inc", - "Xcel Energy Inc", - "Xerox Corp", - "Xilinx Inc", - "XO Communications Inc", - "Yellow Corporation", - "York International Corp", - "Yum Brands Inc.", - "Zale Corporation", - "Zions Bancorporation" - ], - - fileExtension : { - "raster" : ["bmp", "gif", "gpl", "ico", "jpeg", "psd", "png", "psp", "raw", "tiff"], - "vector" : ["3dv", "amf", "awg", "ai", "cgm", "cdr", "cmx", "dxf", "e2d", "egt", "eps", "fs", "odg", "svg", "xar"], - "3d" : ["3dmf", "3dm", "3mf", "3ds", "an8", "aoi", "blend", "cal3d", "cob", "ctm", "iob", "jas", "max", "mb", "mdx", "obj", "x", "x3d"], - "document" : ["doc", "docx", "dot", "html", "xml", "odt", "odm", "ott", "csv", "rtf", "tex", "xhtml", "xps"] - }, - - // Data taken from https://github.com/dmfilipenko/timezones.json/blob/master/timezones.json - timezones: [ - { - "name": "Dateline Standard Time", - "abbr": "DST", - "offset": -12, - "isdst": false, - "text": "(UTC-12:00) International Date Line West", - "utc": [ - "Etc/GMT+12" - ] - }, - { - "name": "UTC-11", - "abbr": "U", - "offset": -11, - "isdst": false, - "text": "(UTC-11:00) Coordinated Universal Time-11", - "utc": [ - "Etc/GMT+11", - "Pacific/Midway", - "Pacific/Niue", - "Pacific/Pago_Pago" - ] - }, - { - "name": "Hawaiian Standard Time", - "abbr": "HST", - "offset": -10, - "isdst": false, - "text": "(UTC-10:00) Hawaii", - "utc": [ - "Etc/GMT+10", - "Pacific/Honolulu", - "Pacific/Johnston", - "Pacific/Rarotonga", - "Pacific/Tahiti" - ] - }, - { - "name": "Alaskan Standard Time", - "abbr": "AKDT", - "offset": -8, - "isdst": true, - "text": "(UTC-09:00) Alaska", - "utc": [ - "America/Anchorage", - "America/Juneau", - "America/Nome", - "America/Sitka", - "America/Yakutat" - ] - }, - { - "name": "Pacific Standard Time (Mexico)", - "abbr": "PDT", - "offset": -7, - "isdst": true, - "text": "(UTC-08:00) Baja California", - "utc": [ - "America/Santa_Isabel" - ] - }, - { - "name": "Pacific Daylight Time", - "abbr": "PDT", - "offset": -7, - "isdst": true, - "text": "(UTC-07:00) Pacific Time (US & Canada)", - "utc": [ - "America/Dawson", - "America/Los_Angeles", - "America/Tijuana", - "America/Vancouver", - "America/Whitehorse" - ] - }, - { - "name": "Pacific Standard Time", - "abbr": "PST", - "offset": -8, - "isdst": false, - "text": "(UTC-08:00) Pacific Time (US & Canada)", - "utc": [ - "America/Dawson", - "America/Los_Angeles", - "America/Tijuana", - "America/Vancouver", - "America/Whitehorse", - "PST8PDT" - ] - }, - { - "name": "US Mountain Standard Time", - "abbr": "UMST", - "offset": -7, - "isdst": false, - "text": "(UTC-07:00) Arizona", - "utc": [ - "America/Creston", - "America/Dawson_Creek", - "America/Hermosillo", - "America/Phoenix", - "Etc/GMT+7" - ] - }, - { - "name": "Mountain Standard Time (Mexico)", - "abbr": "MDT", - "offset": -6, - "isdst": true, - "text": "(UTC-07:00) Chihuahua, La Paz, Mazatlan", - "utc": [ - "America/Chihuahua", - "America/Mazatlan" - ] - }, - { - "name": "Mountain Standard Time", - "abbr": "MDT", - "offset": -6, - "isdst": true, - "text": "(UTC-07:00) Mountain Time (US & Canada)", - "utc": [ - "America/Boise", - "America/Cambridge_Bay", - "America/Denver", - "America/Edmonton", - "America/Inuvik", - "America/Ojinaga", - "America/Yellowknife", - "MST7MDT" - ] - }, - { - "name": "Central America Standard Time", - "abbr": "CAST", - "offset": -6, - "isdst": false, - "text": "(UTC-06:00) Central America", - "utc": [ - "America/Belize", - "America/Costa_Rica", - "America/El_Salvador", - "America/Guatemala", - "America/Managua", - "America/Tegucigalpa", - "Etc/GMT+6", - "Pacific/Galapagos" - ] - }, - { - "name": "Central Standard Time", - "abbr": "CDT", - "offset": -5, - "isdst": true, - "text": "(UTC-06:00) Central Time (US & Canada)", - "utc": [ - "America/Chicago", - "America/Indiana/Knox", - "America/Indiana/Tell_City", - "America/Matamoros", - "America/Menominee", - "America/North_Dakota/Beulah", - "America/North_Dakota/Center", - "America/North_Dakota/New_Salem", - "America/Rainy_River", - "America/Rankin_Inlet", - "America/Resolute", - "America/Winnipeg", - "CST6CDT" - ] - }, - { - "name": "Central Standard Time (Mexico)", - "abbr": "CDT", - "offset": -5, - "isdst": true, - "text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey", - "utc": [ - "America/Bahia_Banderas", - "America/Cancun", - "America/Merida", - "America/Mexico_City", - "America/Monterrey" - ] - }, - { - "name": "Canada Central Standard Time", - "abbr": "CCST", - "offset": -6, - "isdst": false, - "text": "(UTC-06:00) Saskatchewan", - "utc": [ - "America/Regina", - "America/Swift_Current" - ] - }, - { - "name": "SA Pacific Standard Time", - "abbr": "SPST", - "offset": -5, - "isdst": false, - "text": "(UTC-05:00) Bogota, Lima, Quito", - "utc": [ - "America/Bogota", - "America/Cayman", - "America/Coral_Harbour", - "America/Eirunepe", - "America/Guayaquil", - "America/Jamaica", - "America/Lima", - "America/Panama", - "America/Rio_Branco", - "Etc/GMT+5" - ] - }, - { - "name": "Eastern Standard Time", - "abbr": "EDT", - "offset": -4, - "isdst": true, - "text": "(UTC-05:00) Eastern Time (US & Canada)", - "utc": [ - "America/Detroit", - "America/Havana", - "America/Indiana/Petersburg", - "America/Indiana/Vincennes", - "America/Indiana/Winamac", - "America/Iqaluit", - "America/Kentucky/Monticello", - "America/Louisville", - "America/Montreal", - "America/Nassau", - "America/New_York", - "America/Nipigon", - "America/Pangnirtung", - "America/Port-au-Prince", - "America/Thunder_Bay", - "America/Toronto", - "EST5EDT" - ] - }, - { - "name": "US Eastern Standard Time", - "abbr": "UEDT", - "offset": -4, - "isdst": true, - "text": "(UTC-05:00) Indiana (East)", - "utc": [ - "America/Indiana/Marengo", - "America/Indiana/Vevay", - "America/Indianapolis" - ] - }, - { - "name": "Venezuela Standard Time", - "abbr": "VST", - "offset": -4.5, - "isdst": false, - "text": "(UTC-04:30) Caracas", - "utc": [ - "America/Caracas" - ] - }, - { - "name": "Paraguay Standard Time", - "abbr": "PYT", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Asuncion", - "utc": [ - "America/Asuncion" - ] - }, - { - "name": "Atlantic Standard Time", - "abbr": "ADT", - "offset": -3, - "isdst": true, - "text": "(UTC-04:00) Atlantic Time (Canada)", - "utc": [ - "America/Glace_Bay", - "America/Goose_Bay", - "America/Halifax", - "America/Moncton", - "America/Thule", - "Atlantic/Bermuda" - ] - }, - { - "name": "Central Brazilian Standard Time", - "abbr": "CBST", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Cuiaba", - "utc": [ - "America/Campo_Grande", - "America/Cuiaba" - ] - }, - { - "name": "SA Western Standard Time", - "abbr": "SWST", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Georgetown, La Paz, Manaus, San Juan", - "utc": [ - "America/Anguilla", - "America/Antigua", - "America/Aruba", - "America/Barbados", - "America/Blanc-Sablon", - "America/Boa_Vista", - "America/Curacao", - "America/Dominica", - "America/Grand_Turk", - "America/Grenada", - "America/Guadeloupe", - "America/Guyana", - "America/Kralendijk", - "America/La_Paz", - "America/Lower_Princes", - "America/Manaus", - "America/Marigot", - "America/Martinique", - "America/Montserrat", - "America/Port_of_Spain", - "America/Porto_Velho", - "America/Puerto_Rico", - "America/Santo_Domingo", - "America/St_Barthelemy", - "America/St_Kitts", - "America/St_Lucia", - "America/St_Thomas", - "America/St_Vincent", - "America/Tortola", - "Etc/GMT+4" - ] - }, - { - "name": "Pacific SA Standard Time", - "abbr": "PSST", - "offset": -4, - "isdst": false, - "text": "(UTC-04:00) Santiago", - "utc": [ - "America/Santiago", - "Antarctica/Palmer" - ] - }, - { - "name": "Newfoundland Standard Time", - "abbr": "NDT", - "offset": -2.5, - "isdst": true, - "text": "(UTC-03:30) Newfoundland", - "utc": [ - "America/St_Johns" - ] - }, - { - "name": "E. South America Standard Time", - "abbr": "ESAST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Brasilia", - "utc": [ - "America/Sao_Paulo" - ] - }, - { - "name": "Argentina Standard Time", - "abbr": "AST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Buenos Aires", - "utc": [ - "America/Argentina/La_Rioja", - "America/Argentina/Rio_Gallegos", - "America/Argentina/Salta", - "America/Argentina/San_Juan", - "America/Argentina/San_Luis", - "America/Argentina/Tucuman", - "America/Argentina/Ushuaia", - "America/Buenos_Aires", - "America/Catamarca", - "America/Cordoba", - "America/Jujuy", - "America/Mendoza" - ] - }, - { - "name": "SA Eastern Standard Time", - "abbr": "SEST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Cayenne, Fortaleza", - "utc": [ - "America/Araguaina", - "America/Belem", - "America/Cayenne", - "America/Fortaleza", - "America/Maceio", - "America/Paramaribo", - "America/Recife", - "America/Santarem", - "Antarctica/Rothera", - "Atlantic/Stanley", - "Etc/GMT+3" - ] - }, - { - "name": "Greenland Standard Time", - "abbr": "GDT", - "offset": -3, - "isdst": true, - "text": "(UTC-03:00) Greenland", - "utc": [ - "America/Godthab" - ] - }, - { - "name": "Montevideo Standard Time", - "abbr": "MST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Montevideo", - "utc": [ - "America/Montevideo" - ] - }, - { - "name": "Bahia Standard Time", - "abbr": "BST", - "offset": -3, - "isdst": false, - "text": "(UTC-03:00) Salvador", - "utc": [ - "America/Bahia" - ] - }, - { - "name": "UTC-02", - "abbr": "U", - "offset": -2, - "isdst": false, - "text": "(UTC-02:00) Coordinated Universal Time-02", - "utc": [ - "America/Noronha", - "Atlantic/South_Georgia", - "Etc/GMT+2" - ] - }, - { - "name": "Mid-Atlantic Standard Time", - "abbr": "MDT", - "offset": -1, - "isdst": true, - "text": "(UTC-02:00) Mid-Atlantic - Old", - "utc": [] - }, - { - "name": "Azores Standard Time", - "abbr": "ADT", - "offset": 0, - "isdst": true, - "text": "(UTC-01:00) Azores", - "utc": [ - "America/Scoresbysund", - "Atlantic/Azores" - ] - }, - { - "name": "Cape Verde Standard Time", - "abbr": "CVST", - "offset": -1, - "isdst": false, - "text": "(UTC-01:00) Cape Verde Is.", - "utc": [ - "Atlantic/Cape_Verde", - "Etc/GMT+1" - ] - }, - { - "name": "Morocco Standard Time", - "abbr": "MDT", - "offset": 1, - "isdst": true, - "text": "(UTC) Casablanca", - "utc": [ - "Africa/Casablanca", - "Africa/El_Aaiun" - ] - }, - { - "name": "UTC", - "abbr": "UTC", - "offset": 0, - "isdst": false, - "text": "(UTC) Coordinated Universal Time", - "utc": [ - "America/Danmarkshavn", - "Etc/GMT" - ] - }, - { - "name": "GMT Standard Time", - "abbr": "GMT", - "offset": 0, - "isdst": false, - "text": "(UTC) Edinburgh, London", - "utc": [ - "Europe/Isle_of_Man", - "Europe/Guernsey", - "Europe/Jersey", - "Europe/London" - ] - }, - { - "name": "British Summer Time", - "abbr": "BST", - "offset": 1, - "isdst": true, - "text": "(UTC+01:00) Edinburgh, London", - "utc": [ - "Europe/Isle_of_Man", - "Europe/Guernsey", - "Europe/Jersey", - "Europe/London" - ] - }, - { - "name": "GMT Standard Time", - "abbr": "GDT", - "offset": 1, - "isdst": true, - "text": "(UTC) Dublin, Lisbon", - "utc": [ - "Atlantic/Canary", - "Atlantic/Faeroe", - "Atlantic/Madeira", - "Europe/Dublin", - "Europe/Lisbon" - ] - }, - { - "name": "Greenwich Standard Time", - "abbr": "GST", - "offset": 0, - "isdst": false, - "text": "(UTC) Monrovia, Reykjavik", - "utc": [ - "Africa/Abidjan", - "Africa/Accra", - "Africa/Bamako", - "Africa/Banjul", - "Africa/Bissau", - "Africa/Conakry", - "Africa/Dakar", - "Africa/Freetown", - "Africa/Lome", - "Africa/Monrovia", - "Africa/Nouakchott", - "Africa/Ouagadougou", - "Africa/Sao_Tome", - "Atlantic/Reykjavik", - "Atlantic/St_Helena" - ] - }, - { - "name": "W. Europe Standard Time", - "abbr": "WEDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", - "utc": [ - "Arctic/Longyearbyen", - "Europe/Amsterdam", - "Europe/Andorra", - "Europe/Berlin", - "Europe/Busingen", - "Europe/Gibraltar", - "Europe/Luxembourg", - "Europe/Malta", - "Europe/Monaco", - "Europe/Oslo", - "Europe/Rome", - "Europe/San_Marino", - "Europe/Stockholm", - "Europe/Vaduz", - "Europe/Vatican", - "Europe/Vienna", - "Europe/Zurich" - ] - }, - { - "name": "Central Europe Standard Time", - "abbr": "CEDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", - "utc": [ - "Europe/Belgrade", - "Europe/Bratislava", - "Europe/Budapest", - "Europe/Ljubljana", - "Europe/Podgorica", - "Europe/Prague", - "Europe/Tirane" - ] - }, - { - "name": "Romance Standard Time", - "abbr": "RDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris", - "utc": [ - "Africa/Ceuta", - "Europe/Brussels", - "Europe/Copenhagen", - "Europe/Madrid", - "Europe/Paris" - ] - }, - { - "name": "Central European Standard Time", - "abbr": "CEDT", - "offset": 2, - "isdst": true, - "text": "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb", - "utc": [ - "Europe/Sarajevo", - "Europe/Skopje", - "Europe/Warsaw", - "Europe/Zagreb" - ] - }, - { - "name": "W. Central Africa Standard Time", - "abbr": "WCAST", - "offset": 1, - "isdst": false, - "text": "(UTC+01:00) West Central Africa", - "utc": [ - "Africa/Algiers", - "Africa/Bangui", - "Africa/Brazzaville", - "Africa/Douala", - "Africa/Kinshasa", - "Africa/Lagos", - "Africa/Libreville", - "Africa/Luanda", - "Africa/Malabo", - "Africa/Ndjamena", - "Africa/Niamey", - "Africa/Porto-Novo", - "Africa/Tunis", - "Etc/GMT-1" - ] - }, - { - "name": "Namibia Standard Time", - "abbr": "NST", - "offset": 1, - "isdst": false, - "text": "(UTC+01:00) Windhoek", - "utc": [ - "Africa/Windhoek" - ] - }, - { - "name": "GTB Standard Time", - "abbr": "GDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Athens, Bucharest", - "utc": [ - "Asia/Nicosia", - "Europe/Athens", - "Europe/Bucharest", - "Europe/Chisinau" - ] - }, - { - "name": "Middle East Standard Time", - "abbr": "MEDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Beirut", - "utc": [ - "Asia/Beirut" - ] - }, - { - "name": "Egypt Standard Time", - "abbr": "EST", - "offset": 2, - "isdst": false, - "text": "(UTC+02:00) Cairo", - "utc": [ - "Africa/Cairo" - ] - }, - { - "name": "Syria Standard Time", - "abbr": "SDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Damascus", - "utc": [ - "Asia/Damascus" - ] - }, - { - "name": "E. Europe Standard Time", - "abbr": "EEDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) E. Europe", - "utc": [ - "Asia/Nicosia", - "Europe/Athens", - "Europe/Bucharest", - "Europe/Chisinau", - "Europe/Helsinki", - "Europe/Kiev", - "Europe/Mariehamn", - "Europe/Nicosia", - "Europe/Riga", - "Europe/Sofia", - "Europe/Tallinn", - "Europe/Uzhgorod", - "Europe/Vilnius", - "Europe/Zaporozhye" - ] - }, - { - "name": "South Africa Standard Time", - "abbr": "SAST", - "offset": 2, - "isdst": false, - "text": "(UTC+02:00) Harare, Pretoria", - "utc": [ - "Africa/Blantyre", - "Africa/Bujumbura", - "Africa/Gaborone", - "Africa/Harare", - "Africa/Johannesburg", - "Africa/Kigali", - "Africa/Lubumbashi", - "Africa/Lusaka", - "Africa/Maputo", - "Africa/Maseru", - "Africa/Mbabane", - "Etc/GMT-2" - ] - }, - { - "name": "FLE Standard Time", - "abbr": "FDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", - "utc": [ - "Europe/Helsinki", - "Europe/Kiev", - "Europe/Mariehamn", - "Europe/Riga", - "Europe/Sofia", - "Europe/Tallinn", - "Europe/Uzhgorod", - "Europe/Vilnius", - "Europe/Zaporozhye" - ] - }, - { - "name": "Turkey Standard Time", - "abbr": "TDT", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Istanbul", - "utc": [ - "Europe/Istanbul" - ] - }, - { - "name": "Israel Standard Time", - "abbr": "JDT", - "offset": 3, - "isdst": true, - "text": "(UTC+02:00) Jerusalem", - "utc": [ - "Asia/Jerusalem" - ] - }, - { - "name": "Libya Standard Time", - "abbr": "LST", - "offset": 2, - "isdst": false, - "text": "(UTC+02:00) Tripoli", - "utc": [ - "Africa/Tripoli" - ] - }, - { - "name": "Jordan Standard Time", - "abbr": "JST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Amman", - "utc": [ - "Asia/Amman" - ] - }, - { - "name": "Arabic Standard Time", - "abbr": "AST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Baghdad", - "utc": [ - "Asia/Baghdad" - ] - }, - { - "name": "Kaliningrad Standard Time", - "abbr": "KST", - "offset": 3, - "isdst": false, - "text": "(UTC+02:00) Kaliningrad", - "utc": [ - "Europe/Kaliningrad" - ] - }, - { - "name": "Arab Standard Time", - "abbr": "AST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Kuwait, Riyadh", - "utc": [ - "Asia/Aden", - "Asia/Bahrain", - "Asia/Kuwait", - "Asia/Qatar", - "Asia/Riyadh" - ] - }, - { - "name": "E. Africa Standard Time", - "abbr": "EAST", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Nairobi", - "utc": [ - "Africa/Addis_Ababa", - "Africa/Asmera", - "Africa/Dar_es_Salaam", - "Africa/Djibouti", - "Africa/Juba", - "Africa/Kampala", - "Africa/Khartoum", - "Africa/Mogadishu", - "Africa/Nairobi", - "Antarctica/Syowa", - "Etc/GMT-3", - "Indian/Antananarivo", - "Indian/Comoro", - "Indian/Mayotte" - ] - }, - { - "name": "Moscow Standard Time", - "abbr": "MSK", - "offset": 3, - "isdst": false, - "text": "(UTC+03:00) Moscow, St. Petersburg, Volgograd, Minsk", - "utc": [ - "Europe/Kirov", - "Europe/Moscow", - "Europe/Simferopol", - "Europe/Volgograd", - "Europe/Minsk" - ] - }, - { - "name": "Samara Time", - "abbr": "SAMT", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Samara, Ulyanovsk, Saratov", - "utc": [ - "Europe/Astrakhan", - "Europe/Samara", - "Europe/Ulyanovsk" - ] - }, - { - "name": "Iran Standard Time", - "abbr": "IDT", - "offset": 4.5, - "isdst": true, - "text": "(UTC+03:30) Tehran", - "utc": [ - "Asia/Tehran" - ] - }, - { - "name": "Arabian Standard Time", - "abbr": "AST", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Abu Dhabi, Muscat", - "utc": [ - "Asia/Dubai", - "Asia/Muscat", - "Etc/GMT-4" - ] - }, - { - "name": "Azerbaijan Standard Time", - "abbr": "ADT", - "offset": 5, - "isdst": true, - "text": "(UTC+04:00) Baku", - "utc": [ - "Asia/Baku" - ] - }, - { - "name": "Mauritius Standard Time", - "abbr": "MST", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Port Louis", - "utc": [ - "Indian/Mahe", - "Indian/Mauritius", - "Indian/Reunion" - ] - }, - { - "name": "Georgian Standard Time", - "abbr": "GET", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Tbilisi", - "utc": [ - "Asia/Tbilisi" - ] - }, - { - "name": "Caucasus Standard Time", - "abbr": "CST", - "offset": 4, - "isdst": false, - "text": "(UTC+04:00) Yerevan", - "utc": [ - "Asia/Yerevan" - ] - }, - { - "name": "Afghanistan Standard Time", - "abbr": "AST", - "offset": 4.5, - "isdst": false, - "text": "(UTC+04:30) Kabul", - "utc": [ - "Asia/Kabul" - ] - }, - { - "name": "West Asia Standard Time", - "abbr": "WAST", - "offset": 5, - "isdst": false, - "text": "(UTC+05:00) Ashgabat, Tashkent", - "utc": [ - "Antarctica/Mawson", - "Asia/Aqtau", - "Asia/Aqtobe", - "Asia/Ashgabat", - "Asia/Dushanbe", - "Asia/Oral", - "Asia/Samarkand", - "Asia/Tashkent", - "Etc/GMT-5", - "Indian/Kerguelen", - "Indian/Maldives" - ] - }, - { - "name": "Yekaterinburg Time", - "abbr": "YEKT", - "offset": 5, - "isdst": false, - "text": "(UTC+05:00) Yekaterinburg", - "utc": [ - "Asia/Yekaterinburg" - ] - }, - { - "name": "Pakistan Standard Time", - "abbr": "PKT", - "offset": 5, - "isdst": false, - "text": "(UTC+05:00) Islamabad, Karachi", - "utc": [ - "Asia/Karachi" - ] - }, - { - "name": "India Standard Time", - "abbr": "IST", - "offset": 5.5, - "isdst": false, - "text": "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi", - "utc": [ - "Asia/Kolkata" - ] - }, - { - "name": "Sri Lanka Standard Time", - "abbr": "SLST", - "offset": 5.5, - "isdst": false, - "text": "(UTC+05:30) Sri Jayawardenepura", - "utc": [ - "Asia/Colombo" - ] - }, - { - "name": "Nepal Standard Time", - "abbr": "NST", - "offset": 5.75, - "isdst": false, - "text": "(UTC+05:45) Kathmandu", - "utc": [ - "Asia/Kathmandu" - ] - }, - { - "name": "Central Asia Standard Time", - "abbr": "CAST", - "offset": 6, - "isdst": false, - "text": "(UTC+06:00) Nur-Sultan (Astana)", - "utc": [ - "Antarctica/Vostok", - "Asia/Almaty", - "Asia/Bishkek", - "Asia/Qyzylorda", - "Asia/Urumqi", - "Etc/GMT-6", - "Indian/Chagos" - ] - }, - { - "name": "Bangladesh Standard Time", - "abbr": "BST", - "offset": 6, - "isdst": false, - "text": "(UTC+06:00) Dhaka", - "utc": [ - "Asia/Dhaka", - "Asia/Thimphu" - ] - }, - { - "name": "Myanmar Standard Time", - "abbr": "MST", - "offset": 6.5, - "isdst": false, - "text": "(UTC+06:30) Yangon (Rangoon)", - "utc": [ - "Asia/Rangoon", - "Indian/Cocos" - ] - }, - { - "name": "SE Asia Standard Time", - "abbr": "SAST", - "offset": 7, - "isdst": false, - "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta", - "utc": [ - "Antarctica/Davis", - "Asia/Bangkok", - "Asia/Hovd", - "Asia/Jakarta", - "Asia/Phnom_Penh", - "Asia/Pontianak", - "Asia/Saigon", - "Asia/Vientiane", - "Etc/GMT-7", - "Indian/Christmas" - ] - }, - { - "name": "N. Central Asia Standard Time", - "abbr": "NCAST", - "offset": 7, - "isdst": false, - "text": "(UTC+07:00) Novosibirsk", - "utc": [ - "Asia/Novokuznetsk", - "Asia/Novosibirsk", - "Asia/Omsk" - ] - }, - { - "name": "China Standard Time", - "abbr": "CST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi", - "utc": [ - "Asia/Hong_Kong", - "Asia/Macau", - "Asia/Shanghai" - ] - }, - { - "name": "North Asia Standard Time", - "abbr": "NAST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Krasnoyarsk", - "utc": [ - "Asia/Krasnoyarsk" - ] - }, - { - "name": "Singapore Standard Time", - "abbr": "MPST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Kuala Lumpur, Singapore", - "utc": [ - "Asia/Brunei", - "Asia/Kuala_Lumpur", - "Asia/Kuching", - "Asia/Makassar", - "Asia/Manila", - "Asia/Singapore", - "Etc/GMT-8" - ] - }, - { - "name": "W. Australia Standard Time", - "abbr": "WAST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Perth", - "utc": [ - "Antarctica/Casey", - "Australia/Perth" - ] - }, - { - "name": "Taipei Standard Time", - "abbr": "TST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Taipei", - "utc": [ - "Asia/Taipei" - ] - }, - { - "name": "Ulaanbaatar Standard Time", - "abbr": "UST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Ulaanbaatar", - "utc": [ - "Asia/Choibalsan", - "Asia/Ulaanbaatar" - ] - }, - { - "name": "North Asia East Standard Time", - "abbr": "NAEST", - "offset": 8, - "isdst": false, - "text": "(UTC+08:00) Irkutsk", - "utc": [ - "Asia/Irkutsk" - ] - }, - { - "name": "Japan Standard Time", - "abbr": "JST", - "offset": 9, - "isdst": false, - "text": "(UTC+09:00) Osaka, Sapporo, Tokyo", - "utc": [ - "Asia/Dili", - "Asia/Jayapura", - "Asia/Tokyo", - "Etc/GMT-9", - "Pacific/Palau" - ] - }, - { - "name": "Korea Standard Time", - "abbr": "KST", - "offset": 9, - "isdst": false, - "text": "(UTC+09:00) Seoul", - "utc": [ - "Asia/Pyongyang", - "Asia/Seoul" - ] - }, - { - "name": "Cen. Australia Standard Time", - "abbr": "CAST", - "offset": 9.5, - "isdst": false, - "text": "(UTC+09:30) Adelaide", - "utc": [ - "Australia/Adelaide", - "Australia/Broken_Hill" - ] - }, - { - "name": "AUS Central Standard Time", - "abbr": "ACST", - "offset": 9.5, - "isdst": false, - "text": "(UTC+09:30) Darwin", - "utc": [ - "Australia/Darwin" - ] - }, - { - "name": "E. Australia Standard Time", - "abbr": "EAST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Brisbane", - "utc": [ - "Australia/Brisbane", - "Australia/Lindeman" - ] - }, - { - "name": "AUS Eastern Standard Time", - "abbr": "AEST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Canberra, Melbourne, Sydney", - "utc": [ - "Australia/Melbourne", - "Australia/Sydney" - ] - }, - { - "name": "West Pacific Standard Time", - "abbr": "WPST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Guam, Port Moresby", - "utc": [ - "Antarctica/DumontDUrville", - "Etc/GMT-10", - "Pacific/Guam", - "Pacific/Port_Moresby", - "Pacific/Saipan", - "Pacific/Truk" - ] - }, - { - "name": "Tasmania Standard Time", - "abbr": "TST", - "offset": 10, - "isdst": false, - "text": "(UTC+10:00) Hobart", - "utc": [ - "Australia/Currie", - "Australia/Hobart" - ] - }, - { - "name": "Yakutsk Standard Time", - "abbr": "YST", - "offset": 9, - "isdst": false, - "text": "(UTC+09:00) Yakutsk", - "utc": [ - "Asia/Chita", - "Asia/Khandyga", - "Asia/Yakutsk" - ] - }, - { - "name": "Central Pacific Standard Time", - "abbr": "CPST", - "offset": 11, - "isdst": false, - "text": "(UTC+11:00) Solomon Is., New Caledonia", - "utc": [ - "Antarctica/Macquarie", - "Etc/GMT-11", - "Pacific/Efate", - "Pacific/Guadalcanal", - "Pacific/Kosrae", - "Pacific/Noumea", - "Pacific/Ponape" - ] - }, - { - "name": "Vladivostok Standard Time", - "abbr": "VST", - "offset": 11, - "isdst": false, - "text": "(UTC+11:00) Vladivostok", - "utc": [ - "Asia/Sakhalin", - "Asia/Ust-Nera", - "Asia/Vladivostok" - ] - }, - { - "name": "New Zealand Standard Time", - "abbr": "NZST", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Auckland, Wellington", - "utc": [ - "Antarctica/McMurdo", - "Pacific/Auckland" - ] - }, - { - "name": "UTC+12", - "abbr": "U", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Coordinated Universal Time+12", - "utc": [ - "Etc/GMT-12", - "Pacific/Funafuti", - "Pacific/Kwajalein", - "Pacific/Majuro", - "Pacific/Nauru", - "Pacific/Tarawa", - "Pacific/Wake", - "Pacific/Wallis" - ] - }, - { - "name": "Fiji Standard Time", - "abbr": "FST", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Fiji", - "utc": [ - "Pacific/Fiji" - ] - }, - { - "name": "Magadan Standard Time", - "abbr": "MST", - "offset": 12, - "isdst": false, - "text": "(UTC+12:00) Magadan", - "utc": [ - "Asia/Anadyr", - "Asia/Kamchatka", - "Asia/Magadan", - "Asia/Srednekolymsk" - ] - }, - { - "name": "Kamchatka Standard Time", - "abbr": "KDT", - "offset": 13, - "isdst": true, - "text": "(UTC+12:00) Petropavlovsk-Kamchatsky - Old", - "utc": [ - "Asia/Kamchatka" - ] - }, - { - "name": "Tonga Standard Time", - "abbr": "TST", - "offset": 13, - "isdst": false, - "text": "(UTC+13:00) Nuku'alofa", - "utc": [ - "Etc/GMT-13", - "Pacific/Enderbury", - "Pacific/Fakaofo", - "Pacific/Tongatapu" - ] - }, - { - "name": "Samoa Standard Time", - "abbr": "SST", - "offset": 13, - "isdst": false, - "text": "(UTC+13:00) Samoa", - "utc": [ - "Pacific/Apia" - ] - } - ], - //List source: http://answers.google.com/answers/threadview/id/589312.html - profession: [ - "Airline Pilot", - "Academic Team", - "Accountant", - "Account Executive", - "Actor", - "Actuary", - "Acquisition Analyst", - "Administrative Asst.", - "Administrative Analyst", - "Administrator", - "Advertising Director", - "Aerospace Engineer", - "Agent", - "Agricultural Inspector", - "Agricultural Scientist", - "Air Traffic Controller", - "Animal Trainer", - "Anthropologist", - "Appraiser", - "Architect", - "Art Director", - "Artist", - "Astronomer", - "Athletic Coach", - "Auditor", - "Author", - "Baker", - "Banker", - "Bankruptcy Attorney", - "Benefits Manager", - "Biologist", - "Bio-feedback Specialist", - "Biomedical Engineer", - "Biotechnical Researcher", - "Broadcaster", - "Broker", - "Building Manager", - "Building Contractor", - "Building Inspector", - "Business Analyst", - "Business Planner", - "Business Manager", - "Buyer", - "Call Center Manager", - "Career Counselor", - "Cash Manager", - "Ceramic Engineer", - "Chief Executive Officer", - "Chief Operation Officer", - "Chef", - "Chemical Engineer", - "Chemist", - "Child Care Manager", - "Chief Medical Officer", - "Chiropractor", - "Cinematographer", - "City Housing Manager", - "City Manager", - "Civil Engineer", - "Claims Manager", - "Clinical Research Assistant", - "Collections Manager", - "Compliance Manager", - "Comptroller", - "Computer Manager", - "Commercial Artist", - "Communications Affairs Director", - "Communications Director", - "Communications Engineer", - "Compensation Analyst", - "Computer Programmer", - "Computer Ops. Manager", - "Computer Engineer", - "Computer Operator", - "Computer Graphics Specialist", - "Construction Engineer", - "Construction Manager", - "Consultant", - "Consumer Relations Manager", - "Contract Administrator", - "Copyright Attorney", - "Copywriter", - "Corporate Planner", - "Corrections Officer", - "Cosmetologist", - "Credit Analyst", - "Cruise Director", - "Chief Information Officer", - "Chief Technology Officer", - "Customer Service Manager", - "Cryptologist", - "Dancer", - "Data Security Manager", - "Database Manager", - "Day Care Instructor", - "Dentist", - "Designer", - "Design Engineer", - "Desktop Publisher", - "Developer", - "Development Officer", - "Diamond Merchant", - "Dietitian", - "Direct Marketer", - "Director", - "Distribution Manager", - "Diversity Manager", - "Economist", - "EEO Compliance Manager", - "Editor", - "Education Adminator", - "Electrical Engineer", - "Electro Optical Engineer", - "Electronics Engineer", - "Embassy Management", - "Employment Agent", - "Engineer Technician", - "Entrepreneur", - "Environmental Analyst", - "Environmental Attorney", - "Environmental Engineer", - "Environmental Specialist", - "Escrow Officer", - "Estimator", - "Executive Assistant", - "Executive Director", - "Executive Recruiter", - "Facilities Manager", - "Family Counselor", - "Fashion Events Manager", - "Fashion Merchandiser", - "Fast Food Manager", - "Film Producer", - "Film Production Assistant", - "Financial Analyst", - "Financial Planner", - "Financier", - "Fine Artist", - "Wildlife Specialist", - "Fitness Consultant", - "Flight Attendant", - "Flight Engineer", - "Floral Designer", - "Food & Beverage Director", - "Food Service Manager", - "Forestry Technician", - "Franchise Management", - "Franchise Sales", - "Fraud Investigator", - "Freelance Writer", - "Fund Raiser", - "General Manager", - "Geologist", - "General Counsel", - "Geriatric Specialist", - "Gerontologist", - "Glamour Photographer", - "Golf Club Manager", - "Gourmet Chef", - "Graphic Designer", - "Grounds Keeper", - "Hazardous Waste Manager", - "Health Care Manager", - "Health Therapist", - "Health Service Administrator", - "Hearing Officer", - "Home Economist", - "Horticulturist", - "Hospital Administrator", - "Hotel Manager", - "Human Resources Manager", - "Importer", - "Industrial Designer", - "Industrial Engineer", - "Information Director", - "Inside Sales", - "Insurance Adjuster", - "Interior Decorator", - "Internal Controls Director", - "International Acct.", - "International Courier", - "International Lawyer", - "Interpreter", - "Investigator", - "Investment Banker", - "Investment Manager", - "IT Architect", - "IT Project Manager", - "IT Systems Analyst", - "Jeweler", - "Joint Venture Manager", - "Journalist", - "Labor Negotiator", - "Labor Organizer", - "Labor Relations Manager", - "Lab Services Director", - "Lab Technician", - "Land Developer", - "Landscape Architect", - "Law Enforcement Officer", - "Lawyer", - "Lead Software Engineer", - "Lead Software Test Engineer", - "Leasing Manager", - "Legal Secretary", - "Library Manager", - "Litigation Attorney", - "Loan Officer", - "Lobbyist", - "Logistics Manager", - "Maintenance Manager", - "Management Consultant", - "Managed Care Director", - "Managing Partner", - "Manufacturing Director", - "Manpower Planner", - "Marine Biologist", - "Market Res. Analyst", - "Marketing Director", - "Materials Manager", - "Mathematician", - "Membership Chairman", - "Mechanic", - "Mechanical Engineer", - "Media Buyer", - "Medical Investor", - "Medical Secretary", - "Medical Technician", - "Mental Health Counselor", - "Merchandiser", - "Metallurgical Engineering", - "Meteorologist", - "Microbiologist", - "MIS Manager", - "Motion Picture Director", - "Multimedia Director", - "Musician", - "Network Administrator", - "Network Specialist", - "Network Operator", - "New Product Manager", - "Novelist", - "Nuclear Engineer", - "Nuclear Specialist", - "Nutritionist", - "Nursing Administrator", - "Occupational Therapist", - "Oceanographer", - "Office Manager", - "Operations Manager", - "Operations Research Director", - "Optical Technician", - "Optometrist", - "Organizational Development Manager", - "Outplacement Specialist", - "Paralegal", - "Park Ranger", - "Patent Attorney", - "Payroll Specialist", - "Personnel Specialist", - "Petroleum Engineer", - "Pharmacist", - "Photographer", - "Physical Therapist", - "Physician", - "Physician Assistant", - "Physicist", - "Planning Director", - "Podiatrist", - "Political Analyst", - "Political Scientist", - "Politician", - "Portfolio Manager", - "Preschool Management", - "Preschool Teacher", - "Principal", - "Private Banker", - "Private Investigator", - "Probation Officer", - "Process Engineer", - "Producer", - "Product Manager", - "Product Engineer", - "Production Engineer", - "Production Planner", - "Professional Athlete", - "Professional Coach", - "Professor", - "Project Engineer", - "Project Manager", - "Program Manager", - "Property Manager", - "Public Administrator", - "Public Safety Director", - "PR Specialist", - "Publisher", - "Purchasing Agent", - "Publishing Director", - "Quality Assurance Specialist", - "Quality Control Engineer", - "Quality Control Inspector", - "Radiology Manager", - "Railroad Engineer", - "Real Estate Broker", - "Recreational Director", - "Recruiter", - "Redevelopment Specialist", - "Regulatory Affairs Manager", - "Registered Nurse", - "Rehabilitation Counselor", - "Relocation Manager", - "Reporter", - "Research Specialist", - "Restaurant Manager", - "Retail Store Manager", - "Risk Analyst", - "Safety Engineer", - "Sales Engineer", - "Sales Trainer", - "Sales Promotion Manager", - "Sales Representative", - "Sales Manager", - "Service Manager", - "Sanitation Engineer", - "Scientific Programmer", - "Scientific Writer", - "Securities Analyst", - "Security Consultant", - "Security Director", - "Seminar Presenter", - "Ship's Officer", - "Singer", - "Social Director", - "Social Program Planner", - "Social Research", - "Social Scientist", - "Social Worker", - "Sociologist", - "Software Developer", - "Software Engineer", - "Software Test Engineer", - "Soil Scientist", - "Special Events Manager", - "Special Education Teacher", - "Special Projects Director", - "Speech Pathologist", - "Speech Writer", - "Sports Event Manager", - "Statistician", - "Store Manager", - "Strategic Alliance Director", - "Strategic Planning Director", - "Stress Reduction Specialist", - "Stockbroker", - "Surveyor", - "Structural Engineer", - "Superintendent", - "Supply Chain Director", - "System Engineer", - "Systems Analyst", - "Systems Programmer", - "System Administrator", - "Tax Specialist", - "Teacher", - "Technical Support Specialist", - "Technical Illustrator", - "Technical Writer", - "Technology Director", - "Telecom Analyst", - "Telemarketer", - "Theatrical Director", - "Title Examiner", - "Tour Escort", - "Tour Guide Director", - "Traffic Manager", - "Trainer Translator", - "Transportation Manager", - "Travel Agent", - "Treasurer", - "TV Programmer", - "Underwriter", - "Union Representative", - "University Administrator", - "University Dean", - "Urban Planner", - "Veterinarian", - "Vendor Relations Director", - "Viticulturist", - "Warehouse Manager" - ], - animals : { - //list of ocean animals comes from https://owlcation.com/stem/list-of-ocean-animals - "ocean" : ["Acantharea","Anemone","Angelfish King","Ahi Tuna","Albacore","American Oyster","Anchovy","Armored Snail","Arctic Char","Atlantic Bluefin Tuna","Atlantic Cod","Atlantic Goliath Grouper","Atlantic Trumpetfish","Atlantic Wolffish","Baleen Whale","Banded Butterflyfish","Banded Coral Shrimp","Banded Sea Krait","Barnacle","Barndoor Skate","Barracuda","Basking Shark","Bass","Beluga Whale","Bluebanded Goby","Bluehead Wrasse","Bluefish","Bluestreak Cleaner-Wrasse","Blue Marlin","Blue Shark","Blue Spiny Lobster","Blue Tang","Blue Whale","Broadclub Cuttlefish","Bull Shark","Chambered Nautilus","Chilean Basket Star","Chilean Jack Mackerel","Chinook Salmon","Christmas Tree Worm","Clam","Clown Anemonefish","Clown Triggerfish","Cod","Coelacanth","Cockscomb Cup Coral","Common Fangtooth","Conch","Cookiecutter Shark","Copepod","Coral","Corydoras","Cownose Ray","Crab","Crown-of-Thorns Starfish","Cushion Star","Cuttlefish","California Sea Otters","Dolphin","Dolphinfish","Dory","Devil Fish","Dugong","Dumbo Octopus","Dungeness Crab","Eccentric Sand Dollar","Edible Sea Cucumber","Eel","Elephant Seal","Elkhorn Coral","Emperor Shrimp","Estuarine Crocodile","Fathead Sculpin","Fiddler Crab","Fin Whale","Flameback","Flamingo Tongue Snail","Flashlight Fish","Flatback Turtle","Flatfish","Flying Fish","Flounder","Fluke","French Angelfish","Frilled Shark","Fugu (also called Pufferfish)","Gar","Geoduck","Giant Barrel Sponge","Giant Caribbean Sea Anemone","Giant Clam","Giant Isopod","Giant Kingfish","Giant Oarfish","Giant Pacific Octopus","Giant Pyrosome","Giant Sea Star","Giant Squid","Glowing Sucker Octopus","Giant Tube Worm","Goblin Shark","Goosefish","Great White Shark","Greenland Shark","Grey Atlantic Seal","Grouper","Grunion","Guineafowl Puffer","Haddock","Hake","Halibut","Hammerhead Shark","Hapuka","Harbor Porpoise","Harbor Seal","Hatchetfish","Hawaiian Monk Seal","Hawksbill Turtle","Hector's Dolphin","Hermit Crab","Herring","Hoki","Horn Shark","Horseshoe Crab","Humpback Anglerfish","Humpback Whale","Icefish","Imperator Angelfish","Irukandji Jellyfish","Isopod","Ivory Bush Coral","Japanese Spider Crab","Jellyfish","John Dory","Juan Fernandez Fur Seal","Killer Whale","Kiwa Hirsuta","Krill","Lagoon Triggerfish","Lamprey","Leafy Seadragon","Leopard Seal","Limpet","Ling","Lionfish","Lions Mane Jellyfish","Lobe Coral","Lobster","Loggerhead Turtle","Longnose Sawshark","Longsnout Seahorse","Lophelia Coral","Marrus Orthocanna","Manatee","Manta Ray","Marlin","Megamouth Shark","Mexican Lookdown","Mimic Octopus","Moon Jelly","Mollusk","Monkfish","Moray Eel","Mullet","Mussel","Megaladon","Napoleon Wrasse","Nassau Grouper","Narwhal","Nautilus","Needlefish","Northern Seahorse","North Atlantic Right Whale","Northern Red Snapper","Norway Lobster","Nudibranch","Nurse Shark","Oarfish","Ocean Sunfish","Oceanic Whitetip Shark","Octopus","Olive Sea Snake","Orange Roughy","Ostracod","Otter","Oyster","Pacific Angelshark","Pacific Blackdragon","Pacific Halibut","Pacific Sardine","Pacific Sea Nettle Jellyfish","Pacific White Sided Dolphin","Pantropical Spotted Dolphin","Patagonian Toothfish","Peacock Mantis Shrimp","Pelagic Thresher Shark","Penguin","Peruvian Anchoveta","Pilchard","Pink Salmon","Pinniped","Plankton","Porpoise","Polar Bear","Portuguese Man o' War","Pycnogonid Sea Spider","Quahog","Queen Angelfish","Queen Conch","Queen Parrotfish","Queensland Grouper","Ragfish","Ratfish","Rattail Fish","Ray","Red Drum","Red King Crab","Ringed Seal","Risso's Dolphin","Ross Seals","Sablefish","Salmon","Sand Dollar","Sandbar Shark","Sawfish","Sarcastic Fringehead","Scalloped Hammerhead Shark","Seahorse","Sea Cucumber","Sea Lion","Sea Urchin","Seal","Shark","Shortfin Mako Shark","Shovelnose Guitarfish","Shrimp","Silverside Fish","Skipjack Tuna","Slender Snipe Eel","Smalltooth Sawfish","Smelts","Sockeye Salmon","Southern Stingray","Sponge","Spotted Porcupinefish","Spotted Dolphin","Spotted Eagle Ray","Spotted Moray","Squid","Squidworm","Starfish","Stickleback","Stonefish","Stoplight Loosejaw","Sturgeon","Swordfish","Tan Bristlemouth","Tasseled Wobbegong","Terrible Claw Lobster","Threespot Damselfish","Tiger Prawn","Tiger Shark","Tilefish","Toadfish","Tropical Two-Wing Flyfish","Tuna","Umbrella Squid","Velvet Crab","Venus Flytrap Sea Anemone","Vigtorniella Worm","Viperfish","Vampire Squid","Vaquita","Wahoo","Walrus","West Indian Manatee","Whale","Whale Shark","Whiptail Gulper","White-Beaked Dolphin","White-Ring Garden Eel","White Shrimp","Wobbegong","Wrasse","Wreckfish","Xiphosura","Yellowtail Damselfish","Yelloweye Rockfish","Yellow Cup Black Coral","Yellow Tube Sponge","Yellowfin Tuna","Zebrashark","Zooplankton"], - //list of desert, grassland, and forest animals comes from http://www.skyenimals.com/ - "desert" : ["Aardwolf","Addax","African Wild Ass","Ant","Antelope","Armadillo","Baboon","Badger","Bat","Bearded Dragon","Beetle","Bird","Black-footed Cat","Boa","Brown Bear","Bustard","Butterfly","Camel","Caracal","Caracara","Caterpillar","Centipede","Cheetah","Chipmunk","Chuckwalla","Climbing Mouse","Coati","Cobra","Cotton Rat","Cougar","Courser","Crane Fly","Crow","Dassie Rat","Dove","Dunnart","Eagle","Echidna","Elephant","Emu","Falcon","Fly","Fox","Frogmouth","Gecko","Geoffroy's Cat","Gerbil","Grasshopper","Guanaco","Gundi","Hamster","Hawk","Hedgehog","Hyena","Hyrax","Jackal","Kangaroo","Kangaroo Rat","Kestrel","Kowari","Kultarr","Leopard","Lion","Macaw","Meerkat","Mouse","Oryx","Ostrich","Owl","Pronghorn","Python","Rabbit","Raccoon","Rattlesnake","Rhinoceros","Sand Cat","Spectacled Bear","Spiny Mouse","Starling","Stick Bug","Tarantula","Tit","Toad","Tortoise","Tyrant Flycatcher","Viper","Vulture","Waxwing","Xerus","Zebra"], - "grassland" : ["Aardvark","Aardwolf","Accentor","African Buffalo","African Wild Dog","Alpaca","Anaconda","Ant","Anteater","Antelope","Armadillo","Baboon","Badger","Bandicoot","Barbet","Bat","Bee","Bee-eater","Beetle","Bird","Bison","Black-footed Cat","Black-footed Ferret","Bluebird","Boa","Bowerbird","Brown Bear","Bush Dog","Bushshrike","Bustard","Butterfly","Buzzard","Caracal","Caracara","Cardinal","Caterpillar","Cheetah","Chipmunk","Civet","Climbing Mouse","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Common Genet","Cotton Rat","Cougar","Courser","Coyote","Crane","Crane Fly","Cricket","Crow","Culpeo","Death Adder","Deer","Deer Mouse","Dingo","Dinosaur","Dove","Drongo","Duck","Duiker","Dunnart","Eagle","Echidna","Elephant","Elk","Emu","Falcon","Finch","Flea","Fly","Flying Frog","Fox","Frog","Frogmouth","Garter Snake","Gazelle","Gecko","Geoffroy's Cat","Gerbil","Giant Tortoise","Giraffe","Grasshopper","Grison","Groundhog","Grouse","Guanaco","Guinea Pig","Hamster","Harrier","Hartebeest","Hawk","Hedgehog","Helmetshrike","Hippopotamus","Hornbill","Hyena","Hyrax","Impala","Jackal","Jaguar","Jaguarundi","Kangaroo","Kangaroo Rat","Kestrel","Kultarr","Ladybug","Leopard","Lion","Macaw","Meerkat","Mouse","Newt","Oryx","Ostrich","Owl","Pangolin","Pheasant","Prairie Dog","Pronghorn","Przewalski's Horse","Python","Quoll","Rabbit","Raven","Rhinoceros","Shelduck","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Tamandua","Tasmanian Devil","Thornbill","Thrush","Toad","Tortoise"], - "forest" : ["Agouti","Anaconda","Anoa","Ant","Anteater","Antelope","Armadillo","Asian Black Bear","Aye-aye","Babirusa","Baboon","Badger","Bandicoot","Banteng","Barbet","Basilisk","Bat","Bearded Dragon","Bee","Bee-eater","Beetle","Bettong","Binturong","Bird-of-paradise","Bongo","Bowerbird","Bulbul","Bush Dog","Bushbaby","Bushshrike","Butterfly","Buzzard","Caecilian","Cardinal","Cassowary","Caterpillar","Centipede","Chameleon","Chimpanzee","Cicada","Civet","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Colugo","Cotinga","Cotton Rat","Cougar","Crane Fly","Cricket","Crocodile","Crow","Cuckoo","Cuscus","Death Adder","Deer","Dhole","Dingo","Dinosaur","Drongo","Duck","Duiker","Eagle","Echidna","Elephant","Finch","Flat-headed Cat","Flea","Flowerpecker","Fly","Flying Frog","Fossa","Frog","Frogmouth","Gaur","Gecko","Gorilla","Grison","Hawaiian Honeycreeper","Hawk","Hedgehog","Helmetshrike","Hornbill","Hyrax","Iguana","Jackal","Jaguar","Jaguarundi","Kestrel","Ladybug","Lemur","Leopard","Lion","Macaw","Mandrill","Margay","Monkey","Mouse","Mouse Deer","Newt","Okapi","Old World Flycatcher","Orangutan","Owl","Pangolin","Peafowl","Pheasant","Possum","Python","Quokka","Rabbit","Raccoon","Red Panda","Red River Hog","Rhinoceros","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Sun Bear","Tamandua","Tamarin","Tapir","Tarantula","Thrush","Tiger","Tit","Toad","Tortoise","Toucan","Trogon","Trumpeter","Turaco","Turtle","Tyrant Flycatcher","Viper","Vulture","Wallaby","Warbler","Wasp","Waxwing","Weaver","Weaver-finch","Whistler","White-eye","Whydah","Woodswallow","Worm","Wren","Xenops","Yellowjacket","Accentor","African Buffalo","American Black Bear","Anole","Bird","Bison","Boa","Brown Bear","Chipmunk","Common Genet","Copperhead","Coyote","Deer Mouse","Dormouse","Elk","Emu","Fisher","Fox","Garter Snake","Giant Panda","Giant Tortoise","Groundhog","Grouse","Guanaco","Himalayan Tahr","Kangaroo","Koala","Numbat","Quoll","Raccoon dog","Tasmanian Devil","Thornbill","Turkey","Vole","Weasel","Wildcat","Wolf","Wombat","Woodchuck","Woodpecker"], - //list of farm animals comes from https://www.buzzle.com/articles/farm-animals-list.html - "farm" : ["Alpaca","Buffalo","Banteng","Cow","Cat","Chicken","Carp","Camel","Donkey","Dog","Duck","Emu","Goat","Gayal","Guinea","Goose","Horse","Honey","Llama","Pig","Pigeon","Rhea","Rabbit","Sheep","Silkworm","Turkey","Yak","Zebu"], - //list of pet animals comes from https://www.dogbreedinfo.com/pets/pet.htm - "pet" : ["Bearded Dragon","Birds","Burro","Cats","Chameleons","Chickens","Chinchillas","Chinese Water Dragon","Cows","Dogs","Donkey","Ducks","Ferrets","Fish","Geckos","Geese","Gerbils","Goats","Guinea Fowl","Guinea Pigs","Hamsters","Hedgehogs","Horses","Iguanas","Llamas","Lizards","Mice","Mule","Peafowl","Pigs and Hogs","Pigeons","Ponies","Pot Bellied Pig","Rabbits","Rats","Sheep","Skinks","Snakes","Stick Insects","Sugar Gliders","Tarantula","Turkeys","Turtles"], - //list of zoo animals comes from https://bronxzoo.com/animals - "zoo" : ["Aardvark","African Wild Dog","Aldabra Tortoise","American Alligator","American Bison","Amur Tiger","Anaconda","Andean Condor","Asian Elephant","Baby Doll Sheep","Bald Eagle","Barred Owl","Blue Iguana","Boer Goat","California Sea Lion","Caribbean Flamingo","Chinchilla","Collared Lemur","Coquerel's Sifaka","Cuban Amazon Parrot","Ebony Langur","Fennec Fox","Fossa","Gelada","Giant Anteater","Giraffe","Gorilla","Grizzly Bear","Henkel's Leaf-tailed Gecko","Indian Gharial","Indian Rhinoceros","King Cobra","King Vulture","Komodo Dragon","Linne's Two-toed Sloth","Lion","Little Penguin","Madagascar Tree Boa","Magellanic Penguin","Malayan Tapir","Malayan Tiger","Matschies Tree Kangaroo","Mini Donkey","Monarch Butterfly","Nile crocodile","North American Porcupine","Nubian Ibex","Okapi","Poison Dart Frog","Polar Bear","Pygmy Marmoset","Radiated Tortoise","Red Panda","Red Ruffed Lemur","Ring-tailed Lemur","Ring-tailed Mongoose","Rock Hyrax","Small Clawed Asian Otter","Snow Leopard","Snowy Owl","Southern White-faced Owl","Southern White Rhinocerous","Squirrel Monkey","Tufted Puffin","White Cheeked Gibbon","White-throated Bee Eater","Zebra"] - }, - primes: [ - // 1230 first primes, i.e. all primes up to the first one greater than 10000, inclusive. - 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,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007 - ], - emotions: [ - "love", - "joy", - "surprise", - "anger", - "sadness", - "fear" - ], - music_genres: { - 'general': [ - 'Rock', - 'Pop', - 'Hip-Hop', - 'Jazz', - 'Classical', - 'Electronic', - 'Country', - 'R&B', - 'Reggae', - 'Blues', - 'Metal', - 'Folk', - 'Alternative', - 'Punk', - 'Disco', - 'Funk', - 'Techno', - 'Indie', - 'Gospel', - 'Dance', - 'Children\'s', - 'World' - ], - 'alternative': [ - 'Art Punk', - 'Alternative Rock', - 'Britpunk', - 'College Rock', - 'Crossover Thrash', - 'Crust Punk', - 'Emo / Emocore', - 'Experimental Rock', - 'Folk Punk', - 'Goth / Gothic Rock', - 'Grunge', - 'Hardcore Punk', - 'Hard Rock', - 'Indie Rock', - 'Lo-fi', - 'Musique ConcrĆØte', - 'New Wave', - 'Progressive Rock', - 'Punk', - 'Shoegaze', - 'Steampunk', - ], 'blues': [ - 'Acoustic Blues', - 'African Blues', - 'Blues Rock', - 'Blues Shouter', - 'British Blues', - 'Canadian Blues', - 'Chicago Blues', - 'Classic Blues', - 'Classic Female Blues', - 'Contemporary Blues', - 'Country Blues', - 'Dark Blues', - 'Delta Blues', - 'Detroit Blues', - 'Doom Blues', - 'Electric Blues', - 'Folk Blues', - 'Gospel Blues', - 'Harmonica Blues', - 'Hill Country Blues', - 'Hokum Blues', - 'Jazz Blues', - 'Jump Blues', - 'Kansas City Blues', - 'Louisiana Blues', - 'Memphis Blues', - 'Modern Blues', - 'New Orlean Blues', - 'NY Blues', - 'Piano Blues', - 'Piedmont Blues', - 'Punk Blues', - 'Ragtime Blues', - 'Rhythm Blues', - 'Soul Blues', - 'St.Louis Blues', - 'Soul Blues', - 'Swamp Blues', - 'Texas Blues', - 'Urban Blues', - 'Vandeville', - 'West Coast Blues', - ], 'children\'s': [ - 'Lullabies', - 'Sing - Along', - 'Stories' - ], 'classical': [ - 'Avant-Garde', - 'Ballet', - 'Baroque', - 'Cantata', - 'Chamber Music', - 'String Quartet', - 'Chant', - 'Choral', - 'Classical Crossover', - 'Concerto', - 'Concerto Grosso', - 'Contemporary Classical', - 'Early Music', - 'Expressionist', - 'High Classical', - 'Impressionist', - 'Mass Requiem', - 'Medieval', - 'Minimalism', - 'Modern Composition', - 'Modern Classical', - 'Opera', - 'Oratorio', - 'Orchestral', - 'Organum', - 'Renaissance', - 'Romantic (early period)', - 'Romantic (later period)', - 'Sonata', - 'Symphonic', - 'Symphony', - 'Twelve-tone', - 'Wedding Music' - ], 'country': [ - 'Alternative Country', - 'Americana', - 'Australian Country', - 'Bakersfield Sound', - 'Bluegrass', - 'Blues Country', - 'Cajun Fiddle Tunes', - 'Christian Country', - 'Classic Country', - 'Close Harmony', - 'Contemporary Bluegrass', - 'Contemporary Country', - 'Country Gospel', - 'Country Pop', - 'Country Rap', - 'Country Rock', - 'Country Soul', - 'Cowboy / Western', - 'Cowpunk', - 'Dansband', - 'Honky Tonk', - 'Franco-Country', - 'Gulf and Western', - 'Hellbilly Music', - 'Honky Tonk', - 'Instrumental Country', - 'Lubbock Sound', - 'Nashville Sound', - 'Neotraditional Country', - 'Outlaw Country', - 'Progressive', - 'Psychobilly / Punkabilly', - 'Red Dirt', - 'Sertanejo', - 'Texas County', - 'Traditional Bluegrass', - 'Traditional Country', - 'Truck-Driving Country', - 'Urban Cowboy', - 'Western Swing' - ], 'dance': [ - 'Club / Club Dance', - 'Breakcore', - 'Breakbeat / Breakstep', - 'Chillstep', - 'Deep House', - 'Dubstep', - 'Dancehall', - 'Electro House', - 'Electroswing', - 'Exercise', - 'Future Garage', - 'Garage', - 'Glitch Hop', - 'Glitch Pop', - 'Grime', - 'Hardcore', - 'Hard Dance', - 'Hi-NRG / Eurodance', - 'Horrorcore', - 'House', - 'Jackin House', - 'Jungle / Drum n bass', - 'Liquid Dub', - 'Regstep', - 'Speedcore', - 'Techno', - 'Trance', - 'Trap' - ], electronic: [ - '2-Step', - '8bit', - 'Ambient', - 'Asian Underground', - 'Bassline', - 'Chillwave', - 'Chiptune', - 'Crunk', - 'Downtempo', - 'Drum & Bass', - 'Hard Step', - 'Electro', - 'Electro-swing', - 'Electroacoustic', - 'Electronica', - 'Electronic Rock', - 'Eurodance', - 'Hardstyle', - 'Hi-Nrg', - 'IDM/Experimental', - 'Industrial', - 'Trip Hop', - 'Vaporwave', - 'UK Garage', - 'House', - 'Dubstep', - 'Deep House', - 'EDM', - 'Future Bass', - 'Psychedelic trance' - ], 'jazz' : [ - 'Acid Jazz', - 'Afro-Cuban Jazz', - 'Avant-Garde Jazz', - 'Bebop', - 'Big Band', - 'Blue Note', - 'British Dance Band (Jazz)', - 'Cape Jazz', - 'Chamber Jazz', - 'Contemporary Jazz', - 'Continental Jazz', - 'Cool Jazz', - 'Crossover Jazz', - 'Dark Jazz', - 'Dixieland', - 'Early Jazz', - 'Electro Swing (Jazz)', - 'Ethio-jazz', - 'Ethno-Jazz', - 'European Free Jazz', - 'Free Funk (Avant-Garde / Funk Jazz)', - 'Free Jazz', - 'Fusion', - 'Gypsy Jazz', - 'Hard Bop', - 'Indo Jazz', - 'Jazz Blues', - 'Jazz-Funk (see Free Funk)', - 'Jazz-Fusion', - 'Jazz Rap', - 'Jazz Rock', - 'Kansas City Jazz', - 'Latin Jazz', - 'M-Base Jazz', - 'Mainstream Jazz', - 'Modal Jazz', - 'Neo-Bop', - 'Neo-Swing', - 'Nu Jazz', - 'Orchestral Jazz', - 'Post-Bop', - 'Punk Jazz', - 'Ragtime', - 'Ska Jazz', - 'Skiffle (also Folk)', - 'Smooth Jazz', - 'Soul Jazz', - 'Swing Jazz', - 'Straight-Ahead Jazz', - 'Trad Jazz', - 'Third Stream', - 'Jazz-Funk', - 'Free Jazz', - 'West Coast Jazz' - ], 'metal': [ - 'Heavy Metal', - 'Speed Metal', - 'Thrash Metal', - 'Power Metal', - 'Death Metal', - 'Black Metal', - 'Pagan Metal', - 'Viking Metal', - 'Folk Metal', - 'Symphonic Metal', - 'Gothic Metal', - 'Glam Metal', - 'Hair Metal', - 'Doom Metal', - 'Groove Metal', - 'Industrial Metal', - 'Modern Metal', - 'Neoclassical Metal', - 'New Wave Of British Heavy Metal', - 'Post Metal', - 'Progressive Metal', - 'Avantgarde Metal', - 'Sludge', - 'Djent', - 'Drone', - 'Kawaii Metal', - 'Pirate Metal', - 'Nu Metal', - 'Neue Deutsche HƤrte', - 'Math Metal', - 'Crossover', - 'Grindcore', - 'Hardcore', - 'Metalcore', - 'Deathcore', - 'Post Hardcore', - 'Mathcore' - ], 'folk': [ - 'American Folk Revival', - 'Anti - Folk', - 'British Folk Revival', - 'Contemporary Folk', - 'Filk Music', - 'Freak Folk', - 'Indie Folk', - 'Industrial Folk', - 'Neofolk', - 'Progressive Folk', - 'Psychedelic Folk', - 'Sung Poetry', - 'Techno - Folk', - 'Folk Rock', - 'Old-time Music', - 'Bluegrass', - 'Appalachian', - 'Roots Revival', - 'Celtic', - 'Indie Folk' - ], 'pop': [ - 'Adult Contemporary', - 'Arab Pop', - 'Baroque', - 'Britpop', - 'Bubblegum Pop', - 'Chamber Pop', - 'Chanson', - 'Christian Pop', - 'Classical Crossover', - 'Europop', - 'Austropop', - 'Balkan Pop', - 'French Pop', - 'Korean Pop', - 'Japanese Pop', - 'Chinese Pop', - 'Latin Pop', - 'LaĆÆkó', - 'Nederpop', - 'Russian Pop', - 'Dance Pop', - 'Dream Pop', - 'Electro Pop', - 'Iranian Pop', - 'Jangle Pop', - 'Latin Ballad', - 'Levenslied', - 'Louisiana Swamp Pop', - 'Mexican Pop', - 'Motorpop', - 'New Romanticism', - 'Orchestral Pop', - 'Pop Rap', - 'Popera', - 'Pop / Rock', - 'Pop Punk', - 'Power Pop', - 'Psychedelic Pop', - 'Russian Pop', - 'Schlager', - 'Soft Rock', - 'Sophisti - Pop', - 'Space Age Pop', - 'Sunshine Pop', - 'Surf Pop', - 'Synthpop', - 'Teen Pop', - 'Traditional Pop Music', - 'Turkish Pop', - 'Vispop', - 'Wonky Pop' - ], 'r&b': [ - '(Carolina) Beach Music', - 'Contemporary R & B', - 'Disco', - 'Doo Wop', - 'Funk', - 'Modern Soul', - 'Motown', - 'Neo - Soul', - 'Northern Soul', - 'Psychedelic Soul', - 'Quiet Storm', - 'Soul', - 'Soul Blues', - 'Southern Soul' - ], 'reggae': [ - '2 - Tone', - 'Dub', - 'Roots Reggae', - 'Reggae Fusion', - 'Reggae en EspaƱol', - 'Spanish Reggae', - 'Reggae 110', - 'Reggae Bultrón', - 'Romantic Flow', - 'Lovers Rock', - 'Raggamuffin', - 'Ragga', - 'Dancehall', - 'Ska', - ], 'rock': [ - 'Acid Rock', - 'Adult - Oriented Rock', - 'Afro Punk', - 'Adult Alternative', - 'Alternative Rock', - 'American Traditional Rock', - 'Anatolian Rock', - 'Arena Rock', - 'Art Rock', - 'Blues - Rock', - 'British Invasion', - 'Cock Rock', - 'Death Metal / Black Metal', - 'Doom Metal', - 'Glam Rock', - 'Gothic Metal', - 'Grind Core', - 'Hair Metal', - 'Hard Rock', - 'Math Metal', - 'Math Rock', - 'Metal', - 'Metal Core', - 'Noise Rock', - 'Jam Bands', - 'Post Punk', - 'Post Rock', - 'Prog - Rock / Art Rock', - 'Progressive Metal', - 'Psychedelic', - 'Rock & Roll', - 'Rockabilly', - 'Roots Rock', - 'Singer / Songwriter', - 'Southern Rock', - 'Spazzcore', - 'Stoner Metal', - 'Surf', - 'Technical Death Metal', - 'Tex - Mex', - 'Thrash Metal', - 'Time Lord Rock(Trock)', - 'Trip - hop', - 'Yacht Rock', - 'School House Rock' - ], 'hip-hop': [ - 'Alternative Rap', - 'Avant - Garde', - 'Bounce', - 'Chap Hop', - 'Christian Hip Hop', - 'Conscious Hip Hop', - 'Country - Rap', - 'Grunk', - 'Crunkcore', - 'Cumbia Rap', - 'Dirty South', - 'East Coast', - 'Brick City Club', - 'Hardcore Hip Hop', - 'Mafioso Rap', - 'New Jersey Hip Hop', - 'Freestyle Rap', - 'G - Funk', - 'Gangsta Rap', - 'Golden Age', - 'Grime', - 'Hardcore Rap', - 'Hip - Hop', - 'Hip Pop', - 'Horrorcore', - 'Hyphy', - 'Industrial Hip Hop', - 'Instrumental Hip Hop', - 'Jazz Rap', - 'Latin Rap', - 'Low Bap', - 'Lyrical Hip Hop', - 'Merenrap', - 'Midwest Hip Hop', - 'Chicago Hip Hop', - 'Detroit Hip Hop', - 'Horrorcore', - 'St.Louis Hip Hop', - 'Twin Cities Hip Hop', - 'Motswako', - 'Nerdcore', - 'New Jack Swing', - 'New School Hip Hop', - 'Old School Rap', - 'Rap', - 'Trap', - 'Turntablism', - 'Underground Rap', - 'West Coast Rap', - 'East Coast Rap', - 'Trap', - 'UK Grime', - 'Hyphy', - 'Emo-rap', - 'Cloud rap', - 'G-funk', - 'Boom Bap', - 'Mumble', - 'Drill', - 'UK Drill', - 'Soundcloud Rap', - 'Lo-fi' - ], 'punk': [ - 'Afro-punk', - 'Anarcho punk', - 'Art punk', - 'Christian punk', - 'Crust punk', - 'Deathrock', - 'Egg punk', - 'Garage punk', - 'Glam punk', - 'Hardcore punk', - 'Horror punk', - 'Incelcore/e-punk', - 'Oi!', - 'Peace punk', - 'Punk pathetique', - 'Queercore', - 'Riot Grrrl', - 'Skate punk', - 'Street punk', - 'Taqwacore', - 'Trallpunk' - ], 'disco': [ - 'Nu-disco', - 'Disco-funk', - 'Hi-NRG', - 'Italo Disco', - 'Eurodisco', - 'Boogie', - 'Space Disco', - 'Post-disco', - 'Electro Disco', - 'Disco House', - 'Disco Pop', - 'Soulful House' - ], 'funk': [ - 'Funk Rock', - 'P-Funk (Parliament-Funkadelic)', - 'Psychedelic Funk', - 'Funk Metal', - 'Electro-Funk', - 'Go-go', - 'Boogie-Funk', - 'Jazz-Funk', - 'Soul-Funk', - 'Funky Disco', - 'Nu-Funk', - 'Afrobeat', - 'Latin Funk', - 'G-Funk', - 'Acid Jazz', - 'Funktronica', - 'Folk-Funk', - 'Space Funk', - 'Ambient Funk', - 'Hard Funk', - 'Fusion Funk' - ], 'techno': [ - 'Acid Techno', - 'Ambient Techno', - 'Detroit Techno', - 'Dub Techno', - 'Minimal Techno', - 'Industrial Techno', - 'Hard Techno', - 'Trance', - 'Progressive Techno', - 'Tech House', - 'Electronica', - 'Breakbeat Techno', - 'Electro Techno', - 'Melodic Techno', - 'Experimental Techno', - 'Dark Techno', - 'Ebm', - 'Hypnotic Techno', - 'Psychedelic Techno', - 'Rave Techno', - 'Techno-Pop' - ], 'indie': [ - 'Indie Rock', - 'Indie Pop', - 'Indie Folk', - 'Indie Electronic', - 'Indie Punk', - 'Indie Hip-Hop', - 'Dream Pop', - 'Shoegaze', - 'Lo-fi', - 'Chillwave', - 'Freak Folk', - 'Noise Pop', - 'Math Rock', - 'Post-Punk', - 'Garage Rock', - 'Experimental Indie', - 'Surf Rock', - 'Alternative Country', - 'Indie Soul', - 'Art Rock', - 'Indie R&B', - 'Indietronica', - 'Emo', - 'Post-Rock', - 'Indie Pop-Rock', - 'Indie Synthpop', - 'Noise Rock', - 'Psych Folk', - 'Indie Blues' - ], 'gospel': [ - 'Traditional Gospel', - 'Contemporary Gospel', - 'Southern Gospel', - 'Black Gospel', - 'Urban Contemporary Gospel', - 'Gospel Blues', - 'Bluegrass Gospel', - 'Country Gospel', - 'Praise and Worship', - 'Christian Hip-Hop', - 'Gospel Jazz', - 'Reggae Gospel', - 'African Gospel', - 'Latin Gospel', - 'R&B Gospel', - 'Gospel Choir', - 'Acappella Gospel', - 'Instrumental Gospel', - 'Gospel Rap' - ], 'world': [ - 'African', - 'Arabic', - 'Asian', - 'Caribbean', - 'Celtic', - 'European', - 'Latin American', - 'Middle Eastern', - 'Native American', - 'Polynesian', - 'Reggae', - 'Ska', - 'Salsa', - 'Flamenco', - 'Bossa Nova', - 'Tango', - 'Fado', - 'Klezmer', - 'Balkan', - 'Afrobeat', - 'Mongolian Throat Singing', - 'Indian Classical', - 'Gamelan', - 'Sufi Music', - 'Zydeco', - 'Kora Music', - 'Andean Music', - 'Irish Traditional', - 'Gypsy Jazz', - 'Bollywood', - 'Bhangra', - 'Jawaiian', - 'Hawaiian Slack Key Guitar', - 'Calypso', - 'Cuban Son', - 'Taiko Drumming', - 'African Highlife', - 'Merengue', - 'Tuvan Throat Singing' - ] - }, - - // Data sourced from https://unicode.org/emoji/charts/full-emoji-list.html - emojis: { - "smileys_and_emotion": [ - "0x1f600", - "0x1f603", - "0x1f604", - "0x1f601", - "0x1f606", - "0x1f605", - "0x1f923", - "0x1f602", - "0x1f642", - "0x1f643", - "0x1fae0", - "0x1f609", - "0x1f60a", - "0x1f607", - "0x1f970", - "0x1f60d", - "0x1f929", - "0x1f618", - "0x1f617", - "0x263a", - "0x1f61a", - "0x1f619", - "0x1f972", - "0x1f60b", - "0x1f61b", - "0x1f61c", - "0x1f92a", - "0x1f61d", - "0x1f911", - "0x1f917", - "0x1f92d", - "0x1fae2", - "0x1fae3", - "0x1f92b", - "0x1f914", - "0x1fae1", - "0x1f910", - "0x1f928", - "0x1f610", - "0x1f611", - "0x1f636", - "0x1fae5", - "0x1f636", - "0x200d", - "0x1f32b", - "0xfe0f", - "0x1f60f", - "0x1f612", - "0x1f644", - "0x1f62c", - "0x1f62e", - "0x200d", - "0x1f4a8", - "0x1f925", - "0x1fae8", - "0x1f642", - "0x200d", - "0x2194", - "0xfe0f", - "0x1f642", - "0x200d", - "0x2195", - "0xfe0f", - "0x1f60c", - "0x1f614", - "0x1f62a", - "0x1f924", - "0x1f634", - "0x1f637", - "0x1f912", - "0x1f915", - "0x1f922", - "0x1f92e", - "0x1f927", - "0x1f975", - "0x1f976", - "0x1f974", - "0x1f635", - "0x1f635", - "0x200d", - "0x1f4ab", - "0x1f92f", - "0x1f920", - "0x1f973", - "0x1f978", - "0x1f60e", - "0x1f913", - "0x1f9d0", - "0x1f615", - "0x1fae4", - "0x1f61f", - "0x1f641", - "0x2639", - "0x1f62e", - "0x1f62f", - "0x1f632", - "0x1f633", - "0x1f97a", - "0x1f979", - "0x1f626", - "0x1f627", - "0x1f628", - "0x1f630", - "0x1f625", - "0x1f622", - "0x1f62d", - "0x1f631", - "0x1f616", - "0x1f623", - "0x1f61e", - "0x1f613", - "0x1f629", - "0x1f62b", - "0x1f971", - "0x1f624", - "0x1f621", - "0x1f620", - "0x1f92c", - "0x1f608", - "0x1f47f", - "0x1f480", - "0x2620", - "0x1f4a9", - "0x1f921", - "0x1f479", - "0x1f47a", - "0x1f47b", - "0x1f47d", - "0x1f47e", - "0x1f916", - "0x1f63a", - "0x1f638", - "0x1f639", - "0x1f63b", - "0x1f63c", - "0x1f63d", - "0x1f640", - "0x1f63f", - "0x1f63e", - "0x1f648", - "0x1f649", - "0x1f64a", - "0x1f48c", - "0x1f498", - "0x1f49d", - "0x1f496", - "0x1f497", - "0x1f493", - "0x1f49e", - "0x1f495", - "0x1f49f", - "0x2763", - "0x1f494", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f525", - "0x2764", - "0xfe0f", - "0x200d", - "0x1fa79", - "0x2764", - "0x1fa77", - "0x1f9e1", - "0x1f49b", - "0x1f49a", - "0x1f499", - "0x1fa75", - "0x1f49c", - "0x1f90e", - "0x1f5a4", - "0x1fa76", - "0x1f90d", - "0x1f48b", - "0x1f4af", - "0x1f4a2", - "0x1f4a5", - "0x1f4ab", - "0x1f4a6", - "0x1f4a8", - "0x1f573", - "0x1f4ac", - "0x1f441", - "0xfe0f", - "0x200d", - "0x1f5e8", - "0xfe0f", - "0x1f5e8", - "0x1f5ef", - "0x1f4ad", - "0x1f4a4" - ], - "people_and_body": [ - "0x1f44b", - "0x1f91a", - "0x1f590", - "0x270b", - "0x1f596", - "0x1faf1", - "0x1faf2", - "0x1faf3", - "0x1faf4", - "0x1faf7", - "0x1faf8", - "0x1f44c", - "0x1f90c", - "0x1f90f", - "0x270c", - "0x1f91e", - "0x1faf0", - "0x1f91f", - "0x1f918", - "0x1f919", - "0x1f448", - "0x1f449", - "0x1f446", - "0x1f595", - "0x1f447", - "0x261d", - "0x1faf5", - "0x1f44d", - "0x1f44e", - "0x270a", - "0x1f44a", - "0x1f91b", - "0x1f91c", - "0x1f44f", - "0x1f64c", - "0x1faf6", - "0x1f450", - "0x1f932", - "0x1f91d", - "0x1f64f", - "0x270d", - "0x1f485", - "0x1f933", - "0x1f4aa", - "0x1f9be", - "0x1f9bf", - "0x1f9b5", - "0x1f9b6", - "0x1f442", - "0x1f9bb", - "0x1f443", - "0x1f9e0", - "0x1fac0", - "0x1fac1", - "0x1f9b7", - "0x1f9b4", - "0x1f440", - "0x1f441", - "0x1f445", - "0x1f444", - "0x1fae6", - "0x1f476", - "0x1f9d2", - "0x1f466", - "0x1f467", - "0x1f9d1", - "0x1f471", - "0x1f468", - "0x1f9d4", - "0x1f9d4", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d4", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9b0", - "0x1f468", - "0x200d", - "0x1f9b1", - "0x1f468", - "0x200d", - "0x1f9b3", - "0x1f468", - "0x200d", - "0x1f9b2", - "0x1f469", - "0x1f469", - "0x200d", - "0x1f9b0", - "0x1f9d1", - "0x200d", - "0x1f9b0", - "0x1f469", - "0x200d", - "0x1f9b1", - "0x1f9d1", - "0x200d", - "0x1f9b1", - "0x1f469", - "0x200d", - "0x1f9b3", - "0x1f9d1", - "0x200d", - "0x1f9b3", - "0x1f469", - "0x200d", - "0x1f9b2", - "0x1f9d1", - "0x200d", - "0x1f9b2", - "0x1f471", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f471", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d3", - "0x1f474", - "0x1f475", - "0x1f64d", - "0x1f64d", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f64d", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f64e", - "0x1f64e", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f64e", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f645", - "0x1f645", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f645", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f646", - "0x1f646", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f646", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f481", - "0x1f481", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f481", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f64b", - "0x1f64b", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f64b", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9cf", - "0x1f9cf", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9cf", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f647", - "0x1f647", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f647", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f926", - "0x1f926", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f926", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f937", - "0x1f937", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f937", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x2695", - "0xfe0f", - "0x1f468", - "0x200d", - "0x2695", - "0xfe0f", - "0x1f469", - "0x200d", - "0x2695", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f393", - "0x1f468", - "0x200d", - "0x1f393", - "0x1f469", - "0x200d", - "0x1f393", - "0x1f9d1", - "0x200d", - "0x1f3eb", - "0x1f468", - "0x200d", - "0x1f3eb", - "0x1f469", - "0x200d", - "0x1f3eb", - "0x1f9d1", - "0x200d", - "0x2696", - "0xfe0f", - "0x1f468", - "0x200d", - "0x2696", - "0xfe0f", - "0x1f469", - "0x200d", - "0x2696", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f33e", - "0x1f468", - "0x200d", - "0x1f33e", - "0x1f469", - "0x200d", - "0x1f33e", - "0x1f9d1", - "0x200d", - "0x1f373", - "0x1f468", - "0x200d", - "0x1f373", - "0x1f469", - "0x200d", - "0x1f373", - "0x1f9d1", - "0x200d", - "0x1f527", - "0x1f468", - "0x200d", - "0x1f527", - "0x1f469", - "0x200d", - "0x1f527", - "0x1f9d1", - "0x200d", - "0x1f3ed", - "0x1f468", - "0x200d", - "0x1f3ed", - "0x1f469", - "0x200d", - "0x1f3ed", - "0x1f9d1", - "0x200d", - "0x1f4bc", - "0x1f468", - "0x200d", - "0x1f4bc", - "0x1f469", - "0x200d", - "0x1f4bc", - "0x1f9d1", - "0x200d", - "0x1f52c", - "0x1f468", - "0x200d", - "0x1f52c", - "0x1f469", - "0x200d", - "0x1f52c", - "0x1f9d1", - "0x200d", - "0x1f4bb", - "0x1f468", - "0x200d", - "0x1f4bb", - "0x1f469", - "0x200d", - "0x1f4bb", - "0x1f9d1", - "0x200d", - "0x1f3a4", - "0x1f468", - "0x200d", - "0x1f3a4", - "0x1f469", - "0x200d", - "0x1f3a4", - "0x1f9d1", - "0x200d", - "0x1f3a8", - "0x1f468", - "0x200d", - "0x1f3a8", - "0x1f469", - "0x200d", - "0x1f3a8", - "0x1f9d1", - "0x200d", - "0x2708", - "0xfe0f", - "0x1f468", - "0x200d", - "0x2708", - "0xfe0f", - "0x1f469", - "0x200d", - "0x2708", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f680", - "0x1f468", - "0x200d", - "0x1f680", - "0x1f469", - "0x200d", - "0x1f680", - "0x1f9d1", - "0x200d", - "0x1f692", - "0x1f468", - "0x200d", - "0x1f692", - "0x1f469", - "0x200d", - "0x1f692", - "0x1f46e", - "0x1f46e", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f46e", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f575", - "0x1f575", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f575", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f482", - "0x1f482", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f482", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f977", - "0x1f477", - "0x1f477", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f477", - "0x200d", - "0x2640", - "0xfe0f", - "0x1fac5", - "0x1f934", - "0x1f478", - "0x1f473", - "0x1f473", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f473", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f472", - "0x1f9d5", - "0x1f935", - "0x1f935", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f935", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f470", - "0x1f470", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f470", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f930", - "0x1fac3", - "0x1fac4", - "0x1f931", - "0x1f469", - "0x200d", - "0x1f37c", - "0x1f468", - "0x200d", - "0x1f37c", - "0x1f9d1", - "0x200d", - "0x1f37c", - "0x1f47c", - "0x1f385", - "0x1f936", - "0x1f9d1", - "0x200d", - "0x1f384", - "0x1f9b8", - "0x1f9b8", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9b8", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9b9", - "0x1f9b9", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9b9", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d9", - "0x1f9d9", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d9", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9da", - "0x1f9da", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9da", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9db", - "0x1f9db", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9db", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9dc", - "0x1f9dc", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9dc", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9dd", - "0x1f9dd", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9dd", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9de", - "0x1f9de", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9de", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9df", - "0x1f9df", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9df", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9cc", - "0x1f486", - "0x1f486", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f486", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f487", - "0x1f487", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f487", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b6", - "0x1f6b6", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x2640", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f6b6", - "0x200d", - "0x2642", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9cd", - "0x1f9cd", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9cd", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9ce", - "0x1f9ce", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x2640", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9ce", - "0x200d", - "0x2642", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f9af", - "0x1f9d1", - "0x200d", - "0x1f9af", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9af", - "0x1f468", - "0x200d", - "0x1f9af", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f469", - "0x200d", - "0x1f9af", - "0x1f469", - "0x200d", - "0x1f9af", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f9bc", - "0x1f9d1", - "0x200d", - "0x1f9bc", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9bc", - "0x1f468", - "0x200d", - "0x1f9bc", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f469", - "0x200d", - "0x1f9bc", - "0x1f469", - "0x200d", - "0x1f9bc", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f9d1", - "0x200d", - "0x1f9bd", - "0x1f9d1", - "0x200d", - "0x1f9bd", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f468", - "0x200d", - "0x1f9bd", - "0x1f468", - "0x200d", - "0x1f9bd", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f469", - "0x200d", - "0x1f9bd", - "0x1f469", - "0x200d", - "0x1f9bd", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f3c3", - "0x1f3c3", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x2640", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f3c3", - "0x200d", - "0x2642", - "0xfe0f", - "0x200d", - "0x27a1", - "0xfe0f", - "0x1f483", - "0x1f57a", - "0x1f574", - "0x1f46f", - "0x1f46f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f46f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d6", - "0x1f9d6", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d6", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d7", - "0x1f9d7", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d7", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93a", - "0x1f3c7", - "0x26f7", - "0x1f3c2", - "0x1f3cc", - "0x1f3cc", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3cc", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3c4", - "0x1f3c4", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3c4", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6a3", - "0x1f6a3", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6a3", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3ca", - "0x1f3ca", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3ca", - "0x200d", - "0x2640", - "0xfe0f", - "0x26f9", - "0x26f9", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x26f9", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f3cb", - "0x1f3cb", - "0xfe0f", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f3cb", - "0xfe0f", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b4", - "0x1f6b4", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6b4", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6b5", - "0x1f6b5", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f6b5", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f938", - "0x1f938", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f938", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93c", - "0x1f93c", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f93c", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93d", - "0x1f93d", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f93d", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f93e", - "0x1f93e", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f93e", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f939", - "0x1f939", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f939", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f9d8", - "0x1f9d8", - "0x200d", - "0x2642", - "0xfe0f", - "0x1f9d8", - "0x200d", - "0x2640", - "0xfe0f", - "0x1f6c0", - "0x1f6cc", - "0x1f9d1", - "0x200d", - "0x1f91d", - "0x200d", - "0x1f9d1", - "0x1f46d", - "0x1f46b", - "0x1f46c", - "0x1f48f", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f48b", - "0x200d", - "0x1f468", - "0x1f468", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f48b", - "0x200d", - "0x1f468", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f48b", - "0x200d", - "0x1f469", - "0x1f491", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f468", - "0x1f468", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f468", - "0x1f469", - "0x200d", - "0x2764", - "0xfe0f", - "0x200d", - "0x1f469", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f467", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f468", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f466", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f467", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f466", - "0x1f469", - "0x200d", - "0x1f467", - "0x200d", - "0x1f467", - "0x1f5e3", - "0x1f464", - "0x1f465", - "0x1fac2", - "0x1f46a", - "0x1f9d1", - "0x200d", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x1f9d1", - "0x200d", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x200d", - "0x1f9d2", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x1f9d1", - "0x200d", - "0x1f9d2", - "0x200d", - "0x1f9d2", - "0x1f463" - ], - "animals_and_nature": [ - "0x1f435", - "0x1f412", - "0x1f98d", - "0x1f9a7", - "0x1f436", - "0x1f415", - "0x1f9ae", - "0x1f415", - "0x200d", - "0x1f9ba", - "0x1f429", - "0x1f43a", - "0x1f98a", - "0x1f99d", - "0x1f431", - "0x1f408", - "0x1f408", - "0x200d", - "0x2b1b", - "0x1f981", - "0x1f42f", - "0x1f405", - "0x1f406", - "0x1f434", - "0x1face", - "0x1facf", - "0x1f40e", - "0x1f984", - "0x1f993", - "0x1f98c", - "0x1f9ac", - "0x1f42e", - "0x1f402", - "0x1f403", - "0x1f404", - "0x1f437", - "0x1f416", - "0x1f417", - "0x1f43d", - "0x1f40f", - "0x1f411", - "0x1f410", - "0x1f42a", - "0x1f42b", - "0x1f999", - "0x1f992", - "0x1f418", - "0x1f9a3", - "0x1f98f", - "0x1f99b", - "0x1f42d", - "0x1f401", - "0x1f400", - "0x1f439", - "0x1f430", - "0x1f407", - "0x1f43f", - "0x1f9ab", - "0x1f994", - "0x1f987", - "0x1f43b", - "0x1f43b", - "0x200d", - "0x2744", - "0xfe0f", - "0x1f428", - "0x1f43c", - "0x1f9a5", - "0x1f9a6", - "0x1f9a8", - "0x1f998", - "0x1f9a1", - "0x1f43e", - "0x1f983", - "0x1f414", - "0x1f413", - "0x1f423", - "0x1f424", - "0x1f425", - "0x1f426", - "0x1f427", - "0x1f54a", - "0x1f985", - "0x1f986", - "0x1f9a2", - "0x1f989", - "0x1f9a4", - "0x1fab6", - "0x1f9a9", - "0x1f99a", - "0x1f99c", - "0x1fabd", - "0x1f426", - "0x200d", - "0x2b1b", - "0x1fabf", - "0x1f426", - "0x200d", - "0x1f525", - "0x1f438", - "0x1f40a", - "0x1f422", - "0x1f98e", - "0x1f40d", - "0x1f432", - "0x1f409", - "0x1f995", - "0x1f996", - "0x1f433", - "0x1f40b", - "0x1f42c", - "0x1f9ad", - "0x1f41f", - "0x1f420", - "0x1f421", - "0x1f988", - "0x1f419", - "0x1f41a", - "0x1fab8", - "0x1fabc", - "0x1f40c", - "0x1f98b", - "0x1f41b", - "0x1f41c", - "0x1f41d", - "0x1fab2", - "0x1f41e", - "0x1f997", - "0x1fab3", - "0x1f577", - "0x1f578", - "0x1f982", - "0x1f99f", - "0x1fab0", - "0x1fab1", - "0x1f9a0", - "0x1f490", - "0x1f338", - "0x1f4ae", - "0x1fab7", - "0x1f3f5", - "0x1f339", - "0x1f940", - "0x1f33a", - "0x1f33b", - "0x1f33c", - "0x1f337", - "0x1fabb", - "0x1f331", - "0x1fab4", - "0x1f332", - "0x1f333", - "0x1f334", - "0x1f335", - "0x1f33e", - "0x1f33f", - "0x2618", - "0x1f340", - "0x1f341", - "0x1f342", - "0x1f343", - "0x1fab9", - "0x1faba", - "0x1f344" - ], - "food_and_drink": [ - "0x1f347", - "0x1f348", - "0x1f349", - "0x1f34a", - "0x1f34b", - "0x1f34b", - "0x200d", - "0x1f7e9", - "0x1f34c", - "0x1f34d", - "0x1f96d", - "0x1f34e", - "0x1f34f", - "0x1f350", - "0x1f351", - "0x1f352", - "0x1f353", - "0x1fad0", - "0x1f95d", - "0x1f345", - "0x1fad2", - "0x1f965", - "0x1f951", - "0x1f346", - "0x1f954", - "0x1f955", - "0x1f33d", - "0x1f336", - "0x1fad1", - "0x1f952", - "0x1f96c", - "0x1f966", - "0x1f9c4", - "0x1f9c5", - "0x1f95c", - "0x1fad8", - "0x1f330", - "0x1fada", - "0x1fadb", - "0x1f344", - "0x200d", - "0x1f7eb", - "0x1f35e", - "0x1f950", - "0x1f956", - "0x1fad3", - "0x1f968", - "0x1f96f", - "0x1f95e", - "0x1f9c7", - "0x1f9c0", - "0x1f356", - "0x1f357", - "0x1f969", - "0x1f953", - "0x1f354", - "0x1f35f", - "0x1f355", - "0x1f32d", - "0x1f96a", - "0x1f32e", - "0x1f32f", - "0x1fad4", - "0x1f959", - "0x1f9c6", - "0x1f95a", - "0x1f373", - "0x1f958", - "0x1f372", - "0x1fad5", - "0x1f963", - "0x1f957", - "0x1f37f", - "0x1f9c8", - "0x1f9c2", - "0x1f96b", - "0x1f371", - "0x1f358", - "0x1f359", - "0x1f35a", - "0x1f35b", - "0x1f35c", - "0x1f35d", - "0x1f360", - "0x1f362", - "0x1f363", - "0x1f364", - "0x1f365", - "0x1f96e", - "0x1f361", - "0x1f95f", - "0x1f960", - "0x1f961", - "0x1f980", - "0x1f99e", - "0x1f990", - "0x1f991", - "0x1f9aa", - "0x1f366", - "0x1f367", - "0x1f368", - "0x1f369", - "0x1f36a", - "0x1f382", - "0x1f370", - "0x1f9c1", - "0x1f967", - "0x1f36b", - "0x1f36c", - "0x1f36d", - "0x1f36e", - "0x1f36f", - "0x1f37c", - "0x1f95b", - "0x2615", - "0x1fad6", - "0x1f375", - "0x1f376", - "0x1f37e", - "0x1f377", - "0x1f378", - "0x1f379", - "0x1f37a", - "0x1f37b", - "0x1f942", - "0x1f943", - "0x1fad7", - "0x1f964", - "0x1f9cb", - "0x1f9c3", - "0x1f9c9", - "0x1f9ca", - "0x1f962", - "0x1f37d", - "0x1f374", - "0x1f944", - "0x1f52a", - "0x1fad9", - "0x1f3fa" - ], - "travel_and_places": [ - "0x1f30d", - "0x1f30e", - "0x1f30f", - "0x1f310", - "0x1f5fa", - "0x1f5fe", - "0x1f9ed", - "0x1f3d4", - "0x26f0", - "0x1f30b", - "0x1f5fb", - "0x1f3d5", - "0x1f3d6", - "0x1f3dc", - "0x1f3dd", - "0x1f3de", - "0x1f3df", - "0x1f3db", - "0x1f3d7", - "0x1f9f1", - "0x1faa8", - "0x1fab5", - "0x1f6d6", - "0x1f3d8", - "0x1f3da", - "0x1f3e0", - "0x1f3e1", - "0x1f3e2", - "0x1f3e3", - "0x1f3e4", - "0x1f3e5", - "0x1f3e6", - "0x1f3e8", - "0x1f3e9", - "0x1f3ea", - "0x1f3eb", - "0x1f3ec", - "0x1f3ed", - "0x1f3ef", - "0x1f3f0", - "0x1f492", - "0x1f5fc", - "0x1f5fd", - "0x26ea", - "0x1f54c", - "0x1f6d5", - "0x1f54d", - "0x26e9", - "0x1f54b", - "0x26f2", - "0x26fa", - "0x1f301", - "0x1f303", - "0x1f3d9", - "0x1f304", - "0x1f305", - "0x1f306", - "0x1f307", - "0x1f309", - "0x2668", - "0x1f3a0", - "0x1f6dd", - "0x1f3a1", - "0x1f3a2", - "0x1f488", - "0x1f3aa", - "0x1f682", - "0x1f683", - "0x1f684", - "0x1f685", - "0x1f686", - "0x1f687", - "0x1f688", - "0x1f689", - "0x1f68a", - "0x1f69d", - "0x1f69e", - "0x1f68b", - "0x1f68c", - "0x1f68d", - "0x1f68e", - "0x1f690", - "0x1f691", - "0x1f692", - "0x1f693", - "0x1f694", - "0x1f695", - "0x1f696", - "0x1f697", - "0x1f698", - "0x1f699", - "0x1f6fb", - "0x1f69a", - "0x1f69b", - "0x1f69c", - "0x1f3ce", - "0x1f3cd", - "0x1f6f5", - "0x1f9bd", - "0x1f9bc", - "0x1f6fa", - "0x1f6b2", - "0x1f6f4", - "0x1f6f9", - "0x1f6fc", - "0x1f68f", - "0x1f6e3", - "0x1f6e4", - "0x1f6e2", - "0x26fd", - "0x1f6de", - "0x1f6a8", - "0x1f6a5", - "0x1f6a6", - "0x1f6d1", - "0x1f6a7", - "0x2693", - "0x1f6df", - "0x26f5", - "0x1f6f6", - "0x1f6a4", - "0x1f6f3", - "0x26f4", - "0x1f6e5", - "0x1f6a2", - "0x2708", - "0x1f6e9", - "0x1f6eb", - "0x1f6ec", - "0x1fa82", - "0x1f4ba", - "0x1f681", - "0x1f69f", - "0x1f6a0", - "0x1f6a1", - "0x1f6f0", - "0x1f680", - "0x1f6f8", - "0x1f6ce", - "0x1f9f3", - "0x231b", - "0x23f3", - "0x231a", - "0x23f0", - "0x23f1", - "0x23f2", - "0x1f570", - "0x1f55b", - "0x1f567", - "0x1f550", - "0x1f55c", - "0x1f551", - "0x1f55d", - "0x1f552", - "0x1f55e", - "0x1f553", - "0x1f55f", - "0x1f554", - "0x1f560", - "0x1f555", - "0x1f561", - "0x1f556", - "0x1f562", - "0x1f557", - "0x1f563", - "0x1f558", - "0x1f564", - "0x1f559", - "0x1f565", - "0x1f55a", - "0x1f566", - "0x1f311", - "0x1f312", - "0x1f313", - "0x1f314", - "0x1f315", - "0x1f316", - "0x1f317", - "0x1f318", - "0x1f319", - "0x1f31a", - "0x1f31b", - "0x1f31c", - "0x1f321", - "0x2600", - "0x1f31d", - "0x1f31e", - "0x1fa90", - "0x2b50", - "0x1f31f", - "0x1f320", - "0x1f30c", - "0x2601", - "0x26c5", - "0x26c8", - "0x1f324", - "0x1f325", - "0x1f326", - "0x1f327", - "0x1f328", - "0x1f329", - "0x1f32a", - "0x1f32b", - "0x1f32c", - "0x1f300", - "0x1f308", - "0x1f302", - "0x2602", - "0x2614", - "0x26f1", - "0x26a1", - "0x2744", - "0x2603", - "0x26c4", - "0x2604", - "0x1f525", - "0x1f4a7", - "0x1f30a" - ], - "activities": [ - "0x1f383", - "0x1f384", - "0x1f386", - "0x1f387", - "0x1f9e8", - "0x2728", - "0x1f388", - "0x1f389", - "0x1f38a", - "0x1f38b", - "0x1f38d", - "0x1f38e", - "0x1f38f", - "0x1f390", - "0x1f391", - "0x1f9e7", - "0x1f380", - "0x1f381", - "0x1f397", - "0x1f39f", - "0x1f3ab", - "0x1f396", - "0x1f3c6", - "0x1f3c5", - "0x1f947", - "0x1f948", - "0x1f949", - "0x26bd", - "0x26be", - "0x1f94e", - "0x1f3c0", - "0x1f3d0", - "0x1f3c8", - "0x1f3c9", - "0x1f3be", - "0x1f94f", - "0x1f3b3", - "0x1f3cf", - "0x1f3d1", - "0x1f3d2", - "0x1f94d", - "0x1f3d3", - "0x1f3f8", - "0x1f94a", - "0x1f94b", - "0x1f945", - "0x26f3", - "0x26f8", - "0x1f3a3", - "0x1f93f", - "0x1f3bd", - "0x1f3bf", - "0x1f6f7", - "0x1f94c", - "0x1f3af", - "0x1fa80", - "0x1fa81", - "0x1f52b", - "0x1f3b1", - "0x1f52e", - "0x1fa84", - "0x1f3ae", - "0x1f579", - "0x1f3b0", - "0x1f3b2", - "0x1f9e9", - "0x1f9f8", - "0x1fa85", - "0x1faa9", - "0x1fa86", - "0x2660", - "0x2665", - "0x2666", - "0x2663", - "0x265f", - "0x1f0cf", - "0x1f004", - "0x1f3b4", - "0x1f3ad", - "0x1f5bc", - "0x1f3a8", - "0x1f9f5", - "0x1faa1", - "0x1f9f6", - "0x1faa2" - ], - "objects": [ - "0x1f453", - "0x1f576", - "0x1f97d", - "0x1f97c", - "0x1f9ba", - "0x1f454", - "0x1f455", - "0x1f456", - "0x1f9e3", - "0x1f9e4", - "0x1f9e5", - "0x1f9e6", - "0x1f457", - "0x1f458", - "0x1f97b", - "0x1fa71", - "0x1fa72", - "0x1fa73", - "0x1f459", - "0x1f45a", - "0x1faad", - "0x1f45b", - "0x1f45c", - "0x1f45d", - "0x1f6cd", - "0x1f392", - "0x1fa74", - "0x1f45e", - "0x1f45f", - "0x1f97e", - "0x1f97f", - "0x1f460", - "0x1f461", - "0x1fa70", - "0x1f462", - "0x1faae", - "0x1f451", - "0x1f452", - "0x1f3a9", - "0x1f393", - "0x1f9e2", - "0x1fa96", - "0x26d1", - "0x1f4ff", - "0x1f484", - "0x1f48d", - "0x1f48e", - "0x1f507", - "0x1f508", - "0x1f509", - "0x1f50a", - "0x1f4e2", - "0x1f4e3", - "0x1f4ef", - "0x1f514", - "0x1f515", - "0x1f3bc", - "0x1f3b5", - "0x1f3b6", - "0x1f399", - "0x1f39a", - "0x1f39b", - "0x1f3a4", - "0x1f3a7", - "0x1f4fb", - "0x1f3b7", - "0x1fa97", - "0x1f3b8", - "0x1f3b9", - "0x1f3ba", - "0x1f3bb", - "0x1fa95", - "0x1f941", - "0x1fa98", - "0x1fa87", - "0x1fa88", - "0x1f4f1", - "0x1f4f2", - "0x260e", - "0x1f4de", - "0x1f4df", - "0x1f4e0", - "0x1f50b", - "0x1faab", - "0x1f50c", - "0x1f4bb", - "0x1f5a5", - "0x1f5a8", - "0x2328", - "0x1f5b1", - "0x1f5b2", - "0x1f4bd", - "0x1f4be", - "0x1f4bf", - "0x1f4c0", - "0x1f9ee", - "0x1f3a5", - "0x1f39e", - "0x1f4fd", - "0x1f3ac", - "0x1f4fa", - "0x1f4f7", - "0x1f4f8", - "0x1f4f9", - "0x1f4fc", - "0x1f50d", - "0x1f50e", - "0x1f56f", - "0x1f4a1", - "0x1f526", - "0x1f3ee", - "0x1fa94", - "0x1f4d4", - "0x1f4d5", - "0x1f4d6", - "0x1f4d7", - "0x1f4d8", - "0x1f4d9", - "0x1f4da", - "0x1f4d3", - "0x1f4d2", - "0x1f4c3", - "0x1f4dc", - "0x1f4c4", - "0x1f4f0", - "0x1f5de", - "0x1f4d1", - "0x1f516", - "0x1f3f7", - "0x1f4b0", - "0x1fa99", - "0x1f4b4", - "0x1f4b5", - "0x1f4b6", - "0x1f4b7", - "0x1f4b8", - "0x1f4b3", - "0x1f9fe", - "0x1f4b9", - "0x2709", - "0x1f4e7", - "0x1f4e8", - "0x1f4e9", - "0x1f4e4", - "0x1f4e5", - "0x1f4e6", - "0x1f4eb", - "0x1f4ea", - "0x1f4ec", - "0x1f4ed", - "0x1f4ee", - "0x1f5f3", - "0x270f", - "0x2712", - "0x1f58b", - "0x1f58a", - "0x1f58c", - "0x1f58d", - "0x1f4dd", - "0x1f4bc", - "0x1f4c1", - "0x1f4c2", - "0x1f5c2", - "0x1f4c5", - "0x1f4c6", - "0x1f5d2", - "0x1f5d3", - "0x1f4c7", - "0x1f4c8", - "0x1f4c9", - "0x1f4ca", - "0x1f4cb", - "0x1f4cc", - "0x1f4cd", - "0x1f4ce", - "0x1f587", - "0x1f4cf", - "0x1f4d0", - "0x2702", - "0x1f5c3", - "0x1f5c4", - "0x1f5d1", - "0x1f512", - "0x1f513", - "0x1f50f", - "0x1f510", - "0x1f511", - "0x1f5dd", - "0x1f528", - "0x1fa93", - "0x26cf", - "0x2692", - "0x1f6e0", - "0x1f5e1", - "0x2694", - "0x1f4a3", - "0x1fa83", - "0x1f3f9", - "0x1f6e1", - "0x1fa9a", - "0x1f527", - "0x1fa9b", - "0x1f529", - "0x2699", - "0x1f5dc", - "0x2696", - "0x1f9af", - "0x1f517", - "0x26d3", - "0xfe0f", - "0x200d", - "0x1f4a5", - "0x26d3", - "0x1fa9d", - "0x1f9f0", - "0x1f9f2", - "0x1fa9c", - "0x2697", - "0x1f9ea", - "0x1f9eb", - "0x1f9ec", - "0x1f52c", - "0x1f52d", - "0x1f4e1", - "0x1f489", - "0x1fa78", - "0x1f48a", - "0x1fa79", - "0x1fa7c", - "0x1fa7a", - "0x1fa7b", - "0x1f6aa", - "0x1f6d7", - "0x1fa9e", - "0x1fa9f", - "0x1f6cf", - "0x1f6cb", - "0x1fa91", - "0x1f6bd", - "0x1faa0", - "0x1f6bf", - "0x1f6c1", - "0x1faa4", - "0x1fa92", - "0x1f9f4", - "0x1f9f7", - "0x1f9f9", - "0x1f9fa", - "0x1f9fb", - "0x1faa3", - "0x1f9fc", - "0x1fae7", - "0x1faa5", - "0x1f9fd", - "0x1f9ef", - "0x1f6d2", - "0x1f6ac", - "0x26b0", - "0x1faa6", - "0x26b1", - "0x1f9ff", - "0x1faac", - "0x1f5ff", - "0x1faa7", - "0x1faaa" - ], - "symbols": [ - "0x1f3e7", - "0x1f6ae", - "0x1f6b0", - "0x267f", - "0x1f6b9", - "0x1f6ba", - "0x1f6bb", - "0x1f6bc", - "0x1f6be", - "0x1f6c2", - "0x1f6c3", - "0x1f6c4", - "0x1f6c5", - "0x26a0", - "0x1f6b8", - "0x26d4", - "0x1f6ab", - "0x1f6b3", - "0x1f6ad", - "0x1f6af", - "0x1f6b1", - "0x1f6b7", - "0x1f4f5", - "0x1f51e", - "0x2622", - "0x2623", - "0x2b06", - "0x2197", - "0x27a1", - "0x2198", - "0x2b07", - "0x2199", - "0x2b05", - "0x2196", - "0x2195", - "0x2194", - "0x21a9", - "0x21aa", - "0x2934", - "0x2935", - "0x1f503", - "0x1f504", - "0x1f519", - "0x1f51a", - "0x1f51b", - "0x1f51c", - "0x1f51d", - "0x1f6d0", - "0x269b", - "0x1f549", - "0x2721", - "0x2638", - "0x262f", - "0x271d", - "0x2626", - "0x262a", - "0x262e", - "0x1f54e", - "0x1f52f", - "0x1faaf", - "0x2648", - "0x2649", - "0x264a", - "0x264b", - "0x264c", - "0x264d", - "0x264e", - "0x264f", - "0x2650", - "0x2651", - "0x2652", - "0x2653", - "0x26ce", - "0x1f500", - "0x1f501", - "0x1f502", - "0x25b6", - "0x23e9", - "0x23ed", - "0x23ef", - "0x25c0", - "0x23ea", - "0x23ee", - "0x1f53c", - "0x23eb", - "0x1f53d", - "0x23ec", - "0x23f8", - "0x23f9", - "0x23fa", - "0x23cf", - "0x1f3a6", - "0x1f505", - "0x1f506", - "0x1f4f6", - "0x1f6dc", - "0x1f4f3", - "0x1f4f4", - "0x2640", - "0x2642", - "0x26a7", - "0x2716", - "0x2795", - "0x2796", - "0x2797", - "0x1f7f0", - "0x267e", - "0x203c", - "0x2049", - "0x2753", - "0x2754", - "0x2755", - "0x2757", - "0x3030", - "0x1f4b1", - "0x1f4b2", - "0x2695", - "0x267b", - "0x269c", - "0x1f531", - "0x1f4db", - "0x1f530", - "0x2b55", - "0x2705", - "0x2611", - "0x2714", - "0x274c", - "0x274e", - "0x27b0", - "0x27bf", - "0x303d", - "0x2733", - "0x2734", - "0x2747", - "0x00a9", - "0x00ae", - "0x2122", - "0x0023", - "0xfe0f", - "0x20e3", - "0x002a", - "0xfe0f", - "0x20e3", - "0x0030", - "0xfe0f", - "0x20e3", - "0x0031", - "0xfe0f", - "0x20e3", - "0x0032", - "0xfe0f", - "0x20e3", - "0x0033", - "0xfe0f", - "0x20e3", - "0x0034", - "0xfe0f", - "0x20e3", - "0x0035", - "0xfe0f", - "0x20e3", - "0x0036", - "0xfe0f", - "0x20e3", - "0x0037", - "0xfe0f", - "0x20e3", - "0x0038", - "0xfe0f", - "0x20e3", - "0x0039", - "0xfe0f", - "0x20e3", - "0x1f51f", - "0x1f520", - "0x1f521", - "0x1f522", - "0x1f523", - "0x1f524", - "0x1f170", - "0x1f18e", - "0x1f171", - "0x1f191", - "0x1f192", - "0x1f193", - "0x2139", - "0x1f194", - "0x24c2", - "0x1f195", - "0x1f196", - "0x1f17e", - "0x1f197", - "0x1f17f", - "0x1f198", - "0x1f199", - "0x1f19a", - "0x1f201", - "0x1f202", - "0x1f237", - "0x1f236", - "0x1f22f", - "0x1f250", - "0x1f239", - "0x1f21a", - "0x1f232", - "0x1f251", - "0x1f238", - "0x1f234", - "0x1f233", - "0x3297", - "0x3299", - "0x1f23a", - "0x1f235", - "0x1f534", - "0x1f7e0", - "0x1f7e1", - "0x1f7e2", - "0x1f535", - "0x1f7e3", - "0x1f7e4", - "0x26ab", - "0x26aa", - "0x1f7e5", - "0x1f7e7", - "0x1f7e8", - "0x1f7e9", - "0x1f7e6", - "0x1f7ea", - "0x1f7eb", - "0x2b1b", - "0x2b1c", - "0x25fc", - "0x25fb", - "0x25fe", - "0x25fd", - "0x25aa", - "0x25ab", - "0x1f536", - "0x1f537", - "0x1f538", - "0x1f539", - "0x1f53a", - "0x1f53b", - "0x1f4a0", - "0x1f518", - "0x1f533", - "0x1f532" - ], - "flags": [ - "0x1f3c1", - "0x1f6a9", - "0x1f38c", - "0x1f3f4", - "0x1f3f3", - "0x1f3f3", - "0xfe0f", - "0x200d", - "0x1f308", - "0x1f3f3", - "0xfe0f", - "0x200d", - "0x26a7", - "0xfe0f", - "0x1f3f4", - "0x200d", - "0x2620", - "0xfe0f", - "0x1f1e6", - "0x1f1e8", - "0x1f1e6", - "0x1f1e9", - "0x1f1e6", - "0x1f1ea", - "0x1f1e6", - "0x1f1eb", - "0x1f1e6", - "0x1f1ec", - "0x1f1e6", - "0x1f1ee", - "0x1f1e6", - "0x1f1f1", - "0x1f1e6", - "0x1f1f2", - "0x1f1e6", - "0x1f1f4", - "0x1f1e6", - "0x1f1f6", - "0x1f1e6", - "0x1f1f7", - "0x1f1e6", - "0x1f1f8", - "0x1f1e6", - "0x1f1f9", - "0x1f1e6", - "0x1f1fa", - "0x1f1e6", - "0x1f1fc", - "0x1f1e6", - "0x1f1fd", - "0x1f1e6", - "0x1f1ff", - "0x1f1e7", - "0x1f1e6", - "0x1f1e7", - "0x1f1e7", - "0x1f1e7", - "0x1f1e9", - "0x1f1e7", - "0x1f1ea", - "0x1f1e7", - "0x1f1eb", - "0x1f1e7", - "0x1f1ec", - "0x1f1e7", - "0x1f1ed", - "0x1f1e7", - "0x1f1ee", - "0x1f1e7", - "0x1f1ef", - "0x1f1e7", - "0x1f1f1", - "0x1f1e7", - "0x1f1f2", - "0x1f1e7", - "0x1f1f3", - "0x1f1e7", - "0x1f1f4", - "0x1f1e7", - "0x1f1f6", - "0x1f1e7", - "0x1f1f7", - "0x1f1e7", - "0x1f1f8", - "0x1f1e7", - "0x1f1f9", - "0x1f1e7", - "0x1f1fb", - "0x1f1e7", - "0x1f1fc", - "0x1f1e7", - "0x1f1fe", - "0x1f1e7", - "0x1f1ff", - "0x1f1e8", - "0x1f1e6", - "0x1f1e8", - "0x1f1e8", - "0x1f1e8", - "0x1f1e9", - "0x1f1e8", - "0x1f1eb", - "0x1f1e8", - "0x1f1ec", - "0x1f1e8", - "0x1f1ed", - "0x1f1e8", - "0x1f1ee", - "0x1f1e8", - "0x1f1f0", - "0x1f1e8", - "0x1f1f1", - "0x1f1e8", - "0x1f1f2", - "0x1f1e8", - "0x1f1f3", - "0x1f1e8", - "0x1f1f4", - "0x1f1e8", - "0x1f1f5", - "0x1f1e8", - "0x1f1f7", - "0x1f1e8", - "0x1f1fa", - "0x1f1e8", - "0x1f1fb", - "0x1f1e8", - "0x1f1fc", - "0x1f1e8", - "0x1f1fd", - "0x1f1e8", - "0x1f1fe", - "0x1f1e8", - "0x1f1ff", - "0x1f1e9", - "0x1f1ea", - "0x1f1e9", - "0x1f1ec", - "0x1f1e9", - "0x1f1ef", - "0x1f1e9", - "0x1f1f0", - "0x1f1e9", - "0x1f1f2", - "0x1f1e9", - "0x1f1f4", - "0x1f1e9", - "0x1f1ff", - "0x1f1ea", - "0x1f1e6", - "0x1f1ea", - "0x1f1e8", - "0x1f1ea", - "0x1f1ea", - "0x1f1ea", - "0x1f1ec", - "0x1f1ea", - "0x1f1ed", - "0x1f1ea", - "0x1f1f7", - "0x1f1ea", - "0x1f1f8", - "0x1f1ea", - "0x1f1f9", - "0x1f1ea", - "0x1f1fa", - "0x1f1eb", - "0x1f1ee", - "0x1f1eb", - "0x1f1ef", - "0x1f1eb", - "0x1f1f0", - "0x1f1eb", - "0x1f1f2", - "0x1f1eb", - "0x1f1f4", - "0x1f1eb", - "0x1f1f7", - "0x1f1ec", - "0x1f1e6", - "0x1f1ec", - "0x1f1e7", - "0x1f1ec", - "0x1f1e9", - "0x1f1ec", - "0x1f1ea", - "0x1f1ec", - "0x1f1eb", - "0x1f1ec", - "0x1f1ec", - "0x1f1ec", - "0x1f1ed", - "0x1f1ec", - "0x1f1ee", - "0x1f1ec", - "0x1f1f1", - "0x1f1ec", - "0x1f1f2", - "0x1f1ec", - "0x1f1f3", - "0x1f1ec", - "0x1f1f5", - "0x1f1ec", - "0x1f1f6", - "0x1f1ec", - "0x1f1f7", - "0x1f1ec", - "0x1f1f8", - "0x1f1ec", - "0x1f1f9", - "0x1f1ec", - "0x1f1fa", - "0x1f1ec", - "0x1f1fc", - "0x1f1ec", - "0x1f1fe", - "0x1f1ed", - "0x1f1f0", - "0x1f1ed", - "0x1f1f2", - "0x1f1ed", - "0x1f1f3", - "0x1f1ed", - "0x1f1f7", - "0x1f1ed", - "0x1f1f9", - "0x1f1ed", - "0x1f1fa", - "0x1f1ee", - "0x1f1e8", - "0x1f1ee", - "0x1f1e9", - "0x1f1ee", - "0x1f1ea", - "0x1f1ee", - "0x1f1f1", - "0x1f1ee", - "0x1f1f2", - "0x1f1ee", - "0x1f1f3", - "0x1f1ee", - "0x1f1f4", - "0x1f1ee", - "0x1f1f6", - "0x1f1ee", - "0x1f1f7", - "0x1f1ee", - "0x1f1f8", - "0x1f1ee", - "0x1f1f9", - "0x1f1ef", - "0x1f1ea", - "0x1f1ef", - "0x1f1f2", - "0x1f1ef", - "0x1f1f4", - "0x1f1ef", - "0x1f1f5", - "0x1f1f0", - "0x1f1ea", - "0x1f1f0", - "0x1f1ec", - "0x1f1f0", - "0x1f1ed", - "0x1f1f0", - "0x1f1ee", - "0x1f1f0", - "0x1f1f2", - "0x1f1f0", - "0x1f1f3", - "0x1f1f0", - "0x1f1f5", - "0x1f1f0", - "0x1f1f7", - "0x1f1f0", - "0x1f1fc", - "0x1f1f0", - "0x1f1fe", - "0x1f1f0", - "0x1f1ff", - "0x1f1f1", - "0x1f1e6", - "0x1f1f1", - "0x1f1e7", - "0x1f1f1", - "0x1f1e8", - "0x1f1f1", - "0x1f1ee", - "0x1f1f1", - "0x1f1f0", - "0x1f1f1", - "0x1f1f7", - "0x1f1f1", - "0x1f1f8", - "0x1f1f1", - "0x1f1f9", - "0x1f1f1", - "0x1f1fa", - "0x1f1f1", - "0x1f1fb", - "0x1f1f1", - "0x1f1fe", - "0x1f1f2", - "0x1f1e6", - "0x1f1f2", - "0x1f1e8", - "0x1f1f2", - "0x1f1e9", - "0x1f1f2", - "0x1f1ea", - "0x1f1f2", - "0x1f1eb", - "0x1f1f2", - "0x1f1ec", - "0x1f1f2", - "0x1f1ed", - "0x1f1f2", - "0x1f1f0", - "0x1f1f2", - "0x1f1f1", - "0x1f1f2", - "0x1f1f2", - "0x1f1f2", - "0x1f1f3", - "0x1f1f2", - "0x1f1f4", - "0x1f1f2", - "0x1f1f5", - "0x1f1f2", - "0x1f1f6", - "0x1f1f2", - "0x1f1f7", - "0x1f1f2", - "0x1f1f8", - "0x1f1f2", - "0x1f1f9", - "0x1f1f2", - "0x1f1fa", - "0x1f1f2", - "0x1f1fb", - "0x1f1f2", - "0x1f1fc", - "0x1f1f2", - "0x1f1fd", - "0x1f1f2", - "0x1f1fe", - "0x1f1f2", - "0x1f1ff", - "0x1f1f3", - "0x1f1e6", - "0x1f1f3", - "0x1f1e8", - "0x1f1f3", - "0x1f1ea", - "0x1f1f3", - "0x1f1eb", - "0x1f1f3", - "0x1f1ec", - "0x1f1f3", - "0x1f1ee", - "0x1f1f3", - "0x1f1f1", - "0x1f1f3", - "0x1f1f4", - "0x1f1f3", - "0x1f1f5", - "0x1f1f3", - "0x1f1f7", - "0x1f1f3", - "0x1f1fa", - "0x1f1f3", - "0x1f1ff", - "0x1f1f4", - "0x1f1f2", - "0x1f1f5", - "0x1f1e6", - "0x1f1f5", - "0x1f1ea", - "0x1f1f5", - "0x1f1eb", - "0x1f1f5", - "0x1f1ec", - "0x1f1f5", - "0x1f1ed", - "0x1f1f5", - "0x1f1f0", - "0x1f1f5", - "0x1f1f1", - "0x1f1f5", - "0x1f1f2", - "0x1f1f5", - "0x1f1f3", - "0x1f1f5", - "0x1f1f7", - "0x1f1f5", - "0x1f1f8", - "0x1f1f5", - "0x1f1f9", - "0x1f1f5", - "0x1f1fc", - "0x1f1f5", - "0x1f1fe", - "0x1f1f6", - "0x1f1e6", - "0x1f1f7", - "0x1f1ea", - "0x1f1f7", - "0x1f1f4", - "0x1f1f7", - "0x1f1f8", - "0x1f1f7", - "0x1f1fa", - "0x1f1f7", - "0x1f1fc", - "0x1f1f8", - "0x1f1e6", - "0x1f1f8", - "0x1f1e7", - "0x1f1f8", - "0x1f1e8", - "0x1f1f8", - "0x1f1e9", - "0x1f1f8", - "0x1f1ea", - "0x1f1f8", - "0x1f1ec", - "0x1f1f8", - "0x1f1ed", - "0x1f1f8", - "0x1f1ee", - "0x1f1f8", - "0x1f1ef", - "0x1f1f8", - "0x1f1f0", - "0x1f1f8", - "0x1f1f1", - "0x1f1f8", - "0x1f1f2", - "0x1f1f8", - "0x1f1f3", - "0x1f1f8", - "0x1f1f4", - "0x1f1f8", - "0x1f1f7", - "0x1f1f8", - "0x1f1f8", - "0x1f1f8", - "0x1f1f9", - "0x1f1f8", - "0x1f1fb", - "0x1f1f8", - "0x1f1fd", - "0x1f1f8", - "0x1f1fe", - "0x1f1f8", - "0x1f1ff", - "0x1f1f9", - "0x1f1e6", - "0x1f1f9", - "0x1f1e8", - "0x1f1f9", - "0x1f1e9", - "0x1f1f9", - "0x1f1eb", - "0x1f1f9", - "0x1f1ec", - "0x1f1f9", - "0x1f1ed", - "0x1f1f9", - "0x1f1ef", - "0x1f1f9", - "0x1f1f0", - "0x1f1f9", - "0x1f1f1", - "0x1f1f9", - "0x1f1f2", - "0x1f1f9", - "0x1f1f3", - "0x1f1f9", - "0x1f1f4", - "0x1f1f9", - "0x1f1f7", - "0x1f1f9", - "0x1f1f9", - "0x1f1f9", - "0x1f1fb", - "0x1f1f9", - "0x1f1fc", - "0x1f1f9", - "0x1f1ff", - "0x1f1fa", - "0x1f1e6", - "0x1f1fa", - "0x1f1ec", - "0x1f1fa", - "0x1f1f2", - "0x1f1fa", - "0x1f1f3", - "0x1f1fa", - "0x1f1f8", - "0x1f1fa", - "0x1f1fe", - "0x1f1fa", - "0x1f1ff", - "0x1f1fb", - "0x1f1e6", - "0x1f1fb", - "0x1f1e8", - "0x1f1fb", - "0x1f1ea", - "0x1f1fb", - "0x1f1ec", - "0x1f1fb", - "0x1f1ee", - "0x1f1fb", - "0x1f1f3", - "0x1f1fb", - "0x1f1fa", - "0x1f1fc", - "0x1f1eb", - "0x1f1fc", - "0x1f1f8", - "0x1f1fd", - "0x1f1f0", - "0x1f1fe", - "0x1f1ea", - "0x1f1fe", - "0x1f1f9", - "0x1f1ff", - "0x1f1e6", - "0x1f1ff", - "0x1f1f2", - "0x1f1ff", - "0x1f1fc", - "0x1f3f4", - "0xe0067", - "0xe0062", - "0xe0065", - "0xe006e", - "0xe0067", - "0xe007f", - "0x1f3f4", - "0xe0067", - "0xe0062", - "0xe0073", - "0xe0063", - "0xe0074", - "0xe007f", - "0x1f3f4", - "0xe0067", - "0xe0062", - "0xe0077", - "0xe006c", - "0xe0073", - "0xe007f" - ] - } - }; - - var o_hasOwnProperty = Object.prototype.hasOwnProperty; - var o_keys = (Object.keys || function(obj) { - var result = []; - for (var key in obj) { - if (o_hasOwnProperty.call(obj, key)) { - result.push(key); - } - } - - return result; - }); - - - function _copyObject(source, target) { - var keys = o_keys(source); - var key; - - for (var i = 0, l = keys.length; i < l; i++) { - key = keys[i]; - target[key] = source[key] || target[key]; - } - } - - function _copyArray(source, target) { - for (var i = 0, l = source.length; i < l; i++) { - target[i] = source[i]; - } - } - - function copyObject(source, _target) { - var isArray = Array.isArray(source); - var target = _target || (isArray ? new Array(source.length) : {}); - - if (isArray) { - _copyArray(source, target); - } else { - _copyObject(source, target); - } - - return target; - } - - /** Get the data based on key**/ - Chance.prototype.get = function (name) { - return copyObject(data[name]); - }; - - // Mac Address - Chance.prototype.mac_address = function(options){ - // typically mac addresses are separated by ":" - // however they can also be separated by "-" - // the network variant uses a dot every fourth byte - - options = initOptions(options); - if(!options.separator) { - options.separator = options.networkVersion ? "." : ":"; - } - - var mac_pool="ABCDEF1234567890", - mac = ""; - if(!options.networkVersion) { - mac = this.n(this.string, 6, { pool: mac_pool, length:2 }).join(options.separator); - } else { - mac = this.n(this.string, 3, { pool: mac_pool, length:4 }).join(options.separator); - } - - return mac; - }; - - Chance.prototype.normal = function (options) { - options = initOptions(options, {mean : 0, dev : 1, pool : []}); - - testRange( - options.pool.constructor !== Array, - "Chance: The pool option must be a valid array." - ); - testRange( - typeof options.mean !== 'number', - "Chance: Mean (mean) must be a number" - ); - testRange( - typeof options.dev !== 'number', - "Chance: Standard deviation (dev) must be a number" - ); - - // If a pool has been passed, then we are returning an item from that pool, - // using the normal distribution settings that were passed in - if (options.pool.length > 0) { - return this.normal_pool(options); - } - - // The Marsaglia Polar method - var s, u, v, norm, - mean = options.mean, - dev = options.dev; - - do { - // U and V are from the uniform distribution on (-1, 1) - u = this.random() * 2 - 1; - v = this.random() * 2 - 1; - - s = u * u + v * v; - } while (s >= 1); - - // Compute the standard normal variate - norm = u * Math.sqrt(-2 * Math.log(s) / s); - - // Shape and scale - return dev * norm + mean; - }; - - Chance.prototype.normal_pool = function(options) { - var performanceCounter = 0; - do { - var idx = Math.round(this.normal({ mean: options.mean, dev: options.dev })); - if (idx < options.pool.length && idx >= 0) { - return options.pool[idx]; - } else { - performanceCounter++; - } - } while(performanceCounter < 100); - - throw new RangeError("Chance: Your pool is too small for the given mean and standard deviation. Please adjust."); - }; - - Chance.prototype.radio = function (options) { - // Initial Letter (Typically Designated by Side of Mississippi River) - options = initOptions(options, {side : "?"}); - var fl = ""; - switch (options.side.toLowerCase()) { - case "east": - case "e": - fl = "W"; - break; - case "west": - case "w": - fl = "K"; - break; - default: - fl = this.character({pool: "KW"}); - break; - } - - return fl + this.character({alpha: true, casing: "upper"}) + - this.character({alpha: true, casing: "upper"}) + - this.character({alpha: true, casing: "upper"}); - }; - - // Set the data as key and data or the data map - Chance.prototype.set = function (name, values) { - if (typeof name === "string") { - data[name] = values; - } else { - data = copyObject(name, data); - } - }; - - Chance.prototype.tv = function (options) { - return this.radio(options); - }; - - // ID number for Brazil companies - Chance.prototype.cnpj = function () { - var n = this.n(this.natural, 8, { max: 9 }); - var d1 = 2+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; - d1 = 11 - (d1 % 11); - if (d1>=10){ - d1 = 0; - } - var d2 = d1*2+3+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; - d2 = 11 - (d2 % 11); - if (d2>=10){ - d2 = 0; - } - return ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/0001-'+d1+d2; - }; - - Chance.prototype.emotion = function () { - return this.pick(this.get("emotions")); - }; - - // -- End Miscellaneous -- - - Chance.prototype.mersenne_twister = function (seed) { - return new MersenneTwister(seed); - }; - - Chance.prototype.blueimp_md5 = function () { - return new BlueImpMD5(); - }; - - // Mersenne Twister from https://gist.github.com/banksean/300494 - /* - A C-program for MT19937, with initialization improved 2002/1/26. - Coded by Takuji Nishimura and Makoto Matsumoto. - - Before using, initialize the state by using init_genrand(seed) - or init_by_array(init_key, key_length). - - Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, - 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. The names of its contributors may not 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. - - - Any feedback is very welcome. - http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html - email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) - */ - var MersenneTwister = function (seed) { - if (seed === undefined) { - // kept random number same size as time used previously to ensure no unexpected results downstream - seed = Math.floor(Math.random()*Math.pow(10,13)); - } - /* Period parameters */ - this.N = 624; - this.M = 397; - this.MATRIX_A = 0x9908b0df; /* constant vector a */ - this.UPPER_MASK = 0x80000000; /* most significant w-r bits */ - this.LOWER_MASK = 0x7fffffff; /* least significant r bits */ - - this.mt = new Array(this.N); /* the array for the state vector */ - this.mti = this.N + 1; /* mti==N + 1 means mt[N] is not initialized */ - - this.init_genrand(seed); - }; - - /* initializes mt[N] with a seed */ - MersenneTwister.prototype.init_genrand = function (s) { - this.mt[0] = s >>> 0; - for (this.mti = 1; this.mti < this.N; this.mti++) { - s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30); - this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti; - /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ - /* In the previous versions, MSBs of the seed affect */ - /* only MSBs of the array mt[]. */ - /* 2002/01/09 modified by Makoto Matsumoto */ - this.mt[this.mti] >>>= 0; - /* for >32 bit machines */ - } - }; - - /* initialize by an array with array-length */ - /* init_key is the array for initializing keys */ - /* key_length is its length */ - /* slight change for C++, 2004/2/26 */ - MersenneTwister.prototype.init_by_array = function (init_key, key_length) { - var i = 1, j = 0, k, s; - this.init_genrand(19650218); - k = (this.N > key_length ? this.N : key_length); - for (; k; k--) { - s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); - this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525))) + init_key[j] + j; /* non linear */ - this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ - i++; - j++; - if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } - if (j >= key_length) { j = 0; } - } - for (k = this.N - 1; k; k--) { - s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); - this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i; /* non linear */ - this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ - i++; - if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } - } - - this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ - }; - - /* generates a random number on [0,0xffffffff]-interval */ - MersenneTwister.prototype.genrand_int32 = function () { - var y; - var mag01 = new Array(0x0, this.MATRIX_A); - /* mag01[x] = x * MATRIX_A for x=0,1 */ - - if (this.mti >= this.N) { /* generate N words at one time */ - var kk; - - if (this.mti === this.N + 1) { /* if init_genrand() has not been called, */ - this.init_genrand(5489); /* a default initial seed is used */ - } - for (kk = 0; kk < this.N - this.M; kk++) { - y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); - this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 0x1]; - } - for (;kk < this.N - 1; kk++) { - y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); - this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 0x1]; - } - y = (this.mt[this.N - 1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK); - this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; - - this.mti = 0; - } - - y = this.mt[this.mti++]; - - /* Tempering */ - y ^= (y >>> 11); - y ^= (y << 7) & 0x9d2c5680; - y ^= (y << 15) & 0xefc60000; - y ^= (y >>> 18); - - return y >>> 0; - }; - - /* generates a random number on [0,0x7fffffff]-interval */ - MersenneTwister.prototype.genrand_int31 = function () { - return (this.genrand_int32() >>> 1); - }; - - /* generates a random number on [0,1]-real-interval */ - MersenneTwister.prototype.genrand_real1 = function () { - return this.genrand_int32() * (1.0 / 4294967295.0); - /* divided by 2^32-1 */ - }; - - /* generates a random number on [0,1)-real-interval */ - MersenneTwister.prototype.random = function () { - return this.genrand_int32() * (1.0 / 4294967296.0); - /* divided by 2^32 */ - }; - - /* generates a random number on (0,1)-real-interval */ - MersenneTwister.prototype.genrand_real3 = function () { - return (this.genrand_int32() + 0.5) * (1.0 / 4294967296.0); - /* divided by 2^32 */ - }; - - /* generates a random number on [0,1) with 53-bit resolution*/ - MersenneTwister.prototype.genrand_res53 = function () { - var a = this.genrand_int32()>>>5, b = this.genrand_int32()>>>6; - return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); - }; - - // BlueImp MD5 hashing algorithm from https://github.com/blueimp/JavaScript-MD5 - var BlueImpMD5 = function () {}; - - BlueImpMD5.prototype.VERSION = '1.0.1'; - - /* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ - BlueImpMD5.prototype.safe_add = function safe_add(x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF), - msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); - }; - - /* - * Bitwise rotate a 32-bit number to the left. - */ - BlueImpMD5.prototype.bit_roll = function (num, cnt) { - return (num << cnt) | (num >>> (32 - cnt)); - }; - - /* - * These functions implement the five basic operations the algorithm uses. - */ - BlueImpMD5.prototype.md5_cmn = function (q, a, b, x, s, t) { - return this.safe_add(this.bit_roll(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s), b); - }; - BlueImpMD5.prototype.md5_ff = function (a, b, c, d, x, s, t) { - return this.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); - }; - BlueImpMD5.prototype.md5_gg = function (a, b, c, d, x, s, t) { - return this.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); - }; - BlueImpMD5.prototype.md5_hh = function (a, b, c, d, x, s, t) { - return this.md5_cmn(b ^ c ^ d, a, b, x, s, t); - }; - BlueImpMD5.prototype.md5_ii = function (a, b, c, d, x, s, t) { - return this.md5_cmn(c ^ (b | (~d)), a, b, x, s, t); - }; - - /* - * Calculate the MD5 of an array of little-endian words, and a bit length. - */ - BlueImpMD5.prototype.binl_md5 = function (x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << (len % 32); - x[(((len + 64) >>> 9) << 4) + 14] = len; - - var i, olda, oldb, oldc, oldd, - a = 1732584193, - b = -271733879, - c = -1732584194, - d = 271733878; - - for (i = 0; i < x.length; i += 16) { - olda = a; - oldb = b; - oldc = c; - oldd = d; - - a = this.md5_ff(a, b, c, d, x[i], 7, -680876936); - d = this.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); - c = this.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); - b = this.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = this.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); - d = this.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = this.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = this.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); - a = this.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = this.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = this.md5_ff(c, d, a, b, x[i + 10], 17, -42063); - b = this.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = this.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = this.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); - c = this.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = this.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); - - a = this.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); - d = this.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = this.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); - b = this.md5_gg(b, c, d, a, x[i], 20, -373897302); - a = this.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); - d = this.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); - c = this.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); - b = this.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); - a = this.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); - d = this.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = this.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); - b = this.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = this.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = this.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); - c = this.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = this.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); - - a = this.md5_hh(a, b, c, d, x[i + 5], 4, -378558); - d = this.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = this.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = this.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); - a = this.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = this.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = this.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); - b = this.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = this.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); - d = this.md5_hh(d, a, b, c, x[i], 11, -358537222); - c = this.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); - b = this.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); - a = this.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); - d = this.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); - c = this.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); - b = this.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); - - a = this.md5_ii(a, b, c, d, x[i], 6, -198630844); - d = this.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = this.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = this.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); - a = this.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = this.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = this.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); - b = this.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = this.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = this.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); - c = this.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = this.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = this.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); - d = this.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = this.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); - b = this.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); - - a = this.safe_add(a, olda); - b = this.safe_add(b, oldb); - c = this.safe_add(c, oldc); - d = this.safe_add(d, oldd); - } - return [a, b, c, d]; - }; - - /* - * Convert an array of little-endian words to a string - */ - BlueImpMD5.prototype.binl2rstr = function (input) { - var i, - output = ''; - for (i = 0; i < input.length * 32; i += 8) { - output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); - } - return output; - }; - - /* - * Convert a raw string to an array of little-endian words - * Characters >255 have their high-byte silently ignored. - */ - BlueImpMD5.prototype.rstr2binl = function (input) { - var i, - output = []; - output[(input.length >> 2) - 1] = undefined; - for (i = 0; i < output.length; i += 1) { - output[i] = 0; - } - for (i = 0; i < input.length * 8; i += 8) { - output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); - } - return output; - }; - - /* - * Calculate the MD5 of a raw string - */ - BlueImpMD5.prototype.rstr_md5 = function (s) { - return this.binl2rstr(this.binl_md5(this.rstr2binl(s), s.length * 8)); - }; - - /* - * Calculate the HMAC-MD5, of a key and some data (raw strings) - */ - BlueImpMD5.prototype.rstr_hmac_md5 = function (key, data) { - var i, - bkey = this.rstr2binl(key), - ipad = [], - opad = [], - hash; - ipad[15] = opad[15] = undefined; - if (bkey.length > 16) { - bkey = this.binl_md5(bkey, key.length * 8); - } - for (i = 0; i < 16; i += 1) { - ipad[i] = bkey[i] ^ 0x36363636; - opad[i] = bkey[i] ^ 0x5C5C5C5C; - } - hash = this.binl_md5(ipad.concat(this.rstr2binl(data)), 512 + data.length * 8); - return this.binl2rstr(this.binl_md5(opad.concat(hash), 512 + 128)); - }; - - /* - * Convert a raw string to a hex string - */ - BlueImpMD5.prototype.rstr2hex = function (input) { - var hex_tab = '0123456789abcdef', - output = '', - x, - i; - for (i = 0; i < input.length; i += 1) { - x = input.charCodeAt(i); - output += hex_tab.charAt((x >>> 4) & 0x0F) + - hex_tab.charAt(x & 0x0F); - } - return output; - }; - - /* - * Encode a string as utf-8 - */ - BlueImpMD5.prototype.str2rstr_utf8 = function (input) { - return unescape(encodeURIComponent(input)); - }; - - /* - * Take string arguments and return either raw or hex encoded strings - */ - BlueImpMD5.prototype.raw_md5 = function (s) { - return this.rstr_md5(this.str2rstr_utf8(s)); - }; - BlueImpMD5.prototype.hex_md5 = function (s) { - return this.rstr2hex(this.raw_md5(s)); - }; - BlueImpMD5.prototype.raw_hmac_md5 = function (k, d) { - return this.rstr_hmac_md5(this.str2rstr_utf8(k), this.str2rstr_utf8(d)); - }; - BlueImpMD5.prototype.hex_hmac_md5 = function (k, d) { - return this.rstr2hex(this.raw_hmac_md5(k, d)); - }; - - BlueImpMD5.prototype.md5 = function (string, key, raw) { - if (!key) { - if (!raw) { - return this.hex_md5(string); - } - - return this.raw_md5(string); - } - - if (!raw) { - return this.hex_hmac_md5(key, string); - } - - return this.raw_hmac_md5(key, string); - }; - - // CommonJS module - if (true) { - if ( true && module.exports) { - exports = module.exports = Chance; - } - exports.Chance = Chance; - } - - // Register as an anonymous AMD module - if (typeof define === 'function' && define.amd) { - define([], function () { - return Chance; - }); - } - - // if there is a importsScrips object define chance for worker - // allows worker to use full Chance functionality with seed - if (typeof importScripts !== 'undefined') { - chance = new Chance(); - self.Chance = Chance; - } - - // If there is a window object, that at least has a document property, - // instantiate and define chance on the window - if (typeof window === "object" && typeof window.document === "object") { - window.Chance = Chance; - window.chance = new Chance(); - } -})(); - - -/***/ }), - -/***/ 59051: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"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 - - -/***/ }), - -/***/ 83733: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const cliBoxes = __nccwpck_require__(70094); - -module.exports = cliBoxes; -// TODO: Remove this for the next major release -module.exports["default"] = cliBoxes; - - -/***/ }), - -/***/ 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); -}; - - -/***/ }), - -/***/ 24137: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const binding = __nccwpck_require__(24240); - -module.exports = binding.getCPUInfo; - - -/***/ }), - -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { - -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - let m; - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - // eslint-disable-next-line no-return-assign - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; - - -/***/ }), - -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(80900); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - const split = (typeof namespaces === 'string' ? namespaces : '') - .trim() - .replace(/\s+/g, ',') - .split(',') - .filter(Boolean); - - for (const ns of split) { - if (ns[0] === '-') { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } - - /** - * Checks if the given string matches a namespace template, honoring - * asterisks as wildcards. - * - * @param {String} search - * @param {String} template - * @return {Boolean} - */ - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { - // Match character or proceed with wildcard - if (template[templateIndex] === '*') { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; // Skip the '*' - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition - // Backtrack to the last '*' and try to match more characters - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; // No match - } - } - - // Handle trailing '*' in template - while (templateIndex < template.length && template[templateIndex] === '*') { - templateIndex++; - } - - return templateIndex === template.length; - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - - return false; - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; - - -/***/ }), - -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); -} - - -/***/ }), - -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * Module dependencies. - */ - -const tty = __nccwpck_require__(76224); -const util = __nccwpck_require__(73837); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(30132); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = __nccwpck_require__(46243)(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - - -/***/ }), - -/***/ 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; - - -/***/ }), - -/***/ 84305: -/***/ ((module, exports, __nccwpck_require__) => { - -//Based on follow-redirects v0.0.x - -var nativeHttps = __nccwpck_require__(95687), - nativeHttp = __nccwpck_require__(13685), - url = __nccwpck_require__(57310), - utils = __nccwpck_require__(74967); - -var maxRedirects = module.exports.maxRedirects = 5; - -var protocols = { - https: nativeHttps, - http: nativeHttp -}; - -for (var protocol in protocols) { - var h = function() {}; - h.prototype = protocols[protocol]; - h = new h(); - - h.request = function(h) { - return function(options, callback, redirectOptions) { - - redirectOptions = redirectOptions || {}; - - var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects; - - var redirect = utils.extend({ - count: 0, - max: max, - clientRequest: null, - userCallback: callback - }, redirectOptions); - - if (redirect.count > redirect.max) { - var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.'); - redirect.clientRequest.emit('error', err); - return redirect.clientRequest; - } - - redirect.count++; - - var reqUrl; - if (typeof options === 'string') { - reqUrl = options; - } else { - reqUrl = url.format(utils.extend({ - protocol: protocol - }, options)); - } - - var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect)); - - if (!redirect.clientRequest) redirect.clientRequest = clientRequest; - - function redirectCallback(reqUrl, redirect) { - return function(res) { - if (res.statusCode < 300 || res.statusCode > 399) { - return redirect.userCallback(res); - } - - if (!('location' in res.headers)) { - return redirect.userCallback(res); - } - - var redirectUrl = url.resolve(reqUrl, res.headers.location); - - var proto = url.parse(redirectUrl).protocol; - proto = proto.substr(0, proto.length - 1); - return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect); - }; - } - - return clientRequest; - }; - }(h); - - // see https://github.com/joyent/node/blob/master/lib/http.js#L1623 - h.get = function(h) { - return function(options, cb, redirectOptions) { - var req = h.request(options, cb, redirectOptions); - req.end(); - return req; - }; - }(h); - - module.exports[protocol] = h; -} - - -/***/ }), - -/***/ 13855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = HttpDuplex; - -var util = __nccwpck_require__(73837), - stream = __nccwpck_require__(51642); - -util.inherits(HttpDuplex, stream.Duplex); - -function HttpDuplex(req, res, options) { - var self = this; - - if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options); - - stream.Duplex.call(self, options); - self._output = null; - - self.connect(req, res); -} - -HttpDuplex.prototype.connect = function(req, res) { - var self = this; - self.req = req; - self._output = res; - self.emit('response', res); - - res.on('data', function(c) { - if (!self.push(c)) self._output.pause(); - }); - res.on('end', function() { - self.push(null); - }); -}; - -HttpDuplex.prototype._read = function(n) { - if (this._output) this._output.resume(); -}; - -HttpDuplex.prototype._write = function(chunk, encoding, cb) { - this.req.write(chunk, encoding); - cb(); -}; - -HttpDuplex.prototype.end = function(chunk, encoding, cb) { - this._output.socket.destroySoon(); - return this.req.end(chunk, encoding, cb); -}; - -HttpDuplex.prototype.destroy = function() { - this.req.destroy(); - this._output.socket.destroy(); -}; - -HttpDuplex.prototype.destroySoon = function() { - this.req.destroy(); - this._output.socket.destroy(); -}; - - -/***/ }), - -/***/ 26042: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var querystring = __nccwpck_require__(63477), - http = __nccwpck_require__(84305), - fs = __nccwpck_require__(57147), - path = __nccwpck_require__(71017), - url = __nccwpck_require__(57310), - ssh = __nccwpck_require__(7964), - HttpDuplex = __nccwpck_require__(13855), - debug = __nccwpck_require__(38237)('modem'), - utils = __nccwpck_require__(74967), - util = __nccwpck_require__(73837), - splitca = __nccwpck_require__(39798), - os = __nccwpck_require__(22037), - isWin = os.type() === 'Windows_NT', - stream = __nccwpck_require__(12781); - -var defaultOpts = function () { - var host; - var opts = {}; - - if (!process.env.DOCKER_HOST) { - // Windows socket path: //./pipe/docker_engine ( Windows 10 ) - // Linux & Darwin socket path is /var/run/docker.sock when running system-wide, - // or $HOME/.docker/run/docker.sock in new Docker Desktop installs. - opts.socketPath = isWin ? '//./pipe/docker_engine' : findDefaultUnixSocket; - } else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) { - // Strip off unix://, fall back to default if unix:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket; - } else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) { - // Strip off npipe://, fall back to default of //./pipe/docker_engine if - // npipe:// was passed without a path - opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine'; - } else { - var hostStr = process.env.DOCKER_HOST; - if (hostStr.indexOf('\/\/') < 0) { - hostStr = 'tcp://' + hostStr; - } - try { - host = new url.URL(hostStr); - } catch (err) { - throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234'); - } - - opts.port = host.port; - - if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') { - opts.protocol = 'https'; - } else if (host.protocol === 'ssh:') { - opts.protocol = 'ssh'; - opts.username = host.username; - opts.sshOptions = { - agent: process.env.SSH_AUTH_SOCK, - } - } else { - opts.protocol = 'http'; - } - - if (process.env.DOCKER_PATH_PREFIX) { - opts.pathPrefix = process.env.DOCKER_PATH_PREFIX; - } - else { - opts.pathPrefix = '/'; - } - - opts.host = host.hostname; - - if (process.env.DOCKER_CERT_PATH) { - opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem')); - opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem')); - opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem')); - } - - if (process.env.DOCKER_CLIENT_TIMEOUT) { - opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10); - } - } - - return opts; -}; - -var findDefaultUnixSocket = function () { - return new Promise(function (resolve) { - var userDockerSocket = path.join(os.homedir(), '.docker', 'run', 'docker.sock'); - fs.access(userDockerSocket, function (err) { - if (err) resolve('/var/run/docker.sock'); - else resolve(userDockerSocket); - }) - }); -} - - -var Modem = function (options) { - var optDefaults = defaultOpts(); - var opts = Object.assign({}, optDefaults, options); - - this.host = opts.host; - - if (!this.host) { - this.socketPath = opts.socketPath; - } - - this.port = opts.port; - this.pathPrefix = opts.pathPrefix; - this.username = opts.username; - this.password = opts.password; - this.version = opts.version; - this.key = opts.key; - this.cert = opts.cert; - this.ca = opts.ca; - this.timeout = opts.timeout; - this.connectionTimeout = opts.connectionTimeout; - this.checkServerIdentity = opts.checkServerIdentity; - this.agent = opts.agent; - this.headers = opts.headers || {}; - this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions); - //retrocompabitlity - if (this.sshOptions.agentForward === undefined) { - this.sshOptions.agentForward = opts.agentForward; - } - - if (this.key && this.cert && this.ca) { - this.protocol = 'https'; - } - this.protocol = opts.protocol || this.protocol || 'http'; -}; - -Modem.prototype.dial = function (options, callback) { - var opts, address, data; - - if (options.options) { - opts = options.options; - } - - // Prevent credentials from showing up in URL - if (opts && opts.authconfig) { - delete opts.authconfig; - } - - // Prevent abortsignal from showing up in the URL - if (opts && opts.abortSignal) { - delete opts.abortSignal; - } - - if (this.version) { - options.path = '/' + this.version + options.path; - } - - if (this.host) { - var parsed = url.parse(this.host); - address = url.format({ - protocol: parsed.protocol || this.protocol, - hostname: parsed.hostname || this.host, - port: this.port, - pathname: parsed.pathname || this.pathPrefix, - }); - address = url.resolve(address, options.path); - } else { - address = options.path; - } - - if (options.path.indexOf('?') !== -1) { - if (opts && Object.keys(opts).length > 0) { - address += this.buildQuerystring(opts._query || opts); - } else { - address = address.substring(0, address.length - 1); - } - } - - var optionsf = { - path: address, - method: options.method, - headers: options.headers || Object.assign({}, this.headers), - key: this.key, - cert: this.cert, - ca: this.ca - }; - - - if (this.checkServerIdentity) { - optionsf.checkServerIdentity = this.checkServerIdentity; - } - - if (this.agent) { - optionsf.agent = this.agent; - } - - if (options.authconfig) { - optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 || - Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\+/g, "-").replace(/\//g, "_"); - } - - if (options.registryconfig) { - optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 || - Buffer.from(JSON.stringify(options.registryconfig)).toString('base64'); - } - - if (options.abortSignal) { - optionsf.signal = options.abortSignal; - } - - if (options.file) { - if (typeof options.file === 'string') { - data = fs.createReadStream(path.resolve(options.file)); - } else { - data = options.file; - } - optionsf.headers['Content-Type'] = 'application/tar'; - } else if (opts && options.method === 'POST') { - data = JSON.stringify(opts._body || opts); - if (options.allowEmpty) { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - if (data !== '{}' && data !== '""') { - optionsf.headers['Content-Type'] = 'application/json'; - } else { - data = undefined; - } - } - } - - if (typeof data === 'string') { - optionsf.headers['Content-Length'] = Buffer.byteLength(data); - } else if (Buffer.isBuffer(data) === true) { - optionsf.headers['Content-Length'] = data.length; - } else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) { - optionsf.headers['Transfer-Encoding'] = 'chunked'; - } - - if (options.hijack) { - optionsf.headers.Connection = 'Upgrade'; - optionsf.headers.Upgrade = optionsf.headers.Upgrade ?? 'tcp'; - } - - if (this.socketPath) { - // SocketPath may be a function that can return a promise: - this.getSocketPath().then((socketPath) => { - optionsf.socketPath = socketPath; - this.buildRequest(optionsf, options, data, callback); - }); - } else { - var urlp = url.parse(address); - optionsf.hostname = urlp.hostname; - optionsf.port = urlp.port; - optionsf.path = urlp.path; - - this.buildRequest(optionsf, options, data, callback); - } -}; - -Modem.prototype.getSocketPath = function () { - if (!this.socketPath) return; - if (this.socketPathCache) return Promise.resolve(this.socketPathCache); - - var socketPathValue = typeof this.socketPath === 'function' - ? this.socketPath() : this.socketPath; - - this.socketPathCache = socketPathValue; - - return Promise.resolve(socketPathValue); -} - -Modem.prototype.buildRequest = function (options, context, data, callback) { - var self = this; - var connectionTimeoutTimer; - var finished = false; - - var opts = self.protocol === 'ssh' ? Object.assign(options, { - agent: ssh(Object.assign({}, self.sshOptions, { - 'host': self.host, - 'port': self.port, - 'username': self.username, - 'password': self.password, - })), - protocol: 'http:', - }) : options; - - var req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { }); - - debug('Sending: %s', util.inspect(options, { - showHidden: true, - depth: null - })); - - if (self.connectionTimeout) { - connectionTimeoutTimer = setTimeout(function () { - debug('Connection Timeout of %s ms exceeded', self.connectionTimeout); - req.destroy(); - }, self.connectionTimeout); - } - - if (self.timeout) { - req.setTimeout(self.timeout); - req.on('timeout', function () { - debug('Timeout of %s ms exceeded', self.timeout); - req.destroy(); - }); - } - - if (context.hijack === true) { - clearTimeout(connectionTimeoutTimer); - req.on('upgrade', function (res, sock, head) { - if (finished === false) { - finished = true; - if (head.length > 0) { - sock.unshift(head); - } - return callback(null, sock); - } - }); - } - - req.on('connect', function () { - clearTimeout(connectionTimeoutTimer); - }); - - req.on('disconnect', function () { - clearTimeout(connectionTimeoutTimer); - }); - - req.on('response', function (res) { - clearTimeout(connectionTimeoutTimer); - if (context.isStream === true) { - if (finished === false) { - finished = true; - self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback); - } - } else { - // The native 'request' method only handles aborting during the request lifecycle not the response lifecycle. - // We need to make the response stream abortable so that it's destroyed with an error on abort and then - // it triggers the request 'error' event - if (options.signal != null) { - stream.addAbortSignal(options.signal, res) - } - var chunks = []; - res.on('data', function (chunk) { - chunks.push(chunk); - }); - - res.on('end', function () { - var buffer = Buffer.concat(chunks); - var result = buffer.toString(); - - debug('Received: %s', result); - - var json = utils.parseJSON(result) || buffer; - if (finished === false) { - finished = true; - self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback); - } - }); - } - }); - - req.on('error', function (error) { - clearTimeout(connectionTimeoutTimer); - if (finished === false) { - finished = true; - self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback); - } - }); - - if (typeof data === 'string' || Buffer.isBuffer(data)) { - req.write(data); - } else if (data) { - data.on('error', function (error) { - req.destroy(error); - }); - data.pipe(req); - } - - if (!context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) { - req.end(); - } -}; - -Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) { - if (err) return cb(err, null); - - if (statusCodes[res.statusCode] !== true) { - getCause(isStream, res, json, function (err, cause) { - if (err) { - return cb(err, null); - } - var msg = new Error( - '(HTTP code ' + res.statusCode + ') ' + - (statusCodes[res.statusCode] || 'unexpected') + ' - ' + - (cause.message || cause.error || cause) + ' ' - ); - msg.reason = statusCodes[res.statusCode]; - msg.statusCode = res.statusCode; - msg.json = json; - cb(msg, null); - }); - } else { - if (openStdin) { - cb(null, new HttpDuplex(req, res)); - } else if (isStream) { - cb(null, res); - } else { - cb(null, json); - } - } - - function getCause(isStream, res, json, callback) { - var chunks = ''; - var done = false; - - if (isStream) { - res.on('data', function (chunk) { - chunks += chunk; - }); - res.on('error', function (err) { - handler(err, null); - }); - res.on('end', function () { - handler(null, utils.parseJSON(chunks) || chunks) - }); - } else { - callback(null, json); - } - - function handler(err, data) { - if (done === false) { - if (err) { - callback(err); - } else { - callback(null, data); - } - } - done = true; - } - } -}; - -Modem.prototype.demuxStream = function (streama, stdout, stderr) { - var nextDataType = null; - var nextDataLength = null; - var buffer = Buffer.from(''); - function processData(data) { - if (data) { - buffer = Buffer.concat([buffer, data]); - } - if (!nextDataType) { - if (buffer.length >= 8) { - var header = bufferSlice(8); - nextDataType = header.readUInt8(0); - nextDataLength = header.readUInt32BE(4); - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } else { - if (buffer.length >= nextDataLength) { - var content = bufferSlice(nextDataLength); - if (nextDataType === 1) { - stdout.write(content); - } else { - stderr.write(content); - } - nextDataType = null; - // It's possible we got a "data" that contains multiple messages - // Process the next one - processData(); - } - } - } - - function bufferSlice(end) { - var out = buffer.subarray(0, end); - buffer = Buffer.from(buffer.subarray(end, buffer.length)); - return out; - } - - streama.on('data', processData); -}; - -Modem.prototype.followProgress = function (streama, onFinished, onProgress) { - var buf = ''; - var output = []; - var finished = false; - - streama.on('data', onStreamEvent); - streama.on('error', onStreamError); - streama.on('end', onStreamEnd); - streama.on('close', onStreamEnd); - - function onStreamEvent(data) { - buf += data.toString(); - pump(); - - function pump() { - var pos; - while ((pos = buf.indexOf('\n')) >= 0) { - if (pos == 0) { - buf = buf.slice(1); - continue; - } - processLine(buf.slice(0, pos)); - buf = buf.slice(pos + 1); - } - } - - function processLine(line) { - if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1); - if (line.length > 0) { - var obj = JSON.parse(line); - output.push(obj); - if (onProgress) { - onProgress(obj); - } - } - } - }; - - function onStreamError(err) { - finished = true; - streama.removeListener('data', onStreamEvent); - streama.removeListener('error', onStreamError); - streama.removeListener('end', onStreamEnd); - streama.removeListener('close', onStreamEnd); - onFinished(err, output); - } - - function onStreamEnd() { - if (!finished) onFinished(null, output); - finished = true; - } -}; - -Modem.prototype.buildQuerystring = function (opts) { - var clone = {}; - - Object.keys(opts).map(function (key, i) { - if ( - opts[key] && - typeof opts[key] === 'object' && - !Array.isArray(opts[key]) - ) { - clone[key] = JSON.stringify(opts[key]); - } else { - clone[key] = opts[key]; - } - }); - - return querystring.stringify(clone); -}; - -module.exports = Modem; - - -/***/ }), - -/***/ 7964: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var Client = (__nccwpck_require__(95869).Client), - http = __nccwpck_require__(13685); - -module.exports = function (opt) { - var conn = new Client(); - var agent = new http.Agent(); - - agent.createConnection = function (options, fn) { - try { - conn.once('ready', function () { - conn.exec('docker system dial-stdio', function (err, stream) { - if (err) { - handleError(err , fn); - } - - fn(null, stream); - - stream.addListener('error', (err) => { - handleError(err, fn); - }); - stream.once('close', () => { - conn.end(); - agent.destroy(); - }); - }); - }).on('error', (err) => { - handleError(err, fn); - }) - .connect(opt); - conn.once('end', () => agent.destroy()); - - } catch (err) { - handleError(err); - } - }; - - function handleError(err, cb) { - conn.end(); - agent.destroy(); - if (cb) { - cb(err); - } else { - throw err; - } - } - - return agent; -}; - - -/***/ }), - -/***/ 74967: -/***/ ((module) => { - -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js - -var arr = []; -var each = arr.forEach; -var slice = arr.slice; - -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; -}; - -module.exports.parseJSON = function(s) { - try { - return JSON.parse(s); - } catch (e) { - return null; - } -}; - - -/***/ }), - -/***/ 5004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a config - * @param {Object} modem docker-modem - * @param {String} id Config's id - */ -var Config = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Config.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Config.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update a config. - * - * @param {object} opts - * @param {function} callback - */ -Config.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs/' + this.id + '/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Removes the config - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Config.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'config not found', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - -module.exports = Config; - - -/***/ }), - -/***/ 35815: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var extend = (__nccwpck_require__(41604).extend), - Exec = __nccwpck_require__(73149), - util = __nccwpck_require__(41604); - -/** - * Represents a Container - * @param {Object} modem docker-modem - * @param {String} id Container's ID - */ -var Container = function(modem, id) { - this.modem = modem; - this.id = id; - - this.defaultOptions = { - top: {}, - start: {}, - commit: {}, - stop: {}, - pause: {}, - unpause: {}, - restart: {}, - resize: {}, - attach: {}, - remove: {}, - copy: {}, - kill: {}, - exec: {}, - rename: {}, - log: {}, - stats: {}, - getArchive: {}, - infoArchive: {}, - putArchive: {}, - update: {}, - wait: {} - }; -}; - -Container.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if supplied will query Docker. - * @return {Object} ID only and only if callback isn't supplied. - */ -Container.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Rename - * @param {Object} opts Rename options - * @param {Function} callback Callback - */ -Container.prototype.rename = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.rename); - - var optsf = { - path: '/containers/' + this.id + '/rename?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update - * @param {Object} opts Update options - * @param {Function} callback Callback - */ -Container.prototype.update = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.update); - - var optsf = { - path: '/containers/' + this.id + '/update', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Top - * @param {Object} opts like 'ps_args' (optional) - * @param {Function} callback Callback - */ -Container.prototype.top = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.top); - - var optsf = { - path: '/containers/' + this.id + '/top?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Containers changes - * @param {Object} Options - * @param {Function} callback Callback - */ -Container.prototype.changes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/changes', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Checkpoints list - * @param {Object} opts List checkpoints options (optional) - * @param {Function} callback Callback - */ -Container.prototype.listCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/checkpoints?', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Delete checkpoint - * @param {Object} opts Delete checkpoint options (optional) - * @param {Function} callback Callback - */ -Container.prototype.deleteCheckpoint = function(checkpoint, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/checkpoints/' + checkpoint + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Create checkpoint - * @param {Object} opts Create checkpoint options (optional) - * @param {Function} callback Callback - */ -Container.prototype.createCheckpoint = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/checkpoints', - method: 'POST', - abortSignal: args.opts.abortSignal, - allowEmpty: true, - statusCodes: { - 200: true, //unofficial, but proxies may return it - 201: true, - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Export - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with the octet-stream. - */ -Container.prototype.export = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/' + this.id + '/export', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Start - * @param {Object} opts Container start options (optional) - * @param {Function} callback Callback - */ -Container.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.start); - - var optsf = { - path: '/containers/' + this.id + '/start?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already started', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Pause - * @param {Object} opts Pause options (optional) - * @param {Function} callback Callback - */ -Container.prototype.pause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.pause); - - var optsf = { - path: '/containers/' + this.id + '/pause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Unpause - * @param {Object} opts Unpause options (optional) - * @param {Function} callback Callback - */ -Container.prototype.unpause = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.unpause); - - var optsf = { - path: '/containers/' + this.id + '/unpause', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Setup an exec call to a running container - * - * @param {object} opts - * @param {function} callback - */ -Container.prototype.exec = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.exec); - - var optsf = { - path: '/containers/' + this.id + '/exec', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 409: 'container stopped/paused', - 500: 'server error' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(new Exec(self.modem, data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, new Exec(self.modem, data.Id)); - }); - } -}; - -/** - * Commit - * @param {Object} opts Commit options like 'Hostname' (optional) - * @param {Function} callback Callback - */ -Container.prototype.commit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.commit); - - args.opts.container = this.id; - - var optsf = { - path: '/commit?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Stop - * @param {Object} opts Container stop options, like 't' (optional) - * @param {Function} callback Callback - */ -Container.prototype.stop = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stop); - - var optsf = { - path: '/containers/' + this.id + '/stop?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 304: 'container already stopped', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Restart - * @param {Object} opts Container restart options, like 't' (optional) - * @param {Function} callback Callback - */ -Container.prototype.restart = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.restart); - - var optsf = { - path: '/containers/' + this.id + '/restart?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Kill - * @param {Object} opts Container kill options, like 'signal' (optional) - * @param {Function} callback Callback - */ -Container.prototype.kill = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.kill); - - var optsf = { - path: '/containers/' + this.id + '/kill?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Container resize - * @param {[type]} opts Resize options. (optional) - * @param {Function} callback Callback - */ -Container.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.resize); - - var optsf = { - path: '/containers/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Attach - * @param {Object} opts Attach options, like 'logs' (optional) - * @param {Function} callback Callback with stream. - */ -Container.prototype.attach = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.attach); - - var optsf = { - path: '/containers/' + this.id + '/attach?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, stream) { - if (err) { - return reject(err); - } - resolve(stream); - }); - }); - } else { - this.modem.dial(optsf, function(err, stream) { - args.callback(err, stream); - }); - } -}; - -/** - * Waits for a container to end. - * @param {[type]} opts Container wait options, like condition. (optional) - * @param {Function} callback Callback - */ -Container.prototype.wait = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.wait); - - var optsf = { - path: '/containers/' + this.id + '/wait?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes a container - * @param {Object} opts Remove options, like 'force' (optional) - * @param {Function} callback Callback - */ -Container.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.remove); - - var optsf = { - path: '/containers/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 400: 'bad parameter', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Copy (WARNING: DEPRECATED since RAPI v1.20) - * @param {Object} opts Copy options, like 'Resource' (optional) - * @param {Function} callback Callback with stream. - */ -Container.prototype.copy = function(opts, callback) { - var self = this; - console.log('container.copy is deprecated since Docker v1.8.x'); - var args = util.processArgs(opts, callback, this.defaultOptions.copy); - - var optsf = { - path: '/containers/' + this.id + '/copy', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * getArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.getArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.getArchive); - - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * infoArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.infoArchive = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.infoArchive); - - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'HEAD', - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * putArchive - * @param {Object} opts Archive options, like 'path' - * @param {Function} callback Callback with stream. - */ -Container.prototype.putArchive = function(file, opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.putArchive); - - var optsf = { - path: '/containers/' + this.id + '/archive?', - method: 'PUT', - file: file, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'client error, bad parameters', - 403: 'client error, permission denied', - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Container logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Container.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); - - var optsf = { - path: '/containers/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Container stats - * @param {Object} opts Stats options. (optional) - * @param {Function} callback Callback with data - */ -Container.prototype.stats = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.stats); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/containers/' + this.id + '/stats?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such container', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -module.exports = Container; - - -/***/ }), - -/***/ 14571: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var EventEmitter = (__nccwpck_require__(82361).EventEmitter), - Modem = __nccwpck_require__(26042), - Container = __nccwpck_require__(35815), - Image = __nccwpck_require__(96689), - Volume = __nccwpck_require__(94877), - Network = __nccwpck_require__(39780), - Service = __nccwpck_require__(28866), - Plugin = __nccwpck_require__(16606), - Secret = __nccwpck_require__(79934), - Config = __nccwpck_require__(5004), - Task = __nccwpck_require__(61385), - Node = __nccwpck_require__(52297), - Exec = __nccwpck_require__(73149), - util = __nccwpck_require__(41604), - withSession = __nccwpck_require__(68304), - extend = util.extend; - -var Docker = function(opts) { - if (!(this instanceof Docker)) return new Docker(opts); - - var plibrary = global.Promise; - - if (opts && opts.Promise) { - plibrary = opts.Promise; - - if (Object.keys(opts).length === 1) { - opts = undefined; - } - } - - if (opts && opts.modem) { - this.modem = opts.modem; - } else { - this.modem = new Modem(opts); - } - this.modem.Promise = plibrary; -}; - -/** - * Creates a new container - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createContainer = function(opts, callback) { - var self = this; - var optsf = { - path: '/containers/create?', - method: 'POST', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 400: 'bad parameter', - 404: 'no such container', - 406: 'impossible to attach', - 500: 'server error' - } - }; - - delete opts.authconfig; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getContainer(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getContainer(data.Id)); - }); - } -}; - -/** - * Creates a new image - * @param {Object} auth Authentication (optional) - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createImage = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!callback && !opts) { - opts = auth; - auth = opts.authconfig; - } - - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Load image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.loadImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } - - var optsf = { - path: '/images/load?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Import image from a tar archive - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.importImage = function(file, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = undefined; - } - - if (!opts) - opts = {}; - - opts.fromSrc = '-'; - - var optsf = { - path: '/images/create?', - method: 'POST', - options: opts, - file: file, - abortSignal: opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Verifies auth - * @param {Object} opts Options - * @param {Function} callback Callback - */ -Docker.prototype.checkAuth = function(opts, callback) { - var self = this; - var optsf = { - path: '/auth', - method: 'POST', - options: opts, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Builds an image - * @param {String} file File - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.buildImage = function(file, opts, callback) { - var self = this; - - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } - - var optsf = { - path: '/build?', - method: 'POST', - file: undefined, - options: opts, - abortSignal: opts && opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (opts) { - if (opts.registryconfig) { - optsf.registryconfig = optsf.options.registryconfig; - delete optsf.options.registryconfig; - } - - //undocumented? - if (opts.authconfig) { - optsf.authconfig = optsf.options.authconfig; - delete optsf.options.authconfig; - } - - if (opts.cachefrom && Array.isArray(opts.cachefrom)) { - optsf.options.cachefrom = JSON.stringify(opts.cachefrom); - } - } - - function dial(callback) { - util.prepareBuildContext(file, (ctx) => { - optsf.file = ctx; - self.modem.dial(optsf, callback); - }); - } - - function dialWithSession(callback) { - if (opts?.version === "2") { - withSession(self, optsf.authconfig,(err, sessionId, done) => { - if (err) { - return callback(err); - } - - optsf.options.session = sessionId; - - dial((err, data) => { - callback(err, data); - - if (data) { - data.on("end", done); - } - }); - }); - } else { - dial(callback); - } - } - - if (callback === undefined) { - return new self.modem.Promise(function (resolve, reject) { - dialWithSession(function (err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - dialWithSession(callback); - } -}; - -/** - * Fetches a Container by ID - * @param {String} id Container's ID - */ -Docker.prototype.getContainer = function(id) { - return new Container(this.modem, id); -}; - -/** - * Fetches an Image by name - * @param {String} name Image's name - */ -Docker.prototype.getImage = function(name) { - return new Image(this.modem, name); -}; - -/** - * Fetches a Volume by name - * @param {String} name Volume's name - */ -Docker.prototype.getVolume = function(name) { - return new Volume(this.modem, name); -}; - -/** - * Fetches a Plugin by name - * @param {String} name Volume's name - */ -Docker.prototype.getPlugin = function(name, remote) { - return new Plugin(this.modem, name, remote); -}; - -/** - * Fetches a Service by id - * @param {String} id Services's id - */ -Docker.prototype.getService = function(id) { - return new Service(this.modem, id); -}; - -/** - * Fetches a Task by id - * @param {String} id Task's id - */ -Docker.prototype.getTask = function(id) { - return new Task(this.modem, id); -}; - -/** - * Fetches Node by id - * @param {String} id Node's id - */ -Docker.prototype.getNode = function(id) { - return new Node(this.modem, id); -}; - -/** - * Fetches a Network by id - * @param {String} id network's id - */ -Docker.prototype.getNetwork = function(id) { - return new Network(this.modem, id); -}; - -/** - * Fetches a Secret by id - * @param {String} id network's id - */ -Docker.prototype.getSecret = function(id) { - return new Secret(this.modem, id); -}; - -/** - * Fetches a Config by id - * @param {String} id network's id - */ -Docker.prototype.getConfig = function(id) { - return new Config(this.modem, id); -}; - -/** - * Fetches an Exec instance by ID - * @param {String} id Exec instance's ID - */ -Docker.prototype.getExec = function(id) { - return new Exec(this.modem, id); -}; - -/** - * Lists containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/json?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Get images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.getImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/get?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists Services - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listServices = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists Nodes - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listNodes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 404: 'no such node', - 500: 'server error', - 503: 'node is not part of a swarm', - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists Tasks - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listTasks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/tasks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Creates a new secret - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createSecret = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/secrets/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getSecret(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getSecret(data.ID)); - }); - } -}; - - -/** - * Creates a new config - * @param {Object} opts Config options - * @param {Function} callback Callback - */ -Docker.prototype.createConfig = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - var optsf = { - path: '/configs/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 406: 'server error or node is not part of a swarm', - 409: 'name conflicts with an existing object', - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getConfig(data.ID)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getConfig(data.ID)); - }); - } -}; - - -/** - * Lists secrets - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listSecrets = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/secrets?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Lists configs - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listConfigs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/configs?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Creates a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createPlugin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/plugins/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getPlugin(args.opts.name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getPlugin(args.opts.name)); - }); - } -}; - - -/** - * Lists plugins - * @param {Object} opts - * @param {Function} callback Callback - */ -Docker.prototype.listPlugins = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune images - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneImages = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune builder - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneBuilder = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/build/prune', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune containers - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneContainers = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/containers/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Prune networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.pruneNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/prune?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Creates a new volume - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createVolume = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/volumes/create?', - method: 'POST', - allowEmpty: true, - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getVolume(data.Name)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getVolume(data.Name)); - }); - } -}; - -/** - * Creates a new service - * @param {Object} auth - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createService = function(auth, opts, callback) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (!opts && !callback) { - opts = auth; - } - - - var self = this; - var optsf = { - path: '/services/create', - method: 'POST', - options: opts, - authconfig: auth, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 500: 'server error' - } - }; - - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getService(data.ID || data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return callback(err, data); - callback(err, self.getService(data.ID || data.Id)); - }); - } -}; - -/** - * Lists volumes - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listVolumes = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Creates a new network - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Docker.prototype.createNetwork = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - var optsf = { - path: '/networks/create?', - method: 'POST', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 404: 'driver not found', - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(self.getNetwork(data.Id)); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, self.getNetwork(data.Id)); - }); - } -}; - -/** - * Lists networks - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.listNetworks = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Search images - * @param {Object} opts Options - * @param {Function} callback Callback - */ -Docker.prototype.searchImages = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/search?', - method: 'GET', - options: opts, - authconfig: opts.authconfig, - abortSignal: opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Info - * @param {Object} opts Options (optional) - * @param {Function} callback Callback with info - */ -Docker.prototype.info = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/info', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Version - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.version = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/version', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Ping - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.ping = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/_ping', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * SystemDf equivalent to system/df API Engine - * get usage data information - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.df = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/system/df', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Events - * @param {Object} opts Events options, like 'since' (optional) - * @param {Function} callback Callback - */ -Docker.prototype.getEvents = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/events?', - method: 'GET', - options: args.opts, - abortSignal: args.opts.abortSignal, - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Pull is a wrapper around createImage, parsing image's tags. - * @param {String} repoTag Repository tag - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @param {Object} auth Authentication (optional) - * @return {Object} Image - */ -Docker.prototype.pull = function(repoTag, opts, callback, auth) { - var args = util.processArgs(opts, callback); - - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - args.opts.tag = imageSrc.tag || 'latest'; - - var argsf = [args.opts, args.callback]; - if (auth) { - argsf = [auth, args.opts, args.callback]; - } - return this.createImage.apply(this, argsf); -}; - -/** - * PullAll is a wrapper around createImage, to pull all image tags of an image. - * @param {String} repoTag Repository tag - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @param {Object} auth Authentication (optional) - * @return {Object} Image - */ -Docker.prototype.pullAll = function(repoTag, opts, callback, auth) { - var args = util.processArgs(opts, callback); - - var imageSrc = util.parseRepositoryTag(repoTag); - args.opts.fromImage = imageSrc.repository; - - var argsf = [args.opts, args.callback]; - if (auth) { - argsf = [auth, args.opts, args.callback]; - } - return this.createImage.apply(this, argsf); -}; - -/** - * Like run command from Docker's CLI - * @param {String} image Image name to be used. - * @param {Array} cmd Command to run in array format. - * @param {Object} streamo Output stream - * @param {Object} createOptions Container create options (optional) - * @param {Object} startOptions Container start options (optional) - * @param {Function} callback Callback - * @return {Object} EventEmitter - */ -Docker.prototype.run = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (typeof arguments[arguments.length - 1] === 'function') { - return this.runCallback(image, cmd, streamo, createOptions, startOptions, callback); - } else { - return this.runPromise(image, cmd, streamo, createOptions, startOptions); - } -}; - - -Docker.prototype.runCallback = function(image, cmd, streamo, createOptions, startOptions, callback) { - if (!callback && typeof createOptions === 'function') { - callback = createOptions; - createOptions = {}; - startOptions = {}; - } else if (!callback && typeof startOptions === 'function') { - callback = startOptions; - startOptions = {}; - } - - var hub = new EventEmitter(); - - function handler(err, container) { - if (err) return callback(err, null, container); - - hub.emit('container', container); - - container.attach({ - stream: true, - stdout: true, - stderr: true - }, function handler(err, stream) { - if (err) return callback(err, null, container); - - hub.emit('stream', stream); - - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - container.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } - } - - container.start(startOptions, function(err, data) { - if (err) return callback(err, data, container); - hub.emit('start', container); - - container.wait(function(err, data) { - hub.emit('data', data); - callback(err, data, container); - }); - }); - }); - } - - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] - }; - - extend(optsc, createOptions); - - this.createContainer(optsc, handler); - - return hub; -}; - -Docker.prototype.runPromise = function(image, cmd, streamo, createOptions, startOptions) { - var self = this; - - createOptions = createOptions || {}; - startOptions = startOptions || {}; - - var optsc = { - 'Hostname': '', - 'User': '', - 'AttachStdin': false, - 'AttachStdout': true, - 'AttachStderr': true, - 'Tty': true, - 'OpenStdin': false, - 'StdinOnce': false, - 'Env': null, - 'Cmd': cmd, - 'Image': image, - 'Volumes': {}, - 'VolumesFrom': [] - }; - - extend(optsc, createOptions); - - var containero; - - return new this.modem.Promise(function(resolve, reject) { - self.createContainer(optsc).then(function(container) { - containero = container; - return container.attach({ - stream: true, - stdout: true, - stderr: true - }); - }).then(function(stream) { - if (streamo) { - if (streamo instanceof Array) { - stream.on('end', function() { - try { - streamo[0].end(); - } catch (e) {} - try { - streamo[1].end(); - } catch (e) {} - }); - containero.modem.demuxStream(stream, streamo[0], streamo[1]); - } else { - stream.setEncoding('utf8'); - stream.pipe(streamo, { - end: true - }); - } - } - return containero.start(startOptions); - }).then(function(data) { - return containero.wait(); - }).then(function(data) { - resolve([data, containero]); - }).catch(function(err) { - reject(err); - }); - }); -}; - -/** - * Init swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmInit = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/init', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Join swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmJoin = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/join', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Leave swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmLeave = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/leave?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'node is not part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update swarm. - * - * @param {object} opts - * @param {function} callback - */ -Docker.prototype.swarmUpdate = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm/update?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 400: 'bad parameter', - 406: 'node is already part of a Swarm' - }, - options: args.opts - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Inspect a Swarm. - * Warning: This method is not documented in the API - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - */ -Docker.prototype.swarmInspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/swarm', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 406: 'This node is not a swarm manager', - 500: 'server error' - } - }; - - if (args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -Docker.Container = Container; -Docker.Image = Image; -Docker.Volume = Volume; -Docker.Network = Network; -Docker.Service = Service; -Docker.Plugin = Plugin; -Docker.Secret = Secret; -Docker.Task = Task; -Docker.Node = Node; -Docker.Exec = Exec; - -module.exports = Docker; - - -/***/ }), - -/***/ 73149: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Exec - * @param {Object} modem docker-modem - * @param {String} id Exec's ID - */ -var Exec = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Exec.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Start the exec call that was setup. - * - * @param {object} opts - * @param {function} callback - */ -Exec.prototype.start = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/exec/' + this.id + '/start', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - allowEmpty: true, - hijack: args.opts.hijack, - openStdin: args.opts.stdin, - statusCodes: { - 200: true, - 204: true, - 404: 'no such exec', - 409: 'container stopped/paused', - 500: 'container not running' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * Resize the exec call that was setup. - * - * @param {object} opts - * @param {function} callback - */ -Exec.prototype.resize = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/exec/' + this.id + '/resize?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'container not running' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * Get low-level information about the exec call. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Exec.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/exec/' + this.id + '/json', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such exec', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - - -module.exports = Exec; - - -/***/ }), - -/***/ 96689: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an image - * @param {Object} modem docker-modem - * @param {String} name Image's name - */ -var Image = function(modem, name) { - this.modem = modem; - this.name = name; -}; - -Image.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Inspect options, only 'manifests' (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.inspect = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - - var opts = { - path: '/images/' + this.name + '/json', - method: 'GET', - options: args.opts, - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * Distribution - * @param {Object} opts - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Image.prototype.distribution = function(opts, callback) { - var args = util.processArgs(opts, callback); - var self = this; - - var fopts = { - path: '/distribution/' + this.name + '/json', - method: 'GET', - statusCodes: { - 200: true, - 401: 'no such image', - 500: 'server error' - }, - authconfig: (args.opts) ? args.opts.authconfig : undefined - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(fopts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(fopts, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * History - * @param {Function} callback Callback - */ -Image.prototype.history = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/history', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; - -/** - * Get - * @param {Function} callback Callback with data stream. - */ -Image.prototype.get = function(callback) { - var self = this; - var opts = { - path: '/images/' + this.name + '/get', - method: 'GET', - isStream: true, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - if (err) return callback(err, data); - callback(err, data); - }); - } -}; - -/** - * Push - * @param {Object} opts Push options, like 'registry' (optional) - * @param {Function} callback Callback with stream. - * @param {Object} auth Registry authentication - */ -Image.prototype.push = function(opts, callback, auth) { - var self = this; - var args = util.processArgs(opts, callback); - var isStream = true; - if (args.opts.stream === false) { - isStream = false; - } - var optsf = { - path: '/images/' + this.name + '/push?', - method: 'POST', - options: args.opts, - authconfig: args.opts.authconfig || auth, - abortSignal: args.opts.abortSignal, - isStream: isStream, - statusCodes: { - 200: true, - 404: 'no such image', - 500: 'server error' - } - }; - - delete optsf.options.authconfig; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Tag - * @param {Object} opts Tag options, like 'repo' (optional) - * @param {Function} callback Callback - */ -Image.prototype.tag = function(opts, callback) { - var self = this; - var optsf = { - path: '/images/' + this.name + '/tag?', - method: 'POST', - options: opts, - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 201: true, - 400: 'bad parameter', - 404: 'no such image', - 409: 'conflict', - 500: 'server error' - } - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - -/** - * Removes the image - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Image.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/images/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such image', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -module.exports = Image; - - -/***/ }), - -/***/ 39780: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an network - * @param {Object} modem docker-modem - * @param {String} id Network's id - */ -var Network = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Network.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Id only if callback isn't specified. - */ -Network.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var opts = { - path: '/networks/' + this.id + '?', - method: 'GET', - statusCodes: { - 200: true, - 404: 'no such network', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(opts, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(opts, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes the network - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Network.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such network', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; - - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Connects a container to a network - * @param {[Object]} opts Connect options (optional) - * @param {Function} callback Callback - */ -Network.prototype.connect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/' + this.id + '/connect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Disconnects a container from a network - * @param {[Object]} opts Disconnect options (optional) - * @param {Function} callback Callback - */ -Network.prototype.disconnect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/networks/' + this.id + '/disconnect', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 201: true, - 404: 'network or container is not found', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - - -module.exports = Network; - - -/***/ }), - -/***/ 52297: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Node - * @param {Object} modem docker-modem - * @param {String} id Node's ID - */ -var Node = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Node.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Query Docker for Node details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Node.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Update a node. - * - * @param {object} opts - * @param {function} callback - */ -Node.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - } - - var optsf = { - path: '/nodes/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 406: 'node is not part of a swarm', - 500: 'server error' - }, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - -/** - * Remove a Node. - * Warning: This method is not documented in the API. - * - * @param {object} opts - * @param {function} callback - */ -Node.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/nodes/' + this.id + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such node', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -module.exports = Node; - - -/***/ }), - -/***/ 16606: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a plugin - * @param {Object} modem docker-modem - * @param {String} name Plugin's name - */ -var Plugin = function(modem, name, remote) { - this.modem = modem; - this.name = name; - this.remote = remote || name; -}; - -Plugin.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Plugin.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/json', - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes the plugin - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '?', - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin is not installed', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - if (err) return args.callback(err, data); - args.callback(err, data); - }); - } -}; - -/** - * get privileges - * @param {Object} opts Options (optional) - * @param {Function} callback Callback - * @return {Object} Name only if callback isn't specified. - */ -Plugin.prototype.privileges = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/privileges?', - method: 'GET', - options: { - 'remote': this.remote - }, - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Installs a new plugin - * @param {Object} opts Create options - * @param {Function} callback Callback - */ -Plugin.prototype.pull = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - if(args.opts._query && !args.opts._query.name) { - args.opts._query.name = this.name; - } - if(args.opts._query && !args.opts._query.remote) { - args.opts._query.remote = this.remote; - } - - var optsf = { - path: '/plugins/pull?', - method: 'POST', - abortSignal: args.opts.abortSignal, - isStream: true, - options: args.opts, - statusCodes: { - 200: true, // unofficial, but proxies may return it - 204: true, - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Enable - * @param {Object} opts Plugin enable options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.enable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/enable?', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Disable - * @param {Object} opts Plugin disable options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.disable = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/disable', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Push - * @param {Object} opts Plugin push options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.push = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/push', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * COnfigure - * @param {Object} opts Plugin configure options (optional) - * @param {Function} callback Callback - */ -Plugin.prototype.configure = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/plugins/' + this.name + '/set', - method: 'POST', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'plugin not installed', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -/** - * Upgrade plugin - * - * @param {object} auth - * @param {object} opts - * @param {function} callback - */ -Plugin.prototype.upgrade = function(auth, opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } - - var optsf = { - path: '/plugins/' + this.name + '/upgrade?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'plugin not installed', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - -module.exports = Plugin; - - -/***/ }), - -/***/ 79934: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a secret - * @param {Object} modem docker-modem - * @param {String} id Secret's id - */ -var Secret = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Secret.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Secret.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/secrets/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 406: 'node is not part of a swarm', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update a secret. - * - * @param {object} opts - * @param {function} callback - */ -Secret.prototype.update = function(opts, callback) { - var self = this; - if (!callback && typeof opts === 'function') { - callback = opts; - } - - var optsf = { - path: '/secrets/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'secret not found', - 500: 'server error' - }, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - -/** - * Removes the secret - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Secret.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/secrets/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'secret not found', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - -module.exports = Secret; - - -/***/ }), - -/***/ 28866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Service - * @param {Object} modem docker-modem - * @param {String} id Service's ID - */ -var Service = function(modem, id) { - this.modem = modem; - this.id = id; -}; - -Service.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Query Docker for service details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Service.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Delete Service - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Service.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/services/' + this.id, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 204: true, - 404: 'no such service', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Update service - * - * @param {object} auth - * @param {object} opts - * @param {function} callback - */ -Service.prototype.update = function(auth, opts, callback) { - var self = this; - if (!callback) { - var t = typeof opts; - if(t === 'function'){ - callback = opts; - opts = auth; - auth = opts.authconfig || undefined; - } else if (t === 'undefined'){ - opts = auth; - auth = opts.authconfig || undefined; - } - } - - var optsf = { - path: '/services/' + this.id + '/update?', - method: 'POST', - abortSignal: opts && opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error' - }, - authconfig: auth, - options: opts - }; - - if(callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - callback(err, data); - }); - } -}; - - - -/** - * Service logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Service.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, {}); - - var optsf = { - path: '/services/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 200: true, - 404: 'no such service', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - - -module.exports = Service; - - -/***/ }), - -/***/ 68304: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var grpc = __nccwpck_require__(7025), - protoLoader = __nccwpck_require__(98171), - path = __nccwpck_require__(71017), - uuid = (__nccwpck_require__(93704).v4); - -function withSession(docker, auth, handler) { - const sessionId = uuid(); - - const opts = { - method: "POST", - path: "/session", - hijack: true, - headers: { - Upgrade: "h2c", - "X-Docker-Expose-Session-Uuid": sessionId, - "X-Docker-Expose-Session-Name": "testcontainers", - }, - statusCodes: { - 200: true, - 500: "server error", - }, - }; - - docker.modem.dial(opts, function (err, socket) { - if (err) { - return handler(err, null, () => undefined); - } - - const server = new grpc.Server(); - const creds = grpc.ServerCredentials.createInsecure(); - const injector = server.createConnectionInjector(creds); - injector.injectConnection(socket); - - const pkg = protoLoader.loadSync( - __nccwpck_require__.ab + "auth.proto" - ); - const service = grpc.loadPackageDefinition(pkg); - - server.addService(service.moby.filesync.v1.Auth.service, { - Credentials({ request }, callback) { - // We probably want to have the possibility to pass credentials per - // hots. The correct one could be returned based on `request.Host` - if (auth) { - callback(null, { - Username: auth.username, - Secret: auth.password, - }); - } else { - callback(null, {}); - } - }, - }); - - function done() { - server.forceShutdown(); - socket.end(); - } - - handler(null, sessionId, done); - }); -} - -module.exports = withSession; - - -/***/ }), - -/***/ 61385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents an Task - * @param {Object} modem docker-modem - * @param {String} id Task's ID - */ -var Task = function(modem, id) { - this.modem = modem; - this.id = id; - - this.defaultOptions = { - log: {} - }; -}; - -Task.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Query Docker for Task details. - * - * @param {Object} opts Options (optional) - * @param {function} callback - */ -Task.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/tasks/' + this.id, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'unknown task', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Task logs - * @param {Object} opts Logs options. (optional) - * @param {Function} callback Callback with data - */ -Task.prototype.logs = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback, this.defaultOptions.log); - - var optsf = { - path: '/tasks/' + this.id + '/logs?', - method: 'GET', - abortSignal: args.opts.abortSignal, - isStream: args.opts.follow || false, - statusCodes: { - 101: true, - 200: true, - 404: 'no such container', - 500: 'server error', - 503: 'node is not part of a swarm' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - - -module.exports = Task; - - -/***/ }), - -/***/ 41604: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var DockerIgnore = __nccwpck_require__(3358); -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -var tar = __nccwpck_require__(366); -var zlib = __nccwpck_require__(59796); - -// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js - -var arr = []; -var each = arr.forEach; -var slice = arr.slice; - -module.exports.extend = function(obj) { - each.call(slice.call(arguments, 1), function(source) { - if (source) { - for (var prop in source) { - obj[prop] = source[prop]; - } - } - }); - return obj; -}; - -module.exports.processArgs = function(opts, callback, defaultOpts) { - if (!callback && typeof opts === 'function') { - callback = opts; - opts = null; - } - return { - callback: callback, - opts: module.exports.extend({}, defaultOpts, opts) - }; -}; - - -/** - * Parse the given repo tag name (as a string) and break it out into repo/tag pair. - * // if given the input http://localhost:8080/woot:latest - * { - * repository: 'http://localhost:8080/woot', - * tag: 'latest' - * } - * @param {String} input Input e.g: 'repo/foo', 'ubuntu', 'ubuntu:latest' - * @return {Object} input parsed into the repo and tag. - */ -module.exports.parseRepositoryTag = function(input) { - var separatorPos; - var digestPos = input.indexOf('@'); - var colonPos = input.lastIndexOf(':'); - // @ symbol is more important - if (digestPos >= 0) { - separatorPos = digestPos; - } else if (colonPos >= 0) { - separatorPos = colonPos; - } else { - // no colon nor @ - return { - repository: input - }; - } - - // last colon is either the tag (or part of a port designation) - var tag = input.slice(separatorPos + 1); - - // if it contains a / its not a tag and is part of the url - if (tag.indexOf('/') === -1) { - return { - repository: input.slice(0, separatorPos), - tag: tag - }; - } - - return { - repository: input - }; -}; - - -module.exports.prepareBuildContext = function(file, next) { - if (file && file.context) { - fs.readFile(path.join(file.context, '.dockerignore'), (err, data) => { - let ignoreFn; - let filterFn; - - if (!err) { - const dockerIgnore = DockerIgnore({ ignorecase: false }).add(data.toString()); - - filterFn = dockerIgnore.createFilter(); - ignoreFn = (path) => { - return !filterFn(path); - } - } - - const entries = file.src.slice() || [] - - const pack = tar.pack(file.context, { - entries: filterFn ? entries.filter(filterFn) : entries, - ignore: ignoreFn // Only works on directories - }); - - next(pack.pipe(zlib.createGzip())); - }) - } else { - next(file); - } -} - - -/***/ }), - -/***/ 94877: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(41604); - -/** - * Represents a volume - * @param {Object} modem docker-modem - * @param {String} name Volume's name - */ -var Volume = function(modem, name) { - this.modem = modem; - this.name = name; -}; - -Volume.prototype[(__nccwpck_require__(73837).inspect.custom)] = function() { return this; }; - -/** - * Inspect - * @param {Object} opts Options (optional) - * @param {Function} callback Callback, if specified Docker will be queried. - * @return {Object} Name only if callback isn't specified. - */ -Volume.prototype.inspect = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/' + this.name, - method: 'GET', - abortSignal: args.opts.abortSignal, - statusCodes: { - 200: true, - 404: 'no such volume', - 500: 'server error' - } - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -/** - * Removes the volume - * @param {[Object]} opts Remove options (optional) - * @param {Function} callback Callback - */ -Volume.prototype.remove = function(opts, callback) { - var self = this; - var args = util.processArgs(opts, callback); - - var optsf = { - path: '/volumes/' + this.name, - method: 'DELETE', - abortSignal: args.opts.abortSignal, - statusCodes: { - 204: true, - 404: 'no such volume', - 409: 'conflict', - 500: 'server error' - }, - options: args.opts - }; - - if(args.callback === undefined) { - return new this.modem.Promise(function(resolve, reject) { - self.modem.dial(optsf, function(err, data) { - if (err) { - return reject(err); - } - resolve(data); - }); - }); - } else { - this.modem.dial(optsf, function(err, data) { - args.callback(err, data); - }); - } -}; - -module.exports = Volume; - - -/***/ }), - -/***/ 93704: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ - value: true -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _max.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _nil.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _parse.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _stringify.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v1ToV.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v2.default; - } -}); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v4.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v5.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v6ToV.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _v6.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _validate.default; - } -}); -__webpack_unused_export__ = ({ - enumerable: true, - get: function () { - return _version.default; - } -}); -var _max = _interopRequireDefault(__nccwpck_require__(70789)); -var _nil = _interopRequireDefault(__nccwpck_require__(57358)); -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -var _stringify = _interopRequireDefault(__nccwpck_require__(91908)); -var _v = _interopRequireDefault(__nccwpck_require__(20631)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(96802)); -var _v2 = _interopRequireDefault(__nccwpck_require__(7980)); -var _v3 = _interopRequireDefault(__nccwpck_require__(26316)); -var _v4 = _interopRequireDefault(__nccwpck_require__(1858)); -var _v5 = _interopRequireDefault(__nccwpck_require__(33887)); -var _v6ToV = _interopRequireDefault(__nccwpck_require__(60553)); -var _v6 = _interopRequireDefault(__nccwpck_require__(43398)); -var _validate = _interopRequireDefault(__nccwpck_require__(45685)); -var _version = _interopRequireDefault(__nccwpck_require__(74354)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } - -/***/ }), - -/***/ 70789: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - -/***/ }), - -/***/ 12698: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('md5').update(bytes).digest(); -} -var _default = exports["default"] = md5; - -/***/ }), - -/***/ 18355: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -var _default = exports["default"] = { - randomUUID: _nodeCrypto.default.randomUUID -}; - -/***/ }), - -/***/ 57358: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; - -/***/ }), - -/***/ 70807: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(45685)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -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 = exports["default"] = parse; - -/***/ }), - -/***/ 95604: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - -/***/ }), - -/***/ 81359: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 66265: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(6005)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = exports["default"] = sha1; - -/***/ }), - -/***/ 91908: -/***/ ((__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__(45685)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * 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 - // - // Note to future-self: No, you can't remove the `toLowerCase()` call. - // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 - 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]]).toLowerCase(); -} -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 = exports["default"] = stringify; - -/***/ }), - -/***/ 20631: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(81359)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -// **`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; - let clockseq = options.clockseq; - - // v1 only: Use cached `node` and `clockseq` values - if (!options._v6) { - if (!node) { - node = _nodeId; - } - if (clockseq == null) { - clockseq = _clockseq; - } - } - - // Handle cases where we need entropy. 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)(); - - // Randomize node - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - - // v1 only: cache node value for reuse - if (!_nodeId && !options._v6) { - // per RFC4122 4.5: Set MAC multicast bit (v1 only) - node[0] |= 0x01; // Set multicast bit - - _nodeId = node; - } - } - - // Randomize clockseq - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; - } - } - } - - // v1 & v6 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 = exports["default"] = v1; - -/***/ }), - -/***/ 96802: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v1ToV6; -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v1 UUID to a v6 UUID - * - * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 - * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v1ToV6(uuid) { - const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v6Bytes = _v1ToV6(v1Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; -} - -// Do the field transformation needed for v1 -> v6 -function _v1ToV6(v1Bytes, randomize = false) { - return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); -} - -/***/ }), - -/***/ 7980: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(72149)); -var _md = _interopRequireDefault(__nccwpck_require__(12698)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = exports["default"] = v3; - -/***/ }), - -/***/ 72149: -/***/ ((__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__(91908); -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -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 = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -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; - } catch (err) {} - - // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 26316: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _native = _interopRequireDefault(__nccwpck_require__(18355)); -var _rng = _interopRequireDefault(__nccwpck_require__(81359)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -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 = exports["default"] = v4; - -/***/ }), - -/***/ 1858: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(72149)); -var _sha = _interopRequireDefault(__nccwpck_require__(66265)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = exports["default"] = v5; - -/***/ }), - -/***/ 33887: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6; -var _stringify = __nccwpck_require__(91908); -var _v = _interopRequireDefault(__nccwpck_require__(20631)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(96802)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * - * @param {object} options - * @param {Uint8Array=} buf - * @param {number=} offset - * @returns - */ -function v6(options = {}, buf, offset = 0) { - // v6 is v1 with different field layout, so we start with a v1 UUID, albeit - // with slightly different behavior around how the clock_seq and node fields - // are randomized, which is why we call v1 with _v6: true. - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - - // Reorder the fields to v6 layout. - bytes = (0, _v1ToV.default)(bytes); - - // Return as a byte array if requested - if (buf) { - for (let i = 0; i < 16; i++) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); -} - -/***/ }), - -/***/ 60553: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6ToV1; -var _parse = _interopRequireDefault(__nccwpck_require__(70807)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v6 UUID to a v1 UUID - * - * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 - * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v6ToV1(uuid) { - const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v1Bytes = _v6ToV1(v6Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; -} - -// Do the field transformation needed for v6 -> v1 -function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); -} - -/***/ }), - -/***/ 43398: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(81359)); -var _stringify = __nccwpck_require__(91908); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * UUID V7 - Unix Epoch time-based UUID - * - * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This - * implementation of V7 is based on the accepted, though not yet approved, - * revisions. - * - * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique - * IDentifiers (UUIDs) - - * - * Sample V7 value: - * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value - * - * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: - * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 - * - * 0 1 2 3 0 1 2 3 4 5 6 - * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | ver | seq_hi | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |var| seq_low | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit - * seq_low, and randomly initialized upon timestamp change. 31 bit counter size - * was selected as any bitwise operations in node are done as _signed_ 32 bit - * ints. we exclude the sign bit. - */ - -let _seqLow = null; -let _seqHigh = null; -let _msecs = 0; -function v7(options, buf, offset) { - options = options || {}; - - // initialize buffer and pointer - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - - // rnds is Uint8Array(16) filled with random bytes - const rnds = options.random || (options.rng || _rng.default)(); - - // milliseconds since unix epoch, 1970-01-01 00:00 - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // seq is user provided 31 bit counter - let seq = options.seq !== undefined ? options.seq : null; - - // initialize local seq high/low parts - let seqHigh = _seqHigh; - let seqLow = _seqLow; - - // check if clock has advanced and user has not provided msecs - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - - // unless user provided seq, reset seq parts - if (seq !== null) { - seqHigh = null; - seqLow = null; - } - } - - // if we have a user provided seq - if (seq !== null) { - // trim provided seq to 31 bits of value, avoiding overflow - if (seq > 0x7fffffff) { - seq = 0x7fffffff; - } - - // split provided seq into high/low parts - seqHigh = seq >>> 19 & 0xfff; - seqLow = seq & 0x7ffff; - } - - // randomly initialize seq - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 0x7f; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 0x3f; // pad for var - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; - } - - // increment seq if within msecs window - if (msecs + 10000 > _msecs && seq === null) { - if (++seqLow > 0x7ffff) { - seqLow = 0; - if (++seqHigh > 0xfff) { - seqHigh = 0; - - // increment internal _msecs. this allows us to continue incrementing - // while staying monotonic. Note, once we hit 10k milliseconds beyond system - // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) - _msecs++; - } - } - } else { - // resetting; we have advanced more than - // 10k milliseconds beyond system clock - _msecs = msecs; - } - _seqHigh = seqHigh; - _seqLow = seqLow; - - // [bytes 0-5] 48 bits of local timestamp - b[i++] = _msecs / 0x10000000000 & 0xff; - b[i++] = _msecs / 0x100000000 & 0xff; - b[i++] = _msecs / 0x1000000 & 0xff; - b[i++] = _msecs / 0x10000 & 0xff; - b[i++] = _msecs / 0x100 & 0xff; - b[i++] = _msecs & 0xff; - - // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi - b[i++] = seqHigh >>> 4 & 0x0f | 0x70; - - // [byte 7] remaining 8 bits of seq_hi - b[i++] = seqHigh & 0xff; - - // [byte 8] - variant (2 bits), first 6 bits seq_low - b[i++] = seqLow >>> 13 & 0x3f | 0x80; - - // [byte 9] 8 bits seq_low - b[i++] = seqLow >>> 5 & 0xff; - - // [byte 10] remaining 5 bits seq_low, 3 bits random - b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; - - // [bytes 11-15] always random - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v7; - -/***/ }), - -/***/ 45685: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(95604)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} -var _default = exports["default"] = validate; - -/***/ }), - -/***/ 74354: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(45685)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - return parseInt(uuid.slice(14, 15), 16); -} -var _default = exports["default"] = version; - -/***/ }), - -/***/ 62693: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var callBind = __nccwpck_require__(86815); -var gOPD = __nccwpck_require__(18501); - -var hasProtoAccessor; -try { - // eslint-disable-next-line no-extra-parens, no-proto - hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; -} catch (e) { - if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { - throw e; - } -} - -// eslint-disable-next-line no-extra-parens -var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); - -var $Object = Object; -var $getPrototypeOf = $Object.getPrototypeOf; - -/** @type {import('./get')} */ -module.exports = desc && typeof desc.get === 'function' - ? callBind([desc.get]) - : typeof $getPrototypeOf === 'function' - ? /** @type {import('./get')} */ function getDunder(value) { - // eslint-disable-next-line eqeqeq - return $getPrototypeOf(value == null ? value : $Object(value)); - } - : false; - - -/***/ }), - -/***/ 18212: -/***/ ((module) => { - -module.exports = () => { - // https://mths.be/emoji - return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; -}; - - -/***/ }), - -/***/ 81205: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223); - -var noop = function() {}; - -var qnt = global.Bare ? queueMicrotask : process.nextTick.bind(process); - -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() { - qnt(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; - - -/***/ }), - -/***/ 6123: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('.')} */ -var $defineProperty = Object.defineProperty || false; -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = false; - } -} - -module.exports = $defineProperty; - - -/***/ }), - -/***/ 91933: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./eval')} */ -module.exports = EvalError; - - -/***/ }), - -/***/ 28015: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('.')} */ -module.exports = Error; - - -/***/ }), - -/***/ 54415: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./range')} */ -module.exports = RangeError; - - -/***/ }), - -/***/ 46279: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./ref')} */ -module.exports = ReferenceError; - - -/***/ }), - -/***/ 75474: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./syntax')} */ -module.exports = SyntaxError; - - -/***/ }), - -/***/ 6361: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./type')} */ -module.exports = TypeError; - - -/***/ }), - -/***/ 5065: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./uri')} */ -module.exports = URIError; - - -/***/ }), - -/***/ 78308: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('.')} */ -module.exports = Object; - - -/***/ }), - -/***/ 11770: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var GetIntrinsic = __nccwpck_require__(74538); - -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); - -var hasToStringTag = __nccwpck_require__(99038)(); -var hasOwn = __nccwpck_require__(62157); -var $TypeError = __nccwpck_require__(6361); - -var toStringTag = hasToStringTag ? Symbol.toStringTag : null; - -/** @type {import('.')} */ -module.exports = function setToStringTag(object, value) { - var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; - var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; - if ( - (typeof overrideIfSet !== 'undefined' && typeof overrideIfSet !== 'boolean') - || (typeof nonConfigurable !== 'undefined' && typeof nonConfigurable !== 'boolean') - ) { - throw new $TypeError('if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans'); - } - if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) { - if ($defineProperty) { - $defineProperty(object, toStringTag, { - configurable: !nonConfigurable, - enumerable: false, - value: value, - writable: false - }); - } else { - object[toStringTag] = value; // eslint-disable-line no-param-reassign - } - } -}; - - -/***/ }), - -/***/ 31133: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var debug; - -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = __nccwpck_require__(38237)("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; - } - } - debug.apply(null, arguments); -}; - - -/***/ }), - -/***/ 67707: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var url = __nccwpck_require__(57310); -var URL = url.URL; -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var Writable = (__nccwpck_require__(12781).Writable); -var assert = __nccwpck_require__(39491); -var debug = __nccwpck_require__(31133); - -// Preventive platform detection -// istanbul ignore next -(function detectUnsupportedEnvironment() { - var looksLikeNode = typeof process !== "undefined"; - var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; - var looksLikeV8 = isFunction(Error.captureStackTrace); - if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { - console.warn("The follow-redirects package should be excluded from browser builds."); - } -}()); - -// Whether to use the native URL object or the legacy url module -var useNativeURL = false; -try { - assert(new URL("")); -} -catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; -} - -// URL fields to preserve in copy operations -var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash", -]; - -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); - -// Error types with codes -var InvalidUrlError = createErrorType( - "ERR_INVALID_URL", - "Invalid URL", - TypeError -); -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// istanbul ignore next -var destroy = Writable.prototype.destroy || noop; - -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } - - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - try { - self._processResponse(response); - } - catch (cause) { - self.emit("error", cause instanceof RedirectionError ? - cause : new RedirectionError({ cause: cause })); - } - }; - - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); - -RedirectableRequest.prototype.abort = function () { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); -}; - -RedirectableRequest.prototype.destroy = function (error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; -}; - -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - - // Validate input and shift parameters if necessary - if (!isString(data) && !isBuffer(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; - -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (isFunction(data)) { - callback = data; - data = encoding = null; - } - else if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; - -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; - -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; - -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } - - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } - - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - self.removeListener("close", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } - - // Attach callback if passed - if (callback) { - this.on("timeout", callback); - } - - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } - - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); - - return this; -}; - -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); - -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); - -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } - - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; - - -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } - - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } - - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } - - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._options.path; - - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - // istanbul ignore else - if (request === self._currentRequest) { - // Report any write errors - // istanbul ignore if - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - // istanbul ignore else - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; - -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - - // Clean up - this._requestBodyBuffers = []; - return; - } - - // The response is a redirect, so abort the current request - destroyRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); - } - - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } - - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = parseUrl(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); - - // Create the redirected request - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); - - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrl.protocol !== currentUrlParts.protocol && - redirectUrl.protocol !== "https:" || - redirectUrl.host !== currentHost && - !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); - } - - // Evaluate the beforeRedirect callback - if (isFunction(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); - } - - // Perform the redirected request - this._performRequest(); -}; - -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters, ensuring that input is an object - if (isURL(input)) { - input = spreadUrlObject(input); - } - else if (isString(input)) { - input = spreadUrlObject(parseUrl(input)); - } - else { - callback = options; - options = validateUrl(input); - input = { protocol: protocol }; - } - if (isFunction(options)) { - callback = options; - options = null; - } - - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString(options.host) && !isString(options.hostname)) { - options.hostname = "::1"; - } - - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } - - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} - -function noop() { /* empty */ } - -function parseUrl(input) { - var parsed; - // istanbul ignore else - if (useNativeURL) { - parsed = new URL(input); - } - else { - // Ensure the URL is valid and absolute - parsed = validateUrl(url.parse(input)); - if (!isString(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; -} - -function resolveUrl(relative, base) { - // istanbul ignore next - return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); -} - -function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; -} - -function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } - - // Fix IPv6 hostname - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - // Ensure port is a number - if (spread.port !== "") { - spread.port = Number(spread.port); - } - // Concatenate path - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; - - return spread; -} - -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} - -function createErrorType(code, message, baseClass) { - // Create constructor - function CustomError(properties) { - // istanbul ignore else - if (isFunction(Error.captureStackTrace)) { - Error.captureStackTrace(this, this.constructor); - } - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } - - // Attach constructor and set default properties - CustomError.prototype = new (baseClass || Error)(); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false, - }, - name: { - value: "Error [" + code + "]", - enumerable: false, - }, - }); - return CustomError; -} - -function destroyRequest(request, error) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); - } - request.on("error", noop); - request.destroy(error); -} - -function isSubdomain(subdomain, domain) { - assert(isString(subdomain) && isString(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} - -function isString(value) { - return typeof value === "string" || value instanceof String; -} - -function isFunction(value) { - return typeof value === "function"; -} - -function isBuffer(value) { - return typeof value === "object" && ("length" in value); -} - -function isURL(value) { - return URL && value instanceof URL; -} - -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; - - -/***/ }), - -/***/ 73186: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = (__nccwpck_require__(57147).constants) || __nccwpck_require__(22057) - - -/***/ }), - -/***/ 19320: -/***/ ((module) => { - -"use strict"; - - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var toStr = Object.prototype.toString; -var max = Math.max; -var funcType = '[object Function]'; - -var concatty = function concatty(a, b) { - var arr = []; - - for (var i = 0; i < a.length; i += 1) { - arr[i] = a[i]; - } - for (var j = 0; j < b.length; j += 1) { - arr[j + a.length] = b[j]; - } - - return arr; -}; - -var slicy = function slicy(arrLike, offset) { - var arr = []; - for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { - arr[j] = arrLike[i]; - } - return arr; -}; - -var joiny = function (arr, joiner) { - var str = ''; - for (var i = 0; i < arr.length; i += 1) { - str += arr[i]; - if (i + 1 < arr.length) { - str += joiner; - } - } - return str; -}; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - - }; - - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs[i] = '$' + i; - } - - bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - - -/***/ }), - -/***/ 88334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var implementation = __nccwpck_require__(19320); - -module.exports = Function.prototype.bind || implementation; - - -/***/ }), - -/***/ 74538: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var undefined; - -var $Object = __nccwpck_require__(78308); - -var $Error = __nccwpck_require__(28015); -var $EvalError = __nccwpck_require__(91933); -var $RangeError = __nccwpck_require__(54415); -var $ReferenceError = __nccwpck_require__(46279); -var $SyntaxError = __nccwpck_require__(75474); -var $TypeError = __nccwpck_require__(6361); -var $URIError = __nccwpck_require__(5065); - -var abs = __nccwpck_require__(19775); -var floor = __nccwpck_require__(60924); -var max = __nccwpck_require__(52419); -var min = __nccwpck_require__(73373); -var pow = __nccwpck_require__(78029); -var round = __nccwpck_require__(59396); -var sign = __nccwpck_require__(39091); - -var $Function = Function; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = __nccwpck_require__(18501); -var $defineProperty = __nccwpck_require__(6123); - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = __nccwpck_require__(40587)(); - -var getProto = __nccwpck_require__(13592); -var $ObjectGPO = __nccwpck_require__(5045); -var $ReflectGPO = __nccwpck_require__(78859); - -var $apply = __nccwpck_require__(54177); -var $call = __nccwpck_require__(2808); - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - __proto__: null, - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, - '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': $Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': $EvalError, - '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': $Object, - '%Object.getOwnPropertyDescriptor%': $gOPD, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': $RangeError, - '%ReferenceError%': $ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': $URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, - - '%Function.prototype.call%': $call, - '%Function.prototype.apply%': $apply, - '%Object.defineProperty%': $defineProperty, - '%Object.getPrototypeOf%': $ObjectGPO, - '%Math.abs%': abs, - '%Math.floor%': floor, - '%Math.max%': max, - '%Math.min%': min, - '%Math.pow%': pow, - '%Math.round%': round, - '%Math.sign%': sign, - '%Reflect.getPrototypeOf%': $ReflectGPO -}; - -if (getProto) { - try { - null.error; // eslint-disable-line no-unused-expressions - } catch (e) { - // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 - var errorProto = getProto(getProto(e)); - INTRINSICS['%Error.prototype%'] = errorProto; - } -} - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen && getProto) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - __proto__: null, - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = __nccwpck_require__(88334); -var hasOwn = __nccwpck_require__(62157); -var $concat = bind.call($call, Array.prototype.concat); -var $spliceApply = bind.call($apply, Array.prototype.splice); -var $replace = bind.call($call, String.prototype.replace); -var $strSlice = bind.call($call, String.prototype.slice); -var $exec = bind.call($call, RegExp.prototype.exec); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - if ($exec(/^%?[^%]*%?$/, name) === null) { - throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); - } - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - - -/***/ }), - -/***/ 5045: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var $Object = __nccwpck_require__(78308); - -/** @type {import('./Object.getPrototypeOf')} */ -module.exports = $Object.getPrototypeOf || null; - - -/***/ }), - -/***/ 78859: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./Reflect.getPrototypeOf')} */ -module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; - - -/***/ }), - -/***/ 13592: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var reflectGetProto = __nccwpck_require__(78859); -var originalGetProto = __nccwpck_require__(5045); - -var getDunderProto = __nccwpck_require__(62693); - -/** @type {import('.')} */ -module.exports = reflectGetProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return reflectGetProto(O); - } - : originalGetProto - ? function getProto(O) { - if (!O || (typeof O !== 'object' && typeof O !== 'function')) { - throw new TypeError('getProto: not an object'); - } - // @ts-expect-error TS can't narrow inside a closure, for some reason - return originalGetProto(O); - } - : getDunderProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return getDunderProto(O); - } - : null; - - -/***/ }), - -/***/ 57087: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./gOPD')} */ -module.exports = Object.getOwnPropertyDescriptor; - - -/***/ }), - -/***/ 18501: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/** @type {import('.')} */ -var $gOPD = __nccwpck_require__(57087); - -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - - -/***/ }), - -/***/ 40587: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = __nccwpck_require__(57747); - -/** @type {import('.')} */ -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - - -/***/ }), - -/***/ 57747: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./shams')} */ -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - /** @type {{ [k in symbol]?: unknown }} */ - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - // eslint-disable-next-line no-extra-parens - var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - - -/***/ }), - -/***/ 99038: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var hasSymbols = __nccwpck_require__(57747); - -/** @type {import('.')} */ -module.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; -}; - - -/***/ }), - -/***/ 62157: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var call = Function.prototype.call; -var $hasOwn = Object.prototype.hasOwnProperty; -var bind = __nccwpck_require__(88334); - -/** @type {import('.')} */ -module.exports = bind.call(call, $hasOwn); - - -/***/ }), - -/***/ 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 - } - } -} - - -/***/ }), - -/***/ 64882: -/***/ ((module) => { - -"use strict"; -/* eslint-disable yoda */ - - -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } - - return false; -}; - -module.exports = isFullwidthCodePoint; -module.exports["default"] = isFullwidthCodePoint; - - -/***/ }), - -/***/ 7994: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** Used to match words composed of alphanumeric characters. */ -var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - -/** Used to match Latin Unicode letters (excluding mathematical operators). */ -var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', - rsComboSymbolsRange = '\\u20d0-\\u20f0', - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - -/** Used to compose unicode capture groups. */ -var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - -/** Used to compose unicode regexes. */ -var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', - rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match apostrophes. */ -var reApos = RegExp(rsApos, 'g'); - -/** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ -var reComboMark = RegExp(rsCombo, 'g'); - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** Used to match complex or compound words. */ -var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', - rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, - rsUpper + '+' + rsOptUpperContr, - rsDigits, - rsEmoji -].join('|'), 'g'); - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); - -/** Used to detect strings that need a more robust regexp to match words. */ -var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - -/** Used to map Latin Unicode letters to basic Latin letters. */ -var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 'ss' -}; - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ -function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; -} - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -/** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function asciiWords(string) { - return string.match(reAsciiWord) || []; -} - -/** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; -} - -/** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ -var deburrLetter = basePropertyOf(deburredLetters); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ -function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function unicodeWords(string) { - return string.match(reUnicodeWord) || []; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var Symbol = root.Symbol; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} - -/** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ -function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; -} - -/** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ -function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {string} Returns the string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ -var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); -}); - -/** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ -function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); -} - -/** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('dƩjƠ vu'); - * // => 'deja vu' - */ -function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); -} - -/** - * Converts the first character of `string` to upper case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.upperFirst('fred'); - * // => 'Fred' - * - * _.upperFirst('FRED'); - * // => 'FRED' - */ -var upperFirst = createCaseFirst('toUpperCase'); - -/** - * Splits `string` into an array of its words. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {RegExp|string} [pattern] The pattern to match words. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the words of `string`. - * @example - * - * _.words('fred, barney, & pebbles'); - * // => ['fred', 'barney', 'pebbles'] - * - * _.words('fred, barney, & pebbles', /[^, ]+/g); - * // => ['fred', 'barney', '&', 'pebbles'] - */ -function words(string, pattern, guard) { - string = toString(string); - pattern = guard ? undefined : pattern; - - if (pattern === undefined) { - return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); - } - return string.match(pattern) || []; -} - -module.exports = camelCase; - - -/***/ }), - -/***/ 19775: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./abs')} */ -module.exports = Math.abs; - - -/***/ }), - -/***/ 60924: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./floor')} */ -module.exports = Math.floor; - - -/***/ }), - -/***/ 57661: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./isNaN')} */ -module.exports = Number.isNaN || function isNaN(a) { - return a !== a; -}; - - -/***/ }), - -/***/ 52419: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./max')} */ -module.exports = Math.max; - - -/***/ }), - -/***/ 73373: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./min')} */ -module.exports = Math.min; - - -/***/ }), - -/***/ 78029: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./pow')} */ -module.exports = Math.pow; - - -/***/ }), - -/***/ 59396: -/***/ ((module) => { - -"use strict"; - - -/** @type {import('./round')} */ -module.exports = Math.round; - - -/***/ }), - -/***/ 39091: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var $isNaN = __nccwpck_require__(57661); - -/** @type {import('./sign')} */ -module.exports = function sign(number) { - if ($isNaN(number) || number === 0) { - return number; - } - return number < 0 ? -1 : +1; -}; - - -/***/ }), - -/***/ 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 - } - }) -} - - -/***/ }), - -/***/ 97614: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; - - -/***/ }), - -/***/ 80900: -/***/ ((module) => { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function (val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} - - -/***/ }), - -/***/ 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 -} - - -/***/ }), - -/***/ 21629: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; - -var $protobuf = __nccwpck_require__(85881); -module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(__nccwpck_require__(43571)).lookup(".google.protobuf"); - -var Namespace = $protobuf.Namespace, - Root = $protobuf.Root, - Enum = $protobuf.Enum, - Type = $protobuf.Type, - Field = $protobuf.Field, - MapField = $protobuf.MapField, - OneOf = $protobuf.OneOf, - Service = $protobuf.Service, - Method = $protobuf.Method; - -// --- Root --- - -/** - * Properties of a FileDescriptorSet message. - * @interface IFileDescriptorSet - * @property {IFileDescriptorProto[]} file Files - */ - -/** - * Properties of a FileDescriptorProto message. - * @interface IFileDescriptorProto - * @property {string} [name] File name - * @property {string} [package] Package - * @property {*} [dependency] Not supported - * @property {*} [publicDependency] Not supported - * @property {*} [weakDependency] Not supported - * @property {IDescriptorProto[]} [messageType] Nested message types - * @property {IEnumDescriptorProto[]} [enumType] Nested enums - * @property {IServiceDescriptorProto[]} [service] Nested services - * @property {IFieldDescriptorProto[]} [extension] Nested extension fields - * @property {IFileOptions} [options] Options - * @property {*} [sourceCodeInfo] Not supported - * @property {string} [syntax="proto2"] Syntax - * @property {IEdition} [edition] Edition - */ - -/** - * Values of the Edition enum. - * @typedef IEdition - * @type {number} - * @property {number} EDITION_UNKNOWN=0 - * @property {number} EDITION_LEGACY=900 - * @property {number} EDITION_PROTO2=998 - * @property {number} EDITION_PROTO3=999 - * @property {number} EDITION_2023=1000 - * @property {number} EDITION_2024=1001 - * @property {number} EDITION_1_TEST_ONLY=1 - * @property {number} EDITION_2_TEST_ONLY=2 - * @property {number} EDITION_99997_TEST_ONLY=99997 - * @property {number} EDITION_99998_TEST_ONLY=99998 - * @property {number} EDITION_99998_TEST_ONLY=99999 - * @property {number} EDITION_MAX=2147483647 - */ - -/** - * Properties of a FileOptions message. - * @interface IFileOptions - * @property {string} [javaPackage] - * @property {string} [javaOuterClassname] - * @property {boolean} [javaMultipleFiles] - * @property {boolean} [javaGenerateEqualsAndHash] - * @property {boolean} [javaStringCheckUtf8] - * @property {IFileOptionsOptimizeMode} [optimizeFor=1] - * @property {string} [goPackage] - * @property {boolean} [ccGenericServices] - * @property {boolean} [javaGenericServices] - * @property {boolean} [pyGenericServices] - * @property {boolean} [deprecated] - * @property {boolean} [ccEnableArenas] - * @property {string} [objcClassPrefix] - * @property {string} [csharpNamespace] - */ - -/** - * Values of he FileOptions.OptimizeMode enum. - * @typedef IFileOptionsOptimizeMode - * @type {number} - * @property {number} SPEED=1 - * @property {number} CODE_SIZE=2 - * @property {number} LITE_RUNTIME=3 - */ - -/** - * Creates a root from a descriptor set. - * @param {IFileDescriptorSet|Reader|Uint8Array} descriptor Descriptor - * @returns {Root} Root instance - */ -Root.fromDescriptor = function fromDescriptor(descriptor) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.FileDescriptorSet.decode(descriptor); - - var root = new Root(); - - if (descriptor.file) { - var fileDescriptor, - filePackage; - for (var j = 0, i; j < descriptor.file.length; ++j) { - filePackage = root; - if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) - filePackage = root.define(fileDescriptor["package"]); - var edition = editionFromDescriptor(fileDescriptor); - if (fileDescriptor.name && fileDescriptor.name.length) - root.files.push(filePackage.filename = fileDescriptor.name); - if (fileDescriptor.messageType) - for (i = 0; i < fileDescriptor.messageType.length; ++i) - filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], edition)); - if (fileDescriptor.enumType) - for (i = 0; i < fileDescriptor.enumType.length; ++i) - filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition)); - if (fileDescriptor.extension) - for (i = 0; i < fileDescriptor.extension.length; ++i) - filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition)); - if (fileDescriptor.service) - for (i = 0; i < fileDescriptor.service.length; ++i) - filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition)); - var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions); - if (opts) { - var ks = Object.keys(opts); - for (i = 0; i < ks.length; ++i) - filePackage.setOption(ks[i], opts[ks[i]]); - } - } - } - - return root.resolveAll(); -}; - -/** - * Converts a root to a descriptor set. - * @returns {Message} Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - */ -Root.prototype.toDescriptor = function toDescriptor(edition) { - var set = exports.FileDescriptorSet.create(); - Root_toDescriptorRecursive(this, set.file, edition); - return set; -}; - -// Traverses a namespace and assembles the descriptor set -function Root_toDescriptorRecursive(ns, files, edition) { - - // Create a new file - var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); - editionToDescriptor(edition, file); - if (!(ns instanceof Root)) - file["package"] = ns.fullName.substring(1); - - // Add nested types - for (var i = 0, nested; i < ns.nestedArray.length; ++i) - if ((nested = ns._nestedArray[i]) instanceof Type) - file.messageType.push(nested.toDescriptor(edition)); - else if (nested instanceof Enum) - file.enumType.push(nested.toDescriptor()); - else if (nested instanceof Field) - file.extension.push(nested.toDescriptor(edition)); - else if (nested instanceof Service) - file.service.push(nested.toDescriptor()); - else if (nested instanceof /* plain */ Namespace) - Root_toDescriptorRecursive(nested, files, edition); // requires new file - - // Keep package-level options - file.options = toDescriptorOptions(ns.options, exports.FileOptions); - - // And keep the file only if there is at least one nested object - if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) - files.push(file); -} - -// --- Type --- - -/** - * Properties of a DescriptorProto message. - * @interface IDescriptorProto - * @property {string} [name] Message type name - * @property {IFieldDescriptorProto[]} [field] Fields - * @property {IFieldDescriptorProto[]} [extension] Extension fields - * @property {IDescriptorProto[]} [nestedType] Nested message types - * @property {IEnumDescriptorProto[]} [enumType] Nested enums - * @property {IDescriptorProtoExtensionRange[]} [extensionRange] Extension ranges - * @property {IOneofDescriptorProto[]} [oneofDecl] Oneofs - * @property {IMessageOptions} [options] Not supported - * @property {IDescriptorProtoReservedRange[]} [reservedRange] Reserved ranges - * @property {string[]} [reservedName] Reserved names - */ - -/** - * Properties of a MessageOptions message. - * @interface IMessageOptions - * @property {boolean} [mapEntry=false] Whether this message is a map entry - */ - -/** - * Properties of an ExtensionRange message. - * @interface IDescriptorProtoExtensionRange - * @property {number} [start] Start field id - * @property {number} [end] End field id - */ - -/** - * Properties of a ReservedRange message. - * @interface IDescriptorProtoReservedRange - * @property {number} [start] Start field id - * @property {number} [end] End field id - */ - -var unnamedMessageIndex = 0; - -/** - * Creates a type from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a nested object - * @returns {Type} Type instance - */ -Type.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.DescriptorProto.decode(descriptor); - - // Create the message type - var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)), - i; - - if (!nested) - type._edition = edition; - - /* Oneofs */ if (descriptor.oneofDecl) - for (i = 0; i < descriptor.oneofDecl.length; ++i) - type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); - /* Fields */ if (descriptor.field) - for (i = 0; i < descriptor.field.length; ++i) { - var field = Field.fromDescriptor(descriptor.field[i], edition, true); - type.add(field); - if (descriptor.field[i].hasOwnProperty("oneofIndex")) // eslint-disable-line no-prototype-builtins - type.oneofsArray[descriptor.field[i].oneofIndex].add(field); - } - /* Extension fields */ if (descriptor.extension) - for (i = 0; i < descriptor.extension.length; ++i) - type.add(Field.fromDescriptor(descriptor.extension[i], edition, true)); - /* Nested types */ if (descriptor.nestedType) - for (i = 0; i < descriptor.nestedType.length; ++i) { - type.add(Type.fromDescriptor(descriptor.nestedType[i], edition, true)); - if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) - type.setOption("map_entry", true); - } - /* Nested enums */ if (descriptor.enumType) - for (i = 0; i < descriptor.enumType.length; ++i) - type.add(Enum.fromDescriptor(descriptor.enumType[i], edition, true)); - /* Extension ranges */ if (descriptor.extensionRange && descriptor.extensionRange.length) { - type.extensions = []; - for (i = 0; i < descriptor.extensionRange.length; ++i) - type.extensions.push([ descriptor.extensionRange[i].start, descriptor.extensionRange[i].end ]); - } - /* Reserved... */ if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { - type.reserved = []; - /* Ranges */ if (descriptor.reservedRange) - for (i = 0; i < descriptor.reservedRange.length; ++i) - type.reserved.push([ descriptor.reservedRange[i].start, descriptor.reservedRange[i].end ]); - /* Names */ if (descriptor.reservedName) - for (i = 0; i < descriptor.reservedName.length; ++i) - type.reserved.push(descriptor.reservedName[i]); - } - - return type; -}; - -/** - * Converts a type to a descriptor. - * @returns {Message} Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - */ -Type.prototype.toDescriptor = function toDescriptor(edition) { - var descriptor = exports.DescriptorProto.create({ name: this.name }), - i; - - /* Fields */ for (i = 0; i < this.fieldsArray.length; ++i) { - var fieldDescriptor; - descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition)); - if (this._fieldsArray[i] instanceof MapField) { // map fields are repeated FieldNameEntry - var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), - valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), - valueTypeName = valueType === /* type */ 11 || valueType === /* enum */ 14 - ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type - : undefined; - descriptor.nestedType.push(exports.DescriptorProto.create({ - name: fieldDescriptor.typeName, - field: [ - exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), // can't reference a type or enum - exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) - ], - options: exports.MessageOptions.create({ mapEntry: true }) - })); - } - } - /* Oneofs */ for (i = 0; i < this.oneofsArray.length; ++i) - descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); - /* Nested... */ for (i = 0; i < this.nestedArray.length; ++i) { - /* Extension fields */ if (this._nestedArray[i] instanceof Field) - descriptor.field.push(this._nestedArray[i].toDescriptor(edition)); - /* Types */ else if (this._nestedArray[i] instanceof Type) - descriptor.nestedType.push(this._nestedArray[i].toDescriptor(edition)); - /* Enums */ else if (this._nestedArray[i] instanceof Enum) - descriptor.enumType.push(this._nestedArray[i].toDescriptor()); - // plain nested namespaces become packages instead in Root#toDescriptor - } - /* Extension ranges */ if (this.extensions) - for (i = 0; i < this.extensions.length; ++i) - descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); - /* Reserved... */ if (this.reserved) - for (i = 0; i < this.reserved.length; ++i) - /* Names */ if (typeof this.reserved[i] === "string") - descriptor.reservedName.push(this.reserved[i]); - /* Ranges */ else - descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); - - descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions); - - return descriptor; -}; - -// --- Field --- - -/** - * Properties of a FieldDescriptorProto message. - * @interface IFieldDescriptorProto - * @property {string} [name] Field name - * @property {number} [number] Field id - * @property {IFieldDescriptorProtoLabel} [label] Field rule - * @property {IFieldDescriptorProtoType} [type] Field basic type - * @property {string} [typeName] Field type name - * @property {string} [extendee] Extended type name - * @property {string} [defaultValue] Literal default value - * @property {number} [oneofIndex] Oneof index if part of a oneof - * @property {*} [jsonName] Not supported - * @property {IFieldOptions} [options] Field options - */ - -/** - * Values of the FieldDescriptorProto.Label enum. - * @typedef IFieldDescriptorProtoLabel - * @type {number} - * @property {number} LABEL_OPTIONAL=1 - * @property {number} LABEL_REQUIRED=2 - * @property {number} LABEL_REPEATED=3 - */ - -/** - * Values of the FieldDescriptorProto.Type enum. - * @typedef IFieldDescriptorProtoType - * @type {number} - * @property {number} TYPE_DOUBLE=1 - * @property {number} TYPE_FLOAT=2 - * @property {number} TYPE_INT64=3 - * @property {number} TYPE_UINT64=4 - * @property {number} TYPE_INT32=5 - * @property {number} TYPE_FIXED64=6 - * @property {number} TYPE_FIXED32=7 - * @property {number} TYPE_BOOL=8 - * @property {number} TYPE_STRING=9 - * @property {number} TYPE_GROUP=10 - * @property {number} TYPE_MESSAGE=11 - * @property {number} TYPE_BYTES=12 - * @property {number} TYPE_UINT32=13 - * @property {number} TYPE_ENUM=14 - * @property {number} TYPE_SFIXED32=15 - * @property {number} TYPE_SFIXED64=16 - * @property {number} TYPE_SINT32=17 - * @property {number} TYPE_SINT64=18 - */ - -/** - * Properties of a FieldOptions message. - * @interface IFieldOptions - * @property {boolean} [packed] Whether packed or not (defaults to `false` for proto2 and `true` for proto3) - * @property {IFieldOptionsJSType} [jstype] JavaScript value type (not used by protobuf.js) - */ - -/** - * Values of the FieldOptions.JSType enum. - * @typedef IFieldOptionsJSType - * @type {number} - * @property {number} JS_NORMAL=0 - * @property {number} JS_STRING=1 - * @property {number} JS_NUMBER=2 - */ - -// copied here from parse.js -var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; - -/** - * Creates a field from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IFieldDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a top-level object - * @returns {Field} Field instance - */ -Field.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.DescriptorProto.decode(descriptor); - - if (typeof descriptor.number !== "number") - throw Error("missing field id"); - - // Rewire field type - var fieldType; - if (descriptor.typeName && descriptor.typeName.length) - fieldType = descriptor.typeName; - else - fieldType = fromDescriptorType(descriptor.type); - - // Rewire field rule - var fieldRule; - switch (descriptor.label) { - // 0 is reserved for errors - case 1: fieldRule = undefined; break; - case 2: fieldRule = "required"; break; - case 3: fieldRule = "repeated"; break; - default: throw Error("illegal label: " + descriptor.label); - } - - var extendee = descriptor.extendee; - if (descriptor.extendee !== undefined) { - extendee = extendee.length ? extendee : undefined; - } - var field = new Field( - descriptor.name.length ? descriptor.name : "field" + descriptor.number, - descriptor.number, - fieldType, - fieldRule, - extendee - ); - - if (!nested) - field._edition = edition; - - field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions); - if (descriptor.proto3_optional) - field.options.proto3_optional = true; - - if (descriptor.defaultValue && descriptor.defaultValue.length) { - var defaultValue = descriptor.defaultValue; - switch (defaultValue) { - case "true": case "TRUE": - defaultValue = true; - break; - case "false": case "FALSE": - defaultValue = false; - break; - default: - var match = numberRe.exec(defaultValue); - if (match) - defaultValue = parseInt(defaultValue); // eslint-disable-line radix - break; - } - field.setOption("default", defaultValue); - } - - if (packableDescriptorType(descriptor.type)) { - if (edition === "proto3") { // defaults to packed=true (internal preset is packed=true) - if (descriptor.options && !descriptor.options.packed) - field.setOption("packed", false); - } else if ((!edition || edition === "proto2") && descriptor.options && descriptor.options.packed) // defaults to packed=false - field.setOption("packed", true); - } - - return field; -}; - -/** - * Converts a field to a descriptor. - * @returns {Message} Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - */ -Field.prototype.toDescriptor = function toDescriptor(edition) { - var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id }); - - if (this.map) { - - descriptor.type = 11; // message - descriptor.typeName = $protobuf.util.ucFirst(this.name); // fieldName -> FieldNameEntry (built in Type#toDescriptor) - descriptor.label = 3; // repeated - - } else { - - // Rewire field type - switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) { - case 10: // group - case 11: // type - case 14: // enum - descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; - break; - } - - // Rewire field rule - if (this.rule === "repeated") { - descriptor.label = 3; - } else if (this.required && edition === "proto2") { - descriptor.label = 2; - } else { - descriptor.label = 1; - } - } - - // Handle extension field - descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; - - // Handle part of oneof - if (this.partOf) - if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) - throw Error("missing oneof"); - - if (this.options) { - descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions); - if (this.options["default"] != null) - descriptor.defaultValue = String(this.options["default"]); - if (this.options.proto3_optional) - descriptor.proto3_optional = true; - } - - if (edition === "proto3") { // defaults to packed=true - if (!this.packed) - (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false; - } else if ((!edition || edition === "proto2") && this.packed) // defaults to packed=false - (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true; - - return descriptor; -}; - -// --- Enum --- - -/** - * Properties of an EnumDescriptorProto message. - * @interface IEnumDescriptorProto - * @property {string} [name] Enum name - * @property {IEnumValueDescriptorProto[]} [value] Enum values - * @property {IEnumOptions} [options] Enum options - */ - -/** - * Properties of an EnumValueDescriptorProto message. - * @interface IEnumValueDescriptorProto - * @property {string} [name] Name - * @property {number} [number] Value - * @property {*} [options] Not supported - */ - -/** - * Properties of an EnumOptions message. - * @interface IEnumOptions - * @property {boolean} [allowAlias] Whether aliases are allowed - * @property {boolean} [deprecated] - */ - -var unnamedEnumIndex = 0; - -/** - * Creates an enum from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IEnumDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a top-level object - * @returns {Enum} Enum instance - */ -Enum.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.EnumDescriptorProto.decode(descriptor); - - // Construct values object - var values = {}; - if (descriptor.value) - for (var i = 0; i < descriptor.value.length; ++i) { - var name = descriptor.value[i].name, - value = descriptor.value[i].number || 0; - values[name && name.length ? name : "NAME" + value] = value; - } - - var enm = new Enum( - descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, - values, - fromDescriptorOptions(descriptor.options, exports.EnumOptions) - ); - - if (!nested) - enm._edition = edition; - - return enm; -}; - -/** - * Converts an enum to a descriptor. - * @returns {Message} Descriptor - */ -Enum.prototype.toDescriptor = function toDescriptor() { - - // Values - var values = []; - for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i) - values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); - - return exports.EnumDescriptorProto.create({ - name: this.name, - value: values, - options: toDescriptorOptions(this.options, exports.EnumOptions) - }); -}; - -// --- OneOf --- - -/** - * Properties of a OneofDescriptorProto message. - * @interface IOneofDescriptorProto - * @property {string} [name] Oneof name - * @property {*} [options] Not supported - */ - -var unnamedOneofIndex = 0; - -/** - * Creates a oneof from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IOneofDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @returns {OneOf} OneOf instance - */ -OneOf.fromDescriptor = function fromDescriptor(descriptor) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.OneofDescriptorProto.decode(descriptor); - - return new OneOf( - // unnamedOneOfIndex is global, not per type, because we have no ref to a type here - descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++ - // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option - ); -}; - -/** - * Converts a oneof to a descriptor. - * @returns {Message} Descriptor - */ -OneOf.prototype.toDescriptor = function toDescriptor() { - return exports.OneofDescriptorProto.create({ - name: this.name - // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option - }); -}; - -// --- Service --- - -/** - * Properties of a ServiceDescriptorProto message. - * @interface IServiceDescriptorProto - * @property {string} [name] Service name - * @property {IMethodDescriptorProto[]} [method] Methods - * @property {IServiceOptions} [options] Options - */ - -/** - * Properties of a ServiceOptions message. - * @interface IServiceOptions - * @property {boolean} [deprecated] - */ - -var unnamedServiceIndex = 0; - -/** - * Creates a service from a descriptor. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @param {IServiceDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @param {string} [edition="proto2"] The syntax or edition to use - * @param {boolean} [nested=false] Whether or not this is a top-level object - * @returns {Service} Service instance - */ -Service.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.ServiceDescriptorProto.decode(descriptor); - - var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions)); - if (!nested) - service._edition = edition; - if (descriptor.method) - for (var i = 0; i < descriptor.method.length; ++i) - service.add(Method.fromDescriptor(descriptor.method[i])); - - return service; -}; - -/** - * Converts a service to a descriptor. - * @returns {Message} Descriptor - */ -Service.prototype.toDescriptor = function toDescriptor() { - - // Methods - var methods = []; - for (var i = 0; i < this.methodsArray.length; ++i) - methods.push(this._methodsArray[i].toDescriptor()); - - return exports.ServiceDescriptorProto.create({ - name: this.name, - method: methods, - options: toDescriptorOptions(this.options, exports.ServiceOptions) - }); -}; - -// --- Method --- - -/** - * Properties of a MethodDescriptorProto message. - * @interface IMethodDescriptorProto - * @property {string} [name] Method name - * @property {string} [inputType] Request type name - * @property {string} [outputType] Response type name - * @property {IMethodOptions} [options] Not supported - * @property {boolean} [clientStreaming=false] Whether requests are streamed - * @property {boolean} [serverStreaming=false] Whether responses are streamed - */ - -/** - * Properties of a MethodOptions message. - * - * Warning: this is not safe to use with editions protos, since it discards relevant file context. - * - * @interface IMethodOptions - * @property {boolean} [deprecated] - */ - -var unnamedMethodIndex = 0; - -/** - * Creates a method from a descriptor. - * @param {IMethodDescriptorProto|Reader|Uint8Array} descriptor Descriptor - * @returns {Method} Reflected method instance - */ -Method.fromDescriptor = function fromDescriptor(descriptor) { - - // Decode the descriptor message if specified as a buffer: - if (typeof descriptor.length === "number") - descriptor = exports.MethodDescriptorProto.decode(descriptor); - - return new Method( - // unnamedMethodIndex is global, not per service, because we have no ref to a service here - descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, - "rpc", - descriptor.inputType, - descriptor.outputType, - Boolean(descriptor.clientStreaming), - Boolean(descriptor.serverStreaming), - fromDescriptorOptions(descriptor.options, exports.MethodOptions) - ); -}; - -/** - * Converts a method to a descriptor. - * @returns {Message} Descriptor - */ -Method.prototype.toDescriptor = function toDescriptor() { - return exports.MethodDescriptorProto.create({ - name: this.name, - inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, - outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, - clientStreaming: this.requestStream, - serverStreaming: this.responseStream, - options: toDescriptorOptions(this.options, exports.MethodOptions) - }); -}; - -// --- utility --- - -// Converts a descriptor type to a protobuf.js basic type -function fromDescriptorType(type) { - switch (type) { - // 0 is reserved for errors - case 1: return "double"; - case 2: return "float"; - case 3: return "int64"; - case 4: return "uint64"; - case 5: return "int32"; - case 6: return "fixed64"; - case 7: return "fixed32"; - case 8: return "bool"; - case 9: return "string"; - case 12: return "bytes"; - case 13: return "uint32"; - case 15: return "sfixed32"; - case 16: return "sfixed64"; - case 17: return "sint32"; - case 18: return "sint64"; - } - throw Error("illegal type: " + type); -} - -// Tests if a descriptor type is packable -function packableDescriptorType(type) { - switch (type) { - case 1: // double - case 2: // float - case 3: // int64 - case 4: // uint64 - case 5: // int32 - case 6: // fixed64 - case 7: // fixed32 - case 8: // bool - case 13: // uint32 - case 14: // enum (!) - case 15: // sfixed32 - case 16: // sfixed64 - case 17: // sint32 - case 18: // sint64 - return true; - } - return false; -} - -// Converts a protobuf.js basic type to a descriptor type -function toDescriptorType(type, resolvedType, delimited) { - switch (type) { - // 0 is reserved for errors - case "double": return 1; - case "float": return 2; - case "int64": return 3; - case "uint64": return 4; - case "int32": return 5; - case "fixed64": return 6; - case "fixed32": return 7; - case "bool": return 8; - case "string": return 9; - case "bytes": return 12; - case "uint32": return 13; - case "sfixed32": return 15; - case "sfixed64": return 16; - case "sint32": return 17; - case "sint64": return 18; - } - if (resolvedType instanceof Enum) - return 14; - if (resolvedType instanceof Type) - return delimited ? 10 : 11; - throw Error("illegal type: " + type); -} - -function fromDescriptorOptionsRecursive(obj, type) { - var val = {}; - for (var i = 0, field, key; i < type.fieldsArray.length; ++i) { - if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") continue; - if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; - - var newKey = underScore(key); - if (field.resolvedType instanceof Type) { - val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType); - } else if(field.resolvedType instanceof Enum) { - val[newKey] = field.resolvedType.valuesById[obj[key]]; - } else { - val[newKey] = obj[key]; - } - } - return val; -} - -// Converts descriptor options to an options object -function fromDescriptorOptions(options, type) { - if (!options) - return undefined; - return fromDescriptorOptionsRecursive(type.toObject(options), type); -} - -function toDescriptorOptionsRecursive(obj, type) { - var val = {}; - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var newKey = $protobuf.util.camelCase(key); - if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) continue; - var field = type.fields[newKey]; - if (field.resolvedType instanceof Type) { - val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType); - } else { - val[newKey] = obj[key]; - } - if (field.repeated && !Array.isArray(val[newKey])) { - val[newKey] = [val[newKey]]; - } - } - return val; -} - -// Converts an options object to descriptor options -function toDescriptorOptions(options, type) { - if (!options) - return undefined; - return type.fromObject(toDescriptorOptionsRecursive(options, type)); -} - -// Calculates the shortest relative path from `from` to `to`. -function shortname(from, to) { - var fromPath = from.fullName.split("."), - toPath = to.fullName.split("."), - i = 0, - j = 0, - k = toPath.length - 1; - if (!(from instanceof Root) && to instanceof Namespace) - while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { - var other = to.lookup(fromPath[i++], true); - if (other !== null && other !== to) - break; - ++j; - } - else - for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j); - return toPath.slice(j).join("."); -} - -// copied here from cli/targets/proto.js -function underScore(str) { - return str.substring(0,1) - + str.substring(1) - .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); }); -} - -function editionFromDescriptor(fileDescriptor) { - if (fileDescriptor.syntax === "editions") { - switch(fileDescriptor.edition) { - case exports.Edition.EDITION_2023: - return "2023"; - default: - throw new Error("Unsupported edition " + fileDescriptor.edition); - } - } - if (fileDescriptor.syntax === "proto3") { - return "proto3"; - } - return "proto2"; -} - -function editionToDescriptor(edition, fileDescriptor) { - if (!edition) return; - if (edition === "proto2" || edition === "proto3") { - fileDescriptor.syntax = edition; - } else { - fileDescriptor.syntax = "editions"; - switch(edition) { - case "2023": - fileDescriptor.edition = exports.Edition.EDITION_2023; - break; - default: - throw new Error("Unsupported edition " + edition); - } - } -} - -// --- exports --- - -/** - * Reflected file descriptor set. - * @name FileDescriptorSet - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected file descriptor proto. - * @name FileDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected descriptor proto. - * @name DescriptorProto - * @type {Type} - * @property {Type} ExtensionRange - * @property {Type} ReservedRange - * @const - * @tstype $protobuf.Type & { - * ExtensionRange: $protobuf.Type, - * ReservedRange: $protobuf.Type - * } - */ - -/** - * Reflected field descriptor proto. - * @name FieldDescriptorProto - * @type {Type} - * @property {Enum} Label - * @property {Enum} Type - * @const - * @tstype $protobuf.Type & { - * Label: $protobuf.Enum, - * Type: $protobuf.Enum - * } - */ - -/** - * Reflected oneof descriptor proto. - * @name OneofDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum descriptor proto. - * @name EnumDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected service descriptor proto. - * @name ServiceDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum value descriptor proto. - * @name EnumValueDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected method descriptor proto. - * @name MethodDescriptorProto - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected file options. - * @name FileOptions - * @type {Type} - * @property {Enum} OptimizeMode - * @const - * @tstype $protobuf.Type & { - * OptimizeMode: $protobuf.Enum - * } - */ - -/** - * Reflected message options. - * @name MessageOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected field options. - * @name FieldOptions - * @type {Type} - * @property {Enum} CType - * @property {Enum} JSType - * @const - * @tstype $protobuf.Type & { - * CType: $protobuf.Enum, - * JSType: $protobuf.Enum - * } - */ - -/** - * Reflected oneof options. - * @name OneofOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum options. - * @name EnumOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected enum value options. - * @name EnumValueOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected service options. - * @name ServiceOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected method options. - * @name MethodOptions - * @type {Type} - * @const - * @tstype $protobuf.Type - */ - -/** - * Reflected uninterpretet option. - * @name UninterpretedOption - * @type {Type} - * @property {Type} NamePart - * @const - * @tstype $protobuf.Type & { - * NamePart: $protobuf.Type - * } - */ - -/** - * Reflected source code info. - * @name SourceCodeInfo - * @type {Type} - * @property {Type} Location - * @const - * @tstype $protobuf.Type & { - * Location: $protobuf.Type - * } - */ - -/** - * Reflected generated code info. - * @name GeneratedCodeInfo - * @type {Type} - * @property {Type} Annotation - * @const - * @tstype $protobuf.Type & { - * Annotation: $protobuf.Type - * } - */ - - -/***/ }), - -/***/ 85881: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// full library entry point. - - -module.exports = __nccwpck_require__(15360); - - -/***/ }), - -/***/ 12134: -/***/ ((module) => { - -"use strict"; - -module.exports = common; - -var commonRe = /\/|\./; - -/** - * Provides common type definitions. - * Can also be used to provide additional google types or your own custom types. - * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name - * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition - * @returns {undefined} - * @property {INamespace} google/protobuf/any.proto Any - * @property {INamespace} google/protobuf/duration.proto Duration - * @property {INamespace} google/protobuf/empty.proto Empty - * @property {INamespace} google/protobuf/field_mask.proto FieldMask - * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue - * @property {INamespace} google/protobuf/timestamp.proto Timestamp - * @property {INamespace} google/protobuf/wrappers.proto Wrappers - * @example - * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) - * protobuf.common("descriptor", descriptorJson); - * - * // manually provides a custom definition (uses my.foo namespace) - * protobuf.common("my/foo/bar.proto", myFooBarJson); - */ -function common(name, json) { - if (!commonRe.test(name)) { - name = "google/protobuf/" + name + ".proto"; - json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; - } - common[name] = json; -} - -// Not provided because of limited use (feel free to discuss or to provide yourself): -// -// google/protobuf/descriptor.proto -// google/protobuf/source_context.proto -// google/protobuf/type.proto -// -// Stripped and pre-parsed versions of these non-bundled files are instead available as part of -// the repository or package within the google/protobuf directory. - -common("any", { - - /** - * Properties of a google.protobuf.Any message. - * @interface IAny - * @type {Object} - * @property {string} [typeUrl] - * @property {Uint8Array} [bytes] - * @memberof common - */ - Any: { - fields: { - type_url: { - type: "string", - id: 1 - }, - value: { - type: "bytes", - id: 2 - } - } - } -}); - -var timeType; - -common("duration", { - - /** - * Properties of a google.protobuf.Duration message. - * @interface IDuration - * @type {Object} - * @property {number|Long} [seconds] - * @property {number} [nanos] - * @memberof common - */ - Duration: timeType = { - fields: { - seconds: { - type: "int64", - id: 1 - }, - nanos: { - type: "int32", - id: 2 - } - } - } -}); - -common("timestamp", { - - /** - * Properties of a google.protobuf.Timestamp message. - * @interface ITimestamp - * @type {Object} - * @property {number|Long} [seconds] - * @property {number} [nanos] - * @memberof common - */ - Timestamp: timeType -}); - -common("empty", { - - /** - * Properties of a google.protobuf.Empty message. - * @interface IEmpty - * @memberof common - */ - Empty: { - fields: {} - } -}); - -common("struct", { - - /** - * Properties of a google.protobuf.Struct message. - * @interface IStruct - * @type {Object} - * @property {Object.} [fields] - * @memberof common - */ - Struct: { - fields: { - fields: { - keyType: "string", - type: "Value", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.Value message. - * @interface IValue - * @type {Object} - * @property {string} [kind] - * @property {0} [nullValue] - * @property {number} [numberValue] - * @property {string} [stringValue] - * @property {boolean} [boolValue] - * @property {IStruct} [structValue] - * @property {IListValue} [listValue] - * @memberof common - */ - Value: { - oneofs: { - kind: { - oneof: [ - "nullValue", - "numberValue", - "stringValue", - "boolValue", - "structValue", - "listValue" - ] - } - }, - fields: { - nullValue: { - type: "NullValue", - id: 1 - }, - numberValue: { - type: "double", - id: 2 - }, - stringValue: { - type: "string", - id: 3 - }, - boolValue: { - type: "bool", - id: 4 - }, - structValue: { - type: "Struct", - id: 5 - }, - listValue: { - type: "ListValue", - id: 6 - } - } - }, - - NullValue: { - values: { - NULL_VALUE: 0 - } - }, - - /** - * Properties of a google.protobuf.ListValue message. - * @interface IListValue - * @type {Object} - * @property {Array.} [values] - * @memberof common - */ - ListValue: { - fields: { - values: { - rule: "repeated", - type: "Value", - id: 1 - } - } - } -}); - -common("wrappers", { - - /** - * Properties of a google.protobuf.DoubleValue message. - * @interface IDoubleValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - DoubleValue: { - fields: { - value: { - type: "double", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.FloatValue message. - * @interface IFloatValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - FloatValue: { - fields: { - value: { - type: "float", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.Int64Value message. - * @interface IInt64Value - * @type {Object} - * @property {number|Long} [value] - * @memberof common - */ - Int64Value: { - fields: { - value: { - type: "int64", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.UInt64Value message. - * @interface IUInt64Value - * @type {Object} - * @property {number|Long} [value] - * @memberof common - */ - UInt64Value: { - fields: { - value: { - type: "uint64", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.Int32Value message. - * @interface IInt32Value - * @type {Object} - * @property {number} [value] - * @memberof common - */ - Int32Value: { - fields: { - value: { - type: "int32", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.UInt32Value message. - * @interface IUInt32Value - * @type {Object} - * @property {number} [value] - * @memberof common - */ - UInt32Value: { - fields: { - value: { - type: "uint32", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.BoolValue message. - * @interface IBoolValue - * @type {Object} - * @property {boolean} [value] - * @memberof common - */ - BoolValue: { - fields: { - value: { - type: "bool", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.StringValue message. - * @interface IStringValue - * @type {Object} - * @property {string} [value] - * @memberof common - */ - StringValue: { - fields: { - value: { - type: "string", - id: 1 - } - } - }, - - /** - * Properties of a google.protobuf.BytesValue message. - * @interface IBytesValue - * @type {Object} - * @property {Uint8Array} [value] - * @memberof common - */ - BytesValue: { - fields: { - value: { - type: "bytes", - id: 1 - } - } - } -}); - -common("field_mask", { - - /** - * Properties of a google.protobuf.FieldMask message. - * @interface IDoubleValue - * @type {Object} - * @property {number} [value] - * @memberof common - */ - FieldMask: { - fields: { - paths: { - rule: "repeated", - type: "string", - id: 1 - } - } - } -}); - -/** - * Gets the root definition of the specified common proto file. - * - * Bundled definitions are: - * - google/protobuf/any.proto - * - google/protobuf/duration.proto - * - google/protobuf/empty.proto - * - google/protobuf/field_mask.proto - * - google/protobuf/struct.proto - * - google/protobuf/timestamp.proto - * - google/protobuf/wrappers.proto - * - * @param {string} file Proto file name - * @returns {INamespace|null} Root definition or `null` if not defined - */ -common.get = function get(file) { - return common[file] || null; -}; - - -/***/ }), - -/***/ 13617: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -/** - * Runtime message from/to plain object converters. - * @namespace - */ -var converter = exports; - -var Enum = __nccwpck_require__(17732), - util = __nccwpck_require__(47174); - -/** - * Generates a partial value fromObject conveter. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {number} fieldIndex Field index - * @param {string} prop Property reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genValuePartial_fromObject(gen, field, fieldIndex, prop) { - var defaultAlreadyEmitted = false; - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - if (field.resolvedType) { - if (field.resolvedType instanceof Enum) { gen - ("switch(d%s){", prop); - for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { - // enum unknown values passthrough - if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen - ("default:") - ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); - if (!field.repeated) gen // fallback to default value only for - // arrays, to avoid leaving holes. - ("break"); // for non-repeated fields, just ignore - defaultAlreadyEmitted = true; - } - gen - ("case%j:", keys[i]) - ("case %i:", values[keys[i]]) - ("m%s=%j", prop, values[keys[i]]) - ("break"); - } gen - ("}"); - } else gen - ("if(typeof d%s!==\"object\")", prop) - ("throw TypeError(%j)", field.fullName + ": object expected") - ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); - } else { - var isUnsigned = false; - switch (field.type) { - case "double": - case "float": gen - ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" - break; - case "uint32": - case "fixed32": gen - ("m%s=d%s>>>0", prop, prop); - break; - case "int32": - case "sint32": - case "sfixed32": gen - ("m%s=d%s|0", prop, prop); - break; - case "uint64": - isUnsigned = true; - // eslint-disable-next-line no-fallthrough - case "int64": - case "sint64": - case "fixed64": - case "sfixed64": gen - ("if(util.Long)") - ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) - ("else if(typeof d%s===\"string\")", prop) - ("m%s=parseInt(d%s,10)", prop, prop) - ("else if(typeof d%s===\"number\")", prop) - ("m%s=d%s", prop, prop) - ("else if(typeof d%s===\"object\")", prop) - ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); - break; - case "bytes": gen - ("if(typeof d%s===\"string\")", prop) - ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) - ("else if(d%s.length >= 0)", prop) - ("m%s=d%s", prop, prop); - break; - case "string": gen - ("m%s=String(d%s)", prop, prop); - break; - case "bool": gen - ("m%s=Boolean(d%s)", prop, prop); - break; - /* default: gen - ("m%s=d%s", prop, prop); - break; */ - } - } - return gen; - /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ -} - -/** - * Generates a plain object to runtime message converter specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -converter.fromObject = function fromObject(mtype) { - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - var fields = mtype.fieldsArray; - var gen = util.codegen(["d"], mtype.name + "$fromObject") - ("if(d instanceof this.ctor)") - ("return d"); - if (!fields.length) return gen - ("return new this.ctor"); - gen - ("var m=new this.ctor"); - for (var i = 0; i < fields.length; ++i) { - var field = fields[i].resolve(), - prop = util.safeProp(field.name); - - // Map fields - if (field.map) { gen - ("if(d%s){", prop) - ("if(typeof d%s!==\"object\")", prop) - ("throw TypeError(%j)", field.fullName + ": object expected") - ("m%s={}", prop) - ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); - break; - case "bytes": gen - ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); - break; - default: gen - ("d%s=m%s", prop, prop); - break; - } - } - return gen; - /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ -} - -/** - * Generates a runtime message to plain object converter specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -converter.toObject = function toObject(mtype) { - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); - if (!fields.length) - return util.codegen()("return {}"); - var gen = util.codegen(["m", "o"], mtype.name + "$toObject") - ("if(!o)") - ("o={}") - ("var d={}"); - - var repeatedFields = [], - mapFields = [], - normalFields = [], - i = 0; - for (; i < fields.length; ++i) - if (!fields[i].partOf) - ( fields[i].resolve().repeated ? repeatedFields - : fields[i].map ? mapFields - : normalFields).push(fields[i]); - - if (repeatedFields.length) { gen - ("if(o.arrays||o.defaults){"); - for (i = 0; i < repeatedFields.length; ++i) gen - ("d%s=[]", util.safeProp(repeatedFields[i].name)); - gen - ("}"); - } - - if (mapFields.length) { gen - ("if(o.objects||o.defaults){"); - for (i = 0; i < mapFields.length; ++i) gen - ("d%s={}", util.safeProp(mapFields[i].name)); - gen - ("}"); - } - - if (normalFields.length) { gen - ("if(o.defaults){"); - for (i = 0; i < normalFields.length; ++i) { - var field = normalFields[i], - prop = util.safeProp(field.name); - if (field.resolvedType instanceof Enum) gen - ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); - else if (field.long) gen - ("if(util.Long){") - ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) - ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) - ("}else") - ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); - else if (field.bytes) { - var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; - gen - ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) - ("else{") - ("d%s=%s", prop, arrayDefault) - ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) - ("}"); - } else gen - ("d%s=%j", prop, field.typeDefault); // also messages (=null) - } gen - ("}"); - } - var hasKs2 = false; - for (i = 0; i < fields.length; ++i) { - var field = fields[i], - index = mtype._fieldsArray.indexOf(field), - prop = util.safeProp(field.name); - if (field.map) { - if (!hasKs2) { hasKs2 = true; gen - ("var ks2"); - } gen - ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) - ("d%s={}", prop) - ("for(var j=0;j { - -"use strict"; - -module.exports = decoder; - -var Enum = __nccwpck_require__(17732), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -function missing(field) { - return "missing required '" + field.name + "'"; -} - -/** - * Generates a decoder specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -function decoder(mtype) { - /* eslint-disable no-unexpected-multiline */ - var gen = util.codegen(["r", "l", "e"], mtype.name + "$decode") - ("if(!(r instanceof Reader))") - ("r=Reader.create(r)") - ("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field) { return field.map; }).length ? ",k,value" : "")) - ("while(r.pos>>3){"); - - var i = 0; - for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { - var field = mtype._fieldsArray[i].resolve(), - type = field.resolvedType instanceof Enum ? "int32" : field.type, - ref = "m" + util.safeProp(field.name); gen - ("case %i: {", field.id); - - // Map fields - if (field.map) { gen - ("if(%s===util.emptyObject)", ref) - ("%s={}", ref) - ("var c2 = r.uint32()+r.pos"); - - if (types.defaults[field.keyType] !== undefined) gen - ("k=%j", types.defaults[field.keyType]); - else gen - ("k=null"); - - if (types.defaults[type] !== undefined) gen - ("value=%j", types.defaults[type]); - else gen - ("value=null"); - - gen - ("while(r.pos>>3){") - ("case 1: k=r.%s(); break", field.keyType) - ("case 2:"); - - if (types.basic[type] === undefined) gen - ("value=types[%i].decode(r,r.uint32())", i); // can't be groups - else gen - ("value=r.%s()", type); - - gen - ("break") - ("default:") - ("r.skipType(tag2&7)") - ("break") - ("}") - ("}"); - - if (types.long[field.keyType] !== undefined) gen - ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); - else gen - ("%s[k]=value", ref); - - // Repeated fields - } else if (field.repeated) { gen - - ("if(!(%s&&%s.length))", ref, ref) - ("%s=[]", ref); - - // Packable (always check for forward and backward compatiblity) - if (types.packed[type] !== undefined) gen - ("if((t&7)===2){") - ("var c2=r.uint32()+r.pos") - ("while(r.pos { - -"use strict"; - -module.exports = encoder; - -var Enum = __nccwpck_require__(17732), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -/** - * Generates a partial message type encoder. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {number} fieldIndex Field index - * @param {string} ref Variable reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genTypePartial(gen, field, fieldIndex, ref) { - return field.delimited - ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) - : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); -} - -/** - * Generates an encoder specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -function encoder(mtype) { - /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ - var gen = util.codegen(["m", "w"], mtype.name + "$encode") - ("if(!w)") - ("w=Writer.create()"); - - var i, ref; - - // "when a message is serialized its known fields should be written sequentially by field number" - var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); - - for (var i = 0; i < fields.length; ++i) { - var field = fields[i].resolve(), - index = mtype._fieldsArray.indexOf(field), - type = field.resolvedType instanceof Enum ? "int32" : field.type, - wireType = types.basic[type]; - ref = "m" + util.safeProp(field.name); - - // Map fields - if (field.map) { - gen - ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null - ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); - if (wireType === undefined) gen - ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups - else gen - (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); - gen - ("}") - ("}"); - - // Repeated fields - } else if (field.repeated) { gen - ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null - - // Packed repeated - if (field.packed && types.packed[type] !== undefined) { gen - - ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) - ("for(var i=0;i<%s.length;++i)", ref) - ("w.%s(%s[i])", type, ref) - ("w.ldelim()"); - - // Non-packed - } else { gen - - ("for(var i=0;i<%s.length;++i)", ref); - if (wireType === undefined) - genTypePartial(gen, field, index, ref + "[i]"); - else gen - ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); - - } gen - ("}"); - - // Non-repeated - } else { - if (field.optional) gen - ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null - - if (wireType === undefined) - genTypePartial(gen, field, index, ref); - else gen - ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); - - } - } - - return gen - ("return w"); - /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ -} - - -/***/ }), - -/***/ 17732: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Enum; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; - -var Namespace = __nccwpck_require__(76189), - util = __nccwpck_require__(47174); - -/** - * Constructs a new enum instance. - * @classdesc Reflected enum. - * @extends ReflectionObject - * @constructor - * @param {string} name Unique name within its namespace - * @param {Object.} [values] Enum values as an object, by name - * @param {Object.} [options] Declared options - * @param {string} [comment] The comment for this enum - * @param {Object.} [comments] The value comments for this enum - * @param {Object.>|undefined} [valuesOptions] The value options for this enum - */ -function Enum(name, values, options, comment, comments, valuesOptions) { - ReflectionObject.call(this, name, options); - - if (values && typeof values !== "object") - throw TypeError("values must be an object"); - - /** - * Enum values by id. - * @type {Object.} - */ - this.valuesById = {}; - - /** - * Enum values by name. - * @type {Object.} - */ - this.values = Object.create(this.valuesById); // toJSON, marker - - /** - * Enum comment text. - * @type {string|null} - */ - this.comment = comment; - - /** - * Value comment texts, if any. - * @type {Object.} - */ - this.comments = comments || {}; - - /** - * Values options, if any - * @type {Object>|undefined} - */ - this.valuesOptions = valuesOptions; - - /** - * Resolved values features, if any - * @type {Object>|undefined} - */ - this._valuesFeatures = {}; - - /** - * Reserved ranges, if any. - * @type {Array.} - */ - this.reserved = undefined; // toJSON - - // Note that values inherit valuesById on their prototype which makes them a TypeScript- - // compatible enum. This is used by pbts to write actual enum definitions that work for - // static and reflection code alike instead of emitting generic object definitions. - - if (values) - for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) - if (typeof values[keys[i]] === "number") // use forward entries only - this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; -} - -/** - * @override - */ -Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { - edition = this._edition || edition; - ReflectionObject.prototype._resolveFeatures.call(this, edition); - - Object.keys(this.values).forEach(key => { - var parentFeaturesCopy = Object.assign({}, this._features); - this._valuesFeatures[key] = Object.assign(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features); - }); - - return this; -}; - -/** - * Enum descriptor. - * @interface IEnum - * @property {Object.} values Enum values - * @property {Object.} [options] Enum options - */ - -/** - * Constructs an enum from an enum descriptor. - * @param {string} name Enum name - * @param {IEnum} json Enum descriptor - * @returns {Enum} Created enum - * @throws {TypeError} If arguments are invalid - */ -Enum.fromJSON = function fromJSON(name, json) { - var enm = new Enum(name, json.values, json.options, json.comment, json.comments); - enm.reserved = json.reserved; - if (json.edition) - enm._edition = json.edition; - enm._defaultEdition = "proto3"; // For backwards-compatibility. - return enm; -}; - -/** - * Converts this enum to an enum descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IEnum} Enum descriptor - */ -Enum.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "options" , this.options, - "valuesOptions" , this.valuesOptions, - "values" , this.values, - "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, - "comment" , keepComments ? this.comment : undefined, - "comments" , keepComments ? this.comments : undefined - ]); -}; - -/** - * Adds a value to this enum. - * @param {string} name Value name - * @param {number} id Value id - * @param {string} [comment] Comment, if any - * @param {Object.|undefined} [options] Options, if any - * @returns {Enum} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If there is already a value with this name or id - */ -Enum.prototype.add = function add(name, id, comment, options) { - // utilized by the parser but not by .fromJSON - - if (!util.isString(name)) - throw TypeError("name must be a string"); - - if (!util.isInteger(id)) - throw TypeError("id must be an integer"); - - if (this.values[name] !== undefined) - throw Error("duplicate name '" + name + "' in " + this); - - if (this.isReservedId(id)) - throw Error("id " + id + " is reserved in " + this); - - if (this.isReservedName(name)) - throw Error("name '" + name + "' is reserved in " + this); - - if (this.valuesById[id] !== undefined) { - if (!(this.options && this.options.allow_alias)) - throw Error("duplicate id " + id + " in " + this); - this.values[name] = id; - } else - this.valuesById[this.values[name] = id] = name; - - if (options) { - if (this.valuesOptions === undefined) - this.valuesOptions = {}; - this.valuesOptions[name] = options || null; - } - - this.comments[name] = comment || null; - return this; -}; - -/** - * Removes a value from this enum - * @param {string} name Value name - * @returns {Enum} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If `name` is not a name of this enum - */ -Enum.prototype.remove = function remove(name) { - - if (!util.isString(name)) - throw TypeError("name must be a string"); - - var val = this.values[name]; - if (val == null) - throw Error("name '" + name + "' does not exist in " + this); - - delete this.valuesById[val]; - delete this.values[name]; - delete this.comments[name]; - if (this.valuesOptions) - delete this.valuesOptions[name]; - - return this; -}; - -/** - * Tests if the specified id is reserved. - * @param {number} id Id to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Enum.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); -}; - -/** - * Tests if the specified name is reserved. - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Enum.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); -}; - - -/***/ }), - -/***/ 48213: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Field; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; - -var Enum = __nccwpck_require__(17732), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -var Type; // cyclic - -var ruleRe = /^required|optional|repeated$/; - -/** - * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. - * @name Field - * @classdesc Reflected message field. - * @extends FieldBase - * @constructor - * @param {string} name Unique name within its namespace - * @param {number} id Unique id within its namespace - * @param {string} type Value type - * @param {string|Object.} [rule="optional"] Field rule - * @param {string|Object.} [extend] Extended type if different from parent - * @param {Object.} [options] Declared options - */ - -/** - * Constructs a field from a field descriptor. - * @param {string} name Field name - * @param {IField} json Field descriptor - * @returns {Field} Created field - * @throws {TypeError} If arguments are invalid - */ -Field.fromJSON = function fromJSON(name, json) { - var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); - if (json.edition) - field._edition = json.edition; - field._defaultEdition = "proto3"; // For backwards-compatibility. - return field; -}; - -/** - * Not an actual constructor. Use {@link Field} instead. - * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. - * @exports FieldBase - * @extends ReflectionObject - * @constructor - * @param {string} name Unique name within its namespace - * @param {number} id Unique id within its namespace - * @param {string} type Value type - * @param {string|Object.} [rule="optional"] Field rule - * @param {string|Object.} [extend] Extended type if different from parent - * @param {Object.} [options] Declared options - * @param {string} [comment] Comment associated with this field - */ -function Field(name, id, type, rule, extend, options, comment) { - - if (util.isObject(rule)) { - comment = extend; - options = rule; - rule = extend = undefined; - } else if (util.isObject(extend)) { - comment = options; - options = extend; - extend = undefined; - } - - ReflectionObject.call(this, name, options); - - if (!util.isInteger(id) || id < 0) - throw TypeError("id must be a non-negative integer"); - - if (!util.isString(type)) - throw TypeError("type must be a string"); - - if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) - throw TypeError("rule must be a string rule"); - - if (extend !== undefined && !util.isString(extend)) - throw TypeError("extend must be a string"); - - /** - * Field rule, if any. - * @type {string|undefined} - */ - if (rule === "proto3_optional") { - rule = "optional"; - } - this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON - - /** - * Field type. - * @type {string} - */ - this.type = type; // toJSON - - /** - * Unique field id. - * @type {number} - */ - this.id = id; // toJSON, marker - - /** - * Extended type if different from parent. - * @type {string|undefined} - */ - this.extend = extend || undefined; // toJSON - - /** - * Whether this field is repeated. - * @type {boolean} - */ - this.repeated = rule === "repeated"; - - /** - * Whether this field is a map or not. - * @type {boolean} - */ - this.map = false; - - /** - * Message this field belongs to. - * @type {Type|null} - */ - this.message = null; - - /** - * OneOf this field belongs to, if any, - * @type {OneOf|null} - */ - this.partOf = null; - - /** - * The field type's default value. - * @type {*} - */ - this.typeDefault = null; - - /** - * The field's default value on prototypes. - * @type {*} - */ - this.defaultValue = null; - - /** - * Whether this field's value should be treated as a long. - * @type {boolean} - */ - this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; - - /** - * Whether this field's value is a buffer. - * @type {boolean} - */ - this.bytes = type === "bytes"; - - /** - * Resolved type if not a basic type. - * @type {Type|Enum|null} - */ - this.resolvedType = null; - - /** - * Sister-field within the extended type if a declaring extension field. - * @type {Field|null} - */ - this.extensionField = null; - - /** - * Sister-field within the declaring namespace if an extended field. - * @type {Field|null} - */ - this.declaringField = null; - - /** - * Comment for this field. - * @type {string|null} - */ - this.comment = comment; -} - -/** - * Determines whether this field is required. - * @name Field#required - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "required", { - get: function() { - return this._features.field_presence === "LEGACY_REQUIRED"; - } -}); - -/** - * Determines whether this field is not required. - * @name Field#optional - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "optional", { - get: function() { - return !this.required; - } -}); - -/** - * Determines whether this field uses tag-delimited encoding. In proto2 this - * corresponded to group syntax. - * @name Field#delimited - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "delimited", { - get: function() { - return this.resolvedType instanceof Type && - this._features.message_encoding === "DELIMITED"; - } -}); - -/** - * Determines whether this field is packed. Only relevant when repeated. - * @name Field#packed - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "packed", { - get: function() { - return this._features.repeated_field_encoding === "PACKED"; - } -}); - -/** - * Determines whether this field tracks presence. - * @name Field#hasPresence - * @type {boolean} - * @readonly - */ -Object.defineProperty(Field.prototype, "hasPresence", { - get: function() { - if (this.repeated || this.map) { - return false; - } - return this.partOf || // oneofs - this.declaringField || this.extensionField || // extensions - this._features.field_presence !== "IMPLICIT"; - } -}); - -/** - * @override - */ -Field.prototype.setOption = function setOption(name, value, ifNotSet) { - return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); -}; - -/** - * Field descriptor. - * @interface IField - * @property {string} [rule="optional"] Field rule - * @property {string} type Field type - * @property {number} id Field id - * @property {Object.} [options] Field options - */ - -/** - * Extension field descriptor. - * @interface IExtensionField - * @extends IField - * @property {string} extend Extended type - */ - -/** - * Converts this field to a field descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IField} Field descriptor - */ -Field.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "rule" , this.rule !== "optional" && this.rule || undefined, - "type" , this.type, - "id" , this.id, - "extend" , this.extend, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * Resolves this field's type references. - * @returns {Field} `this` - * @throws {Error} If any reference cannot be resolved - */ -Field.prototype.resolve = function resolve() { - - if (this.resolved) - return this; - - if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it - this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); - if (this.resolvedType instanceof Type) - this.typeDefault = null; - else // instanceof Enum - this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined - } else if (this.options && this.options.proto3_optional) { - // proto3 scalar value marked optional; should default to null - this.typeDefault = null; - } - - // use explicitly set default value if present - if (this.options && this.options["default"] != null) { - this.typeDefault = this.options["default"]; - if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") - this.typeDefault = this.resolvedType.values[this.typeDefault]; - } - - // remove unnecessary options - if (this.options) { - if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) - delete this.options.packed; - if (!Object.keys(this.options).length) - this.options = undefined; - } - - // convert to internal data type if necesssary - if (this.long) { - this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); - - /* istanbul ignore else */ - if (Object.freeze) - Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) - - } else if (this.bytes && typeof this.typeDefault === "string") { - var buf; - if (util.base64.test(this.typeDefault)) - util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); - else - util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); - this.typeDefault = buf; - } - - // take special care of maps and repeated fields - if (this.map) - this.defaultValue = util.emptyObject; - else if (this.repeated) - this.defaultValue = util.emptyArray; - else - this.defaultValue = this.typeDefault; - - // ensure proper value on prototype - if (this.parent instanceof Type) - this.parent.ctor.prototype[this.name] = this.defaultValue; - - return ReflectionObject.prototype.resolve.call(this); -}; - -/** - * Infers field features from legacy syntax that may have been specified differently. - * in older editions. - * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions - * @returns {object} The feature values to override - */ -Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { - if (edition !== "proto2" && edition !== "proto3") { - return {}; - } - - var features = {}; - - if (this.rule === "required") { - features.field_presence = "LEGACY_REQUIRED"; - } - if (this.parent && types.defaults[this.type] === undefined) { - // We can't use resolvedType because types may not have been resolved yet. However, - // legacy groups are always in the same scope as the field so we don't have to do a - // full scan of the tree. - var type = this.parent.get(this.type.split(".").pop()); - if (type && type instanceof Type && type.group) { - features.message_encoding = "DELIMITED"; - } - } - if (this.getOption("packed") === true) { - features.repeated_field_encoding = "PACKED"; - } else if (this.getOption("packed") === false) { - features.repeated_field_encoding = "EXPANDED"; - } - return features; -}; - -/** - * @override - */ -Field.prototype._resolveFeatures = function _resolveFeatures(edition) { - return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); -}; - -/** - * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). - * @typedef FieldDecorator - * @type {function} - * @param {Object} prototype Target prototype - * @param {string} fieldName Field name - * @returns {undefined} - */ - -/** - * Field decorator (TypeScript). - * @name Field.d - * @function - * @param {number} fieldId Field id - * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type - * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule - * @param {T} [defaultValue] Default value - * @returns {FieldDecorator} Decorator function - * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] - */ -Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { - - // submessage: decorate the submessage and use its name as the type - if (typeof fieldType === "function") - fieldType = util.decorateType(fieldType).name; - - // enum reference: create a reflected copy of the enum and keep reuseing it - else if (fieldType && typeof fieldType === "object") - fieldType = util.decorateEnum(fieldType).name; - - return function fieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor) - .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); - }; -}; - -/** - * Field decorator (TypeScript). - * @name Field.d - * @function - * @param {number} fieldId Field id - * @param {Constructor|string} fieldType Field type - * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule - * @returns {FieldDecorator} Decorator function - * @template T extends Message - * @variation 2 - */ -// like Field.d but without a default value - -// Sets up cyclic dependencies (called in index-light) -Field._configure = function configure(Type_) { - Type = Type_; -}; - - -/***/ }), - -/***/ 26119: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var protobuf = module.exports = __nccwpck_require__(73242); - -protobuf.build = "light"; - -/** - * A node-style callback as used by {@link load} and {@link Root#load}. - * @typedef LoadCallback - * @type {function} - * @param {Error|null} error Error, if any, otherwise `null` - * @param {Root} [root] Root, if there hasn't been an error - * @returns {undefined} - */ - -/** - * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. - * @param {string|string[]} filename One or multiple files to load - * @param {Root} root Root namespace, defaults to create a new one if omitted. - * @param {LoadCallback} callback Callback function - * @returns {undefined} - * @see {@link Root#load} - */ -function load(filename, root, callback) { - if (typeof root === "function") { - callback = root; - root = new protobuf.Root(); - } else if (!root) - root = new protobuf.Root(); - return root.load(filename, callback); -} - -/** - * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. - * @name load - * @function - * @param {string|string[]} filename One or multiple files to load - * @param {LoadCallback} callback Callback function - * @returns {undefined} - * @see {@link Root#load} - * @variation 2 - */ -// function load(filename:string, callback:LoadCallback):undefined - -/** - * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. - * @name load - * @function - * @param {string|string[]} filename One or multiple files to load - * @param {Root} [root] Root namespace, defaults to create a new one if omitted. - * @returns {Promise} Promise - * @see {@link Root#load} - * @variation 3 - */ -// function load(filename:string, [root:Root]):Promise - -protobuf.load = load; - -/** - * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). - * @param {string|string[]} filename One or multiple files to load - * @param {Root} [root] Root namespace, defaults to create a new one if omitted. - * @returns {Root} Root namespace - * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid - * @see {@link Root#loadSync} - */ -function loadSync(filename, root) { - if (!root) - root = new protobuf.Root(); - return root.loadSync(filename); -} - -protobuf.loadSync = loadSync; - -// Serialization -protobuf.encoder = __nccwpck_require__(23072); -protobuf.decoder = __nccwpck_require__(65871); -protobuf.verifier = __nccwpck_require__(34334); -protobuf.converter = __nccwpck_require__(13617); - -// Reflection -protobuf.ReflectionObject = __nccwpck_require__(83575); -protobuf.Namespace = __nccwpck_require__(76189); -protobuf.Root = __nccwpck_require__(32614); -protobuf.Enum = __nccwpck_require__(17732); -protobuf.Type = __nccwpck_require__(38520); -protobuf.Field = __nccwpck_require__(48213); -protobuf.OneOf = __nccwpck_require__(44408); -protobuf.MapField = __nccwpck_require__(67777); -protobuf.Service = __nccwpck_require__(6178); -protobuf.Method = __nccwpck_require__(57771); - -// Runtime -protobuf.Message = __nccwpck_require__(68027); -protobuf.wrappers = __nccwpck_require__(63216); - -// Utility -protobuf.types = __nccwpck_require__(6581); -protobuf.util = __nccwpck_require__(47174); - -// Set up possibly cyclic reflection dependencies -protobuf.ReflectionObject._configure(protobuf.Root); -protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); -protobuf.Root._configure(protobuf.Type); -protobuf.Field._configure(protobuf.Type); - - -/***/ }), - -/***/ 73242: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -var protobuf = exports; - -/** - * Build type, one of `"full"`, `"light"` or `"minimal"`. - * @name build - * @type {string} - * @const - */ -protobuf.build = "minimal"; - -// Serialization -protobuf.Writer = __nccwpck_require__(13098); -protobuf.BufferWriter = __nccwpck_require__(41863); -protobuf.Reader = __nccwpck_require__(41011); -protobuf.BufferReader = __nccwpck_require__(80339); - -// Utility -protobuf.util = __nccwpck_require__(71241); -protobuf.rpc = __nccwpck_require__(86444); -protobuf.roots = __nccwpck_require__(50073); -protobuf.configure = configure; - -/* istanbul ignore next */ -/** - * Reconfigures the library according to the environment. - * @returns {undefined} - */ -function configure() { - protobuf.util._configure(); - protobuf.Writer._configure(protobuf.BufferWriter); - protobuf.Reader._configure(protobuf.BufferReader); -} - -// Set up buffer utility according to the environment -configure(); - - -/***/ }), - -/***/ 15360: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -var protobuf = module.exports = __nccwpck_require__(26119); - -protobuf.build = "full"; - -// Parser -protobuf.tokenize = __nccwpck_require__(61157); -protobuf.parse = __nccwpck_require__(32137); -protobuf.common = __nccwpck_require__(12134); - -// Configure parser -protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); - - -/***/ }), - -/***/ 67777: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = MapField; - -// extends Field -var Field = __nccwpck_require__(48213); -((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; - -var types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -/** - * Constructs a new map field instance. - * @classdesc Reflected map field. - * @extends FieldBase - * @constructor - * @param {string} name Unique name within its namespace - * @param {number} id Unique id within its namespace - * @param {string} keyType Key type - * @param {string} type Value type - * @param {Object.} [options] Declared options - * @param {string} [comment] Comment associated with this field - */ -function MapField(name, id, keyType, type, options, comment) { - Field.call(this, name, id, type, undefined, undefined, options, comment); - - /* istanbul ignore if */ - if (!util.isString(keyType)) - throw TypeError("keyType must be a string"); - - /** - * Key type. - * @type {string} - */ - this.keyType = keyType; // toJSON, marker - - /** - * Resolved key type if not a basic type. - * @type {ReflectionObject|null} - */ - this.resolvedKeyType = null; - - // Overrides Field#map - this.map = true; -} - -/** - * Map field descriptor. - * @interface IMapField - * @extends {IField} - * @property {string} keyType Key type - */ - -/** - * Extension map field descriptor. - * @interface IExtensionMapField - * @extends IMapField - * @property {string} extend Extended type - */ - -/** - * Constructs a map field from a map field descriptor. - * @param {string} name Field name - * @param {IMapField} json Map field descriptor - * @returns {MapField} Created map field - * @throws {TypeError} If arguments are invalid - */ -MapField.fromJSON = function fromJSON(name, json) { - return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); -}; - -/** - * Converts this map field to a map field descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IMapField} Map field descriptor - */ -MapField.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "keyType" , this.keyType, - "type" , this.type, - "id" , this.id, - "extend" , this.extend, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * @override - */ -MapField.prototype.resolve = function resolve() { - if (this.resolved) - return this; - - // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" - if (types.mapKey[this.keyType] === undefined) - throw Error("invalid key type: " + this.keyType); - - return Field.prototype.resolve.call(this); -}; - -/** - * Map field decorator (TypeScript). - * @name MapField.d - * @function - * @param {number} fieldId Field id - * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type - * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type - * @returns {FieldDecorator} Decorator function - * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } - */ -MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { - - // submessage value: decorate the submessage and use its name as the type - if (typeof fieldValueType === "function") - fieldValueType = util.decorateType(fieldValueType).name; - - // enum reference value: create a reflected copy of the enum and keep reuseing it - else if (fieldValueType && typeof fieldValueType === "object") - fieldValueType = util.decorateEnum(fieldValueType).name; - - return function mapFieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor) - .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); - }; -}; - - -/***/ }), - -/***/ 68027: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Message; - -var util = __nccwpck_require__(71241); - -/** - * Constructs a new message instance. - * @classdesc Abstract runtime message. - * @constructor - * @param {Properties} [properties] Properties to set - * @template T extends object = object - */ -function Message(properties) { - // not used internally - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - this[keys[i]] = properties[keys[i]]; -} - -/** - * Reference to the reflected type. - * @name Message.$type - * @type {Type} - * @readonly - */ - -/** - * Reference to the reflected type. - * @name Message#$type - * @type {Type} - * @readonly - */ - -/*eslint-disable valid-jsdoc*/ - -/** - * Creates a new message of this type using the specified properties. - * @param {Object.} [properties] Properties to set - * @returns {Message} Message instance - * @template T extends Message - * @this Constructor - */ -Message.create = function create(properties) { - return this.$type.create(properties); -}; - -/** - * Encodes a message of this type. - * @param {T|Object.} message Message to encode - * @param {Writer} [writer] Writer to use - * @returns {Writer} Writer - * @template T extends Message - * @this Constructor - */ -Message.encode = function encode(message, writer) { - return this.$type.encode(message, writer); -}; - -/** - * Encodes a message of this type preceeded by its length as a varint. - * @param {T|Object.} message Message to encode - * @param {Writer} [writer] Writer to use - * @returns {Writer} Writer - * @template T extends Message - * @this Constructor - */ -Message.encodeDelimited = function encodeDelimited(message, writer) { - return this.$type.encodeDelimited(message, writer); -}; - -/** - * Decodes a message of this type. - * @name Message.decode - * @function - * @param {Reader|Uint8Array} reader Reader or buffer to decode - * @returns {T} Decoded message - * @template T extends Message - * @this Constructor - */ -Message.decode = function decode(reader) { - return this.$type.decode(reader); -}; - -/** - * Decodes a message of this type preceeded by its length as a varint. - * @name Message.decodeDelimited - * @function - * @param {Reader|Uint8Array} reader Reader or buffer to decode - * @returns {T} Decoded message - * @template T extends Message - * @this Constructor - */ -Message.decodeDelimited = function decodeDelimited(reader) { - return this.$type.decodeDelimited(reader); -}; - -/** - * Verifies a message of this type. - * @name Message.verify - * @function - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ -Message.verify = function verify(message) { - return this.$type.verify(message); -}; - -/** - * Creates a new message of this type from a plain object. Also converts values to their respective internal types. - * @param {Object.} object Plain object - * @returns {T} Message instance - * @template T extends Message - * @this Constructor - */ -Message.fromObject = function fromObject(object) { - return this.$type.fromObject(object); -}; - -/** - * Creates a plain object from a message of this type. Also converts values to other types if specified. - * @param {T} message Message instance - * @param {IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - * @template T extends Message - * @this Constructor - */ -Message.toObject = function toObject(message, options) { - return this.$type.toObject(message, options); -}; - -/** - * Converts this message to JSON. - * @returns {Object.} JSON object - */ -Message.prototype.toJSON = function toJSON() { - return this.$type.toObject(this, util.toJSONOptions); -}; - -/*eslint-enable valid-jsdoc*/ - -/***/ }), - -/***/ 57771: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Method; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; - -var util = __nccwpck_require__(47174); - -/** - * Constructs a new service method instance. - * @classdesc Reflected service method. - * @extends ReflectionObject - * @constructor - * @param {string} name Method name - * @param {string|undefined} type Method type, usually `"rpc"` - * @param {string} requestType Request message type - * @param {string} responseType Response message type - * @param {boolean|Object.} [requestStream] Whether the request is streamed - * @param {boolean|Object.} [responseStream] Whether the response is streamed - * @param {Object.} [options] Declared options - * @param {string} [comment] The comment for this method - * @param {Object.} [parsedOptions] Declared options, properly parsed into an object - */ -function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { - - /* istanbul ignore next */ - if (util.isObject(requestStream)) { - options = requestStream; - requestStream = responseStream = undefined; - } else if (util.isObject(responseStream)) { - options = responseStream; - responseStream = undefined; - } - - /* istanbul ignore if */ - if (!(type === undefined || util.isString(type))) - throw TypeError("type must be a string"); - - /* istanbul ignore if */ - if (!util.isString(requestType)) - throw TypeError("requestType must be a string"); - - /* istanbul ignore if */ - if (!util.isString(responseType)) - throw TypeError("responseType must be a string"); - - ReflectionObject.call(this, name, options); - - /** - * Method type. - * @type {string} - */ - this.type = type || "rpc"; // toJSON - - /** - * Request type. - * @type {string} - */ - this.requestType = requestType; // toJSON, marker - - /** - * Whether requests are streamed or not. - * @type {boolean|undefined} - */ - this.requestStream = requestStream ? true : undefined; // toJSON - - /** - * Response type. - * @type {string} - */ - this.responseType = responseType; // toJSON - - /** - * Whether responses are streamed or not. - * @type {boolean|undefined} - */ - this.responseStream = responseStream ? true : undefined; // toJSON - - /** - * Resolved request type. - * @type {Type|null} - */ - this.resolvedRequestType = null; - - /** - * Resolved response type. - * @type {Type|null} - */ - this.resolvedResponseType = null; - - /** - * Comment for this method - * @type {string|null} - */ - this.comment = comment; - - /** - * Options properly parsed into an object - */ - this.parsedOptions = parsedOptions; -} - -/** - * Method descriptor. - * @interface IMethod - * @property {string} [type="rpc"] Method type - * @property {string} requestType Request type - * @property {string} responseType Response type - * @property {boolean} [requestStream=false] Whether requests are streamed - * @property {boolean} [responseStream=false] Whether responses are streamed - * @property {Object.} [options] Method options - * @property {string} comment Method comments - * @property {Object.} [parsedOptions] Method options properly parsed into an object - */ - -/** - * Constructs a method from a method descriptor. - * @param {string} name Method name - * @param {IMethod} json Method descriptor - * @returns {Method} Created method - * @throws {TypeError} If arguments are invalid - */ -Method.fromJSON = function fromJSON(name, json) { - return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); -}; - -/** - * Converts this method to a method descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IMethod} Method descriptor - */ -Method.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, - "requestType" , this.requestType, - "requestStream" , this.requestStream, - "responseType" , this.responseType, - "responseStream" , this.responseStream, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined, - "parsedOptions" , this.parsedOptions, - ]); -}; - -/** - * @override - */ -Method.prototype.resolve = function resolve() { - - /* istanbul ignore if */ - if (this.resolved) - return this; - - this.resolvedRequestType = this.parent.lookupType(this.requestType); - this.resolvedResponseType = this.parent.lookupType(this.responseType); - - return ReflectionObject.prototype.resolve.call(this); -}; - - -/***/ }), - -/***/ 76189: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Namespace; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; - -var Field = __nccwpck_require__(48213), - util = __nccwpck_require__(47174), - OneOf = __nccwpck_require__(44408); - -var Type, // cyclic - Service, - Enum; - -/** - * Constructs a new namespace instance. - * @name Namespace - * @classdesc Reflected namespace. - * @extends NamespaceBase - * @constructor - * @param {string} name Namespace name - * @param {Object.} [options] Declared options - */ - -/** - * Constructs a namespace from JSON. - * @memberof Namespace - * @function - * @param {string} name Namespace name - * @param {Object.} json JSON object - * @returns {Namespace} Created namespace - * @throws {TypeError} If arguments are invalid - */ -Namespace.fromJSON = function fromJSON(name, json) { - return new Namespace(name, json.options).addJSON(json.nested); -}; - -/** - * Converts an array of reflection objects to JSON. - * @memberof Namespace - * @param {ReflectionObject[]} array Object array - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {Object.|undefined} JSON object or `undefined` when array is empty - */ -function arrayToJSON(array, toJSONOptions) { - if (!(array && array.length)) - return undefined; - var obj = {}; - for (var i = 0; i < array.length; ++i) - obj[array[i].name] = array[i].toJSON(toJSONOptions); - return obj; -} - -Namespace.arrayToJSON = arrayToJSON; - -/** - * Tests if the specified id is reserved. - * @param {Array.|undefined} reserved Array of reserved ranges and names - * @param {number} id Id to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Namespace.isReservedId = function isReservedId(reserved, id) { - if (reserved) - for (var i = 0; i < reserved.length; ++i) - if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) - return true; - return false; -}; - -/** - * Tests if the specified name is reserved. - * @param {Array.|undefined} reserved Array of reserved ranges and names - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Namespace.isReservedName = function isReservedName(reserved, name) { - if (reserved) - for (var i = 0; i < reserved.length; ++i) - if (reserved[i] === name) - return true; - return false; -}; - -/** - * Not an actual constructor. Use {@link Namespace} instead. - * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. - * @exports NamespaceBase - * @extends ReflectionObject - * @abstract - * @constructor - * @param {string} name Namespace name - * @param {Object.} [options] Declared options - * @see {@link Namespace} - */ -function Namespace(name, options) { - ReflectionObject.call(this, name, options); - - /** - * Nested objects by name. - * @type {Object.|undefined} - */ - this.nested = undefined; // toJSON - - /** - * Cached nested objects as an array. - * @type {ReflectionObject[]|null} - * @private - */ - this._nestedArray = null; - - /** - * Cache lookup calls for any objects contains anywhere under this namespace. - * This drastically speeds up resolve for large cross-linked protos where the same - * types are looked up repeatedly. - * @type {Object.} - * @private - */ - this._lookupCache = {}; - - /** - * Whether or not objects contained in this namespace need feature resolution. - * @type {boolean} - * @protected - */ - this._needsRecursiveFeatureResolution = true; - - /** - * Whether or not objects contained in this namespace need a resolve. - * @type {boolean} - * @protected - */ - this._needsRecursiveResolve = true; -} - -function clearCache(namespace) { - namespace._nestedArray = null; - namespace._lookupCache = {}; - - // Also clear parent caches, since they include nested lookups. - var parent = namespace; - while(parent = parent.parent) { - parent._lookupCache = {}; - } - return namespace; -} - -/** - * Nested objects of this namespace as an array for iteration. - * @name NamespaceBase#nestedArray - * @type {ReflectionObject[]} - * @readonly - */ -Object.defineProperty(Namespace.prototype, "nestedArray", { - get: function() { - return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); - } -}); - -/** - * Namespace descriptor. - * @interface INamespace - * @property {Object.} [options] Namespace options - * @property {Object.} [nested] Nested object descriptors - */ - -/** - * Any extension field descriptor. - * @typedef AnyExtensionField - * @type {IExtensionField|IExtensionMapField} - */ - -/** - * Any nested object descriptor. - * @typedef AnyNestedObject - * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} - */ - -/** - * Converts this namespace to a namespace descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {INamespace} Namespace descriptor - */ -Namespace.prototype.toJSON = function toJSON(toJSONOptions) { - return util.toObject([ - "options" , this.options, - "nested" , arrayToJSON(this.nestedArray, toJSONOptions) - ]); -}; - -/** - * Adds nested objects to this namespace from nested object descriptors. - * @param {Object.} nestedJson Any nested object descriptors - * @returns {Namespace} `this` - */ -Namespace.prototype.addJSON = function addJSON(nestedJson) { - var ns = this; - /* istanbul ignore else */ - if (nestedJson) { - for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { - nested = nestedJson[names[i]]; - ns.add( // most to least likely - ( nested.fields !== undefined - ? Type.fromJSON - : nested.values !== undefined - ? Enum.fromJSON - : nested.methods !== undefined - ? Service.fromJSON - : nested.id !== undefined - ? Field.fromJSON - : Namespace.fromJSON )(names[i], nested) - ); - } - } - return this; -}; - -/** - * Gets the nested object of the specified name. - * @param {string} name Nested object name - * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist - */ -Namespace.prototype.get = function get(name) { - return this.nested && this.nested[name] - || null; -}; - -/** - * Gets the values of the nested {@link Enum|enum} of the specified name. - * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. - * @param {string} name Nested enum name - * @returns {Object.} Enum values - * @throws {Error} If there is no such enum - */ -Namespace.prototype.getEnum = function getEnum(name) { - if (this.nested && this.nested[name] instanceof Enum) - return this.nested[name].values; - throw Error("no such enum: " + name); -}; - -/** - * Adds a nested object to this namespace. - * @param {ReflectionObject} object Nested object to add - * @returns {Namespace} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If there is already a nested object with this name - */ -Namespace.prototype.add = function add(object) { - - if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) - throw TypeError("object must be a valid nested object"); - - if (!this.nested) - this.nested = {}; - else { - var prev = this.get(object.name); - if (prev) { - if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { - // replace plain namespace but keep existing nested elements and options - var nested = prev.nestedArray; - for (var i = 0; i < nested.length; ++i) - object.add(nested[i]); - this.remove(prev); - if (!this.nested) - this.nested = {}; - object.setOptions(prev.options, true); - - } else - throw Error("duplicate name '" + object.name + "' in " + this); - } - } - this.nested[object.name] = object; - - if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { - // This is a package or a root namespace. - if (!object._edition) { - // Make sure that some edition is set if it hasn't already been specified. - object._edition = object._defaultEdition; - } - } - - this._needsRecursiveFeatureResolution = true; - this._needsRecursiveResolve = true; - - // Also clear parent caches, since they need to recurse down. - var parent = this; - while(parent = parent.parent) { - parent._needsRecursiveFeatureResolution = true; - parent._needsRecursiveResolve = true; - } - - object.onAdd(this); - return clearCache(this); -}; - -/** - * Removes a nested object from this namespace. - * @param {ReflectionObject} object Nested object to remove - * @returns {Namespace} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If `object` is not a member of this namespace - */ -Namespace.prototype.remove = function remove(object) { - - if (!(object instanceof ReflectionObject)) - throw TypeError("object must be a ReflectionObject"); - if (object.parent !== this) - throw Error(object + " is not a member of " + this); - - delete this.nested[object.name]; - if (!Object.keys(this.nested).length) - this.nested = undefined; - - object.onRemove(this); - return clearCache(this); -}; - -/** - * Defines additial namespaces within this one if not yet existing. - * @param {string|string[]} path Path to create - * @param {*} [json] Nested types to create from JSON - * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty - */ -Namespace.prototype.define = function define(path, json) { - - if (util.isString(path)) - path = path.split("."); - else if (!Array.isArray(path)) - throw TypeError("illegal path"); - if (path && path.length && path[0] === "") - throw Error("path must be relative"); - - var ptr = this; - while (path.length > 0) { - var part = path.shift(); - if (ptr.nested && ptr.nested[part]) { - ptr = ptr.nested[part]; - if (!(ptr instanceof Namespace)) - throw Error("path conflicts with non-namespace objects"); - } else - ptr.add(ptr = new Namespace(part)); - } - if (json) - ptr.addJSON(json); - return ptr; -}; - -/** - * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. - * @returns {Namespace} `this` - */ -Namespace.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - this._resolveFeaturesRecursive(this._edition); - - var nested = this.nestedArray, i = 0; - this.resolve(); - while (i < nested.length) - if (nested[i] instanceof Namespace) - nested[i++].resolveAll(); - else - nested[i++].resolve(); - this._needsRecursiveResolve = false; - return this; -}; - -/** - * @override - */ -Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - this._needsRecursiveFeatureResolution = false; - - edition = this._edition || edition; - - ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); - this.nestedArray.forEach(nested => { - nested._resolveFeaturesRecursive(edition); - }); - return this; -}; - -/** - * Recursively looks up the reflection object matching the specified path in the scope of this namespace. - * @param {string|string[]} path Path to look up - * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. - * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked - * @returns {ReflectionObject|null} Looked up object or `null` if none could be found - */ -Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { - /* istanbul ignore next */ - if (typeof filterTypes === "boolean") { - parentAlreadyChecked = filterTypes; - filterTypes = undefined; - } else if (filterTypes && !Array.isArray(filterTypes)) - filterTypes = [ filterTypes ]; - - if (util.isString(path) && path.length) { - if (path === ".") - return this.root; - path = path.split("."); - } else if (!path.length) - return this; - - var flatPath = path.join("."); - - // Start at root if path is absolute - if (path[0] === "") - return this.root.lookup(path.slice(1), filterTypes); - - // Early bailout for objects with matching absolute paths - var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - - // Do a regular lookup at this namespace and below - found = this._lookupImpl(path, flatPath); - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - - if (parentAlreadyChecked) - return null; - - // If there hasn't been a match, walk up the tree and look more broadly - var current = this; - while (current.parent) { - found = current.parent._lookupImpl(path, flatPath); - if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { - return found; - } - current = current.parent; - } - return null; -}; - -/** - * Internal helper for lookup that handles searching just at this namespace and below along with caching. - * @param {string[]} path Path to look up - * @param {string} flatPath Flattened version of the path to use as a cache key - * @returns {ReflectionObject|null} Looked up object or `null` if none could be found - * @private - */ -Namespace.prototype._lookupImpl = function lookup(path, flatPath) { - if(Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { - return this._lookupCache[flatPath]; - } - - // Test if the first part matches any nested object, and if so, traverse if path contains more - var found = this.get(path[0]); - var exact = null; - if (found) { - if (path.length === 1) { - exact = found; - } else if (found instanceof Namespace) { - path = path.slice(1); - exact = found._lookupImpl(path, path.join(".")); - } - - // Otherwise try each nested namespace - } else { - for (var i = 0; i < this.nestedArray.length; ++i) - if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) - exact = found; - } - - // Set this even when null, so that when we walk up the tree we can quickly bail on repeated checks back down. - this._lookupCache[flatPath] = exact; - return exact; -}; - -/** - * Looks up the reflection object at the specified path, relative to this namespace. - * @name NamespaceBase#lookup - * @function - * @param {string|string[]} path Path to look up - * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked - * @returns {ReflectionObject|null} Looked up object or `null` if none could be found - * @variation 2 - */ -// lookup(path: string, [parentAlreadyChecked: boolean]) - -/** - * Looks up the {@link Type|type} at the specified path, relative to this namespace. - * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. - * @param {string|string[]} path Path to look up - * @returns {Type} Looked up type - * @throws {Error} If `path` does not point to a type - */ -Namespace.prototype.lookupType = function lookupType(path) { - var found = this.lookup(path, [ Type ]); - if (!found) - throw Error("no such type: " + path); - return found; -}; - -/** - * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. - * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. - * @param {string|string[]} path Path to look up - * @returns {Enum} Looked up enum - * @throws {Error} If `path` does not point to an enum - */ -Namespace.prototype.lookupEnum = function lookupEnum(path) { - var found = this.lookup(path, [ Enum ]); - if (!found) - throw Error("no such Enum '" + path + "' in " + this); - return found; -}; - -/** - * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. - * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. - * @param {string|string[]} path Path to look up - * @returns {Type} Looked up type or enum - * @throws {Error} If `path` does not point to a type or enum - */ -Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { - var found = this.lookup(path, [ Type, Enum ]); - if (!found) - throw Error("no such Type or Enum '" + path + "' in " + this); - return found; -}; - -/** - * Looks up the {@link Service|service} at the specified path, relative to this namespace. - * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. - * @param {string|string[]} path Path to look up - * @returns {Service} Looked up service - * @throws {Error} If `path` does not point to a service - */ -Namespace.prototype.lookupService = function lookupService(path) { - var found = this.lookup(path, [ Service ]); - if (!found) - throw Error("no such Service '" + path + "' in " + this); - return found; -}; - -// Sets up cyclic dependencies (called in index-light) -Namespace._configure = function(Type_, Service_, Enum_) { - Type = Type_; - Service = Service_; - Enum = Enum_; -}; - - -/***/ }), - -/***/ 83575: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = ReflectionObject; - -ReflectionObject.className = "ReflectionObject"; - -const OneOf = __nccwpck_require__(44408); -var util = __nccwpck_require__(47174); - -var Root; // cyclic - -/* eslint-disable no-warning-comments */ -// TODO: Replace with embedded proto. -var editions2023Defaults = {enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; -var proto2Defaults = {enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE"}; -var proto3Defaults = {enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY"}; - -/** - * Constructs a new reflection object instance. - * @classdesc Base class of all reflection objects. - * @constructor - * @param {string} name Object name - * @param {Object.} [options] Declared options - * @abstract - */ -function ReflectionObject(name, options) { - - if (!util.isString(name)) - throw TypeError("name must be a string"); - - if (options && !util.isObject(options)) - throw TypeError("options must be an object"); - - /** - * Options. - * @type {Object.|undefined} - */ - this.options = options; // toJSON - - /** - * Parsed Options. - * @type {Array.>|undefined} - */ - this.parsedOptions = null; - - /** - * Unique name within its namespace. - * @type {string} - */ - this.name = name; - - /** - * The edition specified for this object. Only relevant for top-level objects. - * @type {string} - * @private - */ - this._edition = null; - - /** - * The default edition to use for this object if none is specified. For legacy reasons, - * this is proto2 except in the JSON parsing case where it was proto3. - * @type {string} - * @private - */ - this._defaultEdition = "proto2"; - - /** - * Resolved Features. - * @type {object} - * @private - */ - this._features = {}; - - /** - * Whether or not features have been resolved. - * @type {boolean} - * @private - */ - this._featuresResolved = false; - - /** - * Parent namespace. - * @type {Namespace|null} - */ - this.parent = null; - - /** - * Whether already resolved or not. - * @type {boolean} - */ - this.resolved = false; - - /** - * Comment text, if any. - * @type {string|null} - */ - this.comment = null; - - /** - * Defining file name. - * @type {string|null} - */ - this.filename = null; -} - -Object.defineProperties(ReflectionObject.prototype, { - - /** - * Reference to the root namespace. - * @name ReflectionObject#root - * @type {Root} - * @readonly - */ - root: { - get: function() { - var ptr = this; - while (ptr.parent !== null) - ptr = ptr.parent; - return ptr; - } - }, - - /** - * Full name including leading dot. - * @name ReflectionObject#fullName - * @type {string} - * @readonly - */ - fullName: { - get: function() { - var path = [ this.name ], - ptr = this.parent; - while (ptr) { - path.unshift(ptr.name); - ptr = ptr.parent; - } - return path.join("."); - } - } -}); - -/** - * Converts this reflection object to its descriptor representation. - * @returns {Object.} Descriptor - * @abstract - */ -ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { - throw Error(); // not implemented, shouldn't happen -}; - -/** - * Called when this object is added to a parent. - * @param {ReflectionObject} parent Parent added to - * @returns {undefined} - */ -ReflectionObject.prototype.onAdd = function onAdd(parent) { - if (this.parent && this.parent !== parent) - this.parent.remove(this); - this.parent = parent; - this.resolved = false; - var root = parent.root; - if (root instanceof Root) - root._handleAdd(this); -}; - -/** - * Called when this object is removed from a parent. - * @param {ReflectionObject} parent Parent removed from - * @returns {undefined} - */ -ReflectionObject.prototype.onRemove = function onRemove(parent) { - var root = parent.root; - if (root instanceof Root) - root._handleRemove(this); - this.parent = null; - this.resolved = false; -}; - -/** - * Resolves this objects type references. - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.resolve = function resolve() { - if (this.resolved) - return this; - if (this.root instanceof Root) - this.resolved = true; // only if part of a root - return this; -}; - -/** - * Resolves this objects editions features. - * @param {string} edition The edition we're currently resolving for. - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - return this._resolveFeatures(this._edition || edition); -}; - -/** - * Resolves child features from parent features - * @param {string} edition The edition we're currently resolving for. - * @returns {undefined} - */ -ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { - if (this._featuresResolved) { - return; - } - - var defaults = {}; - - /* istanbul ignore if */ - if (!edition) { - throw new Error("Unknown edition for " + this.fullName); - } - - var protoFeatures = Object.assign(this.options ? Object.assign({}, this.options.features) : {}, - this._inferLegacyProtoFeatures(edition)); - - if (this._edition) { - // For a namespace marked with a specific edition, reset defaults. - /* istanbul ignore else */ - if (edition === "proto2") { - defaults = Object.assign({}, proto2Defaults); - } else if (edition === "proto3") { - defaults = Object.assign({}, proto3Defaults); - } else if (edition === "2023") { - defaults = Object.assign({}, editions2023Defaults); - } else { - throw new Error("Unknown edition: " + edition); - } - this._features = Object.assign(defaults, protoFeatures || {}); - this._featuresResolved = true; - return; - } - - // fields in Oneofs aren't actually children of them, so we have to - // special-case it - /* istanbul ignore else */ - if (this.partOf instanceof OneOf) { - var lexicalParentFeaturesCopy = Object.assign({}, this.partOf._features); - this._features = Object.assign(lexicalParentFeaturesCopy, protoFeatures || {}); - } else if (this.declaringField) { - // Skip feature resolution of sister fields. - } else if (this.parent) { - var parentFeaturesCopy = Object.assign({}, this.parent._features); - this._features = Object.assign(parentFeaturesCopy, protoFeatures || {}); - } else { - throw new Error("Unable to find a parent for " + this.fullName); - } - if (this.extensionField) { - // Sister fields should have the same features as their extensions. - this.extensionField._features = this._features; - } - this._featuresResolved = true; -}; - -/** - * Infers features from legacy syntax that may have been specified differently. - * in older editions. - * @param {string|undefined} edition The edition this proto is on, or undefined if pre-editions - * @returns {object} The feature values to override - */ -ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(/*edition*/) { - return {}; -}; - -/** - * Gets an option value. - * @param {string} name Option name - * @returns {*} Option value or `undefined` if not set - */ -ReflectionObject.prototype.getOption = function getOption(name) { - if (this.options) - return this.options[name]; - return undefined; -}; - -/** - * Sets an option. - * @param {string} name Option name - * @param {*} value Option value - * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { - if (!this.options) - this.options = {}; - if (/^features\./.test(name)) { - util.setProperty(this.options, name, value, ifNotSet); - } else if (!ifNotSet || this.options[name] === undefined) { - if (this.getOption(name) !== value) this.resolved = false; - this.options[name] = value; - } - - return this; -}; - -/** - * Sets a parsed option. - * @param {string} name parsed Option name - * @param {*} value Option value - * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { - if (!this.parsedOptions) { - this.parsedOptions = []; - } - var parsedOptions = this.parsedOptions; - if (propName) { - // If setting a sub property of an option then try to merge it - // with an existing option - var opt = parsedOptions.find(function (opt) { - return Object.prototype.hasOwnProperty.call(opt, name); - }); - if (opt) { - // If we found an existing option - just merge the property value - // (If it's a feature, will just write over) - var newValue = opt[name]; - util.setProperty(newValue, propName, value); - } else { - // otherwise, create a new option, set its property and add it to the list - opt = {}; - opt[name] = util.setProperty({}, propName, value); - parsedOptions.push(opt); - } - } else { - // Always create a new option when setting the value of the option itself - var newOpt = {}; - newOpt[name] = value; - parsedOptions.push(newOpt); - } - - return this; -}; - -/** - * Sets multiple options. - * @param {Object.} options Options to set - * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set - * @returns {ReflectionObject} `this` - */ -ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { - if (options) - for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) - this.setOption(keys[i], options[keys[i]], ifNotSet); - return this; -}; - -/** - * Converts this instance to its string representation. - * @returns {string} Class name[, space, full name] - */ -ReflectionObject.prototype.toString = function toString() { - var className = this.constructor.className, - fullName = this.fullName; - if (fullName.length) - return className + " " + fullName; - return className; -}; - -/** - * Converts the edition this object is pinned to for JSON format. - * @returns {string|undefined} The edition string for JSON representation - */ -ReflectionObject.prototype._editionToJSON = function _editionToJSON() { - if (!this._edition || this._edition === "proto3") { - // Avoid emitting proto3 since we need to default to it for backwards - // compatibility anyway. - return undefined; - } - return this._edition; -}; - -// Sets up cyclic dependencies (called in index-light) -ReflectionObject._configure = function(Root_) { - Root = Root_; -}; - - -/***/ }), - -/***/ 44408: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = OneOf; - -// extends ReflectionObject -var ReflectionObject = __nccwpck_require__(83575); -((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; - -var Field = __nccwpck_require__(48213), - util = __nccwpck_require__(47174); - -/** - * Constructs a new oneof instance. - * @classdesc Reflected oneof. - * @extends ReflectionObject - * @constructor - * @param {string} name Oneof name - * @param {string[]|Object.} [fieldNames] Field names - * @param {Object.} [options] Declared options - * @param {string} [comment] Comment associated with this field - */ -function OneOf(name, fieldNames, options, comment) { - if (!Array.isArray(fieldNames)) { - options = fieldNames; - fieldNames = undefined; - } - ReflectionObject.call(this, name, options); - - /* istanbul ignore if */ - if (!(fieldNames === undefined || Array.isArray(fieldNames))) - throw TypeError("fieldNames must be an Array"); - - /** - * Field names that belong to this oneof. - * @type {string[]} - */ - this.oneof = fieldNames || []; // toJSON, marker - - /** - * Fields that belong to this oneof as an array for iteration. - * @type {Field[]} - * @readonly - */ - this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent - - /** - * Comment for this field. - * @type {string|null} - */ - this.comment = comment; -} - -/** - * Oneof descriptor. - * @interface IOneOf - * @property {Array.} oneof Oneof field names - * @property {Object.} [options] Oneof options - */ - -/** - * Constructs a oneof from a oneof descriptor. - * @param {string} name Oneof name - * @param {IOneOf} json Oneof descriptor - * @returns {OneOf} Created oneof - * @throws {TypeError} If arguments are invalid - */ -OneOf.fromJSON = function fromJSON(name, json) { - return new OneOf(name, json.oneof, json.options, json.comment); -}; - -/** - * Converts this oneof to a oneof descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IOneOf} Oneof descriptor - */ -OneOf.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "options" , this.options, - "oneof" , this.oneof, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * Adds the fields of the specified oneof to the parent if not already done so. - * @param {OneOf} oneof The oneof - * @returns {undefined} - * @inner - * @ignore - */ -function addFieldsToParent(oneof) { - if (oneof.parent) - for (var i = 0; i < oneof.fieldsArray.length; ++i) - if (!oneof.fieldsArray[i].parent) - oneof.parent.add(oneof.fieldsArray[i]); -} - -/** - * Adds a field to this oneof and removes it from its current parent, if any. - * @param {Field} field Field to add - * @returns {OneOf} `this` - */ -OneOf.prototype.add = function add(field) { - - /* istanbul ignore if */ - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); - - if (field.parent && field.parent !== this.parent) - field.parent.remove(field); - this.oneof.push(field.name); - this.fieldsArray.push(field); - field.partOf = this; // field.parent remains null - addFieldsToParent(this); - return this; -}; - -/** - * Removes a field from this oneof and puts it back to the oneof's parent. - * @param {Field} field Field to remove - * @returns {OneOf} `this` - */ -OneOf.prototype.remove = function remove(field) { - - /* istanbul ignore if */ - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); - - var index = this.fieldsArray.indexOf(field); - - /* istanbul ignore if */ - if (index < 0) - throw Error(field + " is not a member of " + this); - - this.fieldsArray.splice(index, 1); - index = this.oneof.indexOf(field.name); - - /* istanbul ignore else */ - if (index > -1) // theoretical - this.oneof.splice(index, 1); - - field.partOf = null; - return this; -}; - -/** - * @override - */ -OneOf.prototype.onAdd = function onAdd(parent) { - ReflectionObject.prototype.onAdd.call(this, parent); - var self = this; - // Collect present fields - for (var i = 0; i < this.oneof.length; ++i) { - var field = parent.get(this.oneof[i]); - if (field && !field.partOf) { - field.partOf = self; - self.fieldsArray.push(field); - } - } - // Add not yet present fields - addFieldsToParent(this); -}; - -/** - * @override - */ -OneOf.prototype.onRemove = function onRemove(parent) { - for (var i = 0, field; i < this.fieldsArray.length; ++i) - if ((field = this.fieldsArray[i]).parent) - field.parent.remove(field); - ReflectionObject.prototype.onRemove.call(this, parent); -}; - -/** - * Determines whether this field corresponds to a synthetic oneof created for - * a proto3 optional field. No behavioral logic should depend on this, but it - * can be relevant for reflection. - * @name OneOf#isProto3Optional - * @type {boolean} - * @readonly - */ -Object.defineProperty(OneOf.prototype, "isProto3Optional", { - get: function() { - if (this.fieldsArray == null || this.fieldsArray.length !== 1) { - return false; - } - - var field = this.fieldsArray[0]; - return field.options != null && field.options["proto3_optional"] === true; - } -}); - -/** - * Decorator function as returned by {@link OneOf.d} (TypeScript). - * @typedef OneOfDecorator - * @type {function} - * @param {Object} prototype Target prototype - * @param {string} oneofName OneOf name - * @returns {undefined} - */ - -/** - * OneOf decorator (TypeScript). - * @function - * @param {...string} fieldNames Field names - * @returns {OneOfDecorator} Decorator function - * @template T extends string - */ -OneOf.d = function decorateOneOf() { - var fieldNames = new Array(arguments.length), - index = 0; - while (index < arguments.length) - fieldNames[index] = arguments[index++]; - return function oneOfDecorator(prototype, oneofName) { - util.decorateType(prototype.constructor) - .add(new OneOf(oneofName, fieldNames)); - Object.defineProperty(prototype, oneofName, { - get: util.oneOfGetter(fieldNames), - set: util.oneOfSetter(fieldNames) - }); - }; -}; - - -/***/ }), - -/***/ 32137: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = parse; - -parse.filename = null; -parse.defaults = { keepCase: false }; - -var tokenize = __nccwpck_require__(61157), - Root = __nccwpck_require__(32614), - Type = __nccwpck_require__(38520), - Field = __nccwpck_require__(48213), - MapField = __nccwpck_require__(67777), - OneOf = __nccwpck_require__(44408), - Enum = __nccwpck_require__(17732), - Service = __nccwpck_require__(6178), - Method = __nccwpck_require__(57771), - ReflectionObject = __nccwpck_require__(83575), - types = __nccwpck_require__(6581), - util = __nccwpck_require__(47174); - -var base10Re = /^[1-9][0-9]*$/, - base10NegRe = /^-?[1-9][0-9]*$/, - base16Re = /^0[x][0-9a-fA-F]+$/, - base16NegRe = /^-?0[x][0-9a-fA-F]+$/, - base8Re = /^0[0-7]+$/, - base8NegRe = /^-?0[0-7]+$/, - numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, - nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, - typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/; - -/** - * Result object returned from {@link parse}. - * @interface IParserResult - * @property {string|undefined} package Package name, if declared - * @property {string[]|undefined} imports Imports, if any - * @property {string[]|undefined} weakImports Weak imports, if any - * @property {Root} root Populated root instance - */ - -/** - * Options modifying the behavior of {@link parse}. - * @interface IParseOptions - * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case - * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments. - * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist. - */ - -/** - * Options modifying the behavior of JSON serialization. - * @interface IToJSONOptions - * @property {boolean} [keepComments=false] Serializes comments. - */ - -/** - * Parses the given .proto source and returns an object with the parsed contents. - * @param {string} source Source contents - * @param {Root} root Root to populate - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {IParserResult} Parser result - * @property {string} filename=null Currently processing file name for error reporting, if known - * @property {IParseOptions} defaults Default {@link IParseOptions} - */ -function parse(source, root, options) { - /* eslint-disable callback-return */ - if (!(root instanceof Root)) { - options = root; - root = new Root(); - } - if (!options) - options = parse.defaults; - - var preferTrailingComment = options.preferTrailingComment || false; - var tn = tokenize(source, options.alternateCommentMode || false), - next = tn.next, - push = tn.push, - peek = tn.peek, - skip = tn.skip, - cmnt = tn.cmnt; - - var head = true, - pkg, - imports, - weakImports, - edition = "proto2"; - - var ptr = root; - - var topLevelObjects = []; - var topLevelOptions = {}; - - var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; - - function resolveFileFeatures() { - topLevelObjects.forEach(obj => { - obj._edition = edition; - Object.keys(topLevelOptions).forEach(opt => { - if (obj.getOption(opt) !== undefined) return; - obj.setOption(opt, topLevelOptions[opt], true); - }); - }); - } - - /* istanbul ignore next */ - function illegal(token, name, insideTryCatch) { - var filename = parse.filename; - if (!insideTryCatch) - parse.filename = null; - return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); - } - - function readString() { - var values = [], - token; - do { - /* istanbul ignore if */ - if ((token = next()) !== "\"" && token !== "'") - throw illegal(token); - - values.push(next()); - skip(token); - token = peek(); - } while (token === "\"" || token === "'"); - return values.join(""); - } - - function readValue(acceptTypeRef) { - var token = next(); - switch (token) { - case "'": - case "\"": - push(token); - return readString(); - case "true": case "TRUE": - return true; - case "false": case "FALSE": - return false; - } - try { - return parseNumber(token, /* insideTryCatch */ true); - } catch (e) { - /* istanbul ignore else */ - if (acceptTypeRef && typeRefRe.test(token)) - return token; - - /* istanbul ignore next */ - throw illegal(token, "value"); - } - } - - function readRanges(target, acceptStrings) { - var token, start; - do { - if (acceptStrings && ((token = peek()) === "\"" || token === "'")) { - var str = readString(); - target.push(str); - if (edition >= 2023) { - throw illegal(str, "id"); - } - } else { - try { - target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); - } catch (err) { - if (acceptStrings && typeRefRe.test(token) && edition >= 2023) { - target.push(token); - } else { - throw err; - } - } - } - } while (skip(",", true)); - var dummy = {options: undefined}; - dummy.setOption = function(name, value) { - if (this.options === undefined) this.options = {}; - this.options[name] = value; - }; - ifBlock( - dummy, - function parseRange_block(token) { - /* istanbul ignore else */ - if (token === "option") { - parseOption(dummy, token); // skip - skip(";"); - } else - throw illegal(token); - }, - function parseRange_line() { - parseInlineOptions(dummy); // skip - }); - } - - function parseNumber(token, insideTryCatch) { - var sign = 1; - if (token.charAt(0) === "-") { - sign = -1; - token = token.substring(1); - } - switch (token) { - case "inf": case "INF": case "Inf": - return sign * Infinity; - case "nan": case "NAN": case "Nan": case "NaN": - return NaN; - case "0": - return 0; - } - if (base10Re.test(token)) - return sign * parseInt(token, 10); - if (base16Re.test(token)) - return sign * parseInt(token, 16); - if (base8Re.test(token)) - return sign * parseInt(token, 8); - - /* istanbul ignore else */ - if (numberRe.test(token)) - return sign * parseFloat(token); - - /* istanbul ignore next */ - throw illegal(token, "number", insideTryCatch); - } - - function parseId(token, acceptNegative) { - switch (token) { - case "max": case "MAX": case "Max": - return 536870911; - case "0": - return 0; - } - - /* istanbul ignore if */ - if (!acceptNegative && token.charAt(0) === "-") - throw illegal(token, "id"); - - if (base10NegRe.test(token)) - return parseInt(token, 10); - if (base16NegRe.test(token)) - return parseInt(token, 16); - - /* istanbul ignore else */ - if (base8NegRe.test(token)) - return parseInt(token, 8); - - /* istanbul ignore next */ - throw illegal(token, "id"); - } - - function parsePackage() { - /* istanbul ignore if */ - if (pkg !== undefined) - throw illegal("package"); - - pkg = next(); - - /* istanbul ignore if */ - if (!typeRefRe.test(pkg)) - throw illegal(pkg, "name"); - - ptr = ptr.define(pkg); - - skip(";"); - } - - function parseImport() { - var token = peek(); - var whichImports; - switch (token) { - case "weak": - whichImports = weakImports || (weakImports = []); - next(); - break; - case "public": - next(); - // eslint-disable-next-line no-fallthrough - default: - whichImports = imports || (imports = []); - break; - } - token = readString(); - skip(";"); - whichImports.push(token); - } - - function parseSyntax() { - skip("="); - edition = readString(); - - /* istanbul ignore if */ - if (edition < 2023) - throw illegal(edition, "syntax"); - - skip(";"); - } - - function parseEdition() { - skip("="); - edition = readString(); - const supportedEditions = ["2023"]; - - /* istanbul ignore if */ - if (!supportedEditions.includes(edition)) - throw illegal(edition, "edition"); - - skip(";"); - } - - - function parseCommon(parent, token) { - switch (token) { - - case "option": - parseOption(parent, token); - skip(";"); - return true; - - case "message": - parseType(parent, token); - return true; - - case "enum": - parseEnum(parent, token); - return true; - - case "service": - parseService(parent, token); - return true; - - case "extend": - parseExtension(parent, token); - return true; - } - return false; - } - - function ifBlock(obj, fnIf, fnElse) { - var trailingLine = tn.line; - if (obj) { - if(typeof obj.comment !== "string") { - obj.comment = cmnt(); // try block-type comment - } - obj.filename = parse.filename; - } - if (skip("{", true)) { - var token; - while ((token = next()) !== "}") - fnIf(token); - skip(";", true); - } else { - if (fnElse) - fnElse(); - skip(";"); - if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) - obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment - } - } - - function parseType(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "type name"); - - var type = new Type(token); - ifBlock(type, function parseType_block(token) { - if (parseCommon(type, token)) - return; - - switch (token) { - - case "map": - parseMapField(type, token); - break; - - case "required": - if (edition !== "proto2") - throw illegal(token); - /* eslint-disable no-fallthrough */ - case "repeated": - parseField(type, token); - break; - - case "optional": - /* istanbul ignore if */ - if (edition === "proto3") { - parseField(type, "proto3_optional"); - } else if (edition !== "proto2") { - throw illegal(token); - } else { - parseField(type, "optional"); - } - break; - - case "oneof": - parseOneOf(type, token); - break; - - case "extensions": - readRanges(type.extensions || (type.extensions = [])); - break; - - case "reserved": - readRanges(type.reserved || (type.reserved = []), true); - break; - - default: - /* istanbul ignore if */ - if (edition === "proto2" || !typeRefRe.test(token)) { - throw illegal(token); - } - - push(token); - parseField(type, "optional"); - break; - } - }); - parent.add(type); - if (parent === ptr) { - topLevelObjects.push(type); - } - } - - function parseField(parent, rule, extend) { - var type = next(); - if (type === "group") { - parseGroup(parent, rule); - return; - } - // Type names can consume multiple tokens, in multiple variants: - // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field" - // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field" - // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field" - // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field" - // Keep reading tokens until we get a type name with no period at the end, - // and the next token does not start with a period. - while (type.endsWith(".") || peek().startsWith(".")) { - type += next(); - } - - /* istanbul ignore if */ - if (!typeRefRe.test(type)) - throw illegal(type, "type"); - - var name = next(); - - /* istanbul ignore if */ - - if (!nameRe.test(name)) - throw illegal(name, "name"); - - name = applyCase(name); - skip("="); - - var field = new Field(name, parseId(next()), type, rule, extend); - - ifBlock(field, function parseField_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(field, token); - skip(";"); - } else - throw illegal(token); - - }, function parseField_line() { - parseInlineOptions(field); - }); - - if (rule === "proto3_optional") { - // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior - var oneof = new OneOf("_" + name); - field.setOption("proto3_optional", true); - oneof.add(field); - parent.add(oneof); - } else { - parent.add(field); - } - if (parent === ptr) { - topLevelObjects.push(field); - } - } - - function parseGroup(parent, rule) { - if (edition >= 2023) { - throw illegal("group"); - } - var name = next(); - - /* istanbul ignore if */ - if (!nameRe.test(name)) - throw illegal(name, "name"); - - var fieldName = util.lcFirst(name); - if (name === fieldName) - name = util.ucFirst(name); - skip("="); - var id = parseId(next()); - var type = new Type(name); - type.group = true; - var field = new Field(fieldName, id, name, rule); - field.filename = parse.filename; - ifBlock(type, function parseGroup_block(token) { - switch (token) { - - case "option": - parseOption(type, token); - skip(";"); - break; - case "required": - case "repeated": - parseField(type, token); - break; - - case "optional": - /* istanbul ignore if */ - if (edition === "proto3") { - parseField(type, "proto3_optional"); - } else { - parseField(type, "optional"); - } - break; - - case "message": - parseType(type, token); - break; - - case "enum": - parseEnum(type, token); - break; - - case "reserved": - readRanges(type.reserved || (type.reserved = []), true); - break; - - /* istanbul ignore next */ - default: - throw illegal(token); // there are no groups with proto3 semantics - } - }); - parent.add(type) - .add(field); - } - - function parseMapField(parent) { - skip("<"); - var keyType = next(); - - /* istanbul ignore if */ - if (types.mapKey[keyType] === undefined) - throw illegal(keyType, "type"); - - skip(","); - var valueType = next(); - - /* istanbul ignore if */ - if (!typeRefRe.test(valueType)) - throw illegal(valueType, "type"); - - skip(">"); - var name = next(); - - /* istanbul ignore if */ - if (!nameRe.test(name)) - throw illegal(name, "name"); - - skip("="); - var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); - ifBlock(field, function parseMapField_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(field, token); - skip(";"); - } else - throw illegal(token); - - }, function parseMapField_line() { - parseInlineOptions(field); - }); - parent.add(field); - } - - function parseOneOf(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var oneof = new OneOf(applyCase(token)); - ifBlock(oneof, function parseOneOf_block(token) { - if (token === "option") { - parseOption(oneof, token); - skip(";"); - } else { - push(token); - parseField(oneof, "optional"); - } - }); - parent.add(oneof); - } - - function parseEnum(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var enm = new Enum(token); - ifBlock(enm, function parseEnum_block(token) { - switch(token) { - case "option": - parseOption(enm, token); - skip(";"); - break; - - case "reserved": - readRanges(enm.reserved || (enm.reserved = []), true); - if(enm.reserved === undefined) enm.reserved = []; - break; - - default: - parseEnumValue(enm, token); - } - }); - parent.add(enm); - if (parent === ptr) { - topLevelObjects.push(enm); - } - } - - function parseEnumValue(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token)) - throw illegal(token, "name"); - - skip("="); - var value = parseId(next(), true), - dummy = { - options: undefined - }; - dummy.getOption = function(name) { - return this.options[name]; - }; - dummy.setOption = function(name, value) { - ReflectionObject.prototype.setOption.call(dummy, name, value); - }; - dummy.setParsedOption = function() { - return undefined; - }; - ifBlock(dummy, function parseEnumValue_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(dummy, token); // skip - skip(";"); - } else - throw illegal(token); - - }, function parseEnumValue_line() { - parseInlineOptions(dummy); // skip - }); - parent.add(token, value, dummy.comment, dummy.parsedOptions || dummy.options); - } - - function parseOption(parent, token) { - var option; - var propName; - var isOption = true; - if (token === "option") { - token = next(); - } - - while (token !== "=") { - if (token === "(") { - var parensValue = next(); - skip(")"); - token = "(" + parensValue + ")"; - } - if (isOption) { - isOption = false; - if (token.includes(".") && !token.includes("(")) { - var tokens = token.split("."); - option = tokens[0] + "."; - token = tokens[1]; - continue; - } - option = token; - } else { - propName = propName ? propName += token : token; - } - token = next(); - } - var name = propName ? option.concat(propName) : option; - var optionValue = parseOptionValue(parent, name); - propName = propName && propName[0] === "." ? propName.slice(1) : propName; - option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option; - setParsedOption(parent, option, optionValue, propName); - } - - function parseOptionValue(parent, name) { - // { a: "foo" b { c: "bar" } } - if (skip("{", true)) { - var objectResult = {}; - - while (!skip("}", true)) { - /* istanbul ignore if */ - if (!nameRe.test(token = next())) { - throw illegal(token, "name"); - } - if (token === null) { - throw illegal(token, "end of input"); - } - - var value; - var propName = token; - - skip(":", true); - - if (peek() === "{") { - // option (my_option) = { - // repeated_value: [ "foo", "bar" ] - // }; - value = parseOptionValue(parent, name + "." + token); - } else if (peek() === "[") { - value = []; - var lastValue; - if (skip("[", true)) { - do { - lastValue = readValue(true); - value.push(lastValue); - } while (skip(",", true)); - skip("]"); - if (typeof lastValue !== "undefined") { - setOption(parent, name + "." + token, lastValue); - } - } - } else { - value = readValue(true); - setOption(parent, name + "." + token, value); - } - - var prevValue = objectResult[propName]; - - if (prevValue) - value = [].concat(prevValue).concat(value); - - objectResult[propName] = value; - - // Semicolons and commas can be optional - skip(",", true); - skip(";", true); - } - - return objectResult; - } - - var simpleValue = readValue(true); - setOption(parent, name, simpleValue); - return simpleValue; - // Does not enforce a delimiter to be universal - } - - function setOption(parent, name, value) { - if (ptr === parent && /^features\./.test(name)) { - topLevelOptions[name] = value; - return; - } - if (parent.setOption) - parent.setOption(name, value); - } - - function setParsedOption(parent, name, value, propName) { - if (parent.setParsedOption) - parent.setParsedOption(name, value, propName); - } - - function parseInlineOptions(parent) { - if (skip("[", true)) { - do { - parseOption(parent, "option"); - } while (skip(",", true)); - skip("]"); - } - return parent; - } - - function parseService(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "service name"); - - var service = new Service(token); - ifBlock(service, function parseService_block(token) { - if (parseCommon(service, token)) { - return; - } - - /* istanbul ignore else */ - if (token === "rpc") - parseMethod(service, token); - else - throw illegal(token); - }); - parent.add(service); - if (parent === ptr) { - topLevelObjects.push(service); - } - } - - function parseMethod(parent, token) { - // Get the comment of the preceding line now (if one exists) in case the - // method is defined across multiple lines. - var commentText = cmnt(); - - var type = token; - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var name = token, - requestType, requestStream, - responseType, responseStream; - - skip("("); - if (skip("stream", true)) - requestStream = true; - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token); - - requestType = token; - skip(")"); skip("returns"); skip("("); - if (skip("stream", true)) - responseStream = true; - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token); - - responseType = token; - skip(")"); - - var method = new Method(name, type, requestType, responseType, requestStream, responseStream); - method.comment = commentText; - ifBlock(method, function parseMethod_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(method, token); - skip(";"); - } else - throw illegal(token); - - }); - parent.add(method); - } - - function parseExtension(parent, token) { - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token, "reference"); - - var reference = token; - ifBlock(null, function parseExtension_block(token) { - switch (token) { - - case "required": - case "repeated": - parseField(parent, token, reference); - break; - - case "optional": - /* istanbul ignore if */ - if (edition === "proto3") { - parseField(parent, "proto3_optional", reference); - } else { - parseField(parent, "optional", reference); - } - break; - - default: - /* istanbul ignore if */ - if (edition === "proto2" || !typeRefRe.test(token)) - throw illegal(token); - push(token); - parseField(parent, "optional", reference); - break; - } - }); - } - - var token; - while ((token = next()) !== null) { - switch (token) { - - case "package": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parsePackage(); - break; - - case "import": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parseImport(); - break; - - case "syntax": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parseSyntax(); - break; - - case "edition": - /* istanbul ignore if */ - if (!head) - throw illegal(token); - parseEdition(); - break; - - case "option": - parseOption(ptr, token); - skip(";", true); - break; - - default: - - /* istanbul ignore else */ - if (parseCommon(ptr, token)) { - head = false; - continue; - } - - /* istanbul ignore next */ - throw illegal(token); - } - } - - resolveFileFeatures(); - - parse.filename = null; - return { - "package" : pkg, - "imports" : imports, - weakImports : weakImports, - root : root - }; -} - -/** - * Parses the given .proto source and returns an object with the parsed contents. - * @name parse - * @function - * @param {string} source Source contents - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {IParserResult} Parser result - * @property {string} filename=null Currently processing file name for error reporting, if known - * @property {IParseOptions} defaults Default {@link IParseOptions} - * @variation 2 - */ - - -/***/ }), - -/***/ 41011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Reader; - -var util = __nccwpck_require__(71241); - -var BufferReader; // cyclic - -var LongBits = util.LongBits, - utf8 = util.utf8; - -/* istanbul ignore next */ -function indexOutOfRange(reader, writeLength) { - return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); -} - -/** - * Constructs a new reader instance using the specified buffer. - * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. - * @constructor - * @param {Uint8Array} buffer Buffer to read from - */ -function Reader(buffer) { - - /** - * Read buffer. - * @type {Uint8Array} - */ - this.buf = buffer; - - /** - * Read buffer position. - * @type {number} - */ - this.pos = 0; - - /** - * Read buffer length. - * @type {number} - */ - this.len = buffer.length; -} - -var create_array = typeof Uint8Array !== "undefined" - ? function create_typed_array(buffer) { - if (buffer instanceof Uint8Array || Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - } - /* istanbul ignore next */ - : function create_array(buffer) { - if (Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); - }; - -var create = function create() { - return util.Buffer - ? function create_buffer_setup(buffer) { - return (Reader.create = function create_buffer(buffer) { - return util.Buffer.isBuffer(buffer) - ? new BufferReader(buffer) - /* istanbul ignore next */ - : create_array(buffer); - })(buffer); - } - /* istanbul ignore next */ - : create_array; -}; - -/** - * Creates a new reader using the specified buffer. - * @function - * @param {Uint8Array|Buffer} buffer Buffer to read from - * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} - * @throws {Error} If `buffer` is not a valid buffer - */ -Reader.create = create(); - -Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; - -/** - * Reads a varint as an unsigned 32 bit value. - * @function - * @returns {number} Value read - */ -Reader.prototype.uint32 = (function read_uint32_setup() { - var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) - return function read_uint32() { - value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; - - /* istanbul ignore if */ - if ((this.pos += 5) > this.len) { - this.pos = this.len; - throw indexOutOfRange(this, 10); - } - return value; - }; -})(); - -/** - * Reads a varint as a signed 32 bit value. - * @returns {number} Value read - */ -Reader.prototype.int32 = function read_int32() { - return this.uint32() | 0; -}; - -/** - * Reads a zig-zag encoded varint as a signed 32 bit value. - * @returns {number} Value read - */ -Reader.prototype.sint32 = function read_sint32() { - var value = this.uint32(); - return value >>> 1 ^ -(value & 1) | 0; -}; - -/* eslint-disable no-invalid-this */ - -function readLongVarint() { - // tends to deopt with local vars for octet etc. - var bits = new LongBits(0, 0); - var i = 0; - if (this.len - this.pos > 4) { // fast route (lo) - for (; i < 4; ++i) { - // 1st..4th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 5th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; - bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - i = 0; - } else { - for (; i < 3; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 1st..3th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 4th - bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; - return bits; - } - if (this.len - this.pos > 4) { // fast route (hi) - for (; i < 5; ++i) { - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } else { - for (; i < 5; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } - /* istanbul ignore next */ - throw Error("invalid varint encoding"); -} - -/* eslint-enable no-invalid-this */ - -/** - * Reads a varint as a signed 64 bit value. - * @name Reader#int64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a varint as an unsigned 64 bit value. - * @name Reader#uint64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a zig-zag encoded varint as a signed 64 bit value. - * @name Reader#sint64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a varint as a boolean. - * @returns {boolean} Value read - */ -Reader.prototype.bool = function read_bool() { - return this.uint32() !== 0; -}; - -function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` - return (buf[end - 4] - | buf[end - 3] << 8 - | buf[end - 2] << 16 - | buf[end - 1] << 24) >>> 0; -} - -/** - * Reads fixed 32 bits as an unsigned 32 bit integer. - * @returns {number} Value read - */ -Reader.prototype.fixed32 = function read_fixed32() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4); -}; - -/** - * Reads fixed 32 bits as a signed 32 bit integer. - * @returns {number} Value read - */ -Reader.prototype.sfixed32 = function read_sfixed32() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4) | 0; -}; - -/* eslint-disable no-invalid-this */ - -function readFixed64(/* this: Reader */) { - - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 8); - - return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); -} - -/* eslint-enable no-invalid-this */ - -/** - * Reads fixed 64 bits. - * @name Reader#fixed64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads zig-zag encoded fixed 64 bits. - * @name Reader#sfixed64 - * @function - * @returns {Long} Value read - */ - -/** - * Reads a float (32 bit) as a number. - * @function - * @returns {number} Value read - */ -Reader.prototype.float = function read_float() { - - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readFloatLE(this.buf, this.pos); - this.pos += 4; - return value; -}; - -/** - * Reads a double (64 bit float) as a number. - * @function - * @returns {number} Value read - */ -Reader.prototype.double = function read_double() { - - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readDoubleLE(this.buf, this.pos); - this.pos += 8; - return value; -}; - -/** - * Reads a sequence of bytes preceeded by its length as a varint. - * @returns {Uint8Array} Value read - */ -Reader.prototype.bytes = function read_bytes() { - var length = this.uint32(), - start = this.pos, - end = this.pos + length; - - /* istanbul ignore if */ - if (end > this.len) - throw indexOutOfRange(this, length); - - this.pos += length; - if (Array.isArray(this.buf)) // plain array - return this.buf.slice(start, end); - - if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 - var nativeBuffer = util.Buffer; - return nativeBuffer - ? nativeBuffer.alloc(0) - : new this.buf.constructor(0); - } - return this._slice.call(this.buf, start, end); -}; - -/** - * Reads a string preceeded by its byte length as a varint. - * @returns {string} Value read - */ -Reader.prototype.string = function read_string() { - var bytes = this.bytes(); - return utf8.read(bytes, 0, bytes.length); -}; - -/** - * Skips the specified number of bytes if specified, otherwise skips a varint. - * @param {number} [length] Length if known, otherwise a varint is assumed - * @returns {Reader} `this` - */ -Reader.prototype.skip = function skip(length) { - if (typeof length === "number") { - /* istanbul ignore if */ - if (this.pos + length > this.len) - throw indexOutOfRange(this, length); - this.pos += length; - } else { - do { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - } while (this.buf[this.pos++] & 128); - } - return this; -}; - -/** - * Skips the next element of the specified wire type. - * @param {number} wireType Wire type received - * @returns {Reader} `this` - */ -Reader.prototype.skipType = function(wireType) { - switch (wireType) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - while ((wireType = this.uint32() & 7) !== 4) { - this.skipType(wireType); - } - break; - case 5: - this.skip(4); - break; - - /* istanbul ignore next */ - default: - throw Error("invalid wire type " + wireType + " at offset " + this.pos); - } - return this; -}; - -Reader._configure = function(BufferReader_) { - BufferReader = BufferReader_; - Reader.create = create(); - BufferReader._configure(); - - var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; - util.merge(Reader.prototype, { - - int64: function read_int64() { - return readLongVarint.call(this)[fn](false); - }, - - uint64: function read_uint64() { - return readLongVarint.call(this)[fn](true); - }, - - sint64: function read_sint64() { - return readLongVarint.call(this).zzDecode()[fn](false); - }, - - fixed64: function read_fixed64() { - return readFixed64.call(this)[fn](true); - }, - - sfixed64: function read_sfixed64() { - return readFixed64.call(this)[fn](false); - } - - }); -}; - - -/***/ }), - -/***/ 80339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = BufferReader; - -// extends Reader -var Reader = __nccwpck_require__(41011); -(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; - -var util = __nccwpck_require__(71241); - -/** - * Constructs a new buffer reader instance. - * @classdesc Wire format reader using node buffers. - * @extends Reader - * @constructor - * @param {Buffer} buffer Buffer to read from - */ -function BufferReader(buffer) { - Reader.call(this, buffer); - - /** - * Read buffer. - * @name BufferReader#buf - * @type {Buffer} - */ -} - -BufferReader._configure = function () { - /* istanbul ignore else */ - if (util.Buffer) - BufferReader.prototype._slice = util.Buffer.prototype.slice; -}; - - -/** - * @override - */ -BufferReader.prototype.string = function read_string_buffer() { - var len = this.uint32(); // modifies pos - return this.buf.utf8Slice - ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) - : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); -}; - -/** - * Reads a sequence of bytes preceeded by its length as a varint. - * @name BufferReader#bytes - * @function - * @returns {Buffer} Value read - */ - -BufferReader._configure(); - - -/***/ }), - -/***/ 32614: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Root; - -// extends Namespace -var Namespace = __nccwpck_require__(76189); -((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; - -var Field = __nccwpck_require__(48213), - Enum = __nccwpck_require__(17732), - OneOf = __nccwpck_require__(44408), - util = __nccwpck_require__(47174); - -var Type, // cyclic - parse, // might be excluded - common; // " - -/** - * Constructs a new root namespace instance. - * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. - * @extends NamespaceBase - * @constructor - * @param {Object.} [options] Top level options - */ -function Root(options) { - Namespace.call(this, "", options); - - /** - * Deferred extension fields. - * @type {Field[]} - */ - this.deferred = []; - - /** - * Resolved file names of loaded files. - * @type {string[]} - */ - this.files = []; - - /** - * Edition, defaults to proto2 if unspecified. - * @type {string} - * @private - */ - this._edition = "proto2"; - - /** - * Global lookup cache of fully qualified names. - * @type {Object.} - * @private - */ - this._fullyQualifiedObjects = {}; -} - -/** - * Loads a namespace descriptor into a root namespace. - * @param {INamespace} json Namespace descriptor - * @param {Root} [root] Root namespace, defaults to create a new one if omitted - * @returns {Root} Root namespace - */ -Root.fromJSON = function fromJSON(json, root) { - if (!root) - root = new Root(); - if (json.options) - root.setOptions(json.options); - return root.addJSON(json.nested).resolveAll(); -}; - -/** - * Resolves the path of an imported file, relative to the importing origin. - * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. - * @function - * @param {string} origin The file name of the importing file - * @param {string} target The file name being imported - * @returns {string|null} Resolved path to `target` or `null` to skip the file - */ -Root.prototype.resolvePath = util.path.resolve; - -/** - * Fetch content from file path or url - * This method exists so you can override it with your own logic. - * @function - * @param {string} path File path or url - * @param {FetchCallback} callback Callback function - * @returns {undefined} - */ -Root.prototype.fetch = util.fetch; - -// A symbol-like function to safely signal synchronous loading -/* istanbul ignore next */ -function SYNC() {} // eslint-disable-line no-empty-function - -/** - * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. - * @param {string|string[]} filename Names of one or multiple files to load - * @param {IParseOptions} options Parse options - * @param {LoadCallback} callback Callback function - * @returns {undefined} - */ -Root.prototype.load = function load(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = undefined; - } - var self = this; - if (!callback) { - return util.asPromise(load, self, filename, options); - } - - var sync = callback === SYNC; // undocumented - - // Finishes loading by calling the callback (exactly once) - function finish(err, root) { - /* istanbul ignore if */ - if (!callback) { - return; - } - if (sync) { - throw err; - } - if (root) { - root.resolveAll(); - } - var cb = callback; - callback = null; - cb(err, root); - } - - // Bundled definition existence checking - function getBundledFileName(filename) { - var idx = filename.lastIndexOf("google/protobuf/"); - if (idx > -1) { - var altname = filename.substring(idx); - if (altname in common) return altname; - } - return null; - } - - // Processes a single file - function process(filename, source) { - try { - if (util.isString(source) && source.charAt(0) === "{") - source = JSON.parse(source); - if (!util.isString(source)) - self.setOptions(source.options).addJSON(source.nested); - else { - parse.filename = filename; - var parsed = parse(source, self, options), - resolved, - i = 0; - if (parsed.imports) - for (; i < parsed.imports.length; ++i) - if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) - fetch(resolved); - if (parsed.weakImports) - for (i = 0; i < parsed.weakImports.length; ++i) - if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) - fetch(resolved, true); - } - } catch (err) { - finish(err); - } - if (!sync && !queued) { - finish(null, self); // only once anyway - } - } - - // Fetches a single file - function fetch(filename, weak) { - filename = getBundledFileName(filename) || filename; - - // Skip if already loaded / attempted - if (self.files.indexOf(filename) > -1) { - return; - } - self.files.push(filename); - - // Shortcut bundled definitions - if (filename in common) { - if (sync) { - process(filename, common[filename]); - } else { - ++queued; - setTimeout(function() { - --queued; - process(filename, common[filename]); - }); - } - return; - } - - // Otherwise fetch from disk or network - if (sync) { - var source; - try { - source = util.fs.readFileSync(filename).toString("utf8"); - } catch (err) { - if (!weak) - finish(err); - return; - } - process(filename, source); - } else { - ++queued; - self.fetch(filename, function(err, source) { - --queued; - /* istanbul ignore if */ - if (!callback) { - return; // terminated meanwhile - } - if (err) { - /* istanbul ignore else */ - if (!weak) - finish(err); - else if (!queued) // can't be covered reliably - finish(null, self); - return; - } - process(filename, source); - }); - } - } - var queued = 0; - - // Assembling the root namespace doesn't require working type - // references anymore, so we can load everything in parallel - if (util.isString(filename)) { - filename = [ filename ]; - } - for (var i = 0, resolved; i < filename.length; ++i) - if (resolved = self.resolvePath("", filename[i])) - fetch(resolved); - if (sync) { - self.resolveAll(); - return self; - } - if (!queued) { - finish(null, self); - } - - return self; -}; -// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined - -/** - * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. - * @function Root#load - * @param {string|string[]} filename Names of one or multiple files to load - * @param {LoadCallback} callback Callback function - * @returns {undefined} - * @variation 2 - */ -// function load(filename:string, callback:LoadCallback):undefined - -/** - * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. - * @function Root#load - * @param {string|string[]} filename Names of one or multiple files to load - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {Promise} Promise - * @variation 3 - */ -// function load(filename:string, [options:IParseOptions]):Promise - -/** - * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). - * @function Root#loadSync - * @param {string|string[]} filename Names of one or multiple files to load - * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. - * @returns {Root} Root namespace - * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid - */ -Root.prototype.loadSync = function loadSync(filename, options) { - if (!util.isNode) - throw Error("not supported"); - return this.load(filename, options, SYNC); -}; - -/** - * @override - */ -Root.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - if (this.deferred.length) - throw Error("unresolvable extensions: " + this.deferred.map(function(field) { - return "'extend " + field.extend + "' in " + field.parent.fullName; - }).join(", ")); - return Namespace.prototype.resolveAll.call(this); -}; - -// only uppercased (and thus conflict-free) children are exposed, see below -var exposeRe = /^[A-Z]/; - -/** - * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. - * @param {Root} root Root instance - * @param {Field} field Declaring extension field witin the declaring type - * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise - * @inner - * @ignore - */ -function tryHandleExtension(root, field) { - var extendedType = field.parent.lookup(field.extend); - if (extendedType) { - var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); - //do not allow to extend same field twice to prevent the error - if (extendedType.get(sisterField.name)) { - return true; - } - sisterField.declaringField = field; - field.extensionField = sisterField; - extendedType.add(sisterField); - return true; - } - return false; -} - -/** - * Called when any object is added to this root or its sub-namespaces. - * @param {ReflectionObject} object Object added - * @returns {undefined} - * @private - */ -Root.prototype._handleAdd = function _handleAdd(object) { - if (object instanceof Field) { - - if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) - if (!tryHandleExtension(this, object)) - this.deferred.push(object); - - } else if (object instanceof Enum) { - - if (exposeRe.test(object.name)) - object.parent[object.name] = object.values; // expose enum values as property of its parent - - } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { - - if (object instanceof Type) // Try to handle any deferred extensions - for (var i = 0; i < this.deferred.length;) - if (tryHandleExtension(this, this.deferred[i])) - this.deferred.splice(i, 1); - else - ++i; - for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace - this._handleAdd(object._nestedArray[j]); - if (exposeRe.test(object.name)) - object.parent[object.name] = object; // expose namespace as property of its parent - } - - if (object instanceof Type || object instanceof Enum || object instanceof Field) { - // Only store types and enums for quick lookup during resolve. - this._fullyQualifiedObjects[object.fullName] = object; - } - - // The above also adds uppercased (and thus conflict-free) nested types, services and enums as - // properties of namespaces just like static code does. This allows using a .d.ts generated for - // a static module with reflection-based solutions where the condition is met. -}; - -/** - * Called when any object is removed from this root or its sub-namespaces. - * @param {ReflectionObject} object Object removed - * @returns {undefined} - * @private - */ -Root.prototype._handleRemove = function _handleRemove(object) { - if (object instanceof Field) { - - if (/* an extension field */ object.extend !== undefined) { - if (/* already handled */ object.extensionField) { // remove its sister field - object.extensionField.parent.remove(object.extensionField); - object.extensionField = null; - } else { // cancel the extension - var index = this.deferred.indexOf(object); - /* istanbul ignore else */ - if (index > -1) - this.deferred.splice(index, 1); - } - } - - } else if (object instanceof Enum) { - - if (exposeRe.test(object.name)) - delete object.parent[object.name]; // unexpose enum values - - } else if (object instanceof Namespace) { - - for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace - this._handleRemove(object._nestedArray[i]); - - if (exposeRe.test(object.name)) - delete object.parent[object.name]; // unexpose namespaces - - } - - delete this._fullyQualifiedObjects[object.fullName]; -}; - -// Sets up cyclic dependencies (called in index-light) -Root._configure = function(Type_, parse_, common_) { - Type = Type_; - parse = parse_; - common = common_; -}; - - -/***/ }), - -/***/ 50073: -/***/ ((module) => { - -"use strict"; - -module.exports = {}; - -/** - * Named roots. - * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). - * Can also be used manually to make roots available across modules. - * @name roots - * @type {Object.} - * @example - * // pbjs -r myroot -o compiled.js ... - * - * // in another module: - * require("./compiled.js"); - * - * // in any subsequent module: - * var root = protobuf.roots["myroot"]; - */ - - -/***/ }), - -/***/ 86444: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * Streaming RPC helpers. - * @namespace - */ -var rpc = exports; - -/** - * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. - * @typedef RPCImpl - * @type {function} - * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called - * @param {Uint8Array} requestData Request data - * @param {RPCImplCallback} callback Callback function - * @returns {undefined} - * @example - * function rpcImpl(method, requestData, callback) { - * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code - * throw Error("no such method"); - * asynchronouslyObtainAResponse(requestData, function(err, responseData) { - * callback(err, responseData); - * }); - * } - */ - -/** - * Node-style callback as used by {@link RPCImpl}. - * @typedef RPCImplCallback - * @type {function} - * @param {Error|null} error Error, if any, otherwise `null` - * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error - * @returns {undefined} - */ - -rpc.Service = __nccwpck_require__(12439); - - -/***/ }), - -/***/ 12439: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Service; - -var util = __nccwpck_require__(71241); - -// Extends EventEmitter -(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; - -/** - * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. - * - * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. - * @typedef rpc.ServiceMethodCallback - * @template TRes extends Message - * @type {function} - * @param {Error|null} error Error, if any - * @param {TRes} [response] Response message - * @returns {undefined} - */ - -/** - * A service method part of a {@link rpc.Service} as created by {@link Service.create}. - * @typedef rpc.ServiceMethod - * @template TReq extends Message - * @template TRes extends Message - * @type {function} - * @param {TReq|Properties} request Request message or plain object - * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message - * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` - */ - -/** - * Constructs a new RPC service instance. - * @classdesc An RPC service as returned by {@link Service#create}. - * @exports rpc.Service - * @extends util.EventEmitter - * @constructor - * @param {RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ -function Service(rpcImpl, requestDelimited, responseDelimited) { - - if (typeof rpcImpl !== "function") - throw TypeError("rpcImpl must be a function"); - - util.EventEmitter.call(this); - - /** - * RPC implementation. Becomes `null` once the service is ended. - * @type {RPCImpl|null} - */ - this.rpcImpl = rpcImpl; - - /** - * Whether requests are length-delimited. - * @type {boolean} - */ - this.requestDelimited = Boolean(requestDelimited); - - /** - * Whether responses are length-delimited. - * @type {boolean} - */ - this.responseDelimited = Boolean(responseDelimited); -} - -/** - * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. - * @param {Method|rpc.ServiceMethod} method Reflected or static method - * @param {Constructor} requestCtor Request constructor - * @param {Constructor} responseCtor Response constructor - * @param {TReq|Properties} request Request message or plain object - * @param {rpc.ServiceMethodCallback} callback Service callback - * @returns {undefined} - * @template TReq extends Message - * @template TRes extends Message - */ -Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { - - if (!request) - throw TypeError("request must be specified"); - - var self = this; - if (!callback) - return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); - - if (!self.rpcImpl) { - setTimeout(function() { callback(Error("already ended")); }, 0); - return undefined; - } - - try { - return self.rpcImpl( - method, - requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), - function rpcCallback(err, response) { - - if (err) { - self.emit("error", err, method); - return callback(err); - } - - if (response === null) { - self.end(/* endedByRPC */ true); - return undefined; - } - - if (!(response instanceof responseCtor)) { - try { - response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); - } catch (err) { - self.emit("error", err, method); - return callback(err); - } - } - - self.emit("data", response, method); - return callback(null, response); - } - ); - } catch (err) { - self.emit("error", err, method); - setTimeout(function() { callback(err); }, 0); - return undefined; - } -}; - -/** - * Ends this service and emits the `end` event. - * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. - * @returns {rpc.Service} `this` - */ -Service.prototype.end = function end(endedByRPC) { - if (this.rpcImpl) { - if (!endedByRPC) // signal end to rpcImpl - this.rpcImpl(null, null, null); - this.rpcImpl = null; - this.emit("end").off(); - } - return this; -}; - - -/***/ }), - -/***/ 6178: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Service; - -// extends Namespace -var Namespace = __nccwpck_require__(76189); -((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; - -var Method = __nccwpck_require__(57771), - util = __nccwpck_require__(47174), - rpc = __nccwpck_require__(86444); - -/** - * Constructs a new service instance. - * @classdesc Reflected service. - * @extends NamespaceBase - * @constructor - * @param {string} name Service name - * @param {Object.} [options] Service options - * @throws {TypeError} If arguments are invalid - */ -function Service(name, options) { - Namespace.call(this, name, options); - - /** - * Service methods. - * @type {Object.} - */ - this.methods = {}; // toJSON, marker - - /** - * Cached methods as an array. - * @type {Method[]|null} - * @private - */ - this._methodsArray = null; -} - -/** - * Service descriptor. - * @interface IService - * @extends INamespace - * @property {Object.} methods Method descriptors - */ - -/** - * Constructs a service from a service descriptor. - * @param {string} name Service name - * @param {IService} json Service descriptor - * @returns {Service} Created service - * @throws {TypeError} If arguments are invalid - */ -Service.fromJSON = function fromJSON(name, json) { - var service = new Service(name, json.options); - /* istanbul ignore else */ - if (json.methods) - for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) - service.add(Method.fromJSON(names[i], json.methods[names[i]])); - if (json.nested) - service.addJSON(json.nested); - if (json.edition) - service._edition = json.edition; - service.comment = json.comment; - service._defaultEdition = "proto3"; // For backwards-compatibility. - return service; -}; - -/** - * Converts this service to a service descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IService} Service descriptor - */ -Service.prototype.toJSON = function toJSON(toJSONOptions) { - var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "options" , inherited && inherited.options || undefined, - "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, - "nested" , inherited && inherited.nested || undefined, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * Methods of this service as an array for iteration. - * @name Service#methodsArray - * @type {Method[]} - * @readonly - */ -Object.defineProperty(Service.prototype, "methodsArray", { - get: function() { - return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); - } -}); - -function clearCache(service) { - service._methodsArray = null; - return service; -} - -/** - * @override - */ -Service.prototype.get = function get(name) { - return this.methods[name] - || Namespace.prototype.get.call(this, name); -}; - -/** - * @override - */ -Service.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - Namespace.prototype.resolve.call(this); - var methods = this.methodsArray; - for (var i = 0; i < methods.length; ++i) - methods[i].resolve(); - return this; -}; - -/** - * @override - */ -Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - - edition = this._edition || edition; - - Namespace.prototype._resolveFeaturesRecursive.call(this, edition); - this.methodsArray.forEach(method => { - method._resolveFeaturesRecursive(edition); - }); - return this; -}; - -/** - * @override - */ -Service.prototype.add = function add(object) { - - /* istanbul ignore if */ - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - - if (object instanceof Method) { - this.methods[object.name] = object; - object.parent = this; - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); -}; - -/** - * @override - */ -Service.prototype.remove = function remove(object) { - if (object instanceof Method) { - - /* istanbul ignore if */ - if (this.methods[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.methods[object.name]; - object.parent = null; - return clearCache(this); - } - return Namespace.prototype.remove.call(this, object); -}; - -/** - * Creates a runtime service using the specified rpc implementation. - * @param {RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. - */ -Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { - var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); - for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { - var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); - rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ - m: method, - q: method.resolvedRequestType.ctor, - s: method.resolvedResponseType.ctor - }); - } - return rpcService; -}; - - -/***/ }), - -/***/ 61157: -/***/ ((module) => { - -"use strict"; - -module.exports = tokenize; - -var delimRe = /[\s{}=;:[\],'"()<>]/g, - stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, - stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; - -var setCommentRe = /^ *[*/]+ */, - setCommentAltRe = /^\s*\*?\/*/, - setCommentSplitRe = /\n/g, - whitespaceRe = /\s/, - unescapeRe = /\\(.?)/g; - -var unescapeMap = { - "0": "\0", - "r": "\r", - "n": "\n", - "t": "\t" -}; - -/** - * Unescapes a string. - * @param {string} str String to unescape - * @returns {string} Unescaped string - * @property {Object.} map Special characters map - * @memberof tokenize - */ -function unescape(str) { - return str.replace(unescapeRe, function($0, $1) { - switch ($1) { - case "\\": - case "": - return $1; - default: - return unescapeMap[$1] || ""; - } - }); -} - -tokenize.unescape = unescape; - -/** - * Gets the next token and advances. - * @typedef TokenizerHandleNext - * @type {function} - * @returns {string|null} Next token or `null` on eof - */ - -/** - * Peeks for the next token. - * @typedef TokenizerHandlePeek - * @type {function} - * @returns {string|null} Next token or `null` on eof - */ - -/** - * Pushes a token back to the stack. - * @typedef TokenizerHandlePush - * @type {function} - * @param {string} token Token - * @returns {undefined} - */ - -/** - * Skips the next token. - * @typedef TokenizerHandleSkip - * @type {function} - * @param {string} expected Expected token - * @param {boolean} [optional=false] If optional - * @returns {boolean} Whether the token matched - * @throws {Error} If the token didn't match and is not optional - */ - -/** - * Gets the comment on the previous line or, alternatively, the line comment on the specified line. - * @typedef TokenizerHandleCmnt - * @type {function} - * @param {number} [line] Line number - * @returns {string|null} Comment text or `null` if none - */ - -/** - * Handle object returned from {@link tokenize}. - * @interface ITokenizerHandle - * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof) - * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof) - * @property {TokenizerHandlePush} push Pushes a token back to the stack - * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws - * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any - * @property {number} line Current line number - */ - -/** - * Tokenizes the given .proto source and returns an object with useful utility functions. - * @param {string} source Source contents - * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode. - * @returns {ITokenizerHandle} Tokenizer handle - */ -function tokenize(source, alternateCommentMode) { - /* eslint-disable callback-return */ - source = source.toString(); - - var offset = 0, - length = source.length, - line = 1, - lastCommentLine = 0, - comments = {}; - - var stack = []; - - var stringDelim = null; - - /* istanbul ignore next */ - /** - * Creates an error for illegal syntax. - * @param {string} subject Subject - * @returns {Error} Error created - * @inner - */ - function illegal(subject) { - return Error("illegal " + subject + " (line " + line + ")"); - } - - /** - * Reads a string till its end. - * @returns {string} String read - * @inner - */ - function readString() { - var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; - re.lastIndex = offset - 1; - var match = re.exec(source); - if (!match) - throw illegal("string"); - offset = re.lastIndex; - push(stringDelim); - stringDelim = null; - return unescape(match[1]); - } - - /** - * Gets the character at `pos` within the source. - * @param {number} pos Position - * @returns {string} Character - * @inner - */ - function charAt(pos) { - return source.charAt(pos); - } - - /** - * Sets the current comment text. - * @param {number} start Start offset - * @param {number} end End offset - * @param {boolean} isLeading set if a leading comment - * @returns {undefined} - * @inner - */ - function setComment(start, end, isLeading) { - var comment = { - type: source.charAt(start++), - lineEmpty: false, - leading: isLeading, - }; - var lookback; - if (alternateCommentMode) { - lookback = 2; // alternate comment parsing: "//" or "/*" - } else { - lookback = 3; // "///" or "/**" - } - var commentOffset = start - lookback, - c; - do { - if (--commentOffset < 0 || - (c = source.charAt(commentOffset)) === "\n") { - comment.lineEmpty = true; - break; - } - } while (c === " " || c === "\t"); - var lines = source - .substring(start, end) - .split(setCommentSplitRe); - for (var i = 0; i < lines.length; ++i) - lines[i] = lines[i] - .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "") - .trim(); - comment.text = lines - .join("\n") - .trim(); - - comments[line] = comment; - lastCommentLine = line; - } - - function isDoubleSlashCommentLine(startOffset) { - var endOffset = findEndOfLine(startOffset); - - // see if remaining line matches comment pattern - var lineText = source.substring(startOffset, endOffset); - var isComment = /^\s*\/\//.test(lineText); - return isComment; - } - - function findEndOfLine(cursor) { - // find end of cursor's line - var endOffset = cursor; - while (endOffset < length && charAt(endOffset) !== "\n") { - endOffset++; - } - return endOffset; - } - - /** - * Obtains the next token. - * @returns {string|null} Next token or `null` on eof - * @inner - */ - function next() { - if (stack.length > 0) - return stack.shift(); - if (stringDelim) - return readString(); - var repeat, - prev, - curr, - start, - isDoc, - isLeadingComment = offset === 0; - do { - if (offset === length) - return null; - repeat = false; - while (whitespaceRe.test(curr = charAt(offset))) { - if (curr === "\n") { - isLeadingComment = true; - ++line; - } - if (++offset === length) - return null; - } - - if (charAt(offset) === "/") { - if (++offset === length) { - throw illegal("comment"); - } - if (charAt(offset) === "/") { // Line - if (!alternateCommentMode) { - // check for triple-slash comment - isDoc = charAt(start = offset + 1) === "/"; - - while (charAt(++offset) !== "\n") { - if (offset === length) { - return null; - } - } - ++offset; - if (isDoc) { - setComment(start, offset - 1, isLeadingComment); - // Trailing comment cannot not be multi-line, - // so leading comment state should be reset to handle potential next comments - isLeadingComment = true; - } - ++line; - repeat = true; - } else { - // check for double-slash comments, consolidating consecutive lines - start = offset; - isDoc = false; - if (isDoubleSlashCommentLine(offset - 1)) { - isDoc = true; - do { - offset = findEndOfLine(offset); - if (offset === length) { - break; - } - offset++; - if (!isLeadingComment) { - // Trailing comment cannot not be multi-line - break; - } - } while (isDoubleSlashCommentLine(offset)); - } else { - offset = Math.min(length, findEndOfLine(offset) + 1); - } - if (isDoc) { - setComment(start, offset, isLeadingComment); - isLeadingComment = true; - } - line++; - repeat = true; - } - } else if ((curr = charAt(offset)) === "*") { /* Block */ - // check for /** (regular comment mode) or /* (alternate comment mode) - start = offset + 1; - isDoc = alternateCommentMode || charAt(start) === "*"; - do { - if (curr === "\n") { - ++line; - } - if (++offset === length) { - throw illegal("comment"); - } - prev = curr; - curr = charAt(offset); - } while (prev !== "*" || curr !== "/"); - ++offset; - if (isDoc) { - setComment(start, offset - 2, isLeadingComment); - isLeadingComment = true; - } - repeat = true; - } else { - return "/"; - } - } - } while (repeat); - - // offset !== length if we got here - - var end = offset; - delimRe.lastIndex = 0; - var delim = delimRe.test(charAt(end++)); - if (!delim) - while (end < length && !delimRe.test(charAt(end))) - ++end; - var token = source.substring(offset, offset = end); - if (token === "\"" || token === "'") - stringDelim = token; - return token; - } - - /** - * Pushes a token back to the stack. - * @param {string} token Token - * @returns {undefined} - * @inner - */ - function push(token) { - stack.push(token); - } - - /** - * Peeks for the next token. - * @returns {string|null} Token or `null` on eof - * @inner - */ - function peek() { - if (!stack.length) { - var token = next(); - if (token === null) - return null; - push(token); - } - return stack[0]; - } - - /** - * Skips a token. - * @param {string} expected Expected token - * @param {boolean} [optional=false] Whether the token is optional - * @returns {boolean} `true` when skipped, `false` if not - * @throws {Error} When a required token is not present - * @inner - */ - function skip(expected, optional) { - var actual = peek(), - equals = actual === expected; - if (equals) { - next(); - return true; - } - if (!optional) - throw illegal("token '" + actual + "', '" + expected + "' expected"); - return false; - } - - /** - * Gets a comment. - * @param {number} [trailingLine] Line number if looking for a trailing comment - * @returns {string|null} Comment text - * @inner - */ - function cmnt(trailingLine) { - var ret = null; - var comment; - if (trailingLine === undefined) { - comment = comments[line - 1]; - delete comments[line - 1]; - if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { - ret = comment.leading ? comment.text : null; - } - } else { - /* istanbul ignore else */ - if (lastCommentLine < trailingLine) { - peek(); - } - comment = comments[trailingLine]; - delete comments[trailingLine]; - if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { - ret = comment.leading ? null : comment.text; - } - } - return ret; - } - - return Object.defineProperty({ - next: next, - peek: peek, - push: push, - skip: skip, - cmnt: cmnt - }, "line", { - get: function() { return line; } - }); - /* eslint-enable callback-return */ -} - - -/***/ }), - -/***/ 38520: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Type; - -// extends Namespace -var Namespace = __nccwpck_require__(76189); -((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; - -var Enum = __nccwpck_require__(17732), - OneOf = __nccwpck_require__(44408), - Field = __nccwpck_require__(48213), - MapField = __nccwpck_require__(67777), - Service = __nccwpck_require__(6178), - Message = __nccwpck_require__(68027), - Reader = __nccwpck_require__(41011), - Writer = __nccwpck_require__(13098), - util = __nccwpck_require__(47174), - encoder = __nccwpck_require__(23072), - decoder = __nccwpck_require__(65871), - verifier = __nccwpck_require__(34334), - converter = __nccwpck_require__(13617), - wrappers = __nccwpck_require__(63216); - -/** - * Constructs a new reflected message type instance. - * @classdesc Reflected message type. - * @extends NamespaceBase - * @constructor - * @param {string} name Message name - * @param {Object.} [options] Declared options - */ -function Type(name, options) { - Namespace.call(this, name, options); - - /** - * Message fields. - * @type {Object.} - */ - this.fields = {}; // toJSON, marker - - /** - * Oneofs declared within this namespace, if any. - * @type {Object.} - */ - this.oneofs = undefined; // toJSON - - /** - * Extension ranges, if any. - * @type {number[][]} - */ - this.extensions = undefined; // toJSON - - /** - * Reserved ranges, if any. - * @type {Array.} - */ - this.reserved = undefined; // toJSON - - /*? - * Whether this type is a legacy group. - * @type {boolean|undefined} - */ - this.group = undefined; // toJSON - - /** - * Cached fields by id. - * @type {Object.|null} - * @private - */ - this._fieldsById = null; - - /** - * Cached fields as an array. - * @type {Field[]|null} - * @private - */ - this._fieldsArray = null; - - /** - * Cached oneofs as an array. - * @type {OneOf[]|null} - * @private - */ - this._oneofsArray = null; - - /** - * Cached constructor. - * @type {Constructor<{}>} - * @private - */ - this._ctor = null; -} - -Object.defineProperties(Type.prototype, { - - /** - * Message fields by id. - * @name Type#fieldsById - * @type {Object.} - * @readonly - */ - fieldsById: { - get: function() { - - /* istanbul ignore if */ - if (this._fieldsById) - return this._fieldsById; - - this._fieldsById = {}; - for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { - var field = this.fields[names[i]], - id = field.id; - - /* istanbul ignore if */ - if (this._fieldsById[id]) - throw Error("duplicate id " + id + " in " + this); - - this._fieldsById[id] = field; - } - return this._fieldsById; - } - }, - - /** - * Fields of this message as an array for iteration. - * @name Type#fieldsArray - * @type {Field[]} - * @readonly - */ - fieldsArray: { - get: function() { - return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); - } - }, - - /** - * Oneofs of this message as an array for iteration. - * @name Type#oneofsArray - * @type {OneOf[]} - * @readonly - */ - oneofsArray: { - get: function() { - return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); - } - }, - - /** - * The registered constructor, if any registered, otherwise a generic constructor. - * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. - * @name Type#ctor - * @type {Constructor<{}>} - */ - ctor: { - get: function() { - return this._ctor || (this.ctor = Type.generateConstructor(this)()); - }, - set: function(ctor) { - - // Ensure proper prototype - var prototype = ctor.prototype; - if (!(prototype instanceof Message)) { - (ctor.prototype = new Message()).constructor = ctor; - util.merge(ctor.prototype, prototype); - } - - // Classes and messages reference their reflected type - ctor.$type = ctor.prototype.$type = this; - - // Mix in static methods - util.merge(ctor, Message, true); - - this._ctor = ctor; - - // Messages have non-enumerable default values on their prototype - var i = 0; - for (; i < /* initializes */ this.fieldsArray.length; ++i) - this._fieldsArray[i].resolve(); // ensures a proper value - - // Messages have non-enumerable getters and setters for each virtual oneof field - var ctorProperties = {}; - for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) - ctorProperties[this._oneofsArray[i].resolve().name] = { - get: util.oneOfGetter(this._oneofsArray[i].oneof), - set: util.oneOfSetter(this._oneofsArray[i].oneof) - }; - if (i) - Object.defineProperties(ctor.prototype, ctorProperties); - } - } -}); - -/** - * Generates a constructor function for the specified type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -Type.generateConstructor = function generateConstructor(mtype) { - /* eslint-disable no-unexpected-multiline */ - var gen = util.codegen(["p"], mtype.name); - // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype - for (var i = 0, field; i < mtype.fieldsArray.length; ++i) - if ((field = mtype._fieldsArray[i]).map) gen - ("this%s={}", util.safeProp(field.name)); - else if (field.repeated) gen - ("this%s=[]", util.safeProp(field.name)); - return gen - ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors - * @property {Object.} fields Field descriptors - * @property {number[][]} [extensions] Extension ranges - * @property {Array.} [reserved] Reserved ranges - * @property {boolean} [group=false] Whether a legacy group or not - */ - -/** - * Creates a message type from a message type descriptor. - * @param {string} name Message name - * @param {IType} json Message type descriptor - * @returns {Type} Created message type - */ -Type.fromJSON = function fromJSON(name, json) { - var type = new Type(name, json.options); - type.extensions = json.extensions; - type.reserved = json.reserved; - var names = Object.keys(json.fields), - i = 0; - for (; i < names.length; ++i) - type.add( - ( typeof json.fields[names[i]].keyType !== "undefined" - ? MapField.fromJSON - : Field.fromJSON )(names[i], json.fields[names[i]]) - ); - if (json.oneofs) - for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) - type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); - if (json.nested) - for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { - var nested = json.nested[names[i]]; - type.add( // most to least likely - ( nested.id !== undefined - ? Field.fromJSON - : nested.fields !== undefined - ? Type.fromJSON - : nested.values !== undefined - ? Enum.fromJSON - : nested.methods !== undefined - ? Service.fromJSON - : Namespace.fromJSON )(names[i], nested) - ); - } - if (json.extensions && json.extensions.length) - type.extensions = json.extensions; - if (json.reserved && json.reserved.length) - type.reserved = json.reserved; - if (json.group) - type.group = true; - if (json.comment) - type.comment = json.comment; - if (json.edition) - type._edition = json.edition; - type._defaultEdition = "proto3"; // For backwards-compatibility. - return type; -}; - -/** - * Converts this message type to a message type descriptor. - * @param {IToJSONOptions} [toJSONOptions] JSON conversion options - * @returns {IType} Message type descriptor - */ -Type.prototype.toJSON = function toJSON(toJSONOptions) { - var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "edition" , this._editionToJSON(), - "options" , inherited && inherited.options || undefined, - "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), - "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, - "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, - "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, - "group" , this.group || undefined, - "nested" , inherited && inherited.nested || undefined, - "comment" , keepComments ? this.comment : undefined - ]); -}; - -/** - * @override - */ -Type.prototype.resolveAll = function resolveAll() { - if (!this._needsRecursiveResolve) return this; - - Namespace.prototype.resolveAll.call(this); - var oneofs = this.oneofsArray; i = 0; - while (i < oneofs.length) - oneofs[i++].resolve(); - var fields = this.fieldsArray, i = 0; - while (i < fields.length) - fields[i++].resolve(); - return this; -}; - -/** - * @override - */ -Type.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { - if (!this._needsRecursiveFeatureResolution) return this; - - edition = this._edition || edition; - - Namespace.prototype._resolveFeaturesRecursive.call(this, edition); - this.oneofsArray.forEach(oneof => { - oneof._resolveFeatures(edition); - }); - this.fieldsArray.forEach(field => { - field._resolveFeatures(edition); - }); - return this; -}; - -/** - * @override - */ -Type.prototype.get = function get(name) { - return this.fields[name] - || this.oneofs && this.oneofs[name] - || this.nested && this.nested[name] - || null; -}; - -/** - * Adds a nested object to this type. - * @param {ReflectionObject} object Nested object to add - * @returns {Type} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id - */ -Type.prototype.add = function add(object) { - - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - - if (object instanceof Field && object.extend === undefined) { - // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. - // The root object takes care of adding distinct sister-fields to the respective extended - // type instead. - - // avoids calling the getter if not absolutely necessary because it's called quite frequently - if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) - throw Error("duplicate id " + object.id + " in " + this); - if (this.isReservedId(object.id)) - throw Error("id " + object.id + " is reserved in " + this); - if (this.isReservedName(object.name)) - throw Error("name '" + object.name + "' is reserved in " + this); - - if (object.parent) - object.parent.remove(object); - this.fields[object.name] = object; - object.message = this; - object.onAdd(this); - return clearCache(this); - } - if (object instanceof OneOf) { - if (!this.oneofs) - this.oneofs = {}; - this.oneofs[object.name] = object; - object.onAdd(this); - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); -}; - -/** - * Removes a nested object from this type. - * @param {ReflectionObject} object Nested object to remove - * @returns {Type} `this` - * @throws {TypeError} If arguments are invalid - * @throws {Error} If `object` is not a member of this type - */ -Type.prototype.remove = function remove(object) { - if (object instanceof Field && object.extend === undefined) { - // See Type#add for the reason why extension fields are excluded here. - - /* istanbul ignore if */ - if (!this.fields || this.fields[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.fields[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); - } - if (object instanceof OneOf) { - - /* istanbul ignore if */ - if (!this.oneofs || this.oneofs[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.oneofs[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); - } - return Namespace.prototype.remove.call(this, object); -}; - -/** - * Tests if the specified id is reserved. - * @param {number} id Id to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Type.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); -}; - -/** - * Tests if the specified name is reserved. - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -Type.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); -}; - -/** - * Creates a new message of this type using the specified properties. - * @param {Object.} [properties] Properties to set - * @returns {Message<{}>} Message instance - */ -Type.prototype.create = function create(properties) { - return new this.ctor(properties); -}; - -/** - * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. - * @returns {Type} `this` - */ -Type.prototype.setup = function setup() { - // Sets up everything at once so that the prototype chain does not have to be re-evaluated - // multiple times (V8, soft-deopt prototype-check). - - var fullName = this.fullName, - types = []; - for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) - types.push(this._fieldsArray[i].resolve().resolvedType); - - // Replace setup methods with type-specific generated functions - this.encode = encoder(this)({ - Writer : Writer, - types : types, - util : util - }); - this.decode = decoder(this)({ - Reader : Reader, - types : types, - util : util - }); - this.verify = verifier(this)({ - types : types, - util : util - }); - this.fromObject = converter.fromObject(this)({ - types : types, - util : util - }); - this.toObject = converter.toObject(this)({ - types : types, - util : util - }); - - // Inject custom wrappers for common types - var wrapper = wrappers[fullName]; - if (wrapper) { - var originalThis = Object.create(this); - // if (wrapper.fromObject) { - originalThis.fromObject = this.fromObject; - this.fromObject = wrapper.fromObject.bind(originalThis); - // } - // if (wrapper.toObject) { - originalThis.toObject = this.toObject; - this.toObject = wrapper.toObject.bind(originalThis); - // } - } - - return this; -}; - -/** - * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. - * @param {Message<{}>|Object.} message Message instance or plain object - * @param {Writer} [writer] Writer to encode to - * @returns {Writer} writer - */ -Type.prototype.encode = function encode_setup(message, writer) { - return this.setup().encode(message, writer); // overrides this method -}; - -/** - * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. - * @param {Message<{}>|Object.} message Message instance or plain object - * @param {Writer} [writer] Writer to encode to - * @returns {Writer} writer - */ -Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); -}; - -/** - * Decodes a message of this type. - * @param {Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Length of the message, if known beforehand - * @returns {Message<{}>} Decoded message - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {util.ProtocolError<{}>} If required fields are missing - */ -Type.prototype.decode = function decode_setup(reader, length) { - return this.setup().decode(reader, length); // overrides this method -}; - -/** - * Decodes a message of this type preceeded by its byte length as a varint. - * @param {Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {Message<{}>} Decoded message - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {util.ProtocolError} If required fields are missing - */ -Type.prototype.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof Reader)) - reader = Reader.create(reader); - return this.decode(reader, reader.uint32()); -}; - -/** - * Verifies that field values are valid and that required fields are present. - * @param {Object.} message Plain object to verify - * @returns {null|string} `null` if valid, otherwise the reason why it is not - */ -Type.prototype.verify = function verify_setup(message) { - return this.setup().verify(message); // overrides this method -}; - -/** - * Creates a new message of this type from a plain object. Also converts values to their respective internal types. - * @param {Object.} object Plain object to convert - * @returns {Message<{}>} Message instance - */ -Type.prototype.fromObject = function fromObject(object) { - return this.setup().fromObject(object); -}; - -/** - * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. - * @interface IConversionOptions - * @property {Function} [longs] Long conversion type. - * Valid values are `String` and `Number` (the global types). - * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. - * @property {Function} [enums] Enum value conversion type. - * Only valid value is `String` (the global type). - * Defaults to copy the present value, which is the numeric id. - * @property {Function} [bytes] Bytes value conversion type. - * Valid values are `Array` and (a base64 encoded) `String` (the global types). - * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. - * @property {boolean} [defaults=false] Also sets default values on the resulting object - * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` - * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` - * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any - * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings - */ - -/** - * Creates a plain object from a message of this type. Also converts values to other types if specified. - * @param {Message<{}>} message Message instance - * @param {IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ -Type.prototype.toObject = function toObject(message, options) { - return this.setup().toObject(message, options); -}; - -/** - * Decorator function as returned by {@link Type.d} (TypeScript). - * @typedef TypeDecorator - * @type {function} - * @param {Constructor} target Target constructor - * @returns {undefined} - * @template T extends Message - */ - -/** - * Type decorator (TypeScript). - * @param {string} [typeName] Type name, defaults to the constructor's name - * @returns {TypeDecorator} Decorator function - * @template T extends Message - */ -Type.d = function decorateType(typeName) { - return function typeDecorator(target) { - util.decorateType(target, typeName); - }; -}; - - -/***/ }), - -/***/ 6581: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * Common type constants. - * @namespace - */ -var types = exports; - -var util = __nccwpck_require__(47174); - -var s = [ - "double", // 0 - "float", // 1 - "int32", // 2 - "uint32", // 3 - "sint32", // 4 - "fixed32", // 5 - "sfixed32", // 6 - "int64", // 7 - "uint64", // 8 - "sint64", // 9 - "fixed64", // 10 - "sfixed64", // 11 - "bool", // 12 - "string", // 13 - "bytes" // 14 -]; - -function bake(values, offset) { - var i = 0, o = {}; - offset |= 0; - while (i < values.length) o[s[i + offset]] = values[i++]; - return o; -} - -/** - * Basic type wire types. - * @type {Object.} - * @const - * @property {number} double=1 Fixed64 wire type - * @property {number} float=5 Fixed32 wire type - * @property {number} int32=0 Varint wire type - * @property {number} uint32=0 Varint wire type - * @property {number} sint32=0 Varint wire type - * @property {number} fixed32=5 Fixed32 wire type - * @property {number} sfixed32=5 Fixed32 wire type - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - * @property {number} bool=0 Varint wire type - * @property {number} string=2 Ldelim wire type - * @property {number} bytes=2 Ldelim wire type - */ -types.basic = bake([ - /* double */ 1, - /* float */ 5, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0, - /* string */ 2, - /* bytes */ 2 -]); - -/** - * Basic type defaults. - * @type {Object.} - * @const - * @property {number} double=0 Double default - * @property {number} float=0 Float default - * @property {number} int32=0 Int32 default - * @property {number} uint32=0 Uint32 default - * @property {number} sint32=0 Sint32 default - * @property {number} fixed32=0 Fixed32 default - * @property {number} sfixed32=0 Sfixed32 default - * @property {number} int64=0 Int64 default - * @property {number} uint64=0 Uint64 default - * @property {number} sint64=0 Sint32 default - * @property {number} fixed64=0 Fixed64 default - * @property {number} sfixed64=0 Sfixed64 default - * @property {boolean} bool=false Bool default - * @property {string} string="" String default - * @property {Array.} bytes=Array(0) Bytes default - * @property {null} message=null Message default - */ -types.defaults = bake([ - /* double */ 0, - /* float */ 0, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 0, - /* sfixed32 */ 0, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 0, - /* sfixed64 */ 0, - /* bool */ false, - /* string */ "", - /* bytes */ util.emptyArray, - /* message */ null -]); - -/** - * Basic long type wire types. - * @type {Object.} - * @const - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - */ -types.long = bake([ - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1 -], 7); - -/** - * Allowed types for map keys with their associated wire type. - * @type {Object.} - * @const - * @property {number} int32=0 Varint wire type - * @property {number} uint32=0 Varint wire type - * @property {number} sint32=0 Varint wire type - * @property {number} fixed32=5 Fixed32 wire type - * @property {number} sfixed32=5 Fixed32 wire type - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - * @property {number} bool=0 Varint wire type - * @property {number} string=2 Ldelim wire type - */ -types.mapKey = bake([ - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0, - /* string */ 2 -], 2); - -/** - * Allowed types for packed repeated fields with their associated wire type. - * @type {Object.} - * @const - * @property {number} double=1 Fixed64 wire type - * @property {number} float=5 Fixed32 wire type - * @property {number} int32=0 Varint wire type - * @property {number} uint32=0 Varint wire type - * @property {number} sint32=0 Varint wire type - * @property {number} fixed32=5 Fixed32 wire type - * @property {number} sfixed32=5 Fixed32 wire type - * @property {number} int64=0 Varint wire type - * @property {number} uint64=0 Varint wire type - * @property {number} sint64=0 Varint wire type - * @property {number} fixed64=1 Fixed64 wire type - * @property {number} sfixed64=1 Fixed64 wire type - * @property {number} bool=0 Varint wire type - */ -types.packed = bake([ - /* double */ 1, - /* float */ 5, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0 -]); - - -/***/ }), - -/***/ 47174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/** - * Various utility functions. - * @namespace - */ -var util = module.exports = __nccwpck_require__(71241); - -var roots = __nccwpck_require__(50073); - -var Type, // cyclic - Enum; - -util.codegen = __nccwpck_require__(58882); -util.fetch = __nccwpck_require__(50663); -util.path = __nccwpck_require__(24761); - -/** - * Node's fs module if available. - * @type {Object.} - */ -util.fs = util.inquire("fs"); - -/** - * Converts an object's values to an array. - * @param {Object.} object Object to convert - * @returns {Array.<*>} Converted array - */ -util.toArray = function toArray(object) { - if (object) { - var keys = Object.keys(object), - array = new Array(keys.length), - index = 0; - while (index < keys.length) - array[index] = object[keys[index++]]; - return array; - } - return []; -}; - -/** - * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. - * @param {Array.<*>} array Array to convert - * @returns {Object.} Converted object - */ -util.toObject = function toObject(array) { - var object = {}, - index = 0; - while (index < array.length) { - var key = array[index++], - val = array[index++]; - if (val !== undefined) - object[key] = val; - } - return object; -}; - -var safePropBackslashRe = /\\/g, - safePropQuoteRe = /"/g; - -/** - * Tests whether the specified name is a reserved word in JS. - * @param {string} name Name to test - * @returns {boolean} `true` if reserved, otherwise `false` - */ -util.isReserved = function isReserved(name) { - return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); -}; - -/** - * Returns a safe property accessor for the specified property name. - * @param {string} prop Property name - * @returns {string} Safe accessor - */ -util.safeProp = function safeProp(prop) { - if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) - return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; - return "." + prop; -}; - -/** - * Converts the first character of a string to upper case. - * @param {string} str String to convert - * @returns {string} Converted string - */ -util.ucFirst = function ucFirst(str) { - return str.charAt(0).toUpperCase() + str.substring(1); -}; - -var camelCaseRe = /_([a-z])/g; - -/** - * Converts a string to camel case. - * @param {string} str String to convert - * @returns {string} Converted string - */ -util.camelCase = function camelCase(str) { - return str.substring(0, 1) - + str.substring(1) - .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); -}; - -/** - * Compares reflected fields by id. - * @param {Field} a First field - * @param {Field} b Second field - * @returns {number} Comparison value - */ -util.compareFieldsById = function compareFieldsById(a, b) { - return a.id - b.id; -}; - -/** - * Decorator helper for types (TypeScript). - * @param {Constructor} ctor Constructor function - * @param {string} [typeName] Type name, defaults to the constructor's name - * @returns {Type} Reflected type - * @template T extends Message - * @property {Root} root Decorators root - */ -util.decorateType = function decorateType(ctor, typeName) { - - /* istanbul ignore if */ - if (ctor.$type) { - if (typeName && ctor.$type.name !== typeName) { - util.decorateRoot.remove(ctor.$type); - ctor.$type.name = typeName; - util.decorateRoot.add(ctor.$type); - } - return ctor.$type; - } - - /* istanbul ignore next */ - if (!Type) - Type = __nccwpck_require__(38520); - - var type = new Type(typeName || ctor.name); - util.decorateRoot.add(type); - type.ctor = ctor; // sets up .encode, .decode etc. - Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); - Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); - return type; -}; - -var decorateEnumIndex = 0; - -/** - * Decorator helper for enums (TypeScript). - * @param {Object} object Enum object - * @returns {Enum} Reflected enum - */ -util.decorateEnum = function decorateEnum(object) { - - /* istanbul ignore if */ - if (object.$type) - return object.$type; - - /* istanbul ignore next */ - if (!Enum) - Enum = __nccwpck_require__(17732); - - var enm = new Enum("Enum" + decorateEnumIndex++, object); - util.decorateRoot.add(enm); - Object.defineProperty(object, "$type", { value: enm, enumerable: false }); - return enm; -}; - - -/** - * Sets the value of a property by property path. If a value already exists, it is turned to an array - * @param {Object.} dst Destination object - * @param {string} path dot '.' delimited path of the property to set - * @param {Object} value the value to set - * @param {boolean|undefined} [ifNotSet] Sets the option only if it isn't currently set - * @returns {Object.} Destination object - */ -util.setProperty = function setProperty(dst, path, value, ifNotSet) { - function setProp(dst, path, value) { - var part = path.shift(); - if (part === "__proto__" || part === "prototype") { - return dst; - } - if (path.length > 0) { - dst[part] = setProp(dst[part] || {}, path, value); - } else { - var prevValue = dst[part]; - if (prevValue && ifNotSet) - return dst; - if (prevValue) - value = [].concat(prevValue).concat(value); - dst[part] = value; - } - return dst; - } - - if (typeof dst !== "object") - throw TypeError("dst must be an object"); - if (!path) - throw TypeError("path must be specified"); - - path = path.split("."); - return setProp(dst, path, value); -}; - -/** - * Decorator root (TypeScript). - * @name util.decorateRoot - * @type {Root} - * @readonly - */ -Object.defineProperty(util, "decorateRoot", { - get: function() { - return roots["decorated"] || (roots["decorated"] = new (__nccwpck_require__(32614))()); - } -}); - - -/***/ }), - -/***/ 8374: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = LongBits; - -var util = __nccwpck_require__(71241); - -/** - * Constructs new long bits. - * @classdesc Helper class for working with the low and high bits of a 64 bit value. - * @memberof util - * @constructor - * @param {number} lo Low 32 bits, unsigned - * @param {number} hi High 32 bits, unsigned - */ -function LongBits(lo, hi) { - - // note that the casts below are theoretically unnecessary as of today, but older statically - // generated converter code might still call the ctor with signed 32bits. kept for compat. - - /** - * Low bits. - * @type {number} - */ - this.lo = lo >>> 0; - - /** - * High bits. - * @type {number} - */ - this.hi = hi >>> 0; -} - -/** - * Zero bits. - * @memberof util.LongBits - * @type {util.LongBits} - */ -var zero = LongBits.zero = new LongBits(0, 0); - -zero.toNumber = function() { return 0; }; -zero.zzEncode = zero.zzDecode = function() { return this; }; -zero.length = function() { return 1; }; - -/** - * Zero hash. - * @memberof util.LongBits - * @type {string} - */ -var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; - -/** - * Constructs new long bits from the specified number. - * @param {number} value Value - * @returns {util.LongBits} Instance - */ -LongBits.fromNumber = function fromNumber(value) { - if (value === 0) - return zero; - var sign = value < 0; - if (sign) - value = -value; - var lo = value >>> 0, - hi = (value - lo) / 4294967296 >>> 0; - if (sign) { - hi = ~hi >>> 0; - lo = ~lo >>> 0; - if (++lo > 4294967295) { - lo = 0; - if (++hi > 4294967295) - hi = 0; - } - } - return new LongBits(lo, hi); -}; - -/** - * Constructs new long bits from a number, long or string. - * @param {Long|number|string} value Value - * @returns {util.LongBits} Instance - */ -LongBits.from = function from(value) { - if (typeof value === "number") - return LongBits.fromNumber(value); - if (util.isString(value)) { - /* istanbul ignore else */ - if (util.Long) - value = util.Long.fromString(value); - else - return LongBits.fromNumber(parseInt(value, 10)); - } - return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; -}; - -/** - * Converts this long bits to a possibly unsafe JavaScript number. - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {number} Possibly unsafe number - */ -LongBits.prototype.toNumber = function toNumber(unsigned) { - if (!unsigned && this.hi >>> 31) { - var lo = ~this.lo + 1 >>> 0, - hi = ~this.hi >>> 0; - if (!lo) - hi = hi + 1 >>> 0; - return -(lo + hi * 4294967296); - } - return this.lo + this.hi * 4294967296; -}; - -/** - * Converts this long bits to a long. - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {Long} Long - */ -LongBits.prototype.toLong = function toLong(unsigned) { - return util.Long - ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) - /* istanbul ignore next */ - : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; -}; - -var charCodeAt = String.prototype.charCodeAt; - -/** - * Constructs new long bits from the specified 8 characters long hash. - * @param {string} hash Hash - * @returns {util.LongBits} Bits - */ -LongBits.fromHash = function fromHash(hash) { - if (hash === zeroHash) - return zero; - return new LongBits( - ( charCodeAt.call(hash, 0) - | charCodeAt.call(hash, 1) << 8 - | charCodeAt.call(hash, 2) << 16 - | charCodeAt.call(hash, 3) << 24) >>> 0 - , - ( charCodeAt.call(hash, 4) - | charCodeAt.call(hash, 5) << 8 - | charCodeAt.call(hash, 6) << 16 - | charCodeAt.call(hash, 7) << 24) >>> 0 - ); -}; - -/** - * Converts this long bits to a 8 characters long hash. - * @returns {string} Hash - */ -LongBits.prototype.toHash = function toHash() { - return String.fromCharCode( - this.lo & 255, - this.lo >>> 8 & 255, - this.lo >>> 16 & 255, - this.lo >>> 24 , - this.hi & 255, - this.hi >>> 8 & 255, - this.hi >>> 16 & 255, - this.hi >>> 24 - ); -}; - -/** - * Zig-zag encodes this long bits. - * @returns {util.LongBits} `this` - */ -LongBits.prototype.zzEncode = function zzEncode() { - var mask = this.hi >> 31; - this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; - this.lo = ( this.lo << 1 ^ mask) >>> 0; - return this; -}; - -/** - * Zig-zag decodes this long bits. - * @returns {util.LongBits} `this` - */ -LongBits.prototype.zzDecode = function zzDecode() { - var mask = -(this.lo & 1); - this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; - this.hi = ( this.hi >>> 1 ^ mask) >>> 0; - return this; -}; - -/** - * Calculates the length of this longbits when encoded as a varint. - * @returns {number} Length - */ -LongBits.prototype.length = function length() { - var part0 = this.lo, - part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, - part2 = this.hi >>> 24; - return part2 === 0 - ? part1 === 0 - ? part0 < 16384 - ? part0 < 128 ? 1 : 2 - : part0 < 2097152 ? 3 : 4 - : part1 < 16384 - ? part1 < 128 ? 5 : 6 - : part1 < 2097152 ? 7 : 8 - : part2 < 128 ? 9 : 10; -}; - - -/***/ }), - -/***/ 71241: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var util = exports; - -// used to return a Promise where callback is omitted -util.asPromise = __nccwpck_require__(252); - -// converts to / from base64 encoded strings -util.base64 = __nccwpck_require__(26718); - -// base class of rpc.Service -util.EventEmitter = __nccwpck_require__(86850); - -// float handling accross browsers -util.float = __nccwpck_require__(21843); - -// requires modules optionally and hides the call from bundlers -util.inquire = __nccwpck_require__(60094); - -// converts to / from utf8 encoded strings -util.utf8 = __nccwpck_require__(99049); - -// provides a node-like buffer pool in the browser -util.pool = __nccwpck_require__(47743); - -// utility to work with the low and high bits of a 64 bit value -util.LongBits = __nccwpck_require__(8374); - -/** - * Whether running within node or not. - * @memberof util - * @type {boolean} - */ -util.isNode = Boolean(typeof global !== "undefined" - && global - && global.process - && global.process.versions - && global.process.versions.node); - -/** - * Global object reference. - * @memberof util - * @type {Object} - */ -util.global = util.isNode && global - || typeof window !== "undefined" && window - || typeof self !== "undefined" && self - || this; // eslint-disable-line no-invalid-this - -/** - * An immuable empty array. - * @memberof util - * @type {Array.<*>} - * @const - */ -util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes - -/** - * An immutable empty object. - * @type {Object} - * @const - */ -util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes - -/** - * Tests if the specified value is an integer. - * @function - * @param {*} value Value to test - * @returns {boolean} `true` if the value is an integer - */ -util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; -}; - -/** - * Tests if the specified value is a string. - * @param {*} value Value to test - * @returns {boolean} `true` if the value is a string - */ -util.isString = function isString(value) { - return typeof value === "string" || value instanceof String; -}; - -/** - * Tests if the specified value is a non-null object. - * @param {*} value Value to test - * @returns {boolean} `true` if the value is a non-null object - */ -util.isObject = function isObject(value) { - return value && typeof value === "object"; -}; - -/** - * Checks if a property on a message is considered to be present. - * This is an alias of {@link util.isSet}. - * @function - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ -util.isset = - -/** - * Checks if a property on a message is considered to be present. - * @param {Object} obj Plain object or message instance - * @param {string} prop Property name - * @returns {boolean} `true` if considered to be present, otherwise `false` - */ -util.isSet = function isSet(obj, prop) { - var value = obj[prop]; - if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins - return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; - return false; -}; - -/** - * Any compatible Buffer instance. - * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. - * @interface Buffer - * @extends Uint8Array - */ - -/** - * Node's Buffer class if available. - * @type {Constructor} - */ -util.Buffer = (function() { - try { - var Buffer = util.inquire("buffer").Buffer; - // refuse to use non-node buffers if not explicitly assigned (perf reasons): - return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; - } catch (e) { - /* istanbul ignore next */ - return null; - } -})(); - -// Internal alias of or polyfull for Buffer.from. -util._Buffer_from = null; - -// Internal alias of or polyfill for Buffer.allocUnsafe. -util._Buffer_allocUnsafe = null; - -/** - * Creates a new buffer of whatever type supported by the environment. - * @param {number|number[]} [sizeOrArray=0] Buffer size or number array - * @returns {Uint8Array|Buffer} Buffer - */ -util.newBuffer = function newBuffer(sizeOrArray) { - /* istanbul ignore next */ - return typeof sizeOrArray === "number" - ? util.Buffer - ? util._Buffer_allocUnsafe(sizeOrArray) - : new util.Array(sizeOrArray) - : util.Buffer - ? util._Buffer_from(sizeOrArray) - : typeof Uint8Array === "undefined" - ? sizeOrArray - : new Uint8Array(sizeOrArray); -}; - -/** - * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. - * @type {Constructor} - */ -util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; - -/** - * Any compatible Long instance. - * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. - * @interface Long - * @property {number} low Low bits - * @property {number} high High bits - * @property {boolean} unsigned Whether unsigned or not - */ - -/** - * Long.js's Long class if available. - * @type {Constructor} - */ -util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long - || /* istanbul ignore next */ util.global.Long - || util.inquire("long"); - -/** - * Regular expression used to verify 2 bit (`bool`) map keys. - * @type {RegExp} - * @const - */ -util.key2Re = /^true|false|0|1$/; - -/** - * Regular expression used to verify 32 bit (`int32` etc.) map keys. - * @type {RegExp} - * @const - */ -util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; - -/** - * Regular expression used to verify 64 bit (`int64` etc.) map keys. - * @type {RegExp} - * @const - */ -util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; - -/** - * Converts a number or long to an 8 characters long hash string. - * @param {Long|number} value Value to convert - * @returns {string} Hash - */ -util.longToHash = function longToHash(value) { - return value - ? util.LongBits.from(value).toHash() - : util.LongBits.zeroHash; -}; - -/** - * Converts an 8 characters long hash string to a long or number. - * @param {string} hash Hash - * @param {boolean} [unsigned=false] Whether unsigned or not - * @returns {Long|number} Original value - */ -util.longFromHash = function longFromHash(hash, unsigned) { - var bits = util.LongBits.fromHash(hash); - if (util.Long) - return util.Long.fromBits(bits.lo, bits.hi, unsigned); - return bits.toNumber(Boolean(unsigned)); -}; - -/** - * Merges the properties of the source object into the destination object. - * @memberof util - * @param {Object.} dst Destination object - * @param {Object.} src Source object - * @param {boolean} [ifNotSet=false] Merges only if the key is not already set - * @returns {Object.} Destination object - */ -function merge(dst, src, ifNotSet) { // used by converters - for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) - if (dst[keys[i]] === undefined || !ifNotSet) - dst[keys[i]] = src[keys[i]]; - return dst; -} - -util.merge = merge; - -/** - * Converts the first character of a string to lower case. - * @param {string} str String to convert - * @returns {string} Converted string - */ -util.lcFirst = function lcFirst(str) { - return str.charAt(0).toLowerCase() + str.substring(1); -}; - -/** - * Creates a custom error constructor. - * @memberof util - * @param {string} name Error name - * @returns {Constructor} Custom error constructor - */ -function newError(name) { - - function CustomError(message, properties) { - - if (!(this instanceof CustomError)) - return new CustomError(message, properties); - - // Error.call(this, message); - // ^ just returns a new error instance because the ctor can be called as a function - - Object.defineProperty(this, "message", { get: function() { return message; } }); - - /* istanbul ignore next */ - if (Error.captureStackTrace) // node - Error.captureStackTrace(this, CustomError); - else - Object.defineProperty(this, "stack", { value: new Error().stack || "" }); - - if (properties) - merge(this, properties); - } - - CustomError.prototype = Object.create(Error.prototype, { - constructor: { - value: CustomError, - writable: true, - enumerable: false, - configurable: true, - }, - name: { - get: function get() { return name; }, - set: undefined, - enumerable: false, - // configurable: false would accurately preserve the behavior of - // the original, but I'm guessing that was not intentional. - // For an actual error subclass, this property would - // be configurable. - configurable: true, - }, - toString: { - value: function value() { return this.name + ": " + this.message; }, - writable: true, - enumerable: false, - configurable: true, - }, - }); - - return CustomError; -} - -util.newError = newError; - -/** - * Constructs a new protocol error. - * @classdesc Error subclass indicating a protocol specifc error. - * @memberof util - * @extends Error - * @template T extends Message - * @constructor - * @param {string} message Error message - * @param {Object.} [properties] Additional properties - * @example - * try { - * MyMessage.decode(someBuffer); // throws if required fields are missing - * } catch (e) { - * if (e instanceof ProtocolError && e.instance) - * console.log("decoded so far: " + JSON.stringify(e.instance)); - * } - */ -util.ProtocolError = newError("ProtocolError"); - -/** - * So far decoded message instance. - * @name util.ProtocolError#instance - * @type {Message} - */ - -/** - * A OneOf getter as returned by {@link util.oneOfGetter}. - * @typedef OneOfGetter - * @type {function} - * @returns {string|undefined} Set field name, if any - */ - -/** - * Builds a getter for a oneof's present field name. - * @param {string[]} fieldNames Field names - * @returns {OneOfGetter} Unbound getter - */ -util.oneOfGetter = function getOneOf(fieldNames) { - var fieldMap = {}; - for (var i = 0; i < fieldNames.length; ++i) - fieldMap[fieldNames[i]] = 1; - - /** - * @returns {string|undefined} Set field name, if any - * @this Object - * @ignore - */ - return function() { // eslint-disable-line consistent-return - for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) - if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) - return keys[i]; - }; -}; - -/** - * A OneOf setter as returned by {@link util.oneOfSetter}. - * @typedef OneOfSetter - * @type {function} - * @param {string|undefined} value Field name - * @returns {undefined} - */ - -/** - * Builds a setter for a oneof's present field name. - * @param {string[]} fieldNames Field names - * @returns {OneOfSetter} Unbound setter - */ -util.oneOfSetter = function setOneOf(fieldNames) { - - /** - * @param {string} name Field name - * @returns {undefined} - * @this Object - * @ignore - */ - return function(name) { - for (var i = 0; i < fieldNames.length; ++i) - if (fieldNames[i] !== name) - delete this[fieldNames[i]]; - }; -}; - -/** - * Default conversion options used for {@link Message#toJSON} implementations. - * - * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: - * - * - Longs become strings - * - Enums become string keys - * - Bytes become base64 encoded strings - * - (Sub-)Messages become plain objects - * - Maps become plain objects with all string keys - * - Repeated fields become arrays - * - NaN and Infinity for float and double fields become strings - * - * @type {IConversionOptions} - * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json - */ -util.toJSONOptions = { - longs: String, - enums: String, - bytes: String, - json: true -}; - -// Sets up buffer utility according to the environment (called in index-minimal) -util._configure = function() { - var Buffer = util.Buffer; - /* istanbul ignore if */ - if (!Buffer) { - util._Buffer_from = util._Buffer_allocUnsafe = null; - return; - } - // because node 4.x buffers are incompatible & immutable - // see: https://github.com/dcodeIO/protobuf.js/pull/665 - util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || - /* istanbul ignore next */ - function Buffer_from(value, encoding) { - return new Buffer(value, encoding); - }; - util._Buffer_allocUnsafe = Buffer.allocUnsafe || - /* istanbul ignore next */ - function Buffer_allocUnsafe(size) { - return new Buffer(size); - }; -}; - - -/***/ }), - -/***/ 34334: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = verifier; - -var Enum = __nccwpck_require__(17732), - util = __nccwpck_require__(47174); - -function invalid(field, expected) { - return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; -} - -/** - * Generates a partial value verifier. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {number} fieldIndex Field index - * @param {string} ref Variable reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genVerifyValue(gen, field, fieldIndex, ref) { - /* eslint-disable no-unexpected-multiline */ - if (field.resolvedType) { - if (field.resolvedType instanceof Enum) { gen - ("switch(%s){", ref) - ("default:") - ("return%j", invalid(field, "enum value")); - for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen - ("case %i:", field.resolvedType.values[keys[j]]); - gen - ("break") - ("}"); - } else { - gen - ("{") - ("var e=types[%i].verify(%s);", fieldIndex, ref) - ("if(e)") - ("return%j+e", field.name + ".") - ("}"); - } - } else { - switch (field.type) { - case "int32": - case "uint32": - case "sint32": - case "fixed32": - case "sfixed32": gen - ("if(!util.isInteger(%s))", ref) - ("return%j", invalid(field, "integer")); - break; - case "int64": - case "uint64": - case "sint64": - case "fixed64": - case "sfixed64": gen - ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) - ("return%j", invalid(field, "integer|Long")); - break; - case "float": - case "double": gen - ("if(typeof %s!==\"number\")", ref) - ("return%j", invalid(field, "number")); - break; - case "bool": gen - ("if(typeof %s!==\"boolean\")", ref) - ("return%j", invalid(field, "boolean")); - break; - case "string": gen - ("if(!util.isString(%s))", ref) - ("return%j", invalid(field, "string")); - break; - case "bytes": gen - ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) - ("return%j", invalid(field, "buffer")); - break; - } - } - return gen; - /* eslint-enable no-unexpected-multiline */ -} - -/** - * Generates a partial key verifier. - * @param {Codegen} gen Codegen instance - * @param {Field} field Reflected field - * @param {string} ref Variable reference - * @returns {Codegen} Codegen instance - * @ignore - */ -function genVerifyKey(gen, field, ref) { - /* eslint-disable no-unexpected-multiline */ - switch (field.keyType) { - case "int32": - case "uint32": - case "sint32": - case "fixed32": - case "sfixed32": gen - ("if(!util.key32Re.test(%s))", ref) - ("return%j", invalid(field, "integer key")); - break; - case "int64": - case "uint64": - case "sint64": - case "fixed64": - case "sfixed64": gen - ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not - ("return%j", invalid(field, "integer|Long key")); - break; - case "bool": gen - ("if(!util.key2Re.test(%s))", ref) - ("return%j", invalid(field, "boolean key")); - break; - } - return gen; - /* eslint-enable no-unexpected-multiline */ -} - -/** - * Generates a verifier specific to the specified message type. - * @param {Type} mtype Message type - * @returns {Codegen} Codegen instance - */ -function verifier(mtype) { - /* eslint-disable no-unexpected-multiline */ - - var gen = util.codegen(["m"], mtype.name + "$verify") - ("if(typeof m!==\"object\"||m===null)") - ("return%j", "object expected"); - var oneofs = mtype.oneofsArray, - seenFirstField = {}; - if (oneofs.length) gen - ("var p={}"); - - for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { - var field = mtype._fieldsArray[i].resolve(), - ref = "m" + util.safeProp(field.name); - - if (field.optional) gen - ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null - - // map fields - if (field.map) { gen - ("if(!util.isObject(%s))", ref) - ("return%j", invalid(field, "object")) - ("var k=Object.keys(%s)", ref) - ("for(var i=0;i { - -"use strict"; - - -/** - * Wrappers for common types. - * @type {Object.} - * @const - */ -var wrappers = exports; - -var Message = __nccwpck_require__(68027); - -/** - * From object converter part of an {@link IWrapper}. - * @typedef WrapperFromObjectConverter - * @type {function} - * @param {Object.} object Plain object - * @returns {Message<{}>} Message instance - * @this Type - */ - -/** - * To object converter part of an {@link IWrapper}. - * @typedef WrapperToObjectConverter - * @type {function} - * @param {Message<{}>} message Message instance - * @param {IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - * @this Type - */ - -/** - * Common type wrapper part of {@link wrappers}. - * @interface IWrapper - * @property {WrapperFromObjectConverter} [fromObject] From object converter - * @property {WrapperToObjectConverter} [toObject] To object converter - */ - -// Custom wrapper for Any -wrappers[".google.protobuf.Any"] = { - - fromObject: function(object) { - - // unwrap value type if mapped - if (object && object["@type"]) { - // Only use fully qualified type name after the last '/' - var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); - var type = this.lookup(name); - /* istanbul ignore else */ - if (type) { - // type_url does not accept leading "." - var type_url = object["@type"].charAt(0) === "." ? - object["@type"].slice(1) : object["@type"]; - // type_url prefix is optional, but path seperator is required - if (type_url.indexOf("/") === -1) { - type_url = "/" + type_url; - } - return this.create({ - type_url: type_url, - value: type.encode(type.fromObject(object)).finish() - }); - } - } - - return this.fromObject(object); - }, - - toObject: function(message, options) { - - // Default prefix - var googleApi = "type.googleapis.com/"; - var prefix = ""; - var name = ""; - - // decode value if requested and unmapped - if (options && options.json && message.type_url && message.value) { - // Only use fully qualified type name after the last '/' - name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); - // Separate the prefix used - prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); - var type = this.lookup(name); - /* istanbul ignore else */ - if (type) - message = type.decode(message.value); - } - - // wrap value if unmapped - if (!(message instanceof this.ctor) && message instanceof Message) { - var object = message.$type.toObject(message, options); - var messageName = message.$type.fullName[0] === "." ? - message.$type.fullName.slice(1) : message.$type.fullName; - // Default to type.googleapis.com prefix if no prefix is used - if (prefix === "") { - prefix = googleApi; - } - name = prefix + messageName; - object["@type"] = name; - return object; - } - - return this.toObject(message, options); - } -}; - - -/***/ }), - -/***/ 13098: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = Writer; - -var util = __nccwpck_require__(71241); - -var BufferWriter; // cyclic - -var LongBits = util.LongBits, - base64 = util.base64, - utf8 = util.utf8; - -/** - * Constructs a new writer operation instance. - * @classdesc Scheduled writer operation. - * @constructor - * @param {function(*, Uint8Array, number)} fn Function to call - * @param {number} len Value byte length - * @param {*} val Value to write - * @ignore - */ -function Op(fn, len, val) { - - /** - * Function to call. - * @type {function(Uint8Array, number, *)} - */ - this.fn = fn; - - /** - * Value byte length. - * @type {number} - */ - this.len = len; - - /** - * Next operation. - * @type {Writer.Op|undefined} - */ - this.next = undefined; - - /** - * Value to write. - * @type {*} - */ - this.val = val; // type varies -} - -/* istanbul ignore next */ -function noop() {} // eslint-disable-line no-empty-function - -/** - * Constructs a new writer state instance. - * @classdesc Copied writer state. - * @memberof Writer - * @constructor - * @param {Writer} writer Writer to copy state from - * @ignore - */ -function State(writer) { - - /** - * Current head. - * @type {Writer.Op} - */ - this.head = writer.head; - - /** - * Current tail. - * @type {Writer.Op} - */ - this.tail = writer.tail; - - /** - * Current buffer length. - * @type {number} - */ - this.len = writer.len; - - /** - * Next state. - * @type {State|null} - */ - this.next = writer.states; -} - -/** - * Constructs a new writer instance. - * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. - * @constructor - */ -function Writer() { - - /** - * Current length. - * @type {number} - */ - this.len = 0; - - /** - * Operations head. - * @type {Object} - */ - this.head = new Op(noop, 0, 0); - - /** - * Operations tail - * @type {Object} - */ - this.tail = this.head; - - /** - * Linked forked states. - * @type {Object|null} - */ - this.states = null; - - // When a value is written, the writer calculates its byte length and puts it into a linked - // list of operations to perform when finish() is called. This both allows us to allocate - // buffers of the exact required size and reduces the amount of work we have to do compared - // to first calculating over objects and then encoding over objects. In our case, the encoding - // part is just a linked list walk calling operations with already prepared values. -} - -var create = function create() { - return util.Buffer - ? function create_buffer_setup() { - return (Writer.create = function create_buffer() { - return new BufferWriter(); - })(); - } - /* istanbul ignore next */ - : function create_array() { - return new Writer(); - }; -}; - -/** - * Creates a new writer. - * @function - * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} - */ -Writer.create = create(); - -/** - * Allocates a buffer of the specified size. - * @param {number} size Buffer size - * @returns {Uint8Array} Buffer - */ -Writer.alloc = function alloc(size) { - return new util.Array(size); -}; - -// Use Uint8Array buffer pool in the browser, just like node does with buffers -/* istanbul ignore else */ -if (util.Array !== Array) - Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); - -/** - * Pushes a new operation to the queue. - * @param {function(Uint8Array, number, *)} fn Function to call - * @param {number} len Value byte length - * @param {number} val Value to write - * @returns {Writer} `this` - * @private - */ -Writer.prototype._push = function push(fn, len, val) { - this.tail = this.tail.next = new Op(fn, len, val); - this.len += len; - return this; -}; - -function writeByte(val, buf, pos) { - buf[pos] = val & 255; -} - -function writeVarint32(val, buf, pos) { - while (val > 127) { - buf[pos++] = val & 127 | 128; - val >>>= 7; - } - buf[pos] = val; -} - -/** - * Constructs a new varint writer operation instance. - * @classdesc Scheduled varint writer operation. - * @extends Op - * @constructor - * @param {number} len Value byte length - * @param {number} val Value to write - * @ignore - */ -function VarintOp(len, val) { - this.len = len; - this.next = undefined; - this.val = val; -} - -VarintOp.prototype = Object.create(Op.prototype); -VarintOp.prototype.fn = writeVarint32; - -/** - * Writes an unsigned 32 bit value as a varint. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.uint32 = function write_uint32(value) { - // here, the call to this.push has been inlined and a varint specific Op subclass is used. - // uint32 is by far the most frequently used operation and benefits significantly from this. - this.len += (this.tail = this.tail.next = new VarintOp( - (value = value >>> 0) - < 128 ? 1 - : value < 16384 ? 2 - : value < 2097152 ? 3 - : value < 268435456 ? 4 - : 5, - value)).len; - return this; -}; - -/** - * Writes a signed 32 bit value as a varint. - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.int32 = function write_int32(value) { - return value < 0 - ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec - : this.uint32(value); -}; - -/** - * Writes a 32 bit value as a varint, zig-zag encoded. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.sint32 = function write_sint32(value) { - return this.uint32((value << 1 ^ value >> 31) >>> 0); -}; - -function writeVarint64(val, buf, pos) { - while (val.hi) { - buf[pos++] = val.lo & 127 | 128; - val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; - val.hi >>>= 7; - } - while (val.lo > 127) { - buf[pos++] = val.lo & 127 | 128; - val.lo = val.lo >>> 7; - } - buf[pos++] = val.lo; -} - -/** - * Writes an unsigned 64 bit value as a varint. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.uint64 = function write_uint64(value) { - var bits = LongBits.from(value); - return this._push(writeVarint64, bits.length(), bits); -}; - -/** - * Writes a signed 64 bit value as a varint. - * @function - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.int64 = Writer.prototype.uint64; - -/** - * Writes a signed 64 bit value as a varint, zig-zag encoded. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.sint64 = function write_sint64(value) { - var bits = LongBits.from(value).zzEncode(); - return this._push(writeVarint64, bits.length(), bits); -}; - -/** - * Writes a boolish value as a varint. - * @param {boolean} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.bool = function write_bool(value) { - return this._push(writeByte, 1, value ? 1 : 0); -}; - -function writeFixed32(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; -} - -/** - * Writes an unsigned 32 bit value as fixed 32 bits. - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.fixed32 = function write_fixed32(value) { - return this._push(writeFixed32, 4, value >>> 0); -}; - -/** - * Writes a signed 32 bit value as fixed 32 bits. - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.sfixed32 = Writer.prototype.fixed32; - -/** - * Writes an unsigned 64 bit value as fixed 64 bits. - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.fixed64 = function write_fixed64(value) { - var bits = LongBits.from(value); - return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); -}; - -/** - * Writes a signed 64 bit value as fixed 64 bits. - * @function - * @param {Long|number|string} value Value to write - * @returns {Writer} `this` - * @throws {TypeError} If `value` is a string and no long library is present. - */ -Writer.prototype.sfixed64 = Writer.prototype.fixed64; - -/** - * Writes a float (32 bit). - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.float = function write_float(value) { - return this._push(util.float.writeFloatLE, 4, value); -}; - -/** - * Writes a double (64 bit float). - * @function - * @param {number} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.double = function write_double(value) { - return this._push(util.float.writeDoubleLE, 8, value); -}; - -var writeBytes = util.Array.prototype.set - ? function writeBytes_set(val, buf, pos) { - buf.set(val, pos); // also works for plain array values - } - /* istanbul ignore next */ - : function writeBytes_for(val, buf, pos) { - for (var i = 0; i < val.length; ++i) - buf[pos + i] = val[i]; - }; - -/** - * Writes a sequence of bytes. - * @param {Uint8Array|string} value Buffer or base64 encoded string to write - * @returns {Writer} `this` - */ -Writer.prototype.bytes = function write_bytes(value) { - var len = value.length >>> 0; - if (!len) - return this._push(writeByte, 1, 0); - if (util.isString(value)) { - var buf = Writer.alloc(len = base64.length(value)); - base64.decode(value, buf, 0); - value = buf; - } - return this.uint32(len)._push(writeBytes, len, value); -}; - -/** - * Writes a string. - * @param {string} value Value to write - * @returns {Writer} `this` - */ -Writer.prototype.string = function write_string(value) { - var len = utf8.length(value); - return len - ? this.uint32(len)._push(utf8.write, len, value) - : this._push(writeByte, 1, 0); -}; - -/** - * Forks this writer's state by pushing it to a stack. - * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. - * @returns {Writer} `this` - */ -Writer.prototype.fork = function fork() { - this.states = new State(this); - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - return this; -}; - -/** - * Resets this instance to the last state. - * @returns {Writer} `this` - */ -Writer.prototype.reset = function reset() { - if (this.states) { - this.head = this.states.head; - this.tail = this.states.tail; - this.len = this.states.len; - this.states = this.states.next; - } else { - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - } - return this; -}; - -/** - * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. - * @returns {Writer} `this` - */ -Writer.prototype.ldelim = function ldelim() { - var head = this.head, - tail = this.tail, - len = this.len; - this.reset().uint32(len); - if (len) { - this.tail.next = head.next; // skip noop - this.tail = tail; - this.len += len; - } - return this; -}; - -/** - * Finishes the write operation. - * @returns {Uint8Array} Finished buffer - */ -Writer.prototype.finish = function finish() { - var head = this.head.next, // skip noop - buf = this.constructor.alloc(this.len), - pos = 0; - while (head) { - head.fn(head.val, buf, pos); - pos += head.len; - head = head.next; - } - // this.head = this.tail = null; - return buf; -}; - -Writer._configure = function(BufferWriter_) { - BufferWriter = BufferWriter_; - Writer.create = create(); - BufferWriter._configure(); -}; - - -/***/ }), - -/***/ 41863: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -module.exports = BufferWriter; - -// extends Writer -var Writer = __nccwpck_require__(13098); -(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; - -var util = __nccwpck_require__(71241); - -/** - * Constructs a new buffer writer instance. - * @classdesc Wire format writer using node buffers. - * @extends Writer - * @constructor - */ -function BufferWriter() { - Writer.call(this); -} - -BufferWriter._configure = function () { - /** - * Allocates a buffer of the specified size. - * @function - * @param {number} size Buffer size - * @returns {Buffer} Buffer - */ - BufferWriter.alloc = util._Buffer_allocUnsafe; - - BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" - ? function writeBytesBuffer_set(val, buf, pos) { - buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) - // also works for plain array values - } - /* istanbul ignore next */ - : function writeBytesBuffer_copy(val, buf, pos) { - if (val.copy) // Buffer values - val.copy(buf, pos, 0, val.length); - else for (var i = 0; i < val.length;) // plain array values - buf[pos++] = val[i++]; - }; -}; - - -/** - * @override - */ -BufferWriter.prototype.bytes = function write_bytes_buffer(value) { - if (util.isString(value)) - value = util._Buffer_from(value, "base64"); - var len = value.length >>> 0; - this.uint32(len); - if (len) - this._push(BufferWriter.writeBytesBuffer, len, value); - return this; -}; - -function writeStringBuffer(val, buf, pos) { - if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) - util.utf8.write(val, buf, pos); - else if (buf.utf8Write) - buf.utf8Write(val, pos); - else - buf.write(val, pos); -} - -/** - * @override - */ -BufferWriter.prototype.string = function write_string_buffer(value) { - var len = util.Buffer.byteLength(value); - this.uint32(len); - if (len) - this._push(writeStringBuffer, len, value); - return this; -}; - - -/** - * Finishes the write operation. - * @name BufferWriter#finish - * @function - * @returns {Buffer} Finished buffer - */ - -BufferWriter._configure(); - - -/***/ }), - -/***/ 63329: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -var parseUrl = (__nccwpck_require__(57310).parse); - -var DEFAULT_PORTS = { - ftp: 21, - gopher: 70, - http: 80, - https: 443, - ws: 80, - wss: 443, -}; - -var stringEndsWith = String.prototype.endsWith || function(s) { - return s.length <= this.length && - this.indexOf(s, this.length - s.length) !== -1; -}; - -/** - * @param {string|object} url - The URL, or the result from url.parse. - * @return {string} The URL of the proxy that should handle the request to the - * given URL. If no proxy is set, this will be an empty string. - */ -function getProxyForUrl(url) { - var parsedUrl = typeof url === 'string' ? parseUrl(url) : url || {}; - var proto = parsedUrl.protocol; - var hostname = parsedUrl.host; - var port = parsedUrl.port; - if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') { - return ''; // Don't proxy URLs without a valid scheme or host. - } - - proto = proto.split(':', 1)[0]; - // Stripping ports in this way instead of using parsedUrl.hostname to make - // sure that the brackets around IPv6 addresses are kept. - hostname = hostname.replace(/:\d*$/, ''); - port = parseInt(port) || DEFAULT_PORTS[proto] || 0; - if (!shouldProxy(hostname, port)) { - return ''; // Don't proxy URLs that match NO_PROXY. - } - - var proxy = - getEnv('npm_config_' + proto + '_proxy') || - getEnv(proto + '_proxy') || - getEnv('npm_config_proxy') || - getEnv('all_proxy'); - if (proxy && proxy.indexOf('://') === -1) { - // Missing scheme in proxy, default to the requested URL's scheme. - proxy = proto + '://' + proxy; - } - return proxy; -} - -/** - * Determines whether a given URL should be proxied. - * - * @param {string} hostname - The host name of the URL. - * @param {number} port - The effective port of the URL. - * @returns {boolean} Whether the given URL should be proxied. - * @private - */ -function shouldProxy(hostname, port) { - var NO_PROXY = - (getEnv('npm_config_no_proxy') || getEnv('no_proxy')).toLowerCase(); - if (!NO_PROXY) { - return true; // Always proxy if NO_PROXY is not set. - } - if (NO_PROXY === '*') { - return false; // Never proxy if wildcard is set. - } - - return NO_PROXY.split(/[,\s]/).every(function(proxy) { - if (!proxy) { - return true; // Skip zero-length hosts. - } - var parsedProxy = proxy.match(/^(.+):(\d+)$/); - var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy; - var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0; - if (parsedProxyPort && parsedProxyPort !== port) { - return true; // Skip if ports don't match. - } - - if (!/^[.*]/.test(parsedProxyHostname)) { - // No wildcards, so stop proxying if there is an exact match. - return hostname !== parsedProxyHostname; - } - - if (parsedProxyHostname.charAt(0) === '*') { - // Remove leading wildcard. - parsedProxyHostname = parsedProxyHostname.slice(1); - } - // Stop proxying if the hostname ends with the no_proxy host. - return !stringEndsWith.call(hostname, parsedProxyHostname); - }); -} - -/** - * Get the value for an environment variable. - * - * @param {string} key - The name of the environment variable. - * @return {string} The value of the environment variable. - * @private - */ -function getEnv(key) { - return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || ''; -} - -exports.getProxyForUrl = getProxyForUrl; - - -/***/ }), - -/***/ 18341: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var once = __nccwpck_require__(1223) -var eos = __nccwpck_require__(81205) -var fs - -try { - fs = __nccwpck_require__(57147) // we only need fs to get the ReadStream and WriteStream prototypes -} catch (e) {} - -var noop = function () {} -var ancient = typeof process === 'undefined' ? false : /^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 - - -/***/ }), - -/***/ 67214: -/***/ ((module) => { - -"use strict"; - - -const codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error - } - - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) - } - } - - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); - } - } - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - - codes[code] = NodeError; -} - -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; - } - } else { - return `of ${thing} ${String(expected)}`; - } -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; - } - - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); - -module.exports.q = codes; - - -/***/ }), - -/***/ 41359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - - - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -}; -/**/ - -module.exports = Duplex; -var Readable = __nccwpck_require__(51433); -var Writable = __nccwpck_require__(26993); -__nccwpck_require__(44124)(Duplex, Readable); -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -// the no-half-open enforcer -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(onEndNT, this); -} -function onEndNT(self) { - self.end(); -} -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); - -/***/ }), - -/***/ 81542: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - - - -module.exports = PassThrough; -var Transform = __nccwpck_require__(34415); -__nccwpck_require__(44124)(PassThrough, Transform); -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; - -/***/ }), - -/***/ 51433: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - - - -module.exports = Readable; - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = (__nccwpck_require__(82361).EventEmitter); -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = __nccwpck_require__(62387); -/**/ - -var Buffer = (__nccwpck_require__(14300).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ -var debugUtil = __nccwpck_require__(73837); -var debug; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - -var BufferList = __nccwpck_require__(52746); -var destroyImpl = __nccwpck_require__(97049); -var _require = __nccwpck_require__(39948), - getHighWaterMark = _require.getHighWaterMark; -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - -// Lazy loaded to improve the startup performance. -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; -__nccwpck_require__(44124)(Readable, Stream); -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); - - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(41359); - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; - - // Should close be emitted on destroy. Defaults to true. - this.emitClose = options.emitClose !== false; - - // Should .destroy() be called after 'end' (and potentially 'finish') - this.autoDestroy = !!options.autoDestroy; - - // has it been destroyed - this.destroyed = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(94841)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(41359); - if (!(this instanceof Readable)) return new Readable(options); - - // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); - - // legacy - this.readable = true; - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - Stream.call(this); -} -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } - - // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - return er; -} -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(94841)/* .StringDecoder */ .s); - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; - // If setEncoding(null), decoder.encoding equals utf8 - this._readableState.encoding = this._readableState.decoder.encoding; - - // Iterate over current buffer to convert already stored Buffers: - var p = this._readableState.buffer.head; - var content = ''; - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - this._readableState.buffer.clear(); - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; - -// Don't raise the hwm > 1GB -var MAX_HWM = 0x40000000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - if (ret !== null) this.emit('data', ret); - return ret; -}; -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } - - // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - return dest; -}; -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; - - // Try start flowing on next tick if stream isn't explicitly paused - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - return res; -}; -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - return res; -}; -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; - - // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - state.flowing = !state.readableListening; - resume(this, state); - } - state.paused = false; - return this; -}; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} -function resume_(stream, state) { - debug('resume', state.reading); - if (!state.reading) { - stream.read(0); - } - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - this._readableState.paused = true; - return this; -}; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null); -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } - - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - return this; -}; -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = __nccwpck_require__(43306); - } - return createReadableStreamAsyncIterator(this); - }; -} -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); - -// exposed for testing purposes only. -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); - - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = __nccwpck_require__(39082); - } - return from(Readable, iterable, opts); - }; -} -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} - -/***/ }), - -/***/ 34415: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - - -module.exports = Transform; -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; -var Duplex = __nccwpck_require__(41359); -__nccwpck_require__(44124)(Transform, Duplex); -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - ts.writechunk = null; - ts.writecb = null; - if (data != null) - // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } - - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); -} -function prefinish() { - var _this = this; - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) - // single equals check for both `null` and `undefined` - stream.push(data); - - // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} - -/***/ }), - -/***/ 26993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// 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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - - - -module.exports = Writable; - -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var internalUtil = { - deprecate: __nccwpck_require__(65278) -}; -/**/ - -/**/ -var Stream = __nccwpck_require__(62387); -/**/ - -var Buffer = (__nccwpck_require__(14300).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -var destroyImpl = __nccwpck_require__(97049); -var _require = __nccwpck_require__(39948), - getHighWaterMark = _require.getHighWaterMark; -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; -var errorOrDestroy = destroyImpl.errorOrDestroy; -__nccwpck_require__(44124)(Writable, Stream); -function nop() {} -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(41359); - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); - - // if _final has been called - this.finalCalled = false; - - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // has it been destroyed - this.destroyed = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // Should close be emitted on destroy. Defaults to true. - this.emitClose = options.emitClose !== false; - - // Should .destroy() be called after 'finish' (and potentially 'end') - this.autoDestroy = !!options.autoDestroy; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); - -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(41359); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); - - // legacy. - this.writable = true; - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); - // TODO: defer error events consistently everywhere, not just the cb - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} - -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var er; - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - return true; -} -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; -Writable.prototype.cork = function () { - this._writableState.corked++; -}; -Writable.prototype.uncork = function () { - var state = this._writableState; - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - return ret; -} -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - if (entry === null) state.lastBufferedRequest = null; - } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; -Writable.prototype._writev = null; -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending) endWritable(this, state, cb); - return this; -}; -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - errorOrDestroy(stream, err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - return need; -} -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - - // reuse the free corkReq. - state.corkedRequestsFree.next = corkReq; -} -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; - -/***/ }), - -/***/ 43306: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var _Object$setPrototypeO; -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -var finished = __nccwpck_require__(76080); -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - if (resolve !== null) { - var data = iter[kStream].read(); - // we defer if data is null - // we can be expecting either 'end' or - // 'error' - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - next: function next() { - var _this = this; - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - if (error !== null) { - return Promise.reject(error); - } - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } - - // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - var lastPromise = this[kLastPromise]; - var promise; - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - promise = new Promise(this[kHandlePromise]); - } - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; - // reject if we are waiting for data in the Promise - // returned by next() and store the error - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - iterator[kError] = err; - return; - } - var resolve = iterator[kLastResolve]; - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; -module.exports = createReadableStreamAsyncIterator; - -/***/ }), - -/***/ 52746: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -var _require = __nccwpck_require__(14300), - Buffer = _require.Buffer; -var _require2 = __nccwpck_require__(73837), - inspect = _require2.inspect; -var custom = inspect && inspect.custom || 'inspect'; -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} -module.exports = /*#__PURE__*/function () { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) ret += s + p.data; - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - } - - // Consumes a specified amount of bytes or characters from the buffered data. - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } - - // Consumes a specified amount of characters from the buffered data. - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - this.length -= c; - return ret; - } - - // Consumes a specified amount of bytes from the buffered data. - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - this.length -= c; - return ret; - } - - // Make sure the linked list only shows the minimal necessary information. - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread(_objectSpread({}, options), {}, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - return BufferList; -}(); - -/***/ }), - -/***/ 97049: -/***/ ((module) => { - -"use strict"; - - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - return this; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } - - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - return this; -} -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} -function emitErrorNT(self, err) { - self.emit('error', err); -} -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; - -/***/ }), - -/***/ 76080: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). - - - -var ERR_STREAM_PREMATURE_CLOSE = (__nccwpck_require__(67214)/* .codes.ERR_STREAM_PREMATURE_CLOSE */ .q.ERR_STREAM_PREMATURE_CLOSE); -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - callback.apply(this, args); - }; -} -function noop() {} -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - var writableEnded = stream._writableState && stream._writableState.finished; - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - var readableEnded = stream._readableState && stream._readableState.endEmitted; - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - var onerror = function onerror(err) { - callback.call(stream, err); - }; - var onclose = function onclose() { - var err; - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - var onrequest = function onrequest() { - 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 && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - 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('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} -module.exports = eos; - -/***/ }), - -/***/ 39082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -var ERR_INVALID_ARG_TYPE = (__nccwpck_require__(67214)/* .codes.ERR_INVALID_ARG_TYPE */ .q.ERR_INVALID_ARG_TYPE); -function from(Readable, iterable, opts) { - var iterator; - if (iterable && typeof iterable.next === 'function') { - iterator = iterable; - } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); - var readable = new Readable(_objectSpread({ - objectMode: true - }, opts)); - // Reading boolean to protect against _read - // being called before last iteration completion. - var reading = false; - readable._read = function () { - if (!reading) { - reading = true; - next(); - } - }; - function next() { - return _next2.apply(this, arguments); - } - function _next2() { - _next2 = _asyncToGenerator(function* () { - try { - var _yield$iterator$next = yield iterator.next(), - value = _yield$iterator$next.value, - done = _yield$iterator$next.done; - if (done) { - readable.push(null); - } else if (readable.push(yield value)) { - next(); - } else { - reading = false; - } - } catch (err) { - readable.destroy(err); - } - }); - return _next2.apply(this, arguments); - } - return readable; -} -module.exports = from; - - -/***/ }), - -/***/ 76989: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). - - - -var eos; -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = __nccwpck_require__(76080); - 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; - - // request.destroy just do .end - .abort is what we want - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} -function call(fn) { - fn(); -} -function pipe(from, to) { - return from.pipe(to); -} -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - 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 = pipeline; - -/***/ }), - -/***/ 39948: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var ERR_INVALID_OPT_VALUE = (__nccwpck_require__(67214)/* .codes.ERR_INVALID_OPT_VALUE */ .q.ERR_INVALID_OPT_VALUE); -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - return Math.floor(hwm); - } - - // Default value - return state.objectMode ? 16 : 16 * 1024; -} -module.exports = { - getHighWaterMark: getHighWaterMark -}; - -/***/ }), - -/***/ 62387: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(12781); - - -/***/ }), - -/***/ 51642: -/***/ ((module, exports, __nccwpck_require__) => { - -var Stream = __nccwpck_require__(12781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream.Readable; - Object.assign(module.exports, Stream); - module.exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(51433); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(26993); - exports.Duplex = __nccwpck_require__(41359); - exports.Transform = __nccwpck_require__(34415); - exports.PassThrough = __nccwpck_require__(81542); - exports.finished = __nccwpck_require__(76080); - exports.pipeline = __nccwpck_require__(76989); -} - - -/***/ }), - -/***/ 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 - - -/***/ }), - -/***/ 39798: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var fs = __nccwpck_require__(57147); - -module.exports = function (filepath, split, encoding) { - split = typeof split !== 'undefined' ? split : "\n"; - encoding = typeof encoding !== 'undefined' ? encoding : "utf8"; - - var ca = []; - var chain = fs.readFileSync(filepath, encoding); - if(chain.indexOf("-END CERTIFICATE-") < 0 || chain.indexOf("-BEGIN CERTIFICATE-") < 0){ - throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'"); - } - chain = chain.split(split); - var cert = []; - var _i, _len; - for (_i = 0, _len = chain.length; _i < _len; _i++) { - var line = chain[_i]; - if (!(line.length !== 0)) { - continue; - } - cert.push(line); - if (line.match(/-END CERTIFICATE-/)) { - ca.push(cert.join(split)); - cert = []; - } - } - return ca; -} - - -/***/ }), - -/***/ 83204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - Duplex: DuplexStream, - Readable: ReadableStream, - Writable: WritableStream, -} = __nccwpck_require__(12781); - -const { - CHANNEL_EXTENDED_DATATYPE: { STDERR }, -} = __nccwpck_require__(36832); -const { bufferSlice } = __nccwpck_require__(49475); - -const PACKET_SIZE = 32 * 1024; -const MAX_WINDOW = 2 * 1024 * 1024; -const WINDOW_THRESHOLD = MAX_WINDOW / 2; - -class ClientStderr extends ReadableStream { - constructor(channel, streamOpts) { - super(streamOpts); - - this._channel = channel; - } - _read(n) { - if (this._channel._waitChanDrain) { - this._channel._waitChanDrain = false; - if (this._channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this._channel); - } - } -} - -class ServerStderr extends WritableStream { - constructor(channel) { - super({ highWaterMark: MAX_WINDOW }); - - this._channel = channel; - } - - _write(data, encoding, cb) { - const channel = this._channel; - const protocol = channel._client._protocol; - const outgoing = channel.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelExtData(id, data, STDERR); - else - protocol.channelExtData(id, bufferSlice(data, p, p + sliceLen), STDERR); - - p += sliceLen; - window -= sliceLen; - } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - channel._waitWindow = true; - if (p > 0) - channel._chunkErr = bufferSlice(data, p, len); - else - channel._chunkErr = data; - channel._chunkcbErr = cb; - return; - } - - cb(); - } -} - -class Channel extends DuplexStream { - constructor(client, info, opts) { - const streamOpts = { - highWaterMark: MAX_WINDOW, - allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false)), - emitClose: false, - }; - super(streamOpts); - this.allowHalfOpen = streamOpts.allowHalfOpen; - - const server = !!(opts && opts.server); - - this.server = server; - this.type = info.type; - this.subtype = undefined; - - /* - incoming and outgoing contain these properties: - { - id: undefined, - window: undefined, - packetSize: undefined, - state: 'closed' - } - */ - this.incoming = info.incoming; - this.outgoing = info.outgoing; - this._callbacks = []; - - this._client = client; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - - this.stdin = this.stdout = this; - - if (server) - this.stderr = new ServerStderr(this); - else - this.stderr = new ClientStderr(this, streamOpts); - - // Outgoing data - this._waitWindow = false; // SSH-level backpressure - - // Incoming data - this._waitChanDrain = false; // Channel Readable side backpressure - - this._chunk = undefined; - this._chunkcb = undefined; - this._chunkErr = undefined; - this._chunkcbErr = undefined; - - this.on('finish', onFinish) - .on('prefinish', onFinish); // For node v0.11+ - - this.on('end', onEnd).on('close', onEnd); - } - - _read(n) { - if (this._waitChanDrain) { - this._waitChanDrain = false; - if (this.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(this); - } - } - - _write(data, encoding, cb) { - const protocol = this._client._protocol; - const outgoing = this.outgoing; - const packetSize = outgoing.packetSize; - const id = outgoing.id; - let window = outgoing.window; - const len = data.length; - let p = 0; - - if (outgoing.state !== 'open') - return; - - while (len - p > 0 && window > 0) { - let sliceLen = len - p; - if (sliceLen > window) - sliceLen = window; - if (sliceLen > packetSize) - sliceLen = packetSize; - - if (p === 0 && sliceLen === len) - protocol.channelData(id, data); - else - protocol.channelData(id, bufferSlice(data, p, p + sliceLen)); - - p += sliceLen; - window -= sliceLen; - } - - outgoing.window = window; - - if (len - p > 0) { - if (window === 0) - this._waitWindow = true; - if (p > 0) - this._chunk = bufferSlice(data, p, len); - else - this._chunk = data; - this._chunkcb = cb; - return; - } - - cb(); - } - - eof() { - if (this.outgoing.state === 'open') { - this.outgoing.state = 'eof'; - this._client._protocol.channelEOF(this.outgoing.id); - } - } - - close() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._client._protocol.channelClose(this.outgoing.id); - } - } - - destroy() { - this.end(); - this.close(); - return this; - } - - // Session type-specific methods ============================================= - setWindow(rows, cols, height, width) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && (this.subtype === 'shell' || this.subtype === 'exec') - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.windowChange(this.outgoing.id, - rows, - cols, - height, - width); - } - } - - signal(signalName) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - this._client._protocol.signal(this.outgoing.id, signalName); - } - } - - exit(statusOrSignal, coreDumped, msg) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (this.type === 'session' - && this.writable - && this.outgoing.state === 'open') { - if (typeof statusOrSignal === 'number') { - this._client._protocol.exitStatus(this.outgoing.id, statusOrSignal); - } else { - this._client._protocol.exitSignal(this.outgoing.id, - statusOrSignal, - coreDumped, - msg); - } - } - } - -} - -function onFinish() { - this.eof(); - if (this.server || !this.allowHalfOpen) - this.close(); - this.writable = false; -} - -function onEnd() { - this.readable = false; -} - -function windowAdjust(self) { - if (self.outgoing.state === 'closed') - return; - const amt = MAX_WINDOW - self.incoming.window; - if (amt <= 0) - return; - self.incoming.window += amt; - self._client._protocol.channelWindowAdjust(self.outgoing.id, amt); -} - -module.exports = { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -}; - - -/***/ }), - -/***/ 49054: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Socket } = __nccwpck_require__(41808); -const { Duplex } = __nccwpck_require__(12781); -const { resolve } = __nccwpck_require__(71017); -const { readFile } = __nccwpck_require__(57147); -const { execFile, spawn } = __nccwpck_require__(32081); - -const { isParsedKey, parseKey } = __nccwpck_require__(22218); - -const { - makeBufferParser, - readUInt32BE, - writeUInt32BE, - writeUInt32LE, -} = __nccwpck_require__(49475); - -function once(cb) { - let called = false; - return (...args) => { - if (called) - return; - called = true; - cb(...args); - }; -} - -function concat(buf1, buf2) { - const combined = Buffer.allocUnsafe(buf1.length + buf2.length); - buf1.copy(combined, 0); - buf2.copy(combined, buf1.length); - return combined; -} - -function noop() {} - -const EMPTY_BUF = Buffer.alloc(0); - -const binaryParser = makeBufferParser(); - -class BaseAgent { - getIdentities(cb) { - cb(new Error('Missing getIdentities() implementation')); - } - sign(pubKey, data, options, cb) { - if (typeof options === 'function') - cb = options; - cb(new Error('Missing sign() implementation')); - } -} - -class OpenSSHAgent extends BaseAgent { - constructor(socketPath) { - super(); - this.socketPath = socketPath; - } - - getStream(cb) { - cb = once(cb); - const sock = new Socket(); - sock.on('connect', () => { - cb(null, sock); - }); - sock.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - sock.connect(this.socketPath); - - function onFail() { - try { - sock.destroy(); - } catch {} - - cb(new Error('Failed to connect to agent')); - } - } - - getIdentities(cb) { - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to retrieve identities from agent'); - cb(err); - } - - if (err) - return onFail(err); - - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - - protocol.getIdentities((err, keys) => { - if (err) - return onFail(err); - try { - stream.destroy(); - } catch {} - cb(null, keys); - }); - }); - } - - sign(pubKey, data, options, cb) { - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } - - cb = once(cb); - this.getStream((err, stream) => { - function onFail(err) { - if (stream) { - try { - stream.destroy(); - } catch {} - } - if (!err) - err = new Error('Failed to sign data with agent'); - cb(err); - } - - if (err) - return onFail(err); - - const protocol = new AgentProtocol(true); - protocol.on('error', onFail); - protocol.pipe(stream).pipe(protocol); - - stream.on('close', onFail) - .on('end', onFail) - .on('error', onFail); - - protocol.sign(pubKey, data, options, (err, sig) => { - if (err) - return onFail(err); - - try { - stream.destroy(); - } catch {} - - cb(null, sig); - }); - }); - } -} - -const PageantAgent = (() => { - const RET_ERR_BADARGS = 10; - const RET_ERR_UNAVAILABLE = 11; - const RET_ERR_NOMAP = 12; - const RET_ERR_BINSTDIN = 13; - const RET_ERR_BINSTDOUT = 14; - const RET_ERR_BADLEN = 15; - - const EXEPATH = __nccwpck_require__.ab + "pagent.exe"; - const ERROR = { - [RET_ERR_BADARGS]: new Error('Invalid pagent.exe arguments'), - [RET_ERR_UNAVAILABLE]: new Error('Pageant is not running'), - [RET_ERR_NOMAP]: new Error('pagent.exe could not create an mmap'), - [RET_ERR_BINSTDIN]: new Error('pagent.exe could not set mode for stdin'), - [RET_ERR_BINSTDOUT]: new Error('pagent.exe could not set mode for stdout'), - [RET_ERR_BADLEN]: - new Error('pagent.exe did not get expected input payload'), - }; - - function destroy(stream) { - stream.buffer = null; - if (stream.proc) { - stream.proc.kill(); - stream.proc = undefined; - } - } - - class PageantSocket extends Duplex { - constructor() { - super(); - this.proc = undefined; - this.buffer = null; - } - _read(n) {} - _write(data, encoding, cb) { - if (this.buffer === null) { - this.buffer = data; - } else { - const newBuffer = Buffer.allocUnsafe(this.buffer.length + data.length); - this.buffer.copy(newBuffer, 0); - data.copy(newBuffer, this.buffer.length); - this.buffer = newBuffer; - } - // Wait for at least all length bytes - if (this.buffer.length < 4) - return cb(); - - const len = readUInt32BE(this.buffer, 0); - // Make sure we have a full message before querying pageant - if ((this.buffer.length - 4) < len) - return cb(); - - data = this.buffer.slice(0, 4 + len); - if (this.buffer.length > (4 + len)) - return cb(new Error('Unexpected multiple agent requests')); - this.buffer = null; - - let error; - const proc = this.proc = spawn(__nccwpck_require__.ab + "pagent.exe", [ data.length ]); - proc.stdout.on('data', (data) => { - this.push(data); - }); - proc.on('error', (err) => { - error = err; - cb(error); - }); - proc.on('close', (code) => { - this.proc = undefined; - if (!error) { - if (error = ERROR[code]) - return cb(error); - cb(); - } - }); - proc.stdin.end(data); - } - _final(cb) { - destroy(this); - cb(); - } - _destroy(err, cb) { - destroy(this); - cb(); - } - } - - return class PageantAgent extends OpenSSHAgent { - getStream(cb) { - cb(null, new PageantSocket()); - } - }; -})(); - -const CygwinAgent = (() => { - const RE_CYGWIN_SOCK = /^!(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/; - - return class CygwinAgent extends OpenSSHAgent { - getStream(cb) { - cb = once(cb); - - // The cygwin ssh-agent connection process looks like this: - // 1. Read the "socket" as a file to get the underlying TCP port and a - // special "secret" that must be sent to the TCP server. - // 2. Connect to the server listening on localhost at the TCP port. - // 3. Send the "secret" to the server. - // 4. The server sends back the same "secret". - // 5. Send three 32-bit integer values of zero. This is ordinarily the - // pid, uid, and gid of this process, but cygwin will actually - // send us the correct values as a response. - // 6. The server sends back the pid, uid, gid. - // 7. Disconnect. - // 8. Repeat steps 2-6, except send the received pid, uid, and gid in - // step 5 instead of zeroes. - // 9. Connection is ready to be used. - - let socketPath = this.socketPath; - let triedCygpath = false; - readFile(socketPath, function readCygsocket(err, data) { - if (err) { - if (triedCygpath) - return cb(new Error('Invalid cygwin unix socket path')); - - // Try using `cygpath` to convert a possible *nix-style path to the - // real Windows path before giving up ... - execFile('cygpath', ['-w', socketPath], (err, stdout, stderr) => { - if (err || stdout.length === 0) - return cb(new Error('Invalid cygwin unix socket path')); - - triedCygpath = true; - socketPath = stdout.toString().replace(/[\r\n]/g, ''); - readFile(socketPath, readCygsocket); - }); - return; - } - - const m = RE_CYGWIN_SOCK.exec(data.toString('ascii')); - if (!m) - return cb(new Error('Malformed cygwin unix socket file')); - - let state; - let bc = 0; - let isRetrying = false; - const inBuf = []; - let sock; - - // Use 0 for pid, uid, and gid to ensure we get an error and also - // a valid uid and gid from cygwin so that we don't have to figure it - // out ourselves - let credsBuf = Buffer.alloc(12); - - // Parse cygwin unix socket file contents - const port = parseInt(m[1], 10); - const secret = m[2].replace(/-/g, ''); - const secretBuf = Buffer.allocUnsafe(16); - for (let i = 0, j = 0; j < 32; ++i, j += 2) - secretBuf[i] = parseInt(secret.substring(j, j + 2), 16); - - // Convert to host order (always LE for Windows) - for (let i = 0; i < 16; i += 4) - writeUInt32LE(secretBuf, readUInt32BE(secretBuf, i), i); - - tryConnect(); - - function _onconnect() { - bc = 0; - state = 'secret'; - sock.write(secretBuf); - } - - function _ondata(data) { - bc += data.length; - - if (state === 'secret') { - // The secret we sent is echoed back to us by cygwin, not sure of - // the reason for that, but we ignore it nonetheless ... - if (bc === 16) { - bc = 0; - state = 'creds'; - sock.write(credsBuf); - } - return; - } - - if (state === 'creds') { - // If this is the first attempt, make sure to gather the valid - // uid and gid for our next attempt - if (!isRetrying) - inBuf.push(data); - - if (bc === 12) { - sock.removeListener('connect', _onconnect); - sock.removeListener('data', _ondata); - sock.removeListener('error', onFail); - sock.removeListener('end', onFail); - sock.removeListener('close', onFail); - - if (isRetrying) - return cb(null, sock); - - isRetrying = true; - credsBuf = Buffer.concat(inBuf); - writeUInt32LE(credsBuf, process.pid, 0); - sock.on('error', () => {}); - sock.destroy(); - - tryConnect(); - } - } - } - - function onFail() { - cb(new Error('Problem negotiating cygwin unix socket security')); - } - - function tryConnect() { - sock = new Socket(); - sock.on('connect', _onconnect); - sock.on('data', _ondata); - sock.on('error', onFail); - sock.on('end', onFail); - sock.on('close', onFail); - sock.connect(port); - } - }); - } - }; -})(); - -// Format of `//./pipe/ANYTHING`, with forward slashes and backward slashes -// being interchangeable -const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/; -function createAgent(path) { - if (process.platform === 'win32' && !WINDOWS_PIPE_REGEX.test(path)) { - return (path === 'pageant' - ? new PageantAgent() - : new CygwinAgent(path)); - } - return new OpenSSHAgent(path); -} - -const AgentProtocol = (() => { - // Client->Server messages - const SSH_AGENTC_REQUEST_IDENTITIES = 11; - const SSH_AGENTC_SIGN_REQUEST = 13; - // const SSH_AGENTC_ADD_IDENTITY = 17; - // const SSH_AGENTC_REMOVE_IDENTITY = 18; - // const SSH_AGENTC_REMOVE_ALL_IDENTITIES = 19; - // const SSH_AGENTC_ADD_SMARTCARD_KEY = 20; - // const SSH_AGENTC_REMOVE_SMARTCARD_KEY = 21; - // const SSH_AGENTC_LOCK = 22; - // const SSH_AGENTC_UNLOCK = 23; - // const SSH_AGENTC_ADD_ID_CONSTRAINED = 25; - // const SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED = 26; - // const SSH_AGENTC_EXTENSION = 27; - // Server->Client messages - const SSH_AGENT_FAILURE = 5; - // const SSH_AGENT_SUCCESS = 6; - const SSH_AGENT_IDENTITIES_ANSWER = 12; - const SSH_AGENT_SIGN_RESPONSE = 14; - // const SSH_AGENT_EXTENSION_FAILURE = 28; - - // const SSH_AGENT_CONSTRAIN_LIFETIME = 1; - // const SSH_AGENT_CONSTRAIN_CONFIRM = 2; - // const SSH_AGENT_CONSTRAIN_EXTENSION = 255; - - const SSH_AGENT_RSA_SHA2_256 = (1 << 1); - const SSH_AGENT_RSA_SHA2_512 = (1 << 2); - - const ROLE_CLIENT = 0; - const ROLE_SERVER = 1; - - // Ensures that responses get sent back in the same order the requests were - // received - function processResponses(protocol) { - let ret; - while (protocol[SYM_REQS].length) { - const nextResponse = protocol[SYM_REQS][0][SYM_RESP]; - if (nextResponse === undefined) - break; - - protocol[SYM_REQS].shift(); - ret = protocol.push(nextResponse); - } - return ret; - } - - const SYM_TYPE = Symbol('Inbound Request Type'); - const SYM_RESP = Symbol('Inbound Request Response'); - const SYM_CTX = Symbol('Inbound Request Context'); - class AgentInboundRequest { - constructor(type, ctx) { - this[SYM_TYPE] = type; - this[SYM_RESP] = undefined; - this[SYM_CTX] = ctx; - } - hasResponded() { - return (this[SYM_RESP] !== undefined); - } - getType() { - return this[SYM_TYPE]; - } - getContext() { - return this[SYM_CTX]; - } - } - function respond(protocol, req, data) { - req[SYM_RESP] = data; - return processResponses(protocol); - } - - function cleanup(protocol) { - protocol[SYM_BUFFER] = null; - if (protocol[SYM_MODE] === ROLE_CLIENT) { - const reqs = protocol[SYM_REQS]; - if (reqs && reqs.length) { - protocol[SYM_REQS] = []; - for (const req of reqs) - req.cb(new Error('No reply from server')); - } - } - - // Node streams hackery to make streams do the "right thing" - try { - protocol.end(); - } catch {} - setImmediate(() => { - if (!protocol[SYM_ENDED]) - protocol.emit('end'); - if (!protocol[SYM_CLOSED]) - protocol.emit('close'); - }); - } - - function onClose() { - this[SYM_CLOSED] = true; - } - - function onEnd() { - this[SYM_ENDED] = true; - } - - const SYM_REQS = Symbol('Requests'); - const SYM_MODE = Symbol('Agent Protocol Role'); - const SYM_BUFFER = Symbol('Agent Protocol Buffer'); - const SYM_MSGLEN = Symbol('Agent Protocol Current Message Length'); - const SYM_CLOSED = Symbol('Agent Protocol Closed'); - const SYM_ENDED = Symbol('Agent Protocol Ended'); - // Implementation based on: - // https://tools.ietf.org/html/draft-miller-ssh-agent-04 - return class AgentProtocol extends Duplex { - /* - Notes: - - `constraint` type consists of: - byte constraint_type - byte[] constraint_data - where `constraint_type` is one of: - * SSH_AGENT_CONSTRAIN_LIFETIME - - `constraint_data` consists of: - uint32 seconds - * SSH_AGENT_CONSTRAIN_CONFIRM - - `constraint_data` N/A - * SSH_AGENT_CONSTRAIN_EXTENSION - - `constraint_data` consists of: - string extension name - byte[] extension-specific details - */ - - constructor(isClient) { - super({ autoDestroy: true, emitClose: false }); - this[SYM_MODE] = (isClient ? ROLE_CLIENT : ROLE_SERVER); - this[SYM_REQS] = []; - this[SYM_BUFFER] = null; - this[SYM_MSGLEN] = -1; - this.once('end', onEnd); - this.once('close', onClose); - } - - _read(n) {} - - _write(data, encoding, cb) { - /* - Messages are of the format: - uint32 message length - byte message type - byte[message length - 1] message contents - */ - if (this[SYM_BUFFER] === null) - this[SYM_BUFFER] = data; - else - this[SYM_BUFFER] = concat(this[SYM_BUFFER], data); - - let buffer = this[SYM_BUFFER]; - let bufferLen = buffer.length; - - let p = 0; - while (p < bufferLen) { - // Wait for length + type - if (bufferLen < 5) - break; - - if (this[SYM_MSGLEN] === -1) - this[SYM_MSGLEN] = readUInt32BE(buffer, p); - - // Check if we have the entire message - if (bufferLen < (4 + this[SYM_MSGLEN])) - break; - - const msgType = buffer[p += 4]; - ++p; - - if (this[SYM_MODE] === ROLE_CLIENT) { - if (this[SYM_REQS].length === 0) - return cb(new Error('Received unexpected message from server')); - - const req = this[SYM_REQS].shift(); - - switch (msgType) { - case SSH_AGENT_FAILURE: - req.cb(new Error('Agent responded with failure')); - break; - case SSH_AGENT_IDENTITIES_ANSWER: { - if (req.type !== SSH_AGENTC_REQUEST_IDENTITIES) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - binaryParser.init(buffer, p); - - const numKeys = binaryParser.readUInt32BE(); - - if (numKeys === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const keys = []; - for (let i = 0; i < numKeys; ++i) { - let pubKey = binaryParser.readString(); - if (pubKey === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - const comment = binaryParser.readString(true); - if (comment === undefined) { - binaryParser.clear(); - return cb(new Error('Malformed agent response')); - } - - pubKey = parseKey(pubKey); - // We continue parsing the packet if we encounter an error - // in case the error is due to the key being an unsupported - // type - if (pubKey instanceof Error) - continue; - - pubKey.comment = pubKey.comment || comment; - - keys.push(pubKey); - } - p = binaryParser.pos(); - binaryParser.clear(); - - req.cb(null, keys); - break; - } - case SSH_AGENT_SIGN_RESPONSE: { - if (req.type !== SSH_AGENTC_SIGN_REQUEST) - return cb(new Error('Agent responded with wrong message type')); - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - binaryParser.init(buffer, p); - let signature = binaryParser.readString(); - p = binaryParser.pos(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed agent response')); - - // We strip the algorithm from OpenSSH's output and assume it's - // using the algorithm we specified. This makes it easier on - // custom Agent implementations so they don't have to construct - // the correct binary format for a (OpenSSH-style) signature. - - // TODO: verify signature type based on key and options used - // during initial sign request - binaryParser.init(signature, 0); - binaryParser.readString(true); - signature = binaryParser.readString(); - binaryParser.clear(); - - if (signature === undefined) - return cb(new Error('Malformed OpenSSH signature format')); - - req.cb(null, signature); - break; - } - default: - return cb( - new Error('Agent responded with unsupported message type') - ); - } - } else { - switch (msgType) { - case SSH_AGENTC_REQUEST_IDENTITIES: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - this.emit('identities', req); - break; - } - case SSH_AGENTC_SIGN_REQUEST: { - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - binaryParser.init(buffer, p); - let pubKey = binaryParser.readString(); - const data = binaryParser.readString(); - const flagsVal = binaryParser.readUInt32BE(); - p = binaryParser.pos(); - binaryParser.clear(); - if (flagsVal === undefined) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - return this.failureReply(req); - } - - const flags = { - hash: undefined, - }; - let ctx; - if (pubKey.type === 'ssh-rsa') { - if (flagsVal & SSH_AGENT_RSA_SHA2_256) { - ctx = 'rsa-sha2-256'; - flags.hash = 'sha256'; - } else if (flagsVal & SSH_AGENT_RSA_SHA2_512) { - ctx = 'rsa-sha2-512'; - flags.hash = 'sha512'; - } - } - if (ctx === undefined) - ctx = pubKey.type; - - const req = new AgentInboundRequest(msgType, ctx); - this[SYM_REQS].push(req); - - this.emit('sign', req, pubKey, data, flags); - break; - } - default: { - const req = new AgentInboundRequest(msgType); - this[SYM_REQS].push(req); - this.failureReply(req); - } - } - } - - // Get ready for next message - this[SYM_MSGLEN] = -1; - if (p === bufferLen) { - // Nothing left to process for now - this[SYM_BUFFER] = null; - break; - } else { - this[SYM_BUFFER] = buffer = buffer.slice(p); - bufferLen = buffer.length; - p = 0; - } - } - - cb(); - } - - _destroy(err, cb) { - cleanup(this); - cb(); - } - - _final(cb) { - cleanup(this); - cb(); - } - - // Client->Server messages ================================================= - sign(pubKey, data, options, cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - if (typeof options === 'function') { - cb = options; - options = undefined; - } else if (typeof options !== 'object' || options === null) { - options = undefined; - } - - let flags = 0; - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid public key argument'); - - if (pubKey.type === 'ssh-rsa' && options) { - switch (options.hash) { - case 'sha256': - flags = SSH_AGENT_RSA_SHA2_256; - break; - case 'sha512': - flags = SSH_AGENT_RSA_SHA2_512; - break; - } - } - pubKey = pubKey.getPublicSSH(); - - /* - byte SSH_AGENTC_SIGN_REQUEST - string key_blob - string data - uint32 flags - */ - const type = SSH_AGENTC_SIGN_REQUEST; - const keyLen = pubKey.length; - const dataLen = data.length; - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + keyLen + 4 + dataLen + 4); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - writeUInt32BE(buf, keyLen, ++p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, dataLen, p += keyLen); - data.copy(buf, p += 4); - - writeUInt32BE(buf, flags, p += dataLen); - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); - } - getIdentities(cb) { - if (this[SYM_MODE] !== ROLE_CLIENT) - throw new Error('Client-only method called with server role'); - - /* - byte SSH_AGENTC_REQUEST_IDENTITIES - */ - const type = SSH_AGENTC_REQUEST_IDENTITIES; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = type; - - if (typeof cb !== 'function') - cb = noop; - - this[SYM_REQS].push({ type, cb }); - - return this.push(buf); - } - - // Server->Client messages ================================================= - failureReply(req) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_FAILURE; - - return respond(this, req, buf); - } - getIdentitiesReply(req, keys) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_IDENTITIES_ANSWER - uint32 nkeys - - where `nkeys` is 0 or more of: - string key blob - string comment - */ - - if (req.getType() !== SSH_AGENTC_REQUEST_IDENTITIES) - throw new Error('Invalid response to request'); - - if (!Array.isArray(keys)) - throw new Error('Keys argument must be an array'); - - let totalKeysLen = 4; // Include `nkeys` size - - const newKeys = []; - for (let i = 0; i < keys.length; ++i) { - const entry = keys[i]; - if (typeof entry !== 'object' || entry === null) - throw new Error(`Invalid key entry: ${entry}`); - - let pubKey; - let comment; - if (isParsedKey(entry)) { - pubKey = entry; - } else if (isParsedKey(entry.pubKey)) { - pubKey = entry.pubKey; - } else { - if (typeof entry.pubKey !== 'object' || entry.pubKey === null) - continue; - ({ pubKey, comment } = entry.pubKey); - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - continue; // TODO: add debug output - } - comment = pubKey.comment || comment; - pubKey = pubKey.getPublicSSH(); - - totalKeysLen += 4 + pubKey.length; - - if (comment && typeof comment === 'string') - comment = Buffer.from(comment); - else if (!Buffer.isBuffer(comment)) - comment = EMPTY_BUF; - - totalKeysLen += 4 + comment.length; - - newKeys.push({ pubKey, comment }); - } - - let p = 0; - const buf = Buffer.allocUnsafe(4 + 1 + totalKeysLen); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_IDENTITIES_ANSWER; - - writeUInt32BE(buf, newKeys.length, ++p); - p += 4; - for (let i = 0; i < newKeys.length; ++i) { - const { pubKey, comment } = newKeys[i]; - - writeUInt32BE(buf, pubKey.length, p); - pubKey.copy(buf, p += 4); - - writeUInt32BE(buf, comment.length, p += pubKey.length); - p += 4; - if (comment.length) { - comment.copy(buf, p); - p += comment.length; - } - } - - return respond(this, req, buf); - } - signReply(req, signature) { - if (this[SYM_MODE] !== ROLE_SERVER) - throw new Error('Server-only method called with client role'); - - if (!(req instanceof AgentInboundRequest)) - throw new Error('Wrong request argument'); - - if (req.hasResponded()) - return true; - - /* - byte SSH_AGENT_SIGN_RESPONSE - string signature - */ - - if (req.getType() !== SSH_AGENTC_SIGN_REQUEST) - throw new Error('Invalid response to request'); - - if (!Buffer.isBuffer(signature)) - throw new Error('Signature argument must be a Buffer'); - - if (signature.length === 0) - throw new Error('Signature argument must be non-empty'); - - /* - OpenSSH agent signatures are encoded as: - - string signature format identifier (as specified by the - public key/certificate format) - byte[n] signature blob in format specific encoding. - - This is actually a `string` for: rsa, dss, ecdsa, and ed25519 - types - */ - - let p = 0; - const sigFormat = req.getContext(); - const sigFormatLen = Buffer.byteLength(sigFormat); - const buf = Buffer.allocUnsafe( - 4 + 1 + 4 + 4 + sigFormatLen + 4 + signature.length - ); - - writeUInt32BE(buf, buf.length - 4, p); - - buf[p += 4] = SSH_AGENT_SIGN_RESPONSE; - - writeUInt32BE(buf, 4 + sigFormatLen + 4 + signature.length, ++p); - writeUInt32BE(buf, sigFormatLen, p += 4); - buf.utf8Write(sigFormat, p += 4, sigFormatLen); - writeUInt32BE(buf, signature.length, p += sigFormatLen); - signature.copy(buf, p += 4); - - return respond(this, req, buf); - } - }; -})(); - -const SYM_AGENT = Symbol('Agent'); -const SYM_AGENT_KEYS = Symbol('Agent Keys'); -const SYM_AGENT_KEYS_IDX = Symbol('Agent Keys Index'); -const SYM_AGENT_CBS = Symbol('Agent Init Callbacks'); -class AgentContext { - constructor(agent) { - if (typeof agent === 'string') - agent = createAgent(agent); - else if (!isAgent(agent)) - throw new Error('Invalid agent argument'); - this[SYM_AGENT] = agent; - this[SYM_AGENT_KEYS] = null; - this[SYM_AGENT_KEYS_IDX] = -1; - this[SYM_AGENT_CBS] = null; - } - init(cb) { - if (typeof cb !== 'function') - cb = noop; - - if (this[SYM_AGENT_KEYS] === null) { - if (this[SYM_AGENT_CBS] === null) { - this[SYM_AGENT_CBS] = [cb]; - - const doCbs = (...args) => { - process.nextTick(() => { - const cbs = this[SYM_AGENT_CBS]; - this[SYM_AGENT_CBS] = null; - for (const cb of cbs) - cb(...args); - }); - }; - - this[SYM_AGENT].getIdentities(once((err, keys) => { - if (err) - return doCbs(err); - - if (!Array.isArray(keys)) { - return doCbs(new Error( - 'Agent implementation failed to provide keys' - )); - } - - const newKeys = []; - for (let key of keys) { - key = parseKey(key); - if (key instanceof Error) { - // TODO: add debug output - continue; - } - newKeys.push(key); - } - - this[SYM_AGENT_KEYS] = newKeys; - this[SYM_AGENT_KEYS_IDX] = -1; - doCbs(); - })); - } else { - this[SYM_AGENT_CBS].push(cb); - } - } else { - process.nextTick(cb); - } - } - nextKey() { - if (this[SYM_AGENT_KEYS] === null - || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return false; - } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - currentKey() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return null; - } - - return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]]; - } - pos() { - if (this[SYM_AGENT_KEYS] === null - || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) { - return -1; - } - - return this[SYM_AGENT_KEYS_IDX]; - } - reset() { - this[SYM_AGENT_KEYS_IDX] = -1; - } - - sign(...args) { - this[SYM_AGENT].sign(...args); - } -} - -function isAgent(val) { - return (val instanceof BaseAgent); -} - -module.exports = { - AgentContext, - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - isAgent, - OpenSSHAgent, - PageantAgent, -}; - - -/***/ }), - -/***/ 36063: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// TODO: -// * add `.connected` or similar property to allow immediate connection -// status checking -// * add/improve debug output during user authentication phase - - -const { - createHash, - getHashes, - randomFillSync, -} = __nccwpck_require__(6113); -const { Socket } = __nccwpck_require__(41808); -const { lookup: dnsLookup } = __nccwpck_require__(9523); -const EventEmitter = __nccwpck_require__(82361); -const HASHES = getHashes(); - -const { - COMPAT, - CHANNEL_EXTENDED_DATATYPE: { STDERR }, - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(36832); -const { init: cryptoInit } = __nccwpck_require__(45708); -const Protocol = __nccwpck_require__(59031); -const { parseKey } = __nccwpck_require__(22218); -const { SFTP } = __nccwpck_require__(52026); -const { - bufferCopy, - makeBufferParser, - makeError, - readUInt32BE, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const { AgentContext, createAgent, isAgent } = __nccwpck_require__(49054); -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(83204); -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(40834); - -const bufferParser = makeBufferParser(); -const sigParser = makeBufferParser(); -const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/; -const noop = (err) => {}; - -class Client extends EventEmitter { - constructor() { - super(); - - this.config = { - host: undefined, - port: undefined, - localAddress: undefined, - localPort: undefined, - forceIPv4: undefined, - forceIPv6: undefined, - keepaliveCountMax: undefined, - keepaliveInterval: undefined, - readyTimeout: undefined, - ident: undefined, - - username: undefined, - password: undefined, - privateKey: undefined, - tryKeyboard: undefined, - agent: undefined, - allowAgentFwd: undefined, - authHandler: undefined, - - hostHashAlgo: undefined, - hostHashCb: undefined, - strictVendor: undefined, - debug: undefined - }; - - this._agent = undefined; - this._readyTimeout = undefined; - this._chanMgr = undefined; - this._callbacks = undefined; - this._forwarding = undefined; - this._forwardingUnix = undefined; - this._acceptX11 = undefined; - this._agentFwdEnabled = undefined; - this._remoteVer = undefined; - - this._protocol = undefined; - this._sock = undefined; - this._resetKA = undefined; - } - - connect(cfg) { - if (this._sock && isWritable(this._sock)) { - this.once('close', () => { - this.connect(cfg); - }); - this.end(); - return this; - } - - this.config.host = cfg.hostname || cfg.host || 'localhost'; - this.config.port = cfg.port || 22; - this.config.localAddress = (typeof cfg.localAddress === 'string' - ? cfg.localAddress - : undefined); - this.config.localPort = (typeof cfg.localPort === 'string' - || typeof cfg.localPort === 'number' - ? cfg.localPort - : undefined); - this.config.forceIPv4 = cfg.forceIPv4 || false; - this.config.forceIPv6 = cfg.forceIPv6 || false; - this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' - && cfg.keepaliveCountMax >= 0 - ? cfg.keepaliveCountMax - : 3); - this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' - && cfg.keepaliveInterval > 0 - ? cfg.keepaliveInterval - : 0); - this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' - && cfg.readyTimeout >= 0 - ? cfg.readyTimeout - : 20000); - this.config.ident = (typeof cfg.ident === 'string' - || Buffer.isBuffer(cfg.ident) - ? cfg.ident - : undefined); - - const algorithms = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: [], - }, - sc: undefined, - }; - let allOfferDefaults = true; - if (typeof cfg.algorithms === 'object' && cfg.algorithms !== null) { - algorithms.kex = generateAlgorithmList(cfg.algorithms.kex, - DEFAULT_KEX, - SUPPORTED_KEX); - if (algorithms.kex !== DEFAULT_KEX) - allOfferDefaults = false; - - algorithms.serverHostKey = - generateAlgorithmList(cfg.algorithms.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY); - if (algorithms.serverHostKey !== DEFAULT_SERVER_HOST_KEY) - allOfferDefaults = false; - - algorithms.cs.cipher = generateAlgorithmList(cfg.algorithms.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER); - if (algorithms.cs.cipher !== DEFAULT_CIPHER) - allOfferDefaults = false; - - algorithms.cs.mac = generateAlgorithmList(cfg.algorithms.hmac, - DEFAULT_MAC, - SUPPORTED_MAC); - if (algorithms.cs.mac !== DEFAULT_MAC) - allOfferDefaults = false; - - algorithms.cs.compress = generateAlgorithmList(cfg.algorithms.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION); - if (algorithms.cs.compress !== DEFAULT_COMPRESSION) - allOfferDefaults = false; - - if (!allOfferDefaults) - algorithms.sc = algorithms.cs; - } - - if (typeof cfg.username === 'string') - this.config.username = cfg.username; - else if (typeof cfg.user === 'string') - this.config.username = cfg.user; - else - throw new Error('Invalid username'); - - this.config.password = (typeof cfg.password === 'string' - ? cfg.password - : undefined); - this.config.privateKey = (typeof cfg.privateKey === 'string' - || Buffer.isBuffer(cfg.privateKey) - ? cfg.privateKey - : undefined); - this.config.localHostname = (typeof cfg.localHostname === 'string' - ? cfg.localHostname - : undefined); - this.config.localUsername = (typeof cfg.localUsername === 'string' - ? cfg.localUsername - : undefined); - this.config.tryKeyboard = (cfg.tryKeyboard === true); - if (typeof cfg.agent === 'string' && cfg.agent.length) - this.config.agent = createAgent(cfg.agent); - else if (isAgent(cfg.agent)) - this.config.agent = cfg.agent; - else - this.config.agent = undefined; - this.config.allowAgentFwd = (cfg.agentForward === true - && this.config.agent !== undefined); - let authHandler = this.config.authHandler = ( - typeof cfg.authHandler === 'function' - || Array.isArray(cfg.authHandler) - ? cfg.authHandler - : undefined - ); - - this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' - ? cfg.strictVendor - : true); - - const debug = this.config.debug = (typeof cfg.debug === 'function' - ? cfg.debug - : undefined); - - if (cfg.agentForward === true && !this.config.allowAgentFwd) { - throw new Error( - 'You must set a valid agent path to allow agent forwarding' - ); - } - - let callbacks = this._callbacks = []; - this._chanMgr = new ChannelManager(this); - this._forwarding = {}; - this._forwardingUnix = {}; - this._acceptX11 = 0; - this._agentFwdEnabled = false; - this._agent = (this.config.agent ? this.config.agent : undefined); - this._remoteVer = undefined; - let privateKey; - - if (this.config.privateKey) { - privateKey = parseKey(this.config.privateKey, cfg.passphrase); - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - if (privateKey.getPrivatePEM() === null) { - throw new Error( - 'privateKey value does not contain a (valid) private key' - ); - } - } - - let hostVerifier; - if (typeof cfg.hostVerifier === 'function') { - const hashCb = cfg.hostVerifier; - let hashAlgo; - if (HASHES.indexOf(cfg.hostHash) !== -1) { - // Default to old behavior of hashing on user's behalf - hashAlgo = cfg.hostHash; - } - hostVerifier = (key, verify) => { - if (hashAlgo) - key = createHash(hashAlgo).update(key).digest('hex'); - const ret = hashCb(key, verify); - if (ret !== undefined) - verify(ret); - }; - } - - const sock = this._sock = (cfg.sock || new Socket()); - let ready = false; - let sawHeader = false; - if (this._protocol) - this._protocol.cleanup(); - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from server: ${JSON.stringify(msg)}`); - }); - let serverSigAlgs; - const proto = this._protocol = new Protocol({ - ident: this.config.ident, - offer: (allOfferDefaults ? undefined : algorithms), - onWrite: (data) => { - if (isWritable(sock)) - sock.write(data); - }, - onError: (err) => { - if (err.level === 'handshake') - clearTimeout(this._readyTimeout); - if (!proto._destruct) - sock.removeAllListeners('data'); - this.emit('error', err); - try { - sock.end(); - } catch {} - }, - onHeader: (header) => { - sawHeader = true; - this._remoteVer = header.versions.software; - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - this.emit('handshake', negotiated); - if (!ready) { - ready = true; - proto.service('ssh-userauth'); - } - }, - debug, - hostVerifier, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - sock.end(); - }, - SERVICE_ACCEPT: (p, name) => { - if (name === 'ssh-userauth') - tryNextAuth(); - }, - EXT_INFO: (p, exts) => { - if (serverSigAlgs === undefined) { - for (const ext of exts) { - if (ext.name === 'server-sig-algs') { - serverSigAlgs = ext.algs; - return; - } - } - serverSigAlgs = null; - } - }, - USERAUTH_BANNER: (p, msg) => { - this.emit('banner', msg); - }, - USERAUTH_SUCCESS: (p) => { - // Start keepalive mechanism - resetKA(); - - clearTimeout(this._readyTimeout); - - this.emit('ready'); - }, - USERAUTH_FAILURE: (p, authMethods, partialSuccess) => { - // For key-based authentication, check if we should retry the current - // key with a different algorithm first - if (curAuth.keyAlgos) { - const oldKeyAlgo = curAuth.keyAlgos[0][0]; - if (debug) - debug(`Client: ${curAuth.type} (${oldKeyAlgo}) auth failed`); - curAuth.keyAlgos.shift(); - if (curAuth.keyAlgos.length) { - const [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - switch (curAuth.type) { - case 'agent': - proto.authPK( - curAuth.username, - curAuth.agentCtx.currentKey(), - keyAlgo - ); - return; - case 'publickey': - proto.authPK(curAuth.username, curAuth.key, keyAlgo); - return; - case 'hostbased': - proto.authHostbased(curAuth.username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - keyAlgo, - (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - - cb(signature); - }); - return; - } - } else { - curAuth.keyAlgos = undefined; - } - } - - if (curAuth.type === 'agent') { - const pos = curAuth.agentCtx.pos(); - debug && debug(`Client: Agent key #${pos + 1} failed`); - return tryNextAgentKey(); - } - - debug && debug(`Client: ${curAuth.type} auth failed`); - - curPartial = partialSuccess; - curAuthsLeft = authMethods; - tryNextAuth(); - }, - USERAUTH_PASSWD_CHANGEREQ: (p, prompt) => { - if (curAuth.type === 'password') { - // TODO: support a `changePrompt()` on `curAuth` that defaults to - // emitting 'change password' as before - this.emit('change password', prompt, (newPassword) => { - proto.authPassword( - this.config.username, - this.config.password, - newPassword - ); - }); - } - }, - USERAUTH_PK_OK: (p) => { - let keyAlgo; - let hashAlgo; - if (curAuth.keyAlgos) - [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.currentKey(); - proto.authPK(curAuth.username, key, keyAlgo, (buf, cb) => { - const opts = { hash: hashAlgo }; - curAuth.agentCtx.sign(key, buf, opts, (err, signed) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - } else { - return cb(signed); - } - - tryNextAgentKey(); - }); - }); - } else if (curAuth.type === 'publickey') { - proto.authPK(curAuth.username, curAuth.key, keyAlgo, (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = - `Error signing data with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - cb(signature); - }); - } - }, - USERAUTH_INFO_REQUEST: (p, name, instructions, prompts) => { - if (curAuth.type === 'keyboard-interactive') { - const nprompts = (Array.isArray(prompts) ? prompts.length : 0); - if (nprompts === 0) { - debug && debug( - 'Client: Sending automatic USERAUTH_INFO_RESPONSE' - ); - proto.authInfoRes(); - return; - } - // We sent a keyboard-interactive user authentication request and - // now the server is sending us the prompts we need to present to - // the user - curAuth.prompt( - name, - instructions, - '', - prompts, - (answers) => { - proto.authInfoRes(answers); - } - ); - } - }, - REQUEST_SUCCESS: (p, data) => { - if (callbacks.length) - callbacks.shift()(false, data); - }, - REQUEST_FAILURE: (p) => { - if (callbacks.length) - callbacks.shift()(true); - }, - GLOBAL_REQUEST: (p, name, wantReply, data) => { - switch (name) { - case 'hostkeys-00@openssh.com': - // Automatically verify keys before passing to end user - hostKeysProve(this, data, (err, keys) => { - if (err) - return; - this.emit('hostkeys', keys); - }); - if (wantReply) - proto.requestSuccess(); - break; - default: - // Auto-reject all other global requests, this can be especially - // useful if the server is sending us dummy keepalive global - // requests - if (wantReply) - proto.requestFailure(); - } - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from server, typically a forwarded TCP or - // X11 connection - onCHANNEL_OPEN(this, info); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const isSFTP = (channel.type === 'sftp'); - const type = (isSFTP ? 'session' : channel.type); - const chanInfo = { - type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const instance = ( - isSFTP - ? new SFTP(this, chanInfo, { debug }) - : new Channel(this, chanInfo) - ); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - if (type !== STDERR) - return; - - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (!channel.stderr.push(data)) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); - } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - this._resetKA(); - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - const exit = channel._exit; - if (exit.code !== undefined) - return; - switch (type) { - case 'exit-status': - channel.emit('exit', exit.code = data); - return; - case 'exit-signal': - channel.emit('exit', - exit.code = null, - exit.signal = `SIG${data.signal}`, - exit.dump = data.coreDumped, - exit.desc = data.errorMessage); - return; - } - - // Keepalive request? OpenSSH will send one as a channel request if - // there is a channel open - - if (wantReply) - p.channelFailure(channel.outgoing.id); - }, - CHANNEL_EOF: (p, recipient) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - if (channel.stderr.readable) - channel.stderr.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - onCHANNEL_CLOSE(this, recipient, this._chanMgr.get(recipient)); - }, - }, - }); - - sock.pause(); - - // TODO: check keepalive implementation - // Keepalive-related - const kainterval = this.config.keepaliveInterval; - const kacountmax = this.config.keepaliveCountMax; - let kacount = 0; - let katimer; - const sendKA = () => { - if (++kacount > kacountmax) { - clearInterval(katimer); - if (sock.readable) { - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - } - return; - } - if (isWritable(sock)) { - // Append dummy callback to keep correct callback order - callbacks.push(resetKA); - proto.ping(); - } else { - clearInterval(katimer); - } - }; - function resetKA() { - if (kainterval > 0) { - kacount = 0; - clearInterval(katimer); - if (isWritable(sock)) - katimer = setInterval(sendKA, kainterval); - } - } - this._resetKA = resetKA; - - const onDone = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (wasConnected && !sawHeader) { - const err = - makeError('Connection lost before handshake', 'protocol', true); - this.emit('error', err); - } - }; - })(); - const onConnect = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - - wasConnected = true; - debug && debug('Socket connected'); - this.emit('connect'); - - cryptoInit.then(() => { - proto.start(); - sock.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - } - }); - - // Drain stderr if we are connection hopping using an exec stream - if (sock.stderr && typeof sock.stderr.resume === 'function') - sock.stderr.resume(); - - sock.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(sock)) - sock.end(); - } catch {} - }); - }; - })(); - let wasConnected = false; - sock.on('connect', onConnect) - .on('timeout', () => { - this.emit('timeout'); - }).on('error', (err) => { - debug && debug(`Socket error: ${err.message}`); - clearTimeout(this._readyTimeout); - err.level = 'client-socket'; - this.emit('error', err); - }).on('end', () => { - debug && debug('Socket ended'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('end'); - }).on('close', () => { - debug && debug('Socket closed'); - onDone(); - proto.cleanup(); - clearTimeout(this._readyTimeout); - clearInterval(katimer); - this.emit('close'); - - // Notify outstanding channel requests of disconnection ... - const callbacks_ = callbacks; - callbacks = this._callbacks = []; - const err = new Error('No response from server'); - for (let i = 0; i < callbacks_.length; ++i) - callbacks_[i](err); - - // Simulate error for any channels waiting to be opened - this._chanMgr.cleanup(err); - }); - - // Begin authentication handling =========================================== - let curAuth; - let curPartial = null; - let curAuthsLeft = null; - const authsAllowed = ['none']; - if (this.config.password !== undefined) - authsAllowed.push('password'); - if (privateKey !== undefined) - authsAllowed.push('publickey'); - if (this._agent !== undefined) - authsAllowed.push('agent'); - if (this.config.tryKeyboard) - authsAllowed.push('keyboard-interactive'); - if (privateKey !== undefined - && this.config.localHostname !== undefined - && this.config.localUsername !== undefined) { - authsAllowed.push('hostbased'); - } - - if (Array.isArray(authHandler)) - authHandler = makeSimpleAuthHandler(authHandler); - else if (typeof authHandler !== 'function') - authHandler = makeSimpleAuthHandler(authsAllowed); - - let hasSentAuth = false; - const doNextAuth = (nextAuth) => { - if (hasSentAuth) - return; - hasSentAuth = true; - - if (nextAuth === false) { - const err = new Error('All configured authentication methods failed'); - err.level = 'client-authentication'; - this.emit('error', err); - this.end(); - return; - } - - if (typeof nextAuth === 'string') { - // Remain backwards compatible with original `authHandler()` usage, - // which only supported passing names of next method to try using data - // from the `connect()` config object - - const type = nextAuth; - if (authsAllowed.indexOf(type) === -1) - return skipAuth(`Authentication method not allowed: ${type}`); - - const username = this.config.username; - switch (type) { - case 'password': - nextAuth = { type, username, password: this.config.password }; - break; - case 'publickey': - nextAuth = { type, username, key: privateKey }; - break; - case 'hostbased': - nextAuth = { - type, - username, - key: privateKey, - localHostname: this.config.localHostname, - localUsername: this.config.localUsername, - }; - break; - case 'agent': - nextAuth = { - type, - username, - agentCtx: new AgentContext(this._agent), - }; - break; - case 'keyboard-interactive': - nextAuth = { - type, - username, - prompt: (...args) => this.emit('keyboard-interactive', ...args), - }; - break; - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } else if (typeof nextAuth !== 'object' || nextAuth === null) { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } else { - const username = nextAuth.username; - if (typeof username !== 'string') { - return skipAuth( - `Skipping invalid authentication attempt: ${nextAuth}` - ); - } - const type = nextAuth.type; - switch (type) { - case 'password': { - const { password } = nextAuth; - if (typeof password !== 'string' && !Buffer.isBuffer(password)) - return skipAuth('Skipping invalid password auth attempt'); - nextAuth = { type, username, password }; - break; - } - case 'publickey': { - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error) - return skipAuth('Skipping invalid key auth attempt'); - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key }; - break; - } - case 'hostbased': { - const { localHostname, localUsername } = nextAuth; - const key = parseKey(nextAuth.key, nextAuth.passphrase); - if (key instanceof Error - || typeof localHostname !== 'string' - || typeof localUsername !== 'string') { - return skipAuth('Skipping invalid hostbased auth attempt'); - } - if (!key.isPrivateKey()) - return skipAuth('Skipping non-private key'); - nextAuth = { type, username, key, localHostname, localUsername }; - break; - } - case 'agent': { - let agent = nextAuth.agent; - if (typeof agent === 'string' && agent.length) { - agent = createAgent(agent); - } else if (!isAgent(agent)) { - return skipAuth( - `Skipping invalid agent: ${nextAuth.agent}` - ); - } - nextAuth = { type, username, agentCtx: new AgentContext(agent) }; - break; - } - case 'keyboard-interactive': { - const { prompt } = nextAuth; - if (typeof prompt !== 'function') { - return skipAuth( - 'Skipping invalid keyboard-interactive auth attempt' - ); - } - nextAuth = { type, username, prompt }; - break; - } - case 'none': - nextAuth = { type, username }; - break; - default: - return skipAuth( - `Skipping unsupported authentication method: ${nextAuth}` - ); - } - } - curAuth = nextAuth; - - // Begin authentication method's process - try { - const username = curAuth.username; - switch (curAuth.type) { - case 'password': - proto.authPassword(username, curAuth.password); - break; - case 'publickey': { - let keyAlgo; - curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - keyAlgo = curAuth.keyAlgos[0][0]; - } else { - return skipAuth( - 'Skipping key authentication (no mutual hash algorithm)' - ); - } - } - proto.authPK(username, curAuth.key, keyAlgo); - break; - } - case 'hostbased': { - let keyAlgo; - let hashAlgo; - curAuth.keyAlgos = getKeyAlgos(this, curAuth.key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - [keyAlgo, hashAlgo] = curAuth.keyAlgos[0]; - } else { - return skipAuth( - 'Skipping hostbased authentication (no mutual hash algorithm)' - ); - } - } - - proto.authHostbased(username, - curAuth.key, - curAuth.localHostname, - curAuth.localUsername, - keyAlgo, - (buf, cb) => { - const signature = curAuth.key.sign(buf, hashAlgo); - if (signature instanceof Error) { - signature.message = - `Error while signing with key: ${signature.message}`; - signature.level = 'client-authentication'; - this.emit('error', signature); - return tryNextAuth(); - } - - cb(signature); - }); - break; - } - case 'agent': - curAuth.agentCtx.init((err) => { - if (err) { - err.level = 'agent'; - this.emit('error', err); - return tryNextAuth(); - } - tryNextAgentKey(); - }); - break; - case 'keyboard-interactive': - proto.authKeyboard(username); - break; - case 'none': - proto.authNone(username); - break; - } - } finally { - hasSentAuth = false; - } - }; - - function skipAuth(msg) { - debug && debug(msg); - process.nextTick(tryNextAuth); - } - - function tryNextAuth() { - hasSentAuth = false; - const auth = authHandler(curAuthsLeft, curPartial, doNextAuth); - if (hasSentAuth || auth === undefined) - return; - doNextAuth(auth); - } - - const tryNextAgentKey = () => { - if (curAuth.type === 'agent') { - const key = curAuth.agentCtx.nextKey(); - if (key === false) { - debug && debug('Agent: No more keys left to try'); - debug && debug('Client: agent auth failed'); - tryNextAuth(); - } else { - const pos = curAuth.agentCtx.pos(); - let keyAlgo; - curAuth.keyAlgos = getKeyAlgos(this, key, serverSigAlgs); - if (curAuth.keyAlgos) { - if (curAuth.keyAlgos.length) { - keyAlgo = curAuth.keyAlgos[0][0]; - } else { - debug && debug( - `Agent: Skipping key #${pos + 1} (no mutual hash algorithm)` - ); - tryNextAgentKey(); - return; - } - } - debug && debug(`Agent: Trying key #${pos + 1}`); - proto.authPK(curAuth.username, key, keyAlgo); - } - } - }; - - const startTimeout = () => { - if (this.config.readyTimeout > 0) { - this._readyTimeout = setTimeout(() => { - const err = new Error('Timed out while waiting for handshake'); - err.level = 'client-timeout'; - this.emit('error', err); - sock.destroy(); - }, this.config.readyTimeout); - } - }; - - if (!cfg.sock) { - let host = this.config.host; - const forceIPv4 = this.config.forceIPv4; - const forceIPv6 = this.config.forceIPv6; - - debug && debug(`Client: Trying ${host} on port ${this.config.port} ...`); - - const doConnect = () => { - startTimeout(); - sock.connect({ - host, - port: this.config.port, - localAddress: this.config.localAddress, - localPort: this.config.localPort - }); - sock.setMaxListeners(0); - sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); - }; - - if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) { - doConnect(); - } else { - dnsLookup(host, (forceIPv4 ? 4 : 6), (err, address, family) => { - if (err) { - const type = (forceIPv4 ? 'IPv4' : 'IPv6'); - const error = new Error( - `Error while looking up ${type} address for '${host}': ${err}` - ); - clearTimeout(this._readyTimeout); - error.level = 'client-dns'; - this.emit('error', error); - this.emit('close'); - return; - } - host = address; - doConnect(); - }); - } - } else { - // Custom socket passed in - startTimeout(); - if (typeof sock.connecting === 'boolean') { - // net.Socket - - if (!sock.connecting) { - // Already connected - onConnect(); - } - } else { - // Assume socket/stream is already "connected" - onConnect(); - } - } - - return this; - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - - destroy() { - this._sock && isWritable(this._sock) && this._sock.destroy(); - return this; - } - - exec(cmd, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) }; - - openChannel(this, 'session', extraOpts, (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.pty === 'object' && opts.pty !== null) - || opts.pty === true) { - todo.push(() => reqPty(chan, opts.pty, reqCb)); - } - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqExec(chan, cmd, opts, cb)); - todo.shift()(); - }); - - return this; - } - - shell(wndopts, opts, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof wndopts === 'function') { - cb = wndopts; - wndopts = opts = undefined; - } else if (typeof opts === 'function') { - cb = opts; - opts = undefined; - } - if (wndopts && (wndopts.x11 !== undefined || wndopts.env !== undefined)) { - opts = wndopts; - wndopts = undefined; - } - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - const todo = []; - - function reqCb(err) { - if (err) { - chan.close(); - cb(err); - return; - } - if (todo.length) - todo.shift()(); - } - - if (this.config.allowAgentFwd === true - || (opts - && opts.agentForward === true - && this._agent !== undefined)) { - todo.push(() => reqAgentFwd(chan, reqCb)); - } - - if (wndopts !== false) - todo.push(() => reqPty(chan, wndopts, reqCb)); - - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.env === 'object' && opts.env !== null) - reqEnv(chan, opts.env); - if ((typeof opts.x11 === 'object' && opts.x11 !== null) - || opts.x11 === 'number' - || opts.x11 === true) { - todo.push(() => reqX11(chan, opts.x11, reqCb)); - } - } - - todo.push(() => reqShell(chan, cb)); - todo.shift()(); - }); - - return this; - } - - subsys(name, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - openChannel(this, 'session', (err, chan) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(chan, name, (err, stream) => { - if (err) { - cb(err); - return; - } - - cb(undefined, stream); - }); - }); - - return this; - } - - forwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request for the server to start forwarding TCP connections to us - // on a particular address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${bindAddr}:${bindPort}`)); - return; - } - - let realPort = bindPort; - if (bindPort === 0 && data && data.length >= 4) { - realPort = readUInt32BE(data, 0); - if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) - bindPort = realPort; - } - - this._forwarding[`${bindAddr}:${bindPort}`] = realPort; - - cb(undefined, realPort); - }); - } - - this._protocol.tcpipForward(bindAddr, bindPort, wantReply); - - return this; - } - - unforwardIn(bindAddr, bindPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request to stop forwarding us new connections for a particular - // address and port - - const wantReply = (typeof cb === 'function'); - - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${bindAddr}:${bindPort}`)); - return; - } - - delete this._forwarding[`${bindAddr}:${bindPort}`]; - - cb(); - }); - } - - this._protocol.cancelTcpipForward(bindAddr, bindPort, wantReply); - - return this; - } - - forwardOut(srcIP, srcPort, dstIP, dstPort, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - // Send a request to forward a TCP connection to the server - - const cfg = { - srcIP: srcIP, - srcPort: srcPort, - dstIP: dstIP, - dstPort: dstPort - }; - - if (typeof cb !== 'function') - cb = noop; - - openChannel(this, 'direct-tcpip', cfg, cb); - - return this; - } - - openssh_noMoreSessions(cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to disable future sessions')); - return; - } - - cb(); - }); - } - - this._protocol.openssh_noMoreSessions(wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to bind to ${socketPath}`)); - return; - } - this._forwardingUnix[socketPath] = true; - cb(); - }); - } - - this._protocol.openssh_streamLocalForward(socketPath, wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_unforwardInStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - const wantReply = (typeof cb === 'function'); - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - if (wantReply) { - this._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to unbind from ${socketPath}`)); - return; - } - delete this._forwardingUnix[socketPath]; - cb(); - }); - } - - this._protocol.openssh_cancelStreamLocalForward(socketPath, wantReply); - return this; - } - - if (!wantReply) - return this; - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof cb !== 'function') - cb = noop; - - if (!this.config.strictVendor - || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { - openChannel(this, 'direct-streamlocal@openssh.com', { socketPath }, cb); - return this; - } - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); - - return this; - } - - sftp(env, cb) { - if (!this._sock || !isWritable(this._sock)) - throw new Error('Not connected'); - - if (typeof env === 'function') { - cb = env; - env = undefined; - } - - openChannel(this, 'sftp', (err, sftp) => { - if (err) { - cb(err); - return; - } - - const reqSubsystemCb = (err, sftp_) => { - if (err) { - cb(err); - return; - } - - function removeListeners() { - sftp.removeListener('ready', onReady); - sftp.removeListener('error', onError); - sftp.removeListener('exit', onExit); - sftp.removeListener('close', onExit); - } - - function onReady() { - // TODO: do not remove exit/close in case remote end closes the - // channel abruptly and we need to notify outstanding callbacks - removeListeners(); - cb(undefined, sftp); - } - - function onError(err) { - removeListeners(); - cb(err); - } - - function onExit(code, signal) { - removeListeners(); - let msg; - if (typeof code === 'number') - msg = `Received exit code ${code} while establishing SFTP session`; - else if (signal !== undefined) - msg = `Received signal ${signal} while establishing SFTP session`; - else - msg = 'Received unexpected SFTP session termination'; - const err = new Error(msg); - err.code = code; - err.signal = signal; - cb(err); - } - - sftp.on('ready', onReady) - .on('error', onError) - .on('exit', onExit) - .on('close', onExit); - - sftp._init(); - }; - - if (typeof env === 'object' && env !== null) { - reqEnv(sftp, env, (err) => { - if (err) { - cb(err); - return; - } - - reqSubsystem(sftp, 'sftp', reqSubsystemCb); - }); - } else { - reqSubsystem(sftp, 'sftp', reqSubsystemCb); - } - }); - - return this; - } - - setNoDelay(noDelay) { - if (this._sock && typeof this._sock.setNoDelay === 'function') - this._sock.setNoDelay(noDelay); - - return this; - } -} - -function openChannel(self, type, opts, cb) { - // Ask the server to open a channel for some purpose - // (e.g. session (sftp, exec, shell), or forwarding a TCP connection - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'session': - case 'sftp': - self._protocol.session(localChan, initWindow, maxPacket); - break; - case 'direct-tcpip': - self._protocol.directTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'direct-streamlocal@openssh.com': - self._protocol.openssh_directStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} - -function reqX11(chan, screen, cb) { - // Asks server to start sending us X11 connections - const cfg = { - single: false, - protocol: 'MIT-MAGIC-COOKIE-1', - cookie: undefined, - screen: 0 - }; - - if (typeof screen === 'function') { - cb = screen; - } else if (typeof screen === 'object' && screen !== null) { - if (typeof screen.single === 'boolean') - cfg.single = screen.single; - if (typeof screen.screen === 'number') - cfg.screen = screen.screen; - if (typeof screen.protocol === 'string') - cfg.protocol = screen.protocol; - if (typeof screen.cookie === 'string') - cfg.cookie = screen.cookie; - else if (Buffer.isBuffer(screen.cookie)) - cfg.cookie = screen.cookie.hexSlice(0, screen.cookie.length); - } - if (cfg.cookie === undefined) - cfg.cookie = randomCookie(); - - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } - - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to request X11')); - return; - } - - chan._hasX11 = true; - ++chan._client._acceptX11; - chan.once('close', () => { - if (chan._client._acceptX11) - --chan._client._acceptX11; - }); - - cb(); - }); - } - - chan._client._protocol.x11Forward(chan.outgoing.id, cfg, wantReply); -} - -function reqPty(chan, opts, cb) { - let rows = 24; - let cols = 80; - let width = 640; - let height = 480; - let term = 'vt100'; - let modes = null; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.rows === 'number') - rows = opts.rows; - if (typeof opts.cols === 'number') - cols = opts.cols; - if (typeof opts.width === 'number') - width = opts.width; - if (typeof opts.height === 'number') - height = opts.height; - if (typeof opts.term === 'string') - term = opts.term; - if (typeof opts.modes === 'object') - modes = opts.modes; - } - - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } - - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to request a pseudo-terminal')); - return; - } - cb(); - }); - } - - chan._client._protocol.pty(chan.outgoing.id, - rows, - cols, - height, - width, - term, - modes, - wantReply); -} - -function reqAgentFwd(chan, cb) { - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - wantReply && cb(new Error('Channel is not open')); - return; - } - if (chan._client._agentFwdEnabled) { - wantReply && cb(false); - return; - } - - chan._client._agentFwdEnabled = true; - - chan._callbacks.push((had_err) => { - if (had_err) { - chan._client._agentFwdEnabled = false; - if (wantReply) { - cb(had_err !== true - ? had_err - : new Error('Unable to request agent forwarding')); - } - return; - } - - if (wantReply) - cb(); - }); - - chan._client._protocol.openssh_agentForward(chan.outgoing.id, true); -} - -function reqShell(chan, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to open shell')); - return; - } - chan.subtype = 'shell'; - cb(undefined, chan); - }); - - chan._client._protocol.shell(chan.outgoing.id, true); -} - -function reqExec(chan, cmd, opts, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true ? had_err : new Error('Unable to exec')); - return; - } - chan.subtype = 'exec'; - chan.allowHalfOpen = (opts.allowHalfOpen !== false); - cb(undefined, chan); - }); - - chan._client._protocol.exec(chan.outgoing.id, cmd, true); -} - -function reqEnv(chan, env, cb) { - const wantReply = (typeof cb === 'function'); - - if (chan.outgoing.state !== 'open') { - if (wantReply) - cb(new Error('Channel is not open')); - return; - } - - if (wantReply) { - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Unable to set environment')); - return; - } - cb(); - }); - } - - const keys = Object.keys(env || {}); - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - const val = env[key]; - chan._client._protocol.env(chan.outgoing.id, key, val, wantReply); - } -} - -function reqSubsystem(chan, name, cb) { - if (chan.outgoing.state !== 'open') { - cb(new Error('Channel is not open')); - return; - } - - chan._callbacks.push((had_err) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error(`Unable to start subsystem: ${name}`)); - return; - } - chan.subtype = 'subsystem'; - cb(undefined, chan); - }); - - chan._client._protocol.subsystem(chan.outgoing.id, name, true); -} - -// TODO: inline implementation into single call site -function onCHANNEL_OPEN(self, info) { - // The server is trying to open a channel with us, this is usually when - // we asked the server to forward us connections on some port and now they - // are asking us to accept/deny an incoming connection on their side - - let localChan = -1; - let reason; - - const accept = () => { - const chanInfo = { - type: info.type, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - const stream = new Channel(self, chanInfo); - self._chanMgr.update(localChan, stream); - - self._protocol.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - return stream; - }; - const reject = () => { - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - - if (localChan !== -1) - self._chanMgr.remove(localChan); - - self._protocol.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = self._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of incoming channel open: ' - + 'no channels available' - ); - } - } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'forwarded-tcpip': { - const val = self._forwarding[`${data.destIP}:${data.destPort}`]; - if (val !== undefined && reserveChannel()) { - if (data.destPort === 0) - data.destPort = val; - self.emit('tcp connection', data, accept, reject); - return; - } - break; - } - case 'forwarded-streamlocal@openssh.com': - if (self._forwardingUnix[data.socketPath] !== undefined - && reserveChannel()) { - self.emit('unix connection', data, accept, reject); - return; +// pkg/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repositories/{repository_id}/environments/{environment_name}/variables" + ], + createOrUpdateEnvironmentSecret: [ + "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables" + ], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" } - break; - case 'auth-agent@openssh.com': - if (self._agentFwdEnabled - && typeof self._agent.getStream === 'function' - && reserveChannel()) { - self._agent.getStream((err, stream) => { - if (err) - return reject(); - - const upstream = accept(); - upstream.pipe(stream).pipe(upstream); - }); - return; + ], + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" } - break; - case 'x11': - if (self._acceptX11 !== 0 && reserveChannel()) { - self.emit('x11', data, accept, reject); - return; + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unsupported incoming channel open ' - + `type: ${info.type}` - ); + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (self.config.debug) { - self.config.debug( - 'Client: Automatic rejection of unexpected incoming channel open for: ' - + info.type - ); - } - } - - reject(); -} - -const randomCookie = (() => { - const buffer = Buffer.allocUnsafe(16); - return () => { - randomFillSync(buffer, 0, 16); - return buffer.hexSlice(0, 16); - }; -})(); - -function makeSimpleAuthHandler(authList) { - if (!Array.isArray(authList)) - throw new Error('authList must be an array'); - - let a = 0; - return (authsLeft, partialSuccess, cb) => { - if (a === authList.length) - return false; - return authList[a++]; - }; -} - -function hostKeysProve(client, keys_, cb) { - if (!client._sock || !isWritable(client._sock)) - return; - - if (typeof cb !== 'function') - cb = noop; - - if (!Array.isArray(keys_)) - throw new TypeError('Invalid keys argument type'); - - const keys = []; - for (const key of keys_) { - const parsed = parseKey(key); - if (parsed instanceof Error) - throw parsed; - keys.push(parsed); - } - - if (!client.config.strictVendor - || (client.config.strictVendor && RE_OPENSSH.test(client._remoteVer))) { - client._callbacks.push((had_err, data) => { - if (had_err) { - cb(had_err !== true - ? had_err - : new Error('Server failed to prove supplied keys')); - return; + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" } - - // TODO: move all of this parsing/verifying logic out of the client? - const ret = []; - let keyIdx = 0; - bufferParser.init(data, 0); - while (bufferParser.avail()) { - if (keyIdx === keys.length) - break; - const key = keys[keyIdx++]; - const keyPublic = key.getPublicSSH(); - - const sigEntry = bufferParser.readString(); - sigParser.init(sigEntry, 0); - const type = sigParser.readString(true); - let value = sigParser.readString(); - - let algo; - if (type !== key.type) { - if (key.type === 'ssh-rsa') { - switch (type) { - case 'rsa-sha2-256': - algo = 'sha256'; - break; - case 'rsa-sha2-512': - algo = 'sha512'; - break; - default: - continue; - } - } else { - continue; - } - } - - const sessionID = client._protocol._kex.sessionID; - const verifyData = Buffer.allocUnsafe( - 4 + 29 + 4 + sessionID.length + 4 + keyPublic.length - ); - let p = 0; - writeUInt32BE(verifyData, 29, p); - verifyData.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - writeUInt32BE(verifyData, sessionID.length, p += 29); - bufferCopy(sessionID, verifyData, 0, sessionID.length, p += 4); - writeUInt32BE(verifyData, keyPublic.length, p += sessionID.length); - bufferCopy(keyPublic, verifyData, 0, keyPublic.length, p += 4); - - if (!(value = sigSSHToASN1(value, type))) - continue; - if (key.verify(verifyData, value, algo) === true) - ret.push(key); + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" } - sigParser.clear(); - bufferParser.clear(); - - cb(null, ret); - }); - - client._protocol.openssh_hostKeysProve(keys); - return; - } - - process.nextTick( - cb, - new Error( - 'strictVendor enabled and server is not OpenSSH or compatible version' - ) - ); -} - -function getKeyAlgos(client, key, serverSigAlgs) { - switch (key.type) { - case 'ssh-rsa': - if (client._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) { - if (!Array.isArray(serverSigAlgs)) - serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512']; - else - serverSigAlgs = ['rsa-sha2-256', 'rsa-sha2-512', ...serverSigAlgs]; + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" } - if (Array.isArray(serverSigAlgs)) { - if (serverSigAlgs.indexOf('rsa-sha2-256') !== -1) - return [['rsa-sha2-256', 'sha256']]; - if (serverSigAlgs.indexOf('rsa-sha2-512') !== -1) - return [['rsa-sha2-512', 'sha512']]; - if (serverSigAlgs.indexOf('ssh-rsa') === -1) - return []; + ], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ], + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" } - return [['ssh-rsa', 'sha1']]; - } -} - -module.exports = Client; - - -/***/ }), - -/***/ 42994: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -const { Agent: HttpAgent } = __nccwpck_require__(13685); -const { Agent: HttpsAgent } = __nccwpck_require__(95687); -const { connect: tlsConnect } = __nccwpck_require__(24404); - -let Client; - -for (const ctor of [HttpAgent, HttpsAgent]) { - class SSHAgent extends ctor { - constructor(connectCfg, agentOptions) { - super(agentOptions); - - this._connectCfg = connectCfg; - this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; - } - - createConnection(options, cb) { - const srcIP = (options && options.localAddress) || this._defaultSrcIP; - const srcPort = (options && options.localPort) || 0; - const dstIP = options.host; - const dstPort = options.port; - - if (Client === undefined) - Client = __nccwpck_require__(36063); - - const client = new Client(); - let triedForward = false; - client.on('ready', () => { - client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { - triedForward = true; - if (err) { - client.end(); - return cb(err); - } - stream.once('close', () => client.end()); - cb(null, decorateStream(stream, ctor, options)); - }); - }).on('error', cb).on('close', () => { - if (!triedForward) - cb(new Error('Unexpected connection close')); - }).connect(this._connectCfg); - } - } - - exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; -} - -function noop() {} - -function decorateStream(stream, ctor, options) { - if (ctor === HttpAgent) { - // HTTP - stream.setKeepAlive = noop; - stream.setNoDelay = noop; - stream.setTimeout = noop; - stream.ref = noop; - stream.unref = noop; - stream.destroySoon = stream.destroy; - return stream; - } - - // HTTPS - options.socket = stream; - const wrapped = tlsConnect(options); - - // This is a workaround for a regression in node v12.16.3+ - // https://github.com/nodejs/node/issues/35904 - const onClose = (() => { - let called = false; - return () => { - if (called) - return; - called = true; - if (stream.isPaused()) - stream.resume(); - }; - })(); - // 'end' listener is needed because 'close' is not emitted in some scenarios - // in node v12.x for some unknown reason - wrapped.on('end', onClose).on('close', onClose); - - return wrapped; -} - - -/***/ }), - -/***/ 95869: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - AgentProtocol, - BaseAgent, - createAgent, - CygwinAgent, - OpenSSHAgent, - PageantAgent, -} = __nccwpck_require__(49054); -const { - SSHTTPAgent: HTTPAgent, - SSHTTPSAgent: HTTPSAgent, -} = __nccwpck_require__(42994); -const { parseKey } = __nccwpck_require__(22218); -const { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, -} = __nccwpck_require__(52026); - -module.exports = { - AgentProtocol, - BaseAgent, - createAgent, - Client: __nccwpck_require__(36063), - CygwinAgent, - HTTPAgent, - HTTPSAgent, - OpenSSHAgent, - PageantAgent, - Server: __nccwpck_require__(12986), - utils: { - parseKey, - ...__nccwpck_require__(63823), - sftp: { - flagsToString, - OPEN_MODE, - STATUS_CODE, - stringToFlags, - }, + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}" + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], + createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteCustomOrganizationRole: [ + "DELETE /orgs/{org}/organization-roles/{role_id}" + ], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + enableOrDisableSecurityProductOnAllOrgRepos: [ + "POST /orgs/{org}/{security_product}/{enablement}" + ], + get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + patchCustomOrganizationRole: [ + "PATCH /orgs/{org}/organization-roles/{role_id}" + ], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}" + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: [ + "GET /projects/{project_id}/collaborators/{username}/permission" + ], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: [ + "DELETE /projects/{project_id}/collaborators/{username}" + ], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteTagProtection: [ + "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" + ], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] }, -}; - - -/***/ }), - -/***/ 63823: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - createCipheriv, - generateKeyPair: generateKeyPair_, - generateKeyPairSync: generateKeyPairSync_, - getCurves, - randomBytes, -} = __nccwpck_require__(6113); - -const { Ber } = __nccwpck_require__(80970); -const bcrypt_pbkdf = (__nccwpck_require__(45447).pbkdf); - -const { CIPHER_INFO } = __nccwpck_require__(45708); - -const SALT_LEN = 16; -const DEFAULT_ROUNDS = 16; - -const curves = getCurves(); -const ciphers = new Map(Object.entries(CIPHER_INFO)); - -function makeArgs(type, opts) { - if (typeof type !== 'string') - throw new TypeError('Key type must be a string'); - - const publicKeyEncoding = { type: 'spki', format: 'der' }; - const privateKeyEncoding = { type: 'pkcs8', format: 'der' }; - - switch (type.toLowerCase()) { - case 'rsa': { - if (typeof opts !== 'object' || opts === null) - throw new TypeError('Missing options object for RSA key'); - const modulusLength = opts.bits; - if (!Number.isInteger(modulusLength)) - throw new TypeError('RSA bits must be an integer'); - if (modulusLength <= 0 || modulusLength > 16384) - throw new RangeError('RSA bits must be non-zero and <= 16384'); - return ['rsa', { modulusLength, publicKeyEncoding, privateKeyEncoding }]; - } - case 'ecdsa': { - if (typeof opts !== 'object' || opts === null) - throw new TypeError('Missing options object for ECDSA key'); - if (!Number.isInteger(opts.bits)) - throw new TypeError('ECDSA bits must be an integer'); - let namedCurve; - switch (opts.bits) { - case 256: - namedCurve = 'prime256v1'; - break; - case 384: - namedCurve = 'secp384r1'; - break; - case 521: - namedCurve = 'secp521r1'; - break; - default: - throw new Error('ECDSA bits must be 256, 384, or 521'); - } - if (!curves.includes(namedCurve)) - throw new Error('Unsupported ECDSA bits value'); - return ['ec', { namedCurve, publicKeyEncoding, privateKeyEncoding }]; - } - case 'ed25519': - return ['ed25519', { publicKeyEncoding, privateKeyEncoding }]; - default: - throw new Error(`Unsupported key type: ${type}`); - } -} - -function parseDERs(keyType, pub, priv) { - switch (keyType) { - case 'rsa': { - // Note: we don't need to parse the public key since the PKCS8 private key - // already includes the public key parameters - - // Parse private key - let reader = new Ber.Reader(priv); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 0) - throw new Error('Unsupported version in RSA private key'); - - // - Algorithm - reader.readSequence(); - if (reader.readOID() !== '1.2.840.113549.1.1.1') - throw new Error('Bad RSA private OID'); - // - Algorithm parameters (RSA has none) - if (reader.readByte() !== Ber.Null) - throw new Error('Malformed RSA private key (expected null)'); - if (reader.readByte() !== 0x00) { - throw new Error( - 'Malformed RSA private key (expected zero-length null)' - ); - } - - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - reader.readSequence(); - if (reader.readInt() !== 0) - throw new Error('Unsupported version in RSA private key'); - const n = reader.readString(Ber.Integer, true); - const e = reader.readString(Ber.Integer, true); - const d = reader.readString(Ber.Integer, true); - const p = reader.readString(Ber.Integer, true); - const q = reader.readString(Ber.Integer, true); - reader.readString(Ber.Integer, true); // dmp1 - reader.readString(Ber.Integer, true); // dmq1 - const iqmp = reader.readString(Ber.Integer, true); - - /* - OpenSSH RSA private key: - string "ssh-rsa" - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const keyName = Buffer.from('ssh-rsa'); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + n.length - + 4 + e.length - + 4 + d.length - + 4 + iqmp.length - + 4 + p.length - + 4 + q.length - ); - let pos = 0; - - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(n.length, pos += keyName.length); - privBuf.set(n, pos += 4); - privBuf.writeUInt32BE(e.length, pos += n.length); - privBuf.set(e, pos += 4); - privBuf.writeUInt32BE(d.length, pos += e.length); - privBuf.set(d, pos += 4); - privBuf.writeUInt32BE(iqmp.length, pos += d.length); - privBuf.set(iqmp, pos += 4); - privBuf.writeUInt32BE(p.length, pos += iqmp.length); - privBuf.set(p, pos += 4); - privBuf.writeUInt32BE(q.length, pos += p.length); - privBuf.set(q, pos += 4); - - /* - OpenSSH RSA public key: - string "ssh-rsa" - string e -- public - string n -- public - */ - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + e.length - + 4 + n.length - ); - pos = 0; - - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(e.length, pos += keyName.length); - pubBuf.set(e, pos += 4); - pubBuf.writeUInt32BE(n.length, pos += e.length); - pubBuf.set(n, pos += 4); - - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; - } - case 'ec': { - // Parse public key - let reader = new Ber.Reader(pub); - reader.readSequence(); - - reader.readSequence(); - if (reader.readOID() !== '1.2.840.10045.2.1') - throw new Error('Bad ECDSA public OID'); - // Skip curve OID, we'll get it from the private key - reader.readOID(); - let pubBin = reader.readString(Ber.BitString, true); - { - // Remove leading zero bytes - let i = 0; - for (; i < pubBin.length && pubBin[i] === 0x00; ++i); - if (i > 0) - pubBin = pubBin.slice(i); - } - - // Parse private key - reader = new Ber.Reader(priv); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 0) - throw new Error('Unsupported version in ECDSA private key'); - - reader.readSequence(); - if (reader.readOID() !== '1.2.840.10045.2.1') - throw new Error('Bad ECDSA private OID'); - const curveOID = reader.readOID(); - let sshCurveName; - switch (curveOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - sshCurveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - sshCurveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - sshCurveName = 'nistp521'; - break; - default: - throw new Error('Unsupported curve in ECDSA private key'); - } - - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 1) - throw new Error('Unsupported version in ECDSA private key'); - - // Add leading zero byte to prevent negative bignum in private key - const privBin = Buffer.concat([ - Buffer.from([0x00]), - reader.readString(Ber.OctetString, true) - ]); - - /* - OpenSSH ECDSA private key: - string "ecdsa-sha2-" - string curve name - string Q -- public - string d -- private - */ - const keyName = Buffer.from(`ecdsa-sha2-${sshCurveName}`); - sshCurveName = Buffer.from(sshCurveName); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + sshCurveName.length - + 4 + pubBin.length - + 4 + privBin.length - ); - let pos = 0; - - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); - privBuf.set(sshCurveName, pos += 4); - privBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); - privBuf.set(pubBin, pos += 4); - privBuf.writeUInt32BE(privBin.length, pos += pubBin.length); - privBuf.set(privBin, pos += 4); - - /* - OpenSSH ECDSA public key: - string "ecdsa-sha2-" - string curve name - string Q -- public - */ - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + sshCurveName.length - + 4 + pubBin.length - ); - pos = 0; - - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(sshCurveName.length, pos += keyName.length); - pubBuf.set(sshCurveName, pos += 4); - pubBuf.writeUInt32BE(pubBin.length, pos += sshCurveName.length); - pubBuf.set(pubBin, pos += 4); - - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; - } - case 'ed25519': { - // Parse public key - let reader = new Ber.Reader(pub); - reader.readSequence(); - - // - Algorithm - reader.readSequence(); - if (reader.readOID() !== '1.3.101.112') - throw new Error('Bad ED25519 public OID'); - // - Attributes (absent for ED25519) - - let pubBin = reader.readString(Ber.BitString, true); - { - // Remove leading zero bytes - let i = 0; - for (; i < pubBin.length && pubBin[i] === 0x00; ++i); - if (i > 0) - pubBin = pubBin.slice(i); - } - - // Parse private key - reader = new Ber.Reader(priv); - reader.readSequence(); - - // - Version - if (reader.readInt() !== 0) - throw new Error('Unsupported version in ED25519 private key'); - - // - Algorithm - reader.readSequence(); - if (reader.readOID() !== '1.3.101.112') - throw new Error('Bad ED25519 private OID'); - // - Attributes (absent) - - reader = new Ber.Reader(reader.readString(Ber.OctetString, true)); - const privBin = reader.readString(Ber.OctetString, true); - - /* - OpenSSH ed25519 private key: - string "ssh-ed25519" - string public key - string private key + public key - */ - const keyName = Buffer.from('ssh-ed25519'); - const privBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + pubBin.length - + 4 + (privBin.length + pubBin.length) - ); - let pos = 0; - - privBuf.writeUInt32BE(keyName.length, pos += 0); - privBuf.set(keyName, pos += 4); - privBuf.writeUInt32BE(pubBin.length, pos += keyName.length); - privBuf.set(pubBin, pos += 4); - privBuf.writeUInt32BE( - privBin.length + pubBin.length, - pos += pubBin.length - ); - privBuf.set(privBin, pos += 4); - privBuf.set(pubBin, pos += privBin.length); - - /* - OpenSSH ed25519 public key: - string "ssh-ed25519" - string public key - */ - const pubBuf = Buffer.allocUnsafe( - 4 + keyName.length - + 4 + pubBin.length - ); - pos = 0; - - pubBuf.writeUInt32BE(keyName.length, pos += 0); - pubBuf.set(keyName, pos += 4); - pubBuf.writeUInt32BE(pubBin.length, pos += keyName.length); - pubBuf.set(pubBin, pos += 4); - - return { sshName: keyName.toString(), priv: privBuf, pub: pubBuf }; - } - } -} - -function convertKeys(keyType, pub, priv, opts) { - let format = 'new'; - let encrypted; - let comment = ''; - if (typeof opts === 'object' && opts !== null) { - if (typeof opts.comment === 'string' && opts.comment) - comment = opts.comment; - if (typeof opts.format === 'string' && opts.format) - format = opts.format; - if (opts.passphrase) { - let passphrase; - if (typeof opts.passphrase === 'string') - passphrase = Buffer.from(opts.passphrase); - else if (Buffer.isBuffer(opts.passphrase)) - passphrase = opts.passphrase; - else - throw new Error('Invalid passphrase'); - - if (opts.cipher === undefined) - throw new Error('Missing cipher name'); - const cipher = ciphers.get(opts.cipher); - if (cipher === undefined) - throw new Error('Invalid cipher name'); - - if (format === 'new') { - let rounds = DEFAULT_ROUNDS; - if (opts.rounds !== undefined) { - if (!Number.isInteger(opts.rounds)) - throw new TypeError('rounds must be an integer'); - if (opts.rounds > 0) - rounds = opts.rounds; - } - - const gen = Buffer.allocUnsafe(cipher.keyLen + cipher.ivLen); - const salt = randomBytes(SALT_LEN); - const r = bcrypt_pbkdf( - passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds - ); - if (r !== 0) - return new Error('Failed to generate information to encrypt key'); - - /* - string salt - uint32 rounds - */ - const kdfOptions = Buffer.allocUnsafe(4 + salt.length + 4); - { - let pos = 0; - kdfOptions.writeUInt32BE(salt.length, pos += 0); - kdfOptions.set(salt, pos += 4); - kdfOptions.writeUInt32BE(rounds, pos += salt.length); - } - - encrypted = { - cipher, - cipherName: opts.cipher, - kdfName: 'bcrypt', - kdfOptions, - key: gen.slice(0, cipher.keyLen), - iv: gen.slice(cipher.keyLen), - }; - } - } - } - - switch (format) { - case 'new': { - let privateB64 = '-----BEGIN OPENSSH PRIVATE KEY-----\n'; - let publicB64; - /* - byte[] "openssh-key-v1\0" - string ciphername - string kdfname - string kdfoptions - uint32 number of keys N - string publickey1 - string encrypted, padded list of private keys - uint32 checkint - uint32 checkint - byte[] privatekey1 - string comment1 - byte 1 - byte 2 - byte 3 - ... - byte padlen % 255 - */ - const cipherName = Buffer.from(encrypted ? encrypted.cipherName : 'none'); - const kdfName = Buffer.from(encrypted ? encrypted.kdfName : 'none'); - const kdfOptions = (encrypted ? encrypted.kdfOptions : Buffer.alloc(0)); - const blockLen = (encrypted ? encrypted.cipher.blockLen : 8); - - const parsed = parseDERs(keyType, pub, priv); - - const checkInt = randomBytes(4); - const commentBin = Buffer.from(comment); - const privBlobLen = (4 + 4 + parsed.priv.length + 4 + commentBin.length); - let padding = []; - for (let i = 1; ((privBlobLen + padding.length) % blockLen); ++i) - padding.push(i & 0xFF); - padding = Buffer.from(padding); - - let privBlob = Buffer.allocUnsafe(privBlobLen + padding.length); - let extra; - { - let pos = 0; - privBlob.set(checkInt, pos += 0); - privBlob.set(checkInt, pos += 4); - privBlob.set(parsed.priv, pos += 4); - privBlob.writeUInt32BE(commentBin.length, pos += parsed.priv.length); - privBlob.set(commentBin, pos += 4); - privBlob.set(padding, pos += commentBin.length); - } - - if (encrypted) { - const options = { authTagLength: encrypted.cipher.authLen }; - const cipher = createCipheriv( - encrypted.cipher.sslName, - encrypted.key, - encrypted.iv, - options - ); - cipher.setAutoPadding(false); - privBlob = Buffer.concat([ cipher.update(privBlob), cipher.final() ]); - if (encrypted.cipher.authLen > 0) - extra = cipher.getAuthTag(); - else - extra = Buffer.alloc(0); - encrypted.key.fill(0); - encrypted.iv.fill(0); - } else { - extra = Buffer.alloc(0); - } - - const magicBytes = Buffer.from('openssh-key-v1\0'); - const privBin = Buffer.allocUnsafe( - magicBytes.length - + 4 + cipherName.length - + 4 + kdfName.length - + 4 + kdfOptions.length - + 4 - + 4 + parsed.pub.length - + 4 + privBlob.length - + extra.length - ); - { - let pos = 0; - privBin.set(magicBytes, pos += 0); - privBin.writeUInt32BE(cipherName.length, pos += magicBytes.length); - privBin.set(cipherName, pos += 4); - privBin.writeUInt32BE(kdfName.length, pos += cipherName.length); - privBin.set(kdfName, pos += 4); - privBin.writeUInt32BE(kdfOptions.length, pos += kdfName.length); - privBin.set(kdfOptions, pos += 4); - privBin.writeUInt32BE(1, pos += kdfOptions.length); - privBin.writeUInt32BE(parsed.pub.length, pos += 4); - privBin.set(parsed.pub, pos += 4); - privBin.writeUInt32BE(privBlob.length, pos += parsed.pub.length); - privBin.set(privBlob, pos += 4); - privBin.set(extra, pos += privBlob.length); - } - - { - const b64 = privBin.base64Slice(0, privBin.length); - let formatted = b64.replace(/.{64}/g, '$&\n'); - if (b64.length & 63) - formatted += '\n'; - privateB64 += formatted; - } - - { - const b64 = parsed.pub.base64Slice(0, parsed.pub.length); - publicB64 = `${parsed.sshName} ${b64}${comment ? ` ${comment}` : ''}`; - } - - privateB64 += '-----END OPENSSH PRIVATE KEY-----\n'; - return { - private: privateB64, - public: publicB64, - }; - } - default: - throw new Error('Invalid output key format'); - } -} - -function noop() {} - -module.exports = { - generateKeyPair: (keyType, opts, cb) => { - if (typeof opts === 'function') { - cb = opts; - opts = undefined; - } - if (typeof cb !== 'function') - cb = noop; - const args = makeArgs(keyType, opts); - generateKeyPair_(...args, (err, pub, priv) => { - if (err) - return cb(err); - let ret; - try { - ret = convertKeys(args[0], pub, priv, opts); - } catch (ex) { - return cb(ex); - } - cb(null, ret); - }); + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateProjectPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForProjectInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeProjectInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] }, - generateKeyPairSync: (keyType, opts) => { - const args = makeArgs(keyType, opts); - const { publicKey: pub, privateKey: priv } = generateKeyPairSync_(...args); - return convertKeys(args[0], pub, priv, opts); + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] } }; +var endpoints_default = Endpoints; - -/***/ }), - -/***/ 59031: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* - TODO: - * Replace `buffer._pos` usage in keyParser.js and elsewhere - * Utilize optional "writev" support when writing packets from - cipher.encrypt() - * Built-in support for automatic re-keying, on by default - * Revisit receiving unexpected/unknown packets - * Error (fatal or otherwise) or ignore or pass on to user (in some or all - cases)? - * Including server/client check for single directional packet types? - * Check packets for validity or bail as early as possible? - * Automatic re-key every 2**31 packets after the last key exchange (sent or - received), as suggested by RFC4344. OpenSSH currently does this. - * Automatic re-key every so many blocks depending on cipher. RFC4344: - Because of a birthday property of block ciphers and some modes of - operation, implementations must be careful not to encrypt too many - blocks with the same encryption key. - - Let L be the block length (in bits) of an SSH encryption method's - block cipher (e.g., 128 for AES). If L is at least 128, then, after - rekeying, an SSH implementation SHOULD NOT encrypt more than 2**(L/4) - blocks before rekeying again. If L is at least 128, then SSH - implementations should also attempt to force a rekey before receiving - more than 2**(L/4) blocks. If L is less than 128 (which is the case - for older ciphers such as 3DES, Blowfish, CAST-128, and IDEA), then, - although it may be too expensive to rekey every 2**(L/4) blocks, it - is still advisable for SSH implementations to follow the original - recommendation in [RFC4253]: rekey at least once for every gigabyte - of transmitted data. - - Note that if L is less than or equal to 128, then the recommendation - in this subsection supersedes the recommendation in Section 3.1. If - an SSH implementation uses a block cipher with a larger block size - (e.g., Rijndael with 256-bit blocks), then the recommendations in - Section 3.1 may supersede the recommendations in this subsection - (depending on the lengths of the packets). -*/ - - - -const { inspect } = __nccwpck_require__(73837); - -const { bindingAvailable, NullCipher, NullDecipher } = __nccwpck_require__(45708); -const { - COMPAT_CHECKS, - DISCONNECT_REASON, - eddsaSupported, - MESSAGE, - SIGNALS, - TERMINAL_MODE, -} = __nccwpck_require__(36832); -const { - DEFAULT_KEXINIT_CLIENT, - DEFAULT_KEXINIT_SERVER, - KexInit, - kexinit, - onKEXPayload, -} = __nccwpck_require__(64126); -const { - parseKey, -} = __nccwpck_require__(22218); -const MESSAGE_HANDLERS = __nccwpck_require__(10172); -const { - bufferCopy, - bufferFill, - bufferSlice, - convertSignature, - sendPacket, - writeUInt32BE, -} = __nccwpck_require__(49475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(26715); - -const MODULE_VER = (__nccwpck_require__(66674)/* .version */ .i8); - -const VALID_DISCONNECT_REASONS = new Map( - Object.values(DISCONNECT_REASON).map((n) => [n, 1]) -); -const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`); -const IDENT = Buffer.from(`${IDENT_RAW}\r\n`); -const MAX_LINE_LEN = 8192; -const MAX_LINES = 1024; -const PING_PAYLOAD = Buffer.from([ - MESSAGE.GLOBAL_REQUEST, - // "keepalive@openssh.com" - 0, 0, 0, 21, - 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, - 115, 104, 46, 99, 111, 109, - // Request a reply - 1, -]); -const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]); - -function noop() {} - -/* - Inbound: - * kexinit payload (needed only until exchange hash is generated) - * raw ident - * rekey packet queue - * expected packet (implemented as separate _parse() function?) - Outbound: - * kexinit payload (needed only until exchange hash is generated) - * rekey packet queue - * kex secret (needed only until NEWKEYS) - * exchange hash (needed only until NEWKEYS) - * session ID (set to exchange hash from initial handshake) -*/ -class Protocol { - constructor(config) { - const onWrite = config.onWrite; - if (typeof onWrite !== 'function') - throw new Error('Missing onWrite function'); - this._onWrite = (data) => { onWrite(data); }; - - const onError = config.onError; - if (typeof onError !== 'function') - throw new Error('Missing onError function'); - this._onError = (err) => { onError(err); }; - - const debug = config.debug; - this._debug = (typeof debug === 'function' - ? (msg) => { debug(msg); } - : undefined); - - const onHeader = config.onHeader; - this._onHeader = (typeof onHeader === 'function' - ? (...args) => { onHeader(...args); } - : noop); - - const onPacket = config.onPacket; - this._onPacket = (typeof onPacket === 'function' - ? () => { onPacket(); } - : noop); - - let onHandshakeComplete = config.onHandshakeComplete; - if (typeof onHandshakeComplete !== 'function') - onHandshakeComplete = noop; - let firstHandshake; - this._onHandshakeComplete = (...args) => { - this._debug && this._debug('Handshake completed'); - if (firstHandshake === undefined) - firstHandshake = true; - else - firstHandshake = false; - - // Process packets queued during a rekey where necessary - const oldQueue = this._queue; - if (oldQueue) { - this._queue = undefined; - this._debug && this._debug( - `Draining outbound queue (${oldQueue.length}) ...` - ); - for (let i = 0; i < oldQueue.length; ++i) { - const data = oldQueue[i]; - // data === payload only - - // XXX: hacky - let finalized = this._packetRW.write.finalize(data); - if (finalized === data) { - const packet = this._cipher.allocPacket(data.length); - packet.set(data, 5); - finalized = packet; - } - - sendPacket(this, finalized); - } - this._debug && this._debug('... finished draining outbound queue'); - } - - if (firstHandshake && this._server && this._kex.remoteExtInfoEnabled) - sendExtInfo(this); - - onHandshakeComplete(...args); - }; - this._queue = undefined; - - const messageHandlers = config.messageHandlers; - if (typeof messageHandlers === 'object' && messageHandlers !== null) - this._handlers = messageHandlers; - else - this._handlers = {}; - - this._onPayload = onPayload.bind(this); - - this._server = !!config.server; - this._banner = undefined; - let greeting; - if (this._server) { - if (typeof config.hostKeys !== 'object' || config.hostKeys === null) - throw new Error('Missing server host key(s)'); - this._hostKeys = config.hostKeys; - - // Greeting displayed before the ssh identification string is sent, this - // is usually ignored by most clients - if (typeof config.greeting === 'string' && config.greeting.length) { - greeting = (config.greeting.slice(-2) === '\r\n' - ? config.greeting - : `${config.greeting}\r\n`); - } - - // Banner shown after the handshake completes, but before user - // authentication begins - if (typeof config.banner === 'string' && config.banner.length) { - this._banner = (config.banner.slice(-2) === '\r\n' - ? config.banner - : `${config.banner}\r\n`); - } - } else { - this._hostKeys = undefined; - } - - let offer = config.offer; - if (typeof offer !== 'object' || offer === null) { - offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT); - } else if (offer.constructor !== KexInit) { - if (this._server) { - offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']); - } else { - offer.kex = offer.kex.concat([ - 'ext-info-c', - 'kex-strict-c-v00@openssh.com', - ]); - } - offer = new KexInit(offer); - } - this._kex = undefined; - this._strictMode = undefined; - this._kexinit = undefined; - this._offer = offer; - this._cipher = new NullCipher(0, this._onWrite); - this._decipher = undefined; - this._skipNextInboundPacket = false; - this._packetRW = { - read: new PacketReader(), - write: new PacketWriter(this), - }; - this._hostVerifier = (!this._server - && typeof config.hostVerifier === 'function' - ? config.hostVerifier - : undefined); - - this._parse = parseHeader; - this._buffer = undefined; - this._authsQueue = []; - this._authenticated = false; - this._remoteIdentRaw = undefined; - let sentIdent; - if (typeof config.ident === 'string') { - this._identRaw = Buffer.from(`SSH-2.0-${config.ident}`); - - sentIdent = Buffer.allocUnsafe(this._identRaw.length + 2); - sentIdent.set(this._identRaw, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else if (Buffer.isBuffer(config.ident)) { - const fullIdent = Buffer.allocUnsafe(8 + config.ident.length); - fullIdent.latin1Write('SSH-2.0-', 0, 8); - fullIdent.set(config.ident, 8); - this._identRaw = fullIdent; - - sentIdent = Buffer.allocUnsafe(fullIdent.length + 2); - sentIdent.set(fullIdent, 0); - sentIdent[sentIdent.length - 2] = 13; // '\r' - sentIdent[sentIdent.length - 1] = 10; // '\n' - } else { - this._identRaw = IDENT_RAW; - sentIdent = IDENT; - } - this._compatFlags = 0; - - if (this._debug) { - if (bindingAvailable) - this._debug('Custom crypto binding available'); - else - this._debug('Custom crypto binding not available'); - } - - this._debug && this._debug( - `Local ident: ${inspect(this._identRaw.toString())}` - ); - this.start = () => { - this.start = undefined; - if (greeting) - this._onWrite(greeting); - this._onWrite(sentIdent); - }; - } - _destruct(reason) { - this._packetRW.read.cleanup(); - this._packetRW.write.cleanup(); - this._cipher && this._cipher.free(); - this._decipher && this._decipher.free(); - if (typeof reason !== 'string' || reason.length === 0) - reason = 'fatal error'; - this.parse = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._onWrite = () => { - throw new Error(`Instance unusable after ${reason}`); - }; - this._destruct = undefined; - } - cleanup() { - this._destruct && this._destruct(); - } - parse(chunk, i, len) { - while (i < len) - i = this._parse(chunk, i, len); - } - - // Protocol message API - - // =========================================================================== - // Common/Shared ============================================================= - // =========================================================================== - - // Global - // ------ - disconnect(reason) { - const pktLen = 1 + 4 + 4 + 4; - // We don't use _packetRW.write.* here because we need to make sure that - // we always get a full packet allocated because this message can be sent - // at any time -- even during a key exchange - let p = this._packetRW.write.allocStartKEX; - const packet = this._packetRW.write.alloc(pktLen, true); - const end = p + pktLen; - - if (!VALID_DISCONNECT_REASONS.has(reason)) - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - - packet[p] = MESSAGE.DISCONNECT; - writeUInt32BE(packet, reason, ++p); - packet.fill(0, p += 4, end); - - this._debug && this._debug(`Outbound: Sending DISCONNECT (${reason})`); - sendPacket(this, this._packetRW.write.finalize(packet, true), true); - } - ping() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(PING_PAYLOAD.length); - - packet.set(PING_PAYLOAD, p); - - this._debug && this._debug( - 'Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - rekey() { - if (this._kexinit === undefined) { - this._debug && this._debug('Outbound: Initiated explicit rekey'); - this._queue = []; - kexinit(this); - } else { - this._debug && this._debug('Outbound: Ignoring rekey during handshake'); - } - } - - // 'ssh-connection' service-specific - // --------------------------------- - requestSuccess(data) { - let p = this._packetRW.write.allocStart; - let packet; - if (Buffer.isBuffer(data)) { - packet = this._packetRW.write.alloc(1 + data.length); - - packet[p] = MESSAGE.REQUEST_SUCCESS; - - packet.set(data, ++p); - } else { - packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_SUCCESS; - } - - this._debug && this._debug('Outbound: Sending REQUEST_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - requestFailure() { - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.REQUEST_FAILURE; - - this._debug && this._debug('Outbound: Sending REQUEST_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelSuccess(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_SUCCESS; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelFailure(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_FAILURE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelEOF(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_EOF; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelClose(chan) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4); - - packet[p] = MESSAGE.CHANNEL_CLOSE; - - writeUInt32BE(packet, chan, ++p); - - this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelWindowAdjust(chan, amount) { - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_WINDOW_ADJUST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, amount, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${chan}, ${amount})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelData(chan, data) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_DATA (r:${chan}, ${dataLen})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelExtData(chan, data, type) { - const isBuffer = Buffer.isBuffer(data); - const dataLen = (isBuffer ? data.length : Buffer.byteLength(data)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + dataLen); - - packet[p] = MESSAGE.CHANNEL_EXTENDED_DATA; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, type, p += 4); - - writeUInt32BE(packet, dataLen, p += 4); - - if (isBuffer) - packet.set(data, p += 4); - else - packet.utf8Write(data, p += 4, dataLen); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${chan})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenConfirm(remote, local, initWindow, maxPacket) { - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_CONFIRMATION; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, local, p += 4); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${remote}, l:${local})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - channelOpenFail(remote, reason, desc) { - if (typeof desc !== 'string') - desc = ''; - - const descLen = Buffer.byteLength(desc); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 4 + descLen + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN_FAILURE; - - writeUInt32BE(packet, remote, ++p); - - writeUInt32BE(packet, reason, p += 4); - - writeUInt32BE(packet, descLen, p += 4); - - p += 4; - if (descLen) { - packet.utf8Write(desc, p, descLen); - p += descLen; - } - - writeUInt32BE(packet, 0, p); // Empty language tag - - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${remote})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - - // Global - // ------ - service(name) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + nameLen); - - packet[p] = MESSAGE.SERVICE_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${name})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-userauth' service-specific - // ------------------------------- - authPassword(username, password, newPassword) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - const passLen = Buffer.byteLength(password); - const newPassLen = (newPassword ? Buffer.byteLength(newPassword) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 8 + 1 + 4 + passLen - + (newPassword ? 4 + newPassLen : 0) - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 8, p += 14); - packet.utf8Write('password', p += 4, 8); - - packet[p += 8] = (newPassword ? 1 : 0); - - writeUInt32BE(packet, passLen, ++p); - if (Buffer.isBuffer(password)) - bufferCopy(password, packet, 0, passLen, p += 4); - else - packet.utf8Write(password, p += 4, passLen); - - if (newPassword) { - writeUInt32BE(packet, newPassLen, p += passLen); - if (Buffer.isBuffer(newPassword)) - bufferCopy(newPassword, packet, 0, newPassLen, p += 4); - else - packet.utf8Write(newPassword, p += 4, newPassLen); - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (changed password)' - ); - } else { - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (password)' - ); - } - - this._authsQueue.push('password'); - - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPK(username, pubKey, keyAlgo, cbSign) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - if (typeof keyAlgo === 'function') { - cbSign = keyAlgo; - keyAlgo = undefined; - } - if (!keyAlgo) - keyAlgo = keyType; - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyAlgo); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const payloadLen = - (cbSign ? 4 + sesLen : 0) - + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen; - let packet; - let p; - if (cbSign) { - packet = Buffer.allocUnsafe(payloadLen); - p = 0; - writeUInt32BE(packet, sesLen, p); - packet.set(sessionID, p += 4); - p += sesLen; - } else { - packet = this._packetRW.write.alloc(payloadLen); - p = this._packetRW.write.allocStart; - } - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = (cbSign ? 1 : 0); - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - if (!cbSign) { - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey -- check)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - return; - } - - cbSign(packet, (signature) => { - signature = convertSignature(signature, keyType); - if (signature === false) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - p = this._packetRW.write.allocStart; - packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 9 + 1 + 4 + algoLen + 4 + pubKeyLen + 4 - + 4 + algoLen + 4 + sigLen - ); - - // TODO: simply copy from original "packet" to new `packet` to avoid - // having to write each individual field a second time? - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 9, p += 14); - packet.utf8Write('publickey', p += 4, 9); - - packet[p += 9] = 1; - - writeUInt32BE(packet, algoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(packet, pubKeyLen, p += algoLen); - packet.set(pubKey, p += 4); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += pubKeyLen); - - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - // Servers shouldn't send packet type 60 in response to signed publickey - // attempts, but if they do, interpret as type 60. - this._authsQueue.push('publickey'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (publickey)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authHostbased(username, pubKey, hostname, userlocal, keyAlgo, cbSign) { - // TODO: Make DRY by sharing similar code with authPK() - if (this._server) - throw new Error('Client-only method called in server mode'); - - pubKey = parseKey(pubKey); - if (pubKey instanceof Error) - throw new Error('Invalid key'); - - const keyType = pubKey.type; - pubKey = pubKey.getPublicSSH(); - - if (typeof keyAlgo === 'function') { - cbSign = keyAlgo; - keyAlgo = undefined; - } - if (!keyAlgo) - keyAlgo = keyType; - - const userLen = Buffer.byteLength(username); - const algoLen = Buffer.byteLength(keyAlgo); - const pubKeyLen = pubKey.length; - const sessionID = this._kex.sessionID; - const sesLen = sessionID.length; - const hostnameLen = Buffer.byteLength(hostname); - const userlocalLen = Buffer.byteLength(userlocal); - const data = Buffer.allocUnsafe( - 4 + sesLen + 1 + 4 + userLen + 4 + 14 + 4 + 9 + 4 + algoLen - + 4 + pubKeyLen + 4 + hostnameLen + 4 + userlocalLen - ); - let p = 0; - - writeUInt32BE(data, sesLen, p); - data.set(sessionID, p += 4); - - data[p += sesLen] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(data, userLen, ++p); - data.utf8Write(username, p += 4, userLen); - - writeUInt32BE(data, 14, p += userLen); - data.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(data, 9, p += 14); - data.utf8Write('hostbased', p += 4, 9); - - writeUInt32BE(data, algoLen, p += 9); - data.utf8Write(keyAlgo, p += 4, algoLen); - - writeUInt32BE(data, pubKeyLen, p += algoLen); - data.set(pubKey, p += 4); - - writeUInt32BE(data, hostnameLen, p += pubKeyLen); - data.utf8Write(hostname, p += 4, hostnameLen); - - writeUInt32BE(data, userlocalLen, p += hostnameLen); - data.utf8Write(userlocal, p += 4, userlocalLen); - - cbSign(data, (signature) => { - signature = convertSignature(signature, keyType); - if (!signature) - throw new Error('Error while converting handshake signature'); - - const sigLen = signature.length; - const reqDataLen = (data.length - sesLen - 4); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - reqDataLen + 4 + 4 + algoLen + 4 + sigLen - ); - - bufferCopy(data, packet, 4 + sesLen, data.length, p); - - writeUInt32BE(packet, 4 + algoLen + 4 + sigLen, p += reqDataLen); - writeUInt32BE(packet, algoLen, p += 4); - packet.utf8Write(keyAlgo, p += 4, algoLen); - writeUInt32BE(packet, sigLen, p += algoLen); - packet.set(signature, p += 4); - - this._authsQueue.push('hostbased'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (hostbased)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - }); - } - authKeyboard(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + userLen + 4 + 14 + 4 + 20 + 4 + 4 - ); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 20, p += 14); - packet.utf8Write('keyboard-interactive', p += 4, 20); - - writeUInt32BE(packet, 0, p += 20); - - writeUInt32BE(packet, 0, p += 4); - - this._authsQueue.push('keyboard-interactive'); - - this._debug && this._debug( - 'Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authNone(username) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const userLen = Buffer.byteLength(username); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + userLen + 4 + 14 + 4 + 4); - - packet[p] = MESSAGE.USERAUTH_REQUEST; - - writeUInt32BE(packet, userLen, ++p); - packet.utf8Write(username, p += 4, userLen); - - writeUInt32BE(packet, 14, p += userLen); - packet.utf8Write('ssh-connection', p += 4, 14); - - writeUInt32BE(packet, 4, p += 14); - packet.utf8Write('none', p += 4, 4); - - this._authsQueue.push('none'); - - this._debug && this._debug('Outbound: Sending USERAUTH_REQUEST (none)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoRes(responses) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let responsesTotalLen = 0; - let responseLens; - - if (responses) { - responseLens = new Array(responses.length); - for (let i = 0; i < responses.length; ++i) { - const len = Buffer.byteLength(responses[i]); - responseLens[i] = len; - responsesTotalLen += 4 + len; - } - } - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + responsesTotalLen); - - packet[p] = MESSAGE.USERAUTH_INFO_RESPONSE; - - if (responses) { - writeUInt32BE(packet, responses.length, ++p); - p += 4; - for (let i = 0; i < responses.length; ++i) { - const len = responseLens[i]; - writeUInt32BE(packet, len, p); - p += 4; - if (len) { - packet.utf8Write(responses[i], p, len); - p += len; - } - } - } else { - writeUInt32BE(packet, 0, ++p); - } - - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_RESPONSE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // 'ssh-connection' service-specific - // --------------------------------- - tcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 13, ++p); - packet.utf8Write('tcpip-forward', p += 4, 13); - - packet[p += 13] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - cancelTcpipForward(bindAddr, bindPort, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const addrLen = Buffer.byteLength(bindAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + addrLen + 4); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 20, ++p); - packet.utf8Write('cancel-tcpip-forward', p += 4, 20); - - packet[p += 20] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, addrLen, ++p); - packet.utf8Write(bindAddr, p += 4, addrLen); - - writeUInt32BE(packet, bindPort, p += addrLen); - - this._debug - && this._debug('Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_streamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 31 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 31, ++p); - packet.utf8Write('streamlocal-forward@openssh.com', p += 4, 31); - - packet[p += 31] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)' +// pkg/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults ); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); } - openssh_cancelStreamLocalForward(socketPath, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const socketPathLen = Buffer.byteLength(socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 38 + 1 + 4 + socketPathLen - ); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 38, ++p); - packet.utf8Write('cancel-streamlocal-forward@openssh.com', p += 4, 38); - - packet[p += 38] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, socketPathLen, ++p); - packet.utf8Write(socketPath, p += 4, socketPathLen); - - if (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST ' - + '(cancel-streamlocal-forward@openssh.com)' +} +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); } - sendPacket(this, this._packetRW.write.finalize(packet)); + return cache[methodName]; } - directTcpip(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const srcLen = Buffer.byteLength(cfg.srcIP); - const dstLen = Buffer.byteLength(cfg.dstIP); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 12 + 4 + 4 + 4 + 4 + srcLen + 4 + 4 + dstLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 12, ++p); - packet.utf8Write('direct-tcpip', p += 4, 12); - - writeUInt32BE(packet, chan, p += 12); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, dstLen, p += 4); - packet.utf8Write(cfg.dstIP, p += 4, dstLen); - - writeUInt32BE(packet, cfg.dstPort, p += dstLen); - - writeUInt32BE(packet, srcLen, p += 4); - packet.utf8Write(cfg.srcIP, p += 4, srcLen); - - writeUInt32BE(packet, cfg.srcPort, p += srcLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, direct-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } - openssh_directStreamLocal(chan, initWindow, maxPacket, cfg) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 30 + 4 + 4 + 4 + 4 + pathLen + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 30, ++p); - packet.utf8Write('direct-streamlocal@openssh.com', p += 4, 30); - - writeUInt32BE(packet, chan, p += 30); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - // zero-fill reserved fields (string and uint32) - bufferFill(packet, 0, p += pathLen, p + 8); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, direct-streamlocal@openssh.com)` + return newMethods; +} +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` ); } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_noMoreSessions(wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 28 + 1); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 28, ++p); - packet.utf8Write('no-more-sessions@openssh.com', p += 4, 28); - - packet[p += 28] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug && this._debug( - 'Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)' - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args); } - session(chan, initWindow, maxPacket) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4); + return Object.assign(withDecorations, requestWithDefaults); +} - packet[p] = MESSAGE.CHANNEL_OPEN; +// pkg/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +legacyRestEndpointMethods.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - writeUInt32BE(packet, 7, ++p); - packet.utf8Write('session', p += 4, 7); - writeUInt32BE(packet, chan, p += 7); +/***/ }), - writeUInt32BE(packet, initWindow, p += 4); +/***/ 537: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - writeUInt32BE(packet, maxPacket, p += 4); +"use strict"; - this._debug - && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${chan}, session)`); - sendPacket(this, this._packetRW.write.finalize(packet)); +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 }); } - windowChange(chan, rows, cols, height, width) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 13, p += 4); - packet.utf8Write('window-change', p += 4, 13); - - packet[p += 13] = 0; - - writeUInt32BE(packet, cols, ++p); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, window-change)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - pty(chan, rows, cols, height, width, term, modes, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - if (!term || !term.length) - term = 'vt100'; - if (modes - && !Buffer.isBuffer(modes) - && !Array.isArray(modes) - && typeof modes === 'object' - && modes !== null) { - modes = modesToBytes(modes); - } - if (!modes || !modes.length) - modes = NO_TERMINAL_MODES_BUFFER; - - const termLen = term.length; - const modesLen = modes.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 4 + termLen + 4 + 4 + 4 + 4 + 4 + modesLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('pty-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, termLen, ++p); - packet.utf8Write(term, p += 4, termLen); - - writeUInt32BE(packet, cols, p += termLen); - - writeUInt32BE(packet, rows, p += 4); - - writeUInt32BE(packet, width, p += 4); - - writeUInt32BE(packet, height, p += 4); + 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); - writeUInt32BE(packet, modesLen, p += 4); - p += 4; - if (Array.isArray(modes)) { - for (let i = 0; i < modesLen; ++i) - packet[p++] = modes[i]; - } else if (Buffer.isBuffer(modes)) { - packet.set(modes, p); +// 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__(8932); +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._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, pty-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - shell(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 5, p += 4); - packet.utf8Write('shell', p += 4, 5); - - packet[p += 5] = (wantReply === undefined || wantReply === true ? 1 : 0); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, shell)`); - sendPacket(this, this._packetRW.write.finalize(packet)); + 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( + /(? { - writeUInt32BE(packet, cmdLen, ++p); - if (isBuf) - packet.set(cmd, p += 4); - else - packet.utf8Write(cmd, p += 4, cmdLen); +"use strict"; - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exec: ${cmd})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +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 }); } - signal(chan, signal) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const origSignal = signal; - - signal = signal.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); - - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); - - const signalLen = signal.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 6 + 1 + 4 + signalLen - ); + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - packet[p] = MESSAGE.CHANNEL_REQUEST; +// 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__(9440); +var import_universal_user_agent = __nccwpck_require__(5030); - writeUInt32BE(packet, chan, ++p); +// pkg/dist-src/version.js +var VERSION = "8.4.1"; - writeUInt32BE(packet, 6, p += 4); - packet.utf8Write('signal', p += 4, 6); +// 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); +} - packet[p += 6] = 0; +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(537); - writeUInt32BE(packet, signalLen, ++p); - packet.utf8Write(signal, p += 4, signalLen); +// pkg/dist-src/get-buffer-response.js +function getBufferResponse(response) { + return response.arrayBuffer(); +} - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, signal: ${signal})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +// pkg/dist-src/fetch-wrapper.js +function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + 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); } - env(chan, key, val, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const keyLen = Buffer.byteLength(key); - const isBuf = Buffer.isBuffer(val); - const valLen = (isBuf ? val.length : Buffer.byteLength(val)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 3 + 1 + 4 + keyLen + 4 + valLen - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 3, p += 4); - packet.utf8Write('env', p += 4, 3); - - packet[p += 3] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, keyLen, ++p); - packet.utf8Write(key, p += 4, keyLen); - - writeUInt32BE(packet, valLen, p += keyLen); - if (isBuf) - packet.set(val, p += 4); - else - packet.utf8Write(val, p += 4, valLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, env: ${key}=${val})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11Forward(chan, cfg, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - const protocol = cfg.protocol; - const cookie = cfg.cookie; - const isBufProto = Buffer.isBuffer(protocol); - const protoLen = (isBufProto - ? protocol.length - : Buffer.byteLength(protocol)); - const isBufCookie = Buffer.isBuffer(cookie); - const cookieLen = (isBufCookie - ? cookie.length - : Buffer.byteLength(cookie)); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 7 + 1 + 1 + 4 + protoLen + 4 + cookieLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 7, p += 4); - packet.utf8Write('x11-req', p += 4, 7); - - packet[p += 7] = (wantReply === undefined || wantReply === true ? 1 : 0); - - packet[++p] = (cfg.single ? 1 : 0); - - writeUInt32BE(packet, protoLen, ++p); - if (isBufProto) - packet.set(protocol, p += 4); - else - packet.utf8Write(protocol, p += 4, protoLen); - - writeUInt32BE(packet, cookieLen, p += protoLen); - if (isBufCookie) - packet.set(cookie, p += 4); - else - packet.latin1Write(cookie, p += 4, cookieLen); - - writeUInt32BE(packet, (cfg.screen || 0), p += cookieLen); - - this._debug - && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${chan}, x11-req)`); - sendPacket(this, this._packetRW.write.finalize(packet)); + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; } - subsystem(chan, name, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - const nameLen = Buffer.byteLength(name); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + nameLen); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 9, p += 4); - packet.utf8Write('subsystem', p += 4, 9); - - packet[p += 9] = (wantReply === undefined || wantReply === true ? 1 : 0); - - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(name, p += 4, nameLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, subsystem: ${name})` + 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" ); - sendPacket(this, this._packetRW.write.finalize(packet)); } - openssh_agentForward(chan, wantReply) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - // Does not consume window space - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 26, p += 4); - packet.utf8Write('auth-agent-req@openssh.com', p += 4, 26); - - packet[p += 26] = (wantReply === undefined || wantReply === true ? 1 : 0); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_REQUEST ' - + `(r:${chan}, auth-agent-req@openssh.com)` + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.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}` : ""}` ); } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_hostKeysProve(keys) { - if (this._server) - throw new Error('Client-only method called in server mode'); - - let keysTotal = 0; - const publicKeys = []; - for (const key of keys) { - const publicKey = key.getPublicSSH(); - keysTotal += 4 + publicKey.length; - publicKeys.push(publicKey); + if (status === 204 || status === 205) { + return; } - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 29 + 1 + keysTotal); - - packet[p] = MESSAGE.GLOBAL_REQUEST; - - writeUInt32BE(packet, 29, ++p); - packet.utf8Write('hostkeys-prove-00@openssh.com', p += 4, 29); - - packet[p += 29] = 1; // want reply - - ++p; - for (const buf of publicKeys) { - writeUInt32BE(packet, buf.length, p); - bufferCopy(buf, packet, 0, buf.length, p += 4); - p += buf.length; + 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 (this._debug) { - this._debug( - 'Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)' - ); + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); } - sendPacket(this, this._packetRW.write.finalize(packet)); - } - - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - - // Global - // ------ - serviceAccept(svcName) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const svcNameLen = Buffer.byteLength(svcName); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + svcNameLen); - - packet[p] = MESSAGE.SERVICE_ACCEPT; - - writeUInt32BE(packet, svcNameLen, ++p); - packet.utf8Write(svcName, p += 4, svcNameLen); - - this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${svcName})`); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._server && this._banner && svcName === 'ssh-userauth') { - const banner = this._banner; - this._banner = undefined; // Prevent banner from being displayed again - const bannerLen = Buffer.byteLength(banner); - p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + bannerLen + 4); - - packet[p] = MESSAGE.USERAUTH_BANNER; - - writeUInt32BE(packet, bannerLen, ++p); - packet.utf8Write(banner, p += 4, bannerLen); - - writeUInt32BE(packet, 0, p += bannerLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_BANNER'); - sendPacket(this, this._packetRW.write.finalize(packet)); + 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(() => ""); } - // 'ssh-connection' service-specific - forwardedTcpip(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const boundAddrLen = Buffer.byteLength(cfg.boundAddr); - const remoteAddrLen = Buffer.byteLength(cfg.remoteAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 15 + 4 + 4 + 4 + 4 + boundAddrLen + 4 + 4 + remoteAddrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 15, ++p); - packet.utf8Write('forwarded-tcpip', p += 4, 15); - - writeUInt32BE(packet, chan, p += 15); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, boundAddrLen, p += 4); - packet.utf8Write(cfg.boundAddr, p += 4, boundAddrLen); - - writeUInt32BE(packet, cfg.boundPort, p += boundAddrLen); - - writeUInt32BE(packet, remoteAddrLen, p += 4); - packet.utf8Write(cfg.remoteAddr, p += 4, remoteAddrLen); - - writeUInt32BE(packet, cfg.remotePort, p += remoteAddrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, forwarded-tcpip)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - x11(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const addrLen = Buffer.byteLength(cfg.originAddr); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 3 + 4 + 4 + 4 + 4 + addrLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 3, ++p); - packet.utf8Write('x11', p += 4, 3); - - writeUInt32BE(packet, chan, p += 3); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, addrLen, p += 4); - packet.utf8Write(cfg.originAddr, p += 4, addrLen); - - writeUInt32BE(packet, cfg.originPort, p += addrLen); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, x11)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - openssh_authAgent(chan, initWindow, maxPacket) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 22, ++p); - packet.utf8Write('auth-agent@openssh.com', p += 4, 22); - - writeUInt32BE(packet, chan, p += 22); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_OPEN (r:${chan}, auth-agent@openssh.com)` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); } - openssh_forwardedStreamLocal(chan, initWindow, maxPacket, cfg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const pathLen = Buffer.byteLength(cfg.socketPath); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 33 + 4 + 4 + 4 + 4 + pathLen + 4 - ); - - packet[p] = MESSAGE.CHANNEL_OPEN; - - writeUInt32BE(packet, 33, ++p); - packet.utf8Write('forwarded-streamlocal@openssh.com', p += 4, 33); - - writeUInt32BE(packet, chan, p += 33); - - writeUInt32BE(packet, initWindow, p += 4); - - writeUInt32BE(packet, maxPacket, p += 4); - - writeUInt32BE(packet, pathLen, p += 4); - packet.utf8Write(cfg.socketPath, p += 4, pathLen); - - writeUInt32BE(packet, 0, p += pathLen); - - if (this._debug) { - this._debug( - 'Outbound: Sending CHANNEL_OPEN ' - + `(r:${chan}, forwarded-streamlocal@openssh.com)` - ); + 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}`; } - sendPacket(this, this._packetRW.write.finalize(packet)); + return `${data.message}${suffix}`; } - exitStatus(chan, status) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4); - - packet[p] = MESSAGE.CHANNEL_REQUEST; - - writeUInt32BE(packet, chan, ++p); - - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-status', p += 4, 11); - - packet[p += 11] = 0; + return `Unknown error: ${JSON.stringify(data)}`; +} - writeUInt32BE(packet, status, ++p); +// 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) + }); +} - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-status: ${status})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); +// pkg/dist-src/index.js +var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` } - exitSignal(chan, name, coreDumped, msg) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - // Does not consume window space +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); - const origSignal = name; - if (typeof origSignal !== 'string' || !origSignal) - throw new Error(`Invalid signal: ${origSignal}`); +/***/ }), - let signal = name.toUpperCase(); - if (signal.slice(0, 3) === 'SIG') - signal = signal.slice(3); +/***/ 9809: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (SIGNALS[signal] !== 1) - throw new Error(`Invalid signal: ${origSignal}`); +"use strict"; - const nameLen = Buffer.byteLength(signal); - const msgLen = (msg ? Buffer.byteLength(msg) : 0); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + 4 + 11 + 1 + 4 + nameLen + 1 + 4 + msgLen + 4 - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(6575)); +const AuthAdminApi = GoTrueAdminApi_1.default; +exports["default"] = AuthAdminApi; +//# sourceMappingURL=AuthAdminApi.js.map - packet[p] = MESSAGE.CHANNEL_REQUEST; +/***/ }), - writeUInt32BE(packet, chan, ++p); +/***/ 4525: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - writeUInt32BE(packet, 11, p += 4); - packet.utf8Write('exit-signal', p += 4, 11); +"use strict"; - packet[p += 11] = 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(313)); +const AuthClient = GoTrueClient_1.default; +exports["default"] = AuthClient; +//# sourceMappingURL=AuthClient.js.map - writeUInt32BE(packet, nameLen, ++p); - packet.utf8Write(signal, p += 4, nameLen); +/***/ }), - packet[p += nameLen] = (coreDumped ? 1 : 0); +/***/ 6575: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - writeUInt32BE(packet, msgLen, ++p); +"use strict"; - p += 4; - if (msgLen) { - packet.utf8Write(msg, p, msgLen); - p += msgLen; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const fetch_1 = __nccwpck_require__(7072); +const helpers_1 = __nccwpck_require__(4044); +const types_1 = __nccwpck_require__(1852); +const errors_1 = __nccwpck_require__(9938); +class GoTrueAdminApi { + constructor({ url = '', headers = {}, fetch, }) { + this.url = url; + this.headers = headers; + this.fetch = (0, helpers_1.resolveFetch)(fetch); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this), + }; + this.oauth = { + listClients: this._listOAuthClients.bind(this), + createClient: this._createOAuthClient.bind(this), + getClient: this._getOAuthClient.bind(this), + updateClient: this._updateOAuthClient.bind(this), + deleteClient: this._deleteOAuthClient.bind(this), + regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this), + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) { + if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) { + throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(', ')}`); + } + try { + await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = tslib_1.__rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ('newEmail' in rest) { + // replace newEmail with new_email in request body + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body['newEmail']; + } + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/generate_link`, { + body: body, + headers: this.headers, + xform: fetch_1._generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { + data: { + properties: null, + user: null, + }, + error, + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: fetch_1._noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + (0, helpers_1.validateUUID)(id); + try { + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete, + }, + xform: fetch_1._userResponse, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + (0, helpers_1.validateUUID)(params.userId); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + }, + }); + return { data, error }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + (0, helpers_1.validateUUID)(params.userId); + (0, helpers_1.validateUUID)(params.id); + try { + const data = await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _listOAuthClients(params) { + var _a, _b, _c, _d, _e, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : '', + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : '', + }, + xform: fetch_1._noResolveJsonResponse, + }); + if (response.error) + throw response.error; + const clients = await response.json(); + const total = (_e = response.headers.get('x-total-count')) !== null && _e !== void 0 ? _e : 0; + const links = (_g = (_f = response.headers.get('link')) === null || _f === void 0 ? void 0 : _f.split(',')) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(';')[0].split('=')[1].substring(0, 1)); + const rel = JSON.parse(link.split(';')[1].split('=')[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { clients: [] }, error }; + } + throw error; + } + } + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _createOAuthClient(params) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _getOAuthClient(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _updateOAuthClient(clientId, params) { + try { + return await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/admin/oauth/clients/${clientId}`, { + body: params, + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _deleteOAuthClient(clientId) { + try { + await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + noResolveJson: true, + }); + return { data: null, error: null }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _regenerateOAuthClientSecret(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { + headers: this.headers, + xform: (client) => { + return { data: client, error: null }; + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } } +} +exports["default"] = GoTrueAdminApi; +//# sourceMappingURL=GoTrueAdminApi.js.map - writeUInt32BE(packet, 0, p); - - this._debug && this._debug( - `Outbound: Sending CHANNEL_REQUEST (r:${chan}, exit-signal: ${name})` - ); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - // 'ssh-userauth' service-specific - authFailure(authMethods, isPartial) { - if (!this._server) - throw new Error('Server-only method called in client mode'); +/***/ }), - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); +/***/ 313: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let methods; +"use strict"; - if (typeof authMethods === 'boolean') { - isPartial = authMethods; - authMethods = undefined; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(6575)); +const constants_1 = __nccwpck_require__(518); +const errors_1 = __nccwpck_require__(9938); +const fetch_1 = __nccwpck_require__(7072); +const helpers_1 = __nccwpck_require__(4044); +const local_storage_1 = __nccwpck_require__(5804); +const locks_1 = __nccwpck_require__(163); +const polyfills_1 = __nccwpck_require__(1897); +const version_1 = __nccwpck_require__(6677); +const base64url_1 = __nccwpck_require__(3649); +const ethereum_1 = __nccwpck_require__(9031); +const webauthn_1 = __nccwpck_require__(9451); +(0, polyfills_1.polyfillGlobalThis)(); // Make "globalThis" available +const DEFAULT_OPTIONS = { + url: constants_1.GOTRUE_URL, + storageKey: constants_1.STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: constants_1.DEFAULT_HEADERS, + flowType: 'implicit', + debug: false, + hasCustomAuthorizationHeader: false, + throwOnError: false, +}; +async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); +} +/** + * Caches JWKS values for all clients created in the same environment. This is + * especially useful for shared-memory execution environments such as Vercel's + * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how + * many clients are created, if they share the same storage key they will use + * the same JWKS cache, significantly speeding up getClaims() with asymmetric + * JWTs. + */ +const GLOBAL_JWKS = {}; +class GoTrueClient { + /** + * The JWKS used for verifying asymmetric JWTs + */ + get jwks() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; } - - if (authMethods) { - methods = []; - for (let i = 0; i < authMethods.length; ++i) { - if (authMethods[i].toLowerCase() === 'none') - continue; - methods.push(authMethods[i]); - } - methods = methods.join(','); - } else { - methods = ''; + set jwks(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); } - - const methodsLen = methods.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + methodsLen + 1); - - packet[p] = MESSAGE.USERAUTH_FAILURE; - - writeUInt32BE(packet, methodsLen, ++p); - packet.utf8Write(methods, p += 4, methodsLen); - - packet[p += methodsLen] = (isPartial === true ? 1 : 0); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_FAILURE'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authSuccess() { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0) - throw new Error('No auth in progress'); - - const p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1); - - packet[p] = MESSAGE.USERAUTH_SUCCESS; - - this._authsQueue.shift(); - this._authenticated = true; - - this._debug && this._debug('Outbound: Sending USERAUTH_SUCCESS'); - sendPacket(this, this._packetRW.write.finalize(packet)); - - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - } - authPKOK(keyAlgo, key) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - if (this._authsQueue.length === 0 || this._authsQueue[0] !== 'publickey') - throw new Error('"publickey" auth not in progress'); - - // TODO: support parsed key for `key` - - const keyAlgoLen = Buffer.byteLength(keyAlgo); - const keyLen = key.length; - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + keyAlgoLen + 4 + keyLen); - - packet[p] = MESSAGE.USERAUTH_PK_OK; - - writeUInt32BE(packet, keyAlgoLen, ++p); - packet.utf8Write(keyAlgo, p += 4, keyAlgoLen); - - writeUInt32BE(packet, keyLen, p += keyAlgoLen); - packet.set(key, p += 4); - - this._authsQueue.shift(); - - this._debug && this._debug('Outbound: Sending USERAUTH_PK_OK'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authPasswdChg(prompt) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - const promptLen = Buffer.byteLength(prompt); - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc(1 + 4 + promptLen + 4); - - packet[p] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ; - - writeUInt32BE(packet, promptLen, ++p); - packet.utf8Write(prompt, p += 4, promptLen); - - writeUInt32BE(packet, 0, p += promptLen); // Empty language tag - - this._debug && this._debug('Outbound: Sending USERAUTH_PASSWD_CHANGEREQ'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } - authInfoReq(name, instructions, prompts) { - if (!this._server) - throw new Error('Server-only method called in client mode'); - - let promptsLen = 0; - const nameLen = name ? Buffer.byteLength(name) : 0; - const instrLen = instructions ? Buffer.byteLength(instructions) : 0; - - for (let i = 0; i < prompts.length; ++i) - promptsLen += 4 + Buffer.byteLength(prompts[i].prompt) + 1; - - let p = this._packetRW.write.allocStart; - const packet = this._packetRW.write.alloc( - 1 + 4 + nameLen + 4 + instrLen + 4 + 4 + promptsLen - ); - - packet[p] = MESSAGE.USERAUTH_INFO_REQUEST; - - writeUInt32BE(packet, nameLen, ++p); - p += 4; - if (name) { - packet.utf8Write(name, p, nameLen); - p += nameLen; + get jwks_cached_at() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; } - - writeUInt32BE(packet, instrLen, p); - p += 4; - if (instructions) { - packet.utf8Write(instructions, p, instrLen); - p += instrLen; + set jwks_cached_at(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); } - - writeUInt32BE(packet, 0, p); - - writeUInt32BE(packet, prompts.length, p += 4); - p += 4; - for (let i = 0; i < prompts.length; ++i) { - const prompt = prompts[i]; - const promptLen = Buffer.byteLength(prompt.prompt); - - writeUInt32BE(packet, promptLen, p); - p += 4; - if (promptLen) { - packet.utf8Write(prompt.prompt, p, promptLen); - p += promptLen; - } - packet[p++] = (prompt.echo ? 1 : 0); + /** + * Create a new client for use in the browser. + */ + constructor(options) { + var _a, _b, _c; + /** + * @experimental + */ + this.userStorage = null; + this.memoryStorage = null; + this.stateChangeEmitters = new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + /** + * Keeps track of the async client initialization. + * When null or not yet resolved the auth state is `unknown` + * Once resolved the auth state is known and it's safe to call any further client methods. + * Keep extra care to never reject or throw uncaught errors + */ + this.initializePromise = null; + this.detectSessionInUrl = true; + this.hasCustomAuthorizationHeader = false; + this.suppressGetSessionWarning = false; + this.lockAcquired = false; + this.pendingInLock = []; + /** + * Used to broadcast state change events to other tabs listening. + */ + this.broadcastChannel = null; + this.logger = console.log; + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.storageKey = settings.storageKey; + this.instanceID = (_a = GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 0; + GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1; + this.logDebugMessages = !!settings.debug; + if (typeof settings.debug === 'function') { + this.logger = settings.debug; + } + if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { + const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`; + console.warn(message); + if (this.logDebugMessages) { + console.trace(message); + } + } + this.persistSession = settings.persistSession; + this.autoRefreshToken = settings.autoRefreshToken; + this.admin = new GoTrueAdminApi_1.default({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch, + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; + this.throwOnError = settings.throwOnError; + if (settings.lock) { + this.lock = settings.lock; + } + else if ((0, helpers_1.isBrowser)() && ((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.locks)) { + this.lock = locks_1.navigatorLock; + } + else { + this.lock = lockNoOp; + } + if (!this.jwks) { + this.jwks = { keys: [] }; + this.jwks_cached_at = Number.MIN_SAFE_INTEGER; + } + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + webauthn: new webauthn_1.WebAuthnApi(this), + }; + this.oauth = { + getAuthorizationDetails: this._getAuthorizationDetails.bind(this), + approveAuthorization: this._approveAuthorization.bind(this), + denyAuthorization: this._denyAuthorization.bind(this), + }; + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage; + } + else { + if ((0, helpers_1.supportsLocalStorage)()) { + this.storage = globalThis.localStorage; + } + else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + } + if (settings.userStorage) { + this.userStorage = settings.userStorage; + } + } + else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } + catch (e) { + console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e); + } + (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener('message', async (event) => { + this._debug('received broadcast notification from other tab or client', event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages + }); + } + this.initialize(); } - - this._debug && this._debug('Outbound: Sending USERAUTH_INFO_REQUEST'); - sendPacket(this, this._packetRW.write.finalize(packet)); - } -} - -// SSH-protoversion-softwareversion (SP comments) CR LF -const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/; - -// TODO: optimize this by starting n bytes from the end of this._buffer instead -// of the beginning -function parseHeader(chunk, p, len) { - let data; - let chunkOffset; - if (this._buffer) { - data = Buffer.allocUnsafe(this._buffer.length + (len - p)); - data.set(this._buffer, 0); - if (p === 0) { - data.set(chunk, this._buffer.length); - } else { - data.set(new Uint8Array(chunk.buffer, - chunk.byteOffset + p, - (len - p)), - this._buffer.length); + /** + * Returns whether error throwing mode is enabled for this client. + */ + isThrowOnErrorEnabled() { + return this.throwOnError; } - chunkOffset = this._buffer.length; - p = 0; - } else { - data = chunk; - chunkOffset = 0; - } - const op = p; - let start = p; - let end = p; - let needNL = false; - let lineLen = 0; - let lines = 0; - for (; p < data.length; ++p) { - const ch = data[p]; - - if (ch === 13 /* '\r' */) { - needNL = true; - continue; - } - - if (ch === 10 /* '\n' */) { - if (end > start - && end - start > 4 - && data[start] === 83 /* 'S' */ - && data[start + 1] === 83 /* 'S' */ - && data[start + 2] === 72 /* 'H' */ - && data[start + 3] === 45 /* '-' */) { - - const full = data.latin1Slice(op, end + 1); - const identRaw = (start === op ? full : full.slice(start - op)); - const m = RE_IDENT.exec(identRaw); - if (!m) - throw new Error('Invalid identification string'); - - const header = { - greeting: (start === op ? '' : full.slice(0, start - op)), - identRaw, - versions: { - protocol: m[1], - software: m[2], - }, - comments: m[3] - }; - - // Needed during handshake - this._remoteIdentRaw = Buffer.from(identRaw); - - this._debug && this._debug(`Remote ident: ${inspect(identRaw)}`); - this._compatFlags = getCompatFlags(header); - - this._buffer = undefined; - this._decipher = - new NullDecipher(0, onKEXPayload.bind(this, { firstPacket: true })); - this._parse = parsePacket; - - this._onHeader(header); - if (!this._destruct) { - // We disconnected inside _onHeader - return len; + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + _returnResult(result) { + if (this.throwOnError && result && result.error) { + throw result.error; } - - kexinit(this); - - return p + 1 - chunkOffset; - } - - // Only allow pre-ident greetings when we're a client - if (this._server) - throw new Error('Greetings from clients not permitted'); - - if (++lines > MAX_LINES) - throw new Error('Max greeting lines exceeded'); - - needNL = false; - start = p + 1; - lineLen = 0; - } else if (needNL) { - throw new Error('Invalid header: expected newline'); - } else if (++lineLen >= MAX_LINE_LEN) { - throw new Error('Header line too long'); + return result; } - - end = p; - } - if (!this._buffer) - this._buffer = bufferSlice(data, op); - - return p - chunkOffset; -} - -function parsePacket(chunk, p, len) { - return this._decipher.decrypt(chunk, p, len); -} - -function onPayload(payload) { - // XXX: move this to the Decipher implementations? - - this._onPacket(); - - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - payload = this._packetRW.read.read(payload); - - const type = payload[0]; - if (type === MESSAGE.USERAUTH_SUCCESS - && !this._server - && !this._authenticated) { - this._authenticated = true; - if (this._kex.negotiated.cs.compress === 'zlib@openssh.com') - this._packetRW.write = new ZlibPacketWriter(this); - if (this._kex.negotiated.sc.compress === 'zlib@openssh.com') - this._packetRW.read = new ZlibPacketReader(); - } - const handler = MESSAGE_HANDLERS[type]; - if (handler === undefined) { - this._debug && this._debug(`Inbound: Unsupported message type: ${type}`); - return; - } - - return handler(this, payload); -} - -function getCompatFlags(header) { - const software = header.versions.software; - - let flags = 0; - - for (const rule of COMPAT_CHECKS) { - if (typeof rule[0] === 'string') { - if (software === rule[0]) - flags |= rule[1]; - } else if (rule[0].test(software)) { - flags |= rule[1]; + _logPrefix() { + return ('GoTrueClient@' + + `${this.storageKey}:${this.instanceID} (${version_1.version}) ${new Date().toISOString()}`); } - } - - return flags; -} - -function modesToBytes(modes) { - const keys = Object.keys(modes); - const bytes = Buffer.allocUnsafe((5 * keys.length) + 1); - let b = 0; - - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (key === 'TTY_OP_END') - continue; - - const opcode = TERMINAL_MODE[key]; - if (opcode === undefined) - continue; - - const val = modes[key]; - if (typeof val === 'number' && isFinite(val)) { - bytes[b++] = opcode; - bytes[b++] = val >>> 24; - bytes[b++] = val >>> 16; - bytes[b++] = val >>> 8; - bytes[b++] = val; + _debug(...args) { + if (this.logDebugMessages) { + this.logger(this._logPrefix(), ...args); + } + return this; } - } - - bytes[b++] = TERMINAL_MODE.TTY_OP_END; - - if (b < bytes.length) - return bufferSlice(bytes, 0, b); - - return bytes; -} - -function sendExtInfo(proto) { - let serverSigAlgs = - 'ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521' - + 'rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss'; - if (eddsaSupported) - serverSigAlgs = `ssh-ed25519,${serverSigAlgs}`; - const algsLen = Buffer.byteLength(serverSigAlgs); - - let p = proto._packetRW.write.allocStart; - const packet = proto._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + algsLen); - - packet[p] = MESSAGE.EXT_INFO; - - writeUInt32BE(packet, 1, ++p); - - writeUInt32BE(packet, 15, p += 4); - packet.utf8Write('server-sig-algs', p += 4, 15); - - writeUInt32BE(packet, algsLen, p += 15); - packet.utf8Write(serverSigAlgs, p += 4, algsLen); - - proto._debug && proto._debug('Outbound: Sending EXT_INFO'); - sendPacket(proto, proto._packetRW.write.finalize(packet)); -} - -module.exports = Protocol; - - -/***/ }), - -/***/ 52026: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const EventEmitter = __nccwpck_require__(82361); -const fs = __nccwpck_require__(57147); -const { constants } = fs; -const { - Readable: ReadableStream, - Writable: WritableStream -} = __nccwpck_require__(12781); -const { inherits, types: { isDate } } = __nccwpck_require__(73837); - -const FastBuffer = Buffer[Symbol.species]; - -const { - bufferCopy, - bufferSlice, - makeBufferParser, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const ATTR = { - SIZE: 0x00000001, - UIDGID: 0x00000002, - PERMISSIONS: 0x00000004, - ACMODTIME: 0x00000008, - EXTENDED: 0x80000000, -}; - -// Large enough to store all possible attributes -const ATTRS_BUF = Buffer.alloc(28); - -const STATUS_CODE = { - OK: 0, - EOF: 1, - NO_SUCH_FILE: 2, - PERMISSION_DENIED: 3, - FAILURE: 4, - BAD_MESSAGE: 5, - NO_CONNECTION: 6, - CONNECTION_LOST: 7, - OP_UNSUPPORTED: 8 -}; - -const VALID_STATUS_CODES = new Map( - Object.values(STATUS_CODE).map((n) => [n, 1]) -); - -const STATUS_CODE_STR = { - [STATUS_CODE.OK]: 'No error', - [STATUS_CODE.EOF]: 'End of file', - [STATUS_CODE.NO_SUCH_FILE]: 'No such file or directory', - [STATUS_CODE.PERMISSION_DENIED]: 'Permission denied', - [STATUS_CODE.FAILURE]: 'Failure', - [STATUS_CODE.BAD_MESSAGE]: 'Bad message', - [STATUS_CODE.NO_CONNECTION]: 'No connection', - [STATUS_CODE.CONNECTION_LOST]: 'Connection lost', - [STATUS_CODE.OP_UNSUPPORTED]: 'Operation unsupported', -}; - -const REQUEST = { - INIT: 1, - OPEN: 3, - CLOSE: 4, - READ: 5, - WRITE: 6, - LSTAT: 7, - FSTAT: 8, - SETSTAT: 9, - FSETSTAT: 10, - OPENDIR: 11, - READDIR: 12, - REMOVE: 13, - MKDIR: 14, - RMDIR: 15, - REALPATH: 16, - STAT: 17, - RENAME: 18, - READLINK: 19, - SYMLINK: 20, - EXTENDED: 200 -}; - -const RESPONSE = { - VERSION: 2, - STATUS: 101, - HANDLE: 102, - DATA: 103, - NAME: 104, - ATTRS: 105, - EXTENDED: 201 -}; - -const OPEN_MODE = { - READ: 0x00000001, - WRITE: 0x00000002, - APPEND: 0x00000004, - CREAT: 0x00000008, - TRUNC: 0x00000010, - EXCL: 0x00000020 -}; - -const PKT_RW_OVERHEAD = 2 * 1024; -const MAX_REQID = 2 ** 32 - 1; -const CLIENT_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - REQUEST.INIT, - 0, 0, 0, 3 /* version */ -]); -const SERVER_VERSION_BUFFER = Buffer.from([ - 0, 0, 0, 5 /* length */, - RESPONSE.VERSION, - 0, 0, 0, 3 /* version */ -]); - -const RE_OPENSSH = /^SSH-2.0-(?:OpenSSH|dropbear)/; -const OPENSSH_MAX_PKT_LEN = 256 * 1024; - -const bufferParser = makeBufferParser(); - -const fakeStderr = { - readable: false, - writable: false, - push: (data) => {}, - once: () => {}, - on: () => {}, - emit: () => {}, - end: () => {}, -}; - -function noop() {} - -// Emulates enough of `Channel` to be able to be used as a drop-in replacement -// in order to process incoming data with as little overhead as possible -class SFTP extends EventEmitter { - constructor(client, chanInfo, cfg) { - super(); - - if (typeof cfg !== 'object' || !cfg) - cfg = {}; - - const remoteIdentRaw = client._protocol._remoteIdentRaw; - - this.server = !!cfg.server; - this._debug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - this._isOpenSSH = (remoteIdentRaw && RE_OPENSSH.test(remoteIdentRaw)); - - this._version = -1; - this._extensions = {}; - this._biOpt = cfg.biOpt; - this._pktLenBytes = 0; - this._pktLen = 0; - this._pktPos = 0; - this._pktType = 0; - this._pktData = undefined; - this._writeReqid = -1; - this._requests = {}; - this._maxInPktLen = OPENSSH_MAX_PKT_LEN; - this._maxOutPktLen = 34000; - this._maxReadLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - this._maxWriteLen = - (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34000) - PKT_RW_OVERHEAD; - - this.maxOpenHandles = undefined; - - // Channel compatibility - this._client = client; - this._protocol = client._protocol; - this._callbacks = []; - this._hasX11 = false; - this._exit = { - code: undefined, - signal: undefined, - dump: undefined, - desc: undefined, - }; - this._waitWindow = false; // SSH-level backpressure - this._chunkcb = undefined; - this._buffer = []; - this.type = chanInfo.type; - this.subtype = undefined; - this.incoming = chanInfo.incoming; - this.outgoing = chanInfo.outgoing; - this.stderr = fakeStderr; - this.readable = true; - } - - // This handles incoming data to parse - push(data) { - if (data === null) { - cleanupRequests(this); - if (!this.readable) - return; - // No more incoming data from the remote side - this.readable = false; - this.emit('end'); - return; + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize() { + if (this.initializePromise) { + return await this.initializePromise; + } + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize(); + }); + })(); + return await this.initializePromise; } - /* - uint32 length - byte type - byte[length - 1] data payload - */ - let p = 0; - - while (p < data.length) { - if (this._pktLenBytes < 4) { - let nb = Math.min(4 - this._pktLenBytes, data.length - p); - this._pktLenBytes += nb; - - while (nb--) - this._pktLen = (this._pktLen << 8) + data[p++]; - - if (this._pktLenBytes < 4) - return; - if (this._pktLen === 0) - return doFatalSFTPError(this, 'Invalid packet length'); - if (this._pktLen > this._maxInPktLen) { - const max = this._maxInPktLen; - return doFatalSFTPError( - this, - `Packet length ${this._pktLen} exceeds max length of ${max}` - ); + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + var _a; + try { + let params = {}; + let callbackUrlType = 'none'; + if ((0, helpers_1.isBrowser)()) { + params = (0, helpers_1.parseParametersFromURL)(window.location.href); + if (this._isImplicitGrantCallback(params)) { + callbackUrlType = 'implicit'; + } + else if (await this._isPKCECallback(params)) { + callbackUrlType = 'pkce'; + } + } + /** + * Attempt to get the session from the URL only if these conditions are fulfilled + * + * Note: If the URL isn't one of the callback url types (implicit or pkce), + * then there could be an existing session so we don't want to prematurely remove it + */ + if ((0, helpers_1.isBrowser)() && this.detectSessionInUrl && callbackUrlType !== 'none') { + const { data, error } = await this._getSessionFromURL(params, callbackUrlType); + if (error) { + this._debug('#_initialize()', 'error detecting session from URL', error); + if ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) { + const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; + if (errorCode === 'identity_already_exists' || + errorCode === 'identity_not_found' || + errorCode === 'single_identity_not_deletable') { + return { error }; + } + } + // failed login attempt via url, + // remove old session as in verifyOtp, signUp and signInWith* + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === 'recovery') { + await this._notifyAllSubscribers('PASSWORD_RECOVERY', session); + } + else { + await this._notifyAllSubscribers('SIGNED_IN', session); + } + }, 0); + return { error: null }; + } + // no login attempt via callback url try to recover session from storage + await this._recoverAndRefresh(); + return { error: null }; } - if (p >= data.length) - return; - } - if (this._pktPos < this._pktLen) { - const nb = Math.min(this._pktLen - this._pktPos, data.length - p); - if (p !== 0 || nb !== data.length) { - if (nb === this._pktLen) { - this._pkt = new FastBuffer(data.buffer, data.byteOffset + p, nb); - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._pktPos - ); - } - } else if (nb === this._pktLen) { - this._pkt = data; - } else { - if (!this._pkt) - this._pkt = Buffer.allocUnsafe(this._pktLen); - this._pkt.set(data, this._pktPos); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ error }); + } + return this._returnResult({ + error: new errors_1.AuthUnknownError('Unexpected error during initialization', error), + }); + } + finally { + await this._handleVisibilityChange(); + this._debug('#_initialize()', 'end'); + } + } + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + async signInAnonymously(credentials) { + var _a, _b, _c; + try { + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, + gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a, _b, _c; + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + xform: fetch_1._sessionResponse, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms', + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } - p += nb; - this._pktPos += nb; - if (this._pktPos < this._pktLen) - return; - } - - const type = this._pkt[0]; - const payload = this._pkt; - - // Prepare for next packet - this._pktLen = 0; - this._pktLenBytes = 0; - this._pkt = undefined; - this._pktPos = 0; - - const handler = (this.server - ? SERVER_HANDLERS[type] - : CLIENT_HANDLERS[type]); - if (!handler) - return doFatalSFTPError(this, `Unknown packet type ${type}`); - - if (this._version === -1) { - if (this.server) { - if (type !== REQUEST.INIT) - return doFatalSFTPError(this, `Expected INIT packet, got ${type}`); - } else if (type !== RESPONSE.VERSION) { - return doFatalSFTPError(this, `Expected VERSION packet, got ${type}`); + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + let res; + if ('email' in credentials) { + const { email, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponsePassword, + }); + } + else if ('phone' in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponsePassword, + }); + } + else { + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a password'); + } + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ + data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)), + error, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } - } - - if (handler(this, payload) === false) - return; } - } - - end() { - this.destroy(); - } - destroy() { - if (this.outgoing.state === 'open' || this.outgoing.state === 'eof') { - this.outgoing.state = 'closing'; - this._protocol.channelClose(this.outgoing.id); + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect, + }); } - } - _init() { - this._init = noop; - if (!this.server) - sendOrBuffer(this, CLIENT_VERSION_BUFFER); - } - - // =========================================================================== - // Client-specific =========================================================== - // =========================================================================== - createReadStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new ReadStream(this, path, options); - } - createWriteStream(path, options) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - return new WriteStream(this, path, options); - } - open(path, flags_, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + await this.initializePromise; + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode); + }); } - - const flags = (typeof flags_ === 'number' ? flags_ : stringToFlags(flags_)); - if (flags === null) - throw new Error(`Unknown flags string: ${flags_}`); - - let attrsFlags = 0; - let attrsLen = 0; - if (typeof attrs === 'string' || typeof attrs === 'number') - attrs = { mode: attrs }; - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - attrsFlags = attrs.flags; - attrsLen = attrs.nb; + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + async signInWithWeb3(credentials) { + const { chain } = credentials; + switch (chain) { + case 'ethereum': + return await this.signInWithEthereum(credentials); + case 'solana': + return await this.signInWithSolana(credentials); + default: + throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); + } } - - /* - uint32 id - string filename - uint32 pflags - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPEN; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - writeUInt32BE(buf, attrsFlags, p += 4); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + async signInWithEthereum(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; + // TODO: flatten type + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; + } + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('ethereum' in windowAny && + typeof windowAny.ethereum === 'object' && + 'request' in windowAny.ethereum && + typeof windowAny.ethereum.request === 'function') { + resolvedWallet = windowAny.ethereum; + } + else { + throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + const accounts = await resolvedWallet + .request({ + method: 'eth_requestAccounts', + }) + .then((accs) => accs) + .catch(() => { + throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); + }); + if (!accounts || accounts.length === 0) { + throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); + } + const address = (0, ethereum_1.getAddress)(accounts[0]); + let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; + if (!chainId) { + const chainIdHex = await resolvedWallet.request({ + method: 'eth_chainId', + }); + chainId = (0, ethereum_1.fromHex)(chainIdHex); + } + const siweMessage = { + domain: url.host, + address: address, + statement: statement, + uri: url.href, + version: '1', + chainId: chainId, + nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, + issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : new Date(), + expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, + notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, + requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, + resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources, + }; + message = (0, ethereum_1.createSiweMessage)(siweMessage); + // Sign message + signature = (await resolvedWallet.request({ + method: 'personal_sign', + params: [(0, ethereum_1.toHex)(message), address], + })); + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'ethereum', message, + signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } + : null)), + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPEN` - ); - } - close(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.CLOSE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} CLOSE` - ); - } - read(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off >= buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - - read_(this, handle, buf, off, len, position, cb); - } - readData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.read(handle, buf, off, len, position, cb); - } - write(handle, buf, off, len, position, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - if (!Buffer.isBuffer(buf)) - throw new Error('buffer is not a Buffer'); - if (off > buf.length) - throw new Error('offset is out of bounds'); - if (off + len > buf.length) - throw new Error('length extends beyond buffer'); - if (position === null) - throw new Error('null position currently unsupported'); - - if (!len) { - cb && process.nextTick(cb, undefined, 0); - return; + async signInWithSolana(credentials) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + let message; + let signature; + if ('message' in credentials) { + message = credentials.message; + signature = credentials.signature; + } + else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.'); + } + resolvedWallet = wallet; + } + else if (typeof wallet === 'object') { + resolvedWallet = wallet; + } + else { + const windowAny = window; + if ('solana' in windowAny && + typeof windowAny.solana === 'object' && + (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') || + ('signMessage' in windowAny.solana && + typeof windowAny.solana.signMessage === 'function'))) { + resolvedWallet = windowAny.solana; + } + else { + throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + if ('signIn' in resolvedWallet && resolvedWallet.signIn) { + const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { + // non-overridable properties + version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null))); + let outputToProcess; + if (Array.isArray(output) && output[0] && typeof output[0] === 'object') { + outputToProcess = output[0]; + } + else if (output && + typeof output === 'object' && + 'signedMessage' in output && + 'signature' in output) { + outputToProcess = output; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value'); + } + if ('signedMessage' in outputToProcess && + 'signature' in outputToProcess && + (typeof outputToProcess.signedMessage === 'string' || + outputToProcess.signedMessage instanceof Uint8Array) && + outputToProcess.signature instanceof Uint8Array) { + message = + typeof outputToProcess.signedMessage === 'string' + ? outputToProcess.signedMessage + : new TextDecoder().decode(outputToProcess.signedMessage); + signature = outputToProcess.signature; + } + else { + throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields'); + } + } + else { + if (!('signMessage' in resolvedWallet) || + typeof resolvedWallet.signMessage !== 'function' || + !('publicKey' in resolvedWallet) || + typeof resolvedWallet !== 'object' || + !resolvedWallet.publicKey || + !('toBase58' in resolvedWallet.publicKey) || + typeof resolvedWallet.publicKey.toBase58 !== 'function') { + throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API'); + } + message = [ + `${url.host} wants you to sign in with your Solana account:`, + resolvedWallet.publicKey.toBase58(), + ...(statement ? ['', statement, ''] : ['']), + 'Version: 1', + `URI: ${url.href}`, + `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`, + ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) + ? [`Not Before: ${options.signInWithSolana.notBefore}`] + : []), + ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime) + ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] + : []), + ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) + ? [`Chain ID: ${options.signInWithSolana.chainId}`] + : []), + ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []), + ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) + ? [`Request ID: ${options.signInWithSolana.requestId}`] + : []), + ...(((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) + ? [ + 'Resources', + ...options.signInWithSolana.resources.map((resource) => `- ${resource}`), + ] + : []), + ].join('\n'); + const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8'); + if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { + throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value'); + } + signature = maybeSignature; + } + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: 'solana', message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) + ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } + : null)), + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - - const maxDataLen = this._maxWriteLen; - const overflow = Math.max(len - maxDataLen, 0); - const origPosition = position; - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - string data - */ - const handleLen = handle.length; - let p = 9; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4 + len); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.WRITE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = position & 0xFF; - position /= 256; - } - writeUInt32BE(out, len, p += 8); - bufferCopy(buf, out, off, off + len, p += 4); - - this._requests[reqid] = { - cb: (err) => { - if (err) { - if (typeof cb === 'function') - cb(err); - } else if (overflow) { - this.write(handle, - buf, - off + len, - overflow, - origPosition + len, - cb); - } else if (typeof cb === 'function') { - cb(undefined, off + len); + async _exchangeCodeForSession(authCode) { + const storageItem = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/'); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier, + }, + xform: fetch_1._sessionResponse, + }); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error: invalidTokenError, + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error, + }); + } + throw error; } - } - }; - - const isSent = sendOrBuffer(this, out); - if (this._debug) { - const how = (isSent ? 'Sent' : 'Buffered'); - this._debug(`SFTP: Outbound: ${how} WRITE (id:${reqid})`); } - } - writeData(handle, buf, off, len, position, cb) { - // Backwards compatibility - this.write(handle, buf, off, len, position, cb); - } - fastGet(remotePath, localPath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(this, fs, remotePath, localPath, opts, cb); - } - fastPut(localPath, remotePath, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - fastXfer(fs, this, localPath, remotePath, opts, cb); - } - readFile(path, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('SIGNED_IN', data.session); + } + return this._returnResult({ data, error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - - if (typeof options === 'string') - options = { encoding: options, flag: 'r' }; - else if (!options) - options = { encoding: null, flag: 'r' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - const encoding = options.encoding; - if (encoding && !Buffer.isEncoding(encoding)) - throw new Error(`Unknown encoding: ${encoding}`); - - // First stat the file, so we know the size. - let size; - let buffer; // Single buffer with file data - let buffers; // List for when size is unknown - let pos = 0; - let handle; - - // SFTPv3 does not support using -1 for read position, so we have to track - // read position manually - let bytesRead = 0; - - const flag = options.flag || 'r'; - - const read = () => { - if (size === 0) { - buffer = Buffer.allocUnsafe(8192); - this.read(handle, buffer, 0, 8192, bytesRead, afterRead); - } else { - this.read(handle, buffer, pos, size - pos, bytesRead, afterRead); - } - }; - - const afterRead = (er, nbytes) => { - let eof; - if (er) { - eof = (er.code === STATUS_CODE.EOF); - if (!eof) { - return this.close(handle, () => { - return callback && callback(er); - }); + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e; + try { + if ('email' in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + if ('phone' in credentials) { + const { phone, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms', + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); + } + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number.'); } - } else { - eof = false; - } - - if (eof || (size === 0 && nbytes === 0)) - return close(); - - bytesRead += nbytes; - pos += nbytes; - if (size !== 0) { - if (pos === size) - close(); - else - read(); - } else { - // Unknown size, just read until we don't get bytes. - buffers.push(bufferSlice(buffer, 0, nbytes)); - read(); - } - }; - afterRead._wantEOFError = true; - - const close = () => { - this.close(handle, (er) => { - if (size === 0) { - // Collect the data into the buffers list. - buffer = Buffer.concat(buffers, pos); - } else if (pos < size) { - buffer = bufferSlice(buffer, 0, pos); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } - - if (encoding) - buffer = buffer.toString(encoding); - return callback && callback(er, buffer); - }); - }; - - this.open(path, flag, 0o666, (er, handle_) => { - if (er) - return callback && callback(er); - handle = handle_; - - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; + } + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + async verifyOtp(params) { + var _a, _b; + try { + let redirectTo = undefined; + let captchaToken = undefined; + if ('options' in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: fetch_1._sessionResponse, + }); + if (error) { + throw error; + } + if (!data) { + const tokenVerificationError = new Error('An error occurred on token verification.'); + throw tokenVerificationError; + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session); + } + return this._returnResult({ data: { user, session }, error: null }); } - - size = st.size || 0; - if (size === 0) { - // The kernel lies about many files. - // Go ahead and try to read some bytes. - buffers = []; - return read(); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; } - - buffer = Buffer.allocUnsafe(size); - read(); - }; - this.fstat(handle, tryStat); - }); - } - writeFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; } - - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'w' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'w' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (options.encoding && !Buffer.isEncoding(options.encoding)) - throw new Error(`Unknown encoding: ${options.encoding}`); - - const flag = options.flag || 'w'; - this.open(path, flag, options.mode, (openErr, handle) => { - if (openErr) { - callback && callback(openErr); - } else { - const buffer = (Buffer.isBuffer(data) - ? data - : Buffer.from('' + data, options.encoding || 'utf8')); - const position = (/a/.test(flag) ? null : 0); - - // SFTPv3 does not support the notion of 'current position' - // (null position), so we just attempt to append to the end of the file - // instead - if (position === null) { - const tryStat = (er, st) => { - if (er) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.stat(path, (er_, st_) => { - if (er_) { - return this.close(handle, () => { - callback && callback(er); - }); - } - tryStat(null, st_); - }); - return; - } - writeAll(this, handle, buffer, 0, buffer.length, st.size, callback); - }; - this.fstat(handle, tryStat); - return; + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a, _b, _c; + try { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const result = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) + ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } + : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + headers: this.headers, + xform: fetch_1._ssoResponse, + }); + return this._returnResult(result); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; } - writeAll(this, handle, buffer, 0, buffer.length, position, callback); - } - }); - } - appendFile(path, data, options, callback_) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let callback; - if (typeof callback_ === 'function') { - callback = callback_; - } else if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'string') - options = { encoding: options, mode: 0o666, flag: 'a' }; - else if (!options) - options = { encoding: 'utf8', mode: 0o666, flag: 'a' }; - else if (typeof options !== 'object') - throw new TypeError('Bad arguments'); - - if (!options.flag) - options = Object.assign({ flag: 'a' }, options); - this.writeFile(path, data, options, callback); - } - exists(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - this.stat(path, (err) => { - cb && cb(err ? false : true); - }); - } - unlink(filename, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string filename - */ - const fnameLen = Buffer.byteLength(filename); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + fnameLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REMOVE; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, fnameLen, p); - buf.utf8Write(filename, p += 4, fnameLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REMOVE` - ); - } - rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RENAME; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, oldLen, p); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RENAME` - ); - } - mkdir(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'function') { - cb = attrs; - attrs = undefined; } - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._reauthenticate(); + }); } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.MKDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + async _reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new errors_1.AuthSessionMissingError(); + const { error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} MKDIR` - ); - } - rmdir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.RMDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} RMDIR` - ); - } - readdir(where, opts, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (typeof opts === 'function') { - cb = opts; - opts = {}; + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + const endpoint = `${this.url}/resend`; + if ('email' in credentials) { + const { email, type, options } = credentials; + const { error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if ('phone' in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error, + }); + } + throw new errors_1.AuthInvalidCredentialsError('You must provide either an email or phone number and a type'); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - if (typeof opts !== 'object' || opts === null) - opts = {}; - - const doFilter = (opts && opts.full ? false : true); - - if (!Buffer.isBuffer(where) && typeof where !== 'string') - throw new Error('missing directory handle or path'); - - if (typeof where === 'string') { - const entries = []; - let e = 0; - - const reread = (err, handle) => { - if (err) - return cb(err); - - this.readdir(handle, opts, (err, list) => { - const eof = (err && err.code === STATUS_CODE.EOF); - - if (err && !eof) - return this.close(handle, () => cb(err)); - - if (eof) { - return this.close(handle, (err) => { - if (err) - return cb(err); - cb(undefined, entries); + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + async getSession() { + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result) => { + return result; }); - } - - for (let i = 0; i < list.length; ++i, ++e) - entries[e] = list[i]; - - reread(undefined, handle); }); - }; - return this.opendir(where, reread); - } - - /* - uint32 id - string handle - */ - const handleLen = where.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(where, p += 4); - - this._requests[reqid] = { - cb: (doFilter - ? (err, list) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - - for (let i = list.length - 1; i >= 0; --i) { - if (list[i].filename === '.' || list[i].filename === '..') - list.splice(i, 1); - } - - cb(undefined, list); - } - : cb) - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READDIR` - ); - } - fstat(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSTAT` - ); - } - stat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.STAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STAT` - ); - } - lstat(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.LSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} LSTAT` - ); - } - opendir(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.OPENDIR; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} OPENDIR` - ); - } - setstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SETSTAT` - ); - } - fsetstat(handle, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; - } - - /* - uint32 id - string handle - ATTRS attrs - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.FSETSTAT; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - buf.set(handle, p += 4); - writeUInt32BE(buf, flags, p += handleLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} FSETSTAT` - ); - } - futimes(handle, atime, mtime, cb) { - return this.fsetstat(handle, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - utimes(path, atime, mtime, cb) { - return this.setstat(path, { - atime: toUnixTimestamp(atime), - mtime: toUnixTimestamp(mtime) - }, cb); - } - fchown(handle, uid, gid, cb) { - return this.fsetstat(handle, { - uid: uid, - gid: gid - }, cb); - } - chown(path, uid, gid, cb) { - return this.setstat(path, { - uid: uid, - gid: gid - }, cb); - } - fchmod(handle, mode, cb) { - return this.fsetstat(handle, { - mode: mode - }, cb); - } - chmod(path, mode, cb) { - return this.setstat(path, { - mode: mode - }, cb); - } - readlink(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.READLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing link info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READLINK` - ); - } - symlink(targetPath, linkPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string linkpath - string targetpath - */ - const linkLen = Buffer.byteLength(linkPath); - const targetLen = Buffer.byteLength(targetPath); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + linkLen + 4 + targetLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.SYMLINK; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - if (this._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - writeUInt32BE(buf, targetLen, p); - buf.utf8Write(targetPath, p += 4, targetLen); - writeUInt32BE(buf, linkLen, p += targetLen); - buf.utf8Write(linkPath, p += 4, linkLen); - } else { - writeUInt32BE(buf, linkLen, p); - buf.utf8Write(linkPath, p += 4, linkLen); - writeUInt32BE(buf, targetLen, p += linkLen); - buf.utf8Write(targetPath, p += 4, targetLen); - } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} SYMLINK` - ); - } - realpath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - /* - uint32 id - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.REALPATH; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, pathLen, p); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing path info')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} REALPATH` - ); - } - // extended requests - ext_openssh_rename(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['posix-rename@openssh.com']; - if (!ext || ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "posix-rename@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 24, p); - buf.utf8Write('posix-rename@openssh.com', p += 4, 24); - writeUInt32BE(buf, oldLen, p += 24); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} posix-rename@openssh.com`); - } - } - ext_openssh_statvfs(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['statvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "statvfs@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 19, p); - buf.utf8Write('statvfs@openssh.com', p += 4, 19); - writeUInt32BE(buf, pathLen, p += 19); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { extended: 'statvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} statvfs@openssh.com`); - } - } - ext_openssh_fstatvfs(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fstatvfs@openssh.com']; - if (!ext || ext !== '2') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fstatvfs@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('fstatvfs@openssh.com', p += 4, 20); - writeUInt32BE(buf, handleLen, p += 20); - buf.set(handle, p += 4); - - this._requests[reqid] = { extended: 'fstatvfs@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} fstatvfs@openssh.com`); + return result; } - } - ext_openssh_hardlink(oldPath, newPath, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['hardlink@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "hardlink@openssh.com" - string oldpath - string newpath - */ - const oldLen = Buffer.byteLength(oldPath); - const newLen = Buffer.byteLength(newPath); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + oldLen + 4 + newLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('hardlink@openssh.com', p += 4, 20); - writeUInt32BE(buf, oldLen, p += 20); - buf.utf8Write(oldPath, p += 4, oldLen); - writeUInt32BE(buf, newLen, p += oldLen); - buf.utf8Write(newPath, p += 4, newLen); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${which} hardlink@openssh.com`); - } - } - ext_openssh_fsync(handle, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['fsync@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - /* - uint32 id - string "fsync@openssh.com" - string handle - */ - const handleLen = handle.length; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 17, p); - buf.utf8Write('fsync@openssh.com', p += 4, 17); - writeUInt32BE(buf, handleLen, p += 17); - buf.set(handle, p += 4); - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} fsync@openssh.com` - ); - } - ext_openssh_lsetstat(path, attrs, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['lsetstat@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - let flags = 0; - let attrsLen = 0; - - if (typeof attrs === 'object' && attrs !== null) { - attrs = attrsToBytes(attrs); - flags = attrs.flags; - attrsLen = attrs.nb; - } else if (typeof attrs === 'function') { - cb = attrs; + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug('#_acquireLock', 'begin', acquireTimeout); + try { + if (this.lockAcquired) { + const last = this.pendingInLock.length + ? this.pendingInLock[this.pendingInLock.length - 1] + : Promise.resolve(); + const result = (async () => { + await last; + return await fn(); + })(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + return result; + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey); + try { + this.lockAcquired = true; + const result = fn(); + this.pendingInLock.push((async () => { + try { + await result; + } + catch (e) { + // we just care if it finished + } + })()); + await result; + // keep draining the queue until there's nothing to wait on + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock]; + await Promise.all(waitOn); + this.pendingInLock.splice(0, waitOn.length); + } + return await result; + } + finally { + this._debug('#_acquireLock', 'lock released for storage key', this.storageKey); + this.lockAcquired = false; + } + }); + } + finally { + this._debug('#_acquireLock', 'end'); + } } - - /* - uint32 id - string "lsetstat@openssh.com" - string path - ATTRS attrs - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = - Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + pathLen + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 20, p); - buf.utf8Write('lsetstat@openssh.com', p += 4, 20); - - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - - writeUInt32BE(buf, flags, p += pathLen); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug('#_useSession', 'begin'); + try { + // the use of __loadSession here is the only correct use of the function! + const result = await this.__loadSession(); + return await fn(result); + } + finally { + this._debug('#_useSession', 'end'); + } } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} lsetstat@openssh.com`); + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug('#__loadSession()', 'begin'); + if (!this.lockAcquired) { + this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack); + } + try { + let currentSession = null; + const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + this._debug('#getSession()', 'session from storage', maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } + else { + this._debug('#getSession()', 'session from storage is not valid'); + await this._removeSession(); + } + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + // A session is considered expired before the access token _actually_ + // expires. When the autoRefreshToken option is off (or when the tab is + // in the background), very eager users of getSession() -- like + // realtime-js -- might send a valid JWT which will expire by the time it + // reaches the server. + const hasExpired = currentSession.expires_at + ? currentSession.expires_at * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS + : false; + this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at); + if (!hasExpired) { + if (this.userStorage) { + const maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); + if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { + currentSession.user = maybeUser.user; + } + else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + // Wrap the user object with a warning proxy on the server + // This warns when properties of the user are accessed, not when session.user itself is accessed + if (this.storage.isServer && + currentSession.user && + !currentSession.user.__isUserNotAvailableProxy) { + const suppressWarningRef = { value: this.suppressGetSessionWarning }; + currentSession.user = (0, helpers_1.insecureUserWarningProxy)(currentSession.user, suppressWarningRef); + // Update the client-level suppression flag when the proxy suppresses the warning + if (suppressWarningRef.value) { + this.suppressGetSessionWarning = true; + } + } + return { data: { session: currentSession }, error: null }; + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { session: null }, error }); + } + return this._returnResult({ data: { session }, error: null }); + } + finally { + this._debug('#__loadSession()', 'end'); + } } - } - ext_openssh_expandPath(path, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['expand-path@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - /* - uint32 id - string "expand-path@openssh.com" - string path - */ - const pathLen = Buffer.byteLength(path); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + pathLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 23, p); - buf.utf8Write('expand-path@openssh.com', p += 4, 23); - - writeUInt32BE(buf, pathLen, p += 20); - buf.utf8Write(path, p += 4, pathLen); - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing expanded path')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} expand-path@openssh.com`); + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + async getUser(jwt) { + if (jwt) { + return await this._getUser(jwt); + } + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return await this._getUser(); + }); + return result; } - } - ext_copy_data(srcHandle, srcOffset, len, dstHandle, dstOffset, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['copy-data']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - if (!Buffer.isBuffer(srcHandle)) - throw new Error('Source handle is not a Buffer'); - - if (!Buffer.isBuffer(dstHandle)) - throw new Error('Destination handle is not a Buffer'); - - /* - uint32 id - string "copy-data" - string read-from-handle - uint64 read-from-offset - uint64 read-data-length - string write-to-handle - uint64 write-to-offset - */ - let p = 0; - const buf = Buffer.allocUnsafe( - 4 + 1 - + 4 - + 4 + 9 - + 4 + srcHandle.length - + 8 - + 8 - + 4 + dstHandle.length - + 8 - ); - - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - - buf[p] = REQUEST.EXTENDED; - ++p; - - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - - writeUInt32BE(buf, 9, p); - p += 4; - buf.utf8Write('copy-data', p, 9); - p += 9; - - writeUInt32BE(buf, srcHandle.length, p); - p += 4; - buf.set(srcHandle, p); - p += srcHandle.length; - - for (let i = 7; i >= 0; --i) { - buf[p + i] = srcOffset & 0xFF; - srcOffset /= 256; + async _getUser(jwt) { + try { + if (jwt) { + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: jwt, + xform: fetch_1._userResponse, + }); + } + return await this._useSession(async (result) => { + var _a, _b, _c; + const { data, error } = result; + if (error) { + throw error; + } + // returns an error if there is no access_token or custom authorization header + if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new errors_1.AuthSessionMissingError() }; + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/user`, { + headers: this.headers, + jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined, + xform: fetch_1._userResponse, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + if ((0, errors_1.isAuthSessionMissingError)(error)) { + // JWT contains a `session_id` which does not correspond to an active + // session in the database, indicating the user is signed out. + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } } - p += 8; - - for (let i = 7; i >= 0; --i) { - buf[p + i] = len & 0xFF; - len /= 256; + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options); + }); } - p += 8; - - writeUInt32BE(buf, dstHandle.length, p); - p += 4; - buf.set(dstHandle, p); - p += dstHandle.length; - - for (let i = 7; i >= 0; --i) { - buf[p + i] = dstOffset & 0xFF; - dstOffset /= 256; + async _updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new errors_1.AuthSessionMissingError(); + } + const session = sessionData.session; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce' && attributes.email != null) { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { data, error: userError } = await (0, fetch_1._request)(this.fetch, 'PUT', `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + jwt: session.access_token, + xform: fetch_1._userResponse, + }); + if (userError) { + throw userError; + } + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers('USER_UPDATED', session); + return this._returnResult({ data: { user: session.user }, error: null }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } } - - this._requests[reqid] = { cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} copy-data`); + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession); + }); } - } - ext_home_dir(username, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['home-directory']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - if (typeof username !== 'string') - throw new TypeError('username is not a string'); - - /* - uint32 id - string "home-directory" - string username - */ - let p = 0; - const usernameLen = Buffer.byteLength(username); - const buf = Buffer.allocUnsafe( - 4 + 1 - + 4 - + 4 + 14 - + 4 + usernameLen - ); - - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - - buf[p] = REQUEST.EXTENDED; - ++p; - - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - - writeUInt32BE(buf, 14, p); - p += 4; - buf.utf8Write('home-directory', p, 14); - p += 14; - - writeUInt32BE(buf, usernameLen, p); - p += 4; - buf.utf8Write(username, p, usernameLen); - p += usernameLen; - - this._requests[reqid] = { - cb: (err, names) => { - if (typeof cb !== 'function') - return; - if (err) - return cb(err); - if (!names || !names.length) - return cb(new Error('Response missing home directory')); - cb(undefined, names[0].filename); - } - }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} home-directory`); + async _setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new errors_1.AuthSessionMissingError(); + } + const timeNow = Date.now() / 1000; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const { payload } = (0, helpers_1.decodeJWT)(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } + else { + const { data, error } = await this._getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: 'bearer', + expires_in: expiresAt - timeNow, + expires_at: expiresAt, + }; + await this._saveSession(session); + await this._notifyAllSubscribers('SIGNED_IN', session); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } } - } - ext_users_groups(uids, gids, cb) { - if (this.server) - throw new Error('Client-only method called in server mode'); - - const ext = this._extensions['users-groups-by-id@openssh.com']; - if (ext !== '1') - throw new Error('Server does not support this extended request'); - - if (!Array.isArray(uids)) - throw new TypeError('uids is not an array'); - for (const val of uids) { - if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) - throw new Error('uid values must all be 32-bit unsigned integers'); + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession); + }); } - if (!Array.isArray(gids)) - throw new TypeError('gids is not an array'); - for (const val of gids) { - if (!Number.isInteger(val) || val < 0 || val > (2 ** 32 - 1)) - throw new Error('gid values must all be 32-bit unsigned integers'); + async _refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error } = result; + if (error) { + throw error; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new errors_1.AuthSessionMissingError(); + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error: error }); + } + if (!session) { + return this._returnResult({ data: { user: null, session: null }, error: null }); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } } - - /* - uint32 id - string "users-groups-by-id@openssh.com" - string uids - uint32 uid1 - ... - string gids - uint32 gid1 - ... - */ - let p = 0; - const buf = Buffer.allocUnsafe( - 4 + 1 - + 4 - + 4 + 30 - + 4 + (4 * uids.length) - + 4 + (4 * gids.length) - ); - - writeUInt32BE(buf, buf.length - 4, p); - p += 4; - - buf[p] = REQUEST.EXTENDED; - ++p; - - const reqid = this._writeReqid = (this._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, p); - p += 4; - - writeUInt32BE(buf, 30, p); - p += 4; - buf.utf8Write('users-groups-by-id@openssh.com', p, 30); - p += 30; - - writeUInt32BE(buf, 4 * uids.length, p); - p += 4; - for (const val of uids) { - writeUInt32BE(buf, val, p); - p += 4; + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(params, callbackUrlType) { + try { + if (!(0, helpers_1.isBrowser)()) + throw new errors_1.AuthImplicitGrantRedirectError('No browser detected.'); + // If there's an error in the URL, it doesn't matter what flow it is, we just return the error. + if (params.error || params.error_description || params.error_code) { + // The error class returned implies that the redirect is from an implicit grant flow + // but it could also be from a redirect error from a PKCE flow. + throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', { + error: params.error || 'unspecified_error', + code: params.error_code || 'unspecified_code', + }); + } + // Checks for mismatches between the flowType initialised in the client and the URL parameters + switch (callbackUrlType) { + case 'implicit': + if (this.flowType === 'pkce') { + throw new errors_1.AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.'); + } + break; + case 'pkce': + if (this.flowType === 'implicit') { + throw new errors_1.AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.'); + } + break; + default: + // there's no mismatch so we continue + } + // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange + if (callbackUrlType === 'pkce') { + this._debug('#_initialize()', 'begin', 'is PKCE flow', true); + if (!params.code) + throw new errors_1.AuthPKCEGrantCodeExchangeError('No code detected.'); + const { data, error } = await this._exchangeCodeForSession(params.code); + if (error) + throw error; + const url = new URL(window.location.href); + url.searchParams.delete('code'); + window.history.replaceState(window.history.state, '', url.toString()); + return { data: { session: data.session, redirectType: null }, error: null }; + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new errors_1.AuthImplicitGrantRedirectError('No session defined in URL'); + } + const timeNow = Math.round(Date.now() / 1000); + const expiresIn = parseInt(expires_in); + let expiresAt = timeNow + expiresIn; + if (expires_at) { + expiresAt = parseInt(expires_at); + } + const actuallyExpiresIn = expiresAt - timeNow; + if (actuallyExpiresIn * 1000 <= constants_1.AUTO_REFRESH_TICK_DURATION_MS) { + console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); + } + const issuedAt = expiresAt - expiresIn; + if (timeNow - issuedAt >= 120) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow); + } + else if (timeNow - issuedAt < 0) { + console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow); + } + const { data, error } = await this._getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type: token_type, + user: data.user, + }; + // Remove tokens from URL + window.location.hash = ''; + this._debug('#_getSessionFromURL()', 'clearing window.location.hash'); + return this._returnResult({ data: { session, redirectType: params.type }, error: null }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, redirectType: null }, error }); + } + throw error; + } } - - writeUInt32BE(buf, 4 * gids.length, p); - p += 4; - for (const val of gids) { - writeUInt32BE(buf, val, p); - p += 4; + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantCallback(params) { + return Boolean(params.access_token || params.error_description); } - - this._requests[reqid] = { extended: 'users-groups-by-id@openssh.com', cb }; - - const isBuffered = sendOrBuffer(this, buf); - if (this._debug) { - const status = (isBuffered ? 'Buffered' : 'Sending'); - this._debug(`SFTP: Outbound: ${status} users-groups-by-id@openssh.com`); + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCECallback(params) { + const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); } - } - // =========================================================================== - // Server-specific =========================================================== - // =========================================================================== - handle(reqid, handle) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Buffer.isBuffer(handle)) - throw new Error('handle is not a Buffer'); - - const handleLen = handle.length; - - if (handleLen > 256) - throw new Error('handle too large (> 256 bytes)'); - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.HANDLE; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, handleLen, p); - if (handleLen) - buf.set(handle, p += 4); - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} HANDLE` - ); - } - status(reqid, code, message) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!VALID_STATUS_CODES.has(code)) - throw new Error(`Bad status code: ${code}`); - - message || (message = ''); - - const msgLen = Buffer.byteLength(message); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + msgLen + 4); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.STATUS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, code, p); - - writeUInt32BE(buf, msgLen, p += 4); - p += 4; - if (msgLen) { - buf.utf8Write(message, p, msgLen); - p += msgLen; + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + async signOut(options = { scope: 'global' }) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._signOut(options); + }); } - - writeUInt32BE(buf, 0, p); // Empty language tag - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} STATUS` - ); - } - data(reqid, data, encoding) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - const isBuffer = Buffer.isBuffer(data); - - if (!isBuffer && typeof data !== 'string') - throw new Error('data is not a Buffer or string'); - - let isUTF8; - if (!isBuffer && !encoding) { - encoding = undefined; - isUTF8 = true; + async _signOut({ scope } = { scope: 'global' }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ error: sessionError }); + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + // ignore 404s since user might not exist anymore + // ignore 401s since an invalid or expired JWT should sign out the current session + if (!((0, errors_1.isAuthApiError)(error) && + (error.status === 404 || error.status === 401 || error.status === 403))) { + return this._returnResult({ error }); + } + } + } + if (scope !== 'others') { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ error: null }); + }); } - - const dataLen = ( - isBuffer - ? data.length - : Buffer.byteLength(data, encoding) - ); - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + dataLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.DATA; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, dataLen, p); - if (dataLen) { - if (isBuffer) - buf.set(data, p += 4); - else if (isUTF8) - buf.utf8Write(data, p += 4, dataLen); - else - buf.write(data, p += 4, dataLen, encoding); + onAuthStateChange(callback) { + const id = (0, helpers_1.uuid)(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug('#unsubscribe()', 'state change callback with id removed', id); + this.stateChangeEmitters.delete(id); + }, + }; + this._debug('#onAuthStateChange()', 'registered callback with id', id); + this.stateChangeEmitters.set(id, subscription); + (async () => { + await this.initializePromise; + await this._acquireLock(-1, async () => { + this._emitInitialSession(id); + }); + })(); + return { data: { subscription } }; } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} DATA` - ); - } - name(reqid, names) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (!Array.isArray(names)) { - if (typeof names !== 'object' || names === null) - throw new Error('names is not an object or array'); - names = [ names ]; + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error, } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session)); + this._debug('INITIAL_SESSION', 'callback id', id, 'session', session); + } + catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null)); + this._debug('INITIAL_SESSION', 'callback id', id, 'error', err); + console.error(err); + } + }); } - - const count = names.length; - let namesLen = 0; - let nameAttrs; - const attrs = []; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - namesLen += 4 + Buffer.byteLength(filename); - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - namesLen += 4 + Buffer.byteLength(longname); - - if (typeof name.attrs === 'object' && name.attrs !== null) { - nameAttrs = attrsToBytes(name.attrs); - namesLen += 4 + nameAttrs.nb; - - if (nameAttrs.nb) { - let bytes; - - if (nameAttrs.nb === ATTRS_BUF.length) { - bytes = new Uint8Array(ATTRS_BUF); - } else { - bytes = new Uint8Array(nameAttrs.nb); - bufferCopy(ATTRS_BUF, bytes, 0, nameAttrs.nb, 0); - } - - nameAttrs.bytes = bytes; + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === 'pkce') { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey, true // isPasswordRecovery + ); + } + try { + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken }, + }, + headers: this.headers, + redirectTo: options.redirectTo, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; } - - attrs.push(nameAttrs); - } else { - namesLen += 4; - attrs.push(null); - } } - - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + namesLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.NAME; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, count, p); - - p += 4; - - for (let i = 0; i < count; ++i) { - const name = names[i]; - - { - const filename = ( - !name || !name.filename || typeof name.filename !== 'string' - ? '' - : name.filename - ); - const len = Buffer.byteLength(filename); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(filename, p, len); - p += len; + /** + * Gets all the identities linked to a user. + */ + async getUserIdentities() { + var _a; + try { + const { data, error } = await this.getUser(); + if (error) + throw error; + return this._returnResult({ data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }); } - } - - { - const longname = ( - !name || !name.longname || typeof name.longname !== 'string' - ? '' - : name.longname - ); - const len = Buffer.byteLength(longname); - writeUInt32BE(buf, len, p); - p += 4; - if (len) { - buf.utf8Write(longname, p, len); - p += len; + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; } - } - - const attr = attrs[i]; - if (attr) { - writeUInt32BE(buf, attr.flags, p); - p += 4; - if (attr.flags && attr.bytes) { - buf.set(attr.bytes, p); - p += attr.nb; + } + async linkIdentity(credentials) { + if ('token' in credentials) { + return this.linkIdentityIdToken(credentials); } - } else { - writeUInt32BE(buf, 0, p); - p += 4; - } + return this.linkIdentityOAuth(credentials); } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} NAME` - ); - } - attrs(reqid, attrs) { - if (!this.server) - throw new Error('Server-only method called in client mode'); - - if (typeof attrs !== 'object' || attrs === null) - throw new Error('attrs is not an object'); - - attrs = attrsToBytes(attrs); - const flags = attrs.flags; - const attrsLen = attrs.nb; - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + attrsLen); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = RESPONSE.ATTRS; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, flags, p); - if (attrsLen) { - p += 4; - - if (attrsLen === ATTRS_BUF.length) - buf.set(ATTRS_BUF, p); - else - bufferCopy(ATTRS_BUF, buf, 0, attrsLen, p); - - p += attrsLen; + async linkIdentityOAuth(credentials) { + var _a; + try { + const { data, error } = await this._useSession(async (result) => { + var _a, _b, _c, _d, _e; + const { data, error } = result; + if (error) + throw error; + const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: true, + }); + return await (0, fetch_1._request)(this.fetch, 'GET', url, { + headers: this.headers, + jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined, + }); + }); + if (error) + throw error; + if ((0, helpers_1.isBrowser)() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { + window.location.assign(data === null || data === void 0 ? void 0 : data.url); + } + return this._returnResult({ + data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, + error: null, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { provider: credentials.provider, url: null }, error }); + } + throw error; + } } - - const isBuffered = sendOrBuffer(this, buf); - this._debug && this._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} ATTRS` - ); - } -} - -function tryCreateBuffer(size) { - try { - return Buffer.allocUnsafe(size); - } catch (ex) { - return ex; - } -} - -function read_(self, handle, buf, off, len, position, cb, req_) { - const maxDataLen = self._maxReadLen; - const overflow = Math.max(len - maxDataLen, 0); - - if (overflow) - len = maxDataLen; - - /* - uint32 id - string handle - uint64 offset - uint32 len - */ - const handleLen = handle.length; - let p = 9; - let pos = position; - const out = Buffer.allocUnsafe(4 + 1 + 4 + 4 + handleLen + 8 + 4); - - writeUInt32BE(out, out.length - 4, 0); - out[4] = REQUEST.READ; - const reqid = self._writeReqid = (self._writeReqid + 1) & MAX_REQID; - writeUInt32BE(out, reqid, 5); - - writeUInt32BE(out, handleLen, p); - out.set(handle, p += 4); - p += handleLen; - for (let i = 7; i >= 0; --i) { - out[p + i] = pos & 0xFF; - pos /= 256; - } - writeUInt32BE(out, len, p += 8); - - if (typeof cb !== 'function') - cb = noop; - - const req = (req_ || { - nb: 0, - position, - off, - origOff: off, - len: undefined, - overflow: undefined, - cb: (err, data, nb) => { - const len = req.len; - const overflow = req.overflow; - - if (err) { - if (cb._wantEOFError || err.code !== STATUS_CODE.EOF) - return cb(err); - } else if (nb > len) { - return cb(new Error('Received more data than requested')); - } else if (nb === len && overflow) { - req.nb += nb; - req.position += nb; - req.off += nb; - read_(self, handle, buf, req.off, overflow, req.position, cb, req); - return; - } - - nb = (nb || 0); - if (req.origOff === 0 && buf.length === req.nb) - data = buf; - else - data = bufferSlice(buf, req.origOff, req.origOff + req.nb + nb); - cb(undefined, req.nb + nb, data, req.position); - }, - buffer: undefined, - }); - - req.len = len; - req.overflow = overflow; - - // TODO: avoid creating multiple buffer slices when we need to re-call read_() - // because of overflow - req.buffer = bufferSlice(buf, off, off + len); - - self._requests[reqid] = req; - - const isBuffered = sendOrBuffer(self, out); - self._debug && self._debug( - `SFTP: Outbound: ${isBuffered ? 'Buffered' : 'Sending'} READ` - ); -} - -function fastXfer(src, dst, srcPath, dstPath, opts, cb) { - let concurrency = 64; - let chunkSize = 32768; - let onstep; - let mode; - let fileSize; - - if (typeof opts === 'function') { - cb = opts; - } else if (typeof opts === 'object' && opts !== null) { - if (typeof opts.concurrency === 'number' - && opts.concurrency > 0 - && !isNaN(opts.concurrency)) { - concurrency = opts.concurrency; - } - if (typeof opts.chunkSize === 'number' - && opts.chunkSize > 0 - && !isNaN(opts.chunkSize)) { - chunkSize = opts.chunkSize; - } - if (typeof opts.fileSize === 'number' - && opts.fileSize > 0 - && !isNaN(opts.fileSize)) { - fileSize = opts.fileSize; - } - if (typeof opts.step === 'function') - onstep = opts.step; - - if (typeof opts.mode === 'string' || typeof opts.mode === 'number') - mode = modeNum(opts.mode); - } - - // Internal state variables - let fsize; - let pdst = 0; - let total = 0; - let hadError = false; - let srcHandle; - let dstHandle; - let readbuf; - let bufsize = chunkSize * concurrency; - - function onerror(err) { - if (hadError) - return; - - hadError = true; - - let left = 0; - let cbfinal; - - if (srcHandle || dstHandle) { - cbfinal = () => { - if (--left === 0) - cb(err); - }; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - ++left; - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - ++left; - if (srcHandle && (src === fs || src.outgoing.state === 'open')) - src.close(srcHandle, cbfinal); - if (dstHandle && (dst === fs || dst.outgoing.state === 'open')) - dst.close(dstHandle, cbfinal); - } else { - cb(err); + async linkIdentityIdToken(credentials) { + return await this._useSession(async (result) => { + var _a; + try { + const { error: sessionError, data: { session }, } = result; + if (sessionError) + throw sessionError; + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined, + body: { + provider, + id_token: token, + access_token, + nonce, + link_identity: true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + }, + xform: fetch_1._sessionResponse, + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + else if (!data || !data.session || !data.user) { + return this._returnResult({ + data: { user: null, session: null }, + error: new errors_1.AuthInvalidTokenResponseError(), + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers('USER_UPDATED', data.session); + } + return this._returnResult({ data, error }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + }); } - } - - src.open(srcPath, 'r', (err, sourceHandle) => { - if (err) - return onerror(err); - - srcHandle = sourceHandle; - - if (fileSize === undefined) - src.fstat(srcHandle, tryStat); - else - tryStat(null, { size: fileSize }); - - function tryStat(err, attrs) { - if (err) { - if (src !== fs) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - src.stat(srcPath, (err_, attrs_) => { - if (err_) - return onerror(err); - tryStat(null, attrs_); - }); - return; - } - return onerror(err); - } - fsize = attrs.size; - - dst.open(dstPath, 'w', (err, destHandle) => { - if (err) - return onerror(err); - - dstHandle = destHandle; - - if (fsize <= 0) - return onerror(); - - // Use less memory where possible - while (bufsize > fsize) { - if (concurrency === 1) { - bufsize = fsize; - break; - } - bufsize -= chunkSize; - --concurrency; + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + async unlinkIdentity(identity) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined, + }); + }); } - - readbuf = tryCreateBuffer(bufsize); - if (readbuf instanceof Error) - return onerror(readbuf); - - if (mode !== undefined) { - dst.fchmod(dstHandle, mode, function tryAgain(err) { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() - // for whatever reason - dst.chmod(dstPath, mode, (err_) => tryAgain()); - return; + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); } - startReads(); - }); - } else { - startReads(); + throw error; } - - function onread(err, nb, data, dstpos, datapos, origChunkLen) { - if (err) - return onerror(err); - - datapos = datapos || 0; - - dst.write(dstHandle, readbuf, datapos, nb, dstpos, writeCb); - - function writeCb(err) { - if (err) - return onerror(err); - - total += nb; - onstep && onstep(total, nb, fsize); - - if (nb < origChunkLen) - return singleRead(datapos, dstpos + nb, origChunkLen - nb); - - if (total === fsize) { - dst.close(dstHandle, (err) => { - dstHandle = undefined; - if (err) - return onerror(err); - src.close(srcHandle, (err) => { - srcHandle = undefined; - if (err) - return onerror(err); - cb(); + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + const startedAt = Date.now(); + // will attempt to refresh the token with exponential backoff + return await (0, helpers_1.retryable)(async (attempt) => { + if (attempt > 0) { + await (0, helpers_1.sleep)(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ... + } + this._debug(debugName, 'refreshing attempt', attempt); + return await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: fetch_1._sessionResponse, }); - }); - return; - } - - if (pdst >= fsize) - return; - - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(datapos, pdst, chunk); - pdst += chunk; - } + }, (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt); + return (error && + (0, errors_1.isAuthRetryableFetchError)(error) && + // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < constants_1.AUTO_REFRESH_TICK_DURATION_MS); + }); } - - function makeCb(psrc, pdst, chunk) { - return (err, nb, data) => { - onread(err, nb, data, pdst, psrc, chunk); - }; + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; } - - function singleRead(psrc, pdst, chunk) { - src.read(srcHandle, - readbuf, - psrc, - chunk, - pdst, - makeCb(psrc, pdst, chunk)); - } - - function startReads() { - let reads = 0; - let psrc = 0; - while (pdst < fsize && reads < concurrency) { - const chunk = - (pdst + chunkSize > fsize ? fsize - pdst : chunkSize); - singleRead(psrc, pdst, chunk); - psrc += chunk; - pdst += chunk; - ++reads; - } + finally { + this._debug(debugName, 'end'); } - }); - } - }); -} - -function writeAll(sftp, handle, buffer, offset, length, position, callback_) { - const callback = (typeof callback_ === 'function' ? callback_ : undefined); - - sftp.write(handle, - buffer, - offset, - length, - position, - (writeErr, written) => { - if (writeErr) { - return sftp.close(handle, () => { - callback && callback(writeErr); - }); - } - if (written === length) { - sftp.close(handle, callback); - } else { - offset += written; - length -= written; - position += written; - writeAll(sftp, handle, buffer, offset, length, position, callback); - } - }); -} - -class Stats { - constructor(initial) { - this.mode = (initial && initial.mode); - this.uid = (initial && initial.uid); - this.gid = (initial && initial.gid); - this.size = (initial && initial.size); - this.atime = (initial && initial.atime); - this.mtime = (initial && initial.mtime); - this.extended = (initial && initial.extended); - } - isDirectory() { - return ((this.mode & constants.S_IFMT) === constants.S_IFDIR); - } - isFile() { - return ((this.mode & constants.S_IFMT) === constants.S_IFREG); - } - isBlockDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFBLK); - } - isCharacterDevice() { - return ((this.mode & constants.S_IFMT) === constants.S_IFCHR); - } - isSymbolicLink() { - return ((this.mode & constants.S_IFMT) === constants.S_IFLNK); - } - isFIFO() { - return ((this.mode & constants.S_IFMT) === constants.S_IFIFO); - } - isSocket() { - return ((this.mode & constants.S_IFMT) === constants.S_IFSOCK); - } -} - -function attrsToBytes(attrs) { - let flags = 0; - let nb = 0; - - if (typeof attrs === 'object' && attrs !== null) { - if (typeof attrs.size === 'number') { - flags |= ATTR.SIZE; - const val = attrs.size; - // Big Endian - ATTRS_BUF[nb++] = val / 72057594037927940; // 2**56 - ATTRS_BUF[nb++] = val / 281474976710656; // 2**48 - ATTRS_BUF[nb++] = val / 1099511627776; // 2**40 - ATTRS_BUF[nb++] = val / 4294967296; // 2**32 - ATTRS_BUF[nb++] = val / 16777216; // 2**24 - ATTRS_BUF[nb++] = val / 65536; // 2**16 - ATTRS_BUF[nb++] = val / 256; // 2**8 - ATTRS_BUF[nb++] = val; - } - if (typeof attrs.uid === 'number' && typeof attrs.gid === 'number') { - flags |= ATTR.UIDGID; - const uid = attrs.uid; - const gid = attrs.gid; - // Big Endian - ATTRS_BUF[nb++] = uid >>> 24; - ATTRS_BUF[nb++] = uid >>> 16; - ATTRS_BUF[nb++] = uid >>> 8; - ATTRS_BUF[nb++] = uid; - ATTRS_BUF[nb++] = gid >>> 24; - ATTRS_BUF[nb++] = gid >>> 16; - ATTRS_BUF[nb++] = gid >>> 8; - ATTRS_BUF[nb++] = gid; - } - if (typeof attrs.mode === 'number' || typeof attrs.mode === 'string') { - const mode = modeNum(attrs.mode); - flags |= ATTR.PERMISSIONS; - // Big Endian - ATTRS_BUF[nb++] = mode >>> 24; - ATTRS_BUF[nb++] = mode >>> 16; - ATTRS_BUF[nb++] = mode >>> 8; - ATTRS_BUF[nb++] = mode; - } - if ((typeof attrs.atime === 'number' || isDate(attrs.atime)) - && (typeof attrs.mtime === 'number' || isDate(attrs.mtime))) { - const atime = toUnixTimestamp(attrs.atime); - const mtime = toUnixTimestamp(attrs.mtime); - - flags |= ATTR.ACMODTIME; - // Big Endian - ATTRS_BUF[nb++] = atime >>> 24; - ATTRS_BUF[nb++] = atime >>> 16; - ATTRS_BUF[nb++] = atime >>> 8; - ATTRS_BUF[nb++] = atime; - ATTRS_BUF[nb++] = mtime >>> 24; - ATTRS_BUF[nb++] = mtime >>> 16; - ATTRS_BUF[nb++] = mtime >>> 8; - ATTRS_BUF[nb++] = mtime; - } - // TODO: extended attributes - } - - return { flags, nb }; -} - -function toUnixTimestamp(time) { - // eslint-disable-next-line no-self-compare - if (typeof time === 'number' && time === time) // Valid, non-NaN number - return time; - if (isDate(time)) - return parseInt(time.getTime() / 1000, 10); - throw new Error(`Cannot parse time: ${time}`); -} - -function modeNum(mode) { - // eslint-disable-next-line no-self-compare - if (typeof mode === 'number' && mode === mode) // Valid, non-NaN number - return mode; - if (typeof mode === 'string') - return modeNum(parseInt(mode, 8)); - throw new Error(`Cannot parse mode: ${mode}`); -} - -const stringFlagMap = { - 'r': OPEN_MODE.READ, - 'r+': OPEN_MODE.READ | OPEN_MODE.WRITE, - 'w': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'wx': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xw': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'w+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'wx+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xw+': OPEN_MODE.TRUNC | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'a': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE, - 'ax': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'xa': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.WRITE | OPEN_MODE.EXCL, - 'a+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE, - 'ax+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL, - 'xa+': OPEN_MODE.APPEND | OPEN_MODE.CREAT | OPEN_MODE.READ | OPEN_MODE.WRITE - | OPEN_MODE.EXCL -}; - -function stringToFlags(str) { - const flags = stringFlagMap[str]; - return (flags !== undefined ? flags : null); -} - -const flagsToString = (() => { - const stringFlagMapKeys = Object.keys(stringFlagMap); - return (flags) => { - for (let i = 0; i < stringFlagMapKeys.length; ++i) { - const key = stringFlagMapKeys[i]; - if (stringFlagMap[key] === flags) - return key; - } - return null; - }; -})(); - -function readAttrs(biOpt) { - /* - uint32 flags - uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - string extended_type - string extended_data - ... more extended data (extended_type - extended_data pairs), - so that number of pairs equals extended_count - */ - const flags = bufferParser.readUInt32BE(); - if (flags === undefined) - return; - - const attrs = new Stats(); - if (flags & ATTR.SIZE) { - const size = bufferParser.readUInt64BE(biOpt); - if (size === undefined) - return; - attrs.size = size; - } - - if (flags & ATTR.UIDGID) { - const uid = bufferParser.readUInt32BE(); - const gid = bufferParser.readUInt32BE(); - if (gid === undefined) - return; - attrs.uid = uid; - attrs.gid = gid; - } - - if (flags & ATTR.PERMISSIONS) { - const mode = bufferParser.readUInt32BE(); - if (mode === undefined) - return; - attrs.mode = mode; - } - - if (flags & ATTR.ACMODTIME) { - const atime = bufferParser.readUInt32BE(); - const mtime = bufferParser.readUInt32BE(); - if (mtime === undefined) - return; - attrs.atime = atime; - attrs.mtime = mtime; - } - - if (flags & ATTR.EXTENDED) { - const count = bufferParser.readUInt32BE(); - if (count === undefined) - return; - const extended = {}; - for (let i = 0; i < count; ++i) { - const type = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data === undefined) - return; - extended[type] = data; - } - attrs.extended = extended; - } - - return attrs; -} - -function sendOrBuffer(sftp, payload) { - const ret = tryWritePayload(sftp, payload); - if (ret !== undefined) { - sftp._buffer.push(ret); - return false; - } - return true; -} - -function tryWritePayload(sftp, payload) { - const outgoing = sftp.outgoing; - if (outgoing.state !== 'open') - return; - - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; - return payload; - } - - let ret; - const len = payload.length; - let p = 0; - - while (len - p > 0 && outgoing.window > 0) { - const actualLen = Math.min(len - p, outgoing.window, outgoing.packetSize); - outgoing.window -= actualLen; - if (outgoing.window === 0) { - sftp._waitWindow = true; - sftp._chunkcb = drainBuffer; } - - if (p === 0 && actualLen === len) { - sftp._protocol.channelData(sftp.outgoing.id, payload); - } else { - sftp._protocol.channelData(sftp.outgoing.id, - bufferSlice(payload, p, p + actualLen)); + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === 'object' && + maybeSession !== null && + 'access_token' in maybeSession && + 'refresh_token' in maybeSession && + 'expires_at' in maybeSession; + return isValidSession; } - - p += actualLen; - } - - if (len - p > 0) { - if (p > 0) - ret = bufferSlice(payload, p, len); - else - ret = payload; // XXX: should never get here? - } - - return ret; -} - -function drainBuffer() { - this._chunkcb = undefined; - const buffer = this._buffer; - let i = 0; - while (i < buffer.length) { - const payload = buffer[i]; - const ret = tryWritePayload(this, payload); - if (ret !== undefined) { - if (ret !== payload) - buffer[i] = ret; - if (i > 0) - this._buffer = buffer.slice(i); - return; + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams, + }); + this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url); + // try to open on the browser + if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; } - ++i; - } - if (i > 0) - this._buffer = []; -} - -function doFatalSFTPError(sftp, msg, noDebug) { - const err = new Error(msg); - err.level = 'sftp-protocol'; - if (!noDebug && sftp._debug) - sftp._debug(`SFTP: Inbound: ${msg}`); - sftp.emit('error', err); - sftp.destroy(); - cleanupRequests(sftp); - return false; -} - -function cleanupRequests(sftp) { - const keys = Object.keys(sftp._requests); - if (keys.length === 0) - return; - - const reqs = sftp._requests; - sftp._requests = {}; - const err = new Error('No response from server'); - for (let i = 0; i < keys.length; ++i) { - const req = reqs[keys[i]]; - if (typeof req.cb === 'function') - req.cb(err); - } -} - -function requestLimits(sftp, cb) { - /* - uint32 id - string "limits@openssh.com" - */ - let p = 9; - const buf = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18); - - writeUInt32BE(buf, buf.length - 4, 0); - buf[4] = REQUEST.EXTENDED; - const reqid = sftp._writeReqid = (sftp._writeReqid + 1) & MAX_REQID; - writeUInt32BE(buf, reqid, 5); - - writeUInt32BE(buf, 18, p); - buf.utf8Write('limits@openssh.com', p += 4, 18); - - sftp._requests[reqid] = { extended: 'limits@openssh.com', cb }; - - const isBuffered = sendOrBuffer(sftp, buf); - if (sftp._debug) { - const which = (isBuffered ? 'Buffered' : 'Sending'); - sftp._debug(`SFTP: Outbound: ${which} limits@openssh.com`); - } -} - -const CLIENT_HANDLERS = { - [RESPONSE.VERSION]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate VERSION packet'); - - const extensions = {}; - - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a, _b; + const debugName = '#_recoverAndRefresh()'; + this._debug(debugName, 'begin'); + try { + const currentSession = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey)); + if (currentSession && this.userStorage) { + let maybeUser = (await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + '-user')); + if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { + // storage and userStorage are the same storage medium, for example + // window.localStorage if userStorage does not have the user from + // storage stored, store it first thereby migrating the user object + // from storage -> userStorage + maybeUser = { user: currentSession.user }; + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', maybeUser); + } + currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : (0, helpers_1.userNotAvailableProxy)(); + } + else if (currentSession && !currentSession.user) { + // user storage is not set, let's check if it was previously enabled so + // we bring back the storage as it should be + if (!currentSession.user) { + // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key + const separateUser = (await (0, helpers_1.getItemAsync)(this.storage, this.storageKey + '-user')); + if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { + currentSession.user = separateUser.user; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); + } + else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + } + this._debug(debugName, 'session from storage', currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, 'session is not valid'); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < constants_1.EXPIRY_MARGIN_MS; + this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${constants_1.EXPIRY_MARGIN_MS}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error); + await this._removeSession(); + } + } + } + } + else if (currentSession.user && + currentSession.user.__isUserNotAvailableProxy === true) { + // If we have a proxy user, try to get the real user data + try { + const { data, error: userError } = await this._getUser(currentSession.access_token); + if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { + currentSession.user = data.user; + await this._saveSession(currentSession); + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + else { + this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification'); + } + } + catch (getUserError) { + console.error('Error getting user data:', getUserError); + this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError); + } + } + else { + // no need to persist currentSession again, as we just loaded it from + // local storage; persisting it again may overwrite a value saved by + // another client with access to the same local storage + await this._notifyAllSubscribers('SIGNED_IN', currentSession); + } + } + catch (err) { + this._debug(debugName, 'error', err); + console.error(err); + return; + } + finally { + this._debug(debugName, 'end'); + } } - bufferParser.clear(); - - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed VERSION packet'); - - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received VERSION (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received VERSION (v${version})`); - } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new errors_1.AuthSessionMissingError(); + } + // refreshing is already in progress + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, 'begin'); + try { + this.refreshingDeferred = new helpers_1.Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new errors_1.AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session); + const result = { data: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } + catch (error) { + this._debug(debugName, 'error', error); + if ((0, errors_1.isAuthError)(error)) { + const result = { data: null, error }; + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + await this._removeSession(); + } + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } + finally { + this.refreshingDeferred = null; + this._debug(debugName, 'end'); + } } - - sftp._version = version; - sftp._extensions = extensions; - - if (extensions['limits@openssh.com'] === '1') { - return requestLimits(sftp, (err, limits) => { - if (!err) { - if (limits.maxPktLen > 0) - sftp._maxOutPktLen = limits.maxPktLen; - if (limits.maxReadLen > 0) - sftp._maxReadLen = limits.maxReadLen; - if (limits.maxWriteLen > 0) - sftp._maxWriteLen = limits.maxWriteLen; - sftp.maxOpenHandles = ( - limits.maxOpenHandles > 0 ? limits.maxOpenHandles : Infinity - ); + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => { + try { + await x.callback(event, session); + } + catch (e) { + errors.push(e); + } + }); + await Promise.all(promises); + if (errors.length > 0) { + for (let i = 0; i < errors.length; i += 1) { + console.error(errors[i]); + } + throw errors[0]; + } + } + finally { + this._debug(debugName, 'end'); } - sftp.emit('ready'); - }); - } - - sftp.emit('ready'); - }, - [RESPONSE.STATUS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - uint32 error/status code - string error message (ISO-10646 UTF-8) - string language tag - */ - const errorCode = bufferParser.readUInt32BE(); - const errorMsg = bufferParser.readString(true); - bufferParser.clear(); - - // Note: we avoid checking that the error message and language tag are in - // the packet because there are some broken implementations that incorrectly - // omit them. The language tag in general was never really used amongst ssh - // implementations, so in the case of a missing error message we just - // default to something sensible. - - if (sftp._debug) { - const jsonMsg = JSON.stringify(errorMsg); - sftp._debug( - `SFTP: Inbound: Received STATUS (id:${reqID}, ${errorCode}, ${jsonMsg})` - ); - } - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') { - if (errorCode === STATUS_CODE.OK) { - req.cb(); - return; - } - const err = new Error(errorMsg - || STATUS_CODE_STR[errorCode] - || 'Unknown status'); - err.code = errorCode; - req.cb(err); - } - }, - [RESPONSE.HANDLE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined) { - if (reqID !== undefined) - delete sftp._requests[reqID]; - return doFatalSFTPError(sftp, 'Malformed HANDLE packet'); - } - - sftp._debug && sftp._debug(`SFTP: Inbound: Received HANDLE (id:${reqID})`); - - const req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - if (req && typeof req.cb === 'function') - req.cb(undefined, handle); - }, - [RESPONSE.DATA]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; } - /* - string data - */ - if (req && typeof req.cb === 'function') { - if (req.buffer) { - // We have already pre-allocated space to store the data - - const nb = bufferParser.readString(req.buffer); - bufferParser.clear(); - - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - req.cb(undefined, req.buffer, nb); - return; + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug('#_saveSession()', session); + // _saveSession is always called whenever a new session has been acquired + // so we can safely suppress the warning returned by future getSession calls + this.suppressGetSessionWarning = true; + // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere + const sessionToProcess = Object.assign({}, session); + const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; + if (this.userStorage) { + if (!userIsProxy && sessionToProcess.user) { + // If it's a real user object, save it to userStorage. + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + '-user', { + user: sessionToProcess.user, + }); + } + else if (userIsProxy) { + // If it's the proxy, it means user was not found in userStorage. + // We should ensure no stale user data for this key exists in userStorage if we were to save null, + // or simply not save the proxy. For now, we don't save the proxy here. + // If there's a need to clear userStorage if user becomes proxy, that logic would go here. + } + // Prepare the main session data for primary storage: remove the user property before cloning + // This is important because the original session.user might be the proxy + const mainSessionData = Object.assign({}, sessionToProcess); + delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage + const clonedMainSessionData = (0, helpers_1.deepClone)(mainSessionData); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedMainSessionData); } - } else { - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${data.length})` - ); - req.cb(undefined, data); - return; + else { + // No userStorage is configured. + // In this case, session.user should ideally not be a proxy. + // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here + const clonedSession = (0, helpers_1.deepClone)(sessionToProcess); // sessionToProcess still has its original user property + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedSession); } - } - } else { - const nb = bufferParser.skipString(); - bufferParser.clear(); - if (nb !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received DATA (id:${reqID}, ${nb})` - ); - return; - } - } - - return doFatalSFTPError(sftp, 'Malformed DATA packet'); - }, - [RESPONSE.NAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; - } - /* - uint32 count - repeats count times: - string filename - string longname - ATTRS attrs - */ - const count = bufferParser.readUInt32BE(); - if (count !== undefined) { - let names = []; - for (let i = 0; i < count; ++i) { - // We are going to assume UTF-8 for filenames despite the SFTPv3 - // spec not specifying an encoding because the specs for newer - // versions of the protocol all explicitly specify UTF-8 for - // filenames - const filename = bufferParser.readString(true); - - // `longname` only exists in SFTPv3 and since it typically will - // contain the filename, we assume it is also UTF-8 - const longname = bufferParser.readString(true); - - const attrs = readAttrs(sftp._biOpt); - if (attrs === undefined) { - names = undefined; - break; - } - names.push({ filename, longname, attrs }); - } - if (names !== undefined) { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received NAME (id:${reqID}, ${names.length})` - ); - bufferParser.clear(); - if (req && typeof req.cb === 'function') - req.cb(undefined, names); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed NAME packet'); - }, - [RESPONSE.ATTRS]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - let req; - if (reqID !== undefined) { - req = sftp._requests[reqID]; - delete sftp._requests[reqID]; } - /* - ATTRS attrs - */ - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - if (attrs !== undefined) { - sftp._debug && sftp._debug(`SFTP: Inbound: Received ATTRS (id:${reqID})`); - if (req && typeof req.cb === 'function') - req.cb(undefined, attrs); - return; - } - - return doFatalSFTPError(sftp, 'Malformed ATTRS packet'); - }, - [RESPONSE.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - if (reqID !== undefined) { - const req = sftp._requests[reqID]; - if (req) { - delete sftp._requests[reqID]; - switch (req.extended) { - case 'statvfs@openssh.com': - case 'fstatvfs@openssh.com': { - /* - uint64 f_bsize // file system block size - uint64 f_frsize // fundamental fs block size - uint64 f_blocks // number of blocks (unit f_frsize) - uint64 f_bfree // free blocks in file system - uint64 f_bavail // free blocks for non-root - uint64 f_files // total file inodes - uint64 f_ffree // free file inodes - uint64 f_favail // free file inodes for to non-root - uint64 f_fsid // file system id - uint64 f_flag // bit mask of f_flag values - uint64 f_namemax // maximum filename length - */ - const biOpt = sftp._biOpt; - const stats = { - f_bsize: bufferParser.readUInt64BE(biOpt), - f_frsize: bufferParser.readUInt64BE(biOpt), - f_blocks: bufferParser.readUInt64BE(biOpt), - f_bfree: bufferParser.readUInt64BE(biOpt), - f_bavail: bufferParser.readUInt64BE(biOpt), - f_files: bufferParser.readUInt64BE(biOpt), - f_ffree: bufferParser.readUInt64BE(biOpt), - f_favail: bufferParser.readUInt64BE(biOpt), - f_sid: bufferParser.readUInt64BE(biOpt), - f_flag: bufferParser.readUInt64BE(biOpt), - f_namemax: bufferParser.readUInt64BE(biOpt), - }; - if (stats.f_namemax === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, stats); - return; - } - case 'limits@openssh.com': { - /* - uint64 max-packet-length - uint64 max-read-length - uint64 max-write-length - uint64 max-open-handles - */ - const limits = { - maxPktLen: bufferParser.readUInt64BE(), - maxReadLen: bufferParser.readUInt64BE(), - maxWriteLen: bufferParser.readUInt64BE(), - maxOpenHandles: bufferParser.readUInt64BE(), - }; - if (limits.maxOpenHandles === undefined) - break; - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, limits); - return; - } - case 'users-groups-by-id@openssh.com': { - /* - string usernames - string username1 - ... - string groupnames - string groupname1 - ... - */ - const usernameCount = bufferParser.readUInt32BE(); - if (usernameCount === undefined) - break; - const usernames = new Array(usernameCount); - for (let i = 0; i < usernames.length; ++i) - usernames[i] = bufferParser.readString(true); - - const groupnameCount = bufferParser.readUInt32BE(); - if (groupnameCount === undefined) - break; - const groupnames = new Array(groupnameCount); - for (let i = 0; i < groupnames.length; ++i) - groupnames[i] = bufferParser.readString(true); - if (groupnames.length > 0 - && groupnames[groupnames.length - 1] === undefined) { - break; - } - - if (sftp._debug) { - sftp._debug( - 'SFTP: Inbound: Received EXTENDED_REPLY ' - + `(id:${reqID}, ${req.extended})` - ); - } - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(undefined, usernames, groupnames); - return; - } - default: - // Unknown extended request - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - if (typeof req.cb === 'function') - req.cb(); - return; + async _removeSession() { + this._debug('#_removeSession()'); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-code-verifier'); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + '-user'); + if (this.userStorage) { + await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + '-user'); } - } else { - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED_REPLY (id:${reqID}, ???)` - ); - bufferParser.clear(); - return; - } - } - - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED_REPLY packet'); - }, -}; -const SERVER_HANDLERS = { - [REQUEST.INIT]: (sftp, payload) => { - if (sftp._version !== -1) - return doFatalSFTPError(sftp, 'Duplicate INIT packet'); - - const extensions = {}; - - /* - uint32 version - - */ - bufferParser.init(payload, 1); - let version = bufferParser.readUInt32BE(); - while (bufferParser.avail()) { - const extName = bufferParser.readString(true); - const extData = bufferParser.readString(true); - if (extData === undefined) { - version = undefined; - break; - } - extensions[extName] = extData; - } - bufferParser.clear(); - - if (version === undefined) - return doFatalSFTPError(sftp, 'Malformed INIT packet'); - - if (sftp._debug) { - const names = Object.keys(extensions); - if (names.length) { - sftp._debug( - `SFTP: Inbound: Received INIT (v${version}, exts:${names})` - ); - } else { - sftp._debug(`SFTP: Inbound: Received INIT (v${version})`); - } - } - - sendOrBuffer(sftp, SERVER_VERSION_BUFFER); - - sftp._version = version; - sftp._extensions = extensions; - sftp.emit('ready'); - }, - [REQUEST.OPEN]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string filename - uint32 pflags - ATTRS attrs - */ - const filename = bufferParser.readString(true); - const pflags = bufferParser.readUInt32BE(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed OPEN packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPEN (id:${reqID})`); - - if (!sftp.emit('OPEN', reqID, filename, pflags, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.CLOSE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed CLOSE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received CLOSE (id:${reqID})`); - - if (!sftp.emit('CLOSE', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READ]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - uint32 len - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const len = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (len === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READ packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READ (id:${reqID})`); - - if (!sftp.emit('READ', reqID, handle, offset, len)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.WRITE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - uint64 offset - string data - */ - const handle = bufferParser.readString(); - const offset = bufferParser.readUInt64BE(sftp._biOpt); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed WRITE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received WRITE (id:${reqID})`); - - if (!sftp.emit('WRITE', reqID, handle, offset, data)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.LSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed LSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received LSTAT (id:${reqID})`); - - if (!sftp.emit('LSTAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received FSTAT (id:${reqID})`); - - if (!sftp.emit('FSTAT', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.SETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed SETSTAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SETSTAT (id:${reqID})`); - - if (!sftp.emit('SETSTAT', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.FSETSTAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - ATTRS attrs - */ - const handle = bufferParser.readString(); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed FSETSTAT packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received FSETSTAT (id:${reqID})` - ); - - if (!sftp.emit('FSETSTAT', reqID, handle, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.OPENDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed OPENDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received OPENDIR (id:${reqID})`); - - if (!sftp.emit('OPENDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string handle - */ - const handle = bufferParser.readString(); - bufferParser.clear(); - - if (handle === undefined || handle.length > 256) - return doFatalSFTPError(sftp, 'Malformed READDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received READDIR (id:${reqID})`); - - if (!sftp.emit('READDIR', reqID, handle)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REMOVE]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REMOVE packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received REMOVE (id:${reqID})`); - - if (!sftp.emit('REMOVE', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.MKDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - ATTRS attrs - */ - const path = bufferParser.readString(true); - const attrs = readAttrs(sftp._biOpt); - bufferParser.clear(); - - if (attrs === undefined) - return doFatalSFTPError(sftp, 'Malformed MKDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received MKDIR (id:${reqID})`); - - if (!sftp.emit('MKDIR', reqID, path, attrs)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RMDIR]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed RMDIR packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RMDIR (id:${reqID})`); - - if (!sftp.emit('RMDIR', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.REALPATH]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed REALPATH packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received REALPATH (id:${reqID})` - ); - - if (!sftp.emit('REALPATH', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.STAT]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed STAT packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received STAT (id:${reqID})`); - - if (!sftp.emit('STAT', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.RENAME]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string oldpath - string newpath - */ - const oldPath = bufferParser.readString(true); - const newPath = bufferParser.readString(true); - bufferParser.clear(); - - if (newPath === undefined) - return doFatalSFTPError(sftp, 'Malformed RENAME packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received RENAME (id:${reqID})`); - - if (!sftp.emit('RENAME', reqID, oldPath, newPath)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); - } - }, - [REQUEST.READLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string path - */ - const path = bufferParser.readString(true); - bufferParser.clear(); - - if (path === undefined) - return doFatalSFTPError(sftp, 'Malformed READLINK packet'); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received READLINK (id:${reqID})` - ); - - if (!sftp.emit('READLINK', reqID, path)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + await this._notifyAllSubscribers('SIGNED_OUT', null); } - }, - [REQUEST.SYMLINK]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string linkpath - string targetpath - */ - const linkPath = bufferParser.readString(true); - const targetPath = bufferParser.readString(true); - bufferParser.clear(); - - if (targetPath === undefined) - return doFatalSFTPError(sftp, 'Malformed SYMLINK packet'); - - sftp._debug && sftp._debug(`SFTP: Inbound: Received SYMLINK (id:${reqID})`); - - let handled; - if (sftp._isOpenSSH) { - // OpenSSH has linkpath and targetpath positions switched - handled = sftp.emit('SYMLINK', reqID, targetPath, linkPath); - } else { - handled = sftp.emit('SYMLINK', reqID, linkPath, targetPath); + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug('#_removeVisibilityChangedCallback()'); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener('visibilitychange', callback); + } + } + catch (e) { + console.error('removing visibilitychange callback failed', e); + } } - if (!handled) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug('#_startAutoRefresh()'); + const ticker = setInterval(() => this._autoRefreshTokenTick(), constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') { + // ticker is a NodeJS Timeout object that has an `unref` method + // https://nodejs.org/api/timers.html#timeoutunref + // When auto refresh is used in NodeJS (like for testing) the + // `setInterval` is preventing the process from being marked as + // finished and tests run endlessly. This can be prevented by calling + // `unref()` on the returned object. + ticker.unref(); + // @ts-expect-error TS has no context of Deno + } + else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') { + // similar like for NodeJS, but with the Deno API + // https://deno.land/api@latest?unstable&s=Deno.unrefTimer + // @ts-expect-error TS has no context of Deno + Deno.unrefTimer(ticker); + } + // run the tick immediately, but in the next pass of the event loop so that + // #_initialize can be allowed to complete without recursively waiting on + // itself + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); } - }, - [REQUEST.EXTENDED]: (sftp, payload) => { - bufferParser.init(payload, 1); - const reqID = bufferParser.readUInt32BE(); - /* - string extended-request - ... any request-specific data ... - */ - const extName = bufferParser.readString(true); - if (extName === undefined) { - bufferParser.clear(); - return doFatalSFTPError(sftp, 'Malformed EXTENDED packet'); + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug('#_stopAutoRefresh()'); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } } - - let extData; - if (bufferParser.avail()) - extData = bufferParser.readRaw(); - bufferParser.clear(); - - sftp._debug && sftp._debug( - `SFTP: Inbound: Received EXTENDED (id:${reqID})` - ); - - if (!sftp.emit('EXTENDED', reqID, extName, extData)) { - // Automatically reject request if no handler for request type - sftp.status(reqID, STATUS_CODE.OP_UNSUPPORTED); + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); } - }, -}; - -// ============================================================================= -// ReadStream/WriteStream-related ============================================== -// ============================================================================= -const { - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - validateNumber -} = __nccwpck_require__(47609); - -const kMinPoolSpace = 128; - -let pool; -// It can happen that we expect to read a large chunk of data, and reserve -// a large chunk of the pool accordingly, but the read() call only filled -// a portion of it. If a concurrently executing read() then uses the same pool, -// the "reserved" portion cannot be used, so we allow it to be re-used as a -// new pool later. -const poolFragments = []; - -function allocNewPool(poolSize) { - if (poolFragments.length > 0) - pool = poolFragments.pop(); - else - pool = Buffer.allocUnsafe(poolSize); - pool.used = 0; -} - -// Check the `this.start` and `this.end` of stream. -function checkPosition(pos, name) { - if (!Number.isSafeInteger(pos)) { - validateNumber(pos, name); - if (!Number.isInteger(pos)) - throw new ERR_OUT_OF_RANGE(name, 'an integer', pos); - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); - } - if (pos < 0) - throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos); -} - -function roundUpToMultipleOf8(n) { - return (n + 7) & ~7; // Align to 8 byte boundary. -} - -function ReadStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // A little bit bigger buffer and water marks by default - if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - ReadableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'r' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.end = options.end; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesRead = 0; - this.isClosed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (this.end === undefined) { - this.end = Infinity; - } else if (this.end !== Infinity) { - checkPosition(this.end, 'end'); - - if (this.start !== undefined && this.start > this.end) { - throw new ERR_OUT_OF_RANGE( - 'start', - `<= "end" (here: ${this.end})`, - this.start - ); + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); } - } - - this.on('end', function() { - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(ReadStream, ReadableStream); - -ReadStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug('#_autoRefreshTokenTick()', 'begin'); + try { + await this._acquireLock(0, async () => { + try { + const now = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session }, } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug('#_autoRefreshTokenTick()', 'no session'); + return; + } + // session will expire in this many ticks (or has already expired if <= 0) + const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } + catch (e) { + console.error('Auto refresh tick failed with error. This is likely a transient error.', e); + } + } + finally { + this._debug('#_autoRefreshTokenTick()', 'end'); + } + }); + } + catch (e) { + if (e.isAcquireTimeout || e instanceof locks_1.LockAcquireTimeoutError) { + this._debug('auto refresh token tick lock not available'); + } + else { + throw e; + } + } } - - this.handle = handle; - this.emit('open', handle); - this.emit('ready'); - // Start the flow of data. - this.read(); - }); -}; - -ReadStream.prototype._read = function(n) { - if (!Buffer.isBuffer(this.handle)) - return this.once('open', () => this._read(n)); - - // XXX: safe to remove this? - if (this.destroyed) - return; - - if (!pool || pool.length - pool.used < kMinPoolSpace) { - // Discard the old pool. - allocNewPool(this.readableHighWaterMark - || this._readableState.highWaterMark); - } - - // Grab another reference to the pool in the case that while we're - // in the thread pool another read() finishes up the pool, and - // allocates a new one. - const thisPool = pool; - let toRead = Math.min(pool.length - pool.used, n); - const start = pool.used; - - if (this.end !== undefined) - toRead = Math.min(this.end - this.pos + 1, toRead); - - // Already read everything we were supposed to read! - // treat as EOF. - if (toRead <= 0) - return this.push(null); - - // the actual read. - this.sftp.read(this.handle, - pool, - pool.used, - toRead, - this.pos, - (er, bytesRead) => { - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug('#_handleVisibilityChange()'); + if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + // in non-browser environments the refresh token ticker runs always + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback); + // now immediately call the visbility changed callback to setup with the + // current visbility state + await this._onVisibilityChanged(true); // initial call + } + catch (error) { + console.error('_handleVisibilityChange', error); + } } - let b = null; - - // Now that we know how much data we have actually read, re-wind the - // 'used' field if we can, and otherwise allow the remainder of our - // reservation to be used as a new pool later. - if (start + toRead === thisPool.used && thisPool === pool) { - thisPool.used = roundUpToMultipleOf8(thisPool.used + bytesRead - toRead); - } else { - // Round down to the next lowest multiple of 8 to ensure the new pool - // fragment start and end positions are aligned to an 8 byte boundary. - const alignedEnd = (start + toRead) & ~7; - const alignedStart = roundUpToMultipleOf8(start + bytesRead); - if (alignedEnd - alignedStart >= kMinPoolSpace) - poolFragments.push(thisPool.slice(alignedStart, alignedEnd)); + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(calledFromInitialize) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; + this._debug(methodName, 'visibilityState', document.visibilityState); + if (document.visibilityState === 'visible') { + if (this.autoRefreshToken) { + // in browser environments the refresh token ticker runs only on focused tabs + // which prevents race conditions + this._startAutoRefresh(); + } + if (!calledFromInitialize) { + // called when the visibility has changed, i.e. the browser + // transitioned from hidden -> visible so we need to see if the session + // should be recovered immediately... but to do that we need to acquire + // the lock first asynchronously + await this.initializePromise; + await this._acquireLock(-1, async () => { + if (document.visibilityState !== 'visible') { + this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting'); + // visibility has changed while waiting for the lock, abort + return; + } + // recover the session + await this._recoverAndRefresh(); + }); + } + } + else if (document.visibilityState === 'hidden') { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } } - - if (bytesRead > 0) { - this.bytesRead += bytesRead; - b = thisPool.slice(start, start + bytesRead); + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(url, provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === 'pkce') { + const [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`, + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); + } + return `${url}?${urlParams.join('&')}`; } - - // Move the pool positions, and internal position for reading. - this.pos += bytesRead; - - this.push(b); - }); - - pool.used = roundUpToMultipleOf8(pool.used + toRead); -}; - -ReadStream.prototype._destroy = function(err, cb) { - if (this._opening && !Buffer.isBuffer(this.handle)) { - this.once('open', closeStream.bind(null, this, cb, err)); - return; - } - - closeStream(this, cb, err); - this.handle = null; - this._opening = false; -}; - -function closeStream(stream, cb, err) { - if (!stream.handle) - return onclose(); - - stream.sftp.close(stream.handle, onclose); - - function onclose(er) { - er = er || err; - cb(er); - stream.isClosed = true; - if (!er) - stream.emit('close'); - } -} - -ReadStream.prototype.close = function(cb) { - this.destroy(null, cb); -}; - -Object.defineProperty(ReadStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); - -// TODO: add `concurrency` setting to allow more than one in-flight WRITE -// request to server to improve throughput -function WriteStream(sftp, path, options) { - if (options === undefined) - options = {}; - else if (typeof options === 'string') - options = { encoding: options }; - else if (options === null || typeof options !== 'object') - throw new TypeError('"options" argument must be a string or an object'); - else - options = Object.create(options); - - // For backwards compat do not emit close on destroy. - options.emitClose = false; - options.autoDestroy = false; // Node 14 major change. - - WritableStream.call(this, options); - - this.path = path; - this.flags = options.flags === undefined ? 'w' : options.flags; - this.mode = options.mode === undefined ? 0o666 : options.mode; - - this.start = options.start; - this.autoClose = options.autoClose === undefined ? true : options.autoClose; - this.pos = 0; - this.bytesWritten = 0; - this.isClosed = false; - - this.handle = options.handle === undefined ? null : options.handle; - this.sftp = sftp; - this._opening = false; - - if (this.start !== undefined) { - checkPosition(this.start, 'start'); - - this.pos = this.start; - } - - if (options.encoding) - this.setDefaultEncoding(options.encoding); - - // Node v6.x only - this.on('finish', function() { - if (this._writableState.finalCalled) - return; - if (this.autoClose) - this.destroy(); - }); - - if (!Buffer.isBuffer(this.handle)) - this.open(); -} -inherits(WriteStream, WritableStream); - -WriteStream.prototype._final = function(cb) { - if (this.autoClose) - this.destroy(); - cb(); -}; - -WriteStream.prototype.open = function() { - if (this._opening) - return; - - this._opening = true; - - this.sftp.open(this.path, this.flags, this.mode, (er, handle) => { - this._opening = false; - - if (er) { - this.emit('error', er); - if (this.autoClose) - this.destroy(); - return; + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + return await (0, fetch_1._request)(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - - this.handle = handle; - - const tryAgain = (err) => { - if (err) { - // Try chmod() for sftp servers that may not support fchmod() for - // whatever reason - this.sftp.chmod(this.path, this.mode, (err_) => tryAgain()); - return; - } - - // SFTPv3 requires absolute offsets, no matter the open flag used - if (this.flags[0] === 'a') { - const tryStat = (err, st) => { - if (err) { - // Try stat() for sftp servers that may not support fstat() for - // whatever reason - this.sftp.stat(this.path, (err_, st_) => { - if (err_) { - this.destroy(); - this.emit('error', err); - return; - } - tryStat(null, st_); + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone' + ? { phone: params.phone } + : params.factorType === 'totp' + ? { issuer: params.issuer } + : {})); + const { data, error } = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (error) { + return this._returnResult({ data: null, error }); + } + if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return this._returnResult({ data, error: null }); }); - return; - } - - this.pos = st.size; - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fstat(handle, tryStat); - return; - } - - this.emit('open', handle); - this.emit('ready'); - }; - - this.sftp.fchmod(handle, this.mode, tryAgain); - }); -}; - -WriteStream.prototype._write = function(data, encoding, cb) { - if (!Buffer.isBuffer(data)) { - const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); - return this.emit('error', err); - } - - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._write(data, encoding, cb); - }); - } - - this.sftp.write(this.handle, - data, - 0, - data.length, - this.pos, - (er, bytes) => { - if (er) { - if (this.autoClose) - this.destroy(); - return cb(er); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } } - this.bytesWritten += bytes; - cb(); - }); - - this.pos += data.length; -}; - -WriteStream.prototype._writev = function(data, cb) { - if (!Buffer.isBuffer(this.handle)) { - return this.once('open', function() { - this._writev(data, cb); - }); - } - - const sftp = this.sftp; - const handle = this.handle; - let writesLeft = data.length; - - const onwrite = (er, bytes) => { - if (er) { - this.destroy(); - return cb(er); + async _verify(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params + ? { + webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create' + ? (0, webauthn_1.serializeCredentialCreationResponse)(params.webauthn.credential_response) + : (0, webauthn_1.serializeCredentialRequestResponse)(params.webauthn.credential_response) }), + } + : { code: params.code })); + const { data, error } = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + }); + if (error) { + return this._returnResult({ data: null, error }); + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data)); + await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data); + return this._returnResult({ data, error }); + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); } - this.bytesWritten += bytes; - if (--writesLeft === 0) - cb(); - }; - - // TODO: try to combine chunks to reduce number of requests to the server? - for (let i = 0; i < data.length; ++i) { - const chunk = data[i].chunk; - - sftp.write(handle, chunk, 0, chunk.length, this.pos, onwrite); - this.pos += chunk.length; - } -}; - -if (typeof WritableStream.prototype.destroy !== 'function') - WriteStream.prototype.destroy = ReadStream.prototype.destroy; - -WriteStream.prototype._destroy = ReadStream.prototype._destroy; -WriteStream.prototype.close = function(cb) { - if (cb) { - if (this.isClosed) { - process.nextTick(cb); - return; + async _challenge(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const response = (await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, { + body: params, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token, + })); + if (response.error) { + return response; + } + const { data } = response; + if (data.type !== 'webauthn') { + return { data, error: null }; + } + switch (data.webauthn.type) { + case 'create': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialCreationOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + case 'request': + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialRequestOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null, + }; + } + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); } - this.on('close', cb); - } - - // If we are not autoClosing, we should call - // destroy on 'finish'. - if (!this.autoClose) - this.on('finish', this.destroy.bind(this)); - - this.end(); -}; - -// There is no shutdown() for files. -WriteStream.prototype.destroySoon = WriteStream.prototype.end; - -Object.defineProperty(WriteStream.prototype, 'pending', { - get() { - return this.handle === null; - }, - configurable: true -}); -// ============================================================================= - -module.exports = { - flagsToString, - OPEN_MODE, - SFTP, - Stats, - STATUS_CODE, - stringToFlags, -}; - - -/***/ }), - -/***/ 36832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const crypto = __nccwpck_require__(6113); - -let cpuInfo; -try { - cpuInfo = __nccwpck_require__(24137)(); -} catch {} - -const { bindingAvailable, CIPHER_INFO, MAC_INFO } = __nccwpck_require__(45708); - -const eddsaSupported = (() => { - if (typeof crypto.sign === 'function' - && typeof crypto.verify === 'function') { - const key = - '-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD' - + '/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----'; - const data = Buffer.from('a'); - let sig; - let verified; - try { - sig = crypto.sign(null, data, key); - verified = crypto.verify(null, data, key, sig); - } catch {} - return (Buffer.isBuffer(sig) && sig.length === 64 && verified === true); - } - - return false; -})(); - -const curve25519Supported = (typeof crypto.diffieHellman === 'function' - && typeof crypto.generateKeyPairSync === 'function' - && typeof crypto.createPublicKey === 'function'); - -const DEFAULT_KEX = [ - // https://tools.ietf.org/html/rfc5656#section-10.1 - 'ecdh-sha2-nistp256', - 'ecdh-sha2-nistp384', - 'ecdh-sha2-nistp521', - - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha256', - - // https://tools.ietf.org/html/rfc8268 - 'diffie-hellman-group14-sha256', - 'diffie-hellman-group15-sha512', - 'diffie-hellman-group16-sha512', - 'diffie-hellman-group17-sha512', - 'diffie-hellman-group18-sha512', -]; -if (curve25519Supported) { - DEFAULT_KEX.unshift('curve25519-sha256'); - DEFAULT_KEX.unshift('curve25519-sha256@libssh.org'); -} -const SUPPORTED_KEX = DEFAULT_KEX.concat([ - // https://tools.ietf.org/html/rfc4419#section-4 - 'diffie-hellman-group-exchange-sha1', - - 'diffie-hellman-group14-sha1', // REQUIRED - 'diffie-hellman-group1-sha1', // REQUIRED -]); - - -const DEFAULT_SERVER_HOST_KEY = [ - 'ecdsa-sha2-nistp256', - 'ecdsa-sha2-nistp384', - 'ecdsa-sha2-nistp521', - 'rsa-sha2-512', // RFC 8332 - 'rsa-sha2-256', // RFC 8332 - 'ssh-rsa', -]; -if (eddsaSupported) - DEFAULT_SERVER_HOST_KEY.unshift('ssh-ed25519'); -const SUPPORTED_SERVER_HOST_KEY = DEFAULT_SERVER_HOST_KEY.concat([ - 'ssh-dss', -]); - - -const canUseCipher = (() => { - const ciphers = crypto.getCiphers(); - return (name) => ciphers.includes(CIPHER_INFO[name].sslName); -})(); -let DEFAULT_CIPHER = [ - // http://tools.ietf.org/html/rfc5647 - 'aes128-gcm@openssh.com', - 'aes256-gcm@openssh.com', - - // http://tools.ietf.org/html/rfc4344#section-4 - 'aes128-ctr', - 'aes192-ctr', - 'aes256-ctr', -]; -if (cpuInfo && cpuInfo.flags && !cpuInfo.flags.aes) { - // We know for sure the CPU does not support AES acceleration - if (bindingAvailable) - DEFAULT_CIPHER.unshift('chacha20-poly1305@openssh.com'); - else - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} else if (bindingAvailable && cpuInfo && cpuInfo.arch === 'x86') { - // Places chacha20-poly1305 immediately after GCM ciphers since GCM ciphers - // seem to outperform it on x86, but it seems to be faster than CTR ciphers - DEFAULT_CIPHER.splice(4, 0, 'chacha20-poly1305@openssh.com'); -} else { - DEFAULT_CIPHER.push('chacha20-poly1305@openssh.com'); -} -DEFAULT_CIPHER = DEFAULT_CIPHER.filter(canUseCipher); -const SUPPORTED_CIPHER = DEFAULT_CIPHER.concat([ - 'aes256-cbc', - 'aes192-cbc', - 'aes128-cbc', - 'blowfish-cbc', - '3des-cbc', - 'aes128-gcm', - 'aes256-gcm', - - // http://tools.ietf.org/html/rfc4345#section-4: - 'arcfour256', - 'arcfour128', - - 'cast128-cbc', - 'arcfour', -].filter(canUseCipher)); - - -const canUseMAC = (() => { - const hashes = crypto.getHashes(); - return (name) => hashes.includes(MAC_INFO[name].sslName); -})(); -const DEFAULT_MAC = [ - 'hmac-sha2-256-etm@openssh.com', - 'hmac-sha2-512-etm@openssh.com', - 'hmac-sha1-etm@openssh.com', - 'hmac-sha2-256', - 'hmac-sha2-512', - 'hmac-sha1', -].filter(canUseMAC); -const SUPPORTED_MAC = DEFAULT_MAC.concat([ - 'hmac-md5', - 'hmac-sha2-256-96', // first 96 bits of HMAC-SHA256 - 'hmac-sha2-512-96', // first 96 bits of HMAC-SHA512 - 'hmac-ripemd160', - 'hmac-sha1-96', // first 96 bits of HMAC-SHA1 - 'hmac-md5-96', // first 96 bits of HMAC-MD5 -].filter(canUseMAC)); - -const DEFAULT_COMPRESSION = [ - 'none', - 'zlib@openssh.com', // ZLIB (LZ77) compression, except - // compression/decompression does not start until after - // successful user authentication - 'zlib', // ZLIB (LZ77) compression -]; -const SUPPORTED_COMPRESSION = DEFAULT_COMPRESSION.concat([ -]); - - -const COMPAT = { - BAD_DHGEX: 1 << 0, - OLD_EXIT: 1 << 1, - DYN_RPORT_BUG: 1 << 2, - BUG_DHGEX_LARGE: 1 << 3, - IMPLY_RSA_SHA2_SIGALGS: 1 << 4, -}; - -module.exports = { - MESSAGE: { - // Transport layer protocol -- generic (1-19) - DISCONNECT: 1, - IGNORE: 2, - UNIMPLEMENTED: 3, - DEBUG: 4, - SERVICE_REQUEST: 5, - SERVICE_ACCEPT: 6, - EXT_INFO: 7, // RFC 8308 - - // Transport layer protocol -- algorithm negotiation (20-29) - KEXINIT: 20, - NEWKEYS: 21, - - // Transport layer protocol -- key exchange method-specific (30-49) - KEXDH_INIT: 30, - KEXDH_REPLY: 31, - - KEXDH_GEX_GROUP: 31, - KEXDH_GEX_INIT: 32, - KEXDH_GEX_REPLY: 33, - KEXDH_GEX_REQUEST: 34, - - KEXECDH_INIT: 30, - KEXECDH_REPLY: 31, - - // User auth protocol -- generic (50-59) - USERAUTH_REQUEST: 50, - USERAUTH_FAILURE: 51, - USERAUTH_SUCCESS: 52, - USERAUTH_BANNER: 53, - - // User auth protocol -- user auth method-specific (60-79) - USERAUTH_PASSWD_CHANGEREQ: 60, - - USERAUTH_PK_OK: 60, - - USERAUTH_INFO_REQUEST: 60, - USERAUTH_INFO_RESPONSE: 61, - - // Connection protocol -- generic (80-89) - GLOBAL_REQUEST: 80, - REQUEST_SUCCESS: 81, - REQUEST_FAILURE: 82, - - // Connection protocol -- channel-related (90-127) - CHANNEL_OPEN: 90, - CHANNEL_OPEN_CONFIRMATION: 91, - CHANNEL_OPEN_FAILURE: 92, - CHANNEL_WINDOW_ADJUST: 93, - CHANNEL_DATA: 94, - CHANNEL_EXTENDED_DATA: 95, - CHANNEL_EOF: 96, - CHANNEL_CLOSE: 97, - CHANNEL_REQUEST: 98, - CHANNEL_SUCCESS: 99, - CHANNEL_FAILURE: 100 - - // Reserved for client protocols (128-191) - - // Local extensions (192-155) - }, - DISCONNECT_REASON: { - HOST_NOT_ALLOWED_TO_CONNECT: 1, - PROTOCOL_ERROR: 2, - KEY_EXCHANGE_FAILED: 3, - RESERVED: 4, - MAC_ERROR: 5, - COMPRESSION_ERROR: 6, - SERVICE_NOT_AVAILABLE: 7, - PROTOCOL_VERSION_NOT_SUPPORTED: 8, - HOST_KEY_NOT_VERIFIABLE: 9, - CONNECTION_LOST: 10, - BY_APPLICATION: 11, - TOO_MANY_CONNECTIONS: 12, - AUTH_CANCELED_BY_USER: 13, - NO_MORE_AUTH_METHODS_AVAILABLE: 14, - ILLEGAL_USER_NAME: 15, - }, - DISCONNECT_REASON_STR: undefined, - CHANNEL_OPEN_FAILURE: { - ADMINISTRATIVELY_PROHIBITED: 1, - CONNECT_FAILED: 2, - UNKNOWN_CHANNEL_TYPE: 3, - RESOURCE_SHORTAGE: 4 - }, - TERMINAL_MODE: { - TTY_OP_END: 0, // Indicates end of options. - VINTR: 1, // Interrupt character; 255 if none. Similarly for the - // other characters. Not all of these characters are - // supported on all systems. - VQUIT: 2, // The quit character (sends SIGQUIT signal on POSIX - // systems). - VERASE: 3, // Erase the character to left of the cursor. - VKILL: 4, // Kill the current input line. - VEOF: 5, // End-of-file character (sends EOF from the - // terminal). - VEOL: 6, // End-of-line character in addition to carriage - // return and/or linefeed. - VEOL2: 7, // Additional end-of-line character. - VSTART: 8, // Continues paused output (normally control-Q). - VSTOP: 9, // Pauses output (normally control-S). - VSUSP: 10, // Suspends the current program. - VDSUSP: 11, // Another suspend character. - VREPRINT: 12, // Reprints the current input line. - VWERASE: 13, // Erases a word left of cursor. - VLNEXT: 14, // Enter the next character typed literally, even if - // it is a special character - VFLUSH: 15, // Character to flush output. - VSWTCH: 16, // Switch to a different shell layer. - VSTATUS: 17, // Prints system status line (load, command, pid, - // etc). - VDISCARD: 18, // Toggles the flushing of terminal output. - IGNPAR: 30, // The ignore parity flag. The parameter SHOULD be 0 - // if this flag is FALSE, and 1 if it is TRUE. - PARMRK: 31, // Mark parity and framing errors. - INPCK: 32, // Enable checking of parity errors. - ISTRIP: 33, // Strip 8th bit off characters. - INLCR: 34, // Map NL into CR on input. - IGNCR: 35, // Ignore CR on input. - ICRNL: 36, // Map CR to NL on input. - IUCLC: 37, // Translate uppercase characters to lowercase. - IXON: 38, // Enable output flow control. - IXANY: 39, // Any char will restart after stop. - IXOFF: 40, // Enable input flow control. - IMAXBEL: 41, // Ring bell on input queue full. - ISIG: 50, // Enable signals INTR, QUIT, [D]SUSP. - ICANON: 51, // Canonicalize input lines. - XCASE: 52, // Enable input and output of uppercase characters by - // preceding their lowercase equivalents with "\". - ECHO: 53, // Enable echoing. - ECHOE: 54, // Visually erase chars. - ECHOK: 55, // Kill character discards current line. - ECHONL: 56, // Echo NL even if ECHO is off. - NOFLSH: 57, // Don't flush after interrupt. - TOSTOP: 58, // Stop background jobs from output. - IEXTEN: 59, // Enable extensions. - ECHOCTL: 60, // Echo control characters as ^(Char). - ECHOKE: 61, // Visual erase for line kill. - PENDIN: 62, // Retype pending input. - OPOST: 70, // Enable output processing. - OLCUC: 71, // Convert lowercase to uppercase. - ONLCR: 72, // Map NL to CR-NL. - OCRNL: 73, // Translate carriage return to newline (output). - ONOCR: 74, // Translate newline to carriage return-newline - // (output). - ONLRET: 75, // Newline performs a carriage return (output). - CS7: 90, // 7 bit mode. - CS8: 91, // 8 bit mode. - PARENB: 92, // Parity enable. - PARODD: 93, // Odd parity, else even. - TTY_OP_ISPEED: 128, // Specifies the input baud rate in bits per second. - TTY_OP_OSPEED: 129, // Specifies the output baud rate in bits per second. - }, - CHANNEL_EXTENDED_DATATYPE: { - STDERR: 1, - }, - - SIGNALS: [ - 'ABRT', 'ALRM', 'FPE', 'HUP', 'ILL', 'INT', 'QUIT', 'SEGV', 'TERM', 'USR1', - 'USR2', 'KILL', 'PIPE' - ].reduce((cur, val) => ({ ...cur, [val]: 1 }), {}), - - COMPAT, - COMPAT_CHECKS: [ - [ 'Cisco-1.25', COMPAT.BAD_DHGEX ], - [ /^Cisco-1[.]/, COMPAT.BUG_DHGEX_LARGE ], - [ /^[0-9.]+$/, COMPAT.OLD_EXIT ], // old SSH.com implementations - [ /^OpenSSH_5[.][0-9]+/, COMPAT.DYN_RPORT_BUG ], - [ /^OpenSSH_7[.]4/, COMPAT.IMPLY_RSA_SHA2_SIGALGS ], - ], - - // KEX proposal-related - DEFAULT_KEX, - SUPPORTED_KEX, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY, - DEFAULT_CIPHER, - SUPPORTED_CIPHER, - DEFAULT_MAC, - SUPPORTED_MAC, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION, - - curve25519Supported, - eddsaSupported, -}; - -module.exports.DISCONNECT_REASON_BY_VALUE = - Array.from(Object.entries(module.exports.DISCONNECT_REASON)) - .reduce((obj, [key, value]) => ({ ...obj, [value]: key }), {}); - - -/***/ }), - -/***/ 45708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// TODO: -// * make max packet size configurable -// * if decompression is enabled, use `._packet` in decipher instances as -// input to (sync) zlib inflater with appropriate offset and length to -// avoid an additional copy of payload data before inflation -// * factor decompression status into packet length checks - - -const { - createCipheriv, createDecipheriv, createHmac, randomFillSync, timingSafeEqual -} = __nccwpck_require__(6113); - -const { readUInt32BE, writeUInt32BE } = __nccwpck_require__(49475); - -const FastBuffer = Buffer[Symbol.species]; -const MAX_SEQNO = 2 ** 32 - 1; -const EMPTY_BUFFER = Buffer.alloc(0); -const BUF_INT = Buffer.alloc(4); -const DISCARD_CACHE = new Map(); -const MAX_PACKET_SIZE = 35000; - -let binding; -let AESGCMCipher; -let ChaChaPolyCipher; -let GenericCipher; -let AESGCMDecipher; -let ChaChaPolyDecipher; -let GenericDecipher; -try { - binding = __nccwpck_require__(29041); - ({ AESGCMCipher, ChaChaPolyCipher, GenericCipher, - AESGCMDecipher, ChaChaPolyDecipher, GenericDecipher } = binding); -} catch {} - -const CIPHER_STREAM = 1 << 0; -const CIPHER_INFO = (() => { - function info(sslName, blockLen, keyLen, ivLen, authLen, discardLen, flags) { - return { - sslName, - blockLen, - keyLen, - ivLen: (ivLen !== 0 || (flags & CIPHER_STREAM) - ? ivLen - : blockLen), - authLen, - discardLen, - stream: !!(flags & CIPHER_STREAM), - }; - } - - return { - 'chacha20-poly1305@openssh.com': - info('chacha20', 8, 64, 0, 16, 0, CIPHER_STREAM), - - 'aes128-gcm': info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm': info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - 'aes128-gcm@openssh.com': - info('aes-128-gcm', 16, 16, 12, 16, 0, CIPHER_STREAM), - 'aes256-gcm@openssh.com': - info('aes-256-gcm', 16, 32, 12, 16, 0, CIPHER_STREAM), - - 'aes128-cbc': info('aes-128-cbc', 16, 16, 0, 0, 0, 0), - 'aes192-cbc': info('aes-192-cbc', 16, 24, 0, 0, 0, 0), - 'aes256-cbc': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - 'rijndael-cbc@lysator.liu.se': info('aes-256-cbc', 16, 32, 0, 0, 0, 0), - '3des-cbc': info('des-ede3-cbc', 8, 24, 0, 0, 0, 0), - 'blowfish-cbc': info('bf-cbc', 8, 16, 0, 0, 0, 0), - 'idea-cbc': info('idea-cbc', 8, 16, 0, 0, 0, 0), - 'cast128-cbc': info('cast-cbc', 8, 16, 0, 0, 0, 0), - - 'aes128-ctr': info('aes-128-ctr', 16, 16, 16, 0, 0, CIPHER_STREAM), - 'aes192-ctr': info('aes-192-ctr', 16, 24, 16, 0, 0, CIPHER_STREAM), - 'aes256-ctr': info('aes-256-ctr', 16, 32, 16, 0, 0, CIPHER_STREAM), - '3des-ctr': info('des-ede3', 8, 24, 8, 0, 0, CIPHER_STREAM), - 'blowfish-ctr': info('bf-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - 'cast128-ctr': info('cast5-ecb', 8, 16, 8, 0, 0, CIPHER_STREAM), - - /* The "arcfour128" algorithm is the RC4 cipher, as described in - [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream - generated by the cipher MUST be discarded, and the first byte of the - first encrypted packet MUST be encrypted using the 1537th byte of - keystream. - - -- http://tools.ietf.org/html/rfc4345#section-4 */ - 'arcfour': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour128': info('rc4', 8, 16, 0, 0, 1536, CIPHER_STREAM), - 'arcfour256': info('rc4', 8, 32, 0, 0, 1536, CIPHER_STREAM), - 'arcfour512': info('rc4', 8, 64, 0, 0, 1536, CIPHER_STREAM), - }; -})(); - -const MAC_INFO = (() => { - function info(sslName, len, actualLen, isETM) { - return { - sslName, - len, - actualLen, - isETM, - }; - } - - return { - 'hmac-md5': info('md5', 16, 16, false), - 'hmac-md5-96': info('md5', 16, 12, false), - 'hmac-ripemd160': info('ripemd160', 20, 20, false), - 'hmac-sha1': info('sha1', 20, 20, false), - 'hmac-sha1-etm@openssh.com': info('sha1', 20, 20, true), - 'hmac-sha1-96': info('sha1', 20, 12, false), - 'hmac-sha2-256': info('sha256', 32, 32, false), - 'hmac-sha2-256-etm@openssh.com': info('sha256', 32, 32, true), - 'hmac-sha2-256-96': info('sha256', 32, 12, false), - 'hmac-sha2-512': info('sha512', 64, 64, false), - 'hmac-sha2-512-etm@openssh.com': info('sha512', 64, 64, true), - 'hmac-sha2-512-96': info('sha512', 64, 12, false), - }; -})(); - - -// Should only_be used during the initial handshake -class NullCipher { - constructor(seqno, onWrite) { - this.outSeqno = seqno; - this._onWrite = onWrite; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - (pktLen & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -const POLY1305_ZEROS = Buffer.alloc(32); -const POLY1305_OUT_COMPUTE = Buffer.alloc(16); -let POLY1305_WASM_MODULE; -let POLY1305_RESULT_MALLOC; -let poly1305_auth; -class ChaChaPolyCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encKeyMain = enc.cipherKey.slice(0, 32); - this._encKeyPktLen = enc.cipherKey.slice(32); - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.outSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Encrypt packet length - const pktLenEnc = - createCipheriv('chacha20', this._encKeyPktLen, POLY1305_OUT_COMPUTE) - .update(packet.slice(0, 4)); - this._onWrite(pktLenEnc); - - // Encrypt rest of packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const payloadEnc = - createCipheriv('chacha20', this._encKeyMain, POLY1305_OUT_COMPUTE) - .update(packet.slice(4)); - this._onWrite(payloadEnc); - - // Calculate Poly1305 MAC - poly1305_auth(POLY1305_RESULT_MALLOC, - pktLenEnc, - pktLenEnc.length, - payloadEnc, - payloadEnc.length, - polyKey); - const mac = Buffer.allocUnsafe(16); - mac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - this._onWrite(mac); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class ChaChaPolyCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new ChaChaPolyCipher(enc.cipherKey); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 8 - ((pktLen - 4) & (8 - 1)); - if (padLen < 4) - padLen += 8; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* MAC */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class AESGCMCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encSSLName = enc.cipherInfo.sslName; - this._encKey = enc.cipherKey; - this._encIV = enc.cipherIV; - this._dead = false; - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - const cipher = createCipheriv(this._encSSLName, this._encKey, this._encIV); - cipher.setAutoPadding(false); - - const lenData = packet.slice(0, 4); - cipher.setAAD(lenData); - this._onWrite(lenData); - - // Encrypt pad length, payload, and padding - const encrypted = cipher.update(packet.slice(4)); - this._onWrite(encrypted); - const final = cipher.final(); - // XXX: final.length === 0 always? - if (final.length) - this._onWrite(final); - - // Generate MAC - const tag = cipher.getAuthTag(); - this._onWrite(tag); - - // Increment counter in IV by 1 for next packet - ivIncrement(this._encIV); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class AESGCMCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._instance = new AESGCMCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - let pktLen = 4 + 1 + payloadLen; - let padLen = 16 - ((pktLen - 4) & (16 - 1)); - if (padLen < 4) - padLen += 16; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + 16/* authTag */); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet); - - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class GenericCipherNative { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._cipherInstance = createCipheriv(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV); - this._macSSLName = enc.macInfo.sslName; - this._macKey = enc.macKey; - this._macActualLen = enc.macInfo.actualLen; - this._macETM = enc.macInfo.isETM; - this._aadLen = (this._macETM ? 4 : 0); - this._dead = false; - - const discardLen = enc.cipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._cipherInstance.update(discard); + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + // both _challenge and _verify independently acquire the lock, so no need + // to acquire it here + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId, + }); + if (challengeError) { + return this._returnResult({ data: null, error: challengeError }); + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code, + }); } - } - free() { - this._dead = true; - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - let mac; - if (this._macETM) { - // Encrypt pad length, payload, and padding - const lenBytes = new Uint8Array(packet.buffer, packet.byteOffset, 4); - const encrypted = this._cipherInstance.update( - new Uint8Array(packet.buffer, - packet.byteOffset + 4, - packet.length - 4) - ); - - this._onWrite(lenBytes); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(lenBytes); - mac.update(encrypted); - } else { - // Encrypt length field, pad length, payload, and padding - const encrypted = this._cipherInstance.update(packet); - this._onWrite(encrypted); - - // TODO: look into storing seqno as 4-byte buffer and incrementing like we - // do for AES-GCM IVs to avoid having to (re)write all 4 bytes every time - mac = createHmac(this._macSSLName, this._macKey); - writeUInt32BE(BUF_INT, this.outSeqno, 0); - mac.update(BUF_INT); - mac.update(packet); + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + var _a; + // use #getUser instead of #_getUser as the former acquires a lock + const { data: { user }, error: userError, } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const data = { + all: [], + phone: [], + totp: [], + webauthn: [], + }; + // loop over the factors ONCE + for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) { + data.all.push(factor); + if (factor.status === 'verified') { + ; + data[factor.factor_type].push(factor); + } + } + return { + data, + error: null, + }; } - - let digest = mac.digest(); - if (digest.length > this._macActualLen) - digest = digest.slice(0, this._macActualLen); - this._onWrite(digest); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - -class GenericCipherBinding { - constructor(config) { - const enc = config.outbound; - this.outSeqno = enc.seqno; - this._onWrite = enc.onWrite; - this._encBlockLen = enc.cipherInfo.blockLen; - this._macLen = enc.macInfo.len; - this._macActualLen = enc.macInfo.actualLen; - this._aadLen = (enc.macInfo.isETM ? 4 : 0); - this._instance = new GenericCipher(enc.cipherInfo.sslName, - enc.cipherKey, - enc.cipherIV, - enc.macInfo.sslName, - enc.macKey, - enc.macInfo.isETM); - this._dead = false; - } - free() { - this._dead = true; - this._instance.free(); - } - allocPacket(payloadLen) { - const blockLen = this._encBlockLen; - - let pktLen = 4 + 1 + payloadLen; - let padLen = blockLen - ((pktLen - this._aadLen) & (blockLen - 1)); - if (padLen < 4) - padLen += blockLen; - pktLen += padLen; - - const packet = Buffer.allocUnsafe(pktLen + this._macLen); - - writeUInt32BE(packet, pktLen - 4, 0); - packet[4] = padLen; - - randomFillSync(packet, 5 + payloadLen, padLen); - - return packet; - } - encrypt(packet) { - // `packet` === unencrypted packet - - if (this._dead) - return; - - // Encrypts in-place - this._instance.encrypt(packet, this.outSeqno); - - if (this._macActualLen < this._macLen) { - packet = new FastBuffer(packet.buffer, - packet.byteOffset, - (packet.length - - (this._macLen - this._macActualLen))); + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + var _a, _b; + const { data: { session }, error: sessionError, } = await this.getSession(); + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null, + }; + } + const { payload } = (0, helpers_1.decodeJWT)(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = 'aal2'; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; } - this._onWrite(packet); - - this.outSeqno = (this.outSeqno + 1) >>> 0; - } -} - - -class NullDecipher { - constructor(seqno, onPayload) { - this.inSeqno = seqno; - this._onPayload = onPayload; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - while (p < dataLen) { - // Read packet length - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - - if (this._lenBytes < 4) - return; - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (4 + this._len & 7) !== 0) { - throw new Error('Bad packet length'); + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + async _getAuthorizationDetails(authorizationId) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }), + }); + }); } - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._packetPos < this._len) { - const nb = Math.min(this._len - this._packetPos, dataLen - p); - let chunk; - if (p !== 0 || nb !== dataLen) - chunk = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - chunk = data; - if (nb === this._len) { - this._packet = chunk; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(chunk, this._packetPos); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; } - p += nb; - this._packetPos += nb; - if (this._packetPos < this._len) - return; - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } -} - -class ChaChaPolyDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decKeyMain = dec.decipherKey.slice(0, 32); - this._decKeyPktLen = dec.decipherKey.slice(32); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._calcMac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - - const decLenBytes = - createDecipheriv('chacha20', this._decKeyPktLen, POLY1305_OUT_COMPUTE) - .update(this._lenBuf); - this._len = readUInt32BE(decLenBytes, 0); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _approveAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'approve' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - // Generate Poly1305 key - POLY1305_OUT_COMPUTE[0] = 0; // Set counter to 0 (little endian) - writeUInt32BE(POLY1305_OUT_COMPUTE, this.inSeqno, 12); - const polyKey = - createCipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(POLY1305_ZEROS); - - // Calculate and compare Poly1305 MACs - poly1305_auth(POLY1305_RESULT_MALLOC, - this._lenBuf, - 4, - this._packet, - this._packet.length, - polyKey); - - this._calcMac.set( - new Uint8Array(POLY1305_WASM_MODULE.HEAPU8.buffer, - POLY1305_RESULT_MALLOC, - 16), - 0 - ); - if (!timingSafeEqual(this._calcMac, this._mac)) - throw new Error('Invalid MAC'); - - // Decrypt packet - POLY1305_OUT_COMPUTE[0] = 1; // Set counter to 1 (little endian) - const packet = - createDecipheriv('chacha20', this._decKeyMain, POLY1305_OUT_COMPUTE) - .update(this._packet); - - const payload = new FastBuffer(packet.buffer, - packet.byteOffset + 1, - packet.length - packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } -} - -class ChaChaPolyDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new ChaChaPolyDecipher(dec.decipherKey); - this._len = 0; - this._lenBuf = Buffer.alloc(4); - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(16); - this._macPos = 0; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length - if (this._lenPos < 4) { - let nb = Math.min(4 - this._lenPos, dataLen - p); - while (nb--) - this._lenBuf[this._lenPos++] = data[p++]; - if (this._lenPos < 4) - return; - - this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno); - - if (this._len > MAX_PACKET_SIZE - || this._len < 8 - || (this._len & 7) !== 0) { - throw new Error('Bad packet length'); - } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _denyAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError, } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: 'deny' }, + xform: (data) => ({ data, error: null }), + }); + if (response.data && response.data.redirect_url) { + // Automatically redirect in browser unless skipBrowserRedirect is true + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read Poly1305 MAC - { - const nb = Math.min(16 - this._macPos, dataLen - p); - // TODO: avoid copying if entire MAC is in current chunk - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; } - p += nb; - this._macPos += nb; - if (this._macPos < 16) - return; - } - - this._instance.decrypt(this._packet, this._mac, this.inSeqno); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenPos = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } -} - -class AESGCMDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = null; - this._decipherSSLName = dec.decipherInfo.sslName; - this._decipherKey = dec.decipherKey; - this._decipherIV = dec.decipherIV; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; - - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error('Bad packet length'); + async fetchJwk(kid, jwks = { keys: [] }) { + // try fetching from the supplied jwks + let jwk = jwks.keys.find((key) => key.kid === kid); + if (jwk) { + return jwk; } - - this._decipherInstance = createDecipheriv( - this._decipherSSLName, - this._decipherKey, - this._decipherIV - ); - this._decipherInstance.setAutoPadding(false); - this._decipherInstance.setAAD(intToBytes(this._len)); - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let decrypted; - if (p !== 0 || nb !== dataLen) { - decrypted = this._decipherInstance.update( - new Uint8Array(data.buffer, data.byteOffset + p, nb) - ); - } else { - decrypted = this._decipherInstance.update(data); + const now = Date.now(); + // try fetching from cache + jwk = this.jwks.keys.find((key) => key.kid === kid); + // jwk exists and jwks isn't stale + if (jwk && this.jwks_cached_at + constants_1.JWKS_TTL > now) { + return jwk; } - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; + // jwk isn't cached in memory so we need to fetch it from the well-known endpoint + const { data, error } = await (0, fetch_1._request)(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, { + headers: this.headers, + }); + if (error) { + throw error; } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); + if (!data.keys || data.keys.length === 0) { + return null; } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } - - { - // Verify authentication tag - this._decipherInstance.setAuthTag(this._tag); - - const decrypted = this._decipherInstance.final(); - - // XXX: this should never output any data since stream ciphers always - // return data from .update() and block ciphers must end on a multiple - // of the block length, which would have caused an exception to be - // thrown if the total input was not... - if (decrypted.length) { - if (this._packet) - this._packet.set(decrypted, this._packetPos); - else - this._packet = decrypted; + this.jwks = data; + this.jwks_cached_at = now; + // Find the signing key + jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) { + return null; + } + return jwk; + } + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + async getClaims(jwt, options = {}) { + try { + let token = jwt; + if (!token) { + const { data, error } = await this.getSession(); + if (error || !data.session) { + return this._returnResult({ data: null, error }); + } + token = data.session.access_token; + } + const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = (0, helpers_1.decodeJWT)(token); + if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { + // Reject expired JWTs should only happen if jwt argument was passed + (0, helpers_1.validateExp)(payload.exp); + } + const signingKey = !header.alg || + header.alg.startsWith('HS') || + !header.kid || + !('crypto' in globalThis && 'subtle' in globalThis.crypto) + ? null + : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); + // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser() + if (!signingKey) { + const { error } = await this.getUser(token); + if (error) { + throw error; + } + // getUser succeeds so the claims in the JWT can be trusted + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + const algorithm = (0, helpers_1.getAlgorithm)(header.alg); + // Convert JWK to CryptoKey + const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [ + 'verify', + ]); + // Verify the signature + const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, (0, base64url_1.stringToUint8Array)(`${rawHeader}.${rawPayload}`)); + if (!isValid) { + throw new errors_1.AuthInvalidJwtError('Invalid JWT signature'); + } + // If verification succeeds, decode and return claims + return { + data: { + claims: payload, + header, + signature, + }, + error: null, + }; + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; } - } - - const payload = (!this._packet - ? EMPTY_BUFFER - : new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - - this._packet[0] - 1)); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - ivIncrement(this._decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._tagPos = 0; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } } +GoTrueClient.nextInstanceID = {}; +exports["default"] = GoTrueClient; +//# sourceMappingURL=GoTrueClient.js.map -class AESGCMDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new AESGCMDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tag = Buffer.allocUnsafe(16); - this._tagPos = 0; - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read packet length (unencrypted, but AAD) - if (this._lenBytes < 4) { - let nb = Math.min(4 - this._lenBytes, dataLen - p); - this._lenBytes += nb; - while (nb--) - this._len = (this._len << 8) + data[p++]; - if (this._lenBytes < 4) - return; +/***/ }), - if ((this._len + 20) > MAX_PACKET_SIZE - || this._len < 16 - || (this._len & 15) !== 0) { - throw new Error(`Bad packet length: ${this._len}`); - } - } +/***/ 6748: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - if (p >= dataLen) - return; - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); - } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } +"use strict"; - // Read authentication tag - { - const nb = Math.min(16 - this._tagPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._tag.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._tagPos - ); - } else { - this._tag.set(data, this._tagPos); - } - p += nb; - this._tagPos += nb; - if (this._tagPos < 16) - return; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; +const tslib_1 = __nccwpck_require__(4351); +const GoTrueAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(6575)); +exports.GoTrueAdminApi = GoTrueAdminApi_1.default; +const GoTrueClient_1 = tslib_1.__importDefault(__nccwpck_require__(313)); +exports.GoTrueClient = GoTrueClient_1.default; +const AuthAdminApi_1 = tslib_1.__importDefault(__nccwpck_require__(9809)); +exports.AuthAdminApi = AuthAdminApi_1.default; +const AuthClient_1 = tslib_1.__importDefault(__nccwpck_require__(4525)); +exports.AuthClient = AuthClient_1.default; +tslib_1.__exportStar(__nccwpck_require__(1852), exports); +tslib_1.__exportStar(__nccwpck_require__(9938), exports); +var locks_1 = __nccwpck_require__(163); +Object.defineProperty(exports, "navigatorLock", ({ enumerable: true, get: function () { return locks_1.navigatorLock; } })); +Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", ({ enumerable: true, get: function () { return locks_1.NavigatorLockAcquireTimeoutError; } })); +Object.defineProperty(exports, "lockInternals", ({ enumerable: true, get: function () { return locks_1.internals; } })); +Object.defineProperty(exports, "processLock", ({ enumerable: true, get: function () { return locks_1.processLock; } })); +//# sourceMappingURL=index.js.map - this._instance.decrypt(this._packet, this._len, this._tag); +/***/ }), - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); +/***/ 3649: +/***/ ((__unused_webpack_module, exports) => { - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._len = 0; - this._lenBytes = 0; - this._packet = null; - this._pktLen = 0; - this._tagPos = 0; +"use strict"; - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } +/** + * Avoid modifying this file. It's part of + * https://github.com/supabase-community/base64url-js. Submit all fixes on + * that repo! + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.byteToBase64URL = byteToBase64URL; +exports.byteFromBase64URL = byteFromBase64URL; +exports.stringToBase64URL = stringToBase64URL; +exports.stringFromBase64URL = stringFromBase64URL; +exports.codepointToUTF8 = codepointToUTF8; +exports.stringToUTF8 = stringToUTF8; +exports.stringFromUTF8 = stringFromUTF8; +exports.base64UrlToUint8Array = base64UrlToUint8Array; +exports.stringToUint8Array = stringToUint8Array; +exports.bytesToBase64URL = bytesToBase64URL; +/** + * An array of characters that encode 6 bits into a Base64-URL alphabet + * character. + */ +const TO_BASE64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.split(''); +/** + * An array of characters that can appear in a Base64-URL encoded string but + * should be ignored. + */ +const IGNORE_BASE64URL = ' \t\n\r='.split(''); +/** + * An array of 128 numbers that map a Base64-URL character to 6 bits, or if -2 + * used to skip the character, or if -1 used to error out. + */ +const FROM_BASE64URL = (() => { + const charMap = new Array(128); + for (let i = 0; i < charMap.length; i += 1) { + charMap[i] = -1; } - } -} - -// TODO: test incremental .update()s vs. copying to _packet and doing a single -// .update() after entire packet read -- a single .update() would allow -// verifying MAC before decrypting for ETM MACs -class GenericDecipherNative { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._decipherInstance = createDecipheriv(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV); - this._decipherInstance.setAutoPadding(false); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM ? 4 : dec.decipherInfo.blockLen - ); - this._blockSize = dec.decipherInfo.blockLen; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macSSLName = dec.macInfo.sslName; - this._macKey = dec.macKey; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - this._macInstance = null; - - const discardLen = dec.decipherInfo.discardLen; - if (discardLen) { - let discard = DISCARD_CACHE.get(discardLen); - if (discard === undefined) { - discard = Buffer.alloc(discardLen); - DISCARD_CACHE.set(discardLen, discard); - } - this._decipherInstance.update(discard); + for (let i = 0; i < IGNORE_BASE64URL.length; i += 1) { + charMap[IGNORE_BASE64URL[i].charCodeAt(0)] = -2; } - } - free() {} - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); + for (let i = 0; i < TO_BASE64URL.length; i += 1) { + charMap[TO_BASE64URL[i].charCodeAt(0)] = i; + } + return charMap; +})(); +/** + * Converts a byte to a Base64-URL string. + * + * @param byte The byte to convert, or null to flush at the end of the byte sequence. + * @param state The Base64 conversion state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next Base64 character when ready. + */ +function byteToBase64URL(byte, state, emit) { + if (byte !== null) { + state.queue = (state.queue << 8) | byte; + state.queuedBits += 8; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; } - - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - - let decrypted; - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - decrypted = this._decipherInstance.update(this._block); - this._len = readUInt32BE(decrypted, 0); - need = 4 + this._len - this._blockSize; + } + else if (state.queuedBits > 0) { + state.queue = state.queue << (6 - state.queuedBits); + state.queuedBits = 6; + while (state.queuedBits >= 6) { + const pos = (state.queue >> (state.queuedBits - 6)) & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } +} +/** + * Converts a String char code (extracted using `string.charCodeAt(position)`) to a sequence of Base64-URL characters. + * + * @param charCode The char code of the JavaScript string. + * @param state The Base64 state. Pass an initial value of `{ queue: 0, queuedBits: 0 }`. + * @param emit A function called with the next byte. + */ +function byteFromBase64URL(charCode, state, emit) { + const bits = FROM_BASE64URL[charCode]; + if (bits > -1) { + // valid Base64-URL character + state.queue = (state.queue << 6) | bits; + state.queuedBits += 6; + while (state.queuedBits >= 8) { + emit((state.queue >> (state.queuedBits - 8)) & 0xff); + state.queuedBits -= 8; + } + } + else if (bits === -2) { + // ignore spaces, tabs, newlines, = + return; + } + else { + throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); + } +} +/** + * Converts a JavaScript string (which may include any valid character) into a + * Base64-URL encoded string. The string is first encoded in UTF-8 which is + * then encoded as Base64-URL. + * + * @param str The string to convert. + */ +function stringToBase64URL(str) { + const base64 = []; + const emitter = (char) => { + base64.push(char); + }; + const state = { queue: 0, queuedBits: 0 }; + stringToUTF8(str, (byte) => { + byteToBase64URL(byte, state, emitter); + }); + byteToBase64URL(null, state, emitter); + return base64.join(''); +} +/** + * Converts a Base64-URL encoded string into a JavaScript string. It is assumed + * that the underlying string has been encoded as UTF-8. + * + * @param str The Base64-URL encoded string. + */ +function stringFromBase64URL(str) { + const conv = []; + const utf8Emit = (codepoint) => { + conv.push(String.fromCodePoint(codepoint)); + }; + const utf8State = { + utf8seq: 0, + codepoint: 0, + }; + const b64State = { queue: 0, queuedBits: 0 }; + const byteEmit = (byte) => { + stringFromUTF8(byte, utf8State, utf8Emit); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), b64State, byteEmit); + } + return conv.join(''); +} +/** + * Converts a Unicode codepoint to a multi-byte UTF-8 sequence. + * + * @param codepoint The Unicode codepoint. + * @param emit Function which will be called for each UTF-8 byte that represents the codepoint. + */ +function codepointToUTF8(codepoint, emit) { + if (codepoint <= 0x7f) { + emit(codepoint); + return; + } + else if (codepoint <= 0x7ff) { + emit(0xc0 | (codepoint >> 6)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + else if (codepoint <= 0xffff) { + emit(0xe0 | (codepoint >> 12)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + else if (codepoint <= 0x10ffff) { + emit(0xf0 | (codepoint >> 18)); + emit(0x80 | ((codepoint >> 12) & 0x3f)); + emit(0x80 | ((codepoint >> 6) & 0x3f)); + emit(0x80 | (codepoint & 0x3f)); + return; + } + throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); +} +/** + * Converts a JavaScript string to a sequence of UTF-8 bytes. + * + * @param str The string to convert to UTF-8. + * @param emit Function which will be called for each UTF-8 byte of the string. + */ +function stringToUTF8(str, emit) { + for (let i = 0; i < str.length; i += 1) { + let codepoint = str.charCodeAt(i); + if (codepoint > 0xd7ff && codepoint <= 0xdbff) { + // most UTF-16 codepoints are Unicode codepoints, except values in this + // range where the next UTF-16 codepoint needs to be combined with the + // current one to get the Unicode codepoint + const highSurrogate = ((codepoint - 0xd800) * 0x400) & 0xffff; + const lowSurrogate = (str.charCodeAt(i + 1) - 0xdc00) & 0xffff; + codepoint = (lowSurrogate | highSurrogate) + 0x10000; + i += 1; } - - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._blockSize - 1)) !== 0) { - throw new Error('Bad packet length'); + codepointToUTF8(codepoint, emit); + } +} +/** + * Converts a UTF-8 byte to a Unicode codepoint. + * + * @param byte The UTF-8 byte next in the sequence. + * @param state The shared state between consecutive UTF-8 bytes in the + * sequence, an object with the shape `{ utf8seq: 0, codepoint: 0 }`. + * @param emit Function which will be called for each codepoint. + */ +function stringFromUTF8(byte, state, emit) { + if (state.utf8seq === 0) { + if (byte <= 0x7f) { + emit(byte); + return; } - - // Create MAC up front to calculate in parallel with decryption - this._macInstance = createHmac(this._macSSLName, this._macKey); - - writeUInt32BE(BUF_INT, this.inSeqno, 0); - this._macInstance.update(BUF_INT); - if (this._macETM) { - this._macInstance.update(this._block); - } else { - this._macInstance.update(new Uint8Array(decrypted.buffer, - decrypted.byteOffset, - 4)); - this._pktLen = decrypted.length - 4; - this._packetPos = this._pktLen; - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(decrypted.buffer, - decrypted.byteOffset + 4, - this._packetPos), - 0 - ); + // count the number of 1 leading bits until you reach 0 + for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { + if (((byte >> (7 - leadingBit)) & 1) === 0) { + state.utf8seq = leadingBit; + break; + } } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (this._macETM) - this._macInstance.update(encrypted); - const decrypted = this._decipherInstance.update(encrypted); - if (decrypted.length) { - if (nb === this._len) { - this._packet = decrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(decrypted, this._packetPos); - } - this._packetPos += decrypted.length; + if (state.utf8seq === 2) { + state.codepoint = byte & 31; } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); + else if (state.utf8seq === 3) { + state.codepoint = byte & 15; } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - - // Verify MAC - if (!this._macETM) - this._macInstance.update(this._packet); - let calculated = this._macInstance.digest(); - if (this._macActualLen < calculated.length) { - calculated = new Uint8Array(calculated.buffer, - calculated.byteOffset, - this._macActualLen); - } - if (!timingSafeEquals(calculated, this._mac)) - throw new Error('Invalid MAC'); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._packetPos = 0; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } - } - } -} - -class GenericDecipherBinding { - constructor(config) { - const dec = config.inbound; - this.inSeqno = dec.seqno; - this._onPayload = dec.onPayload; - this._instance = new GenericDecipher(dec.decipherInfo.sslName, - dec.decipherKey, - dec.decipherIV, - dec.macInfo.sslName, - dec.macKey, - dec.macInfo.isETM, - dec.macInfo.actualLen); - this._block = Buffer.allocUnsafe( - dec.macInfo.isETM || dec.decipherInfo.stream - ? 4 - : dec.decipherInfo.blockLen - ); - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._mac = Buffer.allocUnsafe(dec.macInfo.actualLen); - this._macPos = 0; - this._macActualLen = dec.macInfo.actualLen; - this._macETM = dec.macInfo.isETM; - } - free() { - this._instance.free(); - } - decrypt(data, p, dataLen) { - // `data` === encrypted data - - while (p < dataLen) { - // Read first encrypted block - if (this._blockPos < this._block.length) { - const nb = Math.min(this._block.length - this._blockPos, dataLen - p); - if (p !== 0 || nb !== dataLen || nb < data.length) { - this._block.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._blockPos - ); - } else { - this._block.set(data, this._blockPos); + else if (state.utf8seq === 4) { + state.codepoint = byte & 7; } - - p += nb; - this._blockPos += nb; - if (this._blockPos < this._block.length) - return; - - let need; - if (this._macETM) { - this._len = need = readUInt32BE(this._block, 0); - } else { - // Decrypt first block to get packet length - this._instance.decryptBlock(this._block); - this._len = readUInt32BE(this._block, 0); - need = 4 + this._len - this._block.length; - } - - if (this._len > MAX_PACKET_SIZE - || this._len < 5 - || (need & (this._block.length - 1)) !== 0) { - throw new Error('Bad packet length'); - } - - if (!this._macETM) { - this._pktLen = (this._block.length - 4); - if (this._pktLen) { - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set( - new Uint8Array(this._block.buffer, - this._block.byteOffset + 4, - this._pktLen), - 0 - ); - } + else { + throw new Error('Invalid UTF-8 sequence'); } - - if (p >= dataLen) - return; - } - - // Read padding length, payload, and padding - if (this._pktLen < this._len) { - const nb = Math.min(this._len - this._pktLen, dataLen - p); - let encrypted; - if (p !== 0 || nb !== dataLen) - encrypted = new Uint8Array(data.buffer, data.byteOffset + p, nb); - else - encrypted = data; - if (nb === this._len) { - this._packet = encrypted; - } else { - if (!this._packet) - this._packet = Buffer.allocUnsafe(this._len); - this._packet.set(encrypted, this._pktLen); + state.utf8seq -= 1; + } + else if (state.utf8seq > 0) { + if (byte <= 0x7f) { + throw new Error('Invalid UTF-8 sequence'); } - p += nb; - this._pktLen += nb; - if (this._pktLen < this._len || p >= dataLen) - return; - } - - // Read MAC - { - const nb = Math.min(this._macActualLen - this._macPos, dataLen - p); - if (p !== 0 || nb !== dataLen) { - this._mac.set( - new Uint8Array(data.buffer, data.byteOffset + p, nb), - this._macPos - ); - } else { - this._mac.set(data, this._macPos); + state.codepoint = (state.codepoint << 6) | (byte & 63); + state.utf8seq -= 1; + if (state.utf8seq === 0) { + emit(state.codepoint); } - p += nb; - this._macPos += nb; - if (this._macPos < this._macActualLen) - return; - } - - // Decrypt and verify MAC - this._instance.decrypt(this._packet, - this.inSeqno, - this._block, - this._mac); - - const payload = new FastBuffer(this._packet.buffer, - this._packet.byteOffset + 1, - this._packet.length - this._packet[0] - 1); - - // Prepare for next packet - this.inSeqno = (this.inSeqno + 1) >>> 0; - this._blockPos = 0; - this._len = 0; - this._packet = null; - this._pktLen = 0; - this._macPos = 0; - this._macInstance = null; - - { - const ret = this._onPayload(payload); - if (ret !== undefined) - return (ret === false ? p : ret); - } } - } } - -// Increments unsigned, big endian counter (last 8 bytes) of AES-GCM IV -function ivIncrement(iv) { - // eslint-disable-next-line no-unused-expressions - ++iv[11] >>> 8 - && ++iv[10] >>> 8 - && ++iv[9] >>> 8 - && ++iv[8] >>> 8 - && ++iv[7] >>> 8 - && ++iv[6] >>> 8 - && ++iv[5] >>> 8 - && ++iv[4] >>> 8; +/** + * Helper functions to convert different types of strings to Uint8Array + */ +function base64UrlToUint8Array(str) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onByte = (byte) => { + result.push(byte); + }; + for (let i = 0; i < str.length; i += 1) { + byteFromBase64URL(str.charCodeAt(i), state, onByte); + } + return new Uint8Array(result); } - -const intToBytes = (() => { - const ret = Buffer.alloc(4); - return (n) => { - ret[0] = (n >>> 24); - ret[1] = (n >>> 16); - ret[2] = (n >>> 8); - ret[3] = n; - return ret; - }; -})(); - -function timingSafeEquals(a, b) { - if (a.length !== b.length) { - timingSafeEqual(a, a); - return false; - } - return timingSafeEqual(a, b); +function stringToUint8Array(str) { + const result = []; + stringToUTF8(str, (byte) => result.push(byte)); + return new Uint8Array(result); } +function bytesToBase64URL(bytes) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onChar = (char) => { + result.push(char); + }; + bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); + // always call with `null` after processing all bytes + byteToBase64URL(null, state, onChar); + return result.join(''); +} +//# sourceMappingURL=base64url.js.map -function createCipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.outbound !== 'object' || config.outbound === null) - throw new Error('Invalid outbound'); - - const outbound = config.outbound; +/***/ }), - if (typeof outbound.onWrite !== 'function') - throw new Error('Invalid outbound.onWrite'); +/***/ 518: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (typeof outbound.cipherInfo !== 'object' || outbound.cipherInfo === null) - throw new Error('Invalid outbound.cipherInfo'); +"use strict"; - if (!Buffer.isBuffer(outbound.cipherKey) - || outbound.cipherKey.length !== outbound.cipherInfo.keyLen) { - throw new Error('Invalid outbound.cipherKey'); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0; +const version_1 = __nccwpck_require__(6677); +/** Current session will be checked for refresh at this interval. */ +exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000; +/** + * A token refresh will be attempted this many ticks before the current session expires. */ +exports.AUTO_REFRESH_TICK_THRESHOLD = 3; +/* + * Earliest time before an access token expires that the session should be refreshed. + */ +exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS; +exports.GOTRUE_URL = 'http://localhost:9999'; +exports.STORAGE_KEY = 'supabase.auth.token'; +exports.AUDIENCE = ''; +exports.DEFAULT_HEADERS = { 'X-Client-Info': `gotrue-js/${version_1.version}` }; +exports.NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2, // in deciseconds +}; +exports.API_VERSION_HEADER_NAME = 'X-Supabase-Api-Version'; +exports.API_VERSIONS = { + '2024-01-01': { + timestamp: Date.parse('2024-01-01T00:00:00.0Z'), + name: '2024-01-01', + }, +}; +exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; +exports.JWKS_TTL = 10 * 60 * 1000; // 10 minutes +//# sourceMappingURL=constants.js.map - if (outbound.cipherInfo.ivLen - && (!Buffer.isBuffer(outbound.cipherIV) - || outbound.cipherIV.length !== outbound.cipherInfo.ivLen)) { - throw new Error('Invalid outbound.cipherIV'); - } +/***/ }), - if (typeof outbound.seqno !== 'number' - || outbound.seqno < 0 - || outbound.seqno > MAX_SEQNO) { - throw new Error('Invalid outbound.seqno'); - } +/***/ 9938: +/***/ ((__unused_webpack_module, exports) => { - const forceNative = !!outbound.forceNative; +"use strict"; - switch (outbound.cipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMCipher && !forceNative - ? new AESGCMCipherBinding(config) - : new AESGCMCipherNative(config)); - case 'chacha20': - return (ChaChaPolyCipher && !forceNative - ? new ChaChaPolyCipherBinding(config) - : new ChaChaPolyCipherNative(config)); - default: { - if (typeof outbound.macInfo !== 'object' || outbound.macInfo === null) - throw new Error('Invalid outbound.macInfo'); - if (!Buffer.isBuffer(outbound.macKey) - || outbound.macKey.length !== outbound.macInfo.len) { - throw new Error('Invalid outbound.macKey'); - } - return (GenericCipher && !forceNative - ? new GenericCipherBinding(config) - : new GenericCipherNative(config)); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0; +exports.isAuthError = isAuthError; +exports.isAuthApiError = isAuthApiError; +exports.isAuthSessionMissingError = isAuthSessionMissingError; +exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError; +exports.isAuthRetryableFetchError = isAuthRetryableFetchError; +exports.isAuthWeakPasswordError = isAuthWeakPasswordError; +class AuthError extends Error { + constructor(message, status, code) { + super(message); + this.__isAuthError = true; + this.name = 'AuthError'; + this.status = status; + this.code = code; } - } } - -function createDecipher(config) { - if (typeof config !== 'object' || config === null) - throw new Error('Invalid config'); - - if (typeof config.inbound !== 'object' || config.inbound === null) - throw new Error('Invalid inbound'); - - const inbound = config.inbound; - - if (typeof inbound.onPayload !== 'function') - throw new Error('Invalid inbound.onPayload'); - - if (typeof inbound.decipherInfo !== 'object' - || inbound.decipherInfo === null) { - throw new Error('Invalid inbound.decipherInfo'); - } - - if (!Buffer.isBuffer(inbound.decipherKey) - || inbound.decipherKey.length !== inbound.decipherInfo.keyLen) { - throw new Error('Invalid inbound.decipherKey'); - } - - if (inbound.decipherInfo.ivLen - && (!Buffer.isBuffer(inbound.decipherIV) - || inbound.decipherIV.length !== inbound.decipherInfo.ivLen)) { - throw new Error('Invalid inbound.decipherIV'); - } - - if (typeof inbound.seqno !== 'number' - || inbound.seqno < 0 - || inbound.seqno > MAX_SEQNO) { - throw new Error('Invalid inbound.seqno'); - } - - const forceNative = !!inbound.forceNative; - - switch (inbound.decipherInfo.sslName) { - case 'aes-128-gcm': - case 'aes-256-gcm': - return (AESGCMDecipher && !forceNative - ? new AESGCMDecipherBinding(config) - : new AESGCMDecipherNative(config)); - case 'chacha20': - return (ChaChaPolyDecipher && !forceNative - ? new ChaChaPolyDecipherBinding(config) - : new ChaChaPolyDecipherNative(config)); - default: { - if (typeof inbound.macInfo !== 'object' || inbound.macInfo === null) - throw new Error('Invalid inbound.macInfo'); - if (!Buffer.isBuffer(inbound.macKey) - || inbound.macKey.length !== inbound.macInfo.len) { - throw new Error('Invalid inbound.macKey'); - } - return (GenericDecipher && !forceNative - ? new GenericDecipherBinding(config) - : new GenericDecipherNative(config)); +exports.AuthError = AuthError; +function isAuthError(error) { + return typeof error === 'object' && error !== null && '__isAuthError' in error; +} +class AuthApiError extends AuthError { + constructor(message, status, code) { + super(message, status, code); + this.name = 'AuthApiError'; + this.status = status; + this.code = code; } - } } - -module.exports = { - CIPHER_INFO, - MAC_INFO, - bindingAvailable: !!binding, - init: (() => { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - try { - POLY1305_WASM_MODULE = await __nccwpck_require__(64989)(); - POLY1305_RESULT_MALLOC = POLY1305_WASM_MODULE._malloc(16); - poly1305_auth = POLY1305_WASM_MODULE.cwrap( - 'poly1305_auth', - null, - ['number', 'array', 'number', 'array', 'number', 'array'] - ); - } catch (ex) { - return reject(ex); - } - resolve(); - }); - })(), - - NullCipher, - createCipher, - NullDecipher, - createDecipher, -}; - - -/***/ }), - -/***/ 64989: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var createPoly1305 = (function() { - var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; - if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; - return ( -function(createPoly1305) { - createPoly1305 = createPoly1305 || {}; - - -var b;b||(b=typeof createPoly1305 !== 'undefined' ? createPoly1305 : {});var q,r;b.ready=new Promise(function(a,c){q=a;r=c});var u={},w;for(w in b)b.hasOwnProperty(w)&&(u[w]=b[w]);var x="object"===typeof window,y="function"===typeof importScripts,z="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node,B="",C,D,E,F,G; -if(z)B=y?(__nccwpck_require__(71017).dirname)(B)+"/":__dirname+"/",C=function(a,c){var d=H(a);if(d)return c?d:d.toString();F||(F=__nccwpck_require__(57147));G||(G=__nccwpck_require__(71017));a=G.normalize(a);return F.readFileSync(a,c?null:"utf8")},E=function(a){a=C(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},D=function(a,c,d){var e=H(a);e&&c(e);F||(F=__nccwpck_require__(57147));G||(G=__nccwpck_require__(71017));a=G.normalize(a);F.readFile(a,function(f,l){f?d(f):c(l.buffer)})},1=m){var oa=g.charCodeAt(++v);m=65536+((m&1023)<<10)|oa&1023}if(127>=m){if(k>=n)break;h[k++]=m}else{if(2047>=m){if(k+1>=n)break;h[k++]=192|m>>6}else{if(65535>=m){if(k+2>=n)break;h[k++]=224|m>>12}else{if(k+3>=n)break;h[k++]=240|m>>18;h[k++]=128|m>>12&63}h[k++]=128|m>>6&63}h[k++]=128|m&63}}h[k]= -0}}return p},array:function(g){var p=O(g.length);Q.set(g,p);return p}},l=N(a),A=[];a=0;if(e)for(var t=0;t=n);)++k;if(16h?n+=String.fromCharCode(h):(h-=65536,n+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else n+=String.fromCharCode(h)}g=n}}else g="";else g="boolean"===c?!!g:g;return g}(d);0!==a&&fa(a);return d}var ea="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0,ha,Q,P; -function ia(){var a=L.buffer;ha=a;b.HEAP8=Q=new Int8Array(a);b.HEAP16=new Int16Array(a);b.HEAP32=new Int32Array(a);b.HEAPU8=P=new Uint8Array(a);b.HEAPU16=new Uint16Array(a);b.HEAPU32=new Uint32Array(a);b.HEAPF32=new Float32Array(a);b.HEAPF64=new Float64Array(a)}var R,ja=[],ka=[],la=[];function ma(){var a=b.preRun.shift();ja.unshift(a)}var S=0,T=null,U=null;b.preloadedImages={};b.preloadedAudios={}; -function K(a){if(b.onAbort)b.onAbort(a);I(a);M=!0;a=new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");r(a);throw a;}var V="data:application/octet-stream;base64,",W;W="data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";if(!W.startsWith(V)){var na=W;W=b.locateFile?b.locateFile(na,B):B+na}function pa(){var a=W;try{if(a==W&&J)return new Uint8Array(J);var c=H(a);if(c)return c;if(E)return E(a);throw"both async and sync fetching of the wasm failed";}catch(d){K(d)}} -function qa(){if(!J&&(x||y)){if("function"===typeof fetch&&!W.startsWith("file://"))return fetch(W,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+W+"'";return a.arrayBuffer()}).catch(function(){return pa()});if(D)return new Promise(function(a,c){D(W,function(d){a(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return pa()})} -function X(a){for(;0>4;f=(f&15)<<4|l>>2;var t=(l&3)<<6|A;c+=String.fromCharCode(e);64!==l&&(c+=String.fromCharCode(f));64!==A&&(c+=String.fromCharCode(t))}while(d>>=0;if(2147483648=d;d*=2){var e=c*(1+.2/d);e=Math.min(e,a+100663296);e=Math.max(a,e);0>>16);ia();var f=1;break a}catch(l){}f=void 0}if(f)return!0}return!1}}; -(function(){function a(f){b.asm=f.exports;L=b.asm.b;ia();R=b.asm.j;ka.unshift(b.asm.c);S--;b.monitorRunDependencies&&b.monitorRunDependencies(S);0==S&&(null!==T&&(clearInterval(T),T=null),U&&(f=U,U=null,f()))}function c(f){a(f.instance)}function d(f){return qa().then(function(l){return WebAssembly.instantiate(l,e)}).then(f,function(l){I("failed to asynchronously prepare wasm: "+l);K(l)})}var e={a:sa};S++;b.monitorRunDependencies&&b.monitorRunDependencies(S);if(b.instantiateWasm)try{return b.instantiateWasm(e, -a)}catch(f){return I("Module.instantiateWasm callback failed with error: "+f),!1}(function(){return J||"function"!==typeof WebAssembly.instantiateStreaming||W.startsWith(V)||W.startsWith("file://")||"function"!==typeof fetch?d(c):fetch(W,{credentials:"same-origin"}).then(function(f){return WebAssembly.instantiateStreaming(f,e).then(c,function(l){I("wasm streaming compile failed: "+l);I("falling back to ArrayBuffer instantiation");return d(c)})})})().catch(r);return{}})(); -b.___wasm_call_ctors=function(){return(b.___wasm_call_ctors=b.asm.c).apply(null,arguments)};b._poly1305_auth=function(){return(b._poly1305_auth=b.asm.d).apply(null,arguments)};var da=b.stackSave=function(){return(da=b.stackSave=b.asm.e).apply(null,arguments)},fa=b.stackRestore=function(){return(fa=b.stackRestore=b.asm.f).apply(null,arguments)},O=b.stackAlloc=function(){return(O=b.stackAlloc=b.asm.g).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.h).apply(null,arguments)}; -b._free=function(){return(b._free=b.asm.i).apply(null,arguments)};b.cwrap=function(a,c,d,e){d=d||[];var f=d.every(function(l){return"number"===l});return"string"!==c&&f&&!e?N(a):function(){return ca(a,c,d,arguments)}};var Y;U=function ta(){Y||Z();Y||(U=ta)}; -function Z(){function a(){if(!Y&&(Y=!0,b.calledRun=!0,!M)){X(ka);q(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();la.unshift(c)}X(la)}}if(!(0 { - -"use strict"; - - -const MESSAGE_HANDLERS = new Array(256); -[ - (__nccwpck_require__(64126).HANDLERS), - __nccwpck_require__(6475), -].forEach((handlers) => { - // eslint-disable-next-line prefer-const - for (let [type, handler] of Object.entries(handlers)) { - type = +type; - if (isFinite(type) && type >= 0 && type < MESSAGE_HANDLERS.length) - MESSAGE_HANDLERS[type] = handler; - } -}); - -module.exports = MESSAGE_HANDLERS; - +class AuthUnknownError extends AuthError { + constructor(message, originalError) { + super(message); + this.name = 'AuthUnknownError'; + this.originalError = originalError; + } +} +exports.AuthUnknownError = AuthUnknownError; +class CustomAuthError extends AuthError { + constructor(message, name, status, code) { + super(message, status, code); + this.name = name; + this.status = status; + } +} +exports.CustomAuthError = CustomAuthError; +class AuthSessionMissingError extends CustomAuthError { + constructor() { + super('Auth session missing!', 'AuthSessionMissingError', 400, undefined); + } +} +exports.AuthSessionMissingError = AuthSessionMissingError; +function isAuthSessionMissingError(error) { + return isAuthError(error) && error.name === 'AuthSessionMissingError'; +} +class AuthInvalidTokenResponseError extends CustomAuthError { + constructor() { + super('Auth session or user missing', 'AuthInvalidTokenResponseError', 500, undefined); + } +} +exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError; +class AuthInvalidCredentialsError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidCredentialsError', 400, undefined); + } +} +exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError; +class AuthImplicitGrantRedirectError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthImplicitGrantRedirectError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError; +function isAuthImplicitGrantRedirectError(error) { + return isAuthError(error) && error.name === 'AuthImplicitGrantRedirectError'; +} +class AuthPKCEGrantCodeExchangeError extends CustomAuthError { + constructor(message, details = null) { + super(message, 'AuthPKCEGrantCodeExchangeError', 500, undefined); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details, + }; + } +} +exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError; +class AuthRetryableFetchError extends CustomAuthError { + constructor(message, status) { + super(message, 'AuthRetryableFetchError', status, undefined); + } +} +exports.AuthRetryableFetchError = AuthRetryableFetchError; +function isAuthRetryableFetchError(error) { + return isAuthError(error) && error.name === 'AuthRetryableFetchError'; +} +/** + * This error is thrown on certain methods when the password used is deemed + * weak. Inspect the reasons to identify what password strength rules are + * inadequate. + */ +class AuthWeakPasswordError extends CustomAuthError { + constructor(message, status, reasons) { + super(message, 'AuthWeakPasswordError', status, 'weak_password'); + this.reasons = reasons; + } +} +exports.AuthWeakPasswordError = AuthWeakPasswordError; +function isAuthWeakPasswordError(error) { + return isAuthError(error) && error.name === 'AuthWeakPasswordError'; +} +class AuthInvalidJwtError extends CustomAuthError { + constructor(message) { + super(message, 'AuthInvalidJwtError', 400, 'invalid_jwt'); + } +} +exports.AuthInvalidJwtError = AuthInvalidJwtError; +//# sourceMappingURL=errors.js.map /***/ }), -/***/ 6475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7072: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const { - bufferSlice, - bufferParser, - doFatalError, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const { - CHANNEL_OPEN_FAILURE, - COMPAT, - MESSAGE, - TERMINAL_MODE, -} = __nccwpck_require__(36832); - -const { - parseKey, -} = __nccwpck_require__(22218); - -const TERMINAL_MODE_BY_VALUE = - Array.from(Object.entries(TERMINAL_MODE)) - .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); - -module.exports = { - // Transport layer protocol ================================================== - [MESSAGE.DISCONNECT]: (self, payload) => { - /* - byte SSH_MSG_DISCONNECT - uint32 reason code - string description in ISO-10646 UTF-8 encoding - string language tag - */ - bufferParser.init(payload, 1); - const reason = bufferParser.readUInt32BE(); - const desc = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DISCONNECT packet' - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.handleError = handleError; +exports._request = _request; +exports._sessionResponse = _sessionResponse; +exports._sessionResponsePassword = _sessionResponsePassword; +exports._userResponse = _userResponse; +exports._ssoResponse = _ssoResponse; +exports._generateLinkResponse = _generateLinkResponse; +exports._noResolveJsonResponse = _noResolveJsonResponse; +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(518); +const helpers_1 = __nccwpck_require__(4044); +const errors_1 = __nccwpck_require__(9938); +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); +const NETWORK_ERROR_CODES = [502, 503, 504]; +async function handleError(error) { + var _a; + if (!(0, helpers_1.looksLikeFetchResponse)(error)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); } - - self._debug && self._debug( - `Inbound: Received DISCONNECT (${reason}, "${desc}")` - ); - - const handler = self._handlers.DISCONNECT; - handler && handler(self, reason, desc); - }, - [MESSAGE.IGNORE]: (self, payload) => { - /* - byte SSH_MSG_IGNORE - string data - */ - self._debug && self._debug('Inbound: Received IGNORE'); - }, - [MESSAGE.UNIMPLEMENTED]: (self, payload) => { - /* - byte SSH_MSG_UNIMPLEMENTED - uint32 packet sequence number of rejected message - */ - bufferParser.init(payload, 1); - const seqno = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (seqno === undefined) { - return doFatalError( - self, - 'Inbound: Malformed UNIMPLEMENTED packet' - ); + if (NETWORK_ERROR_CODES.includes(error.status)) { + // status in 500...599 range - server had an error, request might be retryed. + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); } - - self._debug - && self._debug(`Inbound: Received UNIMPLEMENTED (seqno ${seqno})`); - }, - [MESSAGE.DEBUG]: (self, payload) => { - /* - byte SSH_MSG_DEBUG - boolean always_display - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const display = bufferParser.readBool(); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed DEBUG packet' - ); + let data; + try { + data = await error.json(); } - - self._debug && self._debug('Inbound: Received DEBUG'); - - const handler = self._handlers.DEBUG; - handler && handler(self, display, msg); - }, - [MESSAGE.SERVICE_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_SERVICE_REQUEST - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_REQUEST packet' - ); + catch (e) { + throw new errors_1.AuthUnknownError(_getErrorMessage(e), e); } - - self._debug && self._debug(`Inbound: Received SERVICE_REQUEST (${name})`); - - const handler = self._handlers.SERVICE_REQUEST; - handler && handler(self, name); - }, - [MESSAGE.SERVICE_ACCEPT]: (self, payload) => { - // S->C - /* - byte SSH_MSG_SERVICE_ACCEPT - string service name - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - bufferParser.clear(); - - if (name === undefined) { - return doFatalError( - self, - 'Inbound: Malformed SERVICE_ACCEPT packet' - ); + let errorCode = undefined; + const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error); + if (responseAPIVersion && + responseAPIVersion.getTime() >= constants_1.API_VERSIONS['2024-01-01'].timestamp && + typeof data === 'object' && + data && + typeof data.code === 'string') { + errorCode = data.code; } - - self._debug && self._debug(`Inbound: Received SERVICE_ACCEPT (${name})`); - - const handler = self._handlers.SERVICE_ACCEPT; - handler && handler(self, name); - }, - [MESSAGE.EXT_INFO]: (self, payload) => { - /* - byte SSH_MSG_EXT_INFO - uint32 nr-extensions - repeat the following 2 fields "nr-extensions" times: - string extension-name - string extension-value (binary) - */ - bufferParser.init(payload, 1); - const numExts = bufferParser.readUInt32BE(); - let exts; - if (numExts !== undefined) { - exts = []; - for (let i = 0; i < numExts; ++i) { - const name = bufferParser.readString(true); - const data = bufferParser.readString(); - if (data !== undefined) { - switch (name) { - case 'server-sig-algs': { - const algs = data.latin1Slice(0, data.length).split(','); - exts.push({ name, algs }); - continue; - } - default: - continue; - } - } - // Malformed - exts = undefined; - break; - } + else if (typeof data === 'object' && data && typeof data.error_code === 'string') { + errorCode = data.error_code; } - bufferParser.clear(); - - if (exts === undefined) - return doFatalError(self, 'Inbound: Malformed EXT_INFO packet'); - - self._debug && self._debug('Inbound: Received EXT_INFO'); - - const handler = self._handlers.EXT_INFO; - handler && handler(self, exts); - }, - - // User auth protocol -- generic ============================================= - [MESSAGE.USERAUTH_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_USERAUTH_REQUEST - string user name in ISO-10646 UTF-8 encoding [RFC3629] - string service name in US-ASCII - string method name in US-ASCII - .... method specific fields - */ - bufferParser.init(payload, 1); - const user = bufferParser.readString(true); - const service = bufferParser.readString(true); - const method = bufferParser.readString(true); - let methodData; - let methodDesc; - switch (method) { - case 'none': - methodData = null; - break; - case 'password': { - /* - boolean - string plaintext password in ISO-10646 UTF-8 encoding [RFC3629] - [string new password] - */ - const isChange = bufferParser.readBool(); - if (isChange !== undefined) { - methodData = bufferParser.readString(true); - if (methodData !== undefined && isChange) { - const newPassword = bufferParser.readString(true); - if (newPassword !== undefined) - methodData = { oldPassword: methodData, newPassword }; - else - methodData = undefined; - } - } - break; - } - case 'publickey': { - /* - boolean - string public key algorithm name - string public key blob - [string signature] - */ - const hasSig = bufferParser.readBool(); - if (hasSig !== undefined) { - const keyAlgo = bufferParser.readString(true); - let realKeyAlgo = keyAlgo; - const key = bufferParser.readString(); - - let hashAlgo; - switch (keyAlgo) { - case 'rsa-sha2-256': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha256'; - break; - case 'rsa-sha2-512': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha512'; - break; - } - - if (hasSig) { - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, realKeyAlgo); - if (signature) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo: realKeyAlgo, - key, - signature, - blob, - hashAlgo, - }; - } - } - } else { - methodData = { keyAlgo: realKeyAlgo, key, hashAlgo }; - methodDesc = 'publickey -- check'; - } - } - break; - } - case 'hostbased': { - /* - string public key algorithm for host key - string public host key and certificates for client host - string client host name expressed as the FQDN in US-ASCII - string user name on the client host in ISO-10646 UTF-8 encoding - [RFC3629] - string signature - */ - const keyAlgo = bufferParser.readString(true); - let realKeyAlgo = keyAlgo; - const key = bufferParser.readString(); - const localHostname = bufferParser.readString(true); - const localUsername = bufferParser.readString(true); - - let hashAlgo; - switch (keyAlgo) { - case 'rsa-sha2-256': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha256'; - break; - case 'rsa-sha2-512': - realKeyAlgo = 'ssh-rsa'; - hashAlgo = 'sha512'; - break; - } - - const blobEnd = bufferParser.pos(); - let signature = bufferParser.readString(); - if (signature !== undefined) { - if (signature.length > (4 + keyAlgo.length + 4) - && signature.utf8Slice(4, 4 + keyAlgo.length) === keyAlgo) { - // Skip algoLen + algo + sigLen - signature = bufferSlice(signature, 4 + keyAlgo.length + 4); - } - - signature = sigSSHToASN1(signature, realKeyAlgo); - if (signature !== undefined) { - const sessionID = self._kex.sessionID; - const blob = Buffer.allocUnsafe(4 + sessionID.length + blobEnd); - writeUInt32BE(blob, sessionID.length, 0); - blob.set(sessionID, 4); - blob.set( - new Uint8Array(payload.buffer, payload.byteOffset, blobEnd), - 4 + sessionID.length - ); - methodData = { - keyAlgo: realKeyAlgo, - key, - signature, - blob, - localHostname, - localUsername, - hashAlgo - }; - } + if (!errorCode) { + // Legacy support for weak password errors, when there were no error codes + if (typeof data === 'object' && + data && + typeof data.weak_password === 'object' && + data.weak_password && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); } - break; - } - case 'keyboard-interactive': - /* - string language tag (as defined in [RFC-3066]) - string submethods (ISO-10646 UTF-8) - */ - // Skip/ignore language field -- it's deprecated in RFC 4256 - bufferParser.skipString(); - - methodData = bufferParser.readList(); - break; - default: - if (method !== undefined) - methodData = bufferParser.readRaw(); } - bufferParser.clear(); - - if (methodData === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_REQUEST packet' - ); + else if (errorCode === 'weak_password') { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); + } + else if (errorCode === 'session_not_found') { + // The `session_id` inside the JWT does not correspond to a row in the + // `sessions` table. This usually means the user has signed out, has been + // deleted, or their session has somehow been terminated. + throw new errors_1.AuthSessionMissingError(); + } + throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); +} +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET') { + return params; + } + params.headers = Object.assign({ 'Content-Type': 'application/json;charset=UTF-8' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); +}; +async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (!headers[constants_1.API_VERSION_HEADER_NAME]) { + headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS['2024-01-01'].name; } - - if (methodDesc === undefined) - methodDesc = method; - - self._authsQueue.push(method); - - self._debug - && self._debug(`Inbound: Received USERAUTH_REQUEST (${methodDesc})`); - - const handler = self._handlers.USERAUTH_REQUEST; - handler && handler(self, user, service, method, methodData); - }, - [MESSAGE.USERAUTH_FAILURE]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_FAILURE - name-list authentications that can continue - boolean partial success - */ - bufferParser.init(payload, 1); - const authMethods = bufferParser.readList(); - const partialSuccess = bufferParser.readBool(); - bufferParser.clear(); - - if (partialSuccess === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_FAILURE packet' - ); + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers['Authorization'] = `Bearer ${options.jwt}`; } - - self._debug - && self._debug(`Inbound: Received USERAUTH_FAILURE (${authMethods})`); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_FAILURE; - handler && handler(self, authMethods, partialSuccess); - }, - [MESSAGE.USERAUTH_SUCCESS]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_SUCCESS - */ - self._debug && self._debug('Inbound: Received USERAUTH_SUCCESS'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_SUCCESS; - handler && handler(self); - }, - [MESSAGE.USERAUTH_BANNER]: (self, payload) => { - // S->C - /* - byte SSH_MSG_USERAUTH_BANNER - string message in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const msg = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_BANNER packet' - ); + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs['redirect_to'] = options.redirectTo; } - - self._debug && self._debug('Inbound: Received USERAUTH_BANNER'); - - const handler = self._handlers.USERAUTH_BANNER; - handler && handler(self, msg); - }, - - // User auth protocol -- method-specific ===================================== - 60: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 60 without auth'); - return; + const queryString = Object.keys(qs).length ? '?' + new URLSearchParams(qs).toString() : ''; + const data = await _handleRequest(fetcher, method, url + queryString, { + headers, + noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson, + }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; +} +async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, Object.assign({}, requestParams)); } - - switch (self._authsQueue[0]) { - case 'password': { - // S->C - /* - byte SSH_MSG_USERAUTH_PASSWD_CHANGEREQ - string prompt in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const prompt = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet' - ); - } - - self._debug - && self._debug('Inbound: Received USERAUTH_PASSWD_CHANGEREQ'); - - const handler = self._handlers.USERAUTH_PASSWD_CHANGEREQ; - handler && handler(self, prompt); - break; - } - case 'publickey': { - // S->C - /* - byte SSH_MSG_USERAUTH_PK_OK - string public key algorithm name from the request - string public key blob from the request - */ - bufferParser.init(payload, 1); - const keyAlgo = bufferParser.readString(true); - const key = bufferParser.readString(); - bufferParser.clear(); - - if (key === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_PK_OK packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_PK_OK'); - - self._authsQueue.shift(); - const handler = self._handlers.USERAUTH_PK_OK; - handler && handler(self, keyAlgo, key); - break; - } - case 'keyboard-interactive': { - // S->C - /* - byte SSH_MSG_USERAUTH_INFO_REQUEST - string name (ISO-10646 UTF-8) - string instruction (ISO-10646 UTF-8) - string language tag (as defined in [RFC-3066]) - int num-prompts - string prompt[1] (ISO-10646 UTF-8) - boolean echo[1] - ... - string prompt[num-prompts] (ISO-10646 UTF-8) - boolean echo[num-prompts] - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const instructions = bufferParser.readString(true); - bufferParser.readString(); // skip lang - const numPrompts = bufferParser.readUInt32BE(); - let prompts; - if (numPrompts !== undefined) { - prompts = new Array(numPrompts); - let i; - for (i = 0; i < numPrompts; ++i) { - const prompt = bufferParser.readString(true); - const echo = bufferParser.readBool(); - if (echo === undefined) - break; - prompts[i] = { prompt, echo }; - } - if (i !== numPrompts) - prompts = undefined; - } - bufferParser.clear(); - - if (prompts === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_REQUEST packet' - ); - } - - self._debug && self._debug('Inbound: Received USERAUTH_INFO_REQUEST'); - - const handler = self._handlers.USERAUTH_INFO_REQUEST; - handler && handler(self, name, instructions, prompts); - break; - } - default: - self._debug - && self._debug('Inbound: Received unexpected payload type 60'); + catch (e) { + console.error(e); + // fetch failed, likely due to a network or CORS error + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e), 0); } - }, - 61: (self, payload) => { - if (!self._authsQueue.length) { - self._debug - && self._debug('Inbound: Received payload type 61 without auth'); - return; + if (!result.ok) { + await handleError(result); } - /* - byte SSH_MSG_USERAUTH_INFO_RESPONSE - int num-responses - string response[1] (ISO-10646 UTF-8) - ... - string response[num-responses] (ISO-10646 UTF-8) - */ - if (self._authsQueue[0] !== 'keyboard-interactive') { - return doFatalError( - self, - 'Inbound: Received unexpected payload type 61' - ); + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; } - bufferParser.init(payload, 1); - const numResponses = bufferParser.readUInt32BE(); - let responses; - if (numResponses !== undefined) { - responses = new Array(numResponses); - let i; - for (i = 0; i < numResponses; ++i) { - const response = bufferParser.readString(true); - if (response === undefined) - break; - responses[i] = response; - } - if (i !== numResponses) - responses = undefined; + try { + return await result.json(); } - bufferParser.clear(); - - if (responses === undefined) { - return doFatalError( - self, - 'Inbound: Malformed USERAUTH_INFO_RESPONSE packet' - ); + catch (e) { + await handleError(e); } - - self._debug && self._debug('Inbound: Received USERAUTH_INFO_RESPONSE'); - - const handler = self._handlers.USERAUTH_INFO_RESPONSE; - handler && handler(self, responses); - }, - - // Connection protocol -- generic ============================================ - [MESSAGE.GLOBAL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_GLOBAL_REQUEST - string request name in US-ASCII only - boolean want reply - .... request-specific data follows - */ - bufferParser.init(payload, 1); - const name = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (name) { - case 'tcpip-forward': - case 'cancel-tcpip-forward': { - /* - string address to bind (e.g., "0.0.0.0") - uint32 port number to bind - */ - const bindAddr = bufferParser.readString(true); - const bindPort = bufferParser.readUInt32BE(); - if (bindPort !== undefined) - data = { bindAddr, bindPort }; - break; - } - case 'streamlocal-forward@openssh.com': - case 'cancel-streamlocal-forward@openssh.com': { - /* - string socket path - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) - data = { socketPath }; - break; - } - case 'no-more-sessions@openssh.com': - data = null; - break; - case 'hostkeys-00@openssh.com': { - data = []; - while (bufferParser.avail() > 0) { - const keyRaw = bufferParser.readString(); - if (keyRaw === undefined) { - data = undefined; - break; - } - const key = parseKey(keyRaw); - if (!(key instanceof Error)) - data.push(key); - } - break; +} +function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + if (!data.expires_at) { + session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); } - default: - data = bufferParser.readRaw(); - } } - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed GLOBAL_REQUEST packet' - ); + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; +} +function _sessionResponsePassword(data) { + const response = _sessionResponse(data); + if (!response.error && + data.weak_password && + typeof data.weak_password === 'object' && + Array.isArray(data.weak_password.reasons) && + data.weak_password.reasons.length && + data.weak_password.message && + typeof data.weak_password.message === 'string' && + data.weak_password.reasons.reduce((a, i) => a && typeof i === 'string', true)) { + response.data.weak_password = data.weak_password; } + return response; +} +function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; +} +function _ssoResponse(data) { + return { data, error: null }; +} +function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type, + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user, + }, + error: null, + }; +} +function _noResolveJsonResponse(data) { + return data; +} +/** + * hasSession checks if the response object contains a valid session + * @param data A response object + * @returns true if a session is in the response + */ +function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; +} +//# sourceMappingURL=fetch.js.map - self._debug && self._debug(`Inbound: GLOBAL_REQUEST (${name})`); - - const handler = self._handlers.GLOBAL_REQUEST; - if (handler) - handler(self, name, wantReply, data); - else - self.requestFailure(); // Auto reject - }, - [MESSAGE.REQUEST_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_SUCCESS - .... response specific data - */ - const data = (payload.length > 1 ? bufferSlice(payload, 1) : null); - - self._debug && self._debug('Inbound: REQUEST_SUCCESS'); - - const handler = self._handlers.REQUEST_SUCCESS; - handler && handler(self, data); - }, - [MESSAGE.REQUEST_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_REQUEST_FAILURE - */ - self._debug && self._debug('Inbound: Received REQUEST_FAILURE'); +/***/ }), - const handler = self._handlers.REQUEST_FAILURE; - handler && handler(self); - }, +/***/ 4044: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Connection protocol -- channel-related ==================================== - [MESSAGE.CHANNEL_OPEN]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN - string channel type in US-ASCII only - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - bufferParser.init(payload, 1); - const type = bufferParser.readString(true); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - let channelInfo; +"use strict"; - switch (type) { - case 'forwarded-tcpip': // S->C - case 'direct-tcpip': { // C->S - /* - string address that was connected / host to connect - uint32 port that was connected / port to connect - string originator IP address - uint32 originator port - */ - const destIP = bufferParser.readString(true); - const destPort = bufferParser.readUInt32BE(); - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { destIP, destPort, srcIP, srcPort } - }; - } - break; - } - case 'forwarded-streamlocal@openssh.com': // S->C - case 'direct-streamlocal@openssh.com': { // C->S - /* - string socket path - string reserved for future use - - (direct-streamlocal@openssh.com additionally has:) - uint32 reserved - */ - const socketPath = bufferParser.readString(true); - if (socketPath !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { socketPath } - }; - } - break; - } - case 'x11': { // S->C - /* - string originator address (e.g., "192.168.7.38") - uint32 originator port - */ - const srcIP = bufferParser.readString(true); - const srcPort = bufferParser.readUInt32BE(); - if (srcPort !== undefined) { - channelInfo = { - type, - sender, - window, - packetSize, - data: { srcIP, srcPort } - }; - } - break; - } - default: - // Includes: - // 'session' (C->S) - // 'auth-agent@openssh.com' (S->C) - channelInfo = { - type, - sender, - window, - packetSize, - data: {} - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0; +exports.expiresAt = expiresAt; +exports.uuid = uuid; +exports.parseParametersFromURL = parseParametersFromURL; +exports.decodeJWT = decodeJWT; +exports.sleep = sleep; +exports.retryable = retryable; +exports.generatePKCEVerifier = generatePKCEVerifier; +exports.generatePKCEChallenge = generatePKCEChallenge; +exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod; +exports.parseResponseAPIVersion = parseResponseAPIVersion; +exports.validateExp = validateExp; +exports.getAlgorithm = getAlgorithm; +exports.validateUUID = validateUUID; +exports.userNotAvailableProxy = userNotAvailableProxy; +exports.insecureUserWarningProxy = insecureUserWarningProxy; +exports.deepClone = deepClone; +const constants_1 = __nccwpck_require__(518); +const errors_1 = __nccwpck_require__(9938); +const base64url_1 = __nccwpck_require__(3649); +function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1000); + return timeNow + expiresIn; +} +function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +const isBrowser = () => typeof window !== 'undefined' && typeof document !== 'undefined'; +exports.isBrowser = isBrowser; +const localStorageWriteTests = { + tested: false, + writable: false, +}; +/** + * Checks whether localStorage is supported on this browser. + */ +const supportsLocalStorage = () => { + if (!(0, exports.isBrowser)()) { + return false; } - bufferParser.clear(); - - if (channelInfo === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN packet' - ); + try { + if (typeof globalThis.localStorage !== 'object') { + return false; + } } - - self._debug && self._debug(`Inbound: CHANNEL_OPEN (s:${sender}, ${type})`); - - const handler = self._handlers.CHANNEL_OPEN; - if (handler) { - handler(self, channelInfo); - } else { - self.channelOpenFail( - channelInfo.sender, - CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED, - '', - '' - ); + catch (e) { + // DOM exception when accessing `localStorage` + return false; } - }, - [MESSAGE.CHANNEL_OPEN_CONFIRMATION]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_CONFIRMATION - uint32 recipient channel - uint32 sender channel - uint32 initial window size - uint32 maximum packet size - .... channel type specific data follows - */ - // "The 'recipient channel' is the channel number given in the - // original open request, and 'sender channel' is the channel number - // allocated by the other side." - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const sender = bufferParser.readUInt32BE(); - const window = bufferParser.readUInt32BE(); - const packetSize = bufferParser.readUInt32BE(); - const data = (bufferParser.avail() ? bufferParser.readRaw() : undefined); - bufferParser.clear(); - - if (packetSize === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet' - ); + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; } - - self._debug && self._debug( - `Inbound: CHANNEL_OPEN_CONFIRMATION (r:${recipient}, s:${sender})` - ); - - const handler = self._handlers.CHANNEL_OPEN_CONFIRMATION; - if (handler) - handler(self, { recipient, sender, window, packetSize, data }); - }, - [MESSAGE.CHANNEL_OPEN_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_OPEN_FAILURE - uint32 recipient channel - uint32 reason code - string description in ISO-10646 UTF-8 encoding [RFC3629] - string language tag [RFC3066] - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const reason = bufferParser.readUInt32BE(); - const description = bufferParser.readString(true); - const lang = bufferParser.readString(); - bufferParser.clear(); - - if (lang === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_OPEN_FAILURE packet' - ); + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; } - - self._debug - && self._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_OPEN_FAILURE; - handler && handler(self, recipient, reason, description); - }, - [MESSAGE.CHANNEL_WINDOW_ADJUST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_WINDOW_ADJUST - uint32 recipient channel - uint32 bytes to add - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const bytesToAdd = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (bytesToAdd === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_WINDOW_ADJUST packet' - ); + catch (e) { + // localStorage can't be written to + // https://www.chromium.org/for-testers/bug-reporting-guidelines/uncaught-securityerror-failed-to-read-the-localstorage-property-from-window-access-is-denied-for-this-document + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; } - - self._debug && self._debug( - `Inbound: CHANNEL_WINDOW_ADJUST (r:${recipient}, ${bytesToAdd})` - ); - - const handler = self._handlers.CHANNEL_WINDOW_ADJUST; - handler && handler(self, recipient, bytesToAdd); - }, - [MESSAGE.CHANNEL_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_DATA - uint32 recipient channel - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_DATA packet' - ); + return localStorageWriteTests.writable; +}; +exports.supportsLocalStorage = supportsLocalStorage; +/** + * Extracts parameters encoded in the URL both in the query and fragment. + */ +function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === '#') { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } + catch (e) { + // hash is not a query string + } } - - self._debug - && self._debug(`Inbound: CHANNEL_DATA (r:${recipient}, ${data.length})`); - - const handler = self._handlers.CHANNEL_DATA; - handler && handler(self, recipient, data); - }, - [MESSAGE.CHANNEL_EXTENDED_DATA]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EXTENDED_DATA - uint32 recipient channel - uint32 data_type_code - string data - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readUInt32BE(); - const data = bufferParser.readString(); - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EXTENDED_DATA packet' - ); + // search parameters take precedence over hash parameters + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; +} +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); } - - self._debug && self._debug( - `Inbound: CHANNEL_EXTENDED_DATA (r:${recipient}, ${data.length})` - ); - - const handler = self._handlers.CHANNEL_EXTENDED_DATA; - handler && handler(self, recipient, data, type); - }, - [MESSAGE.CHANNEL_EOF]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_EOF - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_EOF packet' - ); + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const looksLikeFetchResponse = (maybeResponse) => { + return (typeof maybeResponse === 'object' && + maybeResponse !== null && + 'status' in maybeResponse && + 'ok' in maybeResponse && + 'json' in maybeResponse && + typeof maybeResponse.json === 'function'); +}; +exports.looksLikeFetchResponse = looksLikeFetchResponse; +// Storage helpers +const setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); +}; +exports.setItemAsync = setItemAsync; +const getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; } - - self._debug && self._debug(`Inbound: CHANNEL_EOF (r:${recipient})`); - - const handler = self._handlers.CHANNEL_EOF; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_CLOSE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_CLOSE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_CLOSE packet' - ); + try { + return JSON.parse(value); } - - self._debug && self._debug(`Inbound: CHANNEL_CLOSE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_CLOSE; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_REQUEST]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_REQUEST - uint32 recipient channel - string request type in US-ASCII characters only - boolean want reply - .... type-specific data follows - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - const type = bufferParser.readString(true); - const wantReply = bufferParser.readBool(); - let data; - if (wantReply !== undefined) { - switch (type) { - case 'exit-status': // S->C - /* - uint32 exit_status - */ - data = bufferParser.readUInt32BE(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'exit-signal': { // S->C - /* - string signal name (without the "SIG" prefix) - boolean core dumped - string error message in ISO-10646 UTF-8 encoding - string language tag - */ - let signal; - let coreDumped; - if (self._compatFlags & COMPAT.OLD_EXIT) { - /* - Instead of `signal name` and `core dumped`, we have just: - uint32 signal number - */ - const num = bufferParser.readUInt32BE(); - switch (num) { - case 1: - signal = 'HUP'; - break; - case 2: - signal = 'INT'; - break; - case 3: - signal = 'QUIT'; - break; - case 6: - signal = 'ABRT'; - break; - case 9: - signal = 'KILL'; - break; - case 14: - signal = 'ALRM'; - break; - case 15: - signal = 'TERM'; - break; - default: - if (num !== undefined) { - // Unknown or OS-specific - signal = `UNKNOWN (${num})`; - } - } - coreDumped = false; - } else { - signal = bufferParser.readString(true); - coreDumped = bufferParser.readBool(); - if (coreDumped === undefined) - signal = undefined; - } - const errorMessage = bufferParser.readString(true); - if (bufferParser.skipString() !== undefined) - data = { signal, coreDumped, errorMessage }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${signal})` - ); - break; - } - case 'pty-req': { // C->S - /* - string TERM environment variable value (e.g., vt100) - uint32 terminal width, characters (e.g., 80) - uint32 terminal height, rows (e.g., 24) - uint32 terminal width, pixels (e.g., 640) - uint32 terminal height, pixels (e.g., 480) - string encoded terminal modes - */ - const term = bufferParser.readString(true); - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - const modesBinary = bufferParser.readString(); - if (modesBinary !== undefined) { - bufferParser.init(modesBinary, 1); - let modes = {}; - while (bufferParser.avail()) { - const opcode = bufferParser.readByte(); - if (opcode === TERMINAL_MODE.TTY_OP_END) - break; - const name = TERMINAL_MODE_BY_VALUE[opcode]; - const value = bufferParser.readUInt32BE(); - if (opcode === undefined - || name === undefined - || value === undefined) { - modes = undefined; - break; - } - modes[name] = value; - } - if (modes !== undefined) - data = { term, cols, rows, width, height, modes }; - } - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'window-change': { // C->S - /* - uint32 terminal width, columns - uint32 terminal height, rows - uint32 terminal width, pixels - uint32 terminal height, pixels - */ - const cols = bufferParser.readUInt32BE(); - const rows = bufferParser.readUInt32BE(); - const width = bufferParser.readUInt32BE(); - const height = bufferParser.readUInt32BE(); - if (height !== undefined) - data = { cols, rows, width, height }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'x11-req': { // C->S - /* - boolean single connection - string x11 authentication protocol - string x11 authentication cookie - uint32 x11 screen number - */ - const single = bufferParser.readBool(); - const protocol = bufferParser.readString(true); - const cookie = bufferParser.readString(); - const screen = bufferParser.readUInt32BE(); - if (screen !== undefined) - data = { single, protocol, cookie, screen }; - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - } - case 'env': { // C->S - /* - string variable name - string variable value - */ - const name = bufferParser.readString(true); - const value = bufferParser.readString(true); - if (value !== undefined) - data = { name, value }; - if (self._debug) { - self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ` - + `${name}=${value})` - ); - } - break; - } - case 'shell': // C->S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - case 'exec': // C->S - /* - string command - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'subsystem': // C->S - /* - string subsystem name - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'signal': // C->S - /* - string signal name (without the "SIG" prefix) - */ - data = bufferParser.readString(true); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'xon-xoff': // C->S - /* - boolean client can do - */ - data = bufferParser.readBool(); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type}: ${data})` - ); - break; - case 'auth-agent-req@openssh.com': // C-S - data = null; // No extra data - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - break; - default: - data = (bufferParser.avail() ? bufferParser.readRaw() : null); - self._debug && self._debug( - `Inbound: CHANNEL_REQUEST (r:${recipient}, ${type})` - ); - } + catch (_a) { + return value; } - bufferParser.clear(); - - if (data === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_REQUEST packet' - ); +}; +exports.getItemAsync = getItemAsync; +const removeItemAsync = async (storage, key) => { + await storage.removeItem(key); +}; +exports.removeItemAsync = removeItemAsync; +/** + * A deferred represents some asynchronous work that is not yet finished, which + * may or may not culminate in a value. + * Taken from: https://github.com/mike-north/types/blob/master/src/async.ts + */ +class Deferred { + constructor() { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.promise = new Deferred.promiseConstructor((res, rej) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + this.resolve = res; + this.reject = rej; + }); } - - const handler = self._handlers.CHANNEL_REQUEST; - handler && handler(self, recipient, type, wantReply, data); - }, - [MESSAGE.CHANNEL_SUCCESS]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_SUCCESS - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_SUCCESS packet' - ); +} +exports.Deferred = Deferred; +Deferred.promiseConstructor = Promise; +function decodeJWT(token) { + const parts = token.split('.'); + if (parts.length !== 3) { + throw new errors_1.AuthInvalidJwtError('Invalid JWT structure'); } - - self._debug && self._debug(`Inbound: CHANNEL_SUCCESS (r:${recipient})`); - - const handler = self._handlers.CHANNEL_SUCCESS; - handler && handler(self, recipient); - }, - [MESSAGE.CHANNEL_FAILURE]: (self, payload) => { - /* - byte SSH_MSG_CHANNEL_FAILURE - uint32 recipient channel - */ - bufferParser.init(payload, 1); - const recipient = bufferParser.readUInt32BE(); - bufferParser.clear(); - - if (recipient === undefined) { - return doFatalError( - self, - 'Inbound: Malformed CHANNEL_FAILURE packet' - ); + // Regex checks for base64url format + for (let i = 0; i < parts.length; i++) { + if (!constants_1.BASE64URL_REGEX.test(parts[i])) { + throw new errors_1.AuthInvalidJwtError('JWT not in base64url format'); + } } - - self._debug && self._debug(`Inbound: CHANNEL_FAILURE (r:${recipient})`); - - const handler = self._handlers.CHANNEL_FAILURE; - handler && handler(self, recipient); - }, -}; - - -/***/ }), - -/***/ 64126: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { - createDiffieHellman, - createDiffieHellmanGroup, - createECDH, - createHash, - createPublicKey, - diffieHellman, - generateKeyPairSync, - randomFillSync, -} = __nccwpck_require__(6113); - -const { Ber } = __nccwpck_require__(80970); - -const { - COMPAT, - curve25519Supported, - DEFAULT_KEX, - DEFAULT_SERVER_HOST_KEY, - DEFAULT_CIPHER, - DEFAULT_MAC, - DEFAULT_COMPRESSION, - DISCONNECT_REASON, - MESSAGE, -} = __nccwpck_require__(36832); -const { - CIPHER_INFO, - createCipher, - createDecipher, - MAC_INFO, -} = __nccwpck_require__(45708); -const { parseDERKey } = __nccwpck_require__(22218); -const { - bufferFill, - bufferParser, - convertSignature, - doFatalError, - FastBuffer, - sigSSHToASN1, - writeUInt32BE, -} = __nccwpck_require__(49475); -const { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -} = __nccwpck_require__(26715); - -let MESSAGE_HANDLERS; - -const GEX_MIN_BITS = 2048; // RFC 8270 -const GEX_MAX_BITS = 8192; // RFC 8270 - -const EMPTY_BUFFER = Buffer.alloc(0); - -// Client/Server -function kexinit(self) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - - let payload; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - const entry = self._offer.lists.kex; - let kex = entry.array; - let found = false; - for (let i = 0; i < kex.length; ++i) { - if (kex[i].includes('group-exchange')) { - if (!found) { - found = true; - // Copy array lazily - kex = kex.slice(); - } - kex.splice(i--, 1); - } + const data = { + // using base64url lib + header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])), + payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])), + signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]), + raw: { + header: parts[0], + payload: parts[1], + }, + }; + return data; +} +/** + * Creates a promise that resolves to null after some time. + */ +async function sleep(time) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time); + }); +} +/** + * Converts the provided async function into a retryable function. Each result + * or thrown error is sent to the isRetryable function which should return true + * if the function should run again. + */ +function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + // eslint-disable-next-line @typescript-eslint/no-extra-semi + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } + catch (e) { + if (!isRetryable(attempt, e)) { + reject(e); + return; + } + } + } + })(); + }); + return promise; +} +function dec2hex(dec) { + return ('0' + dec.toString(16)).substr(-2); +} +// Functions below taken from: https://stackoverflow.com/questions/63309409/creating-a-code-verifier-and-challenge-for-pkce-auth-on-spotify-api-in-reactjs +function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === 'undefined') { + const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'; + const charSetLen = charSet.length; + let verifier = ''; + for (let i = 0; i < verifierLength; i++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; } - if (found) { - let len = 1 + 16 + self._offer.totalSize + 1 + 4; - const newKexBuf = Buffer.from(kex.join(',')); - len -= (entry.buffer.length - newKexBuf.length); - - const all = self._offer.lists.all; - const rest = new Uint8Array( - all.buffer, - all.byteOffset + 4 + entry.buffer.length, - all.length - (4 + entry.buffer.length) - ); - - payload = Buffer.allocUnsafe(len); - writeUInt32BE(payload, newKexBuf.length, 17); - payload.set(newKexBuf, 17 + 4); - payload.set(rest, 17 + 4 + newKexBuf.length); + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(''); +} +async function sha256(randomString) { + const encoder = new TextEncoder(); + const encodedData = encoder.encode(randomString); + const hash = await crypto.subtle.digest('SHA-256', encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes) + .map((c) => String.fromCharCode(c)) + .join(''); +} +async function generatePKCEChallenge(verifier) { + const hasCryptoSupport = typeof crypto !== 'undefined' && + typeof crypto.subtle !== 'undefined' && + typeof TextEncoder !== 'undefined'; + if (!hasCryptoSupport) { + console.warn('WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.'); + return verifier; } - } - - if (payload === undefined) { - payload = Buffer.allocUnsafe(1 + 16 + self._offer.totalSize + 1 + 4); - self._offer.copyAllTo(payload, 17); - } - - self._debug && self._debug('Outbound: Sending KEXINIT'); - - payload[0] = MESSAGE.KEXINIT; - randomFillSync(payload, 1, 16); - - // Zero-fill first_kex_packet_follows and reserved bytes - bufferFill(payload, 0, payload.length - 5); - - self._kexinit = payload; - - // Needed to correct the starting position in allocated "packets" when packets - // will be buffered due to active key exchange - self._packetRW.write.allocStart = 0; - - // TODO: only create single buffer and set _kexinit as slice of packet instead - { - const p = self._packetRW.write.allocStartKEX; - const packet = self._packetRW.write.alloc(payload.length, true); - packet.set(payload, p); - self._cipher.encrypt(self._packetRW.write.finalize(packet, true)); - } -} - -function handleKexInit(self, payload) { - /* - byte SSH_MSG_KEXINIT - byte[16] cookie (random bytes) - name-list kex_algorithms - name-list server_host_key_algorithms - name-list encryption_algorithms_client_to_server - name-list encryption_algorithms_server_to_client - name-list mac_algorithms_client_to_server - name-list mac_algorithms_server_to_client - name-list compression_algorithms_client_to_server - name-list compression_algorithms_server_to_client - name-list languages_client_to_server - name-list languages_server_to_client - boolean first_kex_packet_follows - uint32 0 (reserved for future extension) - */ - const init = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - }; - - bufferParser.init(payload, 17); - - if ((init.kex = bufferParser.readList()) === undefined - || (init.serverHostKey = bufferParser.readList()) === undefined - || (init.cs.cipher = bufferParser.readList()) === undefined - || (init.sc.cipher = bufferParser.readList()) === undefined - || (init.cs.mac = bufferParser.readList()) === undefined - || (init.sc.mac = bufferParser.readList()) === undefined - || (init.cs.compress = bufferParser.readList()) === undefined - || (init.sc.compress = bufferParser.readList()) === undefined - || (init.cs.lang = bufferParser.readList()) === undefined - || (init.sc.lang = bufferParser.readList()) === undefined) { - bufferParser.clear(); - return doFatalError( - self, - 'Received malformed KEXINIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const pos = bufferParser.pos(); - const firstFollows = (pos < payload.length && payload[pos] === 1); - bufferParser.clear(); - - const local = self._offer; - const remote = init; - - let localKex = local.lists.kex.array; - if (self._compatFlags & COMPAT.BAD_DHGEX) { - let found = false; - for (let i = 0; i < localKex.length; ++i) { - if (localKex[i].indexOf('group-exchange') !== -1) { - if (!found) { - found = true; - // Copy array lazily - localKex = localKex.slice(); - } - localKex.splice(i--, 1); - } + const hashed = await sha256(verifier); + return btoa(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} +async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { + const codeVerifier = generatePKCEVerifier(); + let storedCodeVerifier = codeVerifier; + if (isPasswordRecovery) { + storedCodeVerifier += '/PASSWORD_RECOVERY'; } - } - - let clientList; - let serverList; - let i; - const debug = self._debug; - - debug && debug('Inbound: Handshake in progress'); - - // Key exchange method ======================================================= - debug && debug(`Handshake: (local) KEX method: ${localKex}`); - debug && debug(`Handshake: (remote) KEX method: ${remote.kex}`); - let remoteExtInfoEnabled; - if (self._server) { - serverList = localKex; - clientList = remote.kex; - remoteExtInfoEnabled = (clientList.indexOf('ext-info-c') !== -1); - } else { - serverList = remote.kex; - clientList = localKex; - remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1); - } - if (self._strictMode === undefined) { - if (self._server) { - self._strictMode = - (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1); - } else { - self._strictMode = - (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1); - } - // Note: We check for seqno of 1 instead of 0 since we increment before - // calling the packet handler - if (self._strictMode) { - debug && debug('Handshake: strict KEX mode enabled'); - if (self._decipher.inSeqno !== 1) { - if (debug) - debug('Handshake: KEXINIT not first packet in strict KEX mode'); - return doFatalError( - self, - 'Handshake failed: KEXINIT not first packet in strict KEX mode', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } + await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? 'plain' : 's256'; + return [codeChallenge, codeChallengeMethod]; +} +/** Parses the API version which is 2YYY-MM-DD. */ +const API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; +function parseResponseAPIVersion(response) { + const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME); + if (!apiVersion) { + return null; } - } - // Check for agreeable key exchange algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: no matching key exchange algorithm'); - return doFatalError( - self, - 'Handshake failed: no matching key exchange algorithm', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.kex = clientList[i]; - debug && debug(`Handshake: KEX algorithm: ${clientList[i]}`); - if (firstFollows && (!remote.kex.length || clientList[i] !== remote.kex[0])) { - // Ignore next inbound packet, it was a wrong first guess at KEX algorithm - self._skipNextInboundPacket = true; - } - - - // Server host key format ==================================================== - const localSrvHostKey = local.lists.serverHostKey.array; - debug && debug(`Handshake: (local) Host key format: ${localSrvHostKey}`); - debug && debug( - `Handshake: (remote) Host key format: ${remote.serverHostKey}` - ); - if (self._server) { - serverList = localSrvHostKey; - clientList = remote.serverHostKey; - } else { - serverList = remote.serverHostKey; - clientList = localSrvHostKey; - } - // Check for agreeable server host key format - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching host key format'); - return doFatalError( - self, - 'Handshake failed: no matching host key format', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.serverHostKey = clientList[i]; - debug && debug(`Handshake: Host key format: ${clientList[i]}`); - - - // Client->Server cipher ===================================================== - const localCSCipher = local.lists.cs.cipher.array; - debug && debug(`Handshake: (local) C->S cipher: ${localCSCipher}`); - debug && debug(`Handshake: (remote) C->S cipher: ${remote.cs.cipher}`); - if (self._server) { - serverList = localCSCipher; - clientList = remote.cs.cipher; - } else { - serverList = remote.cs.cipher; - clientList = localCSCipher; - } - // Check for agreeable client->server cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S cipher'); - return doFatalError( - self, - 'Handshake failed: no matching C->S cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.cipher = clientList[i]; - debug && debug(`Handshake: C->S Cipher: ${clientList[i]}`); - - - // Server->Client cipher ===================================================== - const localSCCipher = local.lists.sc.cipher.array; - debug && debug(`Handshake: (local) S->C cipher: ${localSCCipher}`); - debug && debug(`Handshake: (remote) S->C cipher: ${remote.sc.cipher}`); - if (self._server) { - serverList = localSCCipher; - clientList = remote.sc.cipher; - } else { - serverList = remote.sc.cipher; - clientList = localSCCipher; - } - // Check for agreeable server->client cipher - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C cipher'); - return doFatalError( - self, - 'Handshake failed: no matching S->C cipher', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.cipher = clientList[i]; - debug && debug(`Handshake: S->C cipher: ${clientList[i]}`); - - - // Client->Server MAC ======================================================== - const localCSMAC = local.lists.cs.mac.array; - debug && debug(`Handshake: (local) C->S MAC: ${localCSMAC}`); - debug && debug(`Handshake: (remote) C->S MAC: ${remote.cs.mac}`); - if (CIPHER_INFO[init.cs.cipher].authLen > 0) { - init.cs.mac = ''; - debug && debug('Handshake: C->S MAC: '); - } else { - if (self._server) { - serverList = localCSMAC; - clientList = remote.cs.mac; - } else { - serverList = remote.cs.mac; - clientList = localCSMAC; - } - // Check for agreeable client->server hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S MAC'); - return doFatalError( - self, - 'Handshake failed: no matching C->S MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + if (!apiVersion.match(API_VERSION_REGEX)) { + return null; } - init.cs.mac = clientList[i]; - debug && debug(`Handshake: C->S MAC: ${clientList[i]}`); - } - - - // Server->Client MAC ======================================================== - const localSCMAC = local.lists.sc.mac.array; - debug && debug(`Handshake: (local) S->C MAC: ${localSCMAC}`); - debug && debug(`Handshake: (remote) S->C MAC: ${remote.sc.mac}`); - if (CIPHER_INFO[init.sc.cipher].authLen > 0) { - init.sc.mac = ''; - debug && debug('Handshake: S->C MAC: '); - } else { - if (self._server) { - serverList = localSCMAC; - clientList = remote.sc.mac; - } else { - serverList = remote.sc.mac; - clientList = localSCMAC; - } - // Check for agreeable server->client hmac algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C MAC'); - return doFatalError( - self, - 'Handshake failed: no matching S->C MAC', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); + try { + const date = new Date(`${apiVersion}T00:00:00.0Z`); + return date; } - init.sc.mac = clientList[i]; - debug && debug(`Handshake: S->C MAC: ${clientList[i]}`); - } - - - // Client->Server compression ================================================ - const localCSCompress = local.lists.cs.compress.array; - debug && debug(`Handshake: (local) C->S compression: ${localCSCompress}`); - debug && debug(`Handshake: (remote) C->S compression: ${remote.cs.compress}`); - if (self._server) { - serverList = localCSCompress; - clientList = remote.cs.compress; - } else { - serverList = remote.cs.compress; - clientList = localCSCompress; - } - // Check for agreeable client->server compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching C->S compression'); - return doFatalError( - self, - 'Handshake failed: no matching C->S compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.cs.compress = clientList[i]; - debug && debug(`Handshake: C->S compression: ${clientList[i]}`); - - - // Server->Client compression ================================================ - const localSCCompress = local.lists.sc.compress.array; - debug && debug(`Handshake: (local) S->C compression: ${localSCCompress}`); - debug && debug(`Handshake: (remote) S->C compression: ${remote.sc.compress}`); - if (self._server) { - serverList = localSCCompress; - clientList = remote.sc.compress; - } else { - serverList = remote.sc.compress; - clientList = localSCCompress; - } - // Check for agreeable server->client compression algorithm - for (i = 0; - i < clientList.length && serverList.indexOf(clientList[i]) === -1; - ++i); - if (i === clientList.length) { - // No suitable match found! - debug && debug('Handshake: No matching S->C compression'); - return doFatalError( - self, - 'Handshake failed: no matching S->C compression', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - init.sc.compress = clientList[i]; - debug && debug(`Handshake: S->C compression: ${clientList[i]}`); - - init.cs.lang = ''; - init.sc.lang = ''; - - // XXX: hack -- find a better way to do this - if (self._kex) { - if (!self._kexinit) { - // We received a rekey request, but we haven't sent a KEXINIT in response - // yet - kexinit(self); - } - self._decipher._onPayload = onKEXPayload.bind(self, { firstPacket: false }); - } - - self._kex = createKeyExchange(init, self, payload); - self._kex.remoteExtInfoEnabled = remoteExtInfoEnabled; - self._kex.start(); -} - -const createKeyExchange = (() => { - function convertToMpint(buf) { - let idx = 0; - let length = buf.length; - while (buf[idx] === 0x00) { - ++idx; - --length; - } - let newBuf; - if (buf[idx] & 0x80) { - newBuf = Buffer.allocUnsafe(1 + length); - newBuf[0] = 0; - buf.copy(newBuf, 1, idx); - buf = newBuf; - } else if (length !== buf.length) { - newBuf = Buffer.allocUnsafe(length); - buf.copy(newBuf, 0, idx); - buf = newBuf; - } - return buf; - } - - class KeyExchange { - constructor(negotiated, protocol, remoteKexinit) { - this._protocol = protocol; - - this.sessionID = (protocol._kex ? protocol._kex.sessionID : undefined); - this.negotiated = negotiated; - this.remoteExtInfoEnabled = false; - this._step = 1; - this._public = null; - this._dh = null; - this._sentNEWKEYS = false; - this._receivedNEWKEYS = false; - this._finished = false; - this._hostVerified = false; - - // Data needed for initializing cipher/decipher/etc. - this._kexinit = protocol._kexinit; - this._remoteKexinit = remoteKexinit; - this._identRaw = protocol._identRaw; - this._remoteIdentRaw = protocol._remoteIdentRaw; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - } - finish(scOnly) { - if (this._finished) - return false; - this._finished = true; - - const isServer = this._protocol._server; - const negotiated = this.negotiated; - - const pubKey = this.convertPublicKey(this._dhData); - let secret = this.computeSecret(this._dhData); - if (secret instanceof Error) { - secret.message = - `Error while computing DH secret (${this.type}): ${secret.message}`; - secret.level = 'handshake'; - return doFatalError( - this._protocol, - secret, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - const hash = createHash(this.hashName); - // V_C - hashString(hash, (isServer ? this._remoteIdentRaw : this._identRaw)); - // "V_S" - hashString(hash, (isServer ? this._identRaw : this._remoteIdentRaw)); - // "I_C" - hashString(hash, (isServer ? this._remoteKexinit : this._kexinit)); - // "I_S" - hashString(hash, (isServer ? this._kexinit : this._remoteKexinit)); - // "K_S" - const serverPublicHostKey = (isServer - ? this._hostKey.getPublicSSH() - : this._hostKey); - hashString(hash, serverPublicHostKey); - - if (this.type === 'groupex') { - // Group exchange-specific - const params = this.getDHParams(); - const num = Buffer.allocUnsafe(4); - // min (uint32) - writeUInt32BE(num, this._minBits, 0); - hash.update(num); - // preferred (uint32) - writeUInt32BE(num, this._prefBits, 0); - hash.update(num); - // max (uint32) - writeUInt32BE(num, this._maxBits, 0); - hash.update(num); - // prime - hashString(hash, params.prime); - // generator - hashString(hash, params.generator); - } - - // method-specific data sent by client - hashString(hash, (isServer ? pubKey : this.getPublicKey())); - // method-specific data sent by server - const serverPublicKey = (isServer ? this.getPublicKey() : pubKey); - hashString(hash, serverPublicKey); - // shared secret ("K") - hashString(hash, secret); - - // "H" - const exchangeHash = hash.digest(); - - if (!isServer) { - bufferParser.init(this._sig, 0); - const sigType = bufferParser.readString(true); - - if (!sigType) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (sigType !== negotiated.serverHostKey) { - return doFatalError( - this._protocol, - `Wrong signature type: ${sigType}, ` - + `expected: ${negotiated.serverHostKey}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // "s" - let sigValue = bufferParser.readString(); - - bufferParser.clear(); - - if (sigValue === undefined) { - return doFatalError( - this._protocol, - 'Malformed packet while reading signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (!(sigValue = sigSSHToASN1(sigValue, sigType))) { - return doFatalError( - this._protocol, - 'Malformed signature', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - let parsedHostKey; - { - bufferParser.init(this._hostKey, 0); - const name = bufferParser.readString(true); - const hostKey = this._hostKey.slice(bufferParser.pos()); - bufferParser.clear(); - parsedHostKey = parseDERKey(hostKey, name); - if (parsedHostKey instanceof Error) { - parsedHostKey.level = 'handshake'; - return doFatalError( - this._protocol, - parsedHostKey, - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug - && this._protocol._debug('Verifying signature ...'); - - const verified = parsedHostKey.verify(exchangeHash, sigValue, hashAlgo); - if (verified !== true) { - if (verified instanceof Error) { - this._protocol._debug && this._protocol._debug( - `Signature verification failed: ${verified.stack}` - ); - } else { - this._protocol._debug && this._protocol._debug( - 'Signature verification failed' - ); - } - return doFatalError( - this._protocol, - 'Handshake failed: signature verification failed', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug('Verified signature'); - } else { - // Server - - let hashAlgo; - // Check if we need to override the default hash algorithm - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': hashAlgo = 'sha256'; break; - case 'rsa-sha2-512': hashAlgo = 'sha512'; break; - } - - this._protocol._debug && this._protocol._debug( - 'Generating signature ...' - ); - - let signature = this._hostKey.sign(exchangeHash, hashAlgo); - if (signature instanceof Error) { - return doFatalError( - this._protocol, - 'Handshake failed: signature generation failed for ' - + `${this._hostKey.type} host key: ${signature.message}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - signature = convertSignature(signature, this._hostKey.type); - if (signature === false) { - return doFatalError( - this._protocol, - 'Handshake failed: signature conversion failed for ' - + `${this._hostKey.type} host key`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Send KEX reply - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - const sigType = this.negotiated.serverHostKey; - const sigTypeLen = Buffer.byteLength(sigType); - const sigLen = 4 + sigTypeLen + 4 + signature.length; - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 - + 4 + serverPublicHostKey.length - + 4 + serverPublicKey.length - + 4 + sigLen, - true - ); - - packet[p] = MESSAGE.KEXDH_REPLY; - - writeUInt32BE(packet, serverPublicHostKey.length, ++p); - packet.set(serverPublicHostKey, p += 4); - - writeUInt32BE(packet, - serverPublicKey.length, - p += serverPublicHostKey.length); - packet.set(serverPublicKey, p += 4); - - writeUInt32BE(packet, sigLen, p += serverPublicKey.length); - - writeUInt32BE(packet, sigTypeLen, p += 4); - packet.utf8Write(sigType, p += 4, sigTypeLen); - - writeUInt32BE(packet, signature.length, p += sigTypeLen); - packet.set(signature, p += 4); - - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_REPLY'; - break; - case 'groupex': - type = 'KEXDH_GEX_REPLY'; - break; - default: - type = 'KEXECDH_REPLY'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - - if (isServer || !scOnly) - trySendNEWKEYS(this); - - let hsCipherConfig; - let hsWrite; - const completeHandshake = (partial) => { - if (hsCipherConfig) { - trySendNEWKEYS(this); - hsCipherConfig.outbound.seqno = this._protocol._cipher.outSeqno; - this._protocol._cipher.free(); - this._protocol._cipher = createCipher(hsCipherConfig); - this._protocol._packetRW.write = hsWrite; - hsCipherConfig = undefined; - hsWrite = undefined; - this._protocol._onHandshakeComplete(negotiated); - - return false; - } - - if (!this.sessionID) - this.sessionID = exchangeHash; - - { - const newSecret = Buffer.allocUnsafe(4 + secret.length); - writeUInt32BE(newSecret, secret.length, 0); - newSecret.set(secret, 4); - secret = newSecret; - } - - // Initialize new ciphers, deciphers, etc. - - const csCipherInfo = CIPHER_INFO[negotiated.cs.cipher]; - const scCipherInfo = CIPHER_INFO[negotiated.sc.cipher]; - - const csIV = generateKEXVal(csCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'A'); - const scIV = generateKEXVal(scCipherInfo.ivLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'B'); - const csKey = generateKEXVal(csCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'C'); - const scKey = generateKEXVal(scCipherInfo.keyLen, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'D'); - let csMacInfo; - let csMacKey; - if (!csCipherInfo.authLen) { - csMacInfo = MAC_INFO[negotiated.cs.mac]; - csMacKey = generateKEXVal(csMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'E'); - } - let scMacInfo; - let scMacKey; - if (!scCipherInfo.authLen) { - scMacInfo = MAC_INFO[negotiated.sc.mac]; - scMacKey = generateKEXVal(scMacInfo.len, - this.hashName, - secret, - exchangeHash, - this.sessionID, - 'F'); - } - - const config = { - inbound: { - onPayload: this._protocol._onPayload, - seqno: this._protocol._decipher.inSeqno, - decipherInfo: (!isServer ? scCipherInfo : csCipherInfo), - decipherIV: (!isServer ? scIV : csIV), - decipherKey: (!isServer ? scKey : csKey), - macInfo: (!isServer ? scMacInfo : csMacInfo), - macKey: (!isServer ? scMacKey : csMacKey), - }, - outbound: { - onWrite: this._protocol._onWrite, - seqno: this._protocol._cipher.outSeqno, - cipherInfo: (isServer ? scCipherInfo : csCipherInfo), - cipherIV: (isServer ? scIV : csIV), - cipherKey: (isServer ? scKey : csKey), - macInfo: (isServer ? scMacInfo : csMacInfo), - macKey: (isServer ? scMacKey : csMacKey), - }, - }; - this._protocol._decipher.free(); - hsCipherConfig = config; - this._protocol._decipher = createDecipher(config); - - const rw = { - read: undefined, - write: undefined, - }; - switch (negotiated.cs.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.read = new ZlibPacketReader(); - else - rw.write = new ZlibPacketWriter(this._protocol); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.read = new PacketReader(); - else - rw.write = new PacketWriter(this._protocol); - } - switch (negotiated.sc.compress) { - case 'zlib': // starts immediately - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - case 'zlib@openssh.com': - // Starts after successful user authentication - - if (this._protocol._authenticated) { - // If a rekey happens and this compression method is selected and - // we already authenticated successfully, we need to start - // immediately instead - if (isServer) - rw.write = new ZlibPacketWriter(this._protocol); - else - rw.read = new ZlibPacketReader(); - break; - } - // FALLTHROUGH - default: - // none -- never any compression/decompression - - if (isServer) - rw.write = new PacketWriter(this._protocol); - else - rw.read = new PacketReader(); - } - this._protocol._packetRW.read.cleanup(); - this._protocol._packetRW.write.cleanup(); - this._protocol._packetRW.read = rw.read; - hsWrite = rw.write; - - // Cleanup/reset various state - this._public = null; - this._dh = null; - this._kexinit = this._protocol._kexinit = undefined; - this._remoteKexinit = undefined; - this._identRaw = undefined; - this._remoteIdentRaw = undefined; - this._hostKey = undefined; - this._dhData = undefined; - this._sig = undefined; - - if (!partial) - return completeHandshake(); - return false; - }; - - if (isServer || scOnly) - this.finish = completeHandshake; - - if (!isServer) - return completeHandshake(scOnly); + catch (e) { + return null; } - - start() { - if (!this._protocol._server) { - if (this._protocol._debug) { - let type; - switch (this.type) { - case 'group': - type = 'KEXDH_INIT'; - break; - default: - type = 'KEXECDH_INIT'; - } - this._protocol._debug(`Outbound: Sending ${type}`); - } - - const pubKey = this.getPublicKey(); - - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + pubKey.length, - true - ); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } +} +function validateExp(exp) { + if (!exp) { + throw new Error('Missing exp claim'); } - getPublicKey() { - this.generateKeys(); - - const key = this._public; - - if (key) - return this.convertPublicKey(key); + const timeNow = Math.floor(Date.now() / 1000); + if (exp <= timeNow) { + throw new Error('JWT has expired'); } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } - - if (key[idx] & 0x80) { - newKey = Buffer.allocUnsafe(1 + len); - newKey[0] = 0; - key.copy(newKey, 1, idx); - return newKey; - } - - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; +} +function getAlgorithm(alg) { + switch (alg) { + case 'RS256': + return { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + case 'ES256': + return { + name: 'ECDSA', + namedCurve: 'P-256', + hash: { name: 'SHA-256' }, + }; + default: + throw new Error('Invalid alg claim'); } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - return convertToMpint(this._dh.computeSecret(otherPublicKey)); - } catch (ex) { - return ex; - } +} +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +function validateUUID(str) { + if (!UUID_REGEX.test(str)) { + throw new Error('@supabase/auth-js: Expected parameter to be UUID but is not'); } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: - if (this._protocol._server) { - // Server - if (type !== MESSAGE.KEXDH_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Init' - ); - /* - byte SSH_MSG_KEXDH_INIT - / SSH_MSG_KEX_ECDH_INIT - string - */ - bufferParser.init(payload, 1); - const dhData = bufferParser.readString(); - bufferParser.clear(); - if (dhData === undefined) { - return doFatalError( - this._protocol, - 'Received malformed KEX*_INIT', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - // Client public key - this._dhData = dhData; - - let hostKey = - this._protocol._hostKeys[this.negotiated.serverHostKey]; - if (Array.isArray(hostKey)) - hostKey = hostKey[0]; - this._hostKey = hostKey; - - this.finish(); - } else { - // Client - if (type !== MESSAGE.KEXDH_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH Reply' - ); - /* - byte SSH_MSG_KEXDH_REPLY - / SSH_MSG_KEX_DH_GEX_REPLY - / SSH_MSG_KEX_ECDH_REPLY - string server public host key and certificates (K_S) - string - string signature of H - */ - bufferParser.init(payload, 1); - let hostPubKey; - let dhData; - let sig; - if ((hostPubKey = bufferParser.readString()) === undefined - || (dhData = bufferParser.readString()) === undefined - || (sig = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEX*_REPLY', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // Check that the host public key type matches what was negotiated - // during KEXINIT swap - bufferParser.init(hostPubKey, 0); - const hostPubKeyType = bufferParser.readString(true); - bufferParser.clear(); - if (hostPubKeyType === undefined) { - return doFatalError( - this._protocol, - 'Received malformed host public key', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - if (hostPubKeyType !== this.negotiated.serverHostKey) { - // Check if we need to make an exception - switch (this.negotiated.serverHostKey) { - case 'rsa-sha2-256': - case 'rsa-sha2-512': - if (hostPubKeyType === 'ssh-rsa') - break; - // FALLTHROUGH - default: - return doFatalError( - this._protocol, - 'Host key does not match negotiated type', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } +} +function userNotAvailableProxy() { + const proxyTarget = {}; + return new Proxy(proxyTarget, { + get: (target, prop) => { + if (prop === '__isUserNotAvailableProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms. + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)') { + // Node.js util.inspect + return undefined; + } + } + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); + }, + set: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + deleteProperty: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + }); +} +/** + * Creates a proxy around a user object that warns when properties are accessed on the server. + * This is used to alert developers that using user data from getSession() on the server is insecure. + * + * @param user The actual user object to wrap + * @param suppressWarningRef An object with a 'value' property that controls warning suppression + * @returns A proxied user object that warns on property access + */ +function insecureUserWarningProxy(user, suppressWarningRef) { + return new Proxy(user, { + get: (target, prop, receiver) => { + // Allow internal checks without warning + if (prop === '__isInsecureUserWarningProxy') { + return true; + } + // Preventative check for common problematic symbols during cloning/inspection + // These symbols might be accessed by structuredClone or other internal mechanisms + if (typeof prop === 'symbol') { + const sProp = prop.toString(); + if (sProp === 'Symbol(Symbol.toPrimitive)' || + sProp === 'Symbol(Symbol.toStringTag)' || + sProp === 'Symbol(util.inspect.custom)' || + sProp === 'Symbol(nodejs.util.inspect.custom)') { + // Return the actual value for these symbols to allow proper inspection + return Reflect.get(target, prop, receiver); + } + } + // Emit warning on first property access + if (!suppressWarningRef.value && typeof prop === 'string') { + console.warn('Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.'); + suppressWarningRef.value = true; } + return Reflect.get(target, prop, receiver); + }, + }); +} +/** + * Deep clones a JSON-serializable object using JSON.parse(JSON.stringify(obj)). + * Note: Only works for JSON-safe data. + */ +function deepClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} +//# sourceMappingURL=helpers.js.map - this._hostKey = hostPubKey; - this._dhData = dhData; - this._sig = sig; +/***/ }), - let checked = false; - let ret; - if (this._protocol._hostVerifier === undefined) { - ret = true; - this._protocol._debug && this._protocol._debug( - 'Host accepted by default (no verification)' - ); - } else { - ret = this._protocol._hostVerifier(hostPubKey, (permitted) => { - if (checked) - return; - checked = true; - if (permitted === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - if (this._receivedNEWKEYS) - this.finish(); - else - trySendNEWKEYS(this); - }); - } - if (ret === undefined) { - // Async host verification - ++this._step; - return; - } - checked = true; - if (ret === false) { - this._protocol._debug && this._protocol._debug( - 'Host denied (verification failed)' - ); - return doFatalError( - this._protocol, - 'Host denied (verification failed)', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Host accepted (verified)' - ); - this._hostVerified = true; - trySendNEWKEYS(this); - } - ++this._step; - break; - case 2: - if (type !== MESSAGE.NEWKEYS) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.NEWKEYS}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Inbound: NEWKEYS' - ); - this._receivedNEWKEYS = true; - if (this._protocol._strictMode) - this._protocol._decipher.inSeqno = 0; - ++this._step; +/***/ 5804: +/***/ ((__unused_webpack_module, exports) => { - return this.finish(!this._protocol._server && !this._hostVerified); - default: - return doFatalError( - this._protocol, - `Received unexpected packet ${type} after NEWKEYS`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } - } +"use strict"; - class Curve25519Exchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter; +/** + * Returns a localStorage-like object that stores the key-value pairs in + * memory. + */ +function memoryLocalStorageAdapter(store = {}) { + return { + getItem: (key) => { + return store[key] || null; + }, + setItem: (key, value) => { + store[key] = value; + }, + removeItem: (key) => { + delete store[key]; + }, + }; +} +//# sourceMappingURL=local-storage.js.map - this.type = '25519'; - this.hashName = hashName; - this._keys = null; - } - generateKeys() { - if (!this._keys) - this._keys = generateKeyPairSync('x25519'); - } - getPublicKey() { - this.generateKeys(); +/***/ }), - const key = this._keys.publicKey.export({ type: 'spki', format: 'der' }); - return key.slice(-32); // HACK: avoids parsing DER/BER header - } - convertPublicKey(key) { - let newKey; - let idx = 0; - let len = key.length; - while (key[idx] === 0x00) { - ++idx; - --len; - } +/***/ 163: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (key.length === 32) - return key; +"use strict"; - if (len !== key.length) { - newKey = Buffer.allocUnsafe(len); - key.copy(newKey, 0, idx); - key = newKey; - } - return key; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0; +exports.navigatorLock = navigatorLock; +exports.processLock = processLock; +const helpers_1 = __nccwpck_require__(4044); +/** + * @experimental + */ +exports.internals = { + /** + * @experimental + */ + debug: !!(globalThis && + (0, helpers_1.supportsLocalStorage)() && + globalThis.localStorage && + globalThis.localStorage.getItem('supabase.gotrue-js.locks.debug') === 'true'), +}; +/** + * An error thrown when a lock cannot be acquired after some amount of time. + * + * Use the {@link #isAcquireTimeout} property instead of checking with `instanceof`. + */ +class LockAcquireTimeoutError extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; } - computeSecret(otherPublicKey) { - this.generateKeys(); - - try { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.110'); // id-X25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(otherPublicKey.length); - otherPublicKey.copy(asnWriter._buf, - asnWriter._offset, - 0, - otherPublicKey.length); - asnWriter._offset += otherPublicKey.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - - return convertToMpint(diffieHellman({ - privateKey: this._keys.privateKey, - publicKey: createPublicKey({ - key: asnWriter.buffer, - type: 'spki', - format: 'der', - }), - })); - } catch (ex) { - return ex; - } +} +exports.LockAcquireTimeoutError = LockAcquireTimeoutError; +class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError; +class ProcessLockAcquireTimeoutError extends LockAcquireTimeoutError { +} +exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError; +/** + * Implements a global exclusive lock using the Navigator LockManager API. It + * is available on all browsers released after 2022-03-15 with Safari being the + * last one to release support. If the API is not available, this function will + * throw. Make sure you check availablility before configuring {@link + * GoTrueClient}. + * + * You can turn on debugging by setting the `supabase.gotrue-js.locks.debug` + * local storage item to `true`. + * + * Internals: + * + * Since the LockManager API does not preserve stack traces for the async + * function passed in the `request` method, a trick is used where acquiring the + * lock releases a previously started promise to run the operation in the `fn` + * function. The lock waits for that promise to finish (with or without error), + * while the function will finally wait for the result anyway. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +async function navigatorLock(name, acquireTimeout, fn) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquire lock', name, acquireTimeout); } - } + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort(); + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock acquire timed out', name); + } + }, acquireTimeout); + } + // MDN article: https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request + // Wrapping navigator.locks.request() with a plain Promise is done as some + // libraries like zone.js patch the Promise object to track the execution + // context. However, it appears that most browsers use an internal promise + // implementation when using the navigator.locks.request() API causing them + // to lose context and emit confusing log messages or break certain features. + // This wrapping is believed to help zone.js track the execution context + // better. + return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 + ? { + mode: 'exclusive', + ifAvailable: true, + } + : { + mode: 'exclusive', + signal: abortController.signal, + }, async (lock) => { + if (lock) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: acquired', name, lock.name); + } + try { + return await fn(); + } + finally { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: released', name, lock.name); + } + } + } + else { + if (acquireTimeout === 0) { + if (exports.internals.debug) { + console.log('@supabase/gotrue-js: navigatorLock: not immediately available', name); + } + throw new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + } + else { + if (exports.internals.debug) { + try { + const result = await globalThis.navigator.locks.query(); + console.log('@supabase/gotrue-js: Navigator LockManager state', JSON.stringify(result, null, ' ')); + } + catch (e) { + console.warn('@supabase/gotrue-js: Error when querying Navigator LockManager state', e); + } + } + // Browser is not following the Navigator LockManager spec, it + // returned a null lock when we didn't use ifAvailable. So we can + // pretend the lock is acquired in the name of backward compatibility + // and user experience and just run the function. + console.warn('@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request'); + return await fn(); + } + } + })); +} +const PROCESS_LOCKS = {}; +/** + * Implements a global exclusive lock that works only in the current process. + * Useful for environments like React Native or other non-browser + * single-process (i.e. no concept of "tabs") environments. + * + * Use {@link #navigatorLock} in browser environments. + * + * @param name Name of the lock to be acquired. + * @param acquireTimeout If negative, no timeout. If 0 an error is thrown if + * the lock can't be acquired without waiting. If positive, the lock acquire + * will time out after so many milliseconds. An error is + * a timeout if it has `isAcquireTimeout` set to true. + * @param fn The operation to run once the lock is acquired. + */ +async function processLock(name, acquireTimeout, fn) { + var _a; + const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve(); + const currentOperation = Promise.race([ + previousOperation.catch(() => { + // ignore error of previous operation that we're waiting to finish + return null; + }), + acquireTimeout >= 0 + ? new Promise((_, reject) => { + setTimeout(() => { + reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); + }, acquireTimeout); + }) + : null, + ].filter((x) => x)) + .catch((e) => { + if (e && e.isAcquireTimeout) { + throw e; + } + return null; + }) + .then(async () => { + // previous operations finished and we didn't get a race on the acquire + // timeout, so the current operation can finally start + return await fn(); + }); + PROCESS_LOCKS[name] = currentOperation.catch(async (e) => { + if (e && e.isAcquireTimeout) { + // if the current operation timed out, it doesn't mean that the previous + // operation finished, so we need contnue waiting for it to finish + await previousOperation; + return null; + } + throw e; + }); + // finally wait for the current operation to finish successfully, with an + // error or with an acquire timeout error + return await currentOperation; +} +//# sourceMappingURL=locks.js.map - class ECDHExchange extends KeyExchange { - constructor(curveName, hashName, ...args) { - super(...args); +/***/ }), - this.type = 'ecdh'; - this.curveName = curveName; - this.hashName = hashName; - } - generateKeys() { - if (!this._dh) { - this._dh = createECDH(this.curveName); - this._public = this._dh.generateKeys(); - } - } - } +/***/ 1897: +/***/ ((__unused_webpack_module, exports) => { - class DHGroupExchange extends KeyExchange { - constructor(hashName, ...args) { - super(...args); +"use strict"; - this.type = 'groupex'; - this.hashName = hashName; - this._prime = null; - this._generator = null; - this._minBits = GEX_MIN_BITS; - this._prefBits = dhEstimate(this.negotiated); - if (this._protocol._compatFlags & COMPAT.BUG_DHGEX_LARGE) - this._prefBits = Math.min(this._prefBits, 4096); - this._maxBits = GEX_MAX_BITS; - } - start() { - if (this._protocol._server) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.polyfillGlobalThis = polyfillGlobalThis; +/** + * https://mathiasbynens.be/notes/globalthis + */ +function polyfillGlobalThis() { + if (typeof globalThis === 'object') return; - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_REQUEST' - ); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = this._protocol._packetRW.write.alloc( - 1 + 4 + 4 + 4, - true - ); - packet[p] = MESSAGE.KEXDH_GEX_REQUEST; - writeUInt32BE(packet, this._minBits, ++p); - writeUInt32BE(packet, this._prefBits, p += 4); - writeUInt32BE(packet, this._maxBits, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - generateKeys() { - if (!this._dh && this._prime && this._generator) { - this._dh = createDiffieHellman(this._prime, this._generator); - this._public = this._dh.generateKeys(); - } - } - setDHParams(prime, generator) { - if (!Buffer.isBuffer(prime)) - throw new Error('Invalid prime value'); - if (!Buffer.isBuffer(generator)) - throw new Error('Invalid generator value'); - this._prime = prime; - this._generator = generator; - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } - } - parse(payload) { - const type = payload[0]; - switch (this._step) { - case 1: { - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_REQUEST) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ` - + MESSAGE.KEXDH_GEX_REQUEST, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - // TODO: allow user implementation to provide safe prime and - // generator on demand to support group exchange on server side - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - if (type !== MESSAGE.KEXDH_GEX_GROUP) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_GROUP}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Group' - ); - - /* - byte SSH_MSG_KEX_DH_GEX_GROUP - mpint p, safe prime - mpint g, generator for subgroup in GF(p) - */ - bufferParser.init(payload, 1); - let prime; - let gen; - if ((prime = bufferParser.readString()) === undefined - || (gen = bufferParser.readString()) === undefined) { - bufferParser.clear(); - return doFatalError( - this._protocol, - 'Received malformed KEXDH_GEX_GROUP', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - bufferParser.clear(); - - // TODO: validate prime - this.setDHParams(prime, gen); - this.generateKeys(); - const pubkey = this.getPublicKey(); - - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_GEX_INIT' - ); - - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubkey.length, true); - packet[p] = MESSAGE.KEXDH_GEX_INIT; - writeUInt32BE(packet, pubkey.length, ++p); - packet.set(pubkey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - - ++this._step; - break; - } - case 2: - if (this._protocol._server) { - if (type !== MESSAGE.KEXDH_GEX_INIT) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_INIT}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Init' - ); - return doFatalError( - this._protocol, - 'Group exchange not implemented for server', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } else if (type !== MESSAGE.KEXDH_GEX_REPLY) { - return doFatalError( - this._protocol, - `Received packet ${type} instead of ${MESSAGE.KEXDH_GEX_REPLY}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - this._protocol._debug && this._protocol._debug( - 'Received DH GEX Reply' - ); - this._step = 1; - payload[0] = MESSAGE.KEXDH_REPLY; - this.parse = KeyExchange.prototype.parse; - this.parse(payload); - } - } - } - - class DHExchange extends KeyExchange { - constructor(groupName, hashName, ...args) { - super(...args); - - this.type = 'group'; - this.groupName = groupName; - this.hashName = hashName; - } - start() { - if (!this._protocol._server) { - this._protocol._debug && this._protocol._debug( - 'Outbound: Sending KEXDH_INIT' - ); - const pubKey = this.getPublicKey(); - let p = this._protocol._packetRW.write.allocStartKEX; - const packet = - this._protocol._packetRW.write.alloc(1 + 4 + pubKey.length, true); - packet[p] = MESSAGE.KEXDH_INIT; - writeUInt32BE(packet, pubKey.length, ++p); - packet.set(pubKey, p += 4); - this._protocol._cipher.encrypt( - this._protocol._packetRW.write.finalize(packet, true) - ); - } - } - generateKeys() { - if (!this._dh) { - this._dh = createDiffieHellmanGroup(this.groupName); - this._public = this._dh.generateKeys(); - } - } - getDHParams() { - if (this._dh) { - return { - prime: convertToMpint(this._dh.getPrime()), - generator: convertToMpint(this._dh.getGenerator()), - }; - } - } - } - - return (negotiated, ...args) => { - if (typeof negotiated !== 'object' || negotiated === null) - throw new Error('Invalid negotiated argument'); - const kexType = negotiated.kex; - if (typeof kexType === 'string') { - args = [negotiated, ...args]; - switch (kexType) { - case 'curve25519-sha256': - case 'curve25519-sha256@libssh.org': - if (!curve25519Supported) - break; - return new Curve25519Exchange('sha256', ...args); - - case 'ecdh-sha2-nistp256': - return new ECDHExchange('prime256v1', 'sha256', ...args); - case 'ecdh-sha2-nistp384': - return new ECDHExchange('secp384r1', 'sha384', ...args); - case 'ecdh-sha2-nistp521': - return new ECDHExchange('secp521r1', 'sha512', ...args); - - case 'diffie-hellman-group1-sha1': - return new DHExchange('modp2', 'sha1', ...args); - case 'diffie-hellman-group14-sha1': - return new DHExchange('modp14', 'sha1', ...args); - case 'diffie-hellman-group14-sha256': - return new DHExchange('modp14', 'sha256', ...args); - case 'diffie-hellman-group15-sha512': - return new DHExchange('modp15', 'sha512', ...args); - case 'diffie-hellman-group16-sha512': - return new DHExchange('modp16', 'sha512', ...args); - case 'diffie-hellman-group17-sha512': - return new DHExchange('modp17', 'sha512', ...args); - case 'diffie-hellman-group18-sha512': - return new DHExchange('modp18', 'sha512', ...args); - - case 'diffie-hellman-group-exchange-sha1': - return new DHGroupExchange('sha1', ...args); - case 'diffie-hellman-group-exchange-sha256': - return new DHGroupExchange('sha256', ...args); - } - throw new Error(`Unsupported key exchange algorithm: ${kexType}`); + try { + Object.defineProperty(Object.prototype, '__magic__', { + get: function () { + return this; + }, + configurable: true, + }); + // @ts-expect-error 'Allow access to magic' + __magic__.globalThis = __magic__; + // @ts-expect-error 'Allow access to magic' + delete Object.prototype.__magic__; } - throw new Error(`Invalid key exchange type: ${kexType}`); - }; -})(); - -const KexInit = (() => { - const KEX_PROPERTY_NAMES = [ - 'kex', - 'serverHostKey', - ['cs', 'cipher' ], - ['sc', 'cipher' ], - ['cs', 'mac' ], - ['sc', 'mac' ], - ['cs', 'compress' ], - ['sc', 'compress' ], - ['cs', 'lang' ], - ['sc', 'lang' ], - ]; - return class KexInit { - constructor(obj) { - if (typeof obj !== 'object' || obj === null) - throw new TypeError('Argument must be an object'); - - const lists = { - kex: undefined, - serverHostKey: undefined, - cs: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - sc: { - cipher: undefined, - mac: undefined, - compress: undefined, - lang: undefined, - }, - - all: undefined, - }; - let totalSize = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let base; - let val; - let desc; - let key; - if (typeof prop === 'string') { - base = lists; - val = obj[prop]; - desc = key = prop; - } else { - const parent = prop[0]; - base = lists[parent]; - key = prop[1]; - val = obj[parent][key]; - desc = `${parent}.${key}`; - } - const entry = { array: undefined, buffer: undefined }; - if (Buffer.isBuffer(val)) { - entry.array = ('' + val).split(','); - entry.buffer = val; - totalSize += 4 + val.length; - } else { - if (typeof val === 'string') - val = val.split(','); - if (Array.isArray(val)) { - entry.array = val; - entry.buffer = Buffer.from(val.join(',')); - } else { - throw new TypeError(`Invalid \`${desc}\` type: ${typeof val}`); - } - totalSize += 4 + entry.buffer.length; + catch (e) { + if (typeof self !== 'undefined') { + // @ts-expect-error 'Allow access to globals' + self.globalThis = self; } - base[key] = entry; - } - - const all = Buffer.allocUnsafe(totalSize); - lists.all = all; - - let allPos = 0; - for (const prop of KEX_PROPERTY_NAMES) { - let data; - if (typeof prop === 'string') - data = lists[prop].buffer; - else - data = lists[prop[0]][prop[1]].buffer; - allPos = writeUInt32BE(all, data.length, allPos); - all.set(data, allPos); - allPos += data.length; - } - - this.totalSize = totalSize; - this.lists = lists; - } - copyAllTo(buf, offset) { - const src = this.lists.all; - if (typeof offset !== 'number') - throw new TypeError(`Invalid offset value: ${typeof offset}`); - if (buf.length - offset < src.length) - throw new Error('Insufficient space to copy list'); - buf.set(src, offset); - return src.length; } - }; -})(); - -const hashString = (() => { - const LEN = Buffer.allocUnsafe(4); - return (hash, buf) => { - writeUInt32BE(LEN, buf.length, 0); - hash.update(LEN); - hash.update(buf); - }; -})(); - -function generateKEXVal(len, hashName, secret, exchangeHash, sessionID, char) { - let ret; - if (len) { - let digest = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(char) - .update(sessionID) - .digest(); - while (digest.length < len) { - const chunk = createHash(hashName) - .update(secret) - .update(exchangeHash) - .update(digest) - .digest(); - const extended = Buffer.allocUnsafe(digest.length + chunk.length); - extended.set(digest, 0); - extended.set(chunk, digest.length); - digest = extended; - } - if (digest.length === len) - ret = digest; - else - ret = new FastBuffer(digest.buffer, digest.byteOffset, len); - } else { - ret = EMPTY_BUFFER; - } - return ret; } +//# sourceMappingURL=polyfills.js.map -function onKEXPayload(state, payload) { - // XXX: move this to the Decipher implementations? - if (payload.length === 0) { - this._debug && this._debug('Inbound: Skipping empty packet payload'); - return; - } - - if (this._skipNextInboundPacket) { - this._skipNextInboundPacket = false; - return; - } +/***/ }), - payload = this._packetRW.read.read(payload); +/***/ 1852: +/***/ ((__unused_webpack_module, exports) => { - const type = payload[0]; +"use strict"; - if (!this._strictMode) { - switch (type) { - case MESSAGE.IGNORE: - case MESSAGE.UNIMPLEMENTED: - case MESSAGE.DEBUG: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = __nccwpck_require__(10172); - return MESSAGE_HANDLERS[type](this, payload); - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SIGN_OUT_SCOPES = void 0; +const WeakPasswordReasons = (/* unused pure expression or super */ null && (['length', 'characters', 'pwned'])); +const AMRMethods = (/* unused pure expression or super */ null && ([ + 'password', + 'otp', + 'oauth', + 'totp', + 'mfa/totp', + 'mfa/phone', + 'mfa/webauthn', + 'anonymous', + 'sso/saml', + 'magiclink', + 'web3', +])); +const FactorTypes = (/* unused pure expression or super */ null && (['totp', 'phone', 'webauthn'])); +const FactorVerificationStatuses = (/* unused pure expression or super */ null && (['verified', 'unverified'])); +const MFATOTPChannels = (/* unused pure expression or super */ null && (['sms', 'whatsapp'])); +exports.SIGN_OUT_SCOPES = ['global', 'local', 'others']; +//# sourceMappingURL=types.js.map - switch (type) { - case MESSAGE.DISCONNECT: - if (!MESSAGE_HANDLERS) - MESSAGE_HANDLERS = __nccwpck_require__(10172); - return MESSAGE_HANDLERS[type](this, payload); - case MESSAGE.KEXINIT: - if (!state.firstPacket) { - return doFatalError( - this, - 'Received extra KEXINIT during handshake', - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - state.firstPacket = false; - return handleKexInit(this, payload); - default: - // Ensure packet is either an algorithm negotiation or KEX - // algorithm-specific packet - if (type < 20 || type > 49) { - return doFatalError( - this, - `Received unexpected packet type ${type}`, - 'handshake', - DISCONNECT_REASON.KEY_EXCHANGE_FAILED - ); - } - } +/***/ }), - return this._kex.parse(payload); -} - -function dhEstimate(neg) { - const csCipher = CIPHER_INFO[neg.cs.cipher]; - const scCipher = CIPHER_INFO[neg.sc.cipher]; - // XXX: if OpenSSH's `umac-*` MACs are ever supported, their key lengths will - // also need to be considered when calculating `bits` - const bits = Math.max( - 0, - (csCipher.sslName === 'des-ede3-cbc' ? 14 : csCipher.keyLen), - csCipher.blockLen, - csCipher.ivLen, - (scCipher.sslName === 'des-ede3-cbc' ? 14 : scCipher.keyLen), - scCipher.blockLen, - scCipher.ivLen - ) * 8; - if (bits <= 112) - return 2048; - if (bits <= 128) - return 3072; - if (bits <= 192) - return 7680; - return 8192; -} - -function trySendNEWKEYS(kex) { - if (!kex._sentNEWKEYS) { - kex._protocol._debug && kex._protocol._debug( - 'Outbound: Sending NEWKEYS' - ); - const p = kex._protocol._packetRW.write.allocStartKEX; - const packet = kex._protocol._packetRW.write.alloc(1, true); - packet[p] = MESSAGE.NEWKEYS; - kex._protocol._cipher.encrypt( - kex._protocol._packetRW.write.finalize(packet, true) - ); - kex._sentNEWKEYS = true; - if (kex._protocol._strictMode) - kex._protocol._cipher.outSeqno = 0; - } -} +/***/ 6677: +/***/ ((__unused_webpack_module, exports) => { -module.exports = { - KexInit, - kexinit, - onKEXPayload, - DEFAULT_KEXINIT_CLIENT: new KexInit({ - kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']), - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - DEFAULT_KEXINIT_SERVER: new KexInit({ - kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']), - serverHostKey: DEFAULT_SERVER_HOST_KEY, - cs: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - sc: { - cipher: DEFAULT_CIPHER, - mac: DEFAULT_MAC, - compress: DEFAULT_COMPRESSION, - lang: [], - }, - }), - HANDLERS: { - [MESSAGE.KEXINIT]: handleKexInit, - }, -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map /***/ }), -/***/ 22218: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9031: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// TODO: -// * utilize `crypto.create(Private|Public)Key()` and `keyObject.export()` -// * handle multi-line header values (OpenSSH)? -// * more thorough validation? - -const { - createDecipheriv, - createECDH, - createHash, - createHmac, - createSign, - createVerify, - getCiphers, - sign: sign_, - verify: verify_, -} = __nccwpck_require__(6113); -const supportedOpenSSLCiphers = getCiphers(); - -const { Ber } = __nccwpck_require__(80970); -const bcrypt_pbkdf = (__nccwpck_require__(45447).pbkdf); - -const { CIPHER_INFO } = __nccwpck_require__(45708); -const { eddsaSupported, SUPPORTED_CIPHER } = __nccwpck_require__(36832); -const { - bufferSlice, - makeBufferParser, - readString, - readUInt32BE, - writeUInt32BE, -} = __nccwpck_require__(49475); - -const SYM_HASH_ALGO = Symbol('Hash Algorithm'); -const SYM_PRIV_PEM = Symbol('Private key PEM'); -const SYM_PUB_PEM = Symbol('Public key PEM'); -const SYM_PUB_SSH = Symbol('Public key SSH'); -const SYM_DECRYPTED = Symbol('Decrypted Key'); - -// Create OpenSSL cipher name -> SSH cipher name conversion table -const CIPHER_INFO_OPENSSL = Object.create(null); -{ - const keys = Object.keys(CIPHER_INFO); - for (let i = 0; i < keys.length; ++i) { - const cipherName = CIPHER_INFO[keys[i]].sslName; - if (!cipherName || CIPHER_INFO_OPENSSL[cipherName]) - continue; - CIPHER_INFO_OPENSSL[cipherName] = CIPHER_INFO[keys[i]]; - } +// types and functions copied over from viem so this library doesn't depend on it +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getAddress = getAddress; +exports.fromHex = fromHex; +exports.toHex = toHex; +exports.createSiweMessage = createSiweMessage; +function getAddress(address) { + if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { + throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); + } + return address.toLowerCase(); } - -const binaryKeyParser = makeBufferParser(); - -function makePEM(type, data) { - data = data.base64Slice(0, data.length); - let formatted = data.replace(/.{64}/g, '$&\n'); - if (data.length & 63) - formatted += '\n'; - return `-----BEGIN ${type} KEY-----\n${formatted}-----END ${type} KEY-----`; +function fromHex(hex) { + return parseInt(hex, 16); } - -function combineBuffers(buf1, buf2) { - const result = Buffer.allocUnsafe(buf1.length + buf2.length); - result.set(buf1, 0); - result.set(buf2, buf1.length); - return result; +function toHex(value) { + const bytes = new TextEncoder().encode(value); + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + return ('0x' + hex); } - -function skipFields(buf, nfields) { - const bufLen = buf.length; - let pos = (buf._pos || 0); - for (let i = 0; i < nfields; ++i) { - const left = (bufLen - pos); - if (pos >= bufLen || left < 4) - return false; - const len = readUInt32BE(buf, pos); - if (left < 4 + len) - return false; - pos += 4 + len; - } - buf._pos = pos; - return true; -} - -function genOpenSSLRSAPub(n, e) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.113549.1.1.1'); // rsaEncryption - // algorithm parameters (RSA has none) - asnWriter.writeNull(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.startSequence(); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHRSAPub(n, e) { - const publicKey = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + n.length); - - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-rsa', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, e.length, i); - publicKey.set(e, i += 4); - - writeUInt32BE(publicKey, n.length, i += e.length); - publicKey.set(n, i + 4); - - return publicKey; -} - -const genOpenSSLRSAPriv = (() => { - function genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(n, Ber.Integer); - asnWriter.writeBuffer(e, Ber.Integer); - asnWriter.writeBuffer(d, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(dmp1, Ber.Integer); - asnWriter.writeBuffer(dmq1, Ber.Integer); - asnWriter.writeBuffer(iqmp, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - - function bigIntFromBuffer(buf) { - return BigInt(`0x${buf.hexSlice(0, buf.length)}`); - } - - function bigIntToBuffer(bn) { - let hex = bn.toString(16); - if ((hex.length & 1) !== 0) { - hex = `0${hex}`; - } else { - const sigbit = hex.charCodeAt(0); - // BER/DER integers require leading zero byte to denote a positive value - // when first byte >= 0x80 - if (sigbit === 56/* '8' */ - || sigbit === 57/* '9' */ - || (sigbit >= 97/* 'a' */ && sigbit <= 102/* 'f' */)) { - hex = `00${hex}`; - } - } - return Buffer.from(hex, 'hex'); - } - - return function genOpenSSLRSAPriv(n, e, d, iqmp, p, q) { - const bn_d = bigIntFromBuffer(d); - const dmp1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(p) - 1n)); - const dmq1 = bigIntToBuffer(bn_d % (bigIntFromBuffer(q) - 1n)); - return makePEM('RSA PRIVATE', - genRSAASN1Buf(n, e, d, p, q, dmp1, dmq1, iqmp)); - }; -})(); - -function genOpenSSLDSAPub(p, q, g, y) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10040.4.1'); // id-dsa - // algorithm parameters - asnWriter.startSequence(); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHDSAPub(p, q, g, y) { - const publicKey = Buffer.allocUnsafe( - 4 + 7 + 4 + p.length + 4 + q.length + 4 + g.length + 4 + y.length - ); - - writeUInt32BE(publicKey, 7, 0); - publicKey.utf8Write('ssh-dss', 4, 7); - - let i = 4 + 7; - writeUInt32BE(publicKey, p.length, i); - publicKey.set(p, i += 4); - - writeUInt32BE(publicKey, q.length, i += p.length); - publicKey.set(q, i += 4); - - writeUInt32BE(publicKey, g.length, i += q.length); - publicKey.set(g, i += 4); - - writeUInt32BE(publicKey, y.length, i += g.length); - publicKey.set(y, i + 4); - - return publicKey; -} - -function genOpenSSLDSAPriv(p, q, g, y, x) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeInt(0x00, Ber.Integer); - asnWriter.writeBuffer(p, Ber.Integer); - asnWriter.writeBuffer(q, Ber.Integer); - asnWriter.writeBuffer(g, Ber.Integer); - asnWriter.writeBuffer(y, Ber.Integer); - asnWriter.writeBuffer(x, Ber.Integer); - asnWriter.endSequence(); - return makePEM('DSA PRIVATE', asnWriter.buffer); -} - -function genOpenSSLEdPub(pub) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHEdPub(pub) { - const publicKey = Buffer.allocUnsafe(4 + 11 + 4 + pub.length); - - writeUInt32BE(publicKey, 11, 0); - publicKey.utf8Write('ssh-ed25519', 4, 11); - - writeUInt32BE(publicKey, pub.length, 15); - publicKey.set(pub, 19); - - return publicKey; -} - -function genOpenSSLEdPriv(priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x00, Ber.Integer); - - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.3.101.112'); // id-Ed25519 - asnWriter.endSequence(); - - // PrivateKey - asnWriter.startSequence(Ber.OctetString); - asnWriter.writeBuffer(priv, Ber.OctetString); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPub(oid, Q) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // algorithm - asnWriter.startSequence(); - asnWriter.writeOID('1.2.840.10045.2.1'); // id-ecPublicKey - // algorithm parameters (namedCurve) - asnWriter.writeOID(oid); - asnWriter.endSequence(); - - // subjectPublicKey - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(Q.length); - asnWriter._buf.set(Q, asnWriter._offset); - asnWriter._offset += Q.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('PUBLIC', asnWriter.buffer); -} - -function genOpenSSHECDSAPub(oid, Q) { - let curveName; - switch (oid) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - curveName = 'nistp256'; - break; - case '1.3.132.0.34': - // secp384r1 - curveName = 'nistp384'; - break; - case '1.3.132.0.35': - // secp521r1 - curveName = 'nistp521'; - break; - default: - return; - } - - const publicKey = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + Q.length); - - writeUInt32BE(publicKey, 19, 0); - publicKey.utf8Write(`ecdsa-sha2-${curveName}`, 4, 19); - - writeUInt32BE(publicKey, 8, 23); - publicKey.utf8Write(curveName, 27, 8); - - writeUInt32BE(publicKey, Q.length, 35); - publicKey.set(Q, 39); - - return publicKey; -} - -function genOpenSSLECDSAPriv(oid, pub, priv) { - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - // version - asnWriter.writeInt(0x01, Ber.Integer); - // privateKey - asnWriter.writeBuffer(priv, Ber.OctetString); - // parameters (optional) - asnWriter.startSequence(0xA0); - asnWriter.writeOID(oid); - asnWriter.endSequence(); - // publicKey (optional) - asnWriter.startSequence(0xA1); - asnWriter.startSequence(Ber.BitString); - asnWriter.writeByte(0x00); - // XXX: hack to write a raw buffer without a tag -- yuck - asnWriter._ensure(pub.length); - asnWriter._buf.set(pub, asnWriter._offset); - asnWriter._offset += pub.length; - // end hack - asnWriter.endSequence(); - asnWriter.endSequence(); - asnWriter.endSequence(); - return makePEM('EC PRIVATE', asnWriter.buffer); -} - -function genOpenSSLECDSAPubFromPriv(curveName, priv) { - const tempECDH = createECDH(curveName); - tempECDH.setPrivateKey(priv); - return tempECDH.getPublicKey(); -} - -const BaseKey = { - sign: (() => { - if (typeof sign_ === 'function') { - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return sign_(algo, data, pem); - } catch (ex) { - return ex; - } - }; +/** + * Creates EIP-4361 formatted message. + */ +function createSiweMessage(parameters) { + var _a; + const { chainId, domain, expirationTime, issuedAt = new Date(), nonce, notBefore, requestId, resources, scheme, uri, version, } = parameters; + // Validate fields + { + if (!Number.isInteger(chainId)) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); + if (!domain) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); + if (nonce && nonce.length < 8) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); + if (!uri) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); + if (version !== '1') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`); + if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes('\n')) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); } - return function sign(data, algo) { - const pem = this[SYM_PRIV_PEM]; - if (pem === null) - return new Error('No private key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const signature = createSign(algo); - signature.update(data); - try { - return signature.sign(pem); - } catch (ex) { - return ex; - } - }; - })(), - verify: (() => { - if (typeof verify_ === 'function') { - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - try { - return verify_(algo, data, pem, signature); - } catch (ex) { - return ex; + // Construct message + const address = getAddress(parameters.address); + const origin = scheme ? `${scheme}://${domain}` : domain; + const statement = parameters.statement ? `${parameters.statement}\n` : ''; + const prefix = `${origin} wants you to sign in with your Ethereum account:\n${address}\n\n${statement}`; + let suffix = `URI: ${uri}\nVersion: ${version}\nChain ID: ${chainId}${nonce ? `\nNonce: ${nonce}` : ''}\nIssued At: ${issuedAt.toISOString()}`; + if (expirationTime) + suffix += `\nExpiration Time: ${expirationTime.toISOString()}`; + if (notBefore) + suffix += `\nNot Before: ${notBefore.toISOString()}`; + if (requestId) + suffix += `\nRequest ID: ${requestId}`; + if (resources) { + let content = '\nResources:'; + for (const resource of resources) { + if (!resource || typeof resource !== 'string') + throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); + content += `\n- ${resource}`; } - }; + suffix += content; } - return function verify(data, signature, algo) { - const pem = this[SYM_PUB_PEM]; - if (pem === null) - return new Error('No public key available'); - if (!algo || typeof algo !== 'string') - algo = this[SYM_HASH_ALGO]; - const verifier = createVerify(algo); - verifier.update(data); - try { - return verifier.verify(pem, signature); - } catch (ex) { - return ex; - } - }; - })(), - isPrivateKey: function isPrivateKey() { - return (this[SYM_PRIV_PEM] !== null); - }, - getPrivatePEM: function getPrivatePEM() { - return this[SYM_PRIV_PEM]; - }, - getPublicPEM: function getPublicPEM() { - return this[SYM_PUB_PEM]; - }, - getPublicSSH: function getPublicSSH() { - return this[SYM_PUB_SSH]; - }, - equals: function equals(key) { - const parsed = parseKey(key); - if (parsed instanceof Error) - return false; - return ( - this.type === parsed.type - && this[SYM_PRIV_PEM] === parsed[SYM_PRIV_PEM] - && this[SYM_PUB_PEM] === parsed[SYM_PUB_PEM] - && this[SYM_PUB_SSH].equals(parsed[SYM_PUB_SSH]) - ); - }, -}; - - -function OpenSSH_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; + return `${prefix}\n${suffix}`; } -OpenSSH_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/; - OpenSSH_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let ret; - const data = Buffer.from(m[1], 'base64'); - if (data.length < 31) // magic (+ magic null term.) + minimum field lengths - return new Error('Malformed OpenSSH private key'); - const magic = data.utf8Slice(0, 15); - if (magic !== 'openssh-key-v1\0') - return new Error(`Unsupported OpenSSH key magic: ${magic}`); - - const cipherName = readString(data, 15, true); - if (cipherName === undefined) - return new Error('Malformed OpenSSH private key'); - if (cipherName !== 'none' && SUPPORTED_CIPHER.indexOf(cipherName) === -1) - return new Error(`Unsupported cipher for OpenSSH key: ${cipherName}`); - - const kdfName = readString(data, data._pos, true); - if (kdfName === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'none') { - if (cipherName === 'none') - return new Error('Malformed OpenSSH private key'); - if (kdfName !== 'bcrypt') - return new Error(`Unsupported kdf name for OpenSSH key: ${kdfName}`); - if (!passphrase) { - return new Error( - 'Encrypted private OpenSSH key detected, but no passphrase given' - ); - } - } else if (cipherName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - let encInfo; - let cipherKey; - let cipherIV; - if (cipherName !== 'none') - encInfo = CIPHER_INFO[cipherName]; - const kdfOptions = readString(data, data._pos); - if (kdfOptions === undefined) - return new Error('Malformed OpenSSH private key'); - if (kdfOptions.length) { - switch (kdfName) { - case 'none': - return new Error('Malformed OpenSSH private key'); - case 'bcrypt': { - /* - string salt - uint32 rounds - */ - const salt = readString(kdfOptions, 0); - if (salt === undefined || kdfOptions._pos + 4 > kdfOptions.length) - return new Error('Malformed OpenSSH private key'); - const rounds = readUInt32BE(kdfOptions, kdfOptions._pos); - const gen = Buffer.allocUnsafe(encInfo.keyLen + encInfo.ivLen); - const r = bcrypt_pbkdf(passphrase, - passphrase.length, - salt, - salt.length, - gen, - gen.length, - rounds); - if (r !== 0) - return new Error('Failed to generate information to decrypt key'); - cipherKey = bufferSlice(gen, 0, encInfo.keyLen); - cipherIV = bufferSlice(gen, encInfo.keyLen, gen.length); - break; - } - } - } else if (kdfName !== 'none') { - return new Error('Malformed OpenSSH private key'); - } - - if (data._pos + 3 >= data.length) - return new Error('Malformed OpenSSH private key'); - const keyCount = readUInt32BE(data, data._pos); - data._pos += 4; - - if (keyCount > 0) { - // TODO: place sensible limit on max `keyCount` - - // Read public keys first - for (let i = 0; i < keyCount; ++i) { - const pubData = readString(data, data._pos); - if (pubData === undefined) - return new Error('Malformed OpenSSH private key'); - const type = readString(pubData, 0, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - } - - let privBlob = readString(data, data._pos); - if (privBlob === undefined) - return new Error('Malformed OpenSSH private key'); - - if (cipherKey !== undefined) { - // Encrypted private key(s) - if (privBlob.length < encInfo.blockLen - || (privBlob.length % encInfo.blockLen) !== 0) { - return new Error('Malformed OpenSSH private key'); - } - try { - const options = { authTagLength: encInfo.authLen }; - const decipher = createDecipheriv(encInfo.sslName, - cipherKey, - cipherIV, - options); - decipher.setAutoPadding(false); - if (encInfo.authLen > 0) { - if (data.length - data._pos < encInfo.authLen) - return new Error('Malformed OpenSSH private key'); - decipher.setAuthTag( - bufferSlice(data, data._pos, data._pos += encInfo.authLen) - ); - } - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } - } - // Nothing should we follow the private key(s), except a possible - // authentication tag for relevant ciphers - if (data._pos !== data.length) - return new Error('Malformed OpenSSH private key'); +//# sourceMappingURL=ethereum.js.map - ret = parseOpenSSHPrivKeys(privBlob, keyCount, cipherKey !== undefined); - } else { - ret = []; - } - if (ret instanceof Error) - return ret; - // This will need to change if/when OpenSSH ever starts storing multiple - // keys in their key files - return ret[0]; - }; +/***/ }), - function parseOpenSSHPrivKeys(data, nkeys, decrypted) { - const keys = []; - /* - uint32 checkint - uint32 checkint - string privatekey1 - string comment1 - string privatekey2 - string comment2 - ... - string privatekeyN - string commentN - char 1 - char 2 - char 3 - ... - char padlen % 255 - */ - if (data.length < 8) - return new Error('Malformed OpenSSH private key'); - const check1 = readUInt32BE(data, 0); - const check2 = readUInt32BE(data, 4); - if (check1 !== check2) { - if (decrypted) { - return new Error( - 'OpenSSH key integrity check failed -- bad passphrase?' - ); - } - return new Error('OpenSSH key integrity check failed'); - } - data._pos = 8; - let i; - let oid; - for (i = 0; i < nkeys; ++i) { - let algo; - let privPEM; - let pubPEM; - let pubSSH; - // The OpenSSH documentation for the key format actually lies, the - // entirety of the private key content is not contained with a string - // field, it's actually the literal contents of the private key, so to be - // able to find the end of the key data you need to know the layout/format - // of each key type ... - const type = readString(data, data._pos, true); - if (type === undefined) - return new Error('Malformed OpenSSH private key'); - - switch (type) { - case 'ssh-rsa': { - /* - string n -- public - string e -- public - string d -- private - string iqmp -- private - string p -- private - string q -- private - */ - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH private key'); - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed OpenSSH private key'); - const d = readString(data, data._pos); - if (d === undefined) - return new Error('Malformed OpenSSH private key'); - const iqmp = readString(data, data._pos); - if (iqmp === undefined) - return new Error('Malformed OpenSSH private key'); - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - /* - string p -- public - string q -- public - string g -- public - string y -- public - string x -- private - */ - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed OpenSSH private key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH private key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH private key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH private key'); - const x = readString(data, data._pos); - if (x === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - if (!eddsaSupported) - return new Error(`Unsupported OpenSSH private key type: ${type}`); - /* - * string public key - * string private key + public key - */ - const edpub = readString(data, data._pos); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH private key'); - const edpriv = readString(data, data._pos); - if (edpriv === undefined || edpriv.length !== 64) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - privPEM = genOpenSSLEdPriv(bufferSlice(edpriv, 0, 32)); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - /* - string curve name - string Q -- public - string d -- private - */ - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH private key'); - const ecpub = readString(data, data._pos); - if (ecpub === undefined) - return new Error('Malformed OpenSSH private key'); - const ecpriv = readString(data, data._pos); - if (ecpriv === undefined) - return new Error('Malformed OpenSSH private key'); - - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - privPEM = genOpenSSLECDSAPriv(oid, ecpub, ecpriv); - break; - } - default: - return new Error(`Unsupported OpenSSH private key type: ${type}`); - } +/***/ 7906: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const privComment = readString(data, data._pos, true); - if (privComment === undefined) - return new Error('Malformed OpenSSH private key'); +"use strict"; - keys.push( - new OpenSSH_Private(type, privComment, privPEM, pubPEM, pubSSH, algo, - decrypted) - ); +/* eslint-disable @typescript-eslint/ban-ts-comment */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebAuthnUnknownError = exports.WebAuthnError = void 0; +exports.isWebAuthnError = isWebAuthnError; +exports.identifyRegistrationError = identifyRegistrationError; +exports.identifyAuthenticationError = identifyAuthenticationError; +const webauthn_1 = __nccwpck_require__(9451); +/** + * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented + * errors in the spec was raised after calling `navigator.credentials.create()` or + * `navigator.credentials.get()`: + * + * - `AbortError` + * - `ConstraintError` + * - `InvalidStateError` + * - `NotAllowedError` + * - `NotSupportedError` + * - `SecurityError` + * - `TypeError` + * - `UnknownError` + * + * Error messages were determined through investigation of the spec to determine under which + * scenarios a given error would be raised. + */ +class WebAuthnError extends Error { + constructor({ message, code, cause, name, }) { + var _a; + // @ts-ignore: help Rollup understand that `cause` is okay to set + super(message, { cause }); + this.__isWebAuthnError = true; + this.name = (_a = name !== null && name !== void 0 ? name : (cause instanceof Error ? cause.name : undefined)) !== null && _a !== void 0 ? _a : 'Unknown Error'; + this.code = code; } - let cnt = 0; - for (i = data._pos; i < data.length; ++i) { - if (data[i] !== (++cnt % 255)) - return new Error('Malformed OpenSSH private key'); +} +exports.WebAuthnError = WebAuthnError; +/** + * Error class for unknown WebAuthn errors. + * Wraps unexpected errors that don't match known WebAuthn error conditions. + */ +class WebAuthnUnknownError extends WebAuthnError { + constructor(message, originalError) { + super({ + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: originalError, + message, + }); + this.name = 'WebAuthnUnknownError'; + this.originalError = originalError; } - - return keys; - } } - - -function OpenSSH_Old_Private(type, comment, privPEM, pubPEM, pubSSH, algo, - decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; +exports.WebAuthnUnknownError = WebAuthnUnknownError; +/** + * Type guard to check if an error is a WebAuthnError. + * @param {unknown} error - The error to check + * @returns {boolean} True if the error is a WebAuthnError + */ +function isWebAuthnError(error) { + return typeof error === 'object' && error !== null && '__isWebAuthnError' in error; } -OpenSSH_Old_Private.prototype = BaseKey; -{ - const regexp = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/; - OpenSSH_Old_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - let privBlob = Buffer.from(m[3], 'base64'); - let headers = m[2]; - let decrypted = false; - if (headers !== undefined) { - // encrypted key - headers = headers.split(/\r\n|\n/g); - for (let i = 0; i < headers.length; ++i) { - const header = headers[i]; - let sepIdx = header.indexOf(':'); - if (header.slice(0, sepIdx) === 'DEK-Info') { - const val = header.slice(sepIdx + 2); - sepIdx = val.indexOf(','); - if (sepIdx === -1) - continue; - const cipherName = val.slice(0, sepIdx).toLowerCase(); - if (supportedOpenSSLCiphers.indexOf(cipherName) === -1) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const encInfo = CIPHER_INFO_OPENSSL[cipherName]; - if (!encInfo) { - return new Error( - `Cipher (${cipherName}) not supported ` - + 'for encrypted OpenSSH private key' - ); - } - const cipherIV = Buffer.from(val.slice(sepIdx + 1), 'hex'); - if (cipherIV.length !== encInfo.ivLen) - return new Error('Malformed encrypted OpenSSH private key'); - if (!passphrase) { - return new Error( - 'Encrypted OpenSSH private key detected, but no passphrase given' - ); - } - const ivSlice = bufferSlice(cipherIV, 0, 8); - let cipherKey = createHash('md5') - .update(passphrase) - .update(ivSlice) - .digest(); - while (cipherKey.length < encInfo.keyLen) { - cipherKey = combineBuffers( - cipherKey, - createHash('md5') - .update(cipherKey) - .update(passphrase) - .update(ivSlice) - .digest() - ); - } - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(cipherName, cipherKey, cipherIV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - decrypted = true; - } catch (ex) { - return ex; - } +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialCreationOptions} params.options - The options passed to credentials.create() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + */ +function identifyRegistrationError({ error, options, }) { + var _a, _b, _c; + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); + } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Registration ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); } - } } - - let type; - let privPEM; - let pubPEM; - let pubSSH; - let algo; - let reader; - let errMsg = 'Malformed OpenSSH private key'; - if (decrypted) - errMsg += '. Bad passphrase?'; - switch (m[1]) { - case 'RSA': - type = 'ssh-rsa'; - privPEM = makePEM('RSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const n = reader.readString(Ber.Integer, true); - if (n === null) - return new Error(errMsg); - const e = reader.readString(Ber.Integer, true); - if (e === null) - return new Error(errMsg); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'DSA': - type = 'ssh-dss'; - privPEM = makePEM('DSA PRIVATE', privBlob); - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - const p = reader.readString(Ber.Integer, true); - if (p === null) - return new Error(errMsg); - const q = reader.readString(Ber.Integer, true); - if (q === null) - return new Error(errMsg); - const g = reader.readString(Ber.Integer, true); - if (g === null) - return new Error(errMsg); - const y = reader.readString(Ber.Integer, true); - if (y === null) - return new Error(errMsg); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - } catch { - return new Error(errMsg); - } - algo = 'sha1'; - break; - case 'EC': { - let ecSSLName; - let ecPriv; - let ecOID; - try { - reader = new Ber.Reader(privBlob); - reader.readSequence(); - reader.readInt(); // skip version - ecPriv = reader.readString(Ber.OctetString, true); - reader.readByte(); // Skip "complex" context type byte - const offset = reader.readLength(); // Skip context length - if (offset !== null) { - reader._offset = offset; - ecOID = reader.readOID(); - if (ecOID === null) - return new Error(errMsg); - switch (ecOID) { - case '1.2.840.10045.3.1.7': - // prime256v1/secp256r1 - ecSSLName = 'prime256v1'; - type = 'ecdsa-sha2-nistp256'; - algo = 'sha256'; - break; - case '1.3.132.0.34': - // secp384r1 - ecSSLName = 'secp384r1'; - type = 'ecdsa-sha2-nistp384'; - algo = 'sha384'; - break; - case '1.3.132.0.35': - // secp521r1 - ecSSLName = 'secp521r1'; - type = 'ecdsa-sha2-nistp521'; - algo = 'sha512'; - break; - default: - return new Error(`Unsupported private key EC OID: ${ecOID}`); - } - } else { - return new Error(errMsg); - } - } catch { - return new Error(errMsg); - } - privPEM = makePEM('EC PRIVATE', privBlob); - const pubBlob = genOpenSSLECDSAPubFromPriv(ecSSLName, ecPriv); - pubPEM = genOpenSSLECDSAPub(ecOID, pubBlob); - pubSSH = genOpenSSHECDSAPub(ecOID, pubBlob); - break; - } + else if (error.name === 'ConstraintError') { + if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4) + return new WebAuthnError({ + message: 'Discoverable credentials were required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT', + cause: error, + }); + } + else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === 'conditional' && + ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === 'required') { + // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4) + return new WebAuthnError({ + message: 'User verification was required during automatic registration but it could not be performed', + code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE', + cause: error, + }); + } + else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === 'required') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5) + return new WebAuthnError({ + message: 'User verification was required but no available authenticator supported it', + code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT', + cause: error, + }); + } } - - return new OpenSSH_Old_Private(type, '', privPEM, pubPEM, pubSSH, algo, - decrypted); - }; -} - - -function PPK_Private(type, comment, privPEM, pubPEM, pubSSH, algo, decrypted) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = privPEM; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = decrypted; -} -PPK_Private.prototype = BaseKey; -{ - const EMPTY_PASSPHRASE = Buffer.alloc(0); - const PPK_IV = Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - const PPK_PP1 = Buffer.from([0, 0, 0, 0]); - const PPK_PP2 = Buffer.from([0, 0, 0, 1]); - const regexp = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/; - PPK_Private.parse = (str, passphrase) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = key type - // m[2] = encryption type - // m[3] = comment - // m[4] = base64-encoded public key data: - // for "ssh-rsa": - // string "ssh-rsa" - // mpint e (public exponent) - // mpint n (modulus) - // for "ssh-dss": - // string "ssh-dss" - // mpint p (modulus) - // mpint q (prime) - // mpint g (base number) - // mpint y (public key parameter: g^x mod p) - // m[5] = base64-encoded private key data: - // for "ssh-rsa": - // mpint d (private exponent) - // mpint p (prime 1) - // mpint q (prime 2) - // mpint iqmp ([inverse of q] mod p) - // for "ssh-dss": - // mpint x (private key parameter) - // m[6] = SHA1 HMAC over: - // string name of algorithm ("ssh-dss", "ssh-rsa") - // string encryption type - // string comment - // string public key data - // string private-plaintext (including the final padding) - const cipherName = m[2]; - const encrypted = (cipherName !== 'none'); - if (encrypted && !passphrase) { - return new Error( - 'Encrypted PPK private key detected, but no passphrase given' - ); + else if (error.name === 'InvalidStateError') { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3) + return new WebAuthnError({ + message: 'The authenticator was previously registered', + code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED', + cause: error, + }); + } + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); } - - let privBlob = Buffer.from(m[5], 'base64'); - - if (encrypted) { - const encInfo = CIPHER_INFO[cipherName]; - let cipherKey = combineBuffers( - createHash('sha1').update(PPK_PP1).update(passphrase).digest(), - createHash('sha1').update(PPK_PP2).update(passphrase).digest() - ); - if (cipherKey.length > encInfo.keyLen) - cipherKey = bufferSlice(cipherKey, 0, encInfo.keyLen); - try { - const decipher = createDecipheriv(encInfo.sslName, cipherKey, PPK_IV); - decipher.setAutoPadding(false); - privBlob = combineBuffers(decipher.update(privBlob), - decipher.final()); - } catch (ex) { - return ex; - } + else if (error.name === 'NotSupportedError') { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key'); + if (validPubKeyCredParams.length === 0) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10) + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS', + cause: error, + }); + } + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2) + return new WebAuthnError({ + message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms', + code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG', + cause: error, + }); } - - const type = m[1]; - const comment = m[3]; - const pubBlob = Buffer.from(m[4], 'base64'); - - const mac = m[6]; - const typeLen = type.length; - const cipherNameLen = cipherName.length; - const commentLen = Buffer.byteLength(comment); - const pubLen = pubBlob.length; - const privLen = privBlob.length; - const macData = Buffer.allocUnsafe(4 + typeLen - + 4 + cipherNameLen - + 4 + commentLen - + 4 + pubLen - + 4 + privLen); - let p = 0; - - writeUInt32BE(macData, typeLen, p); - macData.utf8Write(type, p += 4, typeLen); - writeUInt32BE(macData, cipherNameLen, p += typeLen); - macData.utf8Write(cipherName, p += 4, cipherNameLen); - writeUInt32BE(macData, commentLen, p += cipherNameLen); - macData.utf8Write(comment, p += 4, commentLen); - writeUInt32BE(macData, pubLen, p += commentLen); - macData.set(pubBlob, p += 4); - writeUInt32BE(macData, privLen, p += pubLen); - macData.set(privBlob, p + 4); - - if (!passphrase) - passphrase = EMPTY_PASSPHRASE; - - const calcMAC = createHmac( - 'sha1', - createHash('sha1') - .update('putty-private-key-file-mac-key') - .update(passphrase) - .digest() - ).update(macData).digest('hex'); - - if (calcMAC !== mac) { - if (encrypted) { - return new Error( - 'PPK private key integrity check failed -- bad passphrase?' - ); - } - return new Error('PPK private key integrity check failed'); + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rp.id !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } } - - let pubPEM; - let pubSSH; - let privPEM; - pubBlob._pos = 0; - skipFields(pubBlob, 1); // skip (duplicate) key type - switch (type) { - case 'ssh-rsa': { - const e = readString(pubBlob, pubBlob._pos); - if (e === undefined) - return new Error('Malformed PPK public key'); - const n = readString(pubBlob, pubBlob._pos); - if (n === undefined) - return new Error('Malformed PPK public key'); - const d = readString(privBlob, 0); - if (d === undefined) - return new Error('Malformed PPK private key'); - const p = readString(privBlob, privBlob._pos); - if (p === undefined) - return new Error('Malformed PPK private key'); - const q = readString(privBlob, privBlob._pos); - if (q === undefined) - return new Error('Malformed PPK private key'); - const iqmp = readString(privBlob, privBlob._pos); - if (iqmp === undefined) - return new Error('Malformed PPK private key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - privPEM = genOpenSSLRSAPriv(n, e, d, iqmp, p, q); - break; - } - case 'ssh-dss': { - const p = readString(pubBlob, pubBlob._pos); - if (p === undefined) - return new Error('Malformed PPK public key'); - const q = readString(pubBlob, pubBlob._pos); - if (q === undefined) - return new Error('Malformed PPK public key'); - const g = readString(pubBlob, pubBlob._pos); - if (g === undefined) - return new Error('Malformed PPK public key'); - const y = readString(pubBlob, pubBlob._pos); - if (y === undefined) - return new Error('Malformed PPK public key'); - const x = readString(privBlob, 0); - if (x === undefined) - return new Error('Malformed PPK private key'); - - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - privPEM = genOpenSSLDSAPriv(p, q, g, y, x); - break; - } + else if (error.name === 'TypeError') { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5) + return new WebAuthnError({ + message: 'User ID was not between 1 and 64 characters', + code: 'ERROR_INVALID_USER_ID_LENGTH', + cause: error, + }); + } } - - return new PPK_Private(type, comment, privPEM, pubPEM, pubSSH, 'sha1', - encrypted); - }; -} - - -function OpenSSH_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; -} -OpenSSH_Public.prototype = BaseKey; -{ - let regexp; - if (eddsaSupported) - regexp = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - else - regexp = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; - OpenSSH_Public.parse = (str) => { - const m = regexp.exec(str); - if (m === null) - return null; - // m[1] = full type - // m[2] = base type - // m[3] = base64-encoded public key - // m[4] = comment - - const fullType = m[1]; - const baseType = m[2]; - const data = Buffer.from(m[3], 'base64'); - const comment = (m[4] || ''); - - const type = readString(data, data._pos, true); - if (type === undefined || type.indexOf(baseType) !== 0) - return new Error('Malformed OpenSSH public key'); - - return parseDER(data, baseType, comment, fullType); - }; -} - - -function RFC4716_Public(type, comment, pubPEM, pubSSH, algo) { - this.type = type; - this.comment = comment; - this[SYM_PRIV_PEM] = null; - this[SYM_PUB_PEM] = pubPEM; - this[SYM_PUB_SSH] = pubSSH; - this[SYM_HASH_ALGO] = algo; - this[SYM_DECRYPTED] = false; + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new credential', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); + } + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); } -RFC4716_Public.prototype = BaseKey; -{ - const regexp = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/; - const RE_DATA = /^[A-Z0-9a-z/+=\r\n]+$/; - const RE_HEADER = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm; - const RE_HEADER_ENDS = /\\\r?\n/g; - RFC4716_Public.parse = (str) => { - let m = regexp.exec(str); - if (m === null) - return null; - - const body = m[1]; - let dataStart = 0; - let comment = ''; - - while (m = RE_HEADER.exec(body)) { - const headerName = m[1]; - const headerValue = m[2].replace(RE_HEADER_ENDS, ''); - if (headerValue.length > 1024) { - RE_HEADER.lastIndex = 0; - return new Error('Malformed RFC4716 public key'); - } - - dataStart = RE_HEADER.lastIndex; - - if (headerName.toLowerCase() === 'comment') { - comment = headerValue; - if (comment.length > 1 - && comment.charCodeAt(0) === 34/* '"' */ - && comment.charCodeAt(comment.length - 1) === 34/* '"' */) { - comment = comment.slice(1, -1); +/** + * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`. + * Maps browser errors to specific WebAuthn error codes for better debugging. + * @param {Object} params - Error identification parameters + * @param {Error} params.error - The error thrown by the browser + * @param {CredentialRequestOptions} params.options - The options passed to credentials.get() + * @returns {WebAuthnError} A WebAuthnError with a specific error code + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + */ +function identifyAuthenticationError({ error, options, }) { + const { publicKey } = options; + if (!publicKey) { + throw Error('options was missing required publicKey property'); + } + if (error.name === 'AbortError') { + if (options.signal instanceof AbortSignal) { + // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16) + return new WebAuthnError({ + message: 'Authentication ceremony was sent an abort signal', + code: 'ERROR_CEREMONY_ABORTED', + cause: error, + }); } - } } - - let data = body.slice(dataStart); - if (!RE_DATA.test(data)) - return new Error('Malformed RFC4716 public key'); - - data = Buffer.from(data, 'base64'); - - const type = readString(data, 0, true); - if (type === undefined) - return new Error('Malformed RFC4716 public key'); - - let pubPEM = null; - let pubSSH = null; - switch (type) { - case 'ssh-rsa': { - const e = readString(data, data._pos); - if (e === undefined) - return new Error('Malformed RFC4716 public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos); - if (p === undefined) - return new Error('Malformed RFC4716 public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed RFC4716 public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed RFC4716 public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed RFC4716 public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - break; - } - default: - return new Error('Malformed RFC4716 public key'); + else if (error.name === 'NotAllowedError') { + /** + * Pass the error directly through. Platforms are overloading this error beyond what the spec + * defines and we don't want to overwrite potentially useful error messages. + */ + return new WebAuthnError({ + message: error.message, + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); } - - return new RFC4716_Public(type, comment, pubPEM, pubSSH, 'sha1'); - }; -} - - -function parseDER(data, baseType, comment, fullType) { - if (!isSupportedKeyType(baseType)) - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - - let algo; - let oid; - let pubPEM = null; - let pubSSH = null; - - switch (baseType) { - case 'ssh-rsa': { - const e = readString(data, data._pos || 0); - if (e === undefined) - return new Error('Malformed OpenSSH public key'); - const n = readString(data, data._pos); - if (n === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLRSAPub(n, e); - pubSSH = genOpenSSHRSAPub(n, e); - algo = 'sha1'; - break; - } - case 'ssh-dss': { - const p = readString(data, data._pos || 0); - if (p === undefined) - return new Error('Malformed OpenSSH public key'); - const q = readString(data, data._pos); - if (q === undefined) - return new Error('Malformed OpenSSH public key'); - const g = readString(data, data._pos); - if (g === undefined) - return new Error('Malformed OpenSSH public key'); - const y = readString(data, data._pos); - if (y === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLDSAPub(p, q, g, y); - pubSSH = genOpenSSHDSAPub(p, q, g, y); - algo = 'sha1'; - break; - } - case 'ssh-ed25519': { - const edpub = readString(data, data._pos || 0); - if (edpub === undefined || edpub.length !== 32) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLEdPub(edpub); - pubSSH = genOpenSSHEdPub(edpub); - algo = null; - break; - } - case 'ecdsa-sha2-nistp256': - algo = 'sha256'; - oid = '1.2.840.10045.3.1.7'; - // FALLTHROUGH - case 'ecdsa-sha2-nistp384': - if (algo === undefined) { - algo = 'sha384'; - oid = '1.3.132.0.34'; - } - // FALLTHROUGH - case 'ecdsa-sha2-nistp521': { - if (algo === undefined) { - algo = 'sha512'; - oid = '1.3.132.0.35'; - } - // TODO: validate curve name against type - if (!skipFields(data, 1)) // Skip curve name - return new Error('Malformed OpenSSH public key'); - const ecpub = readString(data, data._pos || 0); - if (ecpub === undefined) - return new Error('Malformed OpenSSH public key'); - pubPEM = genOpenSSLECDSAPub(oid, ecpub); - pubSSH = genOpenSSHECDSAPub(oid, ecpub); - break; + else if (error.name === 'SecurityError') { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5) + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: 'ERROR_INVALID_DOMAIN', + cause: error, + }); + } + else if (publicKey.rpId !== effectiveDomain) { + // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6) + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: 'ERROR_INVALID_RP_ID', + cause: error, + }); + } } - default: - return new Error(`Unsupported OpenSSH public key type: ${baseType}`); - } - - return new OpenSSH_Public(fullType, comment, pubPEM, pubSSH, algo); -} - -function isSupportedKeyType(type) { - switch (type) { - case 'ssh-rsa': - case 'ssh-dss': - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': - return true; - case 'ssh-ed25519': - if (eddsaSupported) - return true; - // FALLTHROUGH - default: - return false; - } -} - -function isParsedKey(val) { - if (!val) - return false; - return (typeof val[SYM_DECRYPTED] === 'boolean'); -} - -function parseKey(data, passphrase) { - if (isParsedKey(data)) - return data; - - let origBuffer; - if (Buffer.isBuffer(data)) { - origBuffer = data; - data = data.utf8Slice(0, data.length).trim(); - } else if (typeof data === 'string') { - data = data.trim(); - } else { - return new Error('Key data must be a Buffer or string'); - } - - // eslint-disable-next-line eqeqeq - if (passphrase != undefined) { - if (typeof passphrase === 'string') - passphrase = Buffer.from(passphrase); - else if (!Buffer.isBuffer(passphrase)) - return new Error('Passphrase must be a string or Buffer when supplied'); - } - - let ret; - - // First try as printable string format (e.g. PEM) - - // Private keys - if ((ret = OpenSSH_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = OpenSSH_Old_Private.parse(data, passphrase)) !== null) - return ret; - if ((ret = PPK_Private.parse(data, passphrase)) !== null) - return ret; - - // Public keys - if ((ret = OpenSSH_Public.parse(data)) !== null) - return ret; - if ((ret = RFC4716_Public.parse(data)) !== null) - return ret; - - // Finally try as a binary format if we were originally passed binary data - if (origBuffer) { - binaryKeyParser.init(origBuffer, 0); - const type = binaryKeyParser.readString(true); - if (type !== undefined) { - data = binaryKeyParser.readRaw(); - if (data !== undefined) { - ret = parseDER(data, type, '', type); - // Ignore potentially useless errors in case the data was not actually - // in the binary format - if (ret instanceof Error) - ret = null; - } + else if (error.name === 'UnknownError') { + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1) + // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12) + return new WebAuthnError({ + message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature', + code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR', + cause: error, + }); } - binaryKeyParser.clear(); - } - - if (ret) - return ret; - - return new Error('Unsupported key format'); + return new WebAuthnError({ + message: 'a Non-Webauthn related error has occurred', + code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', + cause: error, + }); } - -module.exports = { - isParsedKey, - isSupportedKeyType, - parseDERKey: (data, type) => parseDER(data, type, '', type), - parseKey, -}; - +//# sourceMappingURL=webauthn.errors.js.map /***/ }), -/***/ 47609: +/***/ 9451: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const assert = __nccwpck_require__(39491); -const { inspect } = __nccwpck_require__(73837); - -// Only use this for integers! Decimal numbers do not work with this function. -function addNumericalSeparator(val) { - let res = ''; - let i = val.length; - const start = val[0] === '-' ? 1 : 0; - for (; i >= start + 4; i -= 3) - res = `_${val.slice(i - 3, i)}${res}`; - return `${val.slice(0, i)}${res}`; -} - -function oneOf(expected, thing) { - assert(typeof thing === 'string', '`thing` has to be of type string'); - if (Array.isArray(expected)) { - const len = expected.length; - assert(len > 0, 'At least one expected value needs to be specified'); - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` - + expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0; +exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions; +exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions; +exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse; +exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse; +exports.isValidDomain = isValidDomain; +exports.createCredential = createCredential; +exports.getCredential = getCredential; +exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions; +exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions; +const tslib_1 = __nccwpck_require__(4351); +const base64url_1 = __nccwpck_require__(3649); +const errors_1 = __nccwpck_require__(9938); +const helpers_1 = __nccwpck_require__(4044); +const webauthn_errors_1 = __nccwpck_require__(7906); +Object.defineProperty(exports, "identifyAuthenticationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } })); +Object.defineProperty(exports, "identifyRegistrationError", ({ enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } })); +Object.defineProperty(exports, "isWebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } })); +Object.defineProperty(exports, "WebAuthnError", ({ enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } })); +/** + * WebAuthn abort service to manage ceremony cancellation. + * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors. + * + * @experimental This class is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies} + */ +class WebAuthnAbortService { + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal() { + // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get() + if (this.controller) { + const abortError = new Error('Cancelling existing WebAuthn API call for new one'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + } + const newController = new AbortController(); + this.controller = newController; + return newController.signal; + } + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony() { + if (this.controller) { + const abortError = new Error('Manually cancelling existing WebAuthn API call'); + abortError.name = 'AbortError'; + this.controller.abort(abortError); + this.controller = undefined; + } } - return `of ${thing} ${expected[0]}`; - } - return `of ${thing} ${String(expected)}`; } - - -exports.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error { - constructor(message) { - super(); - Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION); - - const suffix = 'This is caused by either a bug in ssh2 ' - + 'or incorrect usage of ssh2 internals.\n' - + 'Please open an issue with this stack trace at ' - + 'https://github.com/mscdex/ssh2/issues\n'; - - this.message = (message === undefined ? suffix : `${message}\n${suffix}`); - } -}; - -const MAX_32BIT_INT = 2 ** 32; -const MAX_32BIT_BIGINT = (() => { - try { - return new Function('return 2n ** 32n')(); - } catch {} -})(); -exports.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError { - constructor(str, range, input, replaceDefaultBoolean) { - super(); - Error.captureStackTrace(this, ERR_OUT_OF_RANGE); - - assert(range, 'Missing "range" argument'); - let msg = (replaceDefaultBoolean - ? str - : `The value of "${str}" is out of range.`); - let received; - if (Number.isInteger(input) && Math.abs(input) > MAX_32BIT_INT) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === 'bigint') { - received = String(input); - if (input > MAX_32BIT_BIGINT || input < -MAX_32BIT_BIGINT) - received = addNumericalSeparator(received); - received += 'n'; - } else { - received = inspect(input); +exports.WebAuthnAbortService = WebAuthnAbortService; +/** + * Singleton instance to ensure only one WebAuthn ceremony is active at a time. + * This prevents "operation already in progress" errors when retrying WebAuthn operations. + * + * @experimental This instance is experimental and may change in future releases + */ +exports.webAuthnAbortService = new WebAuthnAbortService(); +/** + * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON} + */ +function deserializeCredentialCreationOptions(options) { + if (!options) { + throw new Error('Credential creation options are required'); } - msg += ` It must be ${range}. Received ${received}`; - - this.message = msg; - } -}; - -class ERR_INVALID_ARG_TYPE extends TypeError { - constructor(name, expected, actual) { - super(); - Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE); - - assert(typeof name === 'string', `'name' must be a string`); - - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && expected.startsWith('not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; + // Check if the native parseCreationOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseCreationOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseCreationOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseCreationOptionsFromJSON( + /** we assert the options here as typescript still doesn't know about future webauthn types */ + options); } - - let msg; - if (name.endsWith(' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = (name.includes('.') ? 'property' : 'argument'); - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "user", "excludeCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + // Convert user.id from base64url to ArrayBuffer + const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer }); + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge, + user }); + // Only add excludeCredentials if it exists + if (excludeCredentials && excludeCredentials.length > 0) { + result.excludeCredentials = new Array(excludeCredentials.length); + for (let i = 0; i < excludeCredentials.length; i++) { + const cred = excludeCredentials[i]; + result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } } - - msg += `. Received type ${typeof actual}`; - - this.message = msg; - } -} -exports.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE; - -exports.validateNumber = function validateNumber(value, name) { - if (typeof value !== 'number') - throw new ERR_INVALID_ARG_TYPE(name, 'number', value); -}; - - -/***/ }), - -/***/ 49475: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const Ber = (__nccwpck_require__(80970).Ber); - -let DISCONNECT_REASON; - -const FastBuffer = Buffer[Symbol.species]; -const TypedArrayFill = Object.getPrototypeOf(Uint8Array.prototype).fill; - -function readUInt32BE(buf, offset) { - return (buf[offset++] * 16777216) - + (buf[offset++] * 65536) - + (buf[offset++] * 256) - + buf[offset]; -} - -function bufferCopy(src, dest, srcStart, srcEnd, destStart) { - if (!destStart) - destStart = 0; - if (srcEnd > src.length) - srcEnd = src.length; - let nb = srcEnd - srcStart; - const destLeft = (dest.length - destStart); - if (nb > destLeft) - nb = destLeft; - dest.set(new Uint8Array(src.buffer, src.byteOffset + srcStart, nb), - destStart); - return nb; -} - -function bufferSlice(buf, start, end) { - if (end === undefined) - end = buf.length; - return new FastBuffer(buf.buffer, buf.byteOffset + start, end - start); -} - -function makeBufferParser() { - let pos = 0; - let buffer; - - const self = { - init: (buf, start) => { - buffer = buf; - pos = (typeof start === 'number' ? start : 0); - }, - pos: () => pos, - length: () => (buffer ? buffer.length : 0), - avail: () => (buffer && pos < buffer.length ? buffer.length - pos : 0), - clear: () => { - buffer = undefined; - }, - readUInt32BE: () => { - if (!buffer || pos + 3 >= buffer.length) - return; - return (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - }, - readUInt64BE: (behavior) => { - if (!buffer || pos + 7 >= buffer.length) - return; - switch (behavior) { - case 'always': - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - case 'maybe': - if (buffer[pos] > 0x1F) - return BigInt(`0x${buffer.hexSlice(pos, pos += 8)}`); - // FALLTHROUGH - default: - return (buffer[pos++] * 72057594037927940) - + (buffer[pos++] * 281474976710656) - + (buffer[pos++] * 1099511627776) - + (buffer[pos++] * 4294967296) - + (buffer[pos++] * 16777216) - + (buffer[pos++] * 65536) - + (buffer[pos++] * 256) - + buffer[pos++]; - } - }, - skip: (n) => { - if (buffer && n > 0) - pos += n; - }, - skipString: () => { - const len = self.readUInt32BE(); - if (len === undefined) - return; - pos += len; - return (pos <= buffer.length ? len : undefined); - }, - readByte: () => { - if (buffer && pos < buffer.length) - return buffer[pos++]; - }, - readBool: () => { - if (buffer && pos < buffer.length) - return !!buffer[pos++]; - }, - readList: () => { - const list = self.readString(true); - if (list === undefined) - return; - return (list ? list.split(',') : []); - }, - readString: (dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } - - const len = self.readUInt32BE(); - if (len === undefined) - return; - - if ((buffer.length - pos) < len - || (typeof maxLen === 'number' && len > maxLen)) { - return; - } - - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, pos, pos += len); - return buffer.utf8Slice(pos, pos += len); - } - return bufferSlice(buffer, pos, pos += len); - }, - readRaw: (len) => { - if (!buffer) - return; - if (typeof len !== 'number') - return bufferSlice(buffer, pos, pos += (buffer.length - pos)); - if ((buffer.length - pos) >= len) - return bufferSlice(buffer, pos, pos += len); - }, - }; - - return self; -} - -function makeError(msg, level, fatal) { - const err = new Error(msg); - if (typeof level === 'boolean') { - fatal = level; - err.level = 'protocol'; - } else { - err.level = level || 'protocol'; - } - err.fatal = !!fatal; - return err; -} - -function writeUInt32BE(buf, value, offset) { - buf[offset++] = (value >>> 24); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 8); - buf[offset++] = value; - return offset; + return result; } - -const utilBufferParser = makeBufferParser(); - -module.exports = { - bufferCopy, - bufferSlice, - FastBuffer, - bufferFill: (buf, value, start, end) => { - return TypedArrayFill.call(buf, value, start, end); - }, - makeError, - doFatalError: (protocol, msg, level, reason) => { - let err; - if (DISCONNECT_REASON === undefined) - ({ DISCONNECT_REASON } = __nccwpck_require__(36832)); - if (msg instanceof Error) { - // doFatalError(protocol, err[, reason]) - err = msg; - if (typeof level !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - else - reason = level; - } else { - // doFatalError(protocol, msg[, level[, reason]]) - err = makeError(msg, level, true); - } - if (typeof reason !== 'number') - reason = DISCONNECT_REASON.PROTOCOL_ERROR; - protocol.disconnect(reason); - protocol._destruct(); - protocol._onError(err); - return Infinity; - }, - readUInt32BE, - writeUInt32BE, - writeUInt32LE: (buf, value, offset) => { - buf[offset++] = value; - buf[offset++] = (value >>> 8); - buf[offset++] = (value >>> 16); - buf[offset++] = (value >>> 24); - return offset; - }, - makeBufferParser, - bufferParser: makeBufferParser(), - readString: (buffer, start, dest, maxLen) => { - if (typeof dest === 'number') { - maxLen = dest; - dest = undefined; - } - - if (start === undefined) - start = 0; - - const left = (buffer.length - start); - if (start < 0 || start >= buffer.length || left < 4) - return; - - const len = readUInt32BE(buffer, start); - if (left < (4 + len) || (typeof maxLen === 'number' && len > maxLen)) - return; - - start += 4; - const end = start + len; - buffer._pos = end; - - if (dest) { - if (Buffer.isBuffer(dest)) - return bufferCopy(buffer, dest, start, end); - return buffer.utf8Slice(start, end); +/** + * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers + * as required by the WebAuthn browser API. + * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback. + * + * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields + * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get() + * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON} + */ +function deserializeCredentialRequestOptions(options) { + if (!options) { + throw new Error('Credential request options are required'); } - return bufferSlice(buffer, start, end); - }, - sigSSHToASN1: (sig, type) => { - switch (type) { - case 'ssh-dss': { - if (sig.length > 40) - return sig; - // Change bare signature r and s values to ASN.1 BER values for OpenSSL - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - let r = sig.slice(0, 20); - let s = sig.slice(20); - if (r[0] & 0x80) { - const rNew = Buffer.allocUnsafe(21); - rNew[0] = 0x00; - r.copy(rNew, 1); - r = rNew; - } else if (r[0] === 0x00 && !(r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] & 0x80) { - const sNew = Buffer.allocUnsafe(21); - sNew[0] = 0x00; - s.copy(sNew, 1); - s = sNew; - } else if (s[0] === 0x00 && !(s[1] & 0x80)) { - s = s.slice(1); - } - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - utilBufferParser.init(sig, 0); - const r = utilBufferParser.readString(); - const s = utilBufferParser.readString(); - utilBufferParser.clear(); - if (r === undefined || s === undefined) - return; - - const asnWriter = new Ber.Writer(); - asnWriter.startSequence(); - asnWriter.writeBuffer(r, Ber.Integer); - asnWriter.writeBuffer(s, Ber.Integer); - asnWriter.endSequence(); - return asnWriter.buffer; - } - default: - return sig; + // Check if the native parseRequestOptionsFromJSON method is available + if (typeof PublicKeyCredential !== 'undefined' && + 'parseRequestOptionsFromJSON' in PublicKeyCredential && + typeof PublicKeyCredential + .parseRequestOptionsFromJSON === 'function') { + // Use the native WebAuthn Level 3 method + return PublicKeyCredential.parseRequestOptionsFromJSON(options); } - }, - convertSignature: (signature, keyType) => { - switch (keyType) { - case 'ssh-dss': { - if (signature.length <= 40) - return signature; - // This is a quick and dirty way to get from BER encoded r and s that - // OpenSSL gives us, to just the bare values back to back (40 bytes - // total) like OpenSSH (and possibly others) are expecting - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - let r = asnReader.readString(Ber.Integer, true); - let s = asnReader.readString(Ber.Integer, true); - let rOffset = 0; - let sOffset = 0; - if (r.length < 20) { - const rNew = Buffer.allocUnsafe(20); - rNew.set(r, 1); - r = rNew; - r[0] = 0; - } - if (s.length < 20) { - const sNew = Buffer.allocUnsafe(20); - sNew.set(s, 1); - s = sNew; - s[0] = 0; - } - if (r.length > 20 && r[0] === 0) - rOffset = 1; - if (s.length > 20 && s[0] === 0) - sOffset = 1; - const newSig = - Buffer.allocUnsafe((r.length - rOffset) + (s.length - sOffset)); - bufferCopy(r, newSig, rOffset, r.length, 0); - bufferCopy(s, newSig, sOffset, s.length, r.length - rOffset); - return newSig; - } - case 'ecdsa-sha2-nistp256': - case 'ecdsa-sha2-nistp384': - case 'ecdsa-sha2-nistp521': { - if (signature[0] === 0) - return signature; - // Convert SSH signature parameters to ASN.1 BER values for OpenSSL - const asnReader = new Ber.Reader(signature); - asnReader.readSequence(); - const r = asnReader.readString(Ber.Integer, true); - const s = asnReader.readString(Ber.Integer, true); - if (r === null || s === null) - return; - const newSig = Buffer.allocUnsafe(4 + r.length + 4 + s.length); - writeUInt32BE(newSig, r.length, 0); - newSig.set(r, 4); - writeUInt32BE(newSig, s.length, 4 + r.length); - newSig.set(s, 4 + 4 + r.length); - return newSig; - } + // Fallback to manual parsing for browsers that don't support the native method + // Destructure to separate fields that need transformation + const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest(options + // Convert challenge from base64url to ArrayBuffer + , ["challenge", "allowCredentials"]); + // Convert challenge from base64url to ArrayBuffer + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + // Build the result object + const result = Object.assign(Object.assign({}, restOptions), { challenge }); + // Only add allowCredentials if it exists + if (allowCredentials && allowCredentials.length > 0) { + result.allowCredentials = new Array(allowCredentials.length); + for (let i = 0; i < allowCredentials.length; i++) { + const cred = allowCredentials[i]; + result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key', + // Cast transports to handle future transport types like "cable" + transports: cred.transports }); + } } - - return signature; - }, - sendPacket: (proto, packet, bypass) => { - if (!bypass && proto._kexinit !== undefined) { - // We're currently in the middle of a handshake - - if (proto._queue === undefined) - proto._queue = []; - proto._queue.push(packet); - proto._debug && proto._debug('Outbound: ... packet queued'); - return false; + return result; +} +/** + * Convert a registration/enrollment credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {RegistrationCredential} credential - Credential from navigator.credentials.create() + * @returns {RegistrationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +function serializeCredentialCreationResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); } - proto._cipher.encrypt(packet); - return true; - }, -}; - - -/***/ }), - -/***/ 26715: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { kMaxLength } = __nccwpck_require__(14300); -const { - createInflate, - constants: { - DEFLATE, - INFLATE, - Z_DEFAULT_CHUNK, - Z_DEFAULT_COMPRESSION, - Z_DEFAULT_MEMLEVEL, - Z_DEFAULT_STRATEGY, - Z_DEFAULT_WINDOWBITS, - Z_PARTIAL_FLUSH, - } -} = __nccwpck_require__(59796); -const ZlibHandle = createInflate()._handle.constructor; - -function processCallback() { - throw new Error('Should not get here'); + const credentialWithAttachment = credential; + return { + id: credential.id, + rawId: credential.id, + response: { + attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)), + }, + type: 'public-key', + clientExtensionResults: credential.getClientExtensionResults(), + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), + }; +} +/** + * Convert an authentication/verification credential response to server format. + * Serializes binary fields to base64url for JSON transmission. + * Supports both native WebAuthn Level 3 toJSON and manual fallback. + * + * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get() + * @returns {AuthenticationResponseJSON} JSON-serializable credential for server + * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON} + */ +function serializeCredentialRequestResponse(credential) { + var _a; + // Check if the credential instance has the toJSON method + if ('toJSON' in credential && typeof credential.toJSON === 'function') { + // Use the native WebAuthn Level 3 method + return credential.toJSON(); + } + // Fallback to manual conversion for browsers that don't support toJSON + // Access authenticatorAttachment via type assertion to handle TypeScript version differences + // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't + const credentialWithAttachment = credential; + const clientExtensionResults = credential.getClientExtensionResults(); + const assertionResponse = credential.response; + return { + id: credential.id, + rawId: credential.id, // W3C spec expects rawId to match id for JSON format + response: { + authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)), + signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)), + userHandle: assertionResponse.userHandle + ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle)) + : undefined, + }, + type: 'public-key', + clientExtensionResults, + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined), + }; } - -function zlibOnError(message, errno, code) { - const self = this._owner; - // There is no way to cleanly recover. - // Continuing only obscures problems. - - const error = new Error(message); - error.errno = errno; - error.code = code; - self._err = error; +/** + * A simple test to determine if a hostname is a properly-formatted domain name. + * Considers localhost valid for development environments. + * + * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain + * + * Regex sourced from here: + * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + * + * @param {string} hostname - The hostname to validate + * @returns {boolean} True if valid domain or localhost + * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain} + */ +function isValidDomain(hostname) { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname)); } - -function _close(engine) { - // Caller may invoke .close after a zlib error (which will null _handle). - if (!engine._handle) - return; - - engine._handle.close(); - engine._handle = null; -} - -class Zlib { - constructor(mode) { - const windowBits = Z_DEFAULT_WINDOWBITS; - const level = Z_DEFAULT_COMPRESSION; - const memLevel = Z_DEFAULT_MEMLEVEL; - const strategy = Z_DEFAULT_STRATEGY; - const dictionary = undefined; - - this._err = undefined; - this._writeState = new Uint32Array(2); - this._chunkSize = Z_DEFAULT_CHUNK; - this._maxOutputLength = kMaxLength; - this._outBuffer = Buffer.allocUnsafe(this._chunkSize); - this._outOffset = 0; - - this._handle = new ZlibHandle(mode); - this._handle._owner = this; - this._handle.onerror = zlibOnError; - this._handle.init(windowBits, - level, - memLevel, - strategy, - this._writeState, - processCallback, - dictionary); - } - - writeSync(chunk, retChunks) { - const handle = this._handle; - if (!handle) - throw new Error('Invalid Zlib instance'); - - let availInBefore = chunk.length; - let availOutBefore = this._chunkSize - this._outOffset; - let inOff = 0; - let availOutAfter; - let availInAfter; - - let buffers; - let nread = 0; - const state = this._writeState; - let buffer = this._outBuffer; - let offset = this._outOffset; - const chunkSize = this._chunkSize; - - while (true) { - handle.writeSync(Z_PARTIAL_FLUSH, - chunk, // in - inOff, // in_off - availInBefore, // in_len - buffer, // out - offset, // out_off - availOutBefore); // out_len - if (this._err) - throw this._err; - - availOutAfter = state[0]; - availInAfter = state[1]; - - const inDelta = availInBefore - availInAfter; - const have = availOutBefore - availOutAfter; - - if (have > 0) { - const out = (offset === 0 && have === buffer.length - ? buffer - : buffer.slice(offset, offset + have)); - offset += have; - if (!buffers) - buffers = out; - else if (buffers.push === undefined) - buffers = [buffers, out]; - else - buffers.push(out); - nread += out.byteLength; - - if (nread > this._maxOutputLength) { - _close(this); - throw new Error( - `Output length exceeded maximum of ${this._maxOutputLength}` - ); +/** + * Determine if the browser is capable of WebAuthn. + * Checks for necessary Web APIs: PublicKeyCredential and Credential Management. + * + * @returns {boolean} True if browser supports WebAuthn + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility} + */ +function browserSupportsWebAuthn() { + var _a, _b; + return !!((0, helpers_1.isBrowser)() && + 'PublicKeyCredential' in window && + window.PublicKeyCredential && + 'credentials' in navigator && + typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' && + typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function'); +} +/** + * Create a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.create() with error handling. + * + * @param {CredentialCreationOptions} options - Options including publicKey parameters + * @returns {Promise>} Created credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create} + */ +async function createCredential(options) { + try { + const response = await navigator.credentials.create( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), + }; } - } else if (have !== 0) { - throw new Error('have should not go down'); - } - - // Exhausted the output buffer, or used all the input create a new one. - if (availOutAfter === 0 || offset >= chunkSize) { - availOutBefore = chunkSize; - offset = 0; - buffer = Buffer.allocUnsafe(chunkSize); - } - - if (availOutAfter === 0) { - // Not actually done. Need to reprocess. - // Also, update the availInBefore to the availInAfter value, - // so that if we have to hit it a third (fourth, etc.) time, - // it'll have the correct byte counts. - inOff += inDelta; - availInBefore = availInAfter; - } else { - break; - } - } - - this._outBuffer = buffer; - this._outOffset = offset; - - if (nread === 0) - buffers = Buffer.alloc(0); - - if (retChunks) { - buffers.totalLen = nread; - return buffers; + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; } - - if (buffers.push === undefined) - return buffers; - - const output = Buffer.allocUnsafe(nread); - for (let i = 0, p = 0; i < buffers.length; ++i) { - const buf = buffers[i]; - output.set(buf, p); - p += buf.length; + catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyRegistrationError)({ + error: err, + options, + }), + }; } - return output; - } } - -class ZlibPacketWriter { - constructor(protocol) { - this.allocStart = 0; - this.allocStartKEX = 0; - this._protocol = protocol; - this._zlib = new Zlib(DEFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - alloc(payloadSize, force) { - return Buffer.allocUnsafe(payloadSize); - } - - finalize(payload, force) { - if (this._protocol._kexinit === undefined || force) { - const output = this._zlib.writeSync(payload, true); - const packet = this._protocol._cipher.allocPacket(output.totalLen); - if (output.push === undefined) { - packet.set(output, 5); - } else { - for (let i = 0, p = 5; i < output.length; ++i) { - const chunk = output[i]; - packet.set(chunk, p); - p += chunk.length; +/** + * Get a WebAuthn credential using the browser's credentials API. + * Wraps navigator.credentials.get() with error handling. + * + * @param {CredentialRequestOptions} options - Options including publicKey parameters + * @returns {Promise>} Retrieved credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get} + */ +async function getCredential(options) { + try { + const response = await navigator.credentials.get( + /** we assert the type here until typescript types are updated */ + options); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response), + }; } - } - return packet; - } - return payload; - } -} - -class PacketWriter { - constructor(protocol) { - this.allocStart = 5; - this.allocStartKEX = 5; - this._protocol = protocol; - } - - cleanup() {} - - alloc(payloadSize, force) { - if (this._protocol._kexinit === undefined || force) - return this._protocol._cipher.allocPacket(payloadSize); - return Buffer.allocUnsafe(payloadSize); - } - - finalize(packet, force) { - return packet; - } -} - -class ZlibPacketReader { - constructor() { - this._zlib = new Zlib(INFLATE); - } - - cleanup() { - if (this._zlib) - _close(this._zlib); - } - - read(data) { - return this._zlib.writeSync(data, false); - } -} - -class PacketReader { - cleanup() {} - - read(data) { - return data; - } -} - -module.exports = { - PacketReader, - PacketWriter, - ZlibPacketReader, - ZlibPacketWriter, -}; - - -/***/ }), - -/***/ 12986: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// TODO: -// * convert listenerCount() usage to emit() return value checking? -// * emit error when connection severed early (e.g. before handshake) -// * add '.connected' or similar property to connection objects to allow -// immediate connection status checking - - -const { Server: netServer } = __nccwpck_require__(41808); -const EventEmitter = __nccwpck_require__(82361); -const { listenerCount } = EventEmitter; - -const { - CHANNEL_OPEN_FAILURE, - DEFAULT_CIPHER, - DEFAULT_COMPRESSION, - DEFAULT_KEX, - DEFAULT_MAC, - DEFAULT_SERVER_HOST_KEY, - DISCONNECT_REASON, - DISCONNECT_REASON_BY_VALUE, - SUPPORTED_CIPHER, - SUPPORTED_COMPRESSION, - SUPPORTED_KEX, - SUPPORTED_MAC, - SUPPORTED_SERVER_HOST_KEY, -} = __nccwpck_require__(36832); -const { init: cryptoInit } = __nccwpck_require__(45708); -const { KexInit } = __nccwpck_require__(64126); -const { parseKey } = __nccwpck_require__(22218); -const Protocol = __nccwpck_require__(59031); -const { SFTP } = __nccwpck_require__(52026); -const { writeUInt32BE } = __nccwpck_require__(49475); - -const { - Channel, - MAX_WINDOW, - PACKET_SIZE, - windowAdjust, - WINDOW_THRESHOLD, -} = __nccwpck_require__(83204); - -const { - ChannelManager, - generateAlgorithmList, - isWritable, - onChannelOpenFailure, - onCHANNEL_CLOSE, -} = __nccwpck_require__(40834); - -const MAX_PENDING_AUTHS = 10; - -class AuthContext extends EventEmitter { - constructor(protocol, username, service, method, cb) { - super(); - - this.username = this.user = username; - this.service = service; - this.method = method; - this._initialResponse = false; - this._finalResponse = false; - this._multistep = false; - this._cbfinal = (allowed, methodsLeft, isPartial) => { - if (!this._finalResponse) { - this._finalResponse = true; - cb(this, allowed, methodsLeft, isPartial); - } - }; - this._protocol = protocol; - } - - accept() { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(true); - } - reject(methodsLeft, isPartial) { - this._cleanup && this._cleanup(); - this._initialResponse = true; - this._cbfinal(false, methodsLeft, isPartial); - } -} - - -class KeyboardAuthContext extends AuthContext { - constructor(protocol, username, service, method, submethods, cb) { - super(protocol, username, service, method, cb); - - this._multistep = true; - - this._cb = undefined; - this._onInfoResponse = (responses) => { - const callback = this._cb; - if (callback) { - this._cb = undefined; - callback(responses); - } - }; - this.submethods = submethods; - this.on('abort', () => { - this._cb && this._cb(new Error('Authentication request aborted')); - }); - } - - prompt(prompts, title, instructions, cb) { - if (!Array.isArray(prompts)) - prompts = [ prompts ]; - - if (typeof title === 'function') { - cb = title; - title = instructions = undefined; - } else if (typeof instructions === 'function') { - cb = instructions; - instructions = undefined; - } else if (typeof cb !== 'function') { - cb = undefined; + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response), + }; + } + return { data: response, error: null }; } - - for (let i = 0; i < prompts.length; ++i) { - if (typeof prompts[i] === 'string') { - prompts[i] = { - prompt: prompts[i], - echo: true + catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyAuthenticationError)({ + error: err, + options, + }), }; - } } - - this._cb = cb; - this._initialResponse = true; - - this._protocol.authInfoReq(title, instructions, prompts); - } } - -class PKAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.hashAlgo = pkInfo.hashAlgo; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - } - - accept() { - if (!this.signature) { - this._initialResponse = true; - this._protocol.authPKOK(this.key.algo, this.key.data); - } else { - AuthContext.prototype.accept.call(this); +exports.DEFAULT_CREATION_OPTIONS = { + hints: ['security-key'], + authenticatorSelection: { + authenticatorAttachment: 'cross-platform', + requireResidentKey: false, + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + residentKey: 'discouraged', + }, + attestation: 'none', +}; +exports.DEFAULT_REQUEST_OPTIONS = { + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: 'preferred', + hints: ['security-key'], +}; +function deepMerge(...sources) { + const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val); + const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); + const result = {}; + for (const source of sources) { + if (!source) + continue; + for (const key in source) { + const value = source[key]; + if (value === undefined) + continue; + if (Array.isArray(value)) { + // preserve array reference, including unions like AuthenticatorTransport[] + result[key] = value; + } + else if (isArrayBufferLike(value)) { + result[key] = value; + } + else if (isObject(value)) { + const existing = result[key]; + if (isObject(existing)) { + result[key] = deepMerge(existing, value); + } + else { + result[key] = deepMerge(value); + } + } + else { + result[key] = value; + } + } } - } -} - -class HostbasedAuthContext extends AuthContext { - constructor(protocol, username, service, method, pkInfo, cb) { - super(protocol, username, service, method, cb); - - this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key }; - this.hashAlgo = pkInfo.hashAlgo; - this.signature = pkInfo.signature; - this.blob = pkInfo.blob; - this.localHostname = pkInfo.localHostname; - this.localUsername = pkInfo.localUsername; - } + return result; } - -class PwdAuthContext extends AuthContext { - constructor(protocol, username, service, method, password, cb) { - super(protocol, username, service, method, cb); - - this.password = password; - this._changeCb = undefined; - } - - requestChange(prompt, cb) { - if (this._changeCb) - throw new Error('Change request already in progress'); - if (typeof prompt !== 'string') - throw new Error('prompt argument must be a string'); - if (typeof cb !== 'function') - throw new Error('Callback argument must be a function'); - this._changeCb = cb; - this._protocol.authPasswdChg(prompt); - } +/** + * Merges WebAuthn credential creation options with overrides. + * Sets sensible defaults for authenticator selection and extensions. + * + * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply + * @param {string} friendlyName - Optional friendly name for the credential + * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options + * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria} + */ +function mergeCredentialCreationOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); } - - -class Session extends EventEmitter { - constructor(client, info, localChan) { - super(); - - this.type = 'session'; - this.subtype = undefined; - this.server = true; - this._ending = false; - this._channel = undefined; - this._chanInfo = { - type: 'session', - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - } +/** + * Merges WebAuthn credential request options with overrides. + * Sets sensible defaults for user verification and hints. + * + * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply + * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options + * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions} + */ +function mergeCredentialRequestOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); } - - -class Server extends EventEmitter { - constructor(cfg, listener) { - super(); - - if (typeof cfg !== 'object' || cfg === null) - throw new Error('Missing configuration object'); - - const hostKeys = Object.create(null); - const hostKeyAlgoOrder = []; - - const hostKeys_ = cfg.hostKeys; - if (!Array.isArray(hostKeys_)) - throw new Error('hostKeys must be an array'); - - const cfgAlgos = ( - typeof cfg.algorithms === 'object' && cfg.algorithms !== null - ? cfg.algorithms - : {} - ); - - const hostKeyAlgos = generateAlgorithmList( - cfgAlgos.serverHostKey, - DEFAULT_SERVER_HOST_KEY, - SUPPORTED_SERVER_HOST_KEY - ); - for (let i = 0; i < hostKeys_.length; ++i) { - let privateKey; - if (Buffer.isBuffer(hostKeys_[i]) || typeof hostKeys_[i] === 'string') - privateKey = parseKey(hostKeys_[i]); - else - privateKey = parseKey(hostKeys_[i].key, hostKeys_[i].passphrase); - - if (privateKey instanceof Error) - throw new Error(`Cannot parse privateKey: ${privateKey.message}`); - - if (Array.isArray(privateKey)) { - // OpenSSH's newer format only stores 1 key for now - privateKey = privateKey[0]; - } - - if (privateKey.getPrivatePEM() === null) - throw new Error('privateKey value contains an invalid private key'); - - // Discard key if we already found a key of the same type - if (hostKeyAlgoOrder.includes(privateKey.type)) - continue; - - if (privateKey.type === 'ssh-rsa') { - // SSH supports multiple signature hashing algorithms for RSA, so we add - // the algorithms in the desired order - let sha1Pos = hostKeyAlgos.indexOf('ssh-rsa'); - const sha256Pos = hostKeyAlgos.indexOf('rsa-sha2-256'); - const sha512Pos = hostKeyAlgos.indexOf('rsa-sha2-512'); - if (sha1Pos === -1) { - // Fall back to giving SHA1 the lowest priority - sha1Pos = Infinity; - } - [sha1Pos, sha256Pos, sha512Pos].sort(compareNumbers).forEach((pos) => { - if (pos === -1) - return; - - let type; - switch (pos) { - case sha1Pos: type = 'ssh-rsa'; break; - case sha256Pos: type = 'rsa-sha2-256'; break; - case sha512Pos: type = 'rsa-sha2-512'; break; - default: return; - } - - // Store same RSA key under each hash algorithm name for convenience - hostKeys[type] = privateKey; - - hostKeyAlgoOrder.push(type); - }); - } else { - hostKeys[privateKey.type] = privateKey; - hostKeyAlgoOrder.push(privateKey.type); - } +/** + * WebAuthn API wrapper for Supabase Auth. + * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials. + * + * @experimental This API is experimental and may change in future releases + * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API} + */ +class WebAuthnApi { + constructor(client) { + this.client = client; + // Bind all methods so they can be destructured + this.enroll = this._enroll.bind(this); + this.challenge = this._challenge.bind(this); + this.verify = this._verify.bind(this); + this.authenticate = this._authenticate.bind(this); + this.register = this._register.bind(this); } - - const algorithms = { - kex: generateAlgorithmList( - cfgAlgos.kex, - DEFAULT_KEX, - SUPPORTED_KEX - ).concat(['kex-strict-s-v00@openssh.com']), - serverHostKey: hostKeyAlgoOrder, - cs: { - cipher: generateAlgorithmList( - cfgAlgos.cipher, - DEFAULT_CIPHER, - SUPPORTED_CIPHER - ), - mac: generateAlgorithmList(cfgAlgos.hmac, DEFAULT_MAC, SUPPORTED_MAC), - compress: generateAlgorithmList( - cfgAlgos.compress, - DEFAULT_COMPRESSION, - SUPPORTED_COMPRESSION - ), - lang: [], - }, - sc: undefined, - }; - algorithms.sc = algorithms.cs; - - if (typeof listener === 'function') - this.on('connection', listener); - - const origDebug = (typeof cfg.debug === 'function' ? cfg.debug : undefined); - const ident = (cfg.ident ? Buffer.from(cfg.ident) : undefined); - const offer = new KexInit(algorithms); - - this._srv = new netServer((socket) => { - if (this._connections >= this.maxConnections) { - socket.destroy(); - return; - } - ++this._connections; - socket.once('close', () => { - --this._connections; - }); - - let debug; - if (origDebug) { - // Prepend debug output with a unique identifier in case there are - // multiple clients connected at the same time - const debugPrefix = `[${process.hrtime().join('.')}] `; - debug = (msg) => { - origDebug(`${debugPrefix}${msg}`); - }; - } - - // eslint-disable-next-line no-use-before-define - new Client(socket, hostKeys, ident, offer, debug, this, cfg); - }).on('error', (err) => { - this.emit('error', err); - }).on('listening', () => { - this.emit('listening'); - }).on('close', () => { - this.emit('close'); - }); - this._connections = 0; - this.maxConnections = Infinity; - } - - injectSocket(socket) { - this._srv.emit('connection', socket); - } - - listen(...args) { - this._srv.listen(...args); - return this; - } - - address() { - return this._srv.address(); - } - - getConnections(cb) { - this._srv.getConnections(cb); - return this; - } - - close(cb) { - this._srv.close(cb); - return this; - } - - ref() { - this._srv.ref(); - return this; - } - - unref() { - this._srv.unref(); - return this; - } -} -Server.KEEPALIVE_CLIENT_INTERVAL = 15000; -Server.KEEPALIVE_CLIENT_COUNT_MAX = 3; - - -class Client extends EventEmitter { - constructor(socket, hostKeys, ident, offer, debug, server, srvCfg) { - super(); - - let exchanges = 0; - let acceptedAuthSvc = false; - let pendingAuths = []; - let authCtx; - let kaTimer; - let onPacket; - const unsentGlobalRequestsReplies = []; - this._sock = socket; - this._chanMgr = new ChannelManager(this); - this._debug = debug; - this.noMoreSessions = false; - this.authenticated = false; - - // Silence pre-header errors - function onClientPreHeaderError(err) {} - this.on('error', onClientPreHeaderError); - - const DEBUG_HANDLER = (!debug ? undefined : (p, display, msg) => { - debug(`Debug output from client: ${JSON.stringify(msg)}`); - }); - - const kaIntvl = ( - typeof srvCfg.keepaliveInterval === 'number' - && isFinite(srvCfg.keepaliveInterval) - && srvCfg.keepaliveInterval > 0 - ? srvCfg.keepaliveInterval - : ( - typeof Server.KEEPALIVE_CLIENT_INTERVAL === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_INTERVAL) - && Server.KEEPALIVE_CLIENT_INTERVAL > 0 - ? Server.KEEPALIVE_CLIENT_INTERVAL - : -1 - ) - ); - const kaCountMax = ( - typeof srvCfg.keepaliveCountMax === 'number' - && isFinite(srvCfg.keepaliveCountMax) - && srvCfg.keepaliveCountMax >= 0 - ? srvCfg.keepaliveCountMax - : ( - typeof Server.KEEPALIVE_CLIENT_COUNT_MAX === 'number' - && isFinite(Server.KEEPALIVE_CLIENT_COUNT_MAX) - && Server.KEEPALIVE_CLIENT_COUNT_MAX >= 0 - ? Server.KEEPALIVE_CLIENT_COUNT_MAX - : -1 - ) - ); - let kaCurCount = 0; - if (kaIntvl !== -1 && kaCountMax !== -1) { - this.once('ready', () => { - const onClose = () => { - clearInterval(kaTimer); - }; - this.on('close', onClose).on('end', onClose); - kaTimer = setInterval(() => { - if (++kaCurCount > kaCountMax) { - clearInterval(kaTimer); - const err = new Error('Keepalive timeout'); - err.level = 'client-timeout'; - this.emit('error', err); - this.end(); - } else { - // XXX: if the server ever starts sending real global requests to - // the client, we will need to add a dummy callback here to - // keep the correct reply order - proto.ping(); - } - }, kaIntvl); - }); - // TODO: re-verify keepalive behavior with OpenSSH - onPacket = () => { - kaTimer && kaTimer.refresh(); - kaCurCount = 0; - }; + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + async _enroll(params) { + return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: 'webauthn' })); + } + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + async _challenge({ factorId, webauthn, friendlyName, signal, }, overrides) { + try { + // Get challenge from server using the client's MFA methods + const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ + factorId, + webauthn, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal(); + /** webauthn will fail if either of the name/displayname are blank */ + if (challengeResponse.webauthn.type === 'create') { + const { user } = challengeResponse.webauthn.credential_options.publicKey; + if (!user.name) { + user.name = `${user.id}:${friendlyName}`; + } + if (!user.displayName) { + user.displayName = user.name; + } + } + switch (challengeResponse.webauthn.type) { + case 'create': { + const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); + const { data, error } = await createCredential({ + publicKey: options, + signal: abortSignal, + }); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + case 'request': { + const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); + const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data, + }, + }, + error: null, + }; + } + return { data: null, error }; + } + } + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in challenge', error), + }; + } + } + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + async _verify({ challengeId, factorId, webauthn, }) { + return this.client.mfa.verify({ + factorId, + challengeId, + webauthn: webauthn, + }); } - - const proto = this._protocol = new Protocol({ - server: true, - hostKeys, - ident, - offer, - onPacket, - greeting: srvCfg.greeting, - banner: srvCfg.banner, - onWrite: (data) => { - if (isWritable(socket)) - socket.write(data); - }, - onError: (err) => { - if (!proto._destruct) - socket.removeAllListeners('data'); - this.emit('error', err); - try { - socket.end(); - } catch {} - }, - onHeader: (header) => { - this.removeListener('error', onClientPreHeaderError); - - const info = { - ip: socket.remoteAddress, - family: socket.remoteFamily, - port: socket.remotePort, - header, - }; - if (!server.emit('connection', this, info)) { - // auto reject - proto.disconnect(DISCONNECT_REASON.BY_APPLICATION); - socket.end(); - return; + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + async _authenticate({ factorId, webauthn: { rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError('rpId is required for WebAuthn authentication'), + }; } - - if (header.greeting) - this.emit('greeting', header.greeting); - }, - onHandshakeComplete: (negotiated) => { - if (++exchanges > 1) - this.emit('rekey'); - this.emit('handshake', negotiated); - }, - debug, - messageHandlers: { - DEBUG: DEBUG_HANDLER, - DISCONNECT: (p, reason, desc) => { - if (reason !== DISCONNECT_REASON.BY_APPLICATION) { - if (!desc) { - desc = DISCONNECT_REASON_BY_VALUE[reason]; - if (desc === undefined) - desc = `Unexpected disconnection reason: ${reason}`; - } - const err = new Error(desc); - err.code = reason; - this.emit('error', err); - } - socket.end(); - }, - CHANNEL_OPEN: (p, info) => { - // Handle incoming requests from client - - // Do early reject in some cases to prevent wasteful channel - // allocation - if ((info.type === 'session' && this.noMoreSessions) - || !this.authenticated) { - const reasonCode = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - return proto.channelOpenFail(info.sender, reasonCode); - } - - let localChan = -1; - let reason; - let replied = false; - - let accept; - const reject = () => { - if (replied) - return; - replied = true; - - if (reason === undefined) { - if (localChan === -1) - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - else - reason = CHANNEL_OPEN_FAILURE.CONNECT_FAILED; - } - - if (localChan !== -1) - this._chanMgr.remove(localChan); - proto.channelOpenFail(info.sender, reason, ''); - }; - const reserveChannel = () => { - localChan = this._chanMgr.add(); - - if (localChan === -1) { - reason = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; - if (debug) { - debug('Automatic rejection of incoming channel open: ' - + 'no channels available'); - } - } - - return (localChan !== -1); - }; - - const data = info.data; - switch (info.type) { - case 'session': - if (listenerCount(this, 'session') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const instance = new Session(this, info, localChan); - this._chanMgr.update(localChan, instance); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return instance; - }; - - this.emit('session', accept, reject); - return; - } - break; - case 'direct-tcpip': - if (listenerCount(this, 'tcpip') && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; - }; - - this.emit('tcpip', accept, reject, data); - return; - } - break; - case 'direct-streamlocal@openssh.com': - if (listenerCount(this, 'openssh.streamlocal') - && reserveChannel()) { - accept = () => { - if (replied) - return; - replied = true; - - const chanInfo = { - type: undefined, - incoming: { - id: localChan, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' - } - }; - - const stream = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(localChan, stream); - - proto.channelOpenConfirm(info.sender, - localChan, - MAX_WINDOW, - PACKET_SIZE); - - return stream; + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), }; - - this.emit('openssh.streamlocal', accept, reject, data); - return; - } - break; - default: - // Automatically reject any unsupported channel open requests - reason = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; - if (debug) { - debug('Automatic rejection of unsupported incoming channel open' - + ` type: ${info.type}`); - } - } - - if (reason === undefined) { - reason = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; - if (debug) { - debug('Automatic rejection of unexpected incoming channel open' - + ` for: ${info.type}`); - } - } - - reject(); - }, - CHANNEL_OPEN_CONFIRMATION: (p, info) => { - const channel = this._chanMgr.get(info.recipient); - if (typeof channel !== 'function') - return; - - const chanInfo = { - type: channel.type, - incoming: { - id: info.recipient, - window: MAX_WINDOW, - packetSize: PACKET_SIZE, - state: 'open' - }, - outgoing: { - id: info.sender, - window: info.window, - packetSize: info.packetSize, - state: 'open' } - }; - - const instance = new Channel(this, chanInfo, { server: true }); - this._chanMgr.update(info.recipient, instance); - channel(undefined, instance); - }, - CHANNEL_OPEN_FAILURE: (p, recipient, reason, description) => { - const channel = this._chanMgr.get(recipient); - if (typeof channel !== 'function') - return; - - const info = { reason, description }; - onChannelOpenFailure(this, recipient, info, channel); - }, - CHANNEL_DATA: (p, recipient, data) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The remote party should not be sending us data if there is no - // window space available ... - // TODO: raise error on data with not enough window? - if (channel.incoming.window === 0) - return; - - channel.incoming.window -= data.length; - - if (channel.push(data) === false) { - channel._waitChanDrain = true; - return; - } - - if (channel.incoming.window <= WINDOW_THRESHOLD) - windowAdjust(channel); - }, - CHANNEL_EXTENDED_DATA: (p, recipient, data, type) => { - // NOOP -- should not be sent by client - }, - CHANNEL_WINDOW_ADJUST: (p, recipient, amount) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - // The other side is allowing us to send `amount` more bytes of data - channel.outgoing.window += amount; - - if (channel._waitWindow) { - channel._waitWindow = false; - - if (channel._chunk) { - channel._write(channel._chunk, null, channel._chunkcb); - } else if (channel._chunkcb) { - channel._chunkcb(); - } else if (channel._chunkErr) { - channel.stderr._write(channel._chunkErr, - null, - channel._chunkcbErr); - } else if (channel._chunkcbErr) { - channel._chunkcbErr(); + // Get challenge and credential + const { data: challengeResponse, error: challengeError } = await this.challenge({ + factorId, + webauthn: { rpId, rpOrigins }, + signal, + }, { request: overrides }); + if (!challengeResponse) { + return { data: null, error: challengeError }; } - } - }, - CHANNEL_SUCCESS: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(false); - }, - CHANNEL_FAILURE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel = channel._channel; - if (!channel) - return; - } - - if (channel._callbacks.length) - channel._callbacks.shift()(true); - }, - CHANNEL_REQUEST: (p, recipient, type, wantReply, data) => { - const session = this._chanMgr.get(recipient); - if (typeof session !== 'object' || session === null) - return; - - let replied = false; - let accept; - let reject; - - if (session.constructor !== Session) { - // normal Channel instance - if (wantReply) - proto.channelFailure(session.outgoing.id); - return; - } - - if (wantReply) { - // "real session" requests will have custom accept behaviors - if (type !== 'shell' - && type !== 'exec' - && type !== 'subsystem') { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelSuccess(session._chanInfo.outgoing.id); - }; + const { webauthn } = challengeResponse; + // Verify credential + return this._verify({ + factorId, + challengeId: challengeResponse.challengeId, + webauthn: { + type: webauthn.type, + rpId, + rpOrigins, + credential_response: webauthn.credential_response, + }, + }); + } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; } - - reject = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - proto.channelFailure(session._chanInfo.outgoing.id); + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in authenticate', error), }; - } - - if (session._ending) { - reject && reject(); - return; - } - - switch (type) { - // "pre-real session start" requests - case 'env': - if (listenerCount(session, 'env')) { - session.emit('env', accept, reject, { - key: data.name, - val: data.value - }); - return; - } - break; - case 'pty-req': - if (listenerCount(session, 'pty')) { - session.emit('pty', accept, reject, data); - return; - } - break; - case 'window-change': - if (listenerCount(session, 'window-change')) - session.emit('window-change', accept, reject, data); - else - reject && reject(); - break; - case 'x11-req': - if (listenerCount(session, 'x11')) { - session.emit('x11', accept, reject, data); - return; - } - break; - // "post-real session start" requests - case 'signal': - if (listenerCount(session, 'signal')) { - session.emit('signal', accept, reject, { - name: data - }); - return; - } - break; - // XXX: is `auth-agent-req@openssh.com` really "post-real session - // start"? - case 'auth-agent-req@openssh.com': - if (listenerCount(session, 'auth-agent')) { - session.emit('auth-agent', accept, reject); - return; - } - break; - // "real session start" requests - case 'shell': - if (listenerCount(session, 'shell')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; - }; - - session.emit('shell', accept, reject); - return; - } - break; - case 'exec': - if (listenerCount(session, 'exec')) { - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - const channel = new Channel( - this, session._chanInfo, { server: true } - ); - - channel.subtype = session.subtype = type; - session._channel = channel; - - return channel; + } + } + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + async _register({ friendlyName, rpId = typeof window !== 'undefined' ? window.location.hostname : undefined, rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined, signal, }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError('rpId is required for WebAuthn registration'), + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError('Browser does not support WebAuthn', null), }; - - session.emit('exec', accept, reject, { - command: data - }); - return; - } - break; - case 'subsystem': { - let useSFTP = (data === 'sftp'); - accept = () => { - if (replied || session._ending || session._channel) - return; - replied = true; - - if (wantReply) - proto.channelSuccess(session._chanInfo.outgoing.id); - - let instance; - if (useSFTP) { - instance = new SFTP(this, session._chanInfo, { - server: true, - debug, - }); - } else { - instance = new Channel( - this, session._chanInfo, { server: true } - ); - instance.subtype = - session.subtype = `${type}:${data}`; - } - session._channel = instance; - - return instance; - }; - - if (data === 'sftp') { - if (listenerCount(session, 'sftp')) { - session.emit('sftp', accept, reject); - return; - } - useSFTP = false; - } - if (listenerCount(session, 'subsystem')) { - session.emit('subsystem', accept, reject, { - name: data - }); - return; - } - break; } - } - debug && debug( - `Automatic rejection of incoming channel request: ${type}` - ); - reject && reject(); - }, - CHANNEL_EOF: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - if (!channel._ending) { - channel._ending = true; - channel.emit('eof'); - channel.emit('end'); + // Enroll factor + const { data: factor, error: enrollError } = await this._enroll({ + friendlyName, + }); + if (!factor) { + await this.client.mfa + .listFactors() + .then((factors) => { + var _a; + return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v) => v.factor_type === 'webauthn' && + v.friendly_name === friendlyName && + v.status !== 'unverified'); + }) + .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor === null || factor === void 0 ? void 0 : factor.id }) : void 0)); + return { data: null, error: enrollError }; } - channel = channel._channel; - if (!channel) - return; - } - - if (channel.incoming.state !== 'open') - return; - channel.incoming.state = 'eof'; - - if (channel.readable) - channel.push(null); - }, - CHANNEL_CLOSE: (p, recipient) => { - let channel = this._chanMgr.get(recipient); - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.constructor === Session) { - channel._ending = true; - channel.emit('close'); - channel = channel._channel; - if (!channel) - return; - } - - onCHANNEL_CLOSE(this, recipient, channel); - }, - // Begin service/auth-related ========================================== - SERVICE_REQUEST: (p, service) => { - if (exchanges === 0 - || acceptedAuthSvc - || this.authenticated - || service !== 'ssh-userauth') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - acceptedAuthSvc = true; - proto.serviceAccept(service); - }, - USERAUTH_REQUEST: (p, username, service, method, methodData) => { - if (exchanges === 0 - || this.authenticated - || (authCtx - && (authCtx.username !== username - || authCtx.service !== service)) - // TODO: support hostbased auth - || (method !== 'password' - && method !== 'publickey' - && method !== 'hostbased' - && method !== 'keyboard-interactive' - && method !== 'none') - || pendingAuths.length === MAX_PENDING_AUTHS) { - proto.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR); - socket.end(); - return; - } else if (service !== 'ssh-connection') { - proto.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE); - socket.end(); - return; - } - - let ctx; - switch (method) { - case 'keyboard-interactive': - ctx = new KeyboardAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'publickey': - ctx = new PKAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'hostbased': - ctx = new HostbasedAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'password': - if (authCtx - && authCtx instanceof PwdAuthContext - && authCtx._changeCb) { - const cb = authCtx._changeCb; - authCtx._changeCb = undefined; - cb(methodData.newPassword); - return; - } - ctx = new PwdAuthContext(proto, username, service, method, - methodData, onAuthDecide); - break; - case 'none': - ctx = new AuthContext(proto, username, service, method, - onAuthDecide); - break; - } - - if (authCtx) { - if (!authCtx._initialResponse) { - return pendingAuths.push(ctx); - } else if (authCtx._multistep && !authCtx._finalResponse) { - // RFC 4252 says to silently abort the current auth request if a - // new auth request comes in before the final response from an - // auth method that requires additional request/response exchanges - // -- this means keyboard-interactive for now ... - authCtx._cleanup && authCtx._cleanup(); - authCtx.emit('abort'); + // Get challenge and create credential + const { data: challengeResponse, error: challengeError } = await this._challenge({ + factorId: factor.id, + friendlyName: factor.friendly_name, + webauthn: { rpId, rpOrigins }, + signal, + }, { + create: overrides, + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; } - } - - authCtx = ctx; - - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - }, - USERAUTH_INFO_RESPONSE: (p, responses) => { - if (authCtx && authCtx instanceof KeyboardAuthContext) - authCtx._onInfoResponse(responses); - }, - // End service/auth-related ============================================ - GLOBAL_REQUEST: (p, name, wantReply, data) => { - const reply = { - type: null, - buf: null - }; - - function setReply(type, buf) { - reply.type = type; - reply.buf = buf; - sendReplies(); - } - - if (wantReply) - unsentGlobalRequestsReplies.push(reply); - - if ((name === 'tcpip-forward' - || name === 'cancel-tcpip-forward' - || name === 'no-more-sessions@openssh.com' - || name === 'streamlocal-forward@openssh.com' - || name === 'cancel-streamlocal-forward@openssh.com') - && listenerCount(this, 'request') - && this.authenticated) { - let accept; - let reject; - - if (wantReply) { - let replied = false; - accept = (chosenPort) => { - if (replied) - return; - replied = true; - let bufPort; - if (name === 'tcpip-forward' - && data.bindPort === 0 - && typeof chosenPort === 'number') { - bufPort = Buffer.allocUnsafe(4); - writeUInt32BE(bufPort, chosenPort, 0); - } - setReply('SUCCESS', bufPort); - }; - reject = () => { - if (replied) - return; - replied = true; - setReply('FAILURE'); - }; - } - - if (name === 'no-more-sessions@openssh.com') { - this.noMoreSessions = true; - accept && accept(); - return; - } - - this.emit('request', accept, reject, name, data); - } else if (wantReply) { - setReply('FAILURE'); - } - }, - }, - }); - - socket.pause(); - cryptoInit.then(() => { - proto.start(); - socket.on('data', (data) => { - try { - proto.parse(data, 0, data.length); - } catch (ex) { - this.emit('error', ex); - try { - if (isWritable(socket)) - socket.end(); - } catch {} + return this._verify({ + factorId: factor.id, + challengeId: challengeResponse.challengeId, + webauthn: { + rpId, + rpOrigins, + type: challengeResponse.webauthn.type, + credential_response: challengeResponse.webauthn.credential_response, + }, + }); } - }); - socket.resume(); - }).catch((err) => { - this.emit('error', err); - try { - if (isWritable(socket)) - socket.end(); - } catch {} - }); - socket.on('error', (err) => { - err.level = 'socket'; - this.emit('error', err); - }).once('end', () => { - debug && debug('Socket ended'); - proto.cleanup(); - this.emit('end'); - }).once('close', () => { - debug && debug('Socket closed'); - proto.cleanup(); - this.emit('close'); - - const err = new Error('No response from server'); - - // Simulate error for pending channels and close any open channels - this._chanMgr.cleanup(err); - }); - - const onAuthDecide = (ctx, allowed, methodsLeft, isPartial) => { - if (authCtx === ctx && !this.authenticated) { - if (allowed) { - authCtx = undefined; - this.authenticated = true; - proto.authSuccess(); - pendingAuths = []; - this.emit('ready'); - } else { - proto.authFailure(methodsLeft, isPartial); - if (pendingAuths.length) { - authCtx = pendingAuths.pop(); - if (listenerCount(this, 'authentication')) - this.emit('authentication', authCtx); - else - authCtx.reject(); - } + catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError('Unexpected error in register', error), + }; } - } - }; - - function sendReplies() { - while (unsentGlobalRequestsReplies.length > 0 - && unsentGlobalRequestsReplies[0].type) { - const reply = unsentGlobalRequestsReplies.shift(); - if (reply.type === 'SUCCESS') - proto.requestSuccess(reply.buf); - if (reply.type === 'FAILURE') - proto.requestFailure(); - } - } - } - - end() { - if (this._sock && isWritable(this._sock)) { - this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION); - this._sock.end(); - } - return this; - } - - x11(originAddr, originPort, cb) { - const opts = { originAddr, originPort }; - openChannel(this, 'x11', opts, cb); - return this; - } - - forwardOut(boundAddr, boundPort, remoteAddr, remotePort, cb) { - const opts = { boundAddr, boundPort, remoteAddr, remotePort }; - openChannel(this, 'forwarded-tcpip', opts, cb); - return this; - } - - openssh_forwardOutStreamLocal(socketPath, cb) { - const opts = { socketPath }; - openChannel(this, 'forwarded-streamlocal@openssh.com', opts, cb); - return this; - } - - rekey(cb) { - let error; - - try { - this._protocol.rekey(); - } catch (ex) { - error = ex; - } - - // TODO: re-throw error if no callback? - - if (typeof cb === 'function') { - if (error) - process.nextTick(cb, error); - else - this.once('rekey', cb); } - } - - setNoDelay(noDelay) { - if (this._sock && typeof this._sock.setNoDelay === 'function') - this._sock.setNoDelay(noDelay); - - return this; - } -} - - -function openChannel(self, type, opts, cb) { - // Ask the client to open a channel for some purpose (e.g. a forwarded TCP - // connection) - const initWindow = MAX_WINDOW; - const maxPacket = PACKET_SIZE; - - if (typeof opts === 'function') { - cb = opts; - opts = {}; - } - - const wrapper = (err, stream) => { - cb(err, stream); - }; - wrapper.type = type; - - const localChan = self._chanMgr.add(wrapper); - - if (localChan === -1) { - cb(new Error('No free channels available')); - return; - } - - switch (type) { - case 'forwarded-tcpip': - self._protocol.forwardedTcpip(localChan, initWindow, maxPacket, opts); - break; - case 'x11': - self._protocol.x11(localChan, initWindow, maxPacket, opts); - break; - case 'forwarded-streamlocal@openssh.com': - self._protocol.openssh_forwardedStreamLocal( - localChan, initWindow, maxPacket, opts - ); - break; - default: - throw new Error(`Unsupported channel type: ${type}`); - } -} - -function compareNumbers(a, b) { - return a - b; } - -module.exports = Server; -module.exports.IncomingClient = Client; - +exports.WebAuthnApi = WebAuthnApi; +//# sourceMappingURL=webauthn.js.map /***/ }), -/***/ 40834: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9904: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const { SFTP } = __nccwpck_require__(52026); - -const MAX_CHANNEL = 2 ** 32 - 1; - -function onChannelOpenFailure(self, recipient, info, cb) { - self._chanMgr.remove(recipient); - if (typeof cb !== 'function') - return; - - let err; - if (info instanceof Error) { - err = info; - } else if (typeof info === 'object' && info !== null) { - err = new Error(`(SSH) Channel open failure: ${info.description}`); - err.reason = info.reason; - } else { - err = new Error( - '(SSH) Channel open failure: server closed channel unexpectedly' - ); - err.reason = ''; - } - - cb(err); -} - -function onCHANNEL_CLOSE(self, recipient, channel, err, dead) { - if (typeof channel === 'function') { - // We got CHANNEL_CLOSE instead of CHANNEL_OPEN_FAILURE when - // requesting to open a channel - onChannelOpenFailure(self, recipient, err, channel); - return; - } - - if (typeof channel !== 'object' || channel === null) - return; - - if (channel.incoming && channel.incoming.state === 'closed') - return; - - self._chanMgr.remove(recipient); - - if (channel.server && channel.constructor.name === 'Session') - return; - - channel.incoming.state = 'closed'; - - if (channel.readable) - channel.push(null); - if (channel.server) { - if (channel.stderr.writable) - channel.stderr.end(); - } else if (channel.stderr.readable) { - channel.stderr.push(null); - } - - if (channel.constructor !== SFTP - && (channel.outgoing.state === 'open' - || channel.outgoing.state === 'eof') - && !dead) { - channel.close(); - } - if (channel.outgoing.state === 'closing') - channel.outgoing.state = 'closed'; - - const readState = channel._readableState; - const writeState = channel._writableState; - if (writeState && !writeState.ending && !writeState.finished && !dead) - channel.end(); - - // Take care of any outstanding channel requests - const chanCallbacks = channel._callbacks; - channel._callbacks = []; - for (let i = 0; i < chanCallbacks.length; ++i) - chanCallbacks[i](true); - - if (channel.server) { - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - channel.emit('close'); - } else { - channel.once('end', () => channel.emit('close')); - } - } else { - let doClose; - switch (channel.type) { - case 'direct-streamlocal@openssh.com': - case 'direct-tcpip': - doClose = () => channel.emit('close'); - break; - default: { - // Align more with node child processes, where the close event gets - // the same arguments as the exit event - const exit = channel._exit; - doClose = () => { - if (exit.code === null) - channel.emit('close', exit.code, exit.signal, exit.dump, exit.desc); - else - channel.emit('close', exit.code); - }; - } - } - if (!channel.readable - || channel.destroyed - || (readState && readState.endEmitted)) { - doClose(); - } else { - channel.once('end', doClose); - } - - const errReadState = channel.stderr._readableState; - if (!channel.stderr.readable - || channel.stderr.destroyed - || (errReadState && errReadState.endEmitted)) { - channel.stderr.emit('close'); - } else { - channel.stderr.once('end', () => channel.stderr.emit('close')); - } - } -} - -class ChannelManager { - constructor(client) { - this._client = client; - this._channels = {}; - this._cur = -1; - this._count = 0; - } - add(val) { - // Attempt to reserve an id - - let id; - // Optimized paths - if (this._cur < MAX_CHANNEL) { - id = ++this._cur; - } else if (this._count === 0) { - // Revert and reset back to fast path once we no longer have any channels - // open - this._cur = 0; - id = 0; - } else { - // Slower lookup path - - // This path is triggered we have opened at least MAX_CHANNEL channels - // while having at least one channel open at any given time, so we have - // to search for a free id. - const channels = this._channels; - for (let i = 0; i < MAX_CHANNEL; ++i) { - if (channels[i] === undefined) { - id = i; - break; - } - } - } - - if (id === undefined) - return -1; - - this._channels[id] = (val || true); - ++this._count; - - return id; - } - update(id, val) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (val && this._channels[id]) - this._channels[id] = val; - } - get(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - return this._channels[id]; - } - remove(id) { - if (typeof id !== 'number' || id < 0 || id >= MAX_CHANNEL || !isFinite(id)) - throw new Error(`Invalid channel id: ${id}`); - - if (this._channels[id]) { - delete this._channels[id]; - if (this._count) - --this._count; - } - } - cleanup(err) { - const channels = this._channels; - this._channels = {}; - this._cur = -1; - this._count = 0; - - const chanIDs = Object.keys(channels); - const client = this._client; - for (let i = 0; i < chanIDs.length; ++i) { - const id = +chanIDs[i]; - const channel = channels[id]; - onCHANNEL_CLOSE(client, id, channel._channel || channel, err, true); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FunctionsClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +const helper_1 = __nccwpck_require__(618); +const types_1 = __nccwpck_require__(3136); +class FunctionsClient { + constructor(url, { headers = {}, customFetch, region = types_1.FunctionRegion.Any, } = {}) { + this.url = url; + this.headers = headers; + this.region = region; + this.fetch = (0, helper_1.resolveFetch)(customFetch); } - } -} - -const isRegExp = (() => { - const toString = Object.prototype.toString; - return (val) => toString.call(val) === '[object RegExp]'; -})(); - -function generateAlgorithmList(algoList, defaultList, supportedList) { - if (Array.isArray(algoList) && algoList.length > 0) { - // Exact list - for (let i = 0; i < algoList.length; ++i) { - if (supportedList.indexOf(algoList[i]) === -1) - throw new Error(`Unsupported algorithm: ${algoList[i]}`); + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; } - return algoList; - } - - if (typeof algoList === 'object' && algoList !== null) { - // Operations based on the default list - const keys = Object.keys(algoList); - let list = defaultList; - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - let val = algoList[key]; - switch (key) { - case 'append': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const append = val[j]; - if (typeof append === 'string') { - if (!append || list.indexOf(append) !== -1) - continue; - if (supportedList.indexOf(append) === -1) - throw new Error(`Unsupported algorithm: ${append}`); - if (list === defaultList) - list = list.slice(); - list.push(append); - } else if (isRegExp(append)) { - for (let k = 0; k < supportedList.length; ++k) { - const algo = supportedList[k]; - if (append.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.push(algo); - } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + */ + invoke(functionName_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) { + var _a; + try { + const { headers, method, body: functionArgs, signal } = options; + let _headers = {}; + let { region } = options; + if (!region) { + region = this.region; + } + // Add region as query parameter using URL API + const url = new URL(`${this.url}/${functionName}`); + if (region && region !== 'any') { + _headers['x-region'] = region; + url.searchParams.set('forceFunctionRegion', region); + } + let body; + if (functionArgs && + ((headers && !Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) || !headers)) { + if ((typeof Blob !== 'undefined' && functionArgs instanceof Blob) || + functionArgs instanceof ArrayBuffer) { + // will work for File as File inherits Blob + // also works for ArrayBuffer as it is the same underlying structure as a Blob + _headers['Content-Type'] = 'application/octet-stream'; + body = functionArgs; + } + else if (typeof functionArgs === 'string') { + // plain string + _headers['Content-Type'] = 'text/plain'; + body = functionArgs; + } + else if (typeof FormData !== 'undefined' && functionArgs instanceof FormData) { + // don't set content-type headers + // Request will automatically add the right boundary value + body = functionArgs; + } + else { + // default, assume this is JSON + _headers['Content-Type'] = 'application/json'; + body = JSON.stringify(functionArgs); + } + } + else { + // if the Content-Type was supplied, simply set the body + body = functionArgs; } - } - } - } - break; - case 'prepend': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = val.length; j >= 0; --j) { - const prepend = val[j]; - if (typeof prepend === 'string') { - if (!prepend || list.indexOf(prepend) !== -1) - continue; - if (supportedList.indexOf(prepend) === -1) - throw new Error(`Unsupported algorithm: ${prepend}`); - if (list === defaultList) - list = list.slice(); - list.unshift(prepend); - } else if (isRegExp(prepend)) { - for (let k = supportedList.length; k >= 0; --k) { - const algo = supportedList[k]; - if (prepend.test(algo)) { - if (list.indexOf(algo) !== -1) - continue; - if (list === defaultList) - list = list.slice(); - list.unshift(algo); - } + const response = yield this.fetch(url.toString(), { + method: method || 'POST', + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + signal, + }).catch((fetchError) => { + if (fetchError.name === 'AbortError') { + throw fetchError; + } + throw new types_1.FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get('x-relay-error'); + if (isRelayError && isRelayError === 'true') { + throw new types_1.FunctionsRelayError(response); } - } + if (!response.ok) { + throw new types_1.FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get('Content-Type')) !== null && _a !== void 0 ? _a : 'text/plain').split(';')[0].trim(); + let data; + if (responseType === 'application/json') { + data = yield response.json(); + } + else if (responseType === 'application/octet-stream' || + responseType === 'application/pdf') { + data = yield response.blob(); + } + else if (responseType === 'text/event-stream') { + data = response; + } + else if (responseType === 'multipart/form-data') { + data = yield response.formData(); + } + else { + // default to text + data = yield response.text(); + } + return { data, error: null, response }; } - } - break; - case 'remove': - if (!Array.isArray(val)) - val = [val]; - if (Array.isArray(val)) { - for (let j = 0; j < val.length; ++j) { - const search = val[j]; - if (typeof search === 'string') { - if (!search) - continue; - const idx = list.indexOf(search); - if (idx === -1) - continue; - if (list === defaultList) - list = list.slice(); - list.splice(idx, 1); - } else if (isRegExp(search)) { - for (let k = 0; k < list.length; ++k) { - if (search.test(list[k])) { - if (list === defaultList) - list = list.slice(); - list.splice(k, 1); - --k; - } + catch (error) { + if (error instanceof Error && error.name === 'AbortError') { + return { data: null, error: new types_1.FunctionsFetchError(error) }; } - } + return { + data: null, + error, + response: error instanceof types_1.FunctionsHttpError || error instanceof types_1.FunctionsRelayError + ? error.context + : undefined, + }; } - } - break; - } + }); } - - return list; - } - - return defaultList; } - -module.exports = { - ChannelManager, - generateAlgorithmList, - onChannelOpenFailure, - onCHANNEL_CLOSE, - isWritable: (stream) => { - // XXX: hack to workaround regression in node - // See: https://github.com/nodejs/node/issues/36029 - return (stream - && stream.writable - && stream._readableState - && stream._readableState.ended === false); - }, -}; - +exports.FunctionsClient = FunctionsClient; +//# sourceMappingURL=FunctionsClient.js.map /***/ }), -/***/ 94841: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 618: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -// 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 Buffer = (__nccwpck_require__(21867).Buffer); -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; + return (...args) => fetch(...args); }; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} +exports.resolveFetch = resolveFetch; +//# sourceMappingURL=helper.js.map /***/ }), -/***/ 366: +/***/ 8519: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var chownr = __nccwpck_require__(59051) -var tar = __nccwpck_require__(2283) -var pump = __nccwpck_require__(18341) -var mkdirp = __nccwpck_require__(97614) -var fs = __nccwpck_require__(57147) -var path = __nccwpck_require__(71017) -var os = __nccwpck_require__(22037) - -var win32 = os.platform() === 'win32' - -var noop = function () {} - -var echo = function (name) { - return name -} - -var normalize = !win32 ? echo : function (name) { - return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') -} - -var statAll = function (fs, stat, cwd, ignore, entries, sort) { - var queue = entries || ['.'] - - return function loop (callback) { - if (!queue.length) return callback() - var next = queue.shift() - var nextAbs = path.join(cwd, next) - - stat.call(fs, nextAbs, function (err, stat) { - if (err) return callback(err) - - if (!stat.isDirectory()) return callback(null, next, stat) +"use strict"; - fs.readdir(nextAbs, function (err, files) { - if (err) return callback(err) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FunctionRegion = exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; +var FunctionsClient_1 = __nccwpck_require__(9904); +Object.defineProperty(exports, "FunctionsClient", ({ enumerable: true, get: function () { return FunctionsClient_1.FunctionsClient; } })); +var types_1 = __nccwpck_require__(3136); +Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return types_1.FunctionsError; } })); +Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return types_1.FunctionsFetchError; } })); +Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return types_1.FunctionsHttpError; } })); +Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return types_1.FunctionsRelayError; } })); +Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return types_1.FunctionRegion; } })); +//# sourceMappingURL=index.js.map - if (sort) files.sort() - for (var i = 0; i < files.length; i++) { - if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) - } +/***/ }), - callback(null, next, stat) - }) - }) - } -} +/***/ 3136: +/***/ ((__unused_webpack_module, exports) => { -var strip = function (map, level) { - return function (header) { - header.name = header.name.split('/').slice(level).join('/') +"use strict"; - var linkname = header.linkname - if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { - header.linkname = linkname.split('/').slice(level).join('/') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; +class FunctionsError extends Error { + constructor(message, name = 'FunctionsError', context) { + super(message); + this.name = name; + this.context = context; } - - return map(header) - } } - -exports.pack = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} - - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) - var strict = opts.strict !== false - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var pack = opts.pack || tar.pack() - var finish = opts.finish || noop - - if (opts.strip) map = strip(map, opts.strip) - - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) - } - - var onsymlink = function (filename, header) { - xfs.readlink(path.join(cwd, filename), function (err, linkname) { - if (err) return pack.destroy(err) - header.linkname = normalize(linkname) - pack.entry(header, onnextentry) - }) - } - - var onstat = function (err, filename, stat) { - if (err) return pack.destroy(err) - if (!filename) { - if (opts.finalize !== false) pack.finalize() - return finish(pack) - } - - if (stat.isSocket()) return onnextentry() // tar does not support sockets... - - var header = { - name: normalize(filename), - mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, - mtime: stat.mtime, - size: stat.size, - type: 'file', - uid: stat.uid, - gid: stat.gid - } - - if (stat.isDirectory()) { - header.size = 0 - header.type = 'directory' - header = map(header) || header - return pack.entry(header, onnextentry) - } - - if (stat.isSymbolicLink()) { - header.size = 0 - header.type = 'symlink' - header = map(header) || header - return onsymlink(filename, header) - } - - // TODO: add fifo etc... - - header = map(header) || header - - if (!stat.isFile()) { - if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) - return onnextentry() +exports.FunctionsError = FunctionsError; +class FunctionsFetchError extends FunctionsError { + constructor(context) { + super('Failed to send a request to the Edge Function', 'FunctionsFetchError', context); } - - var entry = pack.entry(header, onnextentry) - if (!entry) return - - var rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header) - - rs.on('error', function (err) { // always forward errors on destroy - entry.destroy(err) - }) - - pump(rs, entry) - } - - var onnextentry = function (err) { - if (err) return pack.destroy(err) - statNext(onstat) - } - - onnextentry() - - return pack -} - -var head = function (list) { - return list.length ? list[list.length - 1] : null } - -var processGetuid = function () { - return process.getuid ? process.getuid() : -1 +exports.FunctionsFetchError = FunctionsFetchError; +class FunctionsRelayError extends FunctionsError { + constructor(context) { + super('Relay Error invoking the Edge Function', 'FunctionsRelayError', context); + } } - -var processUmask = function () { - return process.umask ? process.umask() : 0 +exports.FunctionsRelayError = FunctionsRelayError; +class FunctionsHttpError extends FunctionsError { + constructor(context) { + super('Edge Function returned a non-2xx status code', 'FunctionsHttpError', context); + } } +exports.FunctionsHttpError = FunctionsHttpError; +// Define the enum for the 'region' property +var FunctionRegion; +(function (FunctionRegion) { + FunctionRegion["Any"] = "any"; + FunctionRegion["ApNortheast1"] = "ap-northeast-1"; + FunctionRegion["ApNortheast2"] = "ap-northeast-2"; + FunctionRegion["ApSouth1"] = "ap-south-1"; + FunctionRegion["ApSoutheast1"] = "ap-southeast-1"; + FunctionRegion["ApSoutheast2"] = "ap-southeast-2"; + FunctionRegion["CaCentral1"] = "ca-central-1"; + FunctionRegion["EuCentral1"] = "eu-central-1"; + FunctionRegion["EuWest1"] = "eu-west-1"; + FunctionRegion["EuWest2"] = "eu-west-2"; + FunctionRegion["EuWest3"] = "eu-west-3"; + FunctionRegion["SaEast1"] = "sa-east-1"; + FunctionRegion["UsEast1"] = "us-east-1"; + FunctionRegion["UsWest1"] = "us-west-1"; + FunctionRegion["UsWest2"] = "us-west-2"; +})(FunctionRegion || (exports.FunctionRegion = FunctionRegion = {})); +//# sourceMappingURL=types.js.map -exports.extract = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} - - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var own = opts.chown !== false && !win32 && processGetuid() === 0 - var extract = opts.extract || tar.extract() - var stack = [] - var now = new Date() - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var strict = opts.strict !== false - - if (opts.strip) map = strip(map, opts.strip) - - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) - } - - var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry - var top - while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() - if (!top) return cb() - xfs.utimes(top[0], now, top[1], cb) - } - - var utimes = function (name, header, cb) { - if (opts.utimes === false) return cb() - - if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) - if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? - - xfs.utimes(name, now, header.mtime, function (err) { - if (err) return cb(err) - utimesParent(name, cb) - }) - } - - var chperm = function (name, header, cb) { - var link = header.type === 'symlink' - - /* eslint-disable node/no-deprecated-api */ - var chmod = link ? xfs.lchmod : xfs.chmod - var chown = link ? xfs.lchown : xfs.chown - /* eslint-enable node/no-deprecated-api */ - - if (!chmod) return cb() - - var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask - - if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown) - else onchown(null) +/***/ }), - function onchown (err) { - if (err) return cb(err) - if (!chmod) return cb() - chmod.call(xfs, name, mode, cb) - } - } +/***/ 1049: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - extract.on('entry', function (header, stream, next) { - header = map(header) || header - header.name = normalize(header.name) - var name = path.join(cwd, path.join('/', header.name)) +"use strict"; - if (ignore(name, header)) { - stream.resume() - return next() +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(7317)); +class PostgrestBuilder { + constructor(builder) { + var _a, _b; + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = new Headers(builder.headers); + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = (_a = builder.shouldThrowOnError) !== null && _a !== void 0 ? _a : false; + this.signal = builder.signal; + this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false; + if (builder.fetch) { + this.fetch = builder.fetch; + } + else { + this.fetch = fetch; + } } - - var stat = function (err) { - if (err) return next(err) - utimes(name, header, function (err) { - if (err) return next(err) - if (win32) return next() - chperm(name, header, next) - }) + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; } - - var onsymlink = function () { - if (win32) return next() // skip symlinks on win for now before it can be tested - xfs.unlink(name, function () { - var dst = path.resolve(path.dirname(name), header.linkname) - if (!inCwd(dst, cwd)) return next(new Error(name + ' is not a valid symlink')) - - xfs.symlink(header.linkname, name, stat) - }) + /** + * Set an HTTP header for the request. + */ + setHeader(name, value) { + this.headers = new Headers(this.headers); + this.headers.set(name, value); + return this; } - - var onlink = function () { - if (win32) return next() // skip links on win for now before it can be tested - xfs.unlink(name, function () { - var srcpath = path.join(cwd, path.join('/', header.linkname)) - - xfs.realpath(srcpath, function (err, dst) { - if (err || !inCwd(dst, cwd)) return next(new Error(name + ' is not a valid hardlink')) - - xfs.link(dst, name, function (err) { - if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { - stream = xfs.createReadStream(srcpath) - return onfile() + then(onfulfilled, onrejected) { + // https://postgrest.org/en/stable/api.html#switching-schemas + if (this.schema === undefined) { + // skip + } + else if (['GET', 'HEAD'].includes(this.method)) { + this.headers.set('Accept-Profile', this.schema); + } + else { + this.headers.set('Content-Profile', this.schema); + } + if (this.method !== 'GET' && this.method !== 'HEAD') { + this.headers.set('Content-Type', 'application/json'); + } + // NOTE: Invoke w/o `this` to avoid illegal invocation error. + // https://github.com/supabase/postgrest-js/pull/247 + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal, + }).then(async (res) => { + var _a, _b, _c, _d; + let error = null; + let data = null; + let count = null; + let status = res.status; + let statusText = res.statusText; + if (res.ok) { + if (this.method !== 'HEAD') { + const body = await res.text(); + if (body === '') { + // Prefer: return=minimal + } + else if (this.headers.get('Accept') === 'text/csv') { + data = body; + } + else if (this.headers.get('Accept') && + ((_a = this.headers.get('Accept')) === null || _a === void 0 ? void 0 : _a.includes('application/vnd.pgrst.plan+text'))) { + data = body; + } + else { + data = JSON.parse(body); + } + } + const countHeader = (_b = this.headers.get('Prefer')) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/); + const contentRange = (_c = res.headers.get('content-range')) === null || _c === void 0 ? void 0 : _c.split('/'); + if (countHeader && contentRange && contentRange.length > 1) { + count = parseInt(contentRange[1]); + } + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.isMaybeSingle && this.method === 'GET' && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: 'PGRST116', + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: 'JSON object requested, multiple (or no) rows returned', + }; + data = null; + count = null; + status = 406; + statusText = 'Not Acceptable'; + } + else if (data.length === 1) { + data = data[0]; + } + else { + data = null; + } + } } - - stat(err) - }) - }) - }) - } - - var onfile = function () { - var ws = xfs.createWriteStream(name) - var rs = mapStream(stream, header) - - ws.on('error', function (err) { // always forward errors on destroy - rs.destroy(err) - }) - - pump(rs, ws, function (err) { - if (err) return next(err) - ws.on('close', stat) - }) + else { + const body = await res.text(); + try { + error = JSON.parse(body); + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (Array.isArray(error) && res.status === 404) { + data = []; + error = null; + status = 200; + statusText = 'OK'; + } + } + catch (_e) { + // Workaround for https://github.com/supabase/postgrest-js/issues/295 + if (res.status === 404 && body === '') { + status = 204; + statusText = 'No Content'; + } + else { + error = { + message: body, + }; + } + } + if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes('0 rows'))) { + error = null; + status = 200; + statusText = 'OK'; + } + if (error && this.shouldThrowOnError) { + throw new PostgrestError_1.default(error); + } + } + const postgrestResponse = { + error, + data, + count, + status, + statusText, + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a, _b, _c; + return ({ + error: { + message: `${(_a = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _a !== void 0 ? _a : 'FetchError'}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: `${(_b = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _b !== void 0 ? _b : ''}`, + hint: '', + code: `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.code) !== null && _c !== void 0 ? _c : ''}`, + }, + data: null, + count: null, + status: 0, + statusText: '', + }); + }); + } + return res.then(onfulfilled, onrejected); } - - if (header.type === 'directory') { - stack.push([name, header.mtime]) - return mkdirfix(name, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, stat) + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + /* istanbul ignore next */ + return this; } - - var dir = path.dirname(name) - - validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { - if (err) return next(err) - if (!valid) return next(new Error(dir + ' is not a valid path')) - - mkdirfix(dir, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, function (err) { - if (err) return next(err) - - switch (header.type) { - case 'file': return onfile() - case 'link': return onlink() - case 'symlink': return onsymlink() - } - - if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) - - stream.resume() - next() - }) - }) - }) - - if (opts.finish) extract.on('finish', opts.finish) - - return extract -} - -function validate (fs, name, root, cb) { - if (name === root) return cb(null, true) - fs.lstat(name, function (err, st) { - if (err && err.code !== 'ENOENT') return cb(err) - if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb) - cb(null, false) - }) -} - -function mkdirfix (name, opts, cb) { - mkdirp(name, { fs: opts.fs }, function (err, made) { - if (!err && made && opts.own) { - chownr(made, opts.uid, opts.gid, cb) - } else { - cb(err) + /** + * Override the type of the returned `data` field in the response. + * + * @typeParam NewResult - The new type to cast the response data to + * @typeParam Options - Optional type configuration (defaults to { merge: true }) + * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) + * @example + * ```typescript + * // Merge with existing types (default behavior) + * const query = supabase + * .from('users') + * .select() + * .overrideTypes<{ custom_field: string }>() + * + * // Replace existing types completely + * const replaceQuery = supabase + * .from('users') + * .select() + * .overrideTypes<{ id: number; name: string }, { merge: false }>() + * ``` + * @returns A PostgrestBuilder instance with the new type + */ + overrideTypes() { + return this; } - }) -} - -function inCwd (dst, cwd) { - cwd = path.resolve(cwd) - return cwd === dst || dst.startsWith(cwd + path.sep) } - +exports["default"] = PostgrestBuilder; +//# sourceMappingURL=PostgrestBuilder.js.map /***/ }), -/***/ 57882: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var util = __nccwpck_require__(73837) -var bl = __nccwpck_require__(20336) -var headers = __nccwpck_require__(68860) - -var Writable = (__nccwpck_require__(51642).Writable) -var PassThrough = (__nccwpck_require__(51642).PassThrough) - -var noop = function () {} - -var overflow = function (size) { - size &= 511 - return size && 512 - size -} - -var emptyStream = function (self, offset) { - var s = new Source(self, offset) - s.end() - return s -} - -var mixinPax = function (header, pax) { - if (pax.path) header.name = pax.path - if (pax.linkpath) header.linkname = pax.linkpath - if (pax.size) header.size = parseInt(pax.size, 10) - header.pax = pax - return header -} - -var Source = function (self, offset) { - this._parent = self - this.offset = offset - PassThrough.call(this, { autoDestroy: false }) -} - -util.inherits(Source, PassThrough) - -Source.prototype.destroy = function (err) { - this._parent.destroy(err) -} - -var Extract = function (opts) { - if (!(this instanceof Extract)) return new Extract(opts) - Writable.call(this, opts) - - opts = opts || {} - - this._offset = 0 - this._buffer = bl() - this._missing = 0 - this._partial = false - this._onparse = noop - this._header = null - this._stream = null - this._overflow = null - this._cb = null - this._locked = false - this._destroyed = false - this._pax = null - this._paxGlobal = null - this._gnuLongPath = null - this._gnuLongLinkPath = null - - var self = this - var b = self._buffer - - var oncontinue = function () { - self._continue() - } - - var onunlock = function (err) { - self._locked = false - if (err) return self.destroy(err) - if (!self._stream) oncontinue() - } - - var onstreamend = function () { - self._stream = null - var drain = overflow(self._header.size) - if (drain) self._parse(drain, ondrain) - else self._parse(512, onheader) - if (!self._locked) oncontinue() - } - - var ondrain = function () { - self._buffer.consume(overflow(self._header.size)) - self._parse(512, onheader) - oncontinue() - } - - var onpaxglobalheader = function () { - var size = self._header.size - self._paxGlobal = headers.decodePax(b.slice(0, size)) - b.consume(size) - onstreamend() - } - - var onpaxheader = function () { - var size = self._header.size - self._pax = headers.decodePax(b.slice(0, size)) - if (self._paxGlobal) self._pax = Object.assign({}, self._paxGlobal, self._pax) - b.consume(size) - onstreamend() - } - - var ongnulongpath = function () { - var size = self._header.size - this._gnuLongPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() - } - - var ongnulonglinkpath = function () { - var size = self._header.size - this._gnuLongLinkPath = headers.decodeLongPath(b.slice(0, size), opts.filenameEncoding) - b.consume(size) - onstreamend() - } - - var onheader = function () { - var offset = self._offset - var header - try { - header = self._header = headers.decode(b.slice(0, 512), opts.filenameEncoding, opts.allowUnknownFormat) - } catch (err) { - self.emit('error', err) - } - b.consume(512) +/***/ 1526: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!header) { - self._parse(512, onheader) - oncontinue() - return - } - if (header.type === 'gnu-long-path') { - self._parse(header.size, ongnulongpath) - oncontinue() - return - } - if (header.type === 'gnu-long-link-path') { - self._parse(header.size, ongnulonglinkpath) - oncontinue() - return - } - if (header.type === 'pax-global-header') { - self._parse(header.size, onpaxglobalheader) - oncontinue() - return - } - if (header.type === 'pax-header') { - self._parse(header.size, onpaxheader) - oncontinue() - return - } +"use strict"; - if (self._gnuLongPath) { - header.name = self._gnuLongPath - self._gnuLongPath = null +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50)); +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); +/** + * PostgREST client. + * + * @typeParam Database - Types for the schema from the [type + * generator](https://supabase.com/docs/reference/javascript/next/typescript-support) + * + * @typeParam SchemaName - Postgres schema to switch to. Must be a string + * literal, the same one passed to the constructor. If the schema is not + * `"public"`, this must be supplied manually. + */ +class PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + */ + constructor(url, { headers = {}, schema, fetch, } = {}) { + this.url = url; + this.headers = new Headers(headers); + this.schemaName = schema; + this.fetch = fetch; } - - if (self._gnuLongLinkPath) { - header.linkname = self._gnuLongLinkPath - self._gnuLongLinkPath = null + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder_1.default(url, { + headers: new Headers(this.headers), + schema: this.schemaName, + fetch: this.fetch, + }); } - - if (self._pax) { - self._header = header = mixinPax(header, self._pax) - self._pax = null + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return new PostgrestClient(this.url, { + headers: this.headers, + schema, + fetch: this.fetch, + }); } - - self._locked = true - - if (!header.size || header.type === 'directory') { - self._parse(512, onheader) - self.emit('entry', header, emptyStream(self, offset), onunlock) - return + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, { head = false, get = false, count, } = {}) { + var _a; + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head || get) { + method = head ? 'HEAD' : 'GET'; + Object.entries(args) + // params with undefined value needs to be filtered out, otherwise it'll + // show up as `?param=undefined` + .filter(([_, value]) => value !== undefined) + // array values need special syntax + .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`]) + .forEach(([name, value]) => { + url.searchParams.append(name, value); + }); + } + else { + method = 'POST'; + body = args; + } + const headers = new Headers(this.headers); + if (count) { + headers.set('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url, + headers, + schema: this.schemaName, + body, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); } - - self._stream = new Source(self, offset) - - self.emit('entry', header, self._stream, onunlock) - self._parse(header.size, onstreamend) - oncontinue() - } - - this._onheader = onheader - this._parse(512, onheader) -} - -util.inherits(Extract, Writable) - -Extract.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true - - if (err) this.emit('error', err) - this.emit('close') - if (this._stream) this._stream.emit('close') -} - -Extract.prototype._parse = function (size, onparse) { - if (this._destroyed) return - this._offset += size - this._missing = size - if (onparse === this._onheader) this._partial = false - this._onparse = onparse -} - -Extract.prototype._continue = function () { - if (this._destroyed) return - var cb = this._cb - this._cb = noop - if (this._overflow) this._write(this._overflow, undefined, cb) - else cb() -} - -Extract.prototype._write = function (data, enc, cb) { - if (this._destroyed) return - - var s = this._stream - var b = this._buffer - var missing = this._missing - if (data.length) this._partial = true - - // we do not reach end-of-chunk now. just forward it - - if (data.length < missing) { - this._missing -= data.length - this._overflow = null - if (s) return s.write(data, cb) - b.append(data) - return cb() - } - - // end-of-chunk. the parser should call cb. - - this._cb = cb - this._missing = 0 - - var overflow = null - if (data.length > missing) { - overflow = data.slice(missing) - data = data.slice(0, missing) - } - - if (s) s.end(data) - else b.append(data) - - this._overflow = overflow - this._onparse() -} - -Extract.prototype._final = function (cb) { - if (this._partial) return this.destroy(new Error('Unexpected end of data')) - cb() } - -module.exports = Extract - +exports["default"] = PostgrestClient; +//# sourceMappingURL=PostgrestClient.js.map /***/ }), -/***/ 68860: +/***/ 7317: /***/ ((__unused_webpack_module, exports) => { -var alloc = Buffer.alloc - -var ZEROS = '0000000000000000000' -var SEVENS = '7777777777777777777' -var ZERO_OFFSET = '0'.charCodeAt(0) -var USTAR_MAGIC = Buffer.from('ustar\x00', 'binary') -var USTAR_VER = Buffer.from('00', 'binary') -var GNU_MAGIC = Buffer.from('ustar\x20', 'binary') -var GNU_VER = Buffer.from('\x20\x00', 'binary') -var MASK = parseInt('7777', 8) -var MAGIC_OFFSET = 257 -var VERSION_OFFSET = 263 - -var clamp = function (index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue - index = ~~index // Coerce to integer. - if (index >= len) return len - if (index >= 0) return index - index += len - if (index >= 0) return index - return 0 -} - -var toType = function (flag) { - switch (flag) { - case 0: - return 'file' - case 1: - return 'link' - case 2: - return 'symlink' - case 3: - return 'character-device' - case 4: - return 'block-device' - case 5: - return 'directory' - case 6: - return 'fifo' - case 7: - return 'contiguous-file' - case 72: - return 'pax-header' - case 55: - return 'pax-global-header' - case 27: - return 'gnu-long-link-path' - case 28: - case 30: - return 'gnu-long-path' - } - - return null -} - -var toTypeflag = function (flag) { - switch (flag) { - case 'file': - return 0 - case 'link': - return 1 - case 'symlink': - return 2 - case 'character-device': - return 3 - case 'block-device': - return 4 - case 'directory': - return 5 - case 'fifo': - return 6 - case 'contiguous-file': - return 7 - case 'pax-header': - return 72 - } - - return 0 -} - -var indexOf = function (block, num, offset, end) { - for (; offset < end; offset++) { - if (block[offset] === num) return offset - } - return end -} - -var cksum = function (block) { - var sum = 8 * 32 - for (var i = 0; i < 148; i++) sum += block[i] - for (var j = 156; j < 512; j++) sum += block[j] - return sum -} - -var encodeOct = function (val, n) { - val = val.toString(8) - if (val.length > n) return SEVENS.slice(0, n) + ' ' - else return ZEROS.slice(0, n - val.length) + val + ' ' -} +"use strict"; -/* Copied from the node-tar repo and modified to meet - * tar-stream coding standard. +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Error format * - * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 + * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes} */ -function parse256 (buf) { - // first byte MUST be either 80 or FF - // 80 for positive, FF for 2's comp - var positive - if (buf[0] === 0x80) positive = true - else if (buf[0] === 0xFF) positive = false - else return null - - // build up a base-256 tuple from the least sig to the highest - var tuple = [] - for (var i = buf.length - 1; i > 0; i--) { - var byte = buf[i] - if (positive) tuple.push(byte) - else tuple.push(0xFF - byte) - } - - var sum = 0 - var l = tuple.length - for (i = 0; i < l; i++) { - sum += tuple[i] * Math.pow(256, i) - } - - return positive ? sum : -1 * sum -} - -var decodeOct = function (val, offset, length) { - val = val.slice(offset, offset + length) - offset = 0 - - // If prefixed with 0x80 then parse as a base-256 integer - if (val[offset] & 0x80) { - return parse256(val) - } else { - // Older versions of tar can prefix with spaces - while (offset < val.length && val[offset] === 32) offset++ - var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) - while (offset < end && val[offset] === 0) offset++ - if (end === offset) return 0 - return parseInt(val.slice(offset, end).toString(), 8) - } -} - -var decodeStr = function (val, offset, length, encoding) { - return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString(encoding) -} - -var addLength = function (str) { - var len = Buffer.byteLength(str) - var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 - if (len + digits >= Math.pow(10, digits)) digits++ - - return (len + digits) + str -} - -exports.decodeLongPath = function (buf, encoding) { - return decodeStr(buf, 0, buf.length, encoding) -} - -exports.encodePax = function (opts) { // TODO: encode more stuff in pax - var result = '' - if (opts.name) result += addLength(' path=' + opts.name + '\n') - if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') - var pax = opts.pax - if (pax) { - for (var key in pax) { - result += addLength(' ' + key + '=' + pax[key] + '\n') - } - } - return Buffer.from(result) -} - -exports.decodePax = function (buf) { - var result = {} - - while (buf.length) { - var i = 0 - while (i < buf.length && buf[i] !== 32) i++ - var len = parseInt(buf.slice(0, i).toString(), 10) - if (!len) return result - - var b = buf.slice(i + 1, len - 1).toString() - var keyIndex = b.indexOf('=') - if (keyIndex === -1) return result - result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) - - buf = buf.slice(len) - } - - return result -} - -exports.encode = function (opts) { - var buf = alloc(512) - var name = opts.name - var prefix = '' - - if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' - if (Buffer.byteLength(name) !== name.length) return null // utf-8 - - while (Buffer.byteLength(name) > 100) { - var i = name.indexOf('/') - if (i === -1) return null - prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) - name = name.slice(i + 1) - } - - if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null - if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null - - buf.write(name) - buf.write(encodeOct(opts.mode & MASK, 6), 100) - buf.write(encodeOct(opts.uid, 6), 108) - buf.write(encodeOct(opts.gid, 6), 116) - buf.write(encodeOct(opts.size, 11), 124) - buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) - - buf[156] = ZERO_OFFSET + toTypeflag(opts.type) - - if (opts.linkname) buf.write(opts.linkname, 157) - - USTAR_MAGIC.copy(buf, MAGIC_OFFSET) - USTAR_VER.copy(buf, VERSION_OFFSET) - if (opts.uname) buf.write(opts.uname, 265) - if (opts.gname) buf.write(opts.gname, 297) - buf.write(encodeOct(opts.devmajor || 0, 6), 329) - buf.write(encodeOct(opts.devminor || 0, 6), 337) - - if (prefix) buf.write(prefix, 345) - - buf.write(encodeOct(cksum(buf), 6), 148) - - return buf -} - -exports.decode = function (buf, filenameEncoding, allowUnknownFormat) { - var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET - - var name = decodeStr(buf, 0, 100, filenameEncoding) - var mode = decodeOct(buf, 100, 8) - var uid = decodeOct(buf, 108, 8) - var gid = decodeOct(buf, 116, 8) - var size = decodeOct(buf, 124, 12) - var mtime = decodeOct(buf, 136, 12) - var type = toType(typeflag) - var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding) - var uname = decodeStr(buf, 265, 32) - var gname = decodeStr(buf, 297, 32) - var devmajor = decodeOct(buf, 329, 8) - var devminor = decodeOct(buf, 337, 8) - - var c = cksum(buf) - - // checksum is still initial value if header was null. - if (c === 8 * 32) return null - - // valid checksum - if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') - - if (USTAR_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) { - // ustar (posix) format. - // prepend prefix, if present. - if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name - } else if (GNU_MAGIC.compare(buf, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && - GNU_VER.compare(buf, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) { - // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and - // multi-volume tarballs. - } else { - if (!allowUnknownFormat) { - throw new Error('Invalid tar header: unknown format.') +class PostgrestError extends Error { + constructor(context) { + super(context.message); + this.name = 'PostgrestError'; + this.details = context.details; + this.hint = context.hint; + this.code = context.code; } - } - - // to support old tar versions that use trailing / to indicate dirs - if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 - - return { - name, - mode, - uid, - gid, - size, - mtime: new Date(1000 * mtime), - type, - linkname, - uname, - gname, - devmajor, - devminor - } } - +exports["default"] = PostgrestError; +//# sourceMappingURL=PostgrestError.js.map /***/ }), -/***/ 2283: +/***/ 6671: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -exports.extract = __nccwpck_require__(57882) -exports.pack = __nccwpck_require__(94930) - - -/***/ }), - -/***/ 94930: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var constants = __nccwpck_require__(73186) -var eos = __nccwpck_require__(81205) -var inherits = __nccwpck_require__(44124) -var alloc = Buffer.alloc - -var Readable = (__nccwpck_require__(51642).Readable) -var Writable = (__nccwpck_require__(51642).Writable) -var StringDecoder = (__nccwpck_require__(71576).StringDecoder) - -var headers = __nccwpck_require__(68860) - -var DMODE = parseInt('755', 8) -var FMODE = parseInt('644', 8) - -var END_OF_TAR = alloc(1024) - -var noop = function () {} - -var overflow = function (self, size) { - size &= 511 - if (size) self.push(END_OF_TAR.slice(0, 512 - size)) -} - -function modeToType (mode) { - switch (mode & constants.S_IFMT) { - case constants.S_IFBLK: return 'block-device' - case constants.S_IFCHR: return 'character-device' - case constants.S_IFDIR: return 'directory' - case constants.S_IFIFO: return 'fifo' - case constants.S_IFLNK: return 'symlink' - } - - return 'file' -} - -var Sink = function (to) { - Writable.call(this) - this.written = 0 - this._to = to - this._destroyed = false -} - -inherits(Sink, Writable) - -Sink.prototype._write = function (data, enc, cb) { - this.written += data.length - if (this._to.push(data)) return cb() - this._to._drain = cb -} - -Sink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} - -var LinkSink = function () { - Writable.call(this) - this.linkname = '' - this._decoder = new StringDecoder('utf-8') - this._destroyed = false -} - -inherits(LinkSink, Writable) - -LinkSink.prototype._write = function (data, enc, cb) { - this.linkname += this._decoder.write(data) - cb() -} - -LinkSink.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} - -var Void = function () { - Writable.call(this) - this._destroyed = false -} - -inherits(Void, Writable) - -Void.prototype._write = function (data, enc, cb) { - cb(new Error('No body allowed for this entry')) -} - -Void.prototype.destroy = function () { - if (this._destroyed) return - this._destroyed = true - this.emit('close') -} - -var Pack = function (opts) { - if (!(this instanceof Pack)) return new Pack(opts) - Readable.call(this, opts) - - this._drain = noop - this._finalized = false - this._finalizing = false - this._destroyed = false - this._stream = null -} - -inherits(Pack, Readable) - -Pack.prototype.entry = function (header, buffer, callback) { - if (this._stream) throw new Error('already piping an entry') - if (this._finalized || this._destroyed) return - - if (typeof buffer === 'function') { - callback = buffer - buffer = null - } - - if (!callback) callback = noop - - var self = this - - if (!header.size || header.type === 'symlink') header.size = 0 - if (!header.type) header.type = modeToType(header.mode) - if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE - if (!header.uid) header.uid = 0 - if (!header.gid) header.gid = 0 - if (!header.mtime) header.mtime = new Date() - - if (typeof buffer === 'string') buffer = Buffer.from(buffer) - if (Buffer.isBuffer(buffer)) { - header.size = buffer.length - this._encode(header) - var ok = this.push(buffer) - overflow(self, header.size) - if (ok) process.nextTick(callback) - else this._drain = callback - return new Void() - } - - if (header.type === 'symlink' && !header.linkname) { - var linkSink = new LinkSink() - eos(linkSink, function (err) { - if (err) { // stream was closed - self.destroy() - return callback(err) - } - - header.linkname = linkSink.linkname - self._encode(header) - callback() - }) - - return linkSink - } - - this._encode(header) - - if (header.type !== 'file' && header.type !== 'contiguous-file') { - process.nextTick(callback) - return new Void() - } - - var sink = new Sink(this) - - this._stream = sink - - eos(sink, function (err) { - self._stream = null - - if (err) { // stream was closed - self.destroy() - return callback(err) - } +"use strict"; - if (sink.written !== header.size) { // corrupting tar - self.destroy() - return callback(new Error('size mismatch')) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1566)); +const PostgrestReservedCharsRegexp = new RegExp('[,()]'); +class PostgrestFilterBuilder extends PostgrestTransformBuilder_1.default { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; } - - overflow(self, header.size) - if (self._finalizing) self.finalize() - callback() - }) - - return sink -} - -Pack.prototype.finalize = function () { - if (this._stream) { - this._finalizing = true - return - } - - if (this._finalized) return - this._finalized = true - this.push(END_OF_TAR) - this.push(null) -} - -Pack.prototype.destroy = function (err) { - if (this._destroyed) return - this._destroyed = true - - if (err) this.emit('error', err) - this.emit('close') - if (this._stream && this._stream.destroy) this._stream.destroy() -} - -Pack.prototype._encode = function (header) { - if (!header.pax) { - var buf = headers.encode(header) - if (buf) { - this.push(buf) - return + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; } - } - this._encodePax(header) -} - -Pack.prototype._encodePax = function (header) { - var paxHeader = headers.encodePax({ - name: header.name, - linkname: header.linkname, - pax: header.pax - }) - - var newHeader = { - name: 'PaxHeader', - mode: header.mode, - uid: header.uid, - gid: header.gid, - size: paxHeader.length, - mtime: header.mtime, - type: 'pax-header', - linkname: header.linkname && 'PaxHeader', - uname: header.uname, - gname: header.gname, - devmajor: header.devmajor, - devminor: header.devminor - } - - this.push(headers.encode(newHeader)) - this.push(paxHeader) - overflow(this, paxHeader.length) - - newHeader.size = header.size - newHeader.type = header.type - this.push(headers.encode(newHeader)) -} - -Pack.prototype._read = function (n) { - var drain = this._drain - this._drain = noop - drain() -} - -module.exports = Pack - - -/***/ }), - -/***/ 84256: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var punycode = __nccwpck_require__(85477); -var mappingTable = __nccwpck_require__(72020); - -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; + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; } - } - - 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; + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; } - } - - 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; + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; } - } - - 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; + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; } - } - - 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; + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; } - }); - - if (verifyDnsLength) { - var total = labels.slice(0, labels.length - 1).join(".").length; - if (total.length > 253 || total.length === 0) { - result.error = true; + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`); + return this; } - - for (var i=0; i < labels.length; ++i) { - if (labels.length > 63 || labels.length === 0) { - result.error = true; - break; - } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`); + return this; } - } - - 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; - - -/***/ }), - -/***/ 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); + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = Array.from(new Set(values)) + .map((s) => { + // handle postgrest reserved characters + // https://postgrest.org/en/v7.0.0/api.html#reserved-characters + if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) + return `"${s}"`; + else + return `${s}`; + }) + .join(','); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === 'string') { + // range types can be inclusive '[', ']' or exclusive '(', ')' so just + // keep it simple and accept a string + this.url.searchParams.append(column, `cs.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cs.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `cd.${value}`); + } + else if (Array.isArray(value)) { + // array + this.url.searchParams.append(column, `cd.{${value.join(',')}}`); + } + else { + // json + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; + } + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === 'string') { + // range + this.url.searchParams.append(column, `ov.${value}`); + } + else { + // array + this.url.searchParams.append(column, `ov.{${value.join(',')}}`); + } + return this; + } + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config, type } = {}) { + let typePart = ''; + if (type === 'plain') { + typePart = 'pl'; + } + else if (type === 'phrase') { + typePart = 'ph'; + } + else if (type === 'websearch') { + typePart = 'w'; + } + const configPart = config === undefined ? '' : `(${config})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; + } + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; + } + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; + } + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or(filters, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.or` : 'or'; + this.url.searchParams.append(key, `(${filters})`); + return this; + } + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; + } +} +exports["default"] = PostgrestFilterBuilder; +//# sourceMappingURL=PostgrestFilterBuilder.js.map + +/***/ }), + +/***/ 50: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); +class PostgrestQueryBuilder { + constructor(url, { headers = {}, schema, fetch, }) { + this.url = url; + this.headers = new Headers(headers); + this.schema = schema; + this.fetch = fetch; + } + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, options) { + const { head = false, count } = options !== null && options !== void 0 ? options : {}; + const method = head ? 'HEAD' : 'GET'; + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch, + }); + } + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. Only applies for bulk + * inserts. + */ + insert(values, { count, defaultToNull = true, } = {}) { + var _a; + const method = 'POST'; + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + if (!defaultToNull) { + this.headers.append('Prefer', `missing=default`); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. + */ + upsert(values, { onConflict, ignoreDuplicates = false, count, defaultToNull = true, } = {}) { + var _a; + const method = 'POST'; + this.headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`); + if (onConflict !== undefined) + this.url.searchParams.set('on_conflict', onConflict); + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + if (!defaultToNull) { + this.headers.append('Prefer', 'missing=default'); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set('columns', uniqueColumns.join(',')); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count, } = {}) { + var _a; + const method = 'PATCH'; + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count, } = {}) { + var _a; + const method = 'DELETE'; + if (count) { + this.headers.append('Prefer', `count=${count}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch, + }); + } +} +exports["default"] = PostgrestQueryBuilder; +//# sourceMappingURL=PostgrestQueryBuilder.js.map /***/ }), -/***/ 74294: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1566: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = __nccwpck_require__(54219); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1049)); +class PostgrestTransformBuilder extends PostgrestBuilder_1.default { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + // Remove whitespaces except when quoted + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : '*') + .split('') + .map((c) => { + if (/\s/.test(c) && !quoted) { + return ''; + } + if (c === '"') { + quoted = !quoted; + } + return c; + }) + .join(''); + this.url.searchParams.set('select', cleanedColumns); + this.headers.append('Prefer', 'return=representation'); + return this; + } + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order referenced tables, but it only affects the ordering of the + * parent table if you use `!inner` in the query. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.referencedTable - Set this to order a referenced table by + * its columns + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable, } = {}) { + const key = referencedTable ? `${referencedTable}.order` : 'order'; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'}`); + return this; + } + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit(count, { foreignTable, referencedTable = foreignTable, } = {}) { + const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(key, `${count}`); + return this; + } + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range(from, to, { foreignTable, referencedTable = foreignTable, } = {}) { + const keyOffset = typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`; + const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + // Range is inclusive, so add 1 + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; + } + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers.set('Accept', 'application/vnd.pgrst.object+json'); + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + // Temporary partial fix for https://github.com/supabase/postgrest-js/issues/361 + // Issue persists e.g. for `.insert([...]).select().maybeSingle()` + if (this.method === 'GET') { + this.headers.set('Accept', 'application/json'); + } + else { + this.headers.set('Accept', 'application/vnd.pgrst.object+json'); + } + this.isMaybeSingle = true; + return this; + } + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers.set('Accept', 'text/csv'); + return this; + } + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers.set('Accept', 'application/geo+json'); + return this; + } + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format = 'text', } = {}) { + var _a; + const options = [ + analyze ? 'analyze' : null, + verbose ? 'verbose' : null, + settings ? 'settings' : null, + buffers ? 'buffers' : null, + wal ? 'wal' : null, + ] + .filter(Boolean) + .join('|'); + // An Accept header can carry multiple media types but postgrest-js always sends one + const forMediatype = (_a = this.headers.get('Accept')) !== null && _a !== void 0 ? _a : 'application/json'; + this.headers.set('Accept', `application/vnd.pgrst.plan+${format}; for="${forMediatype}"; options=${options};`); + if (format === 'json') { + return this; + } + else { + return this; + } + } + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + this.headers.append('Prefer', 'tx=rollback'); + return this; + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + return this; + } + /** + * Set the maximum number of rows that can be affected by the query. + * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. + * + * @param value - The maximum number of rows that can be affected + */ + maxAffected(value) { + this.headers.append('Prefer', 'handling=strict'); + this.headers.append('Prefer', `max-affected=${value}`); + return this; + } +} +exports["default"] = PostgrestTransformBuilder; +//# sourceMappingURL=PostgrestTransformBuilder.js.map /***/ }), -/***/ 54219: +/***/ 1178: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +// Always update wrapper.mjs when updating this file. +const PostgrestClient_1 = tslib_1.__importDefault(__nccwpck_require__(1526)); +exports.PostgrestClient = PostgrestClient_1.default; +const PostgrestQueryBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(50)); +exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; +const PostgrestFilterBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(6671)); +exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; +const PostgrestTransformBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1566)); +exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; +const PostgrestBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(1049)); +exports.PostgrestBuilder = PostgrestBuilder_1.default; +const PostgrestError_1 = tslib_1.__importDefault(__nccwpck_require__(7317)); +exports.PostgrestError = PostgrestError_1.default; +exports["default"] = { + PostgrestClient: PostgrestClient_1.default, + PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, + PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, + PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, + PostgrestBuilder: PostgrestBuilder_1.default, + PostgrestError: PostgrestError_1.default, +}; +//# sourceMappingURL=index.js.map -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; -} +/***/ }), +/***/ 9911: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -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 = []; +"use strict"; - 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; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(88); +const push_1 = tslib_1.__importDefault(__nccwpck_require__(2292)); +const timer_1 = tslib_1.__importDefault(__nccwpck_require__(8960)); +const RealtimePresence_1 = tslib_1.__importDefault(__nccwpck_require__(5583)); +const Transformers = tslib_1.__importStar(__nccwpck_require__(1140)); +const transformers_1 = __nccwpck_require__(1140); +var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; +(function (REALTIME_POSTGRES_CHANGES_LISTEN_EVENT) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT["DELETE"] = "DELETE"; +})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = {})); +var REALTIME_LISTEN_TYPES; +(function (REALTIME_LISTEN_TYPES) { + REALTIME_LISTEN_TYPES["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES["PRESENCE"] = "presence"; + REALTIME_LISTEN_TYPES["POSTGRES_CHANGES"] = "postgres_changes"; + REALTIME_LISTEN_TYPES["SYSTEM"] = "system"; +})(REALTIME_LISTEN_TYPES || (exports.REALTIME_LISTEN_TYPES = REALTIME_LISTEN_TYPES = {})); +var REALTIME_SUBSCRIBE_STATES; +(function (REALTIME_SUBSCRIBE_STATES) { + REALTIME_SUBSCRIBE_STATES["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES["CHANNEL_ERROR"] = "CHANNEL_ERROR"; +})(REALTIME_SUBSCRIBE_STATES || (exports.REALTIME_SUBSCRIBE_STATES = REALTIME_SUBSCRIBE_STATES = {})); +exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES; +/** A channel is the basic building block of Realtime + * and narrows the scope of data flow to subscribed clients. + * You can think of a channel as a chatroom where participants are able to see who's online + * and send and receive messages. + */ +class RealtimeChannel { + constructor( + /** Topic name can be any string. */ + topic, params = { config: {} }, socket) { + var _a, _b; + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = constants_1.CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.subTopic = topic.replace(/^realtime:/i, ''); + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: '', enabled: false }, + private: false, + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive('ok', () => { + this.state = constants_1.CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`); + this.state = constants_1.CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('timeout', () => { + if (!this._isJoining()) { + return; + } + this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive('error', (reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log('channel', `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence_1.default(this); + this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint); + this.private = this.params.config.private || false; + if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { + throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; + } + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b, _c; + if (!this.socket.isConnected()) { + this.socket.connect(); + } + if (this.state == constants_1.CHANNEL_STATES.closed) { + const { config: { broadcast, presence, private: isPrivate }, } = this.params; + const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r) => r.filter)) !== null && _b !== void 0 ? _b : []; + const presence_enabled = (!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE] && + this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length > 0) || + ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; + const accessTokenPayload = {}; + const config = { + broadcast, + presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), + postgres_changes, + private: isPrivate, + }; + if (this.socket.accessTokenValue) { + accessTokenPayload.access_token = this.socket.accessTokenValue; + } + this._onError((e) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, e)); + this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CLOSED)); + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush + .receive('ok', async ({ postgres_changes }) => { + var _a; + this.socket.setAuth(); + if (postgres_changes === undefined) { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a !== void 0 ? _a : 0; + const newPostgresBindings = []; + for (let i = 0; i < bindingsLen; i++) { + const clientPostgresBinding = clientPostgresBindings[i]; + const { filter: { event, schema, table, filter }, } = clientPostgresBinding; + const serverPostgresFilter = postgres_changes && postgres_changes[i]; + if (serverPostgresFilter && + serverPostgresFilter.event === event && + serverPostgresFilter.schema === schema && + serverPostgresFilter.table === table && + serverPostgresFilter.filter === filter) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } + else { + this.unsubscribe(); + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error('mismatch between server and client bindings for postgres changes')); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED); + return; + } + }) + .receive('error', (error) => { + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(', ') || 'error'))); + return; + }) + .receive('timeout', () => { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES.TIMED_OUT); + return; + }); + } + return this; + } + presenceState() { + return this.presence.state; + } + async track(payload, opts = {}) { + return await this.send({ + type: 'presence', + event: 'track', + payload, + }, opts.timeout || this.timeout); + } + async untrack(opts = {}) { + return await this.send({ + type: 'presence', + event: 'untrack', + }, opts); + } + on(type, filter, callback) { + if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES.PRESENCE) { + this.socket.log('channel', `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); + this.unsubscribe().then(() => this.subscribe()); + } + return this._on(type, filter, callback); + } + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + async httpSend(event, payload, opts = {}) { + var _a; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + if (payload === undefined || payload === null) { + return Promise.reject('Payload is required for httpSend()'); + } + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: payload, + private: this.private, + }, + ], + }), + }; + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + if (response.status === 202) { + return { success: true }; + } + let errorMessage = response.statusText; + try { + const errorBody = await response.json(); + errorMessage = errorBody.error || errorBody.message || errorMessage; + } + catch (_b) { } + return Promise.reject(new Error(errorMessage)); } - 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); + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send(args, opts = {}) { + var _a, _b; + if (!this._canPush() && args.type === 'broadcast') { + console.warn('Realtime send() is automatically falling back to REST API. ' + + 'This behavior will be deprecated in the future. ' + + 'Please use httpSend() explicitly for REST delivery.'); + const { event, payload: endpoint_payload } = args; + const authorization = this.socket.accessTokenValue + ? `Bearer ${this.socket.accessTokenValue}` + : ''; + const options = { + method: 'POST', + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : '', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: endpoint_payload, + private: this.private, + }, + ], + }), + }; + try { + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); + return response.ok ? 'ok' : 'error'; + } + catch (error) { + if (error.name === 'AbortError') { + return 'timed out'; + } + else { + return 'error'; + } + } + } + else { + return new Promise((resolve) => { + var _a, _b, _c; + const push = this._push(args.type, args, opts.timeout || this.timeout); + if (args.type === 'broadcast' && !((_c = (_b = (_a = this.params) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve('ok'); + } + push.receive('ok', () => resolve('ok')); + push.receive('error', () => resolve('error')); + push.receive('timeout', () => resolve('timed out')); + }); + } } - - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); } - }); -}; - -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 + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = constants_1.CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log('channel', `leave ${this.topic}`); + this._trigger(constants_1.CHANNEL_EVENTS.close, 'leave', this._joinRef()); + }; + this.joinPush.destroy(); + let leavePush = null; + return new Promise((resolve) => { + leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); + leavePush + .receive('ok', () => { + onClose(); + resolve('ok'); + }) + .receive('timeout', () => { + onClose(); + resolve('timed out'); + }) + .receive('error', () => { + resolve('error'); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger('ok', {}); + } + }).finally(() => { + leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); + }); } - }); - 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; + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown() { + this.pushBuffer.forEach((push) => push.destroy()); + this.pushBuffer = []; + this.rejoinTimer.reset(); + this.joinPush.destroy(); + this.state = constants_1.CHANNEL_STATES.closed; + this.bindings = {}; } - 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; + /** @internal */ + async _fetchWithTimeout(url, options, timeout) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); + clearTimeout(id); + return response; } - 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]; + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new push_1.default(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } + else { + this._addToPushBuffer(pushEvent); + } + return pushEvent; + } + /** @internal */ + _addToPushBuffer(pushEvent) { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + // Enforce buffer size limit + if (this.pushBuffer.length > constants_1.MAX_PUSH_BUFFER_SIZE) { + const removedPush = this.pushBuffer.shift(); + if (removedPush) { + removedPush.destroy(); + this.socket.log('channel', `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); + } + } + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join } = constants_1.CHANNEL_EVENTS; + const events = [close, error, leave, join]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw 'channel onMessage callbacks must return the payload, modified or unmodified'; + } + if (['insert', 'update', 'delete'].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind) => { + var _a, _b, _c; + return ((_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event) === '*' || ((_c = (_b = bind.filter) === null || _b === void 0 ? void 0 : _b.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; + }).map((bind) => bind.callback(handledPayload, ref)); + } + else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind) => { + var _a, _b, _c, _d, _e, _f; + if (['broadcast', 'presence', 'postgres_changes'].includes(typeLower)) { + if ('id' in bind) { + const bindId = bind.id; + const bindEvent = (_a = bind.filter) === null || _a === void 0 ? void 0 : _a.event; + return (bindId && + ((_b = payload.ids) === null || _b === void 0 ? void 0 : _b.includes(bindId)) && + (bindEvent === '*' || + (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase()))); + } + else { + const bindEvent = (_e = (_d = bind === null || bind === void 0 ? void 0 : bind.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e === void 0 ? void 0 : _e.toLocaleLowerCase(); + return bindEvent === '*' || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); + } + } + else { + return bind.type.toLocaleLowerCase() === typeLower; + } + }).map((bind) => { + if (typeof handledPayload === 'object' && 'ids' in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema, table, commit_timestamp, type, errors } = postgresChanges; + const enrichedPayload = { + schema: schema, + table: table, + commit_timestamp: commit_timestamp, + eventType: type, + new: {}, + old: {}, + errors: errors, + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === constants_1.CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === constants_1.CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === constants_1.CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === constants_1.CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter: filter, + callback: callback, + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } + else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + if (this.bindings[typeLower]) { + this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => { + var _a; + return !(((_a = bind.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && + RealtimeChannel.isEqual(bind.filter, filter)); + }); + } + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k in obj1) { + if (obj1[k] !== obj2[k]) { + return false; + } + } + return true; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; } - } + this.socket._leaveOpenTopic(this.topic); + this.state = constants_1.CHANNEL_STATES.joining; + this.joinPush.resend(timeout); } - } - 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:'); + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {}, + }; + if (payload.type === 'INSERT' || payload.type === 'UPDATE') { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === 'UPDATE' || payload.type === 'DELETE') { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; } - console.error.apply(console, args); - } -} else { - debug = function() {}; } -exports.debug = debug; // for test - +exports["default"] = RealtimeChannel; +//# sourceMappingURL=RealtimeChannel.js.map /***/ }), -/***/ 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; - } +/***/ 9103: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; - } +"use strict"; - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(3478)); +const constants_1 = __nccwpck_require__(88); +const serializer_1 = tslib_1.__importDefault(__nccwpck_require__(5360)); +const timer_1 = tslib_1.__importDefault(__nccwpck_require__(8960)); +const transformers_1 = __nccwpck_require__(1140); +const RealtimeChannel_1 = tslib_1.__importDefault(__nccwpck_require__(9911)); +const noop = () => { }; +// Connection-related constants +const CONNECTION_TIMEOUTS = { + HEARTBEAT_INTERVAL: 25000, + RECONNECT_DELAY: 10, + HEARTBEAT_TIMEOUT_FALLBACK: 100, }; - -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); +const RECONNECT_INTERVALS = [1000, 2000, 5000, 10000]; +const DEFAULT_RECONNECT_FALLBACK = 10000; +const WORKER_SCRIPT = ` + addEventListener("message", (e) => { + if (e.data.event === "start") { + setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); + } + });`; +class RealtimeClient { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + */ + constructor(endPoint, options) { + var _a; + this.accessTokenValue = null; + this.apiKey = null; + this.channels = new Array(); + this.endPoint = ''; + this.httpEndpoint = ''; + /** @deprecated headers cannot be set on websocket connections */ + this.headers = {}; + this.params = {}; + this.timeout = constants_1.DEFAULT_TIMEOUT; + this.transport = null; + this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.heartbeatTimer = undefined; + this.pendingHeartbeatRef = null; + this.heartbeatCallback = noop; + this.ref = 0; + this.reconnectTimer = null; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new serializer_1.default(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [], + }; + this.accessToken = null; + this._connectionState = 'disconnected'; + this._wasManualDisconnect = false; + this._authPromise = null; + /** + * Use either custom fetch, if provided, or default fetch to make HTTP requests + * + * @internal + */ + this._resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + // Validate required parameters + if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) { + throw new Error('API key is required to connect to Realtime'); } - } + this.apiKey = options.params.apikey; + // Initialize endpoint URLs + this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; + this.httpEndpoint = (0, transformers_1.httpEndpointURL)(endPoint); + this._initializeOptions(options); + this._setupReconnectionTimer(); + this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); } - - // 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; + /** + * Connects the socket, unless already connected. + */ + connect() { + // Skip if already connecting, disconnecting, or connected + if (this.isConnecting() || + this.isDisconnecting() || + (this.conn !== null && this.isConnected())) { + return; + } + this._setConnectionState('connecting'); + this._setAuthSafely('connect'); + // Establish WebSocket connection + if (this.transport) { + // Use custom transport if provided + this.conn = new this.transport(this.endpointURL()); + } + else { + // Try to use native WebSocket + try { + this.conn = websocket_factory_1.default.createWebSocket(this.endpointURL()); + } + catch (error) { + this._setConnectionState('disconnected'); + const errorMessage = error.message; + // Provide helpful error message based on environment + if (errorMessage.includes('Node.js')) { + throw new Error(`${errorMessage}\n\n` + + 'To use Realtime in Node.js, you need to provide a WebSocket implementation:\n\n' + + 'Option 1: Use Node.js 22+ which has native WebSocket support\n' + + 'Option 2: Install and provide the "ws" package:\n\n' + + ' npm install ws\n\n' + + ' import ws from "ws"\n' + + ' const client = new RealtimeClient(url, {\n' + + ' ...options,\n' + + ' transport: ws\n' + + ' })'); + } + throw new Error(`WebSocket not available: ${errorMessage}`); + } + } + this._setupConnectionHandlers(); } - 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); - }); + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: constants_1.VSN })); + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.isDisconnecting()) { + return; + } + this._setConnectionState('disconnecting', true); + if (this.conn) { + // Setup fallback timer to prevent hanging in disconnecting state + const fallbackTimer = setTimeout(() => { + this._setConnectionState('disconnected'); + }, 100); + this.conn.onclose = () => { + clearTimeout(fallbackTimer); + this._setConnectionState('disconnected'); + }; + // Close the WebSocket connection + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ''); + } + else { + this.conn.close(); + } + this._teardownConnection(); + } + else { + this._setConnectionState('disconnected'); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel) { + const status = await channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + } + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels() { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.channels = []; + this.disconnect(); + return values_1; + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case constants_1.SOCKET_STATES.connecting: + return constants_1.CONNECTION_STATE.Connecting; + case constants_1.SOCKET_STATES.open: + return constants_1.CONNECTION_STATE.Open; + case constants_1.SOCKET_STATES.closing: + return constants_1.CONNECTION_STATE.Closing; + default: + return constants_1.CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === constants_1.CONNECTION_STATE.Open; + } + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting() { + return this._connectionState === 'connecting'; + } + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting() { + return this._connectionState === 'disconnecting'; + } + channel(topic, params = { config: {} }) { + const realtimeTopic = `realtime:${topic}`; + const exists = this.getChannels().find((c) => c.topic === realtimeTopic); + if (!exists) { + const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } + else { + return exists; + } + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + const callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log('push', `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + callback(); + } + else { + this.sendBuffer.push(callback); + } } - } -})(); - -})( true && module.exports ? module.exports : (self.nacl = self.nacl || {})); - - -/***/ }), - -/***/ 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 + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * @param token A JWT string to override the token set on the client. + */ + async setAuth(token = null) { + this._authPromise = this._performAuth(token); + try { + await this._authPromise; + } + finally { + this._authPromise = null; + } } - - if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { - throw new InvalidArgumentError('invalid url') + /** + * Sends a heartbeat message if the socket is connected. + */ + async sendHeartbeat() { + var _a; + if (!this.isConnected()) { + try { + this.heartbeatCallback('disconnected'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + return; + } + // Handle heartbeat timeout and force reconnection if needed + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log('transport', 'heartbeat timeout. Attempting to re-establish connection'); + try { + this.heartbeatCallback('timeout'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + // Force reconnection after heartbeat timeout + this._wasManualDisconnect = false; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, 'heartbeat timeout'); + setTimeout(() => { + var _a; + if (!this.isConnected()) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); + return; + } + // Send heartbeat message to server + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: 'phoenix', + event: 'heartbeat', + payload: {}, + ref: this.pendingHeartbeatRef, + }); + try { + this.heartbeatCallback('sent'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + this._setAuthSafely('heartbeat'); } - - if (opts != null && typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + onHeartbeat(callback) { + this.heartbeatCallback = callback; } - - 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) + /** + * Flushes send buffer + */ + flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } } - - const { agent, dispatcher = getGlobalDispatcher() } = opts - - if (agent) { - throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } + else { + this.ref = newRef; + } + return this.ref.toString(); } - - 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) + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c) => c.topic === topic && (c._isJoined() || c._isJoining())); + if (dupChannel) { + this.log('transport', `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } } - - try { - return await fetchImpl(...arguments) - } catch (err) { - if (typeof err === 'object') { - Error.captureStackTrace(err, this) - } - - throw err + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c) => c.topic !== channel.topic); } - } - 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.') + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + // Handle heartbeat responses + if (msg.topic === 'phoenix' && msg.event === 'phx_reply') { + try { + this.heartbeatCallback(msg.payload.status === 'ok' ? 'ok' : 'error'); + } + catch (e) { + this.log('error', 'error in heartbeat callback', e); + } + } + // Handle pending heartbeat reference cleanup + if (msg.ref && msg.ref === this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + } + // Log incoming message + const { topic, event, payload, ref } = msg; + const refString = ref ? `(${ref})` : ''; + const status = payload.status || ''; + this.log('receive', `${status} ${topic} ${event} ${refString}`.trim(), payload); + // Route message to appropriate channels + this.channels + .filter((channel) => channel._isMember(topic)) + .forEach((channel) => channel._trigger(event, payload, ref)); + this._triggerStateCallbacks('message', msg); + }); } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') + /** + * Clear specific timer + * @internal + */ + _clearTimer(timer) { + var _a; + if (timer === 'heartbeat' && this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = undefined; + } + else if (timer === 'reconnect') { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset(); + } } - - if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { - throw new InvalidArgumentError('maxRedirections must be a positive number') + /** + * Clear all timers + * @internal + */ + _clearAllTimers() { + this._clearTimer('heartbeat'); + this._clearTimer('reconnect'); } - - if (connect && typeof connect !== 'function') { - connect = { ...connect } + /** + * Setup connection handlers for WebSocket events + * @internal + */ + _setupConnectionHandlers() { + if (!this.conn) + return; + // Set binary type if supported (browsers and most WebSocket implementations) + if ('binaryType' in this.conn) { + ; + this.conn.binaryType = 'arraybuffer'; + } + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); } - - 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]) + /** + * Teardown connection and cleanup resources + * @internal + */ + _teardownConnection() { + if (this.conn) { + this.conn.onopen = null; + this.conn.onerror = null; + this.conn.onmessage = null; + this.conn.onclose = null; + this.conn = null; + } + this._clearAllTimers(); + this.channels.forEach((channel) => channel.teardown()); } - - this[kOnConnect] = (origin, targets) => { - agent.emit('connect', origin, [agent, ...targets]) + /** @internal */ + _onConnOpen() { + this._setConnectionState('connected'); + this.log('transport', `connected to ${this.endpointURL()}`); + this.flushSendBuffer(); + this._clearTimer('reconnect'); + if (!this.worker) { + this._startHeartbeat(); + } + else { + if (!this.workerRef) { + this._startWorkerHeartbeat(); + } + } + this._triggerStateCallbacks('open'); } - - this[kOnDisconnect] = (origin, targets, err) => { - agent.emit('disconnect', origin, [agent, ...targets], err) + /** @internal */ + _startHeartbeat() { + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); } - - this[kOnConnectionError] = (origin, targets, err) => { - agent.emit('connectionError', origin, [agent, ...targets], err) + /** @internal */ + _startWorkerHeartbeat() { + if (this.workerUrl) { + this.log('worker', `starting worker for from ${this.workerUrl}`); + } + else { + this.log('worker', `starting default worker`); + } + const objectUrl = this._workerObjectUrl(this.workerUrl); + this.workerRef = new Worker(objectUrl); + this.workerRef.onerror = (error) => { + this.log('worker', 'worker error', error.message); + this.workerRef.terminate(); + }; + this.workerRef.onmessage = (event) => { + if (event.data.event === 'keepAlive') { + this.sendHeartbeat(); + } + }; + this.workerRef.postMessage({ + event: 'start', + interval: this.heartbeatIntervalMs, + }); } - } - - 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] - } + /** @internal */ + _onConnClose(event) { + var _a; + this._setConnectionState('disconnected'); + this.log('transport', 'close', event); + this._triggerChanError(); + this._clearTimer('heartbeat'); + // Only schedule reconnection if it wasn't a manual disconnect + if (!this._wasManualDisconnect) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + this._triggerStateCallbacks('close', event); } - 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.') + /** @internal */ + _onConnError(error) { + this._setConnectionState('disconnected'); + this.log('transport', `${error}`); + this._triggerChanError(); + this._triggerStateCallbacks('error', error); } - - 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) + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); } - - 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()) - } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? '&' : '?'; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; } - - 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)) - } + _workerObjectUrl(url) { + let result_url; + if (url) { + result_url = url; + } + else { + const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' }); + result_url = URL.createObjectURL(blob); + } + return result_url; } - - 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') + /** + * Set connection state with proper state management + * @internal + */ + _setConnectionState(state, manual = false) { + this._connectionState = state; + if (state === 'connecting') { + this._wasManualDisconnect = false; + } + else if (state === 'disconnecting') { + this._wasManualDisconnect = manual; + } } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') + /** + * Perform the actual auth operation + * @internal + */ + async _performAuth(token = null) { + let tokenToSend; + if (token) { + tokenToSend = token; + } + else if (this.accessToken) { + // Always call the accessToken callback to get fresh token + tokenToSend = await this.accessToken(); + } + else { + tokenToSend = this.accessTokenValue; + } + if (this.accessTokenValue != tokenToSend) { + this.accessTokenValue = tokenToSend; + this.channels.forEach((channel) => { + const payload = { + access_token: tokenToSend, + version: constants_1.DEFAULT_VERSION, + }; + tokenToSend && channel.updateJoinPayload(payload); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(constants_1.CHANNEL_EVENTS.access_token, { + access_token: tokenToSend, + }); + } + }); + } } - - 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') + /** + * Wait for any in-flight auth operations to complete + * @internal + */ + async _waitForAuthIfNeeded() { + if (this._authPromise) { + await this._authPromise; + } } - - 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() + /** + * Safely call setAuth with standardized error handling + * @internal + */ + _setAuthSafely(context = 'general') { + this.setAuth().catch((e) => { + this.log('error', `error setting auth in ${context}`, e); + }); } - - 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) + /** + * Trigger state change callbacks with proper error handling + * @internal + */ + _triggerStateCallbacks(event, data) { + try { + this.stateChangeCallbacks[event].forEach((callback) => { + try { + callback(data); + } + catch (e) { + this.log('error', `error in ${event} callback`, e); + } + }); + } + catch (e) { + this.log('error', `error triggering ${event} callbacks`, e); + } } - - 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 }) - }) + /** + * Setup reconnection timer with proper configuration + * @internal + */ + _setupReconnectionTimer() { + this.reconnectTimer = new timer_1.default(async () => { + setTimeout(async () => { + await this._waitForAuthIfNeeded(); + if (!this.isConnected()) { + this.connect(); + } + }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); + }, this.reconnectAfterMs); } - } -} - -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 + /** + * Initialize client options with defaults + * @internal + */ + _initializeOptions(options) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + // Set defaults + this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null; + this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT; + this.heartbeatIntervalMs = + (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; + this.accessToken = (_e = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e !== void 0 ? _e : null; + this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; + // Handle special cases + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { + this.logLevel = options.logLevel || options.log_level; + this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); + } + // Set up functions with defaults + this.reconnectAfterMs = + (_g = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _g !== void 0 ? _g : ((tries) => { + return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; + }); + this.encode = + (_h = options === null || options === void 0 ? void 0 : options.encode) !== null && _h !== void 0 ? _h : ((payload, callback) => { + return callback(JSON.stringify(payload)); + }); + this.decode = (_j = options === null || options === void 0 ? void 0 : options.decode) !== null && _j !== void 0 ? _j : this.serializer.decode.bind(this.serializer); + // Handle worker setup + if (this.worker) { + if (typeof window !== 'undefined' && !window.Worker) { + throw new Error('Web Worker is not supported'); + } + this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; + } } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } } - -module.exports = connect - +exports["default"] = RealtimeClient; +//# sourceMappingURL=RealtimeClient.js.map /***/ }), -/***/ 28752: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5583: +/***/ ((__unused_webpack_module, exports) => { "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() +/* + This file draws heavily from https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/assets/js/phoenix/presence.js + License: https://github.com/phoenixframework/phoenix/blob/d344ec0a732ab4ee204215b31de69cf4be72e3bf/LICENSE.md +*/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; +var REALTIME_PRESENCE_LISTEN_EVENTS; +(function (REALTIME_PRESENCE_LISTEN_EVENTS) { + REALTIME_PRESENCE_LISTEN_EVENTS["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS["LEAVE"] = "leave"; +})(REALTIME_PRESENCE_LISTEN_EVENTS || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS = {})); +class RealtimePresence { + /** + * Initializes the Presence. + * + * @param channel - The RealtimeChannel + * @param opts - The options, + * for example `{events: {state: 'state', diff: 'diff'}}` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.enabled = false; + this.caller = { + onJoin: () => { }, + onLeave: () => { }, + onSync: () => { }, + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: 'presence_state', + diff: 'presence_diff', + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } + else { + this.state = RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger('presence', { + event: 'join', + key, + currentPresences, + newPresences, + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger('presence', { + event: 'leave', + key, + currentPresences, + leftPresences, + }); + }); + this.onSync(() => { + this.channel._trigger('presence', { event: 'sync' }); + }); } - - callback(err) - } -} - -class PipelineHandler extends AsyncResource { - constructor (opts, handler) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m) => m.presence_ref); + const curPresenceRefs = currentPresences.map((m) => m.presence_ref); + const joinedPresences = newPresences.filter((m) => curPresenceRefs.indexOf(m.presence_ref) < 0); + const leftPresences = currentPresences.filter((m) => newPresenceRefs.indexOf(m.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } + else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); } - - if (typeof handler !== 'function') { - throw new InvalidArgumentError('invalid handler') + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves), + }; + if (!onJoin) { + onJoin = () => { }; + } + if (!onLeave) { + onLeave = () => { }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m) => m.presence_ref); + const curPresences = currentPresences.filter((m) => joinedPresenceRefs.indexOf(m.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m) => m.presence_ref); + currentPresences = currentPresences.filter((m) => presenceRefsToRemove.indexOf(m.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; } - - 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') + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ('metas' in presences) { + newState[key] = presences.metas.map((presence) => { + presence['presence_ref'] = presence['phx_ref']; + delete presence['phx_ref']; + delete presence['phx_ref_prev']; + return presence; + }); + } + else { + newState[key] = presences; + } + return newState; + }, {}); } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); } - - 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() + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; } - - 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 + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; } - - 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 + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; } - - if (!body || typeof body.on !== 'function') { - throw new InvalidReturnValueError('expected Readable') + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); } - - 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 - +exports["default"] = RealtimePresence; +//# sourceMappingURL=RealtimePresence.js.map /***/ }), -/***/ 55448: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 442: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; +const tslib_1 = __nccwpck_require__(4351); +const RealtimeClient_1 = tslib_1.__importDefault(__nccwpck_require__(9103)); +exports.RealtimeClient = RealtimeClient_1.default; +const RealtimeChannel_1 = tslib_1.__importStar(__nccwpck_require__(9911)); +exports.RealtimeChannel = RealtimeChannel_1.default; +Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_LISTEN_TYPES; } })); +Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; } })); +Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; } })); +Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", ({ enumerable: true, get: function () { return RealtimeChannel_1.REALTIME_CHANNEL_STATES; } })); +const RealtimePresence_1 = tslib_1.__importStar(__nccwpck_require__(5583)); +exports.RealtimePresence = RealtimePresence_1.default; +Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", ({ enumerable: true, get: function () { return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; } })); +const websocket_factory_1 = tslib_1.__importDefault(__nccwpck_require__(3478)); +exports.WebSocketFactory = websocket_factory_1.default; +//# sourceMappingURL=index.js.map -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 +/***/ 88: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } +"use strict"; - if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { - throw new InvalidArgumentError('invalid highWaterMark') - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.VSN = exports.DEFAULT_VERSION = void 0; +const version_1 = __nccwpck_require__(318); +exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`; +exports.VSN = '1.0.0'; +exports.VERSION = version_1.version; +exports.DEFAULT_TIMEOUT = 10000; +exports.WS_CLOSE_NORMAL = 1000; +exports.MAX_PUSH_BUFFER_SIZE = 100; +var SOCKET_STATES; +(function (SOCKET_STATES) { + SOCKET_STATES[SOCKET_STATES["connecting"] = 0] = "connecting"; + SOCKET_STATES[SOCKET_STATES["open"] = 1] = "open"; + SOCKET_STATES[SOCKET_STATES["closing"] = 2] = "closing"; + SOCKET_STATES[SOCKET_STATES["closed"] = 3] = "closed"; +})(SOCKET_STATES || (exports.SOCKET_STATES = SOCKET_STATES = {})); +var CHANNEL_STATES; +(function (CHANNEL_STATES) { + CHANNEL_STATES["closed"] = "closed"; + CHANNEL_STATES["errored"] = "errored"; + CHANNEL_STATES["joined"] = "joined"; + CHANNEL_STATES["joining"] = "joining"; + CHANNEL_STATES["leaving"] = "leaving"; +})(CHANNEL_STATES || (exports.CHANNEL_STATES = CHANNEL_STATES = {})); +var CHANNEL_EVENTS; +(function (CHANNEL_EVENTS) { + CHANNEL_EVENTS["close"] = "phx_close"; + CHANNEL_EVENTS["error"] = "phx_error"; + CHANNEL_EVENTS["join"] = "phx_join"; + CHANNEL_EVENTS["reply"] = "phx_reply"; + CHANNEL_EVENTS["leave"] = "phx_leave"; + CHANNEL_EVENTS["access_token"] = "access_token"; +})(CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = CHANNEL_EVENTS = {})); +var TRANSPORTS; +(function (TRANSPORTS) { + TRANSPORTS["websocket"] = "websocket"; +})(TRANSPORTS || (exports.TRANSPORTS = TRANSPORTS = {})); +var CONNECTION_STATE; +(function (CONNECTION_STATE) { + CONNECTION_STATE["Connecting"] = "connecting"; + CONNECTION_STATE["Open"] = "open"; + CONNECTION_STATE["Closing"] = "closing"; + CONNECTION_STATE["Closed"] = "closed"; +})(CONNECTION_STATE || (exports.CONNECTION_STATE = CONNECTION_STATE = {})); +//# sourceMappingURL=constants.js.map - 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') - } +/***/ 2292: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } +"use strict"; - super('UNDICI_REQUEST') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err +Object.defineProperty(exports, "__esModule", ({ value: true })); +const constants_1 = __nccwpck_require__(88); +class Push { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = undefined; + this.ref = ''; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; } - - 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) - }) + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ''; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); } - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() + send() { + if (this._hasReceived('timeout')) { + return; + } + this.startTimeout(); + this.sent = true; + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef(), + }); } - - 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 + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); } - - 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 - }) - } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger('timeout', {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); } - } - - 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 }) - }) + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); } - - if (res) { - this.res = null - // Ensure all queued handlers are invoked before destroying res. - queueMicrotask(() => { - util.destroy(res, err) - }) + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); } - - if (body) { - this.body = null - util.destroy(body, err) + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = undefined; } - } -} - -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 + _matchReceive({ status, response }) { + this.recHooks.filter((h) => h.status === status).forEach((h) => h.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } } - -module.exports = request -module.exports.RequestHandler = RequestHandler - +exports["default"] = Push; +//# sourceMappingURL=push.js.map /***/ }), -/***/ 75395: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5360: +/***/ ((__unused_webpack_module, exports) => { "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') +// This file draws heavily from https://github.com/phoenixframework/phoenix/commit/cf098e9cf7a44ee6479d31d911a97d3c7430c6fe +// License: https://github.com/phoenixframework/phoenix/blob/master/LICENSE.md +Object.defineProperty(exports, "__esModule", ({ value: true })); +class Serializer { + constructor() { + this.HEADER_LENGTH = 1; } - - 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 + decode(rawPayload, callback) { + if (rawPayload.constructor === ArrayBuffer) { + return callback(this._binaryDecode(rawPayload)); + } + if (typeof rawPayload === 'string') { + return callback(JSON.parse(rawPayload)); + } + return callback({}); } - - 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) - }) + _binaryDecode(buffer) { + const view = new DataView(buffer); + const decoder = new TextDecoder(); + return this._decodeBroadcast(buffer, view, decoder); } - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() + _decodeBroadcast(buffer, view, decoder) { + const topicSize = view.getUint8(1); + const eventSize = view.getUint8(2); + let offset = this.HEADER_LENGTH + 2; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const event = decoder.decode(buffer.slice(offset, offset + eventSize)); + offset = offset + eventSize; + const data = JSON.parse(decoder.decode(buffer.slice(offset, buffer.byteLength))); + return { ref: null, topic: topic, event: event, payload: data }; } +} +exports["default"] = Serializer; +//# sourceMappingURL=serializer.js.map - this.abort = abort - this.context = context - } +/***/ }), - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { factory, opaque, context, callback, responseHeaders } = this +/***/ 8960: +/***/ ((__unused_webpack_module, exports) => { - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) +"use strict"; - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } - return +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Creates a timer that accepts a `timerCalc` function to perform calculated timeout retries, such as exponential backoff. + * + * @example + * let reconnectTimer = new Timer(() => this.connect(), function(tries){ + * return [1000, 5000, 10000][tries - 1] || 10000 + * }) + * reconnectTimer.scheduleTimeout() // fires after 1000 + * reconnectTimer.scheduleTimeout() // fires after 5000 + * reconnectTimer.reset() + * reconnectTimer.scheduleTimeout() // fires after 1000 + */ +class Timer { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = undefined; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; } + reset() { + this.tries = 0; + clearTimeout(this.timer); + this.timer = undefined; + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } +} +exports["default"] = Timer; +//# sourceMappingURL=timer.js.map - 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') - } +/***/ 1140: +/***/ ((__unused_webpack_module, exports) => { - // TODO: Avoid finished. It registers an unnecessary amount of listeners. - finished(res, { readable: false }, (err) => { - const { callback, res, opaque, trailers, abort } = this +"use strict"; - this.res = null - if (err || !res.readable) { - util.destroy(res, err) +/** + * Helpers to convert the change Payload into native JS types. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.httpEndpointURL = exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; +// Adapted from epgsql (src/epgsql_binary.erl), this module licensed under +// 3-clause BSD found here: https://raw.githubusercontent.com/epgsql/epgsql/devel/LICENSE +var PostgresTypes; +(function (PostgresTypes) { + PostgresTypes["abstime"] = "abstime"; + PostgresTypes["bool"] = "bool"; + PostgresTypes["date"] = "date"; + PostgresTypes["daterange"] = "daterange"; + PostgresTypes["float4"] = "float4"; + PostgresTypes["float8"] = "float8"; + PostgresTypes["int2"] = "int2"; + PostgresTypes["int4"] = "int4"; + PostgresTypes["int4range"] = "int4range"; + PostgresTypes["int8"] = "int8"; + PostgresTypes["int8range"] = "int8range"; + PostgresTypes["json"] = "json"; + PostgresTypes["jsonb"] = "jsonb"; + PostgresTypes["money"] = "money"; + PostgresTypes["numeric"] = "numeric"; + PostgresTypes["oid"] = "oid"; + PostgresTypes["reltime"] = "reltime"; + PostgresTypes["text"] = "text"; + PostgresTypes["time"] = "time"; + PostgresTypes["timestamp"] = "timestamp"; + PostgresTypes["timestamptz"] = "timestamptz"; + PostgresTypes["timetz"] = "timetz"; + PostgresTypes["tsrange"] = "tsrange"; + PostgresTypes["tstzrange"] = "tstzrange"; +})(PostgresTypes || (exports.PostgresTypes = PostgresTypes = {})); +/** + * Takes an array of columns and an object of string values then converts each string value + * to its mapped type. + * + * @param {{name: String, type: String}[]} columns + * @param {Object} record + * @param {Object} options The map of various options that can be applied to the mapper + * @param {Array} options.skipTypes The array of types that should not be converted + * + * @example convertChangeData([{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age:'33'}, {}) + * //=>{ first_name: 'Paul', age: 33 } + */ +const convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + if (!record) { + return {}; + } + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); + return acc; + }, {}); +}; +exports.convertChangeData = convertChangeData; +/** + * Converts the value of an individual column. + * + * @param {String} columnName The column that you want to convert + * @param {{name: String, type: String}[]} columns All of the columns + * @param {Object} record The map of string values + * @param {Array} skipTypes An array of types that should not be converted + * @return {object} Useless information + * + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, []) + * //=> 33 + * @example convertColumn('age', [{name: 'first_name', type: 'text'}, {name: 'age', type: 'int4'}], {first_name: 'Paul', age: '33'}, ['int4']) + * //=> "33" + */ +const convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x) => x.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return (0, exports.convertCell)(colType, value); + } + return noop(value); +}; +exports.convertColumn = convertColumn; +/** + * If the value of the cell is `null`, returns null. + * Otherwise converts the string value to the correct type. + * @param {String} type A postgres column type + * @param {String} value The cell value + * + * @example convertCell('bool', 't') + * //=> true + * @example convertCell('int8', '10') + * //=> 10 + * @example convertCell('_int4', '{1,2,3,4}') + * //=> [1,2,3,4] + */ +const convertCell = (type, value) => { + // if data type is an array + if (type.charAt(0) === '_') { + const dataType = type.slice(1, type.length); + return (0, exports.toArray)(value, dataType); + } + // If not null, convert to correct type. + switch (type) { + case PostgresTypes.bool: + return (0, exports.toBoolean)(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return (0, exports.toNumber)(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return (0, exports.toJson)(value); + case PostgresTypes.timestamp: + return (0, exports.toTimestampString)(value); // Format to be consistent with PostgREST + case PostgresTypes.abstime: // To allow users to cast it based on Timezone + case PostgresTypes.date: // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: // To allow users to cast it based on Timezone + case PostgresTypes.timetz: // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + // Return the value for remaining types + return noop(value); + } +}; +exports.convertCell = convertCell; +const noop = (value) => { + return value; +}; +const toBoolean = (value) => { + switch (value) { + case 't': + return true; + case 'f': + return false; + default: + return value; + } +}; +exports.toBoolean = toBoolean; +const toNumber = (value) => { + if (typeof value === 'string') { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; } - - this.callback = null - this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) - - if (err) { - abort() + } + return value; +}; +exports.toNumber = toNumber; +const toJson = (value) => { + if (typeof value === 'string') { + try { + return JSON.parse(value); } - }) + catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; +}; +exports.toJson = toJson; +/** + * Converts a Postgres Array into a native JS array + * + * @example toArray('{}', 'int4') + * //=> [] + * @example toArray('{"[2021-01-01,2021-12-31)","(2021-01-01,2021-12-32]"}', 'daterange') + * //=> ['[2021-01-01,2021-12-31)', '(2021-01-01,2021-12-32]'] + * @example toArray([1,2,3,4], 'int4') + * //=> [1,2,3,4] + */ +const toArray = (value, type) => { + if (typeof value !== 'string') { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + // Confirm value is a Postgres array by checking curly brackets + if (openBrace === '{' && closeBrace === '}') { + let arr; + const valTrim = value.slice(1, lastIdx); + // TODO: find a better solution to separate Postgres array data + try { + arr = JSON.parse('[' + valTrim + ']'); + } + catch (_) { + // WARNING: splitting on comma does not cover all edge cases + arr = valTrim ? valTrim.split(',') : []; + } + return arr.map((val) => (0, exports.convertCell)(type, val)); + } + return value; +}; +exports.toArray = toArray; +/** + * Fixes timestamp to be ISO-8601. Swaps the space between the date and time for a 'T' + * See https://github.com/supabase/supabase/issues/18 + * + * @example toTimestampString('2019-09-10 00:00:00') + * //=> '2019-09-10T00:00:00' + */ +const toTimestampString = (value) => { + if (typeof value === 'string') { + return value.replace(' ', 'T'); + } + return value; +}; +exports.toTimestampString = toTimestampString; +const httpEndpointURL = (socketUrl) => { + const wsUrl = new URL(socketUrl); + wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, 'http'); + wsUrl.pathname = wsUrl.pathname + .replace(/\/+$/, '') // remove all trailing slashes + .replace(/\/socket\/websocket$/i, '') // remove the socket/websocket path + .replace(/\/socket$/i, '') // remove the socket path + .replace(/\/websocket$/i, ''); // remove the websocket path + if (wsUrl.pathname === '' || wsUrl.pathname === '/') { + wsUrl.pathname = '/api/broadcast'; } + else { + wsUrl.pathname = wsUrl.pathname + '/api/broadcast'; + } + return wsUrl.href; +}; +exports.httpEndpointURL = httpEndpointURL; +//# sourceMappingURL=transformers.js.map - res.on('drain', resume) - - this.res = res +/***/ }), - const needDrain = res.writableNeedDrain !== undefined - ? res.writableNeedDrain - : res._writableState && res._writableState.needDrain +/***/ 318: +/***/ ((__unused_webpack_module, exports) => { - return needDrain !== true - } +"use strict"; - onData (chunk) { - const { res } = this +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map - return res ? res.write(chunk) : true - } +/***/ }), - onComplete (trailers) { - const { res } = this +/***/ 3478: +/***/ ((__unused_webpack_module, exports) => { - removeSignal(this) +"use strict"; - if (!res) { - return +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WebSocketFactory = void 0; +class WebSocketFactory { + static detectEnvironment() { + var _a; + if (typeof WebSocket !== 'undefined') { + return { type: 'native', constructor: WebSocket }; + } + if (typeof globalThis !== 'undefined' && typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; + } + if (typeof global !== 'undefined' && typeof global.WebSocket !== 'undefined') { + return { type: 'native', constructor: global.WebSocket }; + } + if (typeof globalThis !== 'undefined' && + typeof globalThis.WebSocketPair !== 'undefined' && + typeof globalThis.WebSocket === 'undefined') { + return { + type: 'cloudflare', + error: 'Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.', + workaround: 'Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.', + }; + } + if ((typeof globalThis !== 'undefined' && globalThis.EdgeRuntime) || + (typeof navigator !== 'undefined' && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes('Vercel-Edge')))) { + return { + type: 'unsupported', + error: 'Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.', + workaround: 'Use serverless functions or a different deployment target for WebSocket functionality.', + }; + } + if (typeof process !== 'undefined') { + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersions = process['versions']; + if (processVersions && processVersions['node']) { + // Remove 'v' prefix if present and parse the major version + const versionString = processVersions['node']; + const nodeVersion = parseInt(versionString.replace(/^v/, '').split('.')[0]); + // Node.js 22+ should have native WebSocket + if (nodeVersion >= 22) { + // Check if native WebSocket is available (should be in Node.js 22+) + if (typeof globalThis.WebSocket !== 'undefined') { + return { type: 'native', constructor: globalThis.WebSocket }; + } + // If not available, user needs to provide it + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, + workaround: 'Provide a WebSocket implementation via the transport option.', + }; + } + // Node.js < 22 doesn't have native WebSocket + return { + type: 'unsupported', + error: `Node.js ${nodeVersion} detected without native WebSocket support.`, + workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\n' + + 'import ws from "ws"\n' + + 'new RealtimeClient(url, { transport: ws })', + }; + } + } + return { + type: 'unsupported', + error: 'Unknown JavaScript runtime without WebSocket support.', + workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.", + }; } - - 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 }) - }) + static getWebSocketConstructor() { + const env = this.detectEnvironment(); + if (env.constructor) { + return env.constructor; + } + let errorMessage = env.error || 'WebSocket not supported in this environment.'; + if (env.workaround) { + errorMessage += `\n\nSuggested solution: ${env.workaround}`; + } + throw new Error(errorMessage); } - - if (body) { - this.body = null - util.destroy(body, err) + static createWebSocket(url, protocols) { + const WS = this.getWebSocketConstructor(); + return new WS(url, protocols); } - } -} - -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 + static isWebSocketSupported() { + try { + const env = this.detectEnvironment(); + return env.type === 'native' || env.type === 'ws'; + } + catch (_a) { + return false; + } } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } } - -module.exports = stream - +exports.WebSocketFactory = WebSocketFactory; +exports["default"] = WebSocketFactory; +//# sourceMappingURL=websocket-factory.js.map /***/ }), -/***/ 36923: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4249: +/***/ ((__unused_webpack_module, 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') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +const StorageFileApi_1 = tslib_1.__importDefault(__nccwpck_require__(710)); +const StorageBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(3528)); +const StorageAnalyticsApi_1 = tslib_1.__importDefault(__nccwpck_require__(7339)); +const vectors_1 = __nccwpck_require__(9380); +class StorageClient extends StorageBucketApi_1.default { + constructor(url, headers = {}, fetch, opts) { + super(url, headers, fetch, opts); } - - 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() + /** + * Perform file operation in a bucket. + * + * @param id The bucket id to operate on. + */ + from(id) { + return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch); } - - 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 }) - }) + /** + * Access vector storage operations. + * + * @returns A StorageVectorsClient instance configured with the current storage settings. + */ + get vectors() { + return new vectors_1.StorageVectorsClient(this.url + '/vector', { + headers: this.headers, + fetch: this.fetch, + }); } - } -} - -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 + /** + * Access analytics storage operations using Iceberg tables. + * + * @returns A StorageAnalyticsApi instance configured with the current storage settings. + * @example + * ```typescript + * const client = createClient(url, key) + * const analytics = client.storage.analytics + * + * // Create an analytics bucket + * await analytics.createBucket('my-analytics-bucket') + * + * // List all analytics buckets + * const { data: buckets } = await analytics.listBuckets() + * + * // Delete an analytics bucket + * await analytics.deleteBucket('old-analytics-bucket') + * ``` + */ + get analytics() { + return new StorageAnalyticsApi_1.default(this.url + '/iceberg', this.headers, this.fetch); } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } } - -module.exports = upgrade - +exports.StorageClient = StorageClient; +//# sourceMappingURL=StorageClient.js.map /***/ }), -/***/ 44059: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5852: +/***/ ((__unused_webpack_module, 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) - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageAnalyticsApi = exports.StorageClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +var StorageClient_1 = __nccwpck_require__(4249); +Object.defineProperty(exports, "StorageClient", ({ enumerable: true, get: function () { return StorageClient_1.StorageClient; } })); +var StorageAnalyticsApi_1 = __nccwpck_require__(7339); +Object.defineProperty(exports, "StorageAnalyticsApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(StorageAnalyticsApi_1).default; } })); +tslib_1.__exportStar(__nccwpck_require__(7222), exports); +tslib_1.__exportStar(__nccwpck_require__(2758), exports); +tslib_1.__exportStar(__nccwpck_require__(9380), exports); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 73858: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9754: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// Ported from https://github.com/nodejs/undici/pull/907 - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_HEADERS = void 0; +const version_1 = __nccwpck_require__(4499); +exports.DEFAULT_HEADERS = { + 'X-Client-Info': `storage-js/${version_1.version}`, +}; +//# sourceMappingURL=constants.js.map -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') +/***/ 2758: +/***/ ((__unused_webpack_module, exports) => { -const noop = () => {} +"use strict"; -module.exports = class BodyReadable extends Readable { - constructor ({ - resume, - abort, - contentType = '', - highWaterMark = 64 * 1024 // Same as nodejs fs streams. - }) { - super({ - autoDestroy: true, - read: resume, - highWaterMark - }) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageUnknownError = exports.StorageApiError = exports.StorageError = void 0; +exports.isStorageError = isStorageError; +class StorageError extends Error { + constructor(message) { + super(message); + this.__isStorageError = true; + this.name = 'StorageError'; + } +} +exports.StorageError = StorageError; +function isStorageError(error) { + return typeof error === 'object' && error !== null && '__isStorageError' in error; +} +class StorageApiError extends StorageError { + constructor(message, status, statusCode) { + super(message); + this.name = 'StorageApiError'; + this.status = status; + this.statusCode = statusCode; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode, + }; + } +} +exports.StorageApiError = StorageApiError; +class StorageUnknownError extends StorageError { + constructor(message, originalError) { + super(message); + this.name = 'StorageUnknownError'; + this.originalError = originalError; + } +} +exports.StorageUnknownError = StorageUnknownError; +//# sourceMappingURL=errors.js.map - this._readableState.dataEmitted = false +/***/ }), - this[kAbort] = abort - this[kConsume] = null - this[kBody] = null - this[kContentType] = contentType +/***/ 3146: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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 - } +"use strict"; - destroy (err) { - if (this.destroyed) { - // Node < 16 - return this +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.get = get; +exports.post = post; +exports.put = put; +exports.head = head; +exports.remove = remove; +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(2758); +const helpers_1 = __nccwpck_require__(5430); +const _getErrorMessage = (err) => { + var _a; + return err.msg || + err.message || + err.error_description || + (typeof err.error === 'string' ? err.error : (_a = err.error) === null || _a === void 0 ? void 0 : _a.message) || + JSON.stringify(err); +}; +const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + const Res = yield (0, helpers_1.resolveResponse)(); + if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + error + .json() + .then((err) => { + const status = error.status || 500; + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || status + ''; + reject(new errors_1.StorageApiError(_getErrorMessage(err), status, statusCode)); + }) + .catch((err) => { + reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err)); + }); + } + else { + reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error)); + } +}); +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET' || !body) { + return params; + } + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + } + else { + params.body = body; } + if (options === null || options === void 0 ? void 0 : options.duplex) { + params.duplex = options.duplex; + } + return Object.assign(Object.assign({}, params), parameters); +}; +function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)) + .then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + return result.json(); + }) + .then((data) => resolve(data)) + .catch((error) => handleError(error, reject, options)); + }); + }); +} +function get(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'GET', url, options, parameters); + }); +} +function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'POST', url, options, parameters, body); + }); +} +function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'PUT', url, options, parameters, body); + }); +} +function head(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'HEAD', url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); + }); +} +function remove(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); + }); +} +//# sourceMappingURL=fetch.js.map - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } +/***/ }), - if (err) { - this[kAbort]() - } +/***/ 5430: +/***/ ((__unused_webpack_module, exports) => { - return super.destroy(err) - } +"use strict"; - emit (ev, ...args) { - if (ev === 'data') { - // Node < 16.7 - this._readableState.dataEmitted = true - } else if (ev === 'error') { - // Node < 16 - this._readableState.errorEmitted = true +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isPlainObject = exports.recursiveToCamel = exports.resolveResponse = exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); } - return super.emit(ev, ...args) - } - - on (ev, ...args) { - if (ev === 'data' || ev === 'readable') { - this[kReading] = true + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const resolveResponse = () => { + return Response; +}; +exports.resolveResponse = resolveResponse; +const recursiveToCamel = (item) => { + if (Array.isArray(item)) { + return item.map((el) => (0, exports.recursiveToCamel)(el)); } - 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 - ) + else if (typeof item === 'function' || item !== Object(item)) { + return item; } - 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 + const result = {}; + Object.entries(item).forEach(([key, value]) => { + const newKey = key.replace(/([-_][a-z])/gi, (c) => c.toUpperCase().replace(/[-_]/g, '')); + result[newKey] = (0, exports.recursiveToCamel)(value); + }); + return result; +}; +exports.recursiveToCamel = recursiveToCamel; +/** + * Determine if input is a plain object + * An object is plain if it's created by either {}, new Object(), or Object.create(null) + * source: https://github.com/sindresorhus/is-plain-obj + */ +const isPlainObject = (value) => { + if (typeof value !== 'object' || value === null) { + return false; } - return super.push(chunk) - } - - // https://fetch.spec.whatwg.org/#dom-body-text - async text () { - return consume(this, 'text') - } + const prototype = Object.getPrototypeOf(value); + return ((prototype === null || + prototype === Object.prototype || + Object.getPrototypeOf(prototype) === null) && + !(Symbol.toStringTag in value) && + !(Symbol.iterator in value)); +}; +exports.isPlainObject = isPlainObject; +//# sourceMappingURL=helpers.js.map - // 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') - } +/***/ 7222: +/***/ ((__unused_webpack_module, exports) => { - // https://fetch.spec.whatwg.org/#dom-body-arraybuffer - async arrayBuffer () { - return consume(this, 'arrayBuffer') - } +"use strict"; - // https://fetch.spec.whatwg.org/#dom-body-formdata - async formData () { - // TODO: Implement. - throw new NotSupportedError() - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +//# sourceMappingURL=types.js.map - // 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] - } +/***/ 9403: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - dump (opts) { - let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 - const signal = opts && opts.signal +"use strict"; - 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) - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +const VectorIndexApi_1 = tslib_1.__importDefault(__nccwpck_require__(9623)); +const VectorDataApi_1 = tslib_1.__importDefault(__nccwpck_require__(3073)); +const VectorBucketApi_1 = tslib_1.__importDefault(__nccwpck_require__(4268)); +/** + * Main client for interacting with S3 Vectors API + * Provides access to bucket, index, and vector data operations + * + * **Usage Patterns:** + * + * 1. **Via StorageClient (recommended for most use cases):** + * ```typescript + * import { StorageClient } from '@supabase/storage-js' + * + * const storageClient = new StorageClient(url, headers) + * const vectors = storageClient.vectors + * + * // Use vector operations + * await vectors.createBucket('embeddings-prod') + * const bucket = vectors.from('embeddings-prod') + * await bucket.createIndex({ ... }) + * ``` + * + * 2. **Standalone (for vector-only applications):** + * ```typescript + * import { StorageVectorsClient } from '@supabase/storage-js' + * + * const vectorsClient = new StorageVectorsClient('https://api.example.com', { + * headers: { 'Authorization': 'Bearer token' } + * }) + * + * // Access bucket operations + * await vectorsClient.createBucket('embeddings-prod') + * + * // Access index operations via buckets + * const bucket = vectorsClient.from('embeddings-prod') + * await bucket.createIndex({ + * indexName: 'documents', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine' + * }) + * + * // Access vector operations via index + * const index = bucket.index('documents') + * await index.putVectors({ + * vectors: [ + * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } + * ] + * }) + * + * // Query similar vectors + * const { data } = await index.queryVectors({ + * queryVector: { float32: [...] }, + * topK: 5, + * returnDistance: true + * }) + * ``` + */ +class StorageVectorsClient extends VectorBucketApi_1.default { + constructor(url, options = {}) { + super(url, options.headers || {}, options.fetch); } - - if (this.closed) { - return Promise.resolve(null) + /** + * Access operations for a specific vector bucket + * Returns a scoped client for index and vector operations within the bucket + * + * @param vectorBucketName - Name of the vector bucket + * @returns Bucket-scoped client with index and vector operations + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * + * // Create an index in this bucket + * await bucket.createIndex({ + * indexName: 'documents-openai', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine' + * }) + * + * // List indexes in this bucket + * const { data } = await bucket.listIndexes() + * ``` + */ + from(vectorBucketName) { + return new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch); } - - 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) +exports.StorageVectorsClient = StorageVectorsClient; +/** + * Scoped client for operations within a specific vector bucket + * Provides index management and access to vector operations + */ +class VectorBucketScope extends VectorIndexApi_1.default { + constructor(url, headers, vectorBucketName, fetch) { + super(url, headers, fetch); + this.vectorBucketName = vectorBucketName; + } + /** + * Creates a new vector index in this bucket + * Convenience method that automatically includes the bucket name + * + * @param options - Index configuration (vectorBucketName is automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * await bucket.createIndex({ + * indexName: 'documents-openai', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine', + * metadataConfiguration: { + * nonFilterableMetadataKeys: ['raw_text'] + * } + * }) + * ``` + */ + createIndex(options) { + const _super = Object.create(null, { + createIndex: { get: () => super.createIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.createIndex.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); + } + /** + * Lists indexes in this bucket + * Convenience method that automatically includes the bucket name + * + * @param options - Listing options (vectorBucketName is automatically set) + * @returns Promise with list of indexes or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * const { data } = await bucket.listIndexes({ prefix: 'documents-' }) + * ``` + */ + listIndexes() { + const _super = Object.create(null, { + listIndexes: { get: () => super.listIndexes } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listIndexes.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); + } + /** + * Retrieves metadata for a specific index in this bucket + * Convenience method that automatically includes the bucket name + * + * @param indexName - Name of the index to retrieve + * @returns Promise with index metadata or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * const { data } = await bucket.getIndex('documents-openai') + * console.log('Dimension:', data?.index.dimension) + * ``` + */ + getIndex(indexName) { + const _super = Object.create(null, { + getIndex: { get: () => super.getIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * Deletes an index from this bucket + * Convenience method that automatically includes the bucket name + * + * @param indexName - Name of the index to delete + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = client.bucket('embeddings-prod') + * await bucket.deleteIndex('old-index') + * ``` + */ + deleteIndex(indexName) { + const _super = Object.create(null, { + deleteIndex: { get: () => super.deleteIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * Access operations for a specific index within this bucket + * Returns a scoped client for vector data operations + * + * @param indexName - Name of the index + * @returns Index-scoped client with vector data operations + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * + * // Insert vectors + * await index.putVectors({ + * vectors: [ + * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } + * ] + * }) + * + * // Query similar vectors + * const { data } = await index.queryVectors({ + * queryVector: { float32: [...] }, + * topK: 5 + * }) + * ``` + */ + index(indexName) { + return new VectorIndexScope(this.url, this.headers, this.vectorBucketName, indexName, this.fetch); + } } - -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: [] +exports.VectorBucketScope = VectorBucketScope; +/** + * Scoped client for operations within a specific vector index + * Provides vector data operations (put, get, list, query, delete) + */ +class VectorIndexScope extends VectorDataApi_1.default { + constructor(url, headers, vectorBucketName, indexName, fetch) { + super(url, headers, fetch); + this.vectorBucketName = vectorBucketName; + this.indexName = indexName; + } + /** + * Inserts or updates vectors in this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Vector insertion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * await index.putVectors({ + * vectors: [ + * { + * key: 'doc-1', + * data: { float32: [0.1, 0.2, ...] }, + * metadata: { title: 'Introduction', page: 1 } + * } + * ] + * }) + * ``` + */ + putVectors(options) { + const _super = Object.create(null, { + putVectors: { get: () => super.putVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.putVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * Retrieves vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Vector retrieval options (bucket and index names automatically set) + * @returns Promise with array of vectors or error + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * const { data } = await index.getVectors({ + * keys: ['doc-1', 'doc-2'], + * returnMetadata: true + * }) + * ``` + */ + getVectors(options) { + const _super = Object.create(null, { + getVectors: { get: () => super.getVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * Lists vectors in this index with pagination + * Convenience method that automatically includes bucket and index names + * + * @param options - Listing options (bucket and index names automatically set) + * @returns Promise with array of vectors and pagination token + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * const { data } = await index.listVectors({ + * maxResults: 500, + * returnMetadata: true + * }) + * ``` + */ + listVectors() { + const _super = Object.create(null, { + listVectors: { get: () => super.listVectors } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); } - - 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] })) + /** + * Queries for similar vectors in this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Query options (bucket and index names automatically set) + * @returns Promise with array of similar vectors ordered by distance + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * const { data } = await index.queryVectors({ + * queryVector: { float32: [0.1, 0.2, ...] }, + * topK: 5, + * filter: { category: 'technical' }, + * returnDistance: true, + * returnMetadata: true + * }) + * ``` + */ + queryVectors(options) { + const _super = Object.create(null, { + queryVectors: { get: () => super.queryVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.queryVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * Deletes vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * @param options - Deletion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = client.bucket('embeddings-prod').index('documents-openai') + * await index.deleteVectors({ + * keys: ['doc-1', 'doc-2', 'doc-3'] + * }) + * ``` + */ + deleteVectors(options) { + const _super = Object.create(null, { + deleteVectors: { get: () => super.deleteVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); } - - consumeFinish(consume) - } catch (err) { - stream.destroy(err) - } } +exports.VectorIndexScope = VectorIndexScope; +//# sourceMappingURL=StorageVectorsClient.js.map -function consumePush (consume, chunk) { - consume.length += chunk.length - consume.body.push(chunk) -} +/***/ }), -function consumeFinish (consume, err) { - if (consume.body === null) { - return - } +/***/ 4268: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (err) { - consume.reject(err) - } else { - consume.resolve() - } +"use strict"; - consume.type = null - consume.stream = null - consume.resolve = null - consume.reject = null - consume.length = 0 - consume.body = null +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(6876); +const errors_1 = __nccwpck_require__(3071); +const fetch_1 = __nccwpck_require__(2593); +const helpers_1 = __nccwpck_require__(1176); +/** + * API class for managing Vector Buckets + * Provides methods for creating, reading, listing, and deleting vector buckets + */ +class VectorBucketApi { + /** + * Creates a new VectorBucketApi instance + * @param url - The base URL for the storage vectors API + * @param headers - HTTP headers to include in requests + * @param fetch - Optional custom fetch implementation + */ + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + * @example + * ```typescript + * const client = new VectorBucketApi(url, headers) + * client.throwOnError() + * const { data } = await client.createBucket('my-bucket') // throws on error + * ``` + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Creates a new vector bucket + * Vector buckets are containers for vector indexes and their data + * + * @param vectorBucketName - Unique name for the vector bucket + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorConflictException` if bucket already exists (HTTP 409) + * - `S3VectorMaxBucketsExceeded` if quota exceeded (HTTP 400) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.createBucket('embeddings-prod') + * if (error) { + * console.error('Failed to create bucket:', error.message) + * } + * ``` + */ + createBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves metadata for a specific vector bucket + * Returns bucket configuration including encryption settings and creation time + * + * @param vectorBucketName - Name of the vector bucket to retrieve + * @returns Promise with bucket metadata or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.getBucket('embeddings-prod') + * if (data) { + * console.log('Bucket created at:', new Date(data.vectorBucket.creationTime! * 1000)) + * } + * ``` + */ + getBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Lists vector buckets with optional filtering and pagination + * Supports prefix-based filtering and paginated results + * + * @param options - Listing options + * @param options.prefix - Filter buckets by name prefix + * @param options.maxResults - Maximum results per page (default: 100) + * @param options.nextToken - Pagination token from previous response + * @returns Promise with list of buckets and pagination token + * + * @throws {StorageVectorsApiError} With code: + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // List all buckets with prefix 'prod-' + * const { data, error } = await client.listBuckets({ prefix: 'prod-' }) + * if (data) { + * console.log('Found buckets:', data.buckets.length) + * // Fetch next page if available + * if (data.nextToken) { + * const next = await client.listBuckets({ nextToken: data.nextToken }) + * } + * } + * ``` + */ + listBuckets() { + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectorBuckets`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes a vector bucket + * Bucket must be empty before deletion (all indexes must be removed first) + * + * @param vectorBucketName - Name of the vector bucket to delete + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorBucketNotEmpty` if bucket contains indexes (HTTP 400) + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Delete all indexes first, then delete bucket + * const { error } = await client.deleteBucket('old-bucket') + * if (error?.statusCode === 'S3VectorBucketNotEmpty') { + * console.error('Must delete all indexes first') + * } + * ``` + */ + deleteBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } } - +exports["default"] = VectorBucketApi; +//# sourceMappingURL=VectorBucketApi.js.map /***/ }), -/***/ 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) +/***/ 3073: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let chunks = [] - let limit = 0 +"use strict"; - for await (const chunk of body) { - chunks.push(chunk) - limit += chunk.length - if (limit > 128 * 1024) { - chunks = null - break +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(6876); +const errors_1 = __nccwpck_require__(3071); +const fetch_1 = __nccwpck_require__(2593); +const helpers_1 = __nccwpck_require__(1176); +/** + * API class for managing Vector Data within Vector Indexes + * Provides methods for inserting, querying, listing, and deleting vector embeddings + */ +class VectorDataApi { + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + * @example + * ```typescript + * const client = new VectorDataApi(url, headers) + * client.throwOnError() + * const { data } = await client.putVectors(options) // throws on error + * ``` + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Inserts or updates vectors in batch (upsert operation) + * Accepts 1-500 vectors per request. Larger batches should be split + * + * @param options - Vector insertion options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the target index + * @param options.vectors - Array of vectors to insert/update (1-500 items) + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorConflictException` if duplicate key conflict occurs (HTTP 409) + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.putVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * vectors: [ + * { + * key: 'doc-1', + * data: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions + * metadata: { title: 'Introduction', page: 1 } + * }, + * { + * key: 'doc-2', + * data: { float32: [0.4, 0.5, 0.6, ...] }, + * metadata: { title: 'Conclusion', page: 42 } + * } + * ] + * }) + * ``` + */ + putVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Validate batch size + if (options.vectors.length < 1 || options.vectors.length > 500) { + throw new Error('Vector batch size must be between 1 and 500 items'); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/PutVectors`, options, { + headers: this.headers, + }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves vectors by their keys in batch + * Optionally includes vector data and/or metadata in response + * Additional permissions required when returning data or metadata + * + * @param options - Vector retrieval options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.keys - Array of vector keys to retrieve + * @param options.returnData - Whether to include vector embeddings (requires permission) + * @param options.returnMetadata - Whether to include metadata (requires permission) + * @returns Promise with array of vectors or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.getVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * keys: ['doc-1', 'doc-2', 'doc-3'], + * returnData: false, // Don't return embeddings + * returnMetadata: true // Return metadata only + * }) + * if (data) { + * data.vectors.forEach(v => console.log(v.key, v.metadata)) + * } + * ``` + */ + getVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectors`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Lists/scans vectors in an index with pagination + * Supports parallel scanning via segment configuration for high-throughput scenarios + * Additional permissions required when returning data or metadata + * + * @param options - Vector listing options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.maxResults - Maximum results per page (default: 500, max: 1000) + * @param options.nextToken - Pagination token from previous response + * @param options.returnData - Whether to include vector embeddings (requires permission) + * @param options.returnMetadata - Whether to include metadata (requires permission) + * @param options.segmentCount - Total parallel segments (1-16) for distributed scanning + * @param options.segmentIndex - Zero-based segment index (0 to segmentCount-1) + * @returns Promise with array of vectors, pagination token, or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Simple pagination + * let nextToken: string | undefined + * do { + * const { data, error } = await client.listVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * maxResults: 500, + * nextToken, + * returnMetadata: true + * }) + * if (error) break + * console.log('Batch:', data.vectors.length) + * nextToken = data.nextToken + * } while (nextToken) + * + * // Parallel scanning (4 concurrent workers) + * const workers = [0, 1, 2, 3].map(async (segmentIndex) => { + * const { data } = await client.listVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * segmentCount: 4, + * segmentIndex, + * returnMetadata: true + * }) + * return data?.vectors || [] + * }) + * const results = await Promise.all(workers) + * ``` + */ + listVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Validate segment configuration + if (options.segmentCount !== undefined) { + if (options.segmentCount < 1 || options.segmentCount > 16) { + throw new Error('segmentCount must be between 1 and 16'); + } + if (options.segmentIndex !== undefined) { + if (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) { + throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`); + } + } + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectors`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - } - - 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 + /** + * Queries for similar vectors using approximate nearest neighbor (ANN) search + * Returns top-K most similar vectors based on the configured distance metric + * Supports optional metadata filtering (requires GetVectors permission) + * + * @param options - Query options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.queryVector - Query embedding to find similar vectors + * @param options.topK - Number of nearest neighbors to return (default: 10) + * @param options.filter - Optional JSON filter for metadata (requires GetVectors permission) + * @param options.returnDistance - Whether to include similarity distances + * @param options.returnMetadata - Whether to include metadata (requires GetVectors permission) + * @returns Promise with array of similar vectors ordered by distance + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Semantic search with filtering + * const { data, error } = await client.queryVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * queryVector: { float32: [0.1, 0.2, 0.3, ...] }, // 1536 dimensions + * topK: 5, + * filter: { + * category: 'technical', + * published: true + * }, + * returnDistance: true, + * returnMetadata: true + * }) + * if (data) { + * data.matches.forEach(match => { + * console.log(`${match.key}: distance=${match.distance}`) + * console.log('Metadata:', match.metadata) + * }) + * } + * ``` + */ + queryVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/QueryVectors`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - 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 + /** + * Deletes vectors by their keys in batch + * Accepts 1-500 keys per request + * + * @param options - Vector deletion options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Name of the index + * @param options.keys - Array of vector keys to delete (1-500 items) + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket or index doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { error } = await client.deleteVectors({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * keys: ['doc-1', 'doc-2', 'doc-3'] + * }) + * if (!error) { + * console.log('Vectors deleted successfully') + * } + * ``` + */ + deleteVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Validate batch size + if (options.keys.length < 1 || options.keys.length > 500) { + throw new Error('Keys batch size must be between 1 and 500 items'); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectors`, options, { + headers: this.headers, + }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - } catch (err) { - // Process in a fallback if error - } - - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) } - -module.exports = { getResolveErrorBodyCallback } - +exports["default"] = VectorDataApi; +//# sourceMappingURL=VectorDataApi.js.map /***/ }), -/***/ 37931: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9623: +/***/ ((__unused_webpack_module, 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) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(6876); +const errors_1 = __nccwpck_require__(3071); +const fetch_1 = __nccwpck_require__(2593); +const helpers_1 = __nccwpck_require__(1176); +/** + * API class for managing Vector Indexes within Vector Buckets + * Provides methods for creating, reading, listing, and deleting vector indexes + */ +class VectorIndexApi { + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); } - 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 + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + * @example + * ```typescript + * const client = new VectorIndexApi(url, headers) + * client.throwOnError() + * const { data } = await client.createIndex(options) // throws on error + * ``` + */ + throwOnError() { + this.shouldThrowOnError = 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] + /** + * Creates a new vector index within a bucket + * Defines the schema for vectors including dimensionality, distance metric, and metadata config + * + * @param options - Index configuration + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.indexName - Unique name for the index within the bucket + * @param options.dataType - Data type for vector components (currently only 'float32') + * @param options.dimension - Dimensionality of vectors (e.g., 384, 768, 1536) + * @param options.distanceMetric - Similarity metric ('cosine', 'euclidean', 'dotproduct') + * @param options.metadataConfiguration - Optional config for non-filterable metadata keys + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorConflictException` if index already exists (HTTP 409) + * - `S3VectorMaxIndexesExceeded` if quota exceeded (HTTP 400) + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.createIndex({ + * vectorBucketName: 'embeddings-prod', + * indexName: 'documents-openai-small', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine', + * metadataConfiguration: { + * nonFilterableMetadataKeys: ['raw_text', 'internal_id'] + * } + * }) + * ``` + */ + createIndex(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateIndex`, options, { + headers: this.headers, + }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - 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) + /** + * Retrieves metadata for a specific vector index + * Returns index configuration including dimension, distance metric, and metadata settings + * + * @param vectorBucketName - Name of the parent vector bucket + * @param indexName - Name of the index to retrieve + * @returns Promise with index metadata or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * const { data, error } = await client.getIndex('embeddings-prod', 'documents-openai-small') + * if (data) { + * console.log('Index dimension:', data.index.dimension) + * console.log('Distance metric:', data.index.distanceMetric) + * } + * ``` + */ + getIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - 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() + /** + * Lists vector indexes within a bucket with optional filtering and pagination + * Supports prefix-based filtering and paginated results + * + * @param options - Listing options + * @param options.vectorBucketName - Name of the parent vector bucket + * @param options.prefix - Filter indexes by name prefix + * @param options.maxResults - Maximum results per page (default: 100) + * @param options.nextToken - Pagination token from previous response + * @returns Promise with list of indexes and pagination token + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // List all indexes in a bucket + * const { data, error } = await client.listIndexes({ + * vectorBucketName: 'embeddings-prod', + * prefix: 'documents-' + * }) + * if (data) { + * console.log('Found indexes:', data.indexes.map(i => i.indexName)) + * // Fetch next page if available + * if (data.nextToken) { + * const next = await client.listIndexes({ + * vectorBucketName: 'embeddings-prod', + * nextToken: data.nextToken + * }) + * } + * } + * ``` + */ + listIndexes(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListIndexes`, options, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - const dispatcher = this[kClients].find(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) - - if (!dispatcher) { - return + /** + * Deletes a vector index and all its data + * This operation removes the index schema and all vectors stored in the index + * + * @param vectorBucketName - Name of the parent vector bucket + * @param indexName - Name of the index to delete + * @returns Promise with empty response on success or error + * + * @throws {StorageVectorsApiError} With code: + * - `S3VectorNotFoundException` if index or bucket doesn't exist (HTTP 404) + * - `InternalError` for server errors (HTTP 500) + * + * @example + * ```typescript + * // Delete an index and all its vectors + * const { error } = await client.deleteIndex('embeddings-prod', 'old-index') + * if (!error) { + * console.log('Index deleted successfully') + * } + * ``` + */ + deleteIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } +} +exports["default"] = VectorIndexApi; +//# sourceMappingURL=VectorIndexApi.js.map - const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) +/***/ }), - if (allClientsBusy) { - return - } +/***/ 6876: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let counter = 0 +"use strict"; - let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_HEADERS = void 0; +const version_1 = __nccwpck_require__(4499); +exports.DEFAULT_HEADERS = { + 'X-Client-Info': `storage-js/${version_1.version}`, + 'Content-Type': 'application/json', +}; +//# sourceMappingURL=constants.js.map - 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] - } +/***/ 3071: +/***/ ((__unused_webpack_module, exports) => { - // 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] +"use strict"; - if (this[kCurrentWeight] <= 0) { - this[kCurrentWeight] = this[kMaxWeightPerServer] - } - } - if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { - return pool - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = void 0; +exports.isStorageVectorsError = isStorageVectorsError; +/** + * Base error class for all Storage Vectors errors + */ +class StorageVectorsError extends Error { + constructor(message) { + super(message); + this.__isStorageVectorsError = true; + this.name = 'StorageVectorsError'; } - - this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] - this[kIndex] = maxWeightIndex - return this[kClients][maxWeightIndex] - } } - -module.exports = BalancedPool - +exports.StorageVectorsError = StorageVectorsError; +/** + * Type guard to check if an error is a StorageVectorsError + * @param error - The error to check + * @returns True if the error is a StorageVectorsError + */ +function isStorageVectorsError(error) { + return typeof error === 'object' && error !== null && '__isStorageVectorsError' in error; +} +/** + * API error returned from S3 Vectors service + * Includes HTTP status code and service-specific error code + */ +class StorageVectorsApiError extends StorageVectorsError { + constructor(message, status, statusCode) { + super(message); + this.name = 'StorageVectorsApiError'; + this.status = status; + this.statusCode = statusCode; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode, + }; + } +} +exports.StorageVectorsApiError = StorageVectorsApiError; +/** + * Unknown error that doesn't match expected error patterns + * Wraps the original error for debugging + */ +class StorageVectorsUnknownError extends StorageVectorsError { + constructor(message, originalError) { + super(message); + this.name = 'StorageVectorsUnknownError'; + this.originalError = originalError; + } +} +exports.StorageVectorsUnknownError = StorageVectorsUnknownError; +/** + * Error codes specific to S3 Vectors API + * Maps AWS service errors to application-friendly error codes + */ +var StorageVectorsErrorCode; +(function (StorageVectorsErrorCode) { + /** Internal server fault (HTTP 500) */ + StorageVectorsErrorCode["InternalError"] = "InternalError"; + /** Resource already exists / conflict (HTTP 409) */ + StorageVectorsErrorCode["S3VectorConflictException"] = "S3VectorConflictException"; + /** Resource not found (HTTP 404) */ + StorageVectorsErrorCode["S3VectorNotFoundException"] = "S3VectorNotFoundException"; + /** Delete bucket while not empty (HTTP 400) */ + StorageVectorsErrorCode["S3VectorBucketNotEmpty"] = "S3VectorBucketNotEmpty"; + /** Exceeds bucket quota/limit (HTTP 400) */ + StorageVectorsErrorCode["S3VectorMaxBucketsExceeded"] = "S3VectorMaxBucketsExceeded"; + /** Exceeds index quota/limit (HTTP 400) */ + StorageVectorsErrorCode["S3VectorMaxIndexesExceeded"] = "S3VectorMaxIndexesExceeded"; +})(StorageVectorsErrorCode || (exports.StorageVectorsErrorCode = StorageVectorsErrorCode = {})); +//# sourceMappingURL=errors.js.map /***/ }), -/***/ 66101: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 2593: +/***/ ((__unused_webpack_module, 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) - +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.get = get; +exports.post = post; +exports.put = put; +exports.remove = remove; +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(3071); +const helpers_1 = __nccwpck_require__(1176); /** - * @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 + * Extracts error message from various error response formats + * @param err - Error object from API + * @returns Human-readable error message */ - +const _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); /** - * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list - * @typedef {[any, any][]} requestResponseList + * Handles fetch errors and converts them to StorageVectors error types + * @param error - The error caught from fetch + * @param reject - Promise rejection function + * @param options - Fetch options that may affect error handling */ - -class Cache { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list - * @type {requestResponseList} - */ - #relevantRequestResponseList - - constructor () { - if (arguments[0] !== kConstruct) { - webidl.illegalConstructor() +const handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + // Check if error is a Response-like object (has status and ok properties) + // This is more reliable than instanceof which can fail across realms + const isResponseLike = error && + typeof error === 'object' && + 'status' in error && + 'ok' in error && + typeof error.status === 'number'; + if (isResponseLike && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + const status = error.status || 500; + const responseError = error; + // Try to parse JSON body if available + if (typeof responseError.json === 'function') { + responseError + .json() + .then((err) => { + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || (err === null || err === void 0 ? void 0 : err.code) || status + ''; + reject(new errors_1.StorageVectorsApiError(_getErrorMessage(err), status, statusCode)); + }) + .catch(() => { + // If JSON parsing fails, create an ApiError with the HTTP status code + const statusCode = status + ''; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); + }); + } + else { + // No json() method available, create error from status + const statusCode = status + ''; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); + } } - - 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 + else { + reject(new errors_1.StorageVectorsUnknownError(_getErrorMessage(error), error)); } - - 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] - } +}); +/** + * Builds request parameters for fetch calls + * @param method - HTTP method + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters like AbortSignal + * @param body - Request body (will be JSON stringified if plain object) + * @returns Complete fetch request parameters + */ +const _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === 'GET' || !body) { + return params; } - - // 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]) - } + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ 'Content-Type': 'application/json' }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + } + else { + params.body = body; } + return Object.assign(Object.assign({}, params), parameters); +}; +/** + * Internal request handler that wraps fetch with error handling + * @param fetcher - Fetch function to use + * @param method - HTTP method + * @param url - Request URL + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @param body - Request body + * @returns Promise with parsed response or error + */ +function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)) + .then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + // Handle empty responses (204, empty body) + const contentType = result.headers.get('content-type'); + if (!contentType || !contentType.includes('application/json')) { + return {}; + } + return result.json(); + }) + .then((data) => resolve(data)) + .catch((error) => handleError(error, reject, options)); + }); + }); +} +/** + * Performs a GET request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function get(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'GET', url, options, parameters); + }); +} +/** + * Performs a POST request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param body - Request body to be JSON stringified + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'POST', url, options, parameters, body); + }); +} +/** + * Performs a PUT request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param body - Request body to be JSON stringified + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'PUT', url, options, parameters, body); + }); +} +/** + * Performs a DELETE request + * @param fetcher - Fetch function to use + * @param url - Request URL + * @param body - Request body to be JSON stringified + * @param options - Custom fetch options + * @param parameters - Additional fetch parameters + * @returns Promise with parsed response + */ +function remove(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, 'DELETE', url, options, parameters, body); + }); +} +//# sourceMappingURL=fetch.js.map - // 5.4 - // We don't implement CORs so we don't need to loop over the responses, yay! +/***/ }), - // 5.5.1 - const responseList = [] +/***/ 1176: +/***/ ((__unused_webpack_module, exports) => { - // 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' +"use strict"; - responseList.push(responseObject) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = void 0; +/** + * Resolves the fetch implementation to use + * Uses custom fetch if provided, otherwise uses native fetch + * + * @param customFetch - Optional custom fetch implementation + * @returns Resolved fetch function + */ +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); } + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +/** + * Resolves the Response constructor to use + * Returns native Response constructor + * + * @returns Response constructor + */ +const resolveResponse = () => { + return Response; +}; +exports.resolveResponse = resolveResponse; +/** + * Determine if input is a plain object + * An object is plain if it's created by either {}, new Object(), or Object.create(null) + * + * @param value - Value to check + * @returns True if value is a plain object + * @source https://github.com/sindresorhus/is-plain-obj + */ +const isPlainObject = (value) => { + if (typeof value !== 'object' || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return ((prototype === null || + prototype === Object.prototype || + Object.getPrototypeOf(prototype) === null) && + !(Symbol.toStringTag in value) && + !(Symbol.iterator in value)); +}; +exports.isPlainObject = isPlainObject; +/** + * Normalizes a number array to float32 format + * Ensures all vector values are valid 32-bit floats + * + * @param values - Array of numbers to normalize + * @returns Normalized float32 array + */ +const normalizeToFloat32 = (values) => { + // Use Float32Array to ensure proper precision + return Array.from(new Float32Array(values)); +}; +exports.normalizeToFloat32 = normalizeToFloat32; +/** + * Validates vector dimensions match expected dimension + * Throws error if dimensions don't match + * + * @param vector - Vector data to validate + * @param expectedDimension - Expected vector dimension + * @throws Error if dimensions don't match + */ +const validateVectorDimension = (vector, expectedDimension) => { + if (expectedDimension !== undefined && vector.float32.length !== expectedDimension) { + throw new Error(`Vector dimension mismatch: expected ${expectedDimension}, got ${vector.float32.length}`); + } +}; +exports.validateVectorDimension = validateVectorDimension; +//# sourceMappingURL=helpers.js.map - // 6. - return Object.freeze(responseList) - } - - async add (request) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) +/***/ }), - request = webidl.converters.RequestInfo(request) +/***/ 9380: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 1. - const requests = [request] +"use strict"; - // 2. - const responseArrayPromise = this.addAll(requests) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = exports.isStorageVectorsError = exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = exports.VectorDataApi = exports.VectorIndexApi = exports.VectorBucketApi = exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; +const tslib_1 = __nccwpck_require__(4351); +// Main client +var StorageVectorsClient_1 = __nccwpck_require__(9403); +Object.defineProperty(exports, "StorageVectorsClient", ({ enumerable: true, get: function () { return StorageVectorsClient_1.StorageVectorsClient; } })); +Object.defineProperty(exports, "VectorBucketScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorBucketScope; } })); +Object.defineProperty(exports, "VectorIndexScope", ({ enumerable: true, get: function () { return StorageVectorsClient_1.VectorIndexScope; } })); +// API classes (for advanced usage) +var VectorBucketApi_1 = __nccwpck_require__(4268); +Object.defineProperty(exports, "VectorBucketApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorBucketApi_1).default; } })); +var VectorIndexApi_1 = __nccwpck_require__(9623); +Object.defineProperty(exports, "VectorIndexApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorIndexApi_1).default; } })); +var VectorDataApi_1 = __nccwpck_require__(3073); +Object.defineProperty(exports, "VectorDataApi", ({ enumerable: true, get: function () { return tslib_1.__importDefault(VectorDataApi_1).default; } })); +// Errors +var errors_1 = __nccwpck_require__(3071); +Object.defineProperty(exports, "StorageVectorsError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsError; } })); +Object.defineProperty(exports, "StorageVectorsApiError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsApiError; } })); +Object.defineProperty(exports, "StorageVectorsUnknownError", ({ enumerable: true, get: function () { return errors_1.StorageVectorsUnknownError; } })); +Object.defineProperty(exports, "StorageVectorsErrorCode", ({ enumerable: true, get: function () { return errors_1.StorageVectorsErrorCode; } })); +Object.defineProperty(exports, "isStorageVectorsError", ({ enumerable: true, get: function () { return errors_1.isStorageVectorsError; } })); +// Helper utilities +var helpers_1 = __nccwpck_require__(1176); +Object.defineProperty(exports, "resolveFetch", ({ enumerable: true, get: function () { return helpers_1.resolveFetch; } })); +Object.defineProperty(exports, "resolveResponse", ({ enumerable: true, get: function () { return helpers_1.resolveResponse; } })); +Object.defineProperty(exports, "isPlainObject", ({ enumerable: true, get: function () { return helpers_1.isPlainObject; } })); +Object.defineProperty(exports, "normalizeToFloat32", ({ enumerable: true, get: function () { return helpers_1.normalizeToFloat32; } })); +Object.defineProperty(exports, "validateVectorDimension", ({ enumerable: true, get: function () { return helpers_1.validateVectorDimension; } })); +//# sourceMappingURL=index.js.map - // 3. - return await responseArrayPromise - } +/***/ }), - async addAll (requests) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) +/***/ 4499: +/***/ ((__unused_webpack_module, exports) => { - requests = webidl.converters['sequence'](requests) +"use strict"; - // 1. - const responsePromises = [] +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map - // 2. - const requestList = [] +/***/ }), - // 3. - for (const request of requests) { - if (typeof request === 'string') { - continue - } +/***/ 8475: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 3.1 - const r = request[kState] +"use strict"; - // 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.' - }) - } +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(2758); +const StreamDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(7023)); +class BlobDownloadBuilder { + constructor(downloadFn, shouldThrowOnError) { + this.downloadFn = downloadFn; + this.shouldThrowOnError = shouldThrowOnError; + this[_a] = 'BlobDownloadBuilder'; + this.promise = null; } + asStream() { + return new StreamDownloadBuilder_1.default(this.downloadFn, this.shouldThrowOnError); + } + then(onfulfilled, onrejected) { + return this.getPromise().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.getPromise().catch(onrejected); + } + finally(onfinally) { + return this.getPromise().finally(onfinally); + } + getPromise() { + if (!this.promise) { + this.promise = this.execute(); + } + return this.promise; + } + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: yield result.blob(), + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } +} +_a = Symbol.toStringTag; +exports["default"] = BlobDownloadBuilder; +//# sourceMappingURL=BlobDownloadBuilder.js.map - // 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.' - }) - } +/***/ 7339: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 5.4 - r.initiator = 'fetch' - r.destination = 'subresource' +"use strict"; - // 5.5 - requestList.push(r) +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(9754); +const errors_1 = __nccwpck_require__(2758); +const fetch_1 = __nccwpck_require__(3146); +const helpers_1 = __nccwpck_require__(5430); +/** + * API class for managing Analytics Buckets using Iceberg tables + * Provides methods for creating, listing, and deleting analytics buckets + */ +class StorageAnalyticsApi { + /** + * Creates a new StorageAnalyticsApi instance + * @param url - The base URL for the storage API + * @param headers - HTTP headers to include in requests + * @param fetch - Optional custom fetch implementation + */ + constructor(url, headers = {}, fetch) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * @returns This instance for method chaining + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Creates a new analytics bucket using Iceberg tables + * Analytics buckets are optimized for analytical queries and data processing + * + * @param name A unique name for the bucket you are creating + * @returns Promise with newly created bucket name or error + * + * @example + * ```typescript + * const { data, error } = await storage.analytics.createBucket('analytics-data') + * if (error) { + * console.error('Failed to create analytics bucket:', error.message) + * } else { + * console.log('Created bucket:', data.name) + * } + * ``` + */ + createBucket(name) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { name }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of all Analytics Storage buckets within an existing project + * Only returns buckets of type 'ANALYTICS' + * + * @param options Query parameters for listing buckets + * @param options.limit Maximum number of buckets to return + * @param options.offset Number of buckets to skip + * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at') + * @param options.sortOrder Sort order ('asc' or 'desc') + * @param options.search Search term to filter bucket names + * @returns Promise with list of analytics buckets or error + * + * @example + * ```typescript + * const { data, error } = await storage.analytics.listBuckets({ + * limit: 10, + * offset: 0, + * sortColumn: 'created_at', + * sortOrder: 'desc', + * search: 'analytics' + * }) + * if (data) { + * console.log('Found analytics buckets:', data.length) + * data.forEach(bucket => console.log(`- ${bucket.name}`)) + * } + * ``` + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + // Build query string from options + const queryParams = new URLSearchParams(); + if ((options === null || options === void 0 ? void 0 : options.limit) !== undefined) + queryParams.set('limit', options.limit.toString()); + if ((options === null || options === void 0 ? void 0 : options.offset) !== undefined) + queryParams.set('offset', options.offset.toString()); + if (options === null || options === void 0 ? void 0 : options.sortColumn) + queryParams.set('sortColumn', options.sortColumn); + if (options === null || options === void 0 ? void 0 : options.sortOrder) + queryParams.set('sortOrder', options.sortOrder); + if (options === null || options === void 0 ? void 0 : options.search) + queryParams.set('search', options.search); + const queryString = queryParams.toString(); + const url = queryString ? `${this.url}/bucket?${queryString}` : `${this.url}/bucket`; + const data = yield (0, fetch_1.get)(this.fetch, url, { headers: this.headers }); + return { data: data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing analytics bucket + * A bucket can't be deleted with existing objects inside it + * You must first empty the bucket before deletion + * + * @param bucketId The unique identifier of the bucket you would like to delete + * @returns Promise with success message or error + * + * @example + * ```typescript + * const { data, error } = await analyticsApi.deleteBucket('old-analytics-bucket') + * if (error) { + * console.error('Failed to delete bucket:', error.message) + * } else { + * console.log('Bucket deleted successfully:', data.message) + * } + * ``` + */ + deleteBucket(bucketId) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${bucketId}`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } +} +exports["default"] = StorageAnalyticsApi; +//# sourceMappingURL=StorageAnalyticsApi.js.map - // 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')) +/***/ 3528: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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' - })) +"use strict"; - for (const controller of fetchControllers) { - controller.abort() +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const constants_1 = __nccwpck_require__(9754); +const errors_1 = __nccwpck_require__(2758); +const fetch_1 = __nccwpck_require__(3146); +const helpers_1 = __nccwpck_require__(5430); +class StorageBucketApi { + constructor(url, headers = {}, fetch, opts) { + this.shouldThrowOnError = false; + const baseUrl = new URL(url); + // if legacy uri is used, replace with new storage host (disables request buffering to allow > 50GB uploads) + // "project-ref.supabase.co" becomes "project-ref.storage.supabase.co" + if (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) { + const isSupabaseHost = /supabase\.(co|in|red)$/.test(baseUrl.hostname); + if (isSupabaseHost && !baseUrl.hostname.includes('storage.supabase.')) { + baseUrl.hostname = baseUrl.hostname.replace('supabase.', 'storage.supabase.'); + } + } + this.url = baseUrl.href.replace(/\/$/, ''); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch); + } + /** + * Enable throwing errors instead of returning them. + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Retrieves the details of all Storage buckets within an existing project. + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const queryString = this.listBucketOptionsToQueryString(options); + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket${queryString}`, { + headers: this.headers, + }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; } - - return - } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing Storage bucket. + * + * @param id The unique identifier of the bucket you would like to retrieve. + */ + getBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a new Storage bucket + * + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns newly created bucket id + * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details. + * - default bucket type is `STANDARD` + */ + createBucket(id_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (id, options = { + public: false, + }) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { + id, + name: id, + type: options.type, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Updates a Storage bucket + * + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + */ + updateBucket(id, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Removes all objects inside a single bucket. + * + * @param id The unique identifier of the bucket you would like to empty. + */ + emptyBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @param id The unique identifier of the bucket you would like to delete. + */ + deleteBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + listBucketOptionsToQueryString(options) { + const params = {}; + if (options) { + if ('limit' in options) { + params.limit = String(options.limit); + } + if ('offset' in options) { + params.offset = String(options.offset); + } + if (options.search) { + params.search = options.search; + } + if (options.sortColumn) { + params.sortColumn = options.sortColumn; + } + if (options.sortOrder) { + params.sortOrder = options.sortOrder; } - } - }, - 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 + return Object.keys(params).length > 0 ? '?' + new URLSearchParams(params).toString() : ''; } +} +exports["default"] = StorageBucketApi; +//# sourceMappingURL=StorageBucketApi.js.map - // 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) +/***/ 710: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 1. - let innerRequest = null +"use strict"; - // 2. - if (request instanceof Request) { - innerRequest = request[kState] - } else { // 3. - innerRequest = new Request(request)[kState] +Object.defineProperty(exports, "__esModule", ({ value: true })); +const tslib_1 = __nccwpck_require__(4351); +const errors_1 = __nccwpck_require__(2758); +const fetch_1 = __nccwpck_require__(3146); +const helpers_1 = __nccwpck_require__(5430); +const BlobDownloadBuilder_1 = tslib_1.__importDefault(__nccwpck_require__(8475)); +const DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: 'name', + order: 'asc', + }, +}; +const DEFAULT_FILE_OPTIONS = { + cacheControl: '3600', + contentType: 'text/plain;charset=UTF-8', + upsert: false, +}; +class StorageFileApi { + constructor(url, headers = {}, bucketId, fetch) { + this.shouldThrowOnError = false; + this.url = url; + this.headers = headers; + this.bucketId = bucketId; + this.fetch = (0, helpers_1.resolveFetch)(fetch); } - - // 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' - }) + /** + * Enable throwing errors instead of returning them. + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; } - - // 5. - const innerResponse = response[kState] - - // 6. - if (innerResponse.status === 206) { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got 206 status' - }) + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadOrUpdate(method, path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let body; + const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); + let headers = Object.assign(Object.assign({}, this.headers), (method === 'POST' && { 'x-upsert': String(options.upsert) })); + const metadata = options.metadata; + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + if (metadata) { + body.append('metadata', this.encodeMetadata(metadata)); + } + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + // Only append if not already present + if (!body.has('cacheControl')) { + body.append('cacheControl', options.cacheControl); + } + if (metadata && !body.has('metadata')) { + body.append('metadata', this.encodeMetadata(metadata)); + } + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + if (metadata) { + headers['x-metadata'] = this.toBase64(this.encodeMetadata(metadata)); + } + // Node.js streams require duplex option for fetch in Node 20+ + // Check for both web ReadableStream and Node.js streams + const isStream = (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) || + (body && typeof body === 'object' && 'pipe' in body && typeof body.pipe === 'function'); + if (isStream && !options.duplex) { + options.duplex = 'half'; + } + } + if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { + headers = Object.assign(Object.assign({}, headers), fileOptions.headers); + } + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const data = yield (method == 'PUT' ? fetch_1.put : fetch_1.post)(this.fetch, `${this.url}/object/${_path}`, body, Object.assign({ headers }, ((options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {}))); + return { + data: { path: cleanPath, id: data.Id, fullPath: data.Key }, + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - // 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' - }) - } - } + /** + * Uploads a file to an existing bucket. + * + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + upload(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('POST', path, fileBody, fileOptions); + }); } - - // 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' - }) + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadToSignedUrl(path, token, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const url = new URL(this.url + `/object/upload/sign/${_path}`); + url.searchParams.set('token', token); + try { + let body; + const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), { 'x-upsert': String(options.upsert) }); + if (typeof Blob !== 'undefined' && fileBody instanceof Blob) { + body = new FormData(); + body.append('cacheControl', options.cacheControl); + body.append('', fileBody); + } + else if (typeof FormData !== 'undefined' && fileBody instanceof FormData) { + body = fileBody; + body.append('cacheControl', options.cacheControl); + } + else { + body = fileBody; + headers['cache-control'] = `max-age=${options.cacheControl}`; + headers['content-type'] = options.contentType; + } + const data = yield (0, fetch_1.put)(this.fetch, url.toString(), body, { headers }); + return { + data: { path: cleanPath, fullPath: data.Key }, + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - // 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) + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for 2 hours. + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param options.upsert If set to true, allows the file to be overwritten if it already exists. + */ + createSignedUploadUrl(path, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + const headers = Object.assign({}, this.headers); + if (options === null || options === void 0 ? void 0 : options.upsert) { + headers['x-upsert'] = 'true'; + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); + const url = new URL(this.url + data.url); + const token = url.searchParams.get('token'); + if (!token) { + throw new errors_1.StorageError('No token returned by API'); + } + return { data: { signedUrl: url.toString(), path, token }, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - // 12. - /** @type {CacheBatchOperation[]} */ - const operations = [] - - // 13. - /** @type {CacheBatchOperation} */ - const operation = { - type: 'put', // 14. - request: innerRequest, // 15. - response: clonedResponse // 16. + /** + * Replaces an existing file at the specified path with a new one. + * + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + */ + update(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate('PUT', path, fileBody, fileOptions); + }); } - - // 17. - operations.push(operation) - - // 19. - const bytes = await bodyReadPromise.promise - - if (clonedResponse.body != null) { - clonedResponse.body.source = bytes + /** + * Moves an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + * @param options The destination options. + */ + move(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, + }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - // 19.1 - const cacheJobPromise = createDeferredPromise() - - // 19.2.1 - let errorData = null - - // 19.2.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e + /** + * Copies an existing file to a new path in the same bucket. + * + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + * @param options The destination options. + */ + copy(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket, + }, { headers: this.headers }); + return { data: { path: data.Key }, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - // 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} + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. */ - 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] + createSignedUrl(path, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, ((options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {})), { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); + data = { signedUrl }; + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - /** @type {CacheBatchOperation[]} */ - const operations = [] - - /** @type {CacheBatchOperation} */ - const operation = { - type: 'delete', - request: r, - options + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + */ + createSignedUrls(paths, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `&download=${options.download === true ? '' : options.download}` + : ''; + return { + data: data.map((datum) => (Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL + ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) + : null }))), + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - operations.push(operation) - - const cacheJobPromise = createDeferredPromise() - - let errorData = null - let requestResponses - - try { - requestResponses = this.#batchCacheOperations(operations) - } catch (e) { - errorData = e + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + */ + download(path, options) { + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image/authenticated' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + const queryString = transformationQuery ? `?${transformationQuery}` : ''; + const _path = this._getFinalPath(path); + const downloadFn = () => (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true, + }); + return new BlobDownloadBuilder_1.default(downloadFn, this.shouldThrowOnError); } - - 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] - } + /** + * Retrieves the details of an existing file. + * @param path + */ + info(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, { + headers: this.headers, + }); + return { data: (0, helpers_1.recursiveToCamel)(data), error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - // 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]) - } + /** + * Checks the existence of a file. + * @param path + */ + exists(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, { + headers: this.headers, + }); + return { data: true, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) { + const originalError = error.originalError; + if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { + return { data: false, error }; + } + } + throw error; + } + }); } - - // 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' - }) + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + */ + getPublicUrl(path, options) { + const _path = this._getFinalPath(path); + const _queryString = []; + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) + ? `download=${options.download === true ? '' : options.download}` + : ''; + if (downloadQueryParam !== '') { + _queryString.push(downloadQueryParam); } - - // 4.2.3 - if (this.#queryCache(operation.request, operation.options, addedItems).length) { - throw new DOMException('???', 'InvalidStateError') + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== 'undefined'; + const renderPath = wantsTransformation ? 'render/image' : 'object'; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + if (transformationQuery !== '') { + _queryString.push(transformationQuery); } - - // 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]) + let queryString = _queryString.join('&'); + if (queryString !== '') { + queryString = `?${queryString}`; } - - // 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 + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) }, + }; } - } - - /** - * @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) - } + /** + * Deletes files within the same bucket + * + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + */ + remove(paths) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - 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 + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } // } - - const queryURL = new URL(requestQuery.url) - - const cachedURL = new URL(request.url) - - if (options?.ignoreSearch) { - cachedURL.search = '' - - queryURL.search = '' + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Lists all the files and folders within a path of the bucket. + * @param path The folder path. + * @param options Search options including limit (defaults to 100), offset, sortBy, and search + */ + list(path, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || '' }); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @experimental this method signature might change in the future + * @param options search options + * @param parameters + */ + listV2(options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign({}, options); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list-v2/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + encodeMetadata(metadata) { + return JSON.stringify(metadata); } - - if (!urlEquals(queryURL, cachedURL, true)) { - return false + toBase64(data) { + if (typeof Buffer !== 'undefined') { + return Buffer.from(data).toString('base64'); + } + return btoa(data); } - - if ( - response == null || - options?.ignoreVary || - !response.headersList.contains('vary') - ) { - return true + _getFinalPath(path) { + return `${this.bucketId}/${path.replace(/^\/+/, '')}`; } - - 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 - } + _removeEmptyFolders(path) { + return path.replace(/^\/|\/$/g, '').replace(/\/+/g, '/'); + } + transformOptsToQueryString(transform) { + const params = []; + if (transform.width) { + params.push(`width=${transform.width}`); + } + if (transform.height) { + params.push(`height=${transform.height}`); + } + if (transform.resize) { + params.push(`resize=${transform.resize}`); + } + if (transform.format) { + params.push(`format=${transform.format}`); + } + if (transform.quality) { + params.push(`quality=${transform.quality}`); + } + return params.join('&'); } - - 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 } - +exports["default"] = StorageFileApi; +//# sourceMappingURL=StorageFileApi.js.map /***/ }), -/***/ 37907: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7023: +/***/ ((__unused_webpack_module, 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) + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: result.body, + error: null, + }; + } + catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); } - - // 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) } - +exports["default"] = StreamDownloadBuilder; +//# sourceMappingURL=StreamDownloadBuilder.js.map /***/ }), -/***/ 82396: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1807: +/***/ ((__unused_webpack_module, 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 -} - +Object.defineProperty(exports, "__esModule", ({ value: true })); +const functions_js_1 = __nccwpck_require__(8519); +const postgrest_js_1 = __nccwpck_require__(1178); +const realtime_js_1 = __nccwpck_require__(442); +const storage_js_1 = __nccwpck_require__(5852); +const constants_1 = __nccwpck_require__(4868); +const fetch_1 = __nccwpck_require__(785); +const helpers_1 = __nccwpck_require__(3575); +const SupabaseAuthClient_1 = __nccwpck_require__(7620); /** - * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 - * @param {string} header + * Supabase Client. + * + * An isomorphic Javascript client for interacting with Postgres. */ -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 +class SupabaseClient { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + const baseUrl = (0, helpers_1.validateSupabaseUrl)(supabaseUrl); + if (!supabaseKey) + throw new Error('supabaseKey is required.'); + this.realtimeUrl = new URL('realtime/v1', baseUrl); + this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace('http', 'ws'); + this.authUrl = new URL('auth/v1', baseUrl); + this.storageUrl = new URL('storage/v1', baseUrl); + this.functionsUrl = new URL('functions/v1', baseUrl); + // default storage key uses the supabase project ref as a namespace + const defaultStorageKey = `sb-${baseUrl.hostname.split('.')[0]}-auth-token`; + const DEFAULTS = { + db: constants_1.DEFAULT_DB_OPTIONS, + realtime: constants_1.DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: constants_1.DEFAULT_GLOBAL_OPTIONS, + }; + const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ''; + this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); + } + else { + this.accessToken = settings.accessToken; + this.auth = new Proxy({}, { + get: (_, prop) => { + throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); + }, + }); + } + this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); + this.rest = new postgrest_js_1.PostgrestClient(new URL('rest/v1', baseUrl).href, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch, + }); + this.storage = new storage_js_1.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); + if (!settings.accessToken) { + this._listenForAuthEvents(); + } + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new functions_js_1.FunctionsClient(this.functionsUrl.href, { + headers: this.headers, + customFetch: this.fetch, + }); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema) { + return this.rest.schema(schema); + } + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options = { + head: false, + get: false, + count: undefined, + }) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + async _getAccessToken() { + var _a, _b; + if (this.accessToken) { + return await this.accessToken(); + } + const { data } = await this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError, }, headers, fetch) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}`, + }; + return new SupabaseAuthClient_1.SupabaseAuthClient({ + url: this.authUrl.href, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey: storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + flowType, + lock, + debug, + throwOnError, + fetch, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === 'authorization'), + }); + } + _initRealtimeClient(options) { + return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + const data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, 'CLIENT', session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === 'TOKEN_REFRESHED' || event === 'SIGNED_IN') && + this.changedAccessToken !== token) { + this.changedAccessToken = token; + this.realtime.setAuth(token); + } + else if (event === 'SIGNED_OUT') { + this.realtime.setAuth(); + if (source == 'STORAGE') + this.auth.signOut(); + this.changedAccessToken = undefined; + } } - - values.push(value) - } - - return values -} - -module.exports = { - urlEquals, - fieldValues } - +exports["default"] = SupabaseClient; +//# sourceMappingURL=SupabaseClient.js.map /***/ }), -/***/ 33598: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 1206: +/***/ (function(__unused_webpack_module, 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 } -} +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 __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); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0; +const SupabaseClient_1 = __importDefault(__nccwpck_require__(1807)); +__exportStar(__nccwpck_require__(6748), exports); +var postgrest_js_1 = __nccwpck_require__(1178); +Object.defineProperty(exports, "PostgrestError", ({ enumerable: true, get: function () { return postgrest_js_1.PostgrestError; } })); +var functions_js_1 = __nccwpck_require__(8519); +Object.defineProperty(exports, "FunctionsHttpError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsHttpError; } })); +Object.defineProperty(exports, "FunctionsFetchError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsFetchError; } })); +Object.defineProperty(exports, "FunctionsRelayError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsRelayError; } })); +Object.defineProperty(exports, "FunctionsError", ({ enumerable: true, get: function () { return functions_js_1.FunctionsError; } })); +Object.defineProperty(exports, "FunctionRegion", ({ enumerable: true, get: function () { return functions_js_1.FunctionRegion; } })); +__exportStar(__nccwpck_require__(442), exports); +var SupabaseClient_2 = __nccwpck_require__(1807); +Object.defineProperty(exports, "SupabaseClient", ({ enumerable: true, get: function () { return __importDefault(SupabaseClient_2).default; } })); /** - * @type {import('../types/client').default} + * Creates a new Supabase Client. */ -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') +const createClient = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); +}; +exports.createClient = createClient; +// Check for Node.js <= 18 deprecation +function shouldShowDeprecationWarning() { + // Skip in browser environments + if (typeof window !== 'undefined') { + return false; } - - if (socketTimeout !== undefined) { - throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + // Skip if process is not available (e.g., Edge Runtime) + if (typeof process === 'undefined') { + return false; } - - if (requestTimeout !== undefined) { - throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + // Use dynamic property access to avoid Next.js Edge Runtime static analysis warnings + const processVersion = process['version']; + if (processVersion === undefined || processVersion === null) { + return false; } - - if (idleTimeout !== undefined) { - throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + const versionMatch = processVersion.match(/^v(\d+)\./); + if (!versionMatch) { + return false; } + const majorVersion = parseInt(versionMatch[1], 10); + return majorVersion <= 18; +} +if (shouldShowDeprecationWarning()) { + console.warn(`āš ļø Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. ` + + `Please upgrade to Node.js 20 or later. ` + + `For more information, visit: https://github.com/orgs/supabase/discussions/37217`); +} +//# sourceMappingURL=index.js.map - if (maxKeepAliveTimeout !== undefined) { - throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') - } +/***/ }), - if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { - throw new InvalidArgumentError('invalid maxHeaderSize') - } +/***/ 7620: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (socketPath != null && typeof socketPath !== 'string') { - throw new InvalidArgumentError('invalid socketPath') - } +"use strict"; - if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { - throw new InvalidArgumentError('invalid connectTimeout') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SupabaseAuthClient = void 0; +const auth_js_1 = __nccwpck_require__(6748); +class SupabaseAuthClient extends auth_js_1.AuthClient { + constructor(options) { + super(options); } +} +exports.SupabaseAuthClient = SupabaseAuthClient; +//# sourceMappingURL=SupabaseAuthClient.js.map - 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') - } +/***/ 4868: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { - throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') - } +"use strict"; - if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0; +const version_1 = __nccwpck_require__(6136); +let JS_ENV = ''; +// @ts-ignore +if (typeof Deno !== 'undefined') { + JS_ENV = 'deno'; +} +else if (typeof document !== 'undefined') { + JS_ENV = 'web'; +} +else if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { + JS_ENV = 'react-native'; +} +else { + JS_ENV = 'node'; +} +exports.DEFAULT_HEADERS = { 'X-Client-Info': `supabase-js-${JS_ENV}/${version_1.version}` }; +exports.DEFAULT_GLOBAL_OPTIONS = { + headers: exports.DEFAULT_HEADERS, +}; +exports.DEFAULT_DB_OPTIONS = { + schema: 'public', +}; +exports.DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: 'implicit', +}; +exports.DEFAULT_REALTIME_OPTIONS = {}; +//# sourceMappingURL=constants.js.map - 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') - } +/***/ 785: +/***/ ((__unused_webpack_module, exports) => { - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } +"use strict"; - if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { - throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; +const resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); } + return (...args) => fetch(...args); +}; +exports.resolveFetch = resolveFetch; +const resolveHeadersConstructor = () => { + return Headers; +}; +exports.resolveHeadersConstructor = resolveHeadersConstructor; +const fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch = (0, exports.resolveFetch)(customFetch); + const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); + return async (input, init) => { + var _a; + const accessToken = (_a = (await getAccessToken())) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has('apikey')) { + headers.set('apikey', supabaseKey); + } + if (!headers.has('Authorization')) { + headers.set('Authorization', `Bearer ${accessToken}`); + } + return fetch(input, Object.assign(Object.assign({}, init), { headers })); + }; +}; +exports.fetchWithAuth = fetchWithAuth; +//# sourceMappingURL=fetch.js.map - 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') - } +/***/ 3575: +/***/ ((__unused_webpack_module, exports) => { - if ( - autoSelectFamilyAttemptTimeout != null && - (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) - ) { - throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') - } +"use strict"; - // h2 - if (allowH2 != null && typeof allowH2 !== 'boolean') { - throw new InvalidArgumentError('allowH2 must be a valid boolean value') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isBrowser = void 0; +exports.uuid = uuid; +exports.ensureTrailingSlash = ensureTrailingSlash; +exports.applySettingDefaults = applySettingDefaults; +exports.validateSupabaseUrl = validateSupabaseUrl; +function uuid() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +function ensureTrailingSlash(url) { + return url.endsWith('/') ? url : url + '/'; +} +const isBrowser = () => typeof window !== 'undefined'; +exports.isBrowser = isBrowser; +function applySettingDefaults(options, defaults) { + var _a, _b; + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions, } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS, } = defaults; + const result = { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + storage: {}, + global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, ((_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {})), ((_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {})) }), + accessToken: async () => '', + }; + if (options.accessToken) { + result.accessToken = options.accessToken; } - - if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { - throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') + else { + // hack around Required<> + delete result.accessToken; } - - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) + return result; +} +/** + * Validates a Supabase client URL + * + * @param {string} supabaseUrl - The Supabase client URL string. + * @returns {URL} - The validated base URL. + * @throws {Error} + */ +function validateSupabaseUrl(supabaseUrl) { + const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); + if (!trimmedUrl) { + throw new Error('supabaseUrl is required.'); } + if (!trimmedUrl.match(/^https?:\/\//i)) { + throw new Error('Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.'); + } + try { + return new URL(ensureTrailingSlash(trimmedUrl)); + } + catch (_a) { + throw Error('Invalid supabaseUrl: Provided URL is malformed.'); + } +} +//# sourceMappingURL=helpers.js.map - 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 - ) - } +/***/ 6136: +/***/ ((__unused_webpack_module, exports) => { - /* istanbul ignore: only used for test */ - [kConnect] (cb) { - connect(this) - this.once('connect', cb) - } +"use strict"; - [kDispatch] (opts, handler) { - const origin = opts.origin || this[kUrl].origin +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.version = void 0; +// Generated automatically during releases by scripts/update-version-files.ts +// This file provides runtime access to the package version for: +// - HTTP request headers (e.g., X-Client-Info header for API requests) +// - Debugging and support (identifying which version is running) +// - Telemetry and logging (version reporting in errors/analytics) +// - Ensuring build artifacts match the published package version +exports.version = '2.80.0'; +//# sourceMappingURL=version.js.map - 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) - } +/***/ 2225: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { - this[kNeedDrain] = 2 - } +"use strict"; - 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 - } - }) - } +const stringWidth = __nccwpck_require__(5537) - 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) - } +function ansiAlign (text, opts) { + if (!text) return text - const callback = () => { - if (this[kClosedResolve]) { - // TODO (fix): Should we error here with ClientDestroyedError? - this[kClosedResolve]() - this[kClosedResolve] = null - } - resolve() - } + opts = opts || {} + const align = opts.align || 'center' - if (this[kHTTP2Session] != null) { - util.destroy(this[kHTTP2Session], err) - this[kHTTP2Session] = null - this[kHTTP2SessionState] = null - } + // short-circuit `align: 'left'` as no-op + if (align === 'left') return text - if (!this[kSocket]) { - queueMicrotask(callback) - } else { - util.destroy(this[kSocket].on('close', callback), err) - } + const split = opts.split || '\n' + const pad = opts.pad || ' ' + const widthDiffFn = align !== 'right' ? halfDiff : fullDiff - resume(this) - }) + let returnString = false + if (!Array.isArray(text)) { + returnString = true + text = String(text).split(split) } -} - -function onHttp2SessionError (err) { - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - this[kSocket][kError] = err + let width + let maxWidth = 0 + text = text.map(function (str) { + str = String(str) + width = stringWidth(str) + maxWidth = Math.max(width, maxWidth) + return { + str, + width + } + }).map(function (obj) { + return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str + }) - onError(this[kClient], err) + return returnString ? text.join(split) : text } -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) - } +ansiAlign.left = function left (text) { + return ansiAlign(text, { align: 'left' }) } -function onHttp2SessionEnd () { - util.destroy(this, new SocketError('other side closed')) - util.destroy(this[kSocket], new SocketError('other side closed')) +ansiAlign.center = function center (text) { + return ansiAlign(text, { align: 'center' }) } -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) +ansiAlign.right = function right (text) { + return ansiAlign(text, { align: 'right' }) } -const constants = __nccwpck_require__(30953) -const createRedirectInterceptor = __nccwpck_require__(38861) -const EMPTY_BUF = Buffer.alloc(0) +module.exports = ansiAlign -async function lazyllhttp () { - const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(61145) : undefined +function halfDiff (maxWidth, curWidth) { + return Math.floor((maxWidth - curWidth) / 2) +} - let mod - try { - mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(95627), 'base64')) - } catch (e) { - /* istanbul ignore next */ +function fullDiff (maxWidth, curWidth) { + return maxWidth - curWidth +} - // 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 - } +/***/ 140: +/***/ ((module) => { - /* eslint-enable camelcase */ - } - }) -} +"use strict"; -let llhttpInstance = null -let llhttpPromise = lazyllhttp() -llhttpPromise.catch() -let currentParser = null -let currentBufferRef = null -let currentBufferSize = 0 -let currentBufferPtr = null +module.exports = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); -const TIMEOUT_HEADERS = 1 -const TIMEOUT_BODY = 2 -const TIMEOUT_IDLE = 3 + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; -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 +/***/ 3652: +/***/ ((module) => { - this.keepAlive = '' - this.contentLength = '' - this.connection = '' - this.maxResponseSize = client[kMaxResponseSize] - } +"use strict"; - 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 - } +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; - 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() - } - } +/***/ 5537: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.paused = false - this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. - this.readMore() - } +"use strict"; - readMore () { - while (!this.paused && this.ptr) { - const chunk = this.socket.read() - if (chunk === null) { - break - } - this.execute(chunk) - } - } +const stripAnsi = __nccwpck_require__(1411); +const isFullwidthCodePoint = __nccwpck_require__(4882); +const emojiRegex = __nccwpck_require__(3652); - execute (data) { - assert(this.ptr != null) - assert(currentParser == null) - assert(!this.paused) +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } - const { socket, llhttp } = this + string = stripAnsi(string); - if (data.length > currentBufferSize) { - if (currentBufferPtr) { - llhttp.free(currentBufferPtr) - } - currentBufferSize = Math.ceil(data.length / 4096) * 4096 - currentBufferPtr = llhttp.malloc(currentBufferSize) - } + if (string.length === 0) { + return 0; + } - new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + string = string.replace(emojiRegex(), ' '); - // 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 + let width = 0; - 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 - } + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); - const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } - 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) - } - } + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } - destroy () { - assert(this.ptr != null) - assert(currentParser == null) + // Surrogates + if (code > 0xFFFF) { + i++; + } - this.llhttp.llhttp_free(this.ptr) - this.ptr = null + width += isFullwidthCodePoint(code) ? 2 : 1; + } - timers.clearTimeout(this.timeout) - this.timeout = null - this.timeoutValue = null - this.timeoutType = null + return width; +}; - this.paused = false - } +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports["default"] = stringWidth; - 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 - } +/***/ 1411: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const request = client[kQueue][client[kRunningIdx]] - if (!request) { - return -1 - } - } +"use strict"; - onHeaderField (buf) { - const len = this.headers.length +const ansiRegex = __nccwpck_require__(140); - if ((len & 1) === 0) { - this.headers.push(buf) - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) - } +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; - 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]) - } +/***/ 3682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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() - } +var register = __nccwpck_require__(4670); +var addHook = __nccwpck_require__(5549); +var removeHook = __nccwpck_require__(6819); - this.trackHeader(buf.length) - } +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); - trackHeader (len) { - this.headersSize += len - if (this.headersSize >= this.headersMaxSize) { - util.destroy(this.socket, new HeadersOverflowError()) - } - } +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); + }); +} - onUpgrade (head) { - const { upgrade, client, socket, headers, statusCode } = this +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} - assert(upgrade) +function HookCollection() { + var state = { + registry: {}, + }; - const request = client[kQueue][client[kRunningIdx]] - assert(request) + var hook = register.bind(null, state); + bindApi(hook, state); - assert(!socket.destroyed) - assert(socket === client[kSocket]) - assert(!this.paused) - assert(request.upgrade || request.method === 'CONNECT') + return hook; +} - this.statusCode = null - this.statusText = '' - this.shouldKeepAlive = null +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(); +} - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); - socket.unshift(head) +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; - 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')) +/***/ 5549: +/***/ ((module) => { - try { - request.onUpgrade(statusCode, headers, socket) - } catch (err) { - util.destroy(socket, err) - } +module.exports = addHook; - resume(client) +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; } - onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { - const { client, socket, headers, statusText } = this + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 - } + 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; + }); + }; + } - const request = client[kQueue][client[kRunningIdx]] + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } - /* istanbul ignore next: difficult to make a test case for */ - if (!request) { - return -1 - } + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} - 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 - } +/***/ 4670: +/***/ ((module) => { - assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) +module.exports = register; - 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') - ) +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } - 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 (!options) { + options = {}; + } - if (request.method === 'CONNECT') { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - if (upgrade) { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - 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 + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} - 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 - } +/***/ 6819: +/***/ ((module) => { - if (request.method === 'HEAD') { - return 1 - } +module.exports = removeHook; - if (statusCode < 200) { - return 1 - } +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } - if (socket[kBlocking]) { - socket[kBlocking] = false - resume(client) - } + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); - return pause ? constants.ERROR.PAUSED : 0 + if (index === -1) { + return; } - onBody (buf) { - const { client, socket, statusCode, maxResponseSize } = this + state.registry[name].splice(index, 1); +} - 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() - } - } +/***/ 2983: +/***/ ((module, exports) => { - assert(statusCode >= 200) +// Chance.js 1.1.12 +// https://chancejs.com +// (c) 2013 Victor Quinn +// Chance may be freely distributed or modified under the MIT license. - if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { - util.destroy(socket, new ResponseExceededMaxSizeError()) - return -1 - } +(function () { - this.bytesRead += buf.length + // Constants + var MAX_INT = 9007199254740992; + var MIN_INT = -MAX_INT; + var NUMBERS = '0123456789'; + var CHARS_LOWER = 'abcdefghijklmnopqrstuvwxyz'; + var CHARS_UPPER = CHARS_LOWER.toUpperCase(); + var HEX_POOL = NUMBERS + "abcdef"; - if (request.onData(buf) === false) { - return constants.ERROR.PAUSED + // Errors + function UnsupportedError(message) { + this.name = 'UnsupportedError'; + this.message = message || 'This feature is not supported on this platform'; } - } - onMessageComplete () { - const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + UnsupportedError.prototype = new Error(); + UnsupportedError.prototype.constructor = UnsupportedError; - if (socket.destroyed && (!statusCode || shouldKeepAlive)) { - return -1 - } + // Cached array helpers + var slice = Array.prototype.slice; - if (upgrade) { - return - } + // Constructor + function Chance (seed) { + if (!(this instanceof Chance)) { + if (!seed) { seed = null; } // handle other non-truthy seeds, as described in issue #322 + return seed === null ? new Chance() : new Chance(seed); + } - const request = client[kQueue][client[kRunningIdx]] - assert(request) + // if user has provided a function, use that as the generator + if (typeof seed === 'function') { + this.random = seed; + return this; + } - assert(statusCode >= 100) + if (arguments.length) { + // set a starting value of zero so we can add to it + this.seed = 0; + } - this.statusCode = null - this.statusText = '' - this.bytesRead = 0 - this.contentLength = '' - this.keepAlive = '' - this.connection = '' + // otherwise, leave this.seed blank so that MT will receive a blank - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 + for (var i = 0; i < arguments.length; i++) { + var seedling = 0; + if (Object.prototype.toString.call(arguments[i]) === '[object String]') { + for (var j = 0; j < arguments[i].length; j++) { + // create a numeric hash for each argument, add to seedling + var hash = 0; + for (var k = 0; k < arguments[i].length; k++) { + hash = arguments[i].charCodeAt(k) + (hash << 6) + (hash << 16) - hash; + } + seedling += hash; + } + } else { + seedling = arguments[i]; + } + this.seed += (arguments.length - i) * seedling; + } - if (statusCode < 200) { - return - } + // If no generator function was provided, use our MT + this.mt = this.mersenne_twister(this.seed); + this.bimd5 = this.blueimp_md5(); + this.random = function () { + return this.mt.random(this.seed); + }; - /* istanbul ignore next: should be handled by llhttp? */ - if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { - util.destroy(socket, new ResponseContentLengthMismatchError()) - return -1 + return this; } - request.onComplete(headers) - - client[kQueue][client[kRunningIdx]++] = null + Chance.prototype.VERSION = "1.1.13"; - 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) - } - } -} + // Random helper functions + function initOptions(options, defaults) { + options = options || {}; -function onParserTimeout (parser) { - const { socket, timeoutType, client } = parser + if (defaults) { + for (var i in defaults) { + if (typeof options[i] === 'undefined') { + options[i] = defaults[i]; + } + } + } - /* 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()) + return options; } - } else if (timeoutType === TIMEOUT_BODY) { - if (!parser.paused) { - util.destroy(socket, new BodyTimeoutError()) + + function range(size) { + return Array.apply(null, Array(size)).map(function (_, i) {return i;}); } - } 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 testRange(test, errorMessage) { + if (test) { + throw new RangeError(errorMessage); + } + } -function onSocketError (err) { - const { [kClient]: client, [kParser]: parser } = this + /** + * Encode the input string with Base64. + */ + var base64 = function() { + throw new Error('No Base64 encoder available.'); + }; - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + // Select proper Base64 encoder. + (function determineBase64Encoder() { + if (typeof btoa === 'function') { + base64 = btoa; + } else if (typeof Buffer === 'function') { + base64 = function(input) { + return new Buffer(input).toString('base64'); + }; + } + })(); - 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 - } - } + // -- Basics -- - this[kError] = err + /** + * Return a random bool, either true or false + * + * @param {Object} [options={ likelihood: 50 }] alter the likelihood of + * receiving a true or false value back. + * @throws {RangeError} if the likelihood is out of bounds + * @returns {Bool} either true or false + */ + Chance.prototype.bool = function (options) { + // likelihood of success (true) + options = initOptions(options, {likelihood : 50}); - onError(this[kClient], err) -} + // Note, we could get some minor perf optimizations by checking range + // prior to initializing defaults, but that makes code a bit messier + // and the check more complicated as we have to check existence of + // the object then existence of the key before checking constraints. + // Since the options initialization should be minor computationally, + // decision made for code cleanliness intentionally. This is mentioned + // here as it's the first occurrence, will not be mentioned again. + testRange( + options.likelihood < 0 || options.likelihood > 100, + "Chance: Likelihood accepts values from 0 to 100." + ); -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. + return this.random() * 100 < options.likelihood; + }; - assert(client[kPendingIdx] === client[kRunningIdx]) + Chance.prototype.falsy = function (options) { + // return a random falsy value + options = initOptions(options, {pool: [false, null, 0, NaN, '', undefined]}) + var pool = options.pool, + index = this.integer({min: 0, max: pool.length - 1}), + value = pool[index]; - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(client, request, err) + return value; } - assert(client[kSize] === 0) - } -} -function onSocketEnd () { - const { [kParser]: parser, [kClient]: client } = this + Chance.prototype.animal = function (options){ + //returns a random animal + options = initOptions(options); + + if(typeof options.type !== 'undefined'){ + //if user does not put in a valid animal type, user will get an error + testRange( + !this.get("animals")[options.type.toLowerCase()], + "Please pick from desert, ocean, grassland, forest, zoo, pets, farm." + ); + //if user does put in valid animal type, will return a random animal of that type + return this.pick(this.get("animals")[options.type.toLowerCase()]); + } + //if user does not put in any animal type, will return a random animal regardless + var animalTypeArray = ["desert","forest","ocean","zoo","farm","pet","grassland"]; + return this.pick(this.get("animals")[this.pick(animalTypeArray)]); + }; + + /** + * Return a random character. + * + * @param {Object} [options={}] can specify a character pool or alpha, + * numeric, symbols and casing (lower or upper) + * @returns {String} a single random character + */ + Chance.prototype.character = function (options) { + options = initOptions(options); - if (client[kHTTPConnVersion] !== 'h2') { - if (parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so far as a valid response. - parser.onMessageComplete() - return - } - } + var symbols = "!@#$%^&*()[]", + letters, pool; - util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) -} + if (options.casing === 'lower') { + letters = CHARS_LOWER; + } else if (options.casing === 'upper') { + letters = CHARS_UPPER; + } else { + letters = CHARS_LOWER + CHARS_UPPER; + } -function onSocketClose () { - const { [kClient]: client, [kParser]: parser } = this + if (options.pool) { + pool = options.pool; + } else { + pool = ''; + if (options.alpha) { + pool += letters; + } + if (options.numeric) { + pool += NUMBERS; + } + if (options.symbols) { + pool += symbols; + } + if (!pool) { + pool = letters + NUMBERS + symbols; + } + } - 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() - } + return pool.charAt(this.natural({max: (pool.length - 1)})); + }; - this[kParser].destroy() - this[kParser] = null - } + // Note, wanted to use "float" or "double" but those are both JS reserved words. - const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + // Note, fixed means N OR LESS digits after the decimal. This because + // It could be 14.9000 but in JavaScript, when this is cast as a number, + // the trailing zeroes are dropped. Left to the consumer if trailing zeroes are + // needed + /** + * Return a random floating point number + * + * @param {Object} [options={}] can specify a fixed precision, min, max + * @returns {Number} a single floating point number + * @throws {RangeError} Can only specify fixed or precision, not both. Also + * min cannot be greater than max + */ + Chance.prototype.floating = function (options) { + options = initOptions(options, {fixed : 4}); + testRange( + options.fixed && options.precision, + "Chance: Cannot specify both fixed and precision." + ); - client[kSocket] = null + var num; + var fixed = Math.pow(10, options.fixed); - if (client.destroyed) { - assert(client[kPending] === 0) + var max = MAX_INT / fixed; + var min = -max; - // 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 + testRange( + options.min && options.fixed && options.min < min, + "Chance: Min specified is out of range with fixed. Min should be, at least, " + min + ); + testRange( + options.max && options.fixed && options.max > max, + "Chance: Max specified is out of range with fixed. Max should be, at most, " + max + ); - errorRequest(client, request, err) - } + options = initOptions(options, { min : min, max : max }); - client[kPendingIdx] = client[kRunningIdx] + // Todo - Make this work! + // options.precision = (typeof options.precision !== "undefined") ? options.precision : false; - assert(client[kRunning] === 0) + num = this.integer({min: options.min * fixed, max: options.max * fixed}); + var num_fixed = (num / fixed).toFixed(options.fixed); - client.emit('disconnect', client[kUrl], [client], err) + return parseFloat(num_fixed); + }; - resume(client) -} + /** + * Return a random integer + * + * NOTE the max and min are INCLUDED in the range. So: + * chance.integer({min: 1, max: 3}); + * would return either 1, 2, or 3. + * + * @param {Object} [options={}] can specify a min and/or max + * @returns {Number} a single random integer number + * @throws {RangeError} min cannot be greater than max + */ + Chance.prototype.integer = function (options) { + // 9007199254740992 (2^53) is the max integer number in JavaScript + // See: http://vq.io/132sa2j + options = initOptions(options, {min: MIN_INT, max: MAX_INT}); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); -async function connect (client) { - assert(!client[kConnecting]) - assert(!client[kSocket]) + return Math.floor(this.random() * (options.max - options.min + 1) + options.min); + }; - let { host, hostname, protocol, port } = client[kUrl] + /** + * Return a random natural + * + * NOTE the max and min are INCLUDED in the range. So: + * chance.natural({min: 1, max: 3}); + * would return either 1, 2, or 3. + * + * @param {Object} [options={}] can specify a min and/or max or a numerals count. + * @returns {Number} a single random integer number + * @throws {RangeError} min cannot be greater than max + */ + Chance.prototype.natural = function (options) { + options = initOptions(options, {min: 0, max: MAX_INT}); + if (typeof options.numerals === 'number'){ + testRange(options.numerals < 1, "Chance: Numerals cannot be less than one."); + options.min = Math.pow(10, options.numerals - 1); + options.max = Math.pow(10, options.numerals) - 1; + } + testRange(options.min < 0, "Chance: Min cannot be less than zero."); - // Resolve ipv6 - if (hostname[0] === '[') { - const idx = hostname.indexOf(']') + if (options.exclude) { + testRange(!Array.isArray(options.exclude), "Chance: exclude must be an array.") - assert(idx !== -1) - const ip = hostname.substring(1, idx) + for (var exclusionIndex in options.exclude) { + testRange(!Number.isInteger(options.exclude[exclusionIndex]), "Chance: exclude must be numbers.") + } - assert(net.isIP(ip)) - hostname = ip - } + var random = options.min + this.natural({max: options.max - options.min - options.exclude.length}) + var sortedExclusions = options.exclude.sort((a, b) => a - b); + for (var sortedExclusionIndex in sortedExclusions) { + if (random < sortedExclusions[sortedExclusionIndex]) { + break + } + random++ + } + return random + } + return this.integer(options); + }; - client[kConnecting] = true + /** + * Return a random prime number + * + * NOTE the max and min are INCLUDED in the range. + * + * @param {Object} [options={}] can specify a min and/or max + * @returns {Number} a single random prime number + * @throws {RangeError} min cannot be greater than max nor negative + */ + Chance.prototype.prime = function (options) { + options = initOptions(options, {min: 0, max: 10000}); + testRange(options.min < 0, "Chance: Min cannot be less than zero."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - if (channels.beforeConnect.hasSubscribers) { - channels.beforeConnect.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector] - }) - } + var lastPrime = data.primes[data.primes.length - 1]; + if (options.max > lastPrime) { + for (var i = lastPrime + 2; i <= options.max; ++i) { + if (this.is_prime(i)) { + data.primes.push(i); + } + } + } + var targetPrimes = data.primes.filter(function (prime) { + return prime >= options.min && prime <= options.max; + }); + return this.pick(targetPrimes); + }; - 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) + /** + * Determine whether a given number is prime or not. + */ + Chance.prototype.is_prime = function (n) { + if (n % 1 || n < 2) { + return false; } - }) - }) + if (n % 2 === 0) { + return n === 2; + } + if (n % 3 === 0) { + return n === 3; + } + var m = Math.sqrt(n); + for (var i = 5; i <= m; i += 6) { + if (n % i === 0 || n % (i + 2) === 0) { + return false; + } + } + return true; + }; - if (client.destroyed) { - util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) - return - } + /** + * Return a random hex number as string + * + * NOTE the max and min are INCLUDED in the range. So: + * chance.hex({min: '9', max: 'B'}); + * would return either '9', 'A' or 'B'. + * + * @param {Object} [options={}] can specify a min and/or max and/or casing + * @returns {String} a single random string hex number + * @throws {RangeError} min cannot be greater than max + */ + Chance.prototype.hex = function (options) { + options = initOptions(options, {min: 0, max: MAX_INT, casing: 'lower'}); + testRange(options.min < 0, "Chance: Min cannot be less than zero."); + var integer = this.natural({min: options.min, max: options.max}); + if (options.casing === 'upper') { + return integer.toString(16).toUpperCase(); + } + return integer.toString(16); + }; - client[kConnecting] = false + Chance.prototype.letter = function(options) { + options = initOptions(options, {casing: 'lower'}); + var pool = "abcdefghijklmnopqrstuvwxyz"; + var letter = this.character({pool: pool}); + if (options.casing === 'upper') { + letter = letter.toUpperCase(); + } + return letter; + } - assert(socket) + /** + * Return a random string + * + * @param {Object} [options={}] can specify a length or min and max + * @returns {String} a string of random length + * @throws {RangeError} length cannot be less than zero + */ + Chance.prototype.string = function (options) { + options = initOptions(options, { min: 5, max: 20 }); - 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' - }) - } + if (options.length !== 0 && !options.length) { + options.length = this.natural({ min: options.min, max: options.max }) + } - const session = http2.connect(client[kUrl], { - createConnection: () => socket, - peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams - }) + testRange(options.length < 0, "Chance: Length cannot be less than zero."); + var length = options.length, + text = this.n(this.character, length, options); - 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() + return text.join(""); + }; - client[kHTTP2Session] = session - socket[kHTTP2Session] = session - } else { - if (!llhttpInstance) { - llhttpInstance = await llhttpPromise - llhttpPromise = null - } + function CopyToken(c) { + this.c = c + } - socket[kNoRef] = false - socket[kWriting] = false - socket[kReset] = false - socket[kBlocking] = false - socket[kParser] = new Parser(client, socket, llhttpInstance) + CopyToken.prototype = { + substitute: function () { + return this.c + } } - socket[kCounter] = 0 - socket[kMaxRequests] = client[kMaxRequests] - socket[kClient] = client - socket[kError] = null + function EscapeToken(c) { + this.c = c + } - socket - .on('error', onSocketError) - .on('readable', onSocketReadable) - .on('end', onSocketEnd) - .on('close', onSocketClose) + EscapeToken.prototype = { + substitute: function () { + if (!/[{}\\]/.test(this.c)) { + throw new Error('Invalid escape sequence: "\\' + this.c + '".') + } + return this.c + } + } - client[kSocket] = socket + function ReplaceToken(c) { + this.c = c + } - if (channels.connected.hasSubscribers) { - channels.connected.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] + ReplaceToken.prototype = { + replacers: { + '#': function (chance) { return chance.character({ pool: NUMBERS }) }, + 'A': function (chance) { return chance.character({ pool: CHARS_UPPER }) }, + 'a': function (chance) { return chance.character({ pool: CHARS_LOWER }) }, }, - connector: client[kConnector], - socket - }) + + substitute: function (chance) { + var replacer = this.replacers[this.c] + if (!replacer) { + throw new Error('Invalid replacement character: "' + this.c + '".') + } + return replacer(chance) + } } - client.emit('connect', client[kUrl], [client]) - } catch (err) { - if (client.destroyed) { - return + + function parseTemplate(template) { + var tokens = [] + var mode = 'identity' + for (var i = 0; i 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { - const request = client[kQueue][client[kPendingIdx]++] - errorRequest(client, request, err) - } - } else { - onError(client, err) - } + /** + * Return a random buffer + * + * @param {Object} [options={}] can specify a length + * @returns {Buffer} a buffer of random length + * @throws {RangeError} length cannot be less than zero + */ + Chance.prototype.buffer = function (options) { + if (typeof Buffer === 'undefined') { + throw new UnsupportedError('Sorry, the buffer() function is not supported on your platform'); + } + options = initOptions(options, { length: this.natural({min: 5, max: 20}) }); + testRange(options.length < 0, "Chance: Length cannot be less than zero."); + var length = options.length; + var content = this.n(this.character, length, options); - client.emit('connectionError', client[kUrl], [client], err) - } + return Buffer.from(content); + }; - resume(client) -} + // -- End Basics -- -function emitDrain (client) { - client[kNeedDrain] = 0 - client.emit('drain', client[kUrl], [client]) -} + // -- Helpers -- -function resume (client, sync) { - if (client[kResuming] === 2) { - return - } + Chance.prototype.capitalize = function (word) { + return word.charAt(0).toUpperCase() + word.substr(1); + }; - client[kResuming] = 2 + Chance.prototype.mixin = function (obj) { + for (var func_name in obj) { + this[func_name] = obj[func_name]; + } + return this; + }; - _resume(client, sync) - client[kResuming] = 0 + /** + * Given a function that generates something random and a number of items to generate, + * return an array of items where none repeat. + * + * @param {Function} fn the function that generates something random + * @param {Number} num number of terms to generate + * @param {Object} options any options to pass on to the generator function + * @returns {Array} an array of length `num` with every item generated by `fn` and unique + * + * There can be more parameters after these. All additional parameters are provided to the given function + */ + Chance.prototype.unique = function(fn, num, options) { + testRange( + typeof fn !== "function", + "Chance: The first argument must be a function." + ); - if (client[kRunningIdx] > 256) { - client[kQueue].splice(0, client[kRunningIdx]) - client[kPendingIdx] -= client[kRunningIdx] - client[kRunningIdx] = 0 - } -} + var comparator = function(arr, val) { return arr.indexOf(val) !== -1; }; -function _resume (client, sync) { - while (true) { - if (client.destroyed) { - assert(client[kPending] === 0) - return - } + if (options) { + comparator = options.comparator || comparator; + } - if (client[kClosedResolve] && !client[kSize]) { - client[kClosedResolve]() - client[kClosedResolve] = null - return - } + var arr = [], count = 0, result, MAX_DUPLICATES = num * 50, params = slice.call(arguments, 2); - const socket = client[kSocket] + while (arr.length < num) { + var clonedParams = JSON.parse(JSON.stringify(params)); + result = fn.apply(this, clonedParams); + if (!comparator(arr, result)) { + arr.push(result); + // reset count when unique found + count = 0; + } - if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { - if (client[kSize] === 0) { - if (!socket[kNoRef] && socket.unref) { - socket.unref() - socket[kNoRef] = true + if (++count > MAX_DUPLICATES) { + throw new RangeError("Chance: num is likely too large for sample set"); + } } - } else if (socket[kNoRef] && socket.ref) { - socket.ref() - socket[kNoRef] = false - } + return arr; + }; - if (client[kSize] === 0) { - if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { - socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) + /** + * Gives an array of n random terms + * + * @param {Function} fn the function that generates something random + * @param {Number} n number of terms to generate + * @returns {Array} an array of length `n` with items generated by `fn` + * + * There can be more parameters after these. All additional parameters are provided to the given function + */ + Chance.prototype.n = function(fn, n) { + testRange( + typeof fn !== "function", + "Chance: The first argument must be a function." + ); + + if (typeof n === 'undefined') { + n = 1; } - } 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) + var i = n, arr = [], params = slice.call(arguments, 2); + + // Providing a negative count should result in a noop. + i = Math.max( 0, i ); + + for (null; i--; null) { + arr.push(fn.apply(this, params)); } - } - } - if (client[kBusy]) { - client[kNeedDrain] = 2 - } else if (client[kNeedDrain] === 2) { - if (sync) { - client[kNeedDrain] = 1 - process.nextTick(emitDrain, client) - } else { - emitDrain(client) - } - continue - } + return arr; + }; - if (client[kPending] === 0) { - return - } + // H/T to SO for this one: http://vq.io/OtUrZ5 + Chance.prototype.pad = function (number, width, pad) { + // Default pad to 0 if none provided + pad = pad || '0'; + // Convert number to a string + number = number + ''; + return number.length >= width ? number : new Array(width - number.length + 1).join(pad) + number; + }; - if (client[kRunning] >= (client[kPipelining] || 1)) { - return - } + // DEPRECATED on 2015-10-01 + Chance.prototype.pick = function (arr, count) { + if (arr.length === 0) { + throw new RangeError("Chance: Cannot pick() from an empty array"); + } + if (!count || count === 1) { + return arr[this.natural({max: arr.length - 1})]; + } else { + return this.shuffle(arr).slice(0, count); + } + }; - const request = client[kQueue][client[kPendingIdx]] + // Given an array, returns a single random element + Chance.prototype.pickone = function (arr) { + if (arr.length === 0) { + throw new RangeError("Chance: Cannot pickone() from an empty array"); + } + return arr[this.natural({max: arr.length - 1})]; + }; - if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { - if (client[kRunning] > 0) { - return - } + // Given an array, returns a random set with 'count' elements + Chance.prototype.pickset = function (arr, count) { + if (count === 0) { + return []; + } + if (arr.length === 0) { + throw new RangeError("Chance: Cannot pickset() from an empty array"); + } + if (count < 0) { + throw new RangeError("Chance: Count must be a positive number"); + } + if (!count || count === 1) { + return [ this.pickone(arr) ]; + } else { + var array = arr.slice(0); + var end = array.length; - client[kServerName] = request.servername + return this.n(function () { + var index = this.natural({max: --end}); + var value = array[index]; + array[index] = array[end]; + return value; + }, Math.min(end, count)); + } + }; - if (socket && socket.servername !== request.servername) { - util.destroy(socket, new InformationalError('servername changed')) - return - } - } + Chance.prototype.shuffle = function (arr) { + var new_array = [], + j = 0, + length = Number(arr.length), + source_indexes = range(length), + last_source_index = length - 1, + selected_source_index; - if (client[kConnecting]) { - return - } + for (var i = 0; i < length; i++) { + // Pick a random index from the array + selected_source_index = this.natural({max: last_source_index}); + j = source_indexes[selected_source_index]; - if (!socket && !client[kHTTP2Session]) { - connect(client) - return - } + // Add it to the new array + new_array[i] = arr[j]; - if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { - return - } + // Mark the source index as used + source_indexes[selected_source_index] = source_indexes[last_source_index]; + last_source_index -= 1; + } - if (client[kRunning] > 0 && !request.idempotent) { - // Non-idempotent request cannot be retried. - // Ensure that no other requests are inflight and - // could cause failure. - return - } + return new_array; + }; - 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 - } + // Returns a single item from an array with relative weighting of odds + Chance.prototype.weighted = function (arr, weights, trim) { + if (arr.length !== weights.length) { + throw new RangeError("Chance: Length of array and weights must match"); + } - 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. + // scan weights array and sum valid entries + var sum = 0; + var val; + for (var weightIndex = 0; weightIndex < weights.length; ++weightIndex) { + val = weights[weightIndex]; + if (isNaN(val)) { + throw new RangeError("Chance: All weights must be numbers"); + } - // Request with stream or iterator body cannot be retried. - // Ensure that no other requests are inflight and - // could cause failure. - return - } + if (val > 0) { + sum += val; + } + } - if (!request.aborted && write(client, request)) { - client[kPendingIdx]++ - } else { - client[kQueue].splice(client[kPendingIdx], 1) - } - } -} + if (sum === 0) { + throw new RangeError("Chance: No valid entries in array weights"); + } -// 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' -} + // select a value within range + var selected = this.random() * sum; -function write (client, request) { - if (client[kHTTPConnVersion] === 'h2') { - writeH2(client, client[kHTTP2Session], request) - return - } + // find array entry corresponding to selected value + var total = 0; + var lastGoodIdx = -1; + var chosenIdx; + for (weightIndex = 0; weightIndex < weights.length; ++weightIndex) { + val = weights[weightIndex]; + total += val; + if (val > 0) { + if (selected <= total) { + chosenIdx = weightIndex; + break; + } + lastGoodIdx = weightIndex; + } - const { body, method, path, host, upgrade, headers, blocking, reset } = request + // handle any possible rounding error comparison to ensure something is picked + if (weightIndex === (weights.length - 1)) { + chosenIdx = lastGoodIdx; + } + } - // 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 + var chosen = arr[chosenIdx]; + trim = (typeof trim === 'undefined') ? false : trim; + if (trim) { + arr.splice(chosenIdx, 1); + weights.splice(chosenIdx, 1); + } - // 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. + return chosen; + }; - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) + // -- End Helpers -- - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) - } + // -- Text -- - const bodyLength = util.bodyLength(body) + Chance.prototype.paragraph = function (options) { + options = initOptions(options); - let contentLength = bodyLength + var sentences = options.sentences || this.natural({min: 3, max: 7}), + sentence_array = this.n(this.sentence, sentences), + separator = options.linebreak === true ? '\n' : ' '; - if (contentLength === null) { - contentLength = request.contentLength - } + return sentence_array.join(separator); + }; - 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. + // Could get smarter about this than generating random words and + // chaining them together. Such as: http://vq.io/1a5ceOh + Chance.prototype.sentence = function (options) { + options = initOptions(options); - contentLength = null - } + var words = options.words || this.natural({min: 12, max: 18}), + punctuation = options.punctuation, + text, word_array = this.n(this.word, words); - // 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 - } + text = word_array.join(' '); - process.emitWarning(new RequestContentLengthMismatchError()) - } + // Capitalize first letter of sentence + text = this.capitalize(text); - const socket = client[kSocket] + // Make sure punctuation has a usable value + if (punctuation !== false && !/^[.?;!:]$/.test(punctuation)) { + punctuation = '.'; + } - try { - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } + // Add punctuation mark + if (punctuation) { + text += punctuation; + } - errorRequest(client, request, err || new RequestAbortedError()) + return text; + }; - util.destroy(socket, new InformationalError('aborted')) - }) - } catch (err) { - errorRequest(client, request, err) - } + Chance.prototype.syllable = function (options) { + options = initOptions(options); - if (request.aborted) { - return false - } + var length = options.length || this.natural({min: 2, max: 3}), + consonants = 'bcdfghjklmnprstvwz', // consonants except hard to speak ones + vowels = 'aeiou', // vowels + all = consonants + vowels, // all + text = '', + chr; - 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. + // I'm sure there's a more elegant way to do this, but this works + // decently well. + for (var i = 0; i < length; i++) { + if (i === 0) { + // First character can be anything + chr = this.character({pool: all}); + } else if (consonants.indexOf(chr) === -1) { + // Last character was a vowel, now we want a consonant + chr = this.character({pool: consonants}); + } else { + // Last character was a consonant, now we want a vowel + chr = this.character({pool: vowels}); + } - socket[kReset] = true - } + text += chr; + } - if (upgrade || method === 'CONNECT') { - // On CONNECT or upgrade, block pipeline from dispatching further - // requests on this connection. + if (options.capitalize) { + text = this.capitalize(text); + } - socket[kReset] = true - } + return text; + }; - if (reset != null) { - socket[kReset] = reset - } + Chance.prototype.word = function (options) { + options = initOptions(options); - if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { - socket[kReset] = true - } + testRange( + options.syllables && options.length, + "Chance: Cannot specify both syllables AND length." + ); - if (blocking) { - socket[kBlocking] = true - } + var syllables = options.syllables || this.natural({min: 1, max: 3}), + text = ''; - let header = `${method} ${path} HTTP/1.1\r\n` + if (options.length) { + // Either bound word by length + do { + text += this.syllable(); + } while (text.length < options.length); + text = text.substring(0, options.length); + } else { + // Or by number of syllables + for (var i = 0; i < syllables; i++) { + text += this.syllable(); + } + } - if (typeof host === 'string') { - header += `host: ${host}\r\n` - } else { - header += client[kHostHeader] - } + if (options.capitalize) { + text = this.capitalize(text); + } - 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' - } + return text; + }; - if (headers) { - header += headers - } + Chance.prototype.emoji = function (options) { + options = initOptions(options, { category: "all", length: 1 }); - if (channels.sendHeaders.hasSubscribers) { - channels.sendHeaders.publish({ request, headers: header, socket }) - } + testRange( + options.length < 1 || BigInt(options.length) > BigInt(MAX_INT), + "Chance: length must be between 1 and " + String(MAX_INT) + ); - /* 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') + var emojis = this.get("emojis"); + + if (options.category === "all") { + options.category = this.pickone(Object.keys(emojis)); + } - 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) - } + var emojisForCategory = emojis[options.category]; - return true -} + testRange( + emojisForCategory === undefined, + "Chance: Unrecognised emoji category: [" + options.category + "]." + ); -function writeH2 (client, session, request) { - const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request + return this.pickset(emojisForCategory, options.length) + .map(function (codePoint) { + return String.fromCodePoint(codePoint); + }).join(""); + }; - let headers - if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) - else headers = reqHeaders + // -- End Text -- - if (upgrade) { - errorRequest(client, request, new Error('Upgrade not supported for H2')) - return false - } + // -- Person -- - try { - // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } + Chance.prototype.age = function (options) { + options = initOptions(options); + var ageRange; - errorRequest(client, request, err || new RequestAbortedError()) - }) - } catch (err) { - errorRequest(client, request, err) - } + switch (options.type) { + case 'child': + ageRange = {min: 0, max: 12}; + break; + case 'teen': + ageRange = {min: 13, max: 19}; + break; + case 'adult': + ageRange = {min: 18, max: 65}; + break; + case 'senior': + ageRange = {min: 65, max: 100}; + break; + case 'all': + ageRange = {min: 0, max: 100}; + break; + default: + ageRange = {min: 18, max: 65}; + break; + } - if (request.aborted) { - return false - } + return this.natural(ageRange); + }; - /** @type {import('node:http2').ClientHttp2Stream} */ - let stream - const h2State = client[kHTTP2SessionState] + Chance.prototype.birthday = function (options) { + var age = this.age(options); + var now = new Date() + var currentYear = now.getFullYear(); - headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] - headers[HTTP2_HEADER_METHOD] = method + if (options && options.type) { + var min = new Date(); + var max = new Date(); + min.setFullYear(currentYear - age - 1); + max.setFullYear(currentYear - age); - 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 }) + options = initOptions(options, { + min: min, + max: max + }); + } else if (options && ((options.minAge !== undefined) || (options.maxAge !== undefined))) { + testRange(options.minAge < 0, "Chance: MinAge cannot be less than zero."); + testRange(options.minAge > options.maxAge, "Chance: MinAge cannot be greater than MaxAge."); - if (stream.id && !stream.pending) { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - } else { - stream.once('ready', () => { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - }) - } + var minAge = options.minAge !== undefined ? options.minAge : 0; + var maxAge = options.maxAge !== undefined ? options.maxAge : 100; - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) session.unref() - }) + var minDate = new Date(currentYear - maxAge - 1, now.getMonth(), now.getDate()); + var maxDate = new Date(currentYear - minAge, now.getMonth(), now.getDate()); - return true - } + minDate.setDate(minDate.getDate() +1); - // https://tools.ietf.org/html/rfc7540#section-8.3 - // :path and :scheme headers must be omited when sending CONNECT + maxDate.setDate(maxDate.getDate() +1); + maxDate.setMilliseconds(maxDate.getMilliseconds() -1); - headers[HTTP2_HEADER_PATH] = path - headers[HTTP2_HEADER_SCHEME] = 'https' + options = initOptions(options, { + min: minDate, + max: maxDate + }); + } else { + options = initOptions(options, { + year: currentYear - age + }); + } - // 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 + return this.date(options); + }; - // 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. + // CPF; ID to identify taxpayers in Brazil + Chance.prototype.cpf = function (options) { + options = initOptions(options, { + formatted: true + }); - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) + var n = this.n(this.natural, 9, { max: 9 }); + var d1 = n[8]*2+n[7]*3+n[6]*4+n[5]*5+n[4]*6+n[3]*7+n[2]*8+n[1]*9+n[0]*10; + d1 = 11 - (d1 % 11); + if (d1>=10) { + d1 = 0; + } + var d2 = d1*2+n[8]*3+n[7]*4+n[6]*5+n[5]*6+n[4]*7+n[3]*8+n[2]*9+n[1]*10+n[0]*11; + d2 = 11 - (d2 % 11); + if (d2>=10) { + d2 = 0; + } + var cpf = ''+n[0]+n[1]+n[2]+'.'+n[3]+n[4]+n[5]+'.'+n[6]+n[7]+n[8]+'-'+d1+d2; + return options.formatted ? cpf : cpf.replace(/\D/g,''); + }; - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) - } + // CNPJ: ID to identify companies in Brazil + Chance.prototype.cnpj = function (options) { + options = initOptions(options, { + formatted: true + }); - let contentLength = util.bodyLength(body) + var n = this.n(this.natural, 12, { max: 12 }); + var d1 = n[11]*2+n[10]*3+n[9]*4+n[8]*5+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; + d1 = 11 - (d1 % 11); + if (d1<2) { + d1 = 0; + } + var d2 = d1*2+n[11]*3+n[10]*4+n[9]*5+n[8]*6+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; + d2 = 11 - (d2 % 11); + if (d2<2) { + d2 = 0; + } + var cnpj = ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/'+n[8]+n[9]+n[10]+n[11]+'-'+d1+d2; + return options.formatted ? cnpj : cnpj.replace(/\D/g,''); + }; - if (contentLength == null) { - contentLength = request.contentLength - } + Chance.prototype.first = function (options) { + options = initOptions(options, {gender: this.gender(), nationality: 'en'}); + return this.pick(this.get("firstNames")[options.gender.toLowerCase()][options.nationality.toLowerCase()]); + }; - 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. + Chance.prototype.profession = function (options) { + options = initOptions(options); + if(options.rank){ + return this.pick(['Apprentice ', 'Junior ', 'Senior ', 'Lead ']) + this.pick(this.get("profession")); + } else{ + return this.pick(this.get("profession")); + } + }; - contentLength = null - } + Chance.prototype.company = function (){ + return this.pick(this.get("company")); + }; - // 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 - } + Chance.prototype.gender = function (options) { + options = initOptions(options, {extraGenders: []}); + return this.pick(['Male', 'Female'].concat(options.extraGenders)); + }; - process.emitWarning(new RequestContentLengthMismatchError()) - } + Chance.prototype.last = function (options) { + options = initOptions(options, {nationality: '*'}); + if (options.nationality === "*") { + var allLastNames = [] + var lastNames = this.get("lastNames") + Object.keys(lastNames).forEach(function(key){ + allLastNames = allLastNames.concat(lastNames[key]) + }) + return this.pick(allLastNames) + } + else { + return this.pick(this.get("lastNames")[options.nationality.toLowerCase()]); + } - if (contentLength != null) { - assert(body, 'no body must not have content length') - headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` - } + }; - session.ref() + Chance.prototype.israelId=function(){ + var x=this.string({pool: '0123456789',length:8}); + var y=0; + for (var i=0;i { - const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + if(pos !== -1) { + character = pos === 0 ? 0 : pos + 9; + } else { + character = parseInt(character, 10); + } + character *= multipliers[idx % multipliers.length]; + runningTotal += character; + }); + return runningTotal % 10; + }; + var generate = function (opts) { + var pad = function (length) { + return new Array(length + 1).join('<'); + }; + var number = [ 'P<', + opts.issuer, + opts.last.toUpperCase(), + '<<', + opts.first.toUpperCase(), + pad(39 - (opts.last.length + opts.first.length + 2)), + opts.passportNumber, + checkDigit(opts.passportNumber), + opts.nationality, + opts.dob, + checkDigit(opts.dob), + opts.gender, + opts.expiry, + checkDigit(opts.expiry), + pad(14), + checkDigit(pad(14)) ].join(''); - if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { - stream.pause() - } - }) + return number + + (checkDigit(number.substr(44, 10) + + number.substr(57, 7) + + number.substr(65, 7))); + }; - stream.once('end', () => { - request.onComplete([]) - }) + var that = this; - stream.on('data', (chunk) => { - if (request.onData(chunk) === false) { - stream.pause() - } - }) + options = initOptions(options, { + first: this.first(), + last: this.last(), + passportNumber: this.integer({min: 100000000, max: 999999999}), + dob: (function () { + var date = that.birthday({type: 'adult'}); + return [date.getFullYear().toString().substr(2), + that.pad(date.getMonth() + 1, 2), + that.pad(date.getDate(), 2)].join(''); + }()), + expiry: (function () { + var date = new Date(); + return [(date.getFullYear() + 5).toString().substr(2), + that.pad(date.getMonth() + 1, 2), + that.pad(date.getDate(), 2)].join(''); + }()), + gender: this.gender() === 'Female' ? 'F': 'M', + issuer: 'GBR', + nationality: 'GBR' + }); + return generate (options); + }; - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) { - session.unref() - } - }) + Chance.prototype.name = function (options) { + options = initOptions(options); - stream.once('error', function (err) { - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) + var first = this.first(options), + last = this.last(options), + name; - stream.once('frameError', (type, code) => { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - errorRequest(client, request, err) + if (options.middle) { + name = first + ' ' + this.first(options) + ' ' + last; + } else if (options.middle_initial) { + name = first + ' ' + this.character({alpha: true, casing: 'upper'}) + '. ' + last; + } else { + name = first + ' ' + last; + } - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) + if (options.prefix) { + name = this.prefix(options) + ' ' + name; + } - // stream.on('aborted', () => { - // // TODO(HTTP/2): Support aborted - // }) + if (options.suffix) { + name = name + ' ' + this.suffix(options); + } - // stream.on('timeout', () => { - // // TODO(HTTP/2): Support timeout - // }) + return name; + }; - // stream.on('push', headers => { - // // TODO(HTTP/2): Suppor push - // }) + // Return the list of available name prefixes based on supplied gender. + // @todo introduce internationalization + Chance.prototype.name_prefixes = function (gender) { + gender = gender || "all"; + gender = gender.toLowerCase(); - // stream.on('trailers', headers => { - // // TODO(HTTP/2): Support trailers - // }) + var prefixes = [ + { name: 'Doctor', abbreviation: 'Dr.' } + ]; - return true + if (gender === "male" || gender === "all") { + prefixes.push({ name: 'Mister', abbreviation: 'Mr.' }); + } - 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) - } - } -} + if (gender === "female" || gender === "all") { + prefixes.push({ name: 'Miss', abbreviation: 'Miss' }); + prefixes.push({ name: 'Misses', abbreviation: 'Mrs.' }); + } + + return prefixes; + }; + + // Alias for name_prefix + Chance.prototype.prefix = function (options) { + return this.name_prefix(options); + }; -function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + Chance.prototype.name_prefix = function (options) { + options = initOptions(options, { gender: "all" }); + return options.full ? + this.pick(this.name_prefixes(options.gender)).name : + this.pick(this.name_prefixes(options.gender)).abbreviation; + }; + //Hungarian ID number + Chance.prototype.HIDN= function(){ + //Hungarian ID nuber structure: XXXXXXYY (X=number,Y=Capital Latin letter) + var idn_pool="0123456789"; + var idn_chrs="ABCDEFGHIJKLMNOPQRSTUVWXYXZ"; + var idn=""; + idn+=this.string({pool:idn_pool,length:6}); + idn+=this.string({pool:idn_chrs,length:2}); + return idn; + }; - 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) + + Chance.prototype.ssn = function (options) { + options = initOptions(options, {ssnFour: false, dashes: true}); + var ssn_pool = "1234567890", + ssn, + dash = options.dashes ? '-' : ''; + + if(!options.ssnFour) { + ssn = this.string({pool: ssn_pool, length: 3}) + dash + + this.string({pool: ssn_pool, length: 2}) + dash + + this.string({pool: ssn_pool, length: 4}); } else { - request.onRequestSent() + ssn = this.string({pool: ssn_pool, length: 4}); } - } - ) + return ssn; + }; - pipe.on('data', onPipeData) - pipe.once('end', () => { - pipe.removeListener('data', onPipeData) - util.destroy(pipe) - }) + // Aadhar is similar to ssn, used in India to uniquely identify a person + Chance.prototype.aadhar = function (options) { + options = initOptions(options, {onlyLastFour: false, separatedByWhiteSpace: true}); + var aadhar_pool = "1234567890", + aadhar, + whiteSpace = options.separatedByWhiteSpace ? ' ' : ''; - function onPipeData (chunk) { - request.onBodySent(chunk) - } + if(!options.onlyLastFour) { + aadhar = this.string({pool: aadhar_pool, length: 4}) + whiteSpace + + this.string({pool: aadhar_pool, length: 4}) + whiteSpace + + this.string({pool: aadhar_pool, length: 4}); + } else { + aadhar = this.string({pool: aadhar_pool, length: 4}); + } + return aadhar; + }; - return - } + // Return the list of available name suffixes + // @todo introduce internationalization + Chance.prototype.name_suffixes = function () { + var suffixes = [ + { name: 'Doctor of Osteopathic Medicine', abbreviation: 'D.O.' }, + { name: 'Doctor of Philosophy', abbreviation: 'Ph.D.' }, + { name: 'Esquire', abbreviation: 'Esq.' }, + { name: 'Junior', abbreviation: 'Jr.' }, + { name: 'Juris Doctor', abbreviation: 'J.D.' }, + { name: 'Master of Arts', abbreviation: 'M.A.' }, + { name: 'Master of Business Administration', abbreviation: 'M.B.A.' }, + { name: 'Master of Science', abbreviation: 'M.S.' }, + { name: 'Medical Doctor', abbreviation: 'M.D.' }, + { name: 'Senior', abbreviation: 'Sr.' }, + { name: 'The Third', abbreviation: 'III' }, + { name: 'The Fourth', abbreviation: 'IV' }, + { name: 'Bachelor of Engineering', abbreviation: 'B.E' }, + { name: 'Bachelor of Technology', abbreviation: 'B.TECH' } + ]; + return suffixes; + }; - let finished = false + // Alias for name_suffix + Chance.prototype.suffix = function (options) { + return this.name_suffix(options); + }; - const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + Chance.prototype.name_suffix = function (options) { + options = initOptions(options); + return options.full ? + this.pick(this.name_suffixes()).name : + this.pick(this.name_suffixes()).abbreviation; + }; - const onData = function (chunk) { - if (finished) { - return - } + Chance.prototype.nationalities = function () { + return this.get("nationalities"); + }; - try { - if (!writer.write(chunk) && this.pause) { - this.pause() - } - } catch (err) { - util.destroy(this, err) - } - } - const onDrain = function () { - if (finished) { - return - } + // Generate random nationality based on json list + Chance.prototype.nationality = function () { + var nationality = this.pick(this.nationalities()); + return nationality.name; + }; - 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 - } + // Generate random zodiac sign + Chance.prototype.zodiac = function () { + const zodiacSymbols = ["Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius","Capricorn","Aquarius","Pisces"]; + return this.pickone(zodiacSymbols); + }; - finished = true - assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + // -- End Person -- - socket - .off('drain', onDrain) - .off('error', onFinished) + // -- Mobile -- + // Android GCM Registration ID + Chance.prototype.android_id = function () { + return "APA91" + this.string({ pool: "0123456789abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_", length: 178 }); + }; - body - .removeListener('data', onData) - .removeListener('end', onFinished) - .removeListener('error', onFinished) - .removeListener('close', onAbort) + // Apple Push Token + Chance.prototype.apple_token = function () { + return this.string({ pool: "abcdef1234567890", length: 64 }); + }; - if (!err) { - try { - writer.end() - } catch (er) { - err = er - } - } + // Windows Phone 8 ANID2 + Chance.prototype.wp8_anid2 = function () { + return base64( this.hash( { length : 32 } ) ); + }; - writer.destroy(err) + // Windows Phone 7 ANID + Chance.prototype.wp7_anid = function () { + return 'A=' + this.guid().replace(/-/g, '').toUpperCase() + '&E=' + this.hash({ length:3 }) + '&W=' + this.integer({ min:0, max:9 }); + }; - if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { - util.destroy(body, err) - } else { - util.destroy(body) - } - } + // BlackBerry Device PIN + Chance.prototype.bb_pin = function () { + return this.hash({ length: 8 }); + }; - body - .on('data', onData) - .on('end', onFinished) - .on('error', onFinished) - .on('close', onAbort) + // -- End Mobile -- - if (body.resume) { - body.resume() - } + // -- Web -- + Chance.prototype.avatar = function (options) { + var url = null; + var URL_BASE = '//www.gravatar.com/avatar/'; + var PROTOCOLS = { + http: 'http', + https: 'https' + }; + var FILE_TYPES = { + bmp: 'bmp', + gif: 'gif', + jpg: 'jpg', + png: 'png' + }; + var FALLBACKS = { + '404': '404', // Return 404 if not found + mm: 'mm', // Mystery man + identicon: 'identicon', // Geometric pattern based on hash + monsterid: 'monsterid', // A generated monster icon + wavatar: 'wavatar', // A generated face + retro: 'retro', // 8-bit icon + blank: 'blank' // A transparent png + }; + var RATINGS = { + g: 'g', + pg: 'pg', + r: 'r', + x: 'x' + }; + var opts = { + protocol: null, + email: null, + fileExtension: null, + size: null, + fallback: null, + rating: null + }; - socket - .on('drain', onDrain) - .on('error', onFinished) -} + if (!options) { + // Set to a random email + opts.email = this.email(); + options = {}; + } + else if (typeof options === 'string') { + opts.email = options; + options = {}; + } + else if (typeof options !== 'object') { + return null; + } + else if (options.constructor === 'Array') { + return null; + } -async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength === body.size, 'blob body must have content length') + opts = initOptions(options, opts); - const isH2 = client[kHTTPConnVersion] === 'h2' - try { - if (contentLength != null && contentLength !== body.size) { - throw new RequestContentLengthMismatchError() - } + if (!opts.email) { + // Set to a random email + opts.email = this.email(); + } - const buffer = Buffer.from(await body.arrayBuffer()) + // Safe checking for params + opts.protocol = PROTOCOLS[opts.protocol] ? opts.protocol + ':' : ''; + opts.size = parseInt(opts.size, 0) ? opts.size : ''; + opts.rating = RATINGS[opts.rating] ? opts.rating : ''; + opts.fallback = FALLBACKS[opts.fallback] ? opts.fallback : ''; + opts.fileExtension = FILE_TYPES[opts.fileExtension] ? opts.fileExtension : ''; - 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() - } + url = + opts.protocol + + URL_BASE + + this.bimd5.md5(opts.email) + + (opts.fileExtension ? '.' + opts.fileExtension : '') + + (opts.size || opts.rating || opts.fallback ? '?' : '') + + (opts.size ? '&s=' + opts.size.toString() : '') + + (opts.rating ? '&r=' + opts.rating : '') + + (opts.fallback ? '&d=' + opts.fallback : '') + ; - request.onBodySent(buffer) - request.onRequestSent() + return url; + }; - if (!expectsPayload) { - socket[kReset] = true - } + /** + * #Description: + * =============================================== + * Generate random color value base on color type: + * -> hex + * -> rgb + * -> rgba + * -> 0x + * -> named color + * + * #Examples: + * =============================================== + * * Geerate random hex color + * chance.color() => '#79c157' / 'rgb(110,52,164)' / '0x67ae0b' / '#e2e2e2' / '#29CFA7' + * + * * Generate Hex based color value + * chance.color({format: 'hex'}) => '#d67118' + * + * * Generate simple rgb value + * chance.color({format: 'rgb'}) => 'rgb(110,52,164)' + * + * * Generate Ox based color value + * chance.color({format: '0x'}) => '0x67ae0b' + * + * * Generate graiscale based value + * chance.color({grayscale: true}) => '#e2e2e2' + * + * * Return valide color name + * chance.color({format: 'name'}) => 'red' + * + * * Make color uppercase + * chance.color({casing: 'upper'}) => '#29CFA7' + * + * * Min Max values for RGBA + * var light_red = chance.color({format: 'hex', min_red: 200, max_red: 255, max_green: 0, max_blue: 0, min_alpha: .2, max_alpha: .3}); + * + * @param [object] options + * @return [string] color value + */ + Chance.prototype.color = function (options) { + function gray(value, delimiter) { + return [value, value, value].join(delimiter || ''); + } - resume(client) - } catch (err) { - util.destroy(isH2 ? h2stream : socket, err) - } -} + function rgb(hasAlpha) { + var rgbValue = (hasAlpha) ? 'rgba' : 'rgb'; + var alphaChannel = (hasAlpha) ? (',' + this.floating({min:min_alpha, max:max_alpha})) : ""; + var colorValue = (isGrayscale) ? (gray(this.natural({min: min_rgb, max: max_rgb}), ',')) : (this.natural({min: min_green, max: max_green}) + ',' + this.natural({min: min_blue, max: max_blue}) + ',' + this.natural({max: 255})); + return rgbValue + '(' + colorValue + alphaChannel + ')'; + } -async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + function hex(start, end, withHash) { + var symbol = (withHash) ? "#" : ""; + var hexstring = ""; - let callback = null - function onDrain () { - if (callback) { - const cb = callback - callback = null - cb() - } - } + if (isGrayscale) { + hexstring = gray(this.pad(this.hex({min: min_rgb, max: max_rgb}), 2)); + if (options.format === "shorthex") { + hexstring = gray(this.hex({min: 0, max: 15})); + } + } + else { + if (options.format === "shorthex") { + hexstring = this.pad(this.hex({min: Math.floor(min_red / 16), max: Math.floor(max_red / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_green / 16), max: Math.floor(max_green / 16)}), 1) + this.pad(this.hex({min: Math.floor(min_blue / 16), max: Math.floor(max_blue / 16)}), 1); + } + else if (min_red !== undefined || max_red !== undefined || min_green !== undefined || max_green !== undefined || min_blue !== undefined || max_blue !== undefined) { + hexstring = this.pad(this.hex({min: min_red, max: max_red}), 2) + this.pad(this.hex({min: min_green, max: max_green}), 2) + this.pad(this.hex({min: min_blue, max: max_blue}), 2); + } + else { + hexstring = this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2) + this.pad(this.hex({min: min_rgb, max: max_rgb}), 2); + } + } - const waitForDrain = () => new Promise((resolve, reject) => { - assert(callback === null) + return symbol + hexstring; + } - if (socket[kError]) { - reject(socket[kError]) - } else { - callback = resolve - } - }) + options = initOptions(options, { + format: this.pick(['hex', 'shorthex', 'rgb', 'rgba', '0x', 'name']), + grayscale: false, + casing: 'lower', + min: 0, + max: 255, + min_red: undefined, + max_red: undefined, + min_green: undefined, + max_green: undefined, + min_blue: undefined, + max_blue: undefined, + min_alpha: 0, + max_alpha: 1 + }); - if (client[kHTTPConnVersion] === 'h2') { - h2stream - .on('close', onDrain) - .on('drain', onDrain) + var isGrayscale = options.grayscale; + var min_rgb = options.min; + var max_rgb = options.max; + var min_red = options.min_red; + var max_red = options.max_red; + var min_green = options.min_green; + var max_green = options.max_green; + var min_blue = options.min_blue; + var max_blue = options.max_blue; + var min_alpha = options.min_alpha; + var max_alpha = options.max_alpha; + if (options.min_red === undefined) { min_red = min_rgb; } + if (options.max_red === undefined) { max_red = max_rgb; } + if (options.min_green === undefined) { min_green = min_rgb; } + if (options.max_green === undefined) { max_green = max_rgb; } + if (options.min_blue === undefined) { min_blue = min_rgb; } + if (options.max_blue === undefined) { max_blue = max_rgb; } + if (options.min_alpha === undefined) { min_alpha = 0; } + if (options.max_alpha === undefined) { max_alpha = 1; } + if (isGrayscale && min_rgb === 0 && max_rgb === 255 && min_red !== undefined && max_red !== undefined) { + min_rgb = ((min_red + min_green + min_blue) / 3); + max_rgb = ((max_red + max_green + max_blue) / 3); + } + var colorValue; - 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 (options.format === 'hex') { + colorValue = hex.call(this, 2, 6, true); + } + else if (options.format === 'shorthex') { + colorValue = hex.call(this, 1, 3, true); + } + else if (options.format === 'rgb') { + colorValue = rgb.call(this, false); + } + else if (options.format === 'rgba') { + colorValue = rgb.call(this, true); + } + else if (options.format === '0x') { + colorValue = '0x' + hex.call(this, 2, 6); + } + else if(options.format === 'name') { + return this.pick(this.get("colorNames")); + } + else { + throw new RangeError('Invalid format provided. Please provide one of "hex", "shorthex", "rgb", "rgba", "0x" or "name".'); } - const res = h2stream.write(chunk) - request.onBodySent(chunk) - if (!res) { - await waitForDrain() + if (options.casing === 'upper' ) { + colorValue = colorValue.toUpperCase(); } - } - } catch (err) { - h2stream.destroy(err) - } finally { - request.onRequestSent() - h2stream.end() - h2stream - .off('close', onDrain) - .off('drain', onDrain) - } - return - } + return colorValue; + }; + + Chance.prototype.domain = function (options) { + options = initOptions(options); + return this.word() + '.' + (options.tld || this.tld()); + }; + + Chance.prototype.email = function (options) { + options = initOptions(options); + return this.word({length: options.length}) + '@' + (options.domain || this.domain()); + }; + + /** + * #Description: + * =============================================== + * Generate a random Facebook id, aka fbid. + * + * NOTE: At the moment (Sep 2017), Facebook ids are + * "numeric strings" of length 16. + * However, Facebook Graph API documentation states that + * "it is extremely likely to change over time". + * @see https://developers.facebook.com/docs/graph-api/overview/ + * + * #Examples: + * =============================================== + * chance.fbid() => '1000035231661304' + * + * @return [string] facebook id + */ + Chance.prototype.fbid = function () { + return '10000' + this.string({pool: "1234567890", length: 11}); + }; + + Chance.prototype.google_analytics = function () { + var account = this.pad(this.natural({max: 999999}), 6); + var property = this.pad(this.natural({max: 99}), 2); - socket - .on('close', onDrain) - .on('drain', onDrain) + return 'UA-' + account + '-' + property; + }; - 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] - } + Chance.prototype.hashtag = function () { + return '#' + this.word(); + }; - if (!writer.write(chunk)) { - await waitForDrain() - } - } + Chance.prototype.ip = function () { + // Todo: This could return some reserved IPs. See http://vq.io/137dgYy + // this should probably be updated to account for that rare as it may be + return this.natural({min: 1, max: 254}) + '.' + + this.natural({max: 255}) + '.' + + this.natural({max: 255}) + '.' + + this.natural({min: 1, max: 254}); + }; - writer.end() - } catch (err) { - writer.destroy(err) - } finally { - socket - .off('close', onDrain) - .off('drain', onDrain) - } -} + Chance.prototype.ipv6 = function () { + var ip_addr = this.n(this.hash, 8, {length: 4}); -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 + return ip_addr.join(":"); + }; - socket[kWriting] = true - } + Chance.prototype.klout = function () { + return this.natural({min: 1, max: 99}); + }; - write (chunk) { - const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + Chance.prototype.mac = function (options) { + // Todo: This could also be extended to EUI-64 based MACs + // (https://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml#ethernet-numbers-4) + // Todo: This can return some reserved MACs (similar to IP function) + // this should probably be updated to account for that rare as it may be + options = initOptions(options, { delimiter: ':' }); + return this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2) + options.delimiter + + this.pad(this.natural({max: 255}).toString(16),2); + }; - if (socket[kError]) { - throw socket[kError] - } + Chance.prototype.semver = function (options) { + options = initOptions(options, { include_prerelease: true }); - if (socket.destroyed) { - return false - } + var range = this.pickone(["^", "~", "<", ">", "<=", ">=", "="]); + if (options.range) { + range = options.range; + } - const len = Buffer.byteLength(chunk) - if (!len) { - return true - } + var prerelease = ""; + if (options.include_prerelease) { + prerelease = this.weighted(["", "-dev", "-beta", "-alpha"], [50, 10, 5, 1]); + } + return range + this.rpg('3d10').join('.') + prerelease; + }; - // We should defer writing chunks. - if (contentLength !== null && bytesWritten + len > contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } + Chance.prototype.tlds = function () { + return ['com', 'org', 'edu', 'gov', 'co.uk', 'net', 'io', 'ac', 'ad', 'ae', 'af', 'ag', 'ai', 'al', 'am', 'ao', 'aq', 'ar', 'as', 'at', 'au', 'aw', 'ax', 'az', 'ba', 'bb', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bj', 'bm', 'bn', 'bo', 'br', 'bs', 'bt', 'bv', 'bw', 'by', 'bz', 'ca', 'cc', 'cd', 'cf', 'cg', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cr', 'cu', 'cv', 'cw', 'cx', 'cy', 'cz', 'de', 'dj', 'dk', 'dm', 'do', 'dz', 'ec', 'ee', 'eg', 'eh', 'er', 'es', 'et', 'eu', 'fi', 'fj', 'fk', 'fm', 'fo', 'fr', 'ga', 'gb', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gl', 'gm', 'gn', 'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gw', 'gy', 'hk', 'hm', 'hn', 'hr', 'ht', 'hu', 'id', 'ie', 'il', 'im', 'in', 'io', 'iq', 'ir', 'is', 'it', 'je', 'jm', 'jo', 'jp', 'ke', 'kg', 'kh', 'ki', 'km', 'kn', 'kp', 'kr', 'kw', 'ky', 'kz', 'la', 'lb', 'lc', 'li', 'lk', 'lr', 'ls', 'lt', 'lu', 'lv', 'ly', 'ma', 'mc', 'md', 'me', 'mg', 'mh', 'mk', 'ml', 'mm', 'mn', 'mo', 'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'nc', 'ne', 'nf', 'ng', 'ni', 'nl', 'no', 'np', 'nr', 'nu', 'nz', 'om', 'pa', 'pe', 'pf', 'pg', 'ph', 'pk', 'pl', 'pm', 'pn', 'pr', 'ps', 'pt', 'pw', 'py', 'qa', 're', 'ro', 'rs', 'ru', 'rw', 'sa', 'sb', 'sc', 'sd', 'se', 'sg', 'sh', 'si', 'sj', 'sk', 'sl', 'sm', 'sn', 'so', 'sr', 'ss', 'st', 'su', 'sv', 'sx', 'sy', 'sz', 'tc', 'td', 'tf', 'tg', 'th', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tr', 'tt', 'tv', 'tw', 'tz', 'ua', 'ug', 'uk', 'us', 'uy', 'uz', 'va', 'vc', 've', 'vg', 'vi', 'vn', 'vu', 'wf', 'ws', 'ye', 'yt', 'za', 'zm', 'zw']; + }; - process.emitWarning(new RequestContentLengthMismatchError()) - } + Chance.prototype.tld = function () { + return this.pick(this.tlds()); + }; - socket.cork() + Chance.prototype.twitter = function () { + return '@' + this.word(); + }; - if (bytesWritten === 0) { - if (!expectsPayload) { - socket[kReset] = true - } + Chance.prototype.url = function (options) { + options = initOptions(options, { protocol: "http", domain: this.domain(options), domain_prefix: "", path: this.word(), extensions: []}); - if (contentLength === null) { - socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') - } else { - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - } - } + var extension = options.extensions.length > 0 ? "." + this.pick(options.extensions) : ""; + var domain = options.domain_prefix ? options.domain_prefix + "." + options.domain : options.domain; - if (contentLength === null) { - socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') - } + return options.protocol + "://" + domain + "/" + options.path + extension; + }; - this.bytesWritten += len + Chance.prototype.port = function() { + return this.integer({min: 0, max: 65535}); + }; - const ret = socket.write(chunk) + Chance.prototype.locale = function (options) { + options = initOptions(options); + if (options.region){ + return this.pick(this.get("locale_regions")); + } else { + return this.pick(this.get("locale_languages")); + } + }; - socket.uncork() + Chance.prototype.locales = function (options) { + options = initOptions(options); + if (options.region){ + return this.get("locale_regions"); + } else { + return this.get("locale_languages"); + } + }; - request.onBodySent(chunk) + Chance.prototype.loremPicsum = function (options) { + options = initOptions(options, { width: 500, height: 500, greyscale: false, blurred: false }); - 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() - } - } - } + var greyscale = options.greyscale ? 'g/' : ''; + var query = options.blurred ? '/?blur' : '/?random'; - return ret - } + return 'https://picsum.photos/' + greyscale + options.width + '/' + options.height + query; + } - end () { - const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this - request.onRequestSent() + // -- End Web -- - socket[kWriting] = false + // -- Location -- - if (socket[kError]) { - throw socket[kError] - } + Chance.prototype.address = function (options) { + options = initOptions(options); + return this.natural({min: 5, max: 2000}) + ' ' + this.street(options); + }; - if (socket.destroyed) { - return - } + Chance.prototype.altitude = function (options) { + options = initOptions(options, {fixed: 5, min: 0, max: 8848}); + return this.floating({ + min: options.min, + max: options.max, + fixed: options.fixed + }); + }; - 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. + Chance.prototype.areacode = function (options) { + options = initOptions(options, {parens : true}); + // Don't want area codes to start with 1, or have a 9 as the second digit + var areacode = options.exampleNumber ? + "555" : + this.natural({min: 2, max: 9}).toString() + + this.natural({min: 0, max: 8}).toString() + + this.natural({min: 0, max: 9}).toString(); - 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') - } + return options.parens ? '(' + areacode + ')' : areacode; + }; - if (contentLength !== null && bytesWritten !== contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } else { - process.emitWarning(new RequestContentLengthMismatchError()) - } - } + Chance.prototype.city = function () { + return this.capitalize(this.word({syllables: 3})); + }; - if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { - // istanbul ignore else: only for jest - if (socket[kParser].timeout.refresh) { - socket[kParser].timeout.refresh() - } - } + Chance.prototype.coordinates = function (options) { + return this.latitude(options) + ', ' + this.longitude(options); + }; - resume(client) - } + Chance.prototype.countries = function () { + return this.get("countries"); + }; - destroy (err) { - const { socket, client } = this + Chance.prototype.country = function (options) { + options = initOptions(options); + var country = this.pick(this.countries()); + return options.raw ? country : options.full ? country.name : country.abbreviation; + }; - socket[kWriting] = false + Chance.prototype.depth = function (options) { + options = initOptions(options, {fixed: 5, min: -10994, max: 0}); + return this.floating({ + min: options.min, + max: options.max, + fixed: options.fixed + }); + }; - if (err) { - assert(client[kRunning] <= 1, 'pipeline should only contain this request') - util.destroy(socket, err) - } - } -} + Chance.prototype.geohash = function (options) { + options = initOptions(options, { length: 7 }); + return this.string({ length: options.length, pool: '0123456789bcdefghjkmnpqrstuvwxyz' }); + }; -function errorRequest (client, request, err) { - try { - request.onError(err) - assert(request.aborted) - } catch (err) { - client.emit('error', err) - } -} + Chance.prototype.geojson = function (options) { + return this.latitude(options) + ', ' + this.longitude(options) + ', ' + this.altitude(options); + }; -module.exports = Client + Chance.prototype.latitude = function (options) { + // Constants - Formats + var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; + options = initOptions( +options, + options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? + {min: 0, max: 89, fixed: 4} : + {fixed: 5, min: -90, max: 90, format: DD} +); -/***/ }), + var format = options.format.toLowerCase(); -/***/ 56436: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (format === DDM || format === DMS) { + testRange(options.min < 0 || options.min > 89, "Chance: Min specified is out of range. Should be between 0 - 89"); + testRange(options.max < 0 || options.max > 89, "Chance: Max specified is out of range. Should be between 0 - 89"); + testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); + } -"use strict"; + switch (format) { + case DDM: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.floating({min: 0, max: 59, fixed: options.fixed}); + } + case DMS: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.integer({min: 0, max: 59}) + '’' + + this.floating({min: 0, max: 59, fixed: options.fixed}) + 'ā€'; + } + case DD: + default: { + return this.floating({min: options.min, max: options.max, fixed: options.fixed}); + } + } + }; + Chance.prototype.longitude = function (options) { + // Constants - Formats + var [DDM, DMS, DD] = ['ddm', 'dms', 'dd']; -/* istanbul ignore file: only for Node 12 */ + options = initOptions( +options, + options && options.format && [DDM, DMS].includes(options.format.toLowerCase()) ? + {min: 0, max: 179, fixed: 4} : + {fixed: 5, min: -180, max: 180, format: DD} +); -const { kConnected, kSize } = __nccwpck_require__(72785) + var format = options.format.toLowerCase(); -class CompatWeakRef { - constructor (value) { - this.value = value - } + if (format === DDM || format === DMS) { + testRange(options.min < 0 || options.min > 179, "Chance: Min specified is out of range. Should be between 0 - 179"); + testRange(options.max < 0 || options.max > 179, "Chance: Max specified is out of range. Should be between 0 - 179"); + testRange(options.fixed > 4, 'Chance: Fixed specified should be below or equal to 4'); + } - deref () { - return this.value[kConnected] === 0 && this.value[kSize] === 0 - ? undefined - : this.value - } -} + switch (format) { + case DDM: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.floating({min: 0, max: 59.9999, fixed: options.fixed}) + } + case DMS: { + return this.integer({min: options.min, max: options.max}) + '°' + + this.integer({min: 0, max: 59}) + '’' + + this.floating({min: 0, max: 59.9999, fixed: options.fixed}) + 'ā€'; + } + case DD: + default: { + return this.floating({min: options.min, max: options.max, fixed: options.fixed}); + } + } + }; -class CompatFinalizer { - constructor (finalizer) { - this.finalizer = finalizer - } + Chance.prototype.phone = function (options) { + var self = this, + numPick, + ukNum = function (parts) { + var section = []; + //fills the section part of the phone number with random numbers. + parts.sections.forEach(function(n) { + section.push(self.string({ pool: '0123456789', length: n})); + }); + return parts.area + section.join(' '); + }; + options = initOptions(options, { + formatted: true, + country: 'us', + mobile: false, + exampleNumber: false, + }); + if (!options.formatted) { + options.parens = false; + } + var phone; + switch (options.country) { + case 'fr': + if (!options.mobile) { + numPick = this.pick([ + // Valid zone and dĆ©partement codes. + '01' + this.pick(['30', '34', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '53', '55', '56', '58', '60', '64', '69', '70', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83']) + self.string({ pool: '0123456789', length: 6}), + '02' + this.pick(['14', '18', '22', '23', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '40', '41', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '56', '57', '61', '62', '69', '72', '76', '77', '78', '85', '90', '96', '97', '98', '99']) + self.string({ pool: '0123456789', length: 6}), + '03' + this.pick(['10', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '39', '44', '45', '51', '52', '54', '55', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90']) + self.string({ pool: '0123456789', length: 6}), + '04' + this.pick(['11', '13', '15', '20', '22', '26', '27', '30', '32', '34', '37', '42', '43', '44', '50', '56', '57', '63', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '88', '89', '90', '91', '92', '93', '94', '95', '97', '98']) + self.string({ pool: '0123456789', length: 6}), + '05' + this.pick(['08', '16', '17', '19', '24', '31', '32', '33', '34', '35', '40', '45', '46', '47', '49', '53', '55', '56', '57', '58', '59', '61', '62', '63', '64', '65', '67', '79', '81', '82', '86', '87', '90', '94']) + self.string({ pool: '0123456789', length: 6}), + '09' + self.string({ pool: '0123456789', length: 8}), + ]); + phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; + } else { + numPick = this.pick(['06', '07']) + self.string({ pool: '0123456789', length: 8}); + phone = options.formatted ? numPick.match(/../g).join(' ') : numPick; + } + break; + case 'uk': + if (!options.mobile) { + numPick = this.pick([ + //valid area codes of major cities/counties followed by random numbers in required format. - register (dispatcher, key) { - if (dispatcher.on) { - dispatcher.on('disconnect', () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key) + { area: '01' + this.character({ pool: '234569' }) + '1 ', sections: [3,4] }, + { area: '020 ' + this.character({ pool: '378' }), sections: [3,4] }, + { area: '023 ' + this.character({ pool: '89' }), sections: [3,4] }, + { area: '024 7', sections: [3,4] }, + { area: '028 ' + this.pick(['25','28','37','71','82','90','92','95']), sections: [2,4] }, + { area: '012' + this.pick(['04','08','54','76','97','98']) + ' ', sections: [6] }, + { area: '013' + this.pick(['63','64','84','86']) + ' ', sections: [6] }, + { area: '014' + this.pick(['04','20','60','61','80','88']) + ' ', sections: [6] }, + { area: '015' + this.pick(['24','27','62','66']) + ' ', sections: [6] }, + { area: '016' + this.pick(['06','29','35','47','59','95']) + ' ', sections: [6] }, + { area: '017' + this.pick(['26','44','50','68']) + ' ', sections: [6] }, + { area: '018' + this.pick(['27','37','84','97']) + ' ', sections: [6] }, + { area: '019' + this.pick(['00','05','35','46','49','63','95']) + ' ', sections: [6] } + ]); + phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', '', 'g'); + } else { + numPick = this.pick([ + { area: '07' + this.pick(['4','5','7','8','9']), sections: [2,6] }, + { area: '07624 ', sections: [6] } + ]); + phone = options.formatted ? ukNum(numPick) : ukNum(numPick).replace(' ', ''); + } + break; + case 'za': + if (!options.mobile) { + numPick = this.pick([ + '01' + this.pick(['0', '1', '2', '3', '4', '5', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), + '02' + this.pick(['1', '2', '3', '4', '7', '8']) + self.string({ pool: '0123456789', length: 7}), + '03' + this.pick(['1', '2', '3', '5', '6', '9']) + self.string({ pool: '0123456789', length: 7}), + '04' + this.pick(['1', '2', '3', '4', '5','6','7', '8','9']) + self.string({ pool: '0123456789', length: 7}), + '05' + this.pick(['1', '3', '4', '6', '7', '8']) + self.string({ pool: '0123456789', length: 7}), + ]); + phone = options.formatted || numPick; + } else { + numPick = this.pick([ + '060' + this.pick(['3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), + '061' + this.pick(['0','1','2','3','4','5','8']) + self.string({ pool: '0123456789', length: 6}), + '06' + self.string({ pool: '0123456789', length: 7}), + '071' + this.pick(['0','1','2','3','4','5','6','7','8','9']) + self.string({ pool: '0123456789', length: 6}), + '07' + this.pick(['2','3','4','6','7','8','9']) + self.string({ pool: '0123456789', length: 7}), + '08' + this.pick(['0','1','2','3','4','5']) + self.string({ pool: '0123456789', length: 7}), + ]); + phone = options.formatted || numPick; + } + break; + case 'us': + var areacode = this.areacode(options).toString(); + var exchange = this.natural({ min: 2, max: 9 }).toString() + + this.natural({ min: 0, max: 9 }).toString() + + this.natural({ min: 0, max: 9 }).toString(); + var subscriber = this.natural({ min: 1000, max: 9999 }).toString(); // this could be random [0-9]{4} + phone = options.formatted ? areacode + ' ' + exchange + '-' + subscriber : areacode + exchange + subscriber; + break; + case 'br': + var areaCode = this.pick(["11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "24", "27", "28", "31", "32", "33", "34", "35", "37", "38", "41", "42", "43", "44", "45", "46", "47", "48", "49", "51", "53", "54", "55", "61", "62", "63", "64", "65", "66", "67", "68", "69", "71", "73", "74", "75", "77", "79", "81", "82", "83", "84", "85", "86", "87", "88", "89", "91", "92", "93", "94", "95", "96", "97", "98", "99"]); + var prefix; + if (options.mobile) { + // Brasilian official reference (mobile): http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=330 + prefix = '9' + self.string({ pool: '0123456789', length: 4}); + } else { + // Brasilian official reference: http://www.anatel.gov.br/setorregulado/plano-de-numeracao-brasileiro?id=331 + prefix = this.natural({ min: 2000, max: 5999 }).toString(); + } + var mcdu = self.string({ pool: '0123456789', length: 4}); + phone = options.formatted ? '(' + areaCode + ') ' + prefix + '-' + mcdu : areaCode + prefix + mcdu; + break; } - }) - } - } -} + return phone; + }; -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 - } -} + Chance.prototype.postal = function () { + // Postal District + var pd = this.character({pool: "XVTSRPNKLMHJGECBA"}); + // Forward Sortation Area (FSA) + var fsa = pd + this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}); + // Local Delivery Unut (LDU) + var ldu = this.natural({max: 9}) + this.character({alpha: true, casing: "upper"}) + this.natural({max: 9}); + + return fsa + " " + ldu; + }; + + Chance.prototype.postcode = function () { + // Area + var area = this.pick(this.get("postcodeAreas")).code; + // District + var district = this.natural({max: 9}); + // Sub-District + var subDistrict = this.bool() ? this.character({alpha: true, casing: "upper"}) : ""; + // Outward Code + var outward = area + district + subDistrict; + // Sector + var sector = this.natural({max: 9}); + // Unit + var unit = this.character({alpha: true, casing: "upper"}) + this.character({alpha: true, casing: "upper"}); + // Inward Code + var inward = sector + unit; + return outward + " " + inward; + }; -/***/ }), + Chance.prototype.counties = function (options) { + options = initOptions(options, { country: 'uk' }); + return this.get("counties")[options.country.toLowerCase()]; + }; -/***/ 20663: -/***/ ((module) => { + Chance.prototype.county = function (options) { + return this.pick(this.counties(options)).name; + }; -"use strict"; + Chance.prototype.provinces = function (options) { + options = initOptions(options, { country: 'ca' }); + return this.get("provinces")[options.country.toLowerCase()]; + }; + Chance.prototype.province = function (options) { + return (options && options.full) ? + this.pick(this.provinces(options)).name : + this.pick(this.provinces(options)).abbreviation; + }; -// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size -const maxAttributeValueSize = 1024 + Chance.prototype.state = function (options) { + return (options && options.full) ? + this.pick(this.states(options)).name : + this.pick(this.states(options)).abbreviation; + }; -// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size -const maxNameValuePairSize = 4096 + Chance.prototype.states = function (options) { + options = initOptions(options, { country: 'us', us_states_and_dc: true } ); -module.exports = { - maxAttributeValueSize, - maxNameValuePairSize -} + var states; + switch (options.country.toLowerCase()) { + case 'us': + var us_states_and_dc = this.get("us_states_and_dc"), + territories = this.get("territories"), + armed_forces = this.get("armed_forces"); -/***/ }), + states = []; -/***/ 41724: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (options.us_states_and_dc) { + states = states.concat(us_states_and_dc); + } + if (options.territories) { + states = states.concat(territories); + } + if (options.armed_forces) { + states = states.concat(armed_forces); + } + break; + case 'it': + case 'mx': + states = this.get("country_regions")[options.country.toLowerCase()]; + break; + case 'uk': + states = this.get("counties")[options.country.toLowerCase()]; + break; + } -"use strict"; + return states; + }; + Chance.prototype.street = function (options) { + options = initOptions(options, { country: 'us', syllables: 2 }); + var street; -const { parseSetCookie } = __nccwpck_require__(24408) -const { stringify } = __nccwpck_require__(43121) -const { webidl } = __nccwpck_require__(21744) -const { Headers } = __nccwpck_require__(10554) + switch (options.country.toLowerCase()) { + case 'us': + street = this.word({ syllables: options.syllables }); + street = this.capitalize(street); + street += ' '; + street += options.short_suffix ? + this.street_suffix(options).abbreviation : + this.street_suffix(options).name; + break; + case 'it': + street = this.word({ syllables: options.syllables }); + street = this.capitalize(street); + street = (options.short_suffix ? + this.street_suffix(options).abbreviation : + this.street_suffix(options).name) + " " + street; + break; + } + return street; + }; -/** - * @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 - */ + Chance.prototype.street_suffix = function (options) { + options = initOptions(options, { country: 'us' }); + return this.pick(this.street_suffixes(options)); + }; -/** - * @param {Headers} headers - * @returns {Record} - */ -function getCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) + Chance.prototype.street_suffixes = function (options) { + options = initOptions(options, { country: 'us' }); + // These are the most common suffixes. + return this.get("street_suffixes")[options.country.toLowerCase()]; + }; - webidl.brandCheck(headers, Headers, { strict: false }) + // Note: only returning US zip codes, internationalization will be a whole + // other beast to tackle at some point. + Chance.prototype.zip = function (options) { + var zip = this.n(this.natural, 5, {max: 9}); - const cookie = headers.get('cookie') - const out = {} + if (options && options.plusfour === true) { + zip.push('-'); + zip = zip.concat(this.n(this.natural, 4, {max: 9})); + } - if (!cookie) { - return out - } + return zip.join(""); + }; - for (const piece of cookie.split(';')) { - const [name, ...value] = piece.split('=') + // -- End Location -- - out[name.trim()] = value.join('=') - } + // -- Time - return out -} + Chance.prototype.ampm = function () { + return this.bool() ? 'am' : 'pm'; + }; -/** - * @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' }) + Chance.prototype.date = function (options) { + var date_string, date; - webidl.brandCheck(headers, Headers, { strict: false }) + // If interval is specified we ignore preset + if(options && (options.min || options.max)) { + options = initOptions(options, { + american: true, + string: false + }); + var min = typeof options.min !== "undefined" ? options.min.getTime() : 1; + // 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. http://es5.github.io/#x15.9.1.1 + var max = typeof options.max !== "undefined" ? options.max.getTime() : 8640000000000000; - name = webidl.converters.DOMString(name) - attributes = webidl.converters.DeleteCookieAttributes(attributes) + date = new Date(this.integer({min: min, max: max})); + } else { + var m = this.month({raw: true}); + var daysInMonth = m.days; - // Matches behavior of - // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 - setCookie(headers, { - name, - value: '', - expires: new Date(0), - ...attributes - }) -} + if(options && options.month) { + // Mod 12 to allow months outside range of 0-11 (not encouraged, but also not prevented). + daysInMonth = this.get('months')[((options.month % 12) + 12) % 12].days; + } -/** - * @param {Headers} headers - * @returns {Cookie[]} - */ -function getSetCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + options = initOptions(options, { + year: parseInt(this.year(), 10), + // Necessary to subtract 1 because Date() 0-indexes month but not day or year + // for some reason. + month: m.numeric - 1, + day: this.natural({min: 1, max: daysInMonth}), + hour: this.hour({twentyfour: true}), + minute: this.minute(), + second: this.second(), + millisecond: this.millisecond(), + american: true, + string: false + }); - webidl.brandCheck(headers, Headers, { strict: false }) + date = new Date(options.year, options.month, options.day, options.hour, options.minute, options.second, options.millisecond); + } - const cookies = headers.getSetCookie() + if (options.american) { + // Adding 1 to the month is necessary because Date() 0-indexes + // months but not day for some odd reason. + date_string = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear(); + } else { + date_string = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear(); + } - if (!cookies) { - return [] - } + return options.string ? date_string : date; + }; - return cookies.map((pair) => parseSetCookie(pair)) -} + Chance.prototype.hammertime = function (options) { + return this.date(options).getTime(); + }; -/** - * @param {Headers} headers - * @param {Cookie} cookie - * @returns {void} - */ -function setCookie (headers, cookie) { - webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) + Chance.prototype.hour = function (options) { + options = initOptions(options, { + min: options && options.twentyfour ? 0 : 1, + max: options && options.twentyfour ? 23 : 12 + }); - webidl.brandCheck(headers, Headers, { strict: false }) + testRange(options.min < 0, "Chance: Min cannot be less than 0."); + testRange(options.twentyfour && options.max > 23, "Chance: Max cannot be greater than 23 for twentyfour option."); + testRange(!options.twentyfour && options.max > 12, "Chance: Max cannot be greater than 12."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); - cookie = webidl.converters.Cookie(cookie) + return this.natural({min: options.min, max: options.max}); + }; - const str = stringify(cookie) + Chance.prototype.millisecond = function () { + return this.natural({max: 999}); + }; - if (str) { - headers.append('Set-Cookie', stringify(cookie)) - } -} + Chance.prototype.minute = Chance.prototype.second = function (options) { + options = initOptions(options, {min: 0, max: 59}); -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 - } -]) + testRange(options.min < 0, "Chance: Min cannot be less than 0."); + testRange(options.max > 59, "Chance: Max cannot be greater than 59."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); -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 this.natural({min: options.min, max: options.max}); + }; - 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: [] - } -]) + Chance.prototype.month = function (options) { + options = initOptions(options, {min: 1, max: 12}); -module.exports = { - getCookies, - deleteCookie, - getSetCookies, - setCookie -} + testRange(options.min < 1, "Chance: Min cannot be less than 1."); + testRange(options.max > 12, "Chance: Max cannot be greater than 12."); + testRange(options.min > options.max, "Chance: Min cannot be greater than Max."); + var month = this.pick(this.months().slice(options.min - 1, options.max)); + return options.raw ? month : month.name; + }; -/***/ }), + Chance.prototype.months = function () { + return this.get("months"); + }; -/***/ 24408: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Chance.prototype.second = function () { + return this.natural({max: 59}); + }; -"use strict"; + Chance.prototype.timestamp = function () { + return this.natural({min: 1, max: parseInt(new Date().getTime() / 1000, 10)}); + }; + Chance.prototype.weekday = function (options) { + options = initOptions(options, {weekday_only: false}); + var weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; + if (!options.weekday_only) { + weekdays.push("Saturday"); + weekdays.push("Sunday"); + } + return this.pickone(weekdays); + }; -const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(20663) -const { isCTLExcludingHtab } = __nccwpck_require__(43121) -const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) -const assert = __nccwpck_require__(39491) + Chance.prototype.year = function (options) { + // Default to current year as min if none specified + options = initOptions(options, {min: new Date().getFullYear()}); -/** - * @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 - } + // Default to one century after current year as max if none specified + options.max = (typeof options.max !== "undefined") ? options.max : options.min + 100; - let nameValuePair = '' - let unparsedAttributes = '' - let name = '' - let value = '' + return this.natural(options).toString(); + }; - // 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 } + // -- End Time - nameValuePair = collectASequenceOfCodePointsFast(';', header, position) - unparsedAttributes = header.slice(position.position) - } else { - // Otherwise: + // -- Finance -- - // 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 - } + Chance.prototype.cc = function (options) { + options = initOptions(options); - // 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) - } + var type, number, to_generate; - // 4. Remove any leading or trailing WSP characters from the name - // string and the value string. - name = name.trim() - value = value.trim() + type = (options.type) ? + this.cc_type({ name: options.type, raw: true }) : + this.cc_type({ raw: true }); - // 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 - } + number = type.prefix.split(""); + to_generate = type.length - type.prefix.length - 1; - // 6. The cookie-name is the name string, and the cookie-value is the - // value string. - return { - name, value, ...parseUnparsedAttributes(unparsedAttributes) - } -} + // Generates n - 1 digits + number = number.concat(this.n(this.integer, to_generate, {min: 0, max: 9})); -/** - * 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 - } + // Generates the last digit according to Luhn algorithm + number.push(this.luhn_calculate(number.join(""))); - // 2. Discard the first character of the unparsed-attributes (which - // will be a %x3B (";") character). - assert(unparsedAttributes[0] === ';') - unparsedAttributes = unparsedAttributes.slice(1) + return number.join(""); + }; - let cookieAv = '' + Chance.prototype.cc_types = function () { + // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 + return this.get("cc_types"); + }; - // 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: + Chance.prototype.cc_type = function (options) { + options = initOptions(options); + var types = this.cc_types(), + type = null; + + if (options.name) { + for (var i = 0; i < types.length; i++) { + // Accept either name or short_name to specify card type + if (types[i].name === options.name || types[i].short_name === options.name) { + type = types[i]; + break; + } + } + if (type === null) { + throw new RangeError("Chance: Credit card type '" + options.name + "' is not supported"); + } + } else { + type = this.pick(types); + } - // 1. Consume the remainder of the unparsed-attributes. - cookieAv = unparsedAttributes - unparsedAttributes = '' - } + return options.raw ? type : type.name; + }; - // Let the cookie-av string be the characters consumed in this step. + // return all world currency by ISO 4217 + Chance.prototype.currency_types = function () { + return this.get("currency_types"); + }; - let attributeName = '' - let attributeValue = '' + // return random world currency by ISO 4217 + Chance.prototype.currency = function () { + return this.pick(this.currency_types()); + }; - // 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 } + // return all timezones available + Chance.prototype.timezones = function () { + return this.get("timezones"); + }; - attributeName = collectASequenceOfCodePointsFast( - '=', - cookieAv, - position - ) - attributeValue = cookieAv.slice(position.position + 1) - } else { - // Otherwise: + // return random timezone + Chance.prototype.timezone = function () { + return this.pick(this.timezones()); + }; - // 1. The attribute-name string consists of the entire cookie-av - // string, and the attribute-value string is empty. - attributeName = cookieAv - } + //Return random correct currency exchange pair (e.g. EUR/USD) or array of currency code + Chance.prototype.currency_pair = function (returnAsString) { + var currencies = this.unique(this.currency, 2, { + comparator: function(arr, val) { - // 5. Remove any leading or trailing WSP characters from the attribute- - // name string and the attribute-value string. - attributeName = attributeName.trim() - attributeValue = attributeValue.trim() + return arr.reduce(function(acc, item) { + // If a match has been found, short circuit check and just return + return acc || (item.code === val.code); + }, false); + } + }); - // 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) - } + if (returnAsString) { + return currencies[0].code + '/' + currencies[1].code; + } else { + return currencies; + } + }; - // 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() + Chance.prototype.dollar = function (options) { + // By default, a somewhat more sane max for dollar than all available numbers + options = initOptions(options, {max : 10000, min : 0}); - // 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) + var dollar = this.floating({min: options.min, max: options.max, fixed: 2}).toString(), + cents = dollar.split('.')[1]; - // 2. If the attribute-value failed to parse as a cookie date, ignore - // the cookie-av. + if (cents === undefined) { + dollar += '.00'; + } else if (cents.length < 2) { + dollar = dollar + '0'; + } - 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. + if (dollar < 0) { + return '-$' + dollar.replace('-', ''); + } else { + return '$' + dollar; + } + }; - // 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) + Chance.prototype.euro = function (options) { + return Number(this.dollar(options).replace("$", "")).toLocaleString() + "€"; + }; - if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } + Chance.prototype.exp = function (options) { + options = initOptions(options); + var exp = {}; - // 2. If the remainder of attribute-value contains a non-DIGIT - // character, ignore the cookie-av. - if (!/^\d+$/.test(attributeValue)) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } + exp.year = this.exp_year(); - // 3. Let delta-seconds be the attribute-value converted to an integer. - const deltaSeconds = Number(attributeValue) + // If the year is this year, need to ensure month is greater than the + // current month or this expiration will not be valid + if (exp.year === (new Date().getFullYear()).toString()) { + exp.month = this.exp_month({future: true}); + } else { + exp.month = this.exp_month(); + } - // 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). + return options.raw ? exp : exp.month + '/' + exp.year; + }; - // 5. Set delta-seconds to the smaller of its present value and cookie- - // age-limit. - // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + Chance.prototype.exp_month = function (options) { + options = initOptions(options); + var month, month_int, + // Date object months are 0 indexed + curMonth = new Date().getMonth() + 1; - // 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 + if (options.future && (curMonth !== 12)) { + do { + month = this.month({raw: true}).numeric; + month_int = parseInt(month, 10); + } while (month_int <= curMonth); + } else { + month = this.month({raw: true}).numeric; + } - // 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. + return month; + }; - // 1. Let cookie-domain be the attribute-value. - let cookieDomain = attributeValue + Chance.prototype.exp_year = function () { + var curMonth = new Date().getMonth() + 1, + curYear = new Date().getFullYear(); - // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be - // cookie-domain without its leading %x2E ("."). - if (cookieDomain[0] === '.') { - cookieDomain = cookieDomain.slice(1) - } + return this.year({min: ((curMonth === 12) ? (curYear + 1) : curYear), max: (curYear + 10)}); + }; - // 3. Convert the cookie-domain to lower case. - cookieDomain = cookieDomain.toLowerCase() + Chance.prototype.vat = function (options) { + options = initOptions(options, { country: 'it' }); + switch (options.country.toLowerCase()) { + case 'it': + return this.it_vat(); + } + }; - // 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. + /** + * Generate a string matching IBAN pattern (https://en.wikipedia.org/wiki/International_Bank_Account_Number). + * No country-specific formats support (yet) + */ + Chance.prototype.iban = function () { + var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + var alphanum = alpha + '0123456789'; + var iban = + this.string({ length: 2, pool: alpha }) + + this.pad(this.integer({ min: 0, max: 99 }), 2) + + this.string({ length: 4, pool: alphanum }) + + this.pad(this.natural(), this.natural({ min: 6, max: 26 })); + return iban; + }; - // 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: + // -- End Finance - // 1. Let cookie-path be the attribute-value. - cookiePath = attributeValue - } + // -- Regional - // 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. + Chance.prototype.it_vat = function () { + var it_vat = this.natural({min: 1, max: 1800000}); - 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. + it_vat = this.pad(it_vat, 7) + this.pad(this.pick(this.provinces({ country: 'it' })).code, 3); + return it_vat + this.luhn_calculate(it_vat); + }; - 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: + /* + * this generator is written following the official algorithm + * all data can be passed explicitely or randomized by calling chance.cf() without options + * the code does not check that the input data is valid (it goes beyond the scope of the generator) + * + * @param [Object] options = { first: first name, + * last: last name, + * gender: female|male, + birthday: JavaScript date object, + city: string(4), 1 letter + 3 numbers + } + * @return [string] codice fiscale + * + */ + Chance.prototype.cf = function (options) { + options = options || {}; + var gender = !!options.gender ? options.gender : this.gender(), + first = !!options.first ? options.first : this.first( { gender: gender, nationality: 'it'} ), + last = !!options.last ? options.last : this.last( { nationality: 'it'} ), + birthday = !!options.birthday ? options.birthday : this.birthday(), + city = !!options.city ? options.city : this.pickone(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L', 'M', 'Z']) + this.pad(this.natural({max:999}), 3), + cf = [], + name_generator = function(name, isLast) { + var temp, + return_value = []; - // 1. Let enforcement be "Default". - let enforcement = 'Default' + if (name.length < 3) { + return_value = name.split("").concat("XXX".split("")).splice(0,3); + } + else { + temp = name.toUpperCase().split('').map(function(c){ + return ("BCDFGHJKLMNPRSTVWZ".indexOf(c) !== -1) ? c : undefined; + }).join(''); + if (temp.length > 3) { + if (isLast) { + temp = temp.substr(0,3); + } else { + temp = temp[0] + temp.substr(2,2); + } + } + if (temp.length < 3) { + return_value = temp; + temp = name.toUpperCase().split('').map(function(c){ + return ("AEIOU".indexOf(c) !== -1) ? c : undefined; + }).join('').substr(0, 3 - return_value.length); + } + return_value = return_value + temp; + } - 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' - } + return return_value; + }, + date_generator = function(birthday, gender, that) { + var lettermonths = ['A', 'B', 'C', 'D', 'E', 'H', 'L', 'M', 'P', 'R', 'S', 'T']; - // 3. If cookie-av's attribute-value is a case-insensitive match for - // "Strict", set enforcement to "Strict". - if (attributeValueLowercase.includes('strict')) { - enforcement = 'Strict' - } + return birthday.getFullYear().toString().substr(2) + + lettermonths[birthday.getMonth()] + + that.pad(birthday.getDate() + ((gender.toLowerCase() === "female") ? 40 : 0), 2); + }, + checkdigit_generator = function(cf) { + var range1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", + range2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ", + evens = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", + odds = "BAKPLCQDREVOSFTGUHMINJWZYX", + digit = 0; - // 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 ??= [] + for(var i = 0; i < 15; i++) { + if (i % 2 !== 0) { + digit += evens.indexOf(range2[range1.indexOf(cf[i])]); + } + else { + digit += odds.indexOf(range2[range1.indexOf(cf[i])]); + } + } + return evens[digit % 26]; + }; - cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) - } + cf = cf.concat(name_generator(last, true), name_generator(first), date_generator(birthday, gender, this), city.toUpperCase().split("")).join(""); + cf += checkdigit_generator(cf.toUpperCase(), this); - // 8. Return to Step 1 of this algorithm. - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) -} + return cf.toUpperCase(); + }; -module.exports = { - parseSetCookie, - parseUnparsedAttributes -} + Chance.prototype.pl_pesel = function () { + var number = this.natural({min: 1, max: 9999999999}); + var arr = this.pad(number, 10).split(''); + for (var i = 0; i < arr.length; i++) { + arr[i] = parseInt(arr[i]); + } + var controlNumber = (1 * arr[0] + 3 * arr[1] + 7 * arr[2] + 9 * arr[3] + 1 * arr[4] + 3 * arr[5] + 7 * arr[6] + 9 * arr[7] + 1 * arr[8] + 3 * arr[9]) % 10; + if(controlNumber !== 0) { + controlNumber = 10 - controlNumber; + } -/***/ }), + return arr.join('') + controlNumber; + }; -/***/ 43121: -/***/ ((module) => { + Chance.prototype.pl_nip = function () { + var number = this.natural({min: 1, max: 999999999}); + var arr = this.pad(number, 9).split(''); + for (var i = 0; i < arr.length; i++) { + arr[i] = parseInt(arr[i]); + } -"use strict"; + var controlNumber = (6 * arr[0] + 5 * arr[1] + 7 * arr[2] + 2 * arr[3] + 3 * arr[4] + 4 * arr[5] + 5 * arr[6] + 6 * arr[7] + 7 * arr[8]) % 11; + if(controlNumber === 10) { + return this.pl_nip(); + } + return arr.join('') + controlNumber; + }; -/** - * @param {string} value - * @returns {boolean} - */ -function isCTLExcludingHtab (value) { - if (value.length === 0) { - return false - } + Chance.prototype.pl_regon = function () { + var number = this.natural({min: 1, max: 99999999}); + var arr = this.pad(number, 8).split(''); + for (var i = 0; i < arr.length; i++) { + arr[i] = parseInt(arr[i]); + } - for (const char of value) { - const code = char.charCodeAt(0) + var controlNumber = (8 * arr[0] + 9 * arr[1] + 2 * arr[2] + 3 * arr[3] + 4 * arr[4] + 5 * arr[5] + 6 * arr[6] + 7 * arr[7]) % 11; + if(controlNumber === 10) { + controlNumber = 0; + } - if ( - (code >= 0x00 || code <= 0x08) || - (code >= 0x0A || code <= 0x1F) || - code === 0x7F - ) { - return false - } - } -} + return arr.join('') + controlNumber; + }; -/** - CHAR = - token = 1* - separators = "(" | ")" | "<" | ">" | "@" - | "," | ";" | ":" | "\" | <"> - | "/" | "[" | "]" | "?" | "=" - | "{" | "}" | SP | HT - * @param {string} name - */ -function validateCookieName (name) { - for (const char of name) { - const code = char.charCodeAt(0) + // -- End Regional - 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') - } - } -} + // -- Music -- -/** - 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) + // Genre choices: + // Rock,Pop,Hip-Hop,Jazz,Classical,Electronic,Country,R&B,Reggae, + // Blues,Metal,Folk,Alternative,Punk,Disco,Funk,Techno, + // Indie,Gospel,Dance,Children's,World - 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') - } - } -} + Chance.prototype.music_genre = function (genre = 'general') { + if (!(genre.toLowerCase() in data.music_genres)) { + throw new Error(`Unsupported genre: ${genre}`); + } -/** - * path-value = - * @param {string} path - */ -function validateCookiePath (path) { - for (const char of path) { - const code = char.charCodeAt(0) + const genres = data.music_genres[genre.toLowerCase()]; + const randomIndex = this.integer({ min: 0, max: genres.length - 1 }); - if (code < 0x21 || char === ';') { - throw new Error('Invalid cookie path') + return genres[randomIndex]; + }; + + Chance.prototype.note = function(options) { + // choices for 'notes' option: + // flatKey - chromatic scale with flat notes (default) + // sharpKey - chromatic scale with sharp notes + // flats - just flat notes + // sharps - just sharp notes + // naturals - just natural notes + // all - naturals, sharps and flats + options = initOptions(options, { notes : 'flatKey'}); + var scales = { + naturals: ['C', 'D', 'E', 'F', 'G', 'A', 'B'], + flats: ['Dā™­', 'Eā™­', 'Gā™­', 'Aā™­', 'Bā™­'], + sharps: ['C♯', 'D♯', 'F♯', 'G♯', 'A♯'] + }; + scales.all = scales.naturals.concat(scales.flats.concat(scales.sharps)) + scales.flatKey = scales.naturals.concat(scales.flats) + scales.sharpKey = scales.naturals.concat(scales.sharps) + return this.pickone(scales[options.notes]); } - } -} -/** - * 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') - } -} + Chance.prototype.midi_note = function(options) { + var min = 0; + var max = 127; + options = initOptions(options, { min : min, max : max }); + return this.integer({min: options.min, max: options.max}); + } -/** - * @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] + Chance.prototype.chord_quality = function(options) { + options = initOptions(options, { jazz: true }); + var chord_qualities = ['maj', 'min', 'aug', 'dim']; + if (options.jazz){ + chord_qualities = [ + 'maj7', + 'min7', + '7', + 'sus', + 'dim', + 'Ćø' + ]; + } + return this.pickone(chord_qualities); + } - 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 + Chance.prototype.chord = function (options) { + options = initOptions(options); + return this.note(options) + this.chord_quality(options); + } - 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 + Chance.prototype.tempo = function (options) { + var min = 40; + var max = 320; + options = initOptions(options, {min: min, max: max}); + return this.integer({min: options.min, max: options.max}); + } - GMT = %x47.4D.54 ; "GMT", case-sensitive + // -- End Music - time-of-day = hour ":" minute ":" second - ; 00:00:00 - 23:59:60 (leap second) + // -- Miscellaneous -- - hour = 2DIGIT - minute = 2DIGIT - second = 2DIGIT - */ -function toIMFDate (date) { - if (typeof date === 'number') { - date = new Date(date) - } + // Coin - Flip, flip, flipadelphia + Chance.prototype.coin = function() { + return this.bool() ? "heads" : "tails"; + } - const days = [ - 'Sun', 'Mon', 'Tue', 'Wed', - 'Thu', 'Fri', 'Sat' - ] + // Dice - For all the board game geeks out there, myself included ;) + function diceFn (range) { + return function () { + return this.natural(range); + }; + } + Chance.prototype.d4 = diceFn({min: 1, max: 4}); + Chance.prototype.d6 = diceFn({min: 1, max: 6}); + Chance.prototype.d8 = diceFn({min: 1, max: 8}); + Chance.prototype.d10 = diceFn({min: 1, max: 10}); + Chance.prototype.d12 = diceFn({min: 1, max: 12}); + Chance.prototype.d20 = diceFn({min: 1, max: 20}); + Chance.prototype.d30 = diceFn({min: 1, max: 30}); + Chance.prototype.d100 = diceFn({min: 1, max: 100}); - const months = [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' - ] + Chance.prototype.rpg = function (thrown, options) { + options = initOptions(options); + if (!thrown) { + throw new RangeError("Chance: A type of die roll must be included"); + } else { + var bits = thrown.toLowerCase().split("d"), + rolls = []; - 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') + if (bits.length !== 2 || !parseInt(bits[0], 10) || !parseInt(bits[1], 10)) { + throw new Error("Chance: Invalid format provided. Please provide #d# where the first # is the number of dice to roll, the second # is the max of each die"); + } + for (var i = bits[0]; i > 0; i--) { + rolls[i - 1] = this.natural({min: 1, max: bits[1]}); + } + return (typeof options.sum !== 'undefined' && options.sum) ? rolls.reduce(function (p, c) { return p + c; }) : rolls; + } + }; - return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` -} + // Guid + Chance.prototype.guid = function (options) { + options = initOptions(options, { version: 5 }); -/** - 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') - } -} + var guid_pool = "abcdef1234567890", + variant_pool = "ab89", + guid = this.string({ pool: guid_pool, length: 8 }) + '-' + + this.string({ pool: guid_pool, length: 4 }) + '-' + + // The Version + options.version + + this.string({ pool: guid_pool, length: 3 }) + '-' + + // The Variant + this.string({ pool: variant_pool, length: 1 }) + + this.string({ pool: guid_pool, length: 3 }) + '-' + + this.string({ pool: guid_pool, length: 12 }); + return guid; + }; -/** - * @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 - } + // Hash + Chance.prototype.hash = function (options) { + options = initOptions(options, {length : 40, casing: 'lower'}); + var pool = options.casing === 'upper' ? HEX_POOL.toUpperCase() : HEX_POOL; + return this.string({pool: pool, length: options.length}); + }; - validateCookieName(cookie.name) - validateCookieValue(cookie.value) + Chance.prototype.luhn_check = function (num) { + var str = num.toString(); + var checkDigit = +str.substring(str.length - 1); + return checkDigit === this.luhn_calculate(+str.substring(0, str.length - 1)); + }; - const out = [`${cookie.name}=${cookie.value}`] + Chance.prototype.luhn_calculate = function (num) { + var digits = num.toString().split("").reverse(); + var sum = 0; + var digit; - // 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 - } + for (var i = 0, l = digits.length; l > i; ++i) { + digit = +digits[i]; + if (i % 2 === 0) { + digit *= 2; + if (digit > 9) { + digit -= 9; + } + } + sum += digit; + } + return (sum * 9) % 10; + }; - if (cookie.name.startsWith('__Host-')) { - cookie.secure = true - cookie.domain = null - cookie.path = '/' - } + // MD5 Hash + Chance.prototype.md5 = function(options) { + var opts = { str: '', key: null, raw: false }; - if (cookie.secure) { - out.push('Secure') - } + if (!options) { + opts.str = this.string(); + options = {}; + } + else if (typeof options === 'string') { + opts.str = options; + options = {}; + } + else if (typeof options !== 'object') { + return null; + } + else if(options.constructor === 'Array') { + return null; + } - if (cookie.httpOnly) { - out.push('HttpOnly') - } + opts = initOptions(options, opts); - if (typeof cookie.maxAge === 'number') { - validateCookieMaxAge(cookie.maxAge) - out.push(`Max-Age=${cookie.maxAge}`) - } + if(!opts.str){ + throw new Error('A parameter is required to return an md5 hash.'); + } - if (cookie.domain) { - validateCookieDomain(cookie.domain) - out.push(`Domain=${cookie.domain}`) - } + return this.bimd5.md5(opts.str, opts.key, opts.raw); + }; - if (cookie.path) { - validateCookiePath(cookie.path) - out.push(`Path=${cookie.path}`) - } + /** + * #Description: + * ===================================================== + * Generate random file name with extension + * + * The argument provide extension type + * -> raster + * -> vector + * -> 3d + * -> document + * + * If nothing is provided the function return random file name with random + * extension type of any kind + * + * The user can validate the file name length range + * If nothing provided the generated file name is random + * + * #Extension Pool : + * * Currently the supported extensions are + * -> some of the most popular raster image extensions + * -> some of the most popular vector image extensions + * -> some of the most popular 3d image extensions + * -> some of the most popular document extensions + * + * #Examples : + * ===================================================== + * + * Return random file name with random extension. The file extension + * is provided by a predefined collection of extensions. More about the extension + * pool can be found in #Extension Pool section + * + * chance.file() + * => dsfsdhjf.xml + * + * In order to generate a file name with specific length, specify the + * length property and integer value. The extension is going to be random + * + * chance.file({length : 10}) + * => asrtineqos.pdf + * + * In order to generate file with extension from some of the predefined groups + * of the extension pool just specify the extension pool category in fileType property + * + * chance.file({fileType : 'raster'}) + * => dshgssds.psd + * + * You can provide specific extension for your files + * chance.file({extension : 'html'}) + * => djfsd.html + * + * Or you could pass custom collection of extensions by array or by object + * chance.file({extensions : [...]}) + * => dhgsdsd.psd + * + * chance.file({extensions : { key : [...], key : [...]}}) + * => djsfksdjsd.xml + * + * @param [collection] options + * @return [string] + * + */ + Chance.prototype.file = function(options) { - if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { - out.push(`Expires=${toIMFDate(cookie.expires)}`) - } + var fileOptions = options || {}; + var poolCollectionKey = "fileExtension"; + var typeRange = Object.keys(this.get("fileExtension"));//['raster', 'vector', '3d', 'document']; + var fileName; + var fileExtension; - if (cookie.sameSite) { - out.push(`SameSite=${cookie.sameSite}`) - } + // Generate random file name + fileName = this.word({length : fileOptions.length}); - for (const part of cookie.unparsed) { - if (!part.includes('=')) { - throw new Error('Invalid unparsed') - } + // Generate file by specific extension provided by the user + if(fileOptions.extension) { - const [key, ...value] = part.split('=') + fileExtension = fileOptions.extension; + return (fileName + '.' + fileExtension); + } - out.push(`${key.trim()}=${value.join('=')}`) - } + // Generate file by specific extension collection + if(fileOptions.extensions) { - return out.join('; ') -} + if(Array.isArray(fileOptions.extensions)) { -module.exports = { - isCTLExcludingHtab, - validateCookieName, - validateCookiePath, - validateCookieValue, - toIMFDate, - stringify -} + fileExtension = this.pickone(fileOptions.extensions); + return (fileName + '.' + fileExtension); + } + else if(fileOptions.extensions.constructor === Object) { + var extensionObjectCollection = fileOptions.extensions; + var keys = Object.keys(extensionObjectCollection); -/***/ }), + fileExtension = this.pickone(extensionObjectCollection[this.pickone(keys)]); + return (fileName + '.' + fileExtension); + } -/***/ 82067: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + throw new Error("Chance: Extensions must be an Array or Object"); + } -"use strict"; + // Generate file extension based on specific file type + if(fileOptions.fileType) { + var fileType = fileOptions.fileType; + if(typeRange.indexOf(fileType) !== -1) { -const net = __nccwpck_require__(41808) -const assert = __nccwpck_require__(39491) -const util = __nccwpck_require__(83983) -const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(48045) + fileExtension = this.pickone(this.get(poolCollectionKey)[fileType]); + return (fileName + '.' + fileExtension); + } -let tls // include tls conditionally since it is not always available + throw new RangeError("Chance: Expect file type value to be 'raster', 'vector', '3d' or 'document'"); + } -// 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. + // Generate random file name if no extension options are passed + fileExtension = this.pickone(this.get(poolCollectionKey)[this.pickone(typeRange)]); + return (fileName + '.' + fileExtension); + }; -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 - } + /** + * Generates file data of random bytes using the chance.file method for the file name + * + * @param {object} + * fileName: String + * fileExtention: String + * fileSize: Number <- in bytes + * @returns {object} fileName: String, fileData: Buffer + */ + Chance.prototype.fileWithContent = function (options){ + var fileOptions = options || {}; + var fileName = 'fileName' in fileOptions ? fileOptions.fileName : this.file().split(".")[0]; + fileName += "." + ('fileExtension' in fileOptions ? fileOptions.fileExtension : this.file().split(".")[1]); - 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 - } + if (typeof fileOptions.fileSize !== "number") { + throw new Error('File size must be an integer') + } + var file = { + fileData: this.buffer({length: fileOptions.fileSize}), + fileName: fileName, + }; + return file; + } - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } + var data = { - 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() - } + firstNames: { + "male": { + "en": ["James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "George", "Donald", "Anthony", "Paul", "Mark", "Edward", "Steven", "Kenneth", "Andrew", "Brian", "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Frank", "Gary", "Ryan", "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Jonathan", "Scott", "Raymond", "Justin", "Brandon", "Gregory", "Samuel", "Benjamin", "Patrick", "Jack", "Henry", "Walter", "Dennis", "Jerry", "Alexander", "Peter", "Tyler", "Douglas", "Harold", "Aaron", "Jose", "Adam", "Arthur", "Zachary", "Carl", "Nathan", "Albert", "Kyle", "Lawrence", "Joe", "Willie", "Gerald", "Roger", "Keith", "Jeremy", "Terry", "Harry", "Ralph", "Sean", "Jesse", "Roy", "Louis", "Billy", "Austin", "Bruce", "Eugene", "Christian", "Bryan", "Wayne", "Russell", "Howard", "Fred", "Ethan", "Jordan", "Philip", "Alan", "Juan", "Randy", "Vincent", "Bobby", "Dylan", "Johnny", "Phillip", "Victor", "Clarence", "Ernest", "Martin", "Craig", "Stanley", "Shawn", "Travis", "Bradley", "Leonard", "Earl", "Gabriel", "Jimmy", "Francis", "Todd", "Noah", "Danny", "Dale", "Cody", "Carlos", "Allen", "Frederick", "Logan", "Curtis", "Alex", "Joel", "Luis", "Norman", "Marvin", "Glenn", "Tony", "Nathaniel", "Rodney", "Melvin", "Alfred", "Steve", "Cameron", "Chad", "Edwin", "Caleb", "Evan", "Antonio", "Lee", "Herbert", "Jeffery", "Isaac", "Derek", "Ricky", "Marcus", "Theodore", "Elijah", "Luke", "Jesus", "Eddie", "Troy", "Mike", "Dustin", "Ray", "Adrian", "Bernard", "Leroy", "Angel", "Randall", "Wesley", "Ian", "Jared", "Mason", "Hunter", "Calvin", "Oscar", "Clifford", "Jay", "Shane", "Ronnie", "Barry", "Lucas", "Corey", "Manuel", "Leo", "Tommy", "Warren", "Jackson", "Isaiah", "Connor", "Don", "Dean", "Jon", "Julian", "Miguel", "Bill", "Lloyd", "Charlie", "Mitchell", "Leon", "Jerome", "Darrell", "Jeremiah", "Alvin", "Brett", "Seth", "Floyd", "Jim", "Blake", "Micheal", "Gordon", "Trevor", "Lewis", "Erik", "Edgar", "Vernon", "Devin", "Gavin", "Jayden", "Chris", "Clyde", "Tom", "Derrick", "Mario", "Brent", "Marc", "Herman", "Chase", "Dominic", "Ricardo", "Franklin", "Maurice", "Max", "Aiden", "Owen", "Lester", "Gilbert", "Elmer", "Gene", "Francisco", "Glen", "Cory", "Garrett", "Clayton", "Sam", "Jorge", "Chester", "Alejandro", "Jeff", "Harvey", "Milton", "Cole", "Ivan", "Andre", "Duane", "Landon"], + // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0163 + "it": ["Adolfo", "Alberto", "Aldo", "Alessandro", "Alessio", "Alfredo", "Alvaro", "Andrea", "Angelo", "Angiolo", "Antonino", "Antonio", "Attilio", "Benito", "Bernardo", "Bruno", "Carlo", "Cesare", "Christian", "Claudio", "Corrado", "Cosimo", "Cristian", "Cristiano", "Daniele", "Dario", "David", "Davide", "Diego", "Dino", "Domenico", "Duccio", "Edoardo", "Elia", "Elio", "Emanuele", "Emiliano", "Emilio", "Enrico", "Enzo", "Ettore", "Fabio", "Fabrizio", "Federico", "Ferdinando", "Fernando", "Filippo", "Francesco", "Franco", "Gabriele", "Giacomo", "Giampaolo", "Giampiero", "Giancarlo", "Gianfranco", "Gianluca", "Gianmarco", "Gianni", "Gino", "Giorgio", "Giovanni", "Giuliano", "Giulio", "Giuseppe", "Graziano", "Gregorio", "Guido", "Iacopo", "Jacopo", "Lapo", "Leonardo", "Lorenzo", "Luca", "Luciano", "Luigi", "Manuel", "Marcello", "Marco", "Marino", "Mario", "Massimiliano", "Massimo", "Matteo", "Mattia", "Maurizio", "Mauro", "Michele", "Mirko", "Mohamed", "Nello", "Neri", "Niccolò", "Nicola", "Osvaldo", "Otello", "Paolo", "Pier Luigi", "Piero", "Pietro", "Raffaele", "Remo", "Renato", "Renzo", "Riccardo", "Roberto", "Rolando", "Romano", "Salvatore", "Samuele", "Sandro", "Sergio", "Silvano", "Simone", "Stefano", "Thomas", "Tommaso", "Ubaldo", "Ugo", "Umberto", "Valerio", "Valter", "Vasco", "Vincenzo", "Vittorio"], + // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html + "nl": ["Aaron","Abel","Adam","Adriaan","Albert","Alexander","Ali","Arjen","Arno","Bart","Bas","Bastiaan","Benjamin","Bob", "Boris","Bram","Brent","Cas","Casper","Chris","Christiaan","Cornelis","Daan","Daley","Damian","Dani","Daniel","DaniĆ«l","David","Dean","Dirk","Dylan","Egbert","Elijah","Erik","Erwin","Evert","Ezra","Fabian","Fedde","Finn","Florian","Floris","Frank","Frans","Frederik","Freek","Geert","Gerard","Gerben","Gerrit","Gijs","Guus","Hans","Hendrik","Henk","Herman","Hidde","Hugo","Jaap","Jan Jaap","Jan-Willem","Jack","Jacob","Jan","Jason","Jasper","Jayden","Jelle","Jelte","Jens","Jeroen","Jesse","Jim","Job","Joep","Johannes","John","Jonathan","Joris","Joshua","JoĆ«l","Julian","Kees","Kevin","Koen","Lars","Laurens","Leendert","Lennard","Lodewijk","Luc","Luca","Lucas","Lukas","Luuk","Maarten","Marcus","Martijn","Martin","Matthijs","Maurits","Max","Mees","Melle","Mick","Mika","Milan","Mohamed","Mohammed","Morris","Muhammed","Nathan","Nick","Nico","Niek","Niels","Noah","Noud","Olivier","Oscar","Owen","Paul","Pepijn","Peter","Pieter","Pim","Quinten","Reinier","Rens","Robin","Ruben","Sam","Samuel","Sander","Sebastiaan","Sem","Sep","Sepp","Siem","Simon","Stan","Stef","Steven","Stijn","Sven","Teun","Thijmen","Thijs","Thomas","Tijn","Tim","Timo","Tobias","Tom","Victor","Vince","Willem","Wim","Wouter","Yusuf"], + // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie + "fr": ["Aaron","Abdon","Abel","AbĆ©lard","Abelin","Abondance","Abraham","Absalon","Acace","Achaire","Achille","Adalard","Adalbald","AdalbĆ©ron","Adalbert","Adalric","Adam","Adegrin","Adel","Adelin","Andelin","Adelphe","Adam","AdĆ©odat","AdhĆ©mar","Adjutor","Adolphe","Adonis","Adon","Adrien","Agapet","Agathange","Agathon","Agilbert","AgĆ©nor","Agnan","Aignan","Agrippin","Aimable","AimĆ©","Alain","Alban","Albin","Aubin","AlbĆ©ric","Albert","Albertet","Alcibiade","Alcide","AlcĆ©e","Alcime","Aldonce","Aldric","AldĆ©ric","Aleaume","Alexandre","Alexis","Alix","Alliaume","Aleaume","Almine","Almire","AloĆÆs","AlphĆ©e","Alphonse","Alpinien","AlverĆØde","Amalric","Amaury","Amandin","Amant","Ambroise","AmĆ©dĆ©e","AmĆ©lien","Amiel","Amour","AnaĆ«l","Anastase","Anatole","Ancelin","AndĆ©ol","Andoche","AndrĆ©","Andoche","Ange","Angelin","Angilbe","Anglebert","Angoustan","Anicet","Anne","Annibal","Ansbert","Anselme","Anthelme","Antheaume","Anthime","Antide","Antoine","Antonius","Antonin","Apollinaire","Apollon","Aquilin","Arcade","Archambaud","Archambeau","Archange","Archibald","Arian","Ariel","Ariste","Aristide","Armand","Armel","Armin","Arnould","Arnaud","Arolde","ArsĆØne","ArsinoĆ©","Arthaud","ArthĆØme","Arthur","Ascelin","Athanase","Aubry","Audebert","Audouin","Audran","Audric","Auguste","Augustin","AurĆØle","AurĆ©lien","Aurian","Auxence","Axel","Aymard","Aymeric","Aymon","Aymond","Balthazar","Baptiste","BarnabĆ©","BarthĆ©lemy","BartimĆ©e","Basile","Bastien","Baudouin","BĆ©nigne","Benjamin","BenoĆ®t","BĆ©renger","BĆ©rard","Bernard","Bertrand","Blaise","Bon","Boniface","Bouchard","Brice","Brieuc","Bruno","Brunon","Calixte","Calliste","CamĆ©lien","Camille","Camillien","Candide","Caribert","Carloman","Cassandre","Cassien","CĆ©dric","CĆ©leste","CĆ©lestin","CĆ©lien","CĆ©saire","CĆ©sar","Charles","Charlemagne","Childebert","ChilpĆ©ric","ChrĆ©tien","Christian","Christodule","Christophe","Chrysostome","Clarence","Claude","Claudien","ClĆ©andre","ClĆ©ment","Clotaire","CĆ“me","Constance","Constant","Constantin","Corentin","Cyprien","Cyriaque","Cyrille","Cyril","Damien","Daniel","David","Delphin","Denis","DĆ©sirĆ©","Didier","DieudonnĆ©","Dimitri","Dominique","Dorian","DorothĆ©e","Edgard","Edmond","Ɖdouard","ƉleuthĆØre","Ɖlie","ƉlisĆ©e","Ɖmeric","Ɖmile","Ɖmilien","Emmanuel","Enguerrand","Ɖpiphane","Ɖric","Esprit","Ernest","Ɖtienne","Eubert","Eudes","Eudoxe","EugĆØne","EusĆØbe","Eustache","Ɖvariste","Ɖvrard","Fabien","Fabrice","Falba","FĆ©licitĆ©","FĆ©lix","Ferdinand","Fiacre","FidĆØle","Firmin","Flavien","Flodoard","Florent","Florentin","Florestan","Florian","FortunĆ©","Foulques","Francisque","FranƧois","FranƧais","Franciscus","Francs","FrĆ©dĆ©ric","Fulbert","Fulcran","Fulgence","Gabin","Gabriel","GaĆ«l","Garnier","Gaston","Gaspard","Gatien","Gaud","Gautier","GĆ©dĆ©on","Geoffroy","Georges","GĆ©raud","GĆ©rard","Gerbert","Germain","Gervais","Ghislain","Gilbert","Gilles","Girart","Gislebert","Gondebaud","Gonthier","Gontran","Gonzague","GrĆ©goire","GuĆ©rin","Gui","Guillaume","Gustave","Guy","Guyot","Hardouin","Hector","HĆ©delin","HĆ©lier","Henri","Herbert","Herluin","HervĆ©","Hilaire","Hildebert","Hincmar","Hippolyte","HonorĆ©","Hubert","Hugues","Innocent","Isabeau","Isidore","Jacques","Japhet","Jason","Jean","Jeannel","Jeannot","JĆ©rĆ©mie","JĆ©rĆ“me","Joachim","Joanny","Job","Jocelyn","JoĆ«l","Johan","Jonas","Jonathan","Joseph","Josse","Josselin","Jourdain","Jude","JudicaĆ«l","Jules","Julien","Juste","Justin","Lambert","Landry","Laurent","Lazare","LĆ©andre","LĆ©on","LĆ©onard","LĆ©opold","Leu","Loup","Leufroy","LibĆØre","LiĆ©tald","Lionel","LoĆÆc","Longin","Lorrain","Lorraine","Lothaire","Louis","Loup","Luc","Lucas","Lucien","Ludolphe","Ludovic","Macaire","Malo","Mamert","ManassĆ©","Marc","Marceau","Marcel","Marcelin","Marius","Marseille","Martial","Martin","Mathurin","Matthias","Mathias","Matthieu","Maugis","Maurice","Mauricet","Maxence","Maxime","Maximilien","Mayeul","MĆ©dĆ©ric","Melchior","Mence","Merlin","MĆ©rovĆ©e","MichaĆ«l","Michel","MoĆÆse","Morgan","Nathan","NathanaĆ«l","Narcisse","NĆ©hĆ©mie","Nestor","Nestor","NicĆ©phore","Nicolas","NoĆ©","NoĆ«l","Norbert","Normand","Normands","Octave","Odilon","Odon","Oger","Olivier","Oury","PacĆ“me","PalĆ©mon","Parfait","Pascal","Paterne","Patrice","Paul","PĆ©pin","Perceval","PhilĆ©mon","Philibert","Philippe","PhilothĆ©e","Pie","Pierre","Pierrick","Prosper","Quentin","Raoul","RaphaĆ«l","Raymond","RĆ©gis","RĆ©jean","RĆ©mi","Renaud","RenĆ©","Reybaud","Richard","Robert","Roch","Rodolphe","Rodrigue","Roger","Roland","Romain","Romuald","RomĆ©o","Rome","Ronan","Roselin","Salomon","Samuel","Savin","Savinien","Scholastique","SĆ©bastien","SĆ©raphin","Serge","SĆ©verin","Sidoine","Sigebert","Sigismond","SilvĆØre","Simon","SimĆ©on","Sixte","Stanislas","StĆ©phane","Stephan","Sylvain","Sylvestre","TancrĆØde","Tanguy","Taurin","ThĆ©odore","ThĆ©odose","ThĆ©ophile","ThĆ©ophraste","Thibault","Thibert","Thierry","Thomas","TimolĆ©on","TimothĆ©e","Titien","Tonnin","Toussaint","Trajan","Tristan","Turold","Tim","Ulysse","Urbain","Valentin","ValĆØre","ValĆ©ry","Venance","Venant","Venceslas","Vianney","Victor","Victorien","Victorin","Vigile","Vincent","Vital","Vitalien","Vivien","Waleran","Wandrille","Xavier","XĆ©nophon","Yves","Zacharie","ZachĆ©","ZĆ©phirin"] + }, - get (sessionKey) { - return this._sessionCache.get(sessionKey) - } + "female": { + "en": ["Mary", "Emma", "Elizabeth", "Minnie", "Margaret", "Ida", "Alice", "Bertha", "Sarah", "Annie", "Clara", "Ella", "Florence", "Cora", "Martha", "Laura", "Nellie", "Grace", "Carrie", "Maude", "Mabel", "Bessie", "Jennie", "Gertrude", "Julia", "Hattie", "Edith", "Mattie", "Rose", "Catherine", "Lillian", "Ada", "Lillie", "Helen", "Jessie", "Louise", "Ethel", "Lula", "Myrtle", "Eva", "Frances", "Lena", "Lucy", "Edna", "Maggie", "Pearl", "Daisy", "Fannie", "Josephine", "Dora", "Rosa", "Katherine", "Agnes", "Marie", "Nora", "May", "Mamie", "Blanche", "Stella", "Ellen", "Nancy", "Effie", "Sallie", "Nettie", "Della", "Lizzie", "Flora", "Susie", "Maud", "Mae", "Etta", "Harriet", "Sadie", "Caroline", "Katie", "Lydia", "Elsie", "Kate", "Susan", "Mollie", "Alma", "Addie", "Georgia", "Eliza", "Lulu", "Nannie", "Lottie", "Amanda", "Belle", "Charlotte", "Rebecca", "Ruth", "Viola", "Olive", "Amelia", "Hannah", "Jane", "Virginia", "Emily", "Matilda", "Irene", "Kathryn", "Esther", "Willie", "Henrietta", "Ollie", "Amy", "Rachel", "Sara", "Estella", "Theresa", "Augusta", "Ora", "Pauline", "Josie", "Lola", "Sophia", "Leona", "Anne", "Mildred", "Ann", "Beulah", "Callie", "Lou", "Delia", "Eleanor", "Barbara", "Iva", "Louisa", "Maria", "Mayme", "Evelyn", "Estelle", "Nina", "Betty", "Marion", "Bettie", "Dorothy", "Luella", "Inez", "Lela", "Rosie", "Allie", "Millie", "Janie", "Cornelia", "Victoria", "Ruby", "Winifred", "Alta", "Celia", "Christine", "Beatrice", "Birdie", "Harriett", "Mable", "Myra", "Sophie", "Tillie", "Isabel", "Sylvia", "Carolyn", "Isabelle", "Leila", "Sally", "Ina", "Essie", "Bertie", "Nell", "Alberta", "Katharine", "Lora", "Rena", "Mina", "Rhoda", "Mathilda", "Abbie", "Eula", "Dollie", "Hettie", "Eunice", "Fanny", "Ola", "Lenora", "Adelaide", "Christina", "Lelia", "Nelle", "Sue", "Johanna", "Lilly", "Lucinda", "Minerva", "Lettie", "Roxie", "Cynthia", "Helena", "Hilda", "Hulda", "Bernice", "Genevieve", "Jean", "Cordelia", "Marian", "Francis", "Jeanette", "Adeline", "Gussie", "Leah", "Lois", "Lura", "Mittie", "Hallie", "Isabella", "Olga", "Phoebe", "Teresa", "Hester", "Lida", "Lina", "Winnie", "Claudia", "Marguerite", "Vera", "Cecelia", "Bess", "Emilie", "Rosetta", "Verna", "Myrtie", "Cecilia", "Elva", "Olivia", "Ophelia", "Georgie", "Elnora", "Violet", "Adele", "Lily", "Linnie", "Loretta", "Madge", "Polly", "Virgie", "Eugenia", "Lucile", "Lucille", "Mabelle", "Rosalie"], + // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0162 + "it": ["Ada", "Adriana", "Alessandra", "Alessia", "Alice", "Angela", "Anna", "Anna Maria", "Annalisa", "Annita", "Annunziata", "Antonella", "Arianna", "Asia", "Assunta", "Aurora", "Barbara", "Beatrice", "Benedetta", "Bianca", "Bruna", "Camilla", "Carla", "Carlotta", "Carmela", "Carolina", "Caterina", "Catia", "Cecilia", "Chiara", "Cinzia", "Clara", "Claudia", "Costanza", "Cristina", "Daniela", "Debora", "Diletta", "Dina", "Donatella", "Elena", "Eleonora", "Elisa", "Elisabetta", "Emanuela", "Emma", "Eva", "Federica", "Fernanda", "Fiorella", "Fiorenza", "Flora", "Franca", "Francesca", "Gabriella", "Gaia", "Gemma", "Giada", "Gianna", "Gina", "Ginevra", "Giorgia", "Giovanna", "Giulia", "Giuliana", "Giuseppa", "Giuseppina", "Grazia", "Graziella", "Greta", "Ida", "Ilaria", "Ines", "Iolanda", "Irene", "Irma", "Isabella", "Jessica", "Laura", "Lea", "Letizia", "Licia", "Lidia", "Liliana", "Lina", "Linda", "Lisa", "Livia", "Loretta", "Luana", "Lucia", "Luciana", "Lucrezia", "Luisa", "Manuela", "Mara", "Marcella", "Margherita", "Maria", "Maria Cristina", "Maria Grazia", "Maria Luisa", "Maria Pia", "Maria Teresa", "Marina", "Marisa", "Marta", "Martina", "Marzia", "Matilde", "Melissa", "Michela", "Milena", "Mirella", "Monica", "Natalina", "Nella", "Nicoletta", "Noemi", "Olga", "Paola", "Patrizia", "Piera", "Pierina", "Raffaella", "Rebecca", "Renata", "Rina", "Rita", "Roberta", "Rosa", "Rosanna", "Rossana", "Rossella", "Sabrina", "Sandra", "Sara", "Serena", "Silvana", "Silvia", "Simona", "Simonetta", "Sofia", "Sonia", "Stefania", "Susanna", "Teresa", "Tina", "Tiziana", "Tosca", "Valentina", "Valeria", "Vanda", "Vanessa", "Vanna", "Vera", "Veronica", "Vilma", "Viola", "Virginia", "Vittoria"], + // Data taken from http://www.svbkindernamen.nl/int/nl/kindernamen/index.html + "nl": ["Ada", "Arianne", "Afke", "Amanda", "Amber", "Amy", "Aniek", "Anita", "Anja", "Anna", "Anne", "Annelies", "Annemarie", "Annette", "Anouk", "Astrid", "Aukje", "Barbara", "Bianca", "Carla", "Carlijn", "Carolien", "Chantal", "Charlotte", "Claudia", "DaniĆ«lle", "Debora", "Diane", "Dora", "Eline", "Elise", "Ella", "Ellen", "Emma", "Esmee", "Evelien", "Esther", "Erica", "Eva", "Femke", "Fleur", "Floor", "Froukje", "Gea", "Gerda", "Hanna", "Hanneke", "Heleen", "Hilde", "Ilona", "Ina", "Inge", "Ingrid", "Iris", "Isabel", "Isabelle", "Janneke", "Jasmijn", "Jeanine", "Jennifer", "Jessica", "Johanna", "Joke", "Julia", "Julie", "Karen", "Karin", "Katja", "Kim", "Lara", "Laura", "Lena", "Lianne", "Lieke", "Lilian", "Linda", "Lisa", "Lisanne", "Lotte", "Louise", "Maaike", "Manon", "Marga", "Maria", "Marissa", "Marit", "Marjolein", "Martine", "Marleen", "Melissa", "Merel", "Miranda", "Michelle", "Mirjam", "Mirthe", "Naomi", "Natalie", 'Nienke', "Nina", "Noortje", "Olivia", "Patricia", "Paula", "Paulien", "Ramona", "Ria", "Rianne", "Roos", "Rosanne", "Ruth", "Sabrina", "Sandra", "Sanne", "Sara", "Saskia", "Silvia", "Sofia", "Sophie", "Sonja", "Suzanne", "Tamara", "Tess", "Tessa", "Tineke", "Valerie", "Vanessa", "Veerle", "Vera", "Victoria", "Wendy", "Willeke", "Yvonne", "ZoĆ«"], + // Data taken from https://fr.wikipedia.org/wiki/Liste_de_pr%C3%A9noms_fran%C3%A7ais_et_de_la_francophonie + "fr": ["Abdon","Abel","AbigaĆ«lle","AbigaĆÆl","Acacius","Acanthe","Adalbert","Adalsinde","Adegrine","AdĆ©laĆÆde","AdĆØle","AdĆ©lie","Adeline","Adeltrude","Adolphe","Adonis","AdrastĆ©e","Adrehilde","Adrienne","Agathe","Agilbert","AglaĆ©","Aignan","AgneflĆØte","AgnĆØs","Agrippine","AimĆ©","Alaine","AlaĆÆs","Albane","AlbĆ©rade","Alberte","Alcide","Alcine","Alcyone","Aldegonde","Aleth","Alexandrine","Alexine","Alice","AliĆ©nor","Aliette","Aline","Alix","AlizĆ©","AloĆÆse","Aloyse","Alphonsine","AlthĆ©e","Amaliane","AmalthĆ©e","Amande","Amandine","Amant","Amarande","Amaranthe","Amaryllis","Ambre","Ambroisie","AmĆ©lie","AmĆ©thyste","Aminte","AnaĆ«l","AnaĆÆs","Anastasie","Anatole","Ancelin","AndrĆ©e","AnĆ©mone","AngadrĆŖme","AngĆØle","Angeline","AngĆ©lique","Angilbert","Anicet","Annabelle","Anne","Annette","Annick","Annie","Annonciade","Ansbert","Anstrudie","Anthelme","Antigone","Antoinette","Antonine","AphĆ©lie","Apolline","Apollonie","Aquiline","Arabelle","Arcadie","Archange","Argine","Ariane","Aricie","Ariel","Arielle","Arlette","Armance","Armande","Armandine","Armelle","Armide","Armelle","Armin","Arnaud","ArsĆØne","ArsinoĆ©","ArtĆ©mis","Arthur","Ascelin","Ascension","Assomption","AstartĆ©","AstĆ©rie","AstrĆ©e","Astrid","Athalie","Athanasie","Athina","Aube","Albert","Aude","Audrey","Augustine","Aure","AurĆ©lie","AurĆ©lien","AurĆØle","Aurore","Auxence","Aveline","AbigaĆ«lle","Avoye","Axelle","Aymard","AzalĆ©e","AdĆØle","Adeline","Barbe","Basilisse","Bathilde","BĆ©atrice","BĆ©atrix","BĆ©nĆ©dicte","BĆ©rengĆØre","Bernadette","Berthe","Bertille","Beuve","Blanche","Blanc","Blandine","Brigitte","Brune","Brunehilde","Callista","Camille","Capucine","Carine","Caroline","Cassandre","Catherine","CĆ©cile","CĆ©leste","CĆ©lestine","CĆ©line","Chantal","CharlĆØne","Charline","Charlotte","ChloĆ©","Christelle","Christiane","Christine","Claire","Clara","Claude","Claudine","Clarisse","ClĆ©mence","ClĆ©mentine","ClĆ©o","Clio","Clotilde","Coline","Conception","Constance","Coralie","Coraline","Corentine","Corinne","Cyrielle","Daniel","Daniel","DaphnĆ©","DĆ©bora","Delphine","Denise","Diane","DieudonnĆ©","Dominique","Doriane","DorothĆ©e","Douce","Ɖdith","EdmĆ©e","ƉlĆ©onore","Ɖliane","Ɖlia","Ɖliette","Ɖlisabeth","Ɖlise","Ella","Ɖlodie","ƉloĆÆse","Elsa","Ɖmeline","ƉmĆ©rance","ƉmĆ©rentienne","ƉmĆ©rencie","Ɖmilie","Emma","Emmanuelle","Emmelie","Ernestine","Esther","Estelle","Eudoxie","EugĆ©nie","Eulalie","Euphrasie","EusĆ©bie","ƉvangĆ©line","Eva","ƈve","Ɖvelyne","Fanny","Fantine","Faustine","FĆ©licie","Fernande","Flavie","Fleur","Flore","Florence","Florie","FortunĆ©","France","Francia","FranƧoise","Francine","Gabrielle","GaĆ«lle","Garance","GeneviĆØve","Georgette","Gerberge","Germaine","Gertrude","GisĆØle","GueniĆØvre","Guilhemine","Guillemette","Gustave","Gwenael","HĆ©lĆØne","HĆ©loĆÆse","Henriette","Hermine","Hermione","Hippolyte","Honorine","Hortense","Huguette","Ines","IrĆØne","Irina","Iris","Isabeau","Isabelle","Iseult","Isolde","IsmĆ©rie","Jacinthe","Jacqueline","Jade","Janine","Jeanne","Jocelyne","JoĆ«lle","JosĆ©phine","Judith","Julia","Julie","Jules","Juliette","Justine","Katy","Kathy","Katie","Laura","Laure","Laureline","Laurence","Laurene","Lauriane","Laurianne","Laurine","LĆ©a","LĆ©na","LĆ©onie","LĆ©on","LĆ©ontine","Lorraine","Lucie","Lucienne","Lucille","Ludivine","Lydie","Lydie","Megane","Madeleine","Magali","Maguelone","Mallaury","Manon","Marceline","Margot","Marguerite","Marianne","Marie","Myriam","Marie","Marine","Marion","MarlĆØne","Marthe","Martine","Mathilde","Maud","Maureen","Mauricette","Maxime","MĆ©lanie","Melissa","MĆ©lissandre","MĆ©lisande","MĆ©lodie","Michel","Micheline","Mireille","Miriam","MoĆÆse","Monique","Morgane","Muriel","MylĆØne","NadĆØge","Nadine","Nathalie","Nicole","Nicolette","Nine","NoĆ«l","NoĆ©mie","OcĆ©ane","Odette","Odile","Olive","Olivia","Olympe","Ombline","Ombeline","OphĆ©lie","Oriande","Oriane","Ozanne","Pascale","Pascaline","Paule","Paulette","Pauline","Priscille","Prisca","Prisque","PĆ©cine","PĆ©lagie","PĆ©nĆ©lope","Perrine","PĆ©tronille","Philippine","PhilomĆØne","PhilothĆ©e","Primerose","Prudence","PulchĆ©rie","Quentine","QuiĆ©ta","Quintia","Quintilla","Rachel","RaphaĆ«lle","Raymonde","Rebecca","RĆ©gine","RĆ©jeanne","RenĆ©","Rita","Rita","Rolande","Romane","Rosalie","Rose","Roseline","Sabine","SalomĆ©","Sandra","Sandrine","Sarah","SĆ©golĆØne","SĆ©verine","Sibylle","Simone","Sixt","Solange","Soline","SolĆØne","Sophie","StĆ©phanie","Suzanne","Sylvain","Sylvie","Tatiana","ThaĆÆs","ThĆ©odora","ThĆ©rĆØse","Tiphaine","Ursule","Valentine","ValĆ©rie","VĆ©ronique","Victoire","Victorine","Vinciane","Violette","Virginie","Viviane","XaviĆØre","Yolande","Ysaline","Yvette","Yvonne","ZĆ©lie","Zita","ZoĆ©"] + } + }, - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } + lastNames: { + "en": ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis', 'Miller', 'Wilson', 'Moore', 'Taylor', 'Anderson', 'Thomas', 'Jackson', 'White', 'Harris', 'Martin', 'Thompson', 'Garcia', 'Martinez', 'Robinson', 'Clark', 'Rodriguez', 'Lewis', 'Lee', 'Walker', 'Hall', 'Allen', 'Young', 'Hernandez', 'King', 'Wright', 'Lopez', 'Hill', 'Scott', 'Green', 'Adams', 'Baker', 'Gonzalez', 'Nelson', 'Carter', 'Mitchell', 'Perez', 'Roberts', 'Turner', 'Phillips', 'Campbell', 'Parker', 'Evans', 'Edwards', 'Collins', 'Stewart', 'Sanchez', 'Morris', 'Rogers', 'Reed', 'Cook', 'Morgan', 'Bell', 'Murphy', 'Bailey', 'Rivera', 'Cooper', 'Richardson', 'Cox', 'Howard', 'Ward', 'Torres', 'Peterson', 'Gray', 'Ramirez', 'James', 'Watson', 'Brooks', 'Kelly', 'Sanders', 'Price', 'Bennett', 'Wood', 'Barnes', 'Ross', 'Henderson', 'Coleman', 'Jenkins', 'Perry', 'Powell', 'Long', 'Patterson', 'Hughes', 'Flores', 'Washington', 'Butler', 'Simmons', 'Foster', 'Gonzales', 'Bryant', 'Alexander', 'Russell', 'Griffin', 'Diaz', 'Hayes', 'Myers', 'Ford', 'Hamilton', 'Graham', 'Sullivan', 'Wallace', 'Woods', 'Cole', 'West', 'Jordan', 'Owens', 'Reynolds', 'Fisher', 'Ellis', 'Harrison', 'Gibson', 'McDonald', 'Cruz', 'Marshall', 'Ortiz', 'Gomez', 'Murray', 'Freeman', 'Wells', 'Webb', 'Simpson', 'Stevens', 'Tucker', 'Porter', 'Hunter', 'Hicks', 'Crawford', 'Henry', 'Boyd', 'Mason', 'Morales', 'Kennedy', 'Warren', 'Dixon', 'Ramos', 'Reyes', 'Burns', 'Gordon', 'Shaw', 'Holmes', 'Rice', 'Robertson', 'Hunt', 'Black', 'Daniels', 'Palmer', 'Mills', 'Nichols', 'Grant', 'Knight', 'Ferguson', 'Rose', 'Stone', 'Hawkins', 'Dunn', 'Perkins', 'Hudson', 'Spencer', 'Gardner', 'Stephens', 'Payne', 'Pierce', 'Berry', 'Matthews', 'Arnold', 'Wagner', 'Willis', 'Ray', 'Watkins', 'Olson', 'Carroll', 'Duncan', 'Snyder', 'Hart', 'Cunningham', 'Bradley', 'Lane', 'Andrews', 'Ruiz', 'Harper', 'Fox', 'Riley', 'Armstrong', 'Carpenter', 'Weaver', 'Greene', 'Lawrence', 'Elliott', 'Chavez', 'Sims', 'Austin', 'Peters', 'Kelley', 'Franklin', 'Lawson', 'Fields', 'Gutierrez', 'Ryan', 'Schmidt', 'Carr', 'Vasquez', 'Castillo', 'Wheeler', 'Chapman', 'Oliver', 'Montgomery', 'Richards', 'Williamson', 'Johnston', 'Banks', 'Meyer', 'Bishop', 'McCoy', 'Howell', 'Alvarez', 'Morrison', 'Hansen', 'Fernandez', 'Garza', 'Harvey', 'Little', 'Burton', 'Stanley', 'Nguyen', 'George', 'Jacobs', 'Reid', 'Kim', 'Fuller', 'Lynch', 'Dean', 'Gilbert', 'Garrett', 'Romero', 'Welch', 'Larson', 'Frazier', 'Burke', 'Hanson', 'Day', 'Mendoza', 'Moreno', 'Bowman', 'Medina', 'Fowler', 'Brewer', 'Hoffman', 'Carlson', 'Silva', 'Pearson', 'Holland', 'Douglas', 'Fleming', 'Jensen', 'Vargas', 'Byrd', 'Davidson', 'Hopkins', 'May', 'Terry', 'Herrera', 'Wade', 'Soto', 'Walters', 'Curtis', 'Neal', 'Caldwell', 'Lowe', 'Jennings', 'Barnett', 'Graves', 'Jimenez', 'Horton', 'Shelton', 'Barrett', 'Obrien', 'Castro', 'Sutton', 'Gregory', 'McKinney', 'Lucas', 'Miles', 'Craig', 'Rodriquez', 'Chambers', 'Holt', 'Lambert', 'Fletcher', 'Watts', 'Bates', 'Hale', 'Rhodes', 'Pena', 'Beck', 'Newman', 'Haynes', 'McDaniel', 'Mendez', 'Bush', 'Vaughn', 'Parks', 'Dawson', 'Santiago', 'Norris', 'Hardy', 'Love', 'Steele', 'Curry', 'Powers', 'Schultz', 'Barker', 'Guzman', 'Page', 'Munoz', 'Ball', 'Keller', 'Chandler', 'Weber', 'Leonard', 'Walsh', 'Lyons', 'Ramsey', 'Wolfe', 'Schneider', 'Mullins', 'Benson', 'Sharp', 'Bowen', 'Daniel', 'Barber', 'Cummings', 'Hines', 'Baldwin', 'Griffith', 'Valdez', 'Hubbard', 'Salazar', 'Reeves', 'Warner', 'Stevenson', 'Burgess', 'Santos', 'Tate', 'Cross', 'Garner', 'Mann', 'Mack', 'Moss', 'Thornton', 'Dennis', 'McGee', 'Farmer', 'Delgado', 'Aguilar', 'Vega', 'Glover', 'Manning', 'Cohen', 'Harmon', 'Rodgers', 'Robbins', 'Newton', 'Todd', 'Blair', 'Higgins', 'Ingram', 'Reese', 'Cannon', 'Strickland', 'Townsend', 'Potter', 'Goodwin', 'Walton', 'Rowe', 'Hampton', 'Ortega', 'Patton', 'Swanson', 'Joseph', 'Francis', 'Goodman', 'Maldonado', 'Yates', 'Becker', 'Erickson', 'Hodges', 'Rios', 'Conner', 'Adkins', 'Webster', 'Norman', 'Malone', 'Hammond', 'Flowers', 'Cobb', 'Moody', 'Quinn', 'Blake', 'Maxwell', 'Pope', 'Floyd', 'Osborne', 'Paul', 'McCarthy', 'Guerrero', 'Lindsey', 'Estrada', 'Sandoval', 'Gibbs', 'Tyler', 'Gross', 'Fitzgerald', 'Stokes', 'Doyle', 'Sherman', 'Saunders', 'Wise', 'Colon', 'Gill', 'Alvarado', 'Greer', 'Padilla', 'Simon', 'Waters', 'Nunez', 'Ballard', 'Schwartz', 'McBride', 'Houston', 'Christensen', 'Klein', 'Pratt', 'Briggs', 'Parsons', 'McLaughlin', 'Zimmerman', 'French', 'Buchanan', 'Moran', 'Copeland', 'Roy', 'Pittman', 'Brady', 'McCormick', 'Holloway', 'Brock', 'Poole', 'Frank', 'Logan', 'Owen', 'Bass', 'Marsh', 'Drake', 'Wong', 'Jefferson', 'Park', 'Morton', 'Abbott', 'Sparks', 'Patrick', 'Norton', 'Huff', 'Clayton', 'Massey', 'Lloyd', 'Figueroa', 'Carson', 'Bowers', 'Roberson', 'Barton', 'Tran', 'Lamb', 'Harrington', 'Casey', 'Boone', 'Cortez', 'Clarke', 'Mathis', 'Singleton', 'Wilkins', 'Cain', 'Bryan', 'Underwood', 'Hogan', 'McKenzie', 'Collier', 'Luna', 'Phelps', 'McGuire', 'Allison', 'Bridges', 'Wilkerson', 'Nash', 'Summers', 'Atkins'], + // Data taken from http://www.dati.gov.it/dataset/comune-di-firenze_0164 (first 1000) + "it": ["Acciai", "Aglietti", "Agostini", "Agresti", "Ahmed", "Aiazzi", "Albanese", "Alberti", "Alessi", "Alfani", "Alinari", "Alterini", "Amato", "Ammannati", "Ancillotti", "Andrei", "Andreini", "Andreoni", "Angeli", "Anichini", "Antonelli", "Antonini", "Arena", "Ariani", "Arnetoli", "Arrighi", "Baccani", "Baccetti", "Bacci", "Bacherini", "Badii", "Baggiani", "Baglioni", "Bagni", "Bagnoli", "Baldassini", "Baldi", "Baldini", "Ballerini", "Balli", "Ballini", "Balloni", "Bambi", "Banchi", "Bandinelli", "Bandini", "Bani", "Barbetti", "Barbieri", "Barchielli", "Bardazzi", "Bardelli", "Bardi", "Barducci", "Bargellini", "Bargiacchi", "Barni", "Baroncelli", "Baroncini", "Barone", "Baroni", "Baronti", "Bartalesi", "Bartoletti", "Bartoli", "Bartolini", "Bartoloni", "Bartolozzi", "Basagni", "Basile", "Bassi", "Batacchi", "Battaglia", "Battaglini", "Bausi", "Becagli", "Becattini", "Becchi", "Becucci", "Bellandi", "Bellesi", "Belli", "Bellini", "Bellucci", "Bencini", "Benedetti", "Benelli", "Beni", "Benini", "Bensi", "Benucci", "Benvenuti", "Berlincioni", "Bernacchioni", "Bernardi", "Bernardini", "Berni", "Bernini", "Bertelli", "Berti", "Bertini", "Bessi", "Betti", "Bettini", "Biagi", "Biagini", "Biagioni", "Biagiotti", "Biancalani", "Bianchi", "Bianchini", "Bianco", "Biffoli", "Bigazzi", "Bigi", "Biliotti", "Billi", "Binazzi", "Bindi", "Bini", "Biondi", "Bizzarri", "Bocci", "Bogani", "Bolognesi", "Bonaiuti", "Bonanni", "Bonciani", "Boncinelli", "Bondi", "Bonechi", "Bongini", "Boni", "Bonini", "Borchi", "Boretti", "Borghi", "Borghini", "Borgioli", "Borri", "Borselli", "Boschi", "Bottai", "Bracci", "Braccini", "Brandi", "Braschi", "Bravi", "Brazzini", "Breschi", "Brilli", "Brizzi", "Brogelli", "Brogi", "Brogioni", "Brunelli", "Brunetti", "Bruni", "Bruno", "Brunori", "Bruschi", "Bucci", "Bucciarelli", "Buccioni", "Bucelli", "Bulli", "Burberi", "Burchi", "Burgassi", "Burroni", "Bussotti", "Buti", "Caciolli", "Caiani", "Calabrese", "Calamai", "Calamandrei", "Caldini", "Calo'", "Calonaci", "Calosi", "Calvelli", "Cambi", "Camiciottoli", "Cammelli", "Cammilli", "Campolmi", "Cantini", "Capanni", "Capecchi", "Caponi", "Cappelletti", "Cappelli", "Cappellini", "Cappugi", "Capretti", "Caputo", "Carbone", "Carboni", "Cardini", "Carlesi", "Carletti", "Carli", "Caroti", "Carotti", "Carrai", "Carraresi", "Carta", "Caruso", "Casalini", "Casati", "Caselli", "Casini", "Castagnoli", "Castellani", "Castelli", "Castellucci", "Catalano", "Catarzi", "Catelani", "Cavaciocchi", "Cavallaro", "Cavallini", "Cavicchi", "Cavini", "Ceccarelli", "Ceccatelli", "Ceccherelli", "Ceccherini", "Cecchi", "Cecchini", "Cecconi", "Cei", "Cellai", "Celli", "Cellini", "Cencetti", "Ceni", "Cenni", "Cerbai", "Cesari", "Ceseri", "Checcacci", "Checchi", "Checcucci", "Cheli", "Chellini", "Chen", "Cheng", "Cherici", "Cherubini", "Chiaramonti", "Chiarantini", "Chiarelli", "Chiari", "Chiarini", "Chiarugi", "Chiavacci", "Chiesi", "Chimenti", "Chini", "Chirici", "Chiti", "Ciabatti", "Ciampi", "Cianchi", "Cianfanelli", "Cianferoni", "Ciani", "Ciapetti", "Ciappi", "Ciardi", "Ciatti", "Cicali", "Ciccone", "Cinelli", "Cini", "Ciobanu", "Ciolli", "Cioni", "Cipriani", "Cirillo", "Cirri", "Ciucchi", "Ciuffi", "Ciulli", "Ciullini", "Clemente", "Cocchi", "Cognome", "Coli", "Collini", "Colombo", "Colzi", "Comparini", "Conforti", "Consigli", "Conte", "Conti", "Contini", "Coppini", "Coppola", "Corsi", "Corsini", "Corti", "Cortini", "Cosi", "Costa", "Costantini", "Costantino", "Cozzi", "Cresci", "Crescioli", "Cresti", "Crini", "Curradi", "D'Agostino", "D'Alessandro", "D'Amico", "D'Angelo", "Daddi", "Dainelli", "Dallai", "Danti", "Davitti", "De Angelis", "De Luca", "De Marco", "De Rosa", "De Santis", "De Simone", "De Vita", "Degl'Innocenti", "Degli Innocenti", "Dei", "Del Lungo", "Del Re", "Di Marco", "Di Stefano", "Dini", "Diop", "Dobre", "Dolfi", "Donati", "Dondoli", "Dong", "Donnini", "Ducci", "Dumitru", "Ermini", "Esposito", "Evangelisti", "Fabbri", "Fabbrini", "Fabbrizzi", "Fabbroni", "Fabbrucci", "Fabiani", "Facchini", "Faggi", "Fagioli", "Failli", "Faini", "Falciani", "Falcini", "Falcone", "Fallani", "Falorni", "Falsini", "Falugiani", "Fancelli", "Fanelli", "Fanetti", "Fanfani", "Fani", "Fantappie'", "Fantechi", "Fanti", "Fantini", "Fantoni", "Farina", "Fattori", "Favilli", "Fedi", "Fei", "Ferrante", "Ferrara", "Ferrari", "Ferraro", "Ferretti", "Ferri", "Ferrini", "Ferroni", "Fiaschi", "Fibbi", "Fiesoli", "Filippi", "Filippini", "Fini", "Fioravanti", "Fiore", "Fiorentini", "Fiorini", "Fissi", "Focardi", "Foggi", "Fontana", "Fontanelli", "Fontani", "Forconi", "Formigli", "Forte", "Forti", "Fortini", "Fossati", "Fossi", "Francalanci", "Franceschi", "Franceschini", "Franchi", "Franchini", "Franci", "Francini", "Francioni", "Franco", "Frassineti", "Frati", "Fratini", "Frilli", "Frizzi", "Frosali", "Frosini", "Frullini", "Fusco", "Fusi", "Gabbrielli", "Gabellini", "Gagliardi", "Galanti", "Galardi", "Galeotti", "Galletti", "Galli", "Gallo", "Gallori", "Gambacciani", "Gargani", "Garofalo", "Garuglieri", "Gashi", "Gasperini", "Gatti", "Gelli", "Gensini", "Gentile", "Gentili", "Geri", "Gerini", "Gheri", "Ghini", "Giachetti", "Giachi", "Giacomelli", "Gianassi", "Giani", "Giannelli", "Giannetti", "Gianni", "Giannini", "Giannoni", "Giannotti", "Giannozzi", "Gigli", "Giordano", "Giorgetti", "Giorgi", "Giovacchini", "Giovannelli", "Giovannetti", "Giovannini", "Giovannoni", "Giuliani", "Giunti", "Giuntini", "Giusti", "Gonnelli", "Goretti", "Gori", "Gradi", "Gramigni", "Grassi", "Grasso", "Graziani", "Grazzini", "Greco", "Grifoni", "Grillo", "Grimaldi", "Grossi", "Gualtieri", "Guarducci", "Guarino", "Guarnieri", "Guasti", "Guerra", "Guerri", "Guerrini", "Guidi", "Guidotti", "He", "Hoxha", "Hu", "Huang", "Iandelli", "Ignesti", "Innocenti", "Jin", "La Rosa", "Lai", "Landi", "Landini", "Lanini", "Lapi", "Lapini", "Lari", "Lascialfari", "Lastrucci", "Latini", "Lazzeri", "Lazzerini", "Lelli", "Lenzi", "Leonardi", "Leoncini", "Leone", "Leoni", "Lepri", "Li", "Liao", "Lin", "Linari", "Lippi", "Lisi", "Livi", "Lombardi", "Lombardini", "Lombardo", "Longo", "Lopez", "Lorenzi", "Lorenzini", "Lorini", "Lotti", "Lu", "Lucchesi", "Lucherini", "Lunghi", "Lupi", "Madiai", "Maestrini", "Maffei", "Maggi", "Maggini", "Magherini", "Magini", "Magnani", "Magnelli", "Magni", "Magnolfi", "Magrini", "Malavolti", "Malevolti", "Manca", "Mancini", "Manetti", "Manfredi", "Mangani", "Mannelli", "Manni", "Mannini", "Mannucci", "Manuelli", "Manzini", "Marcelli", "Marchese", "Marchetti", "Marchi", "Marchiani", "Marchionni", "Marconi", "Marcucci", "Margheri", "Mari", "Mariani", "Marilli", "Marinai", "Marinari", "Marinelli", "Marini", "Marino", "Mariotti", "Marsili", "Martelli", "Martinelli", "Martini", "Martino", "Marzi", "Masi", "Masini", "Masoni", "Massai", "Materassi", "Mattei", "Matteini", "Matteucci", "Matteuzzi", "Mattioli", "Mattolini", "Matucci", "Mauro", "Mazzanti", "Mazzei", "Mazzetti", "Mazzi", "Mazzini", "Mazzocchi", "Mazzoli", "Mazzoni", "Mazzuoli", "Meacci", "Mecocci", "Meini", "Melani", "Mele", "Meli", "Mengoni", "Menichetti", "Meoni", "Merlini", "Messeri", "Messina", "Meucci", "Miccinesi", "Miceli", "Micheli", "Michelini", "Michelozzi", "Migliori", "Migliorini", "Milani", "Miniati", "Misuri", "Monaco", "Montagnani", "Montagni", "Montanari", "Montelatici", "Monti", "Montigiani", "Montini", "Morandi", "Morandini", "Morelli", "Moretti", "Morganti", "Mori", "Morini", "Moroni", "Morozzi", "Mugnai", "Mugnaini", "Mustafa", "Naldi", "Naldini", "Nannelli", "Nanni", "Nannini", "Nannucci", "Nardi", "Nardini", "Nardoni", "Natali", "Ndiaye", "Nencetti", "Nencini", "Nencioni", "Neri", "Nesi", "Nesti", "Niccolai", "Niccoli", "Niccolini", "Nigi", "Nistri", "Nocentini", "Noferini", "Novelli", "Nucci", "Nuti", "Nutini", "Oliva", "Olivieri", "Olmi", "Orlandi", "Orlandini", "Orlando", "Orsini", "Ortolani", "Ottanelli", "Pacciani", "Pace", "Paci", "Pacini", "Pagani", "Pagano", "Paggetti", "Pagliai", "Pagni", "Pagnini", "Paladini", "Palagi", "Palchetti", "Palloni", "Palmieri", "Palumbo", "Pampaloni", "Pancani", "Pandolfi", "Pandolfini", "Panerai", "Panichi", "Paoletti", "Paoli", "Paolini", "Papi", "Papini", "Papucci", "Parenti", "Parigi", "Parisi", "Parri", "Parrini", "Pasquini", "Passeri", "Pecchioli", "Pecorini", "Pellegrini", "Pepi", "Perini", "Perrone", "Peruzzi", "Pesci", "Pestelli", "Petri", "Petrini", "Petrucci", "Pettini", "Pezzati", "Pezzatini", "Piani", "Piazza", "Piazzesi", "Piazzini", "Piccardi", "Picchi", "Piccini", "Piccioli", "Pieraccini", "Pieraccioni", "Pieralli", "Pierattini", "Pieri", "Pierini", "Pieroni", "Pietrini", "Pini", "Pinna", "Pinto", "Pinzani", "Pinzauti", "Piras", "Pisani", "Pistolesi", "Poggesi", "Poggi", "Poggiali", "Poggiolini", "Poli", "Pollastri", "Porciani", "Pozzi", "Pratellesi", "Pratesi", "Prosperi", "Pruneti", "Pucci", "Puccini", "Puccioni", "Pugi", "Pugliese", "Puliti", "Querci", "Quercioli", "Raddi", "Radu", "Raffaelli", "Ragazzini", "Ranfagni", "Ranieri", "Rastrelli", "Raugei", "Raveggi", "Renai", "Renzi", "Rettori", "Ricci", "Ricciardi", "Ridi", "Ridolfi", "Rigacci", "Righi", "Righini", "Rinaldi", "Risaliti", "Ristori", "Rizzo", "Rocchi", "Rocchini", "Rogai", "Romagnoli", "Romanelli", "Romani", "Romano", "Romei", "Romeo", "Romiti", "Romoli", "Romolini", "Rontini", "Rosati", "Roselli", "Rosi", "Rossetti", "Rossi", "Rossini", "Rovai", "Ruggeri", "Ruggiero", "Russo", "Sabatini", "Saccardi", "Sacchetti", "Sacchi", "Sacco", "Salerno", "Salimbeni", "Salucci", "Salvadori", "Salvestrini", "Salvi", "Salvini", "Sanesi", "Sani", "Sanna", "Santi", "Santini", "Santoni", "Santoro", "Santucci", "Sardi", "Sarri", "Sarti", "Sassi", "Sbolci", "Scali", "Scarpelli", "Scarselli", "Scopetani", "Secci", "Selvi", "Senatori", "Senesi", "Serafini", "Sereni", "Serra", "Sestini", "Sguanci", "Sieni", "Signorini", "Silvestri", "Simoncini", "Simonetti", "Simoni", "Singh", "Sodi", "Soldi", "Somigli", "Sorbi", "Sorelli", "Sorrentino", "Sottili", "Spina", "Spinelli", "Staccioli", "Staderini", "Stefanelli", "Stefani", "Stefanini", "Stella", "Susini", "Tacchi", "Tacconi", "Taddei", "Tagliaferri", "Tamburini", "Tanganelli", "Tani", "Tanini", "Tapinassi", "Tarchi", "Tarchiani", "Targioni", "Tassi", "Tassini", "Tempesti", "Terzani", "Tesi", "Testa", "Testi", "Tilli", "Tinti", "Tirinnanzi", "Toccafondi", "Tofanari", "Tofani", "Tognaccini", "Tonelli", "Tonini", "Torelli", "Torrini", "Tosi", "Toti", "Tozzi", "Trambusti", "Trapani", "Tucci", "Turchi", "Ugolini", "Ulivi", "Valente", "Valenti", "Valentini", "Vangelisti", "Vanni", "Vannini", "Vannoni", "Vannozzi", "Vannucchi", "Vannucci", "Ventura", "Venturi", "Venturini", "Vestri", "Vettori", "Vichi", "Viciani", "Vieri", "Vigiani", "Vignoli", "Vignolini", "Vignozzi", "Villani", "Vinci", "Visani", "Vitale", "Vitali", "Viti", "Viviani", "Vivoli", "Volpe", "Volpi", "Wang", "Wu", "Xu", "Yang", "Ye", "Zagli", "Zani", "Zanieri", "Zanobini", "Zecchi", "Zetti", "Zhang", "Zheng", "Zhou", "Zhu", "Zingoni", "Zini", "Zoppi"], + // http://www.voornamelijk.nl/meest-voorkomende-achternamen-in-nederland-en-amsterdam/ + "nl":["Albers", "Alblas", "Appelman", "Baars", "Baas", "Bakker", "Blank", "Bleeker", "Blok", "Blom", "Boer", "Boers", "Boldewijn", "Boon", "Boot", "Bos", "Bosch", "Bosma", "Bosman", "Bouma", "Bouman", "Bouwman", "Brands", "Brouwer", "Burger", "Buijs", "Buitenhuis", "Ceder", "Cohen", "Dekker", "Dekkers", "Dijkman", "Dijkstra", "Driessen", "Drost", "Engel", "Evers", "Faber", "Franke", "Gerritsen", "Goedhart", "Goossens", "Groen", "Groenenberg", "Groot", "Haan", "Hart", "Heemskerk", "Hendriks", "Hermans", "Hoekstra", "Hofman", "Hopman", "Huisman", "Jacobs", "Jansen", "Janssen", "Jonker", "Jaspers", "Keijzer", "Klaassen", "Klein", "Koek", "Koenders", "Kok", "Kool", "Koopman", "Koopmans", "Koning", "Koster", "Kramer", "Kroon", "Kuijpers", "Kuiper", "Kuipers", "Kurt", "Koster", "Kwakman", "Los", "Lubbers", "Maas", "Markus", "Martens", "Meijer", "Mol", "Molenaar", "Mulder", "Nieuwenhuis", "Peeters", "Peters", "Pengel", "Pieters", "Pool", "Post", "Postma", "Prins", "Pronk", "Reijnders", "Rietveld", "Roest", "Roos", "Sanders", "Schaap", "Scheffer", "Schenk", "Schilder", "Schipper", "Schmidt", "Scholten", "Schouten", "Schut", "Schutte", "Schuurman", "Simons", "Smeets", "Smit", "Smits", "Snel", "Swinkels", "Tas", "Terpstra", "Timmermans", "Tol", "Tromp", "Troost", "Valk", "Veenstra", "Veldkamp", "Verbeek", "Verheul", "Verhoeven", "Vermeer", "Vermeulen", "Verweij", "Vink", "Visser", "Voorn", "Vos", "Wagenaar", "Wiersema", "Willems", "Willemsen", "Witteveen", "Wolff", "Wolters", "Zijlstra", "Zwart", "de Beer", "de Boer", "de Bruijn", "de Bruin", "de Graaf", "de Groot", "de Haan", "de Haas", "de Jager", "de Jong", "de Jonge", "de Koning", "de Lange", "de Leeuw", "de Ridder", "de Rooij", "de Ruiter", "de Vos", "de Vries", "de Waal", "de Wit", "de Zwart", "van Beek", "van Boven", "van Dam", "van Dijk", "van Dongen", "van Doorn", "van Egmond", "van Eijk", "van Es", "van Gelder", "van Gelderen", "van Houten", "van Hulst", "van Kempen", "van Kesteren", "van Leeuwen", "van Loon", "van Mill", "van Noord", "van Ommen", "van Ommeren", "van Oosten", "van Oostveen", "van Rijn", "van Schaik", "van Veen", "van Vliet", "van Wijk", "van Wijngaarden", "van den Poel", "van de Pol", "van den Ploeg", "van de Ven", "van den Berg", "van den Bosch", "van den Brink", "van den Broek", "van den Heuvel", "van der Heijden", "van der Horst", "van der Hulst", "van der Kroon", "van der Laan", "van der Linden", "van der Meer", "van der Meij", "van der Meulen", "van der Molen", "van der Sluis", "van der Spek", "van der Veen", "van der Velde", "van der Velden", "van der Vliet", "van der Wal"], + // https://surnames.behindthename.com/top/lists/england-wales/1991 + "uk":["Smith","Jones","Williams","Taylor","Brown","Davies","Evans","Wilson","Thomas","Johnson","Roberts","Robinson","Thompson","Wright","Walker","White","Edwards","Hughes","Green","Hall","Lewis","Harris","Clarke","Patel","Jackson","Wood","Turner","Martin","Cooper","Hill","Ward","Morris","Moore","Clark","Lee","King","Baker","Harrison","Morgan","Allen","James","Scott","Phillips","Watson","Davis","Parker","Price","Bennett","Young","Griffiths","Mitchell","Kelly","Cook","Carter","Richardson","Bailey","Collins","Bell","Shaw","Murphy","Miller","Cox","Richards","Khan","Marshall","Anderson","Simpson","Ellis","Adams","Singh","Begum","Wilkinson","Foster","Chapman","Powell","Webb","Rogers","Gray","Mason","Ali","Hunt","Hussain","Campbell","Matthews","Owen","Palmer","Holmes","Mills","Barnes","Knight","Lloyd","Butler","Russell","Barker","Fisher","Stevens","Jenkins","Murray","Dixon","Harvey","Graham","Pearson","Ahmed","Fletcher","Walsh","Kaur","Gibson","Howard","Andrews","Stewart","Elliott","Reynolds","Saunders","Payne","Fox","Ford","Pearce","Day","Brooks","West","Lawrence","Cole","Atkinson","Bradley","Spencer","Gill","Dawson","Ball","Burton","O'brien","Watts","Rose","Booth","Perry","Ryan","Grant","Wells","Armstrong","Francis","Rees","Hayes","Hart","Hudson","Newman","Barrett","Webster","Hunter","Gregory","Carr","Lowe","Page","Marsh","Riley","Dunn","Woods","Parsons","Berry","Stone","Reid","Holland","Hawkins","Harding","Porter","Robertson","Newton","Oliver","Reed","Kennedy","Williamson","Bird","Gardner","Shah","Dean","Lane","Cooke","Bates","Henderson","Parry","Burgess","Bishop","Walton","Burns","Nicholson","Shepherd","Ross","Cross","Long","Freeman","Warren","Nicholls","Hamilton","Byrne","Sutton","Mcdonald","Yates","Hodgson","Robson","Curtis","Hopkins","O'connor","Harper","Coleman","Watkins","Moss","Mccarthy","Chambers","O'neill","Griffin","Sharp","Hardy","Wheeler","Potter","Osborne","Johnston","Gordon","Doyle","Wallace","George","Jordan","Hutchinson","Rowe","Burke","May","Pritchard","Gilbert","Willis","Higgins","Read","Miles","Stevenson","Stephenson","Hammond","Arnold","Buckley","Walters","Hewitt","Barber","Nelson","Slater","Austin","Sullivan","Whitehead","Mann","Frost","Lambert","Stephens","Blake","Akhtar","Lynch","Goodwin","Barton","Woodward","Thomson","Cunningham","Quinn","Barnett","Baxter","Bibi","Clayton","Nash","Greenwood","Jennings","Holt","Kemp","Poole","Gallagher","Bond","Stokes","Tucker","Davidson","Fowler","Heath","Norman","Middleton","Lawson","Banks","French","Stanley","Jarvis","Gibbs","Ferguson","Hayward","Carroll","Douglas","Dickinson","Todd","Barlow","Peters","Lucas","Knowles","Hartley","Miah","Simmons","Morton","Alexander","Field","Morrison","Norris","Townsend","Preston","Hancock","Thornton","Baldwin","Burrows","Briggs","Parkinson","Reeves","Macdonald","Lamb","Black","Abbott","Sanders","Thorpe","Holden","Tomlinson","Perkins","Ashton","Rhodes","Fuller","Howe","Bryant","Vaughan","Dale","Davey","Weston","Bartlett","Whittaker","Davison","Kent","Skinner","Birch","Morley","Daniels","Glover","Howell","Cartwright","Pugh","Humphreys","Goddard","Brennan","Wall","Kirby","Bowen","Savage","Bull","Wong","Dobson","Smart","Wilkins","Kirk","Fraser","Duffy","Hicks","Patterson","Bradshaw","Little","Archer","Warner","Waters","O'sullivan","Farrell","Brookes","Atkins","Kay","Dodd","Bentley","Flynn","John","Schofield","Short","Haynes","Wade","Butcher","Henry","Sanderson","Crawford","Sheppard","Bolton","Coates","Giles","Gould","Houghton","Gibbons","Pratt","Manning","Law","Hooper","Noble","Dyer","Rahman","Clements","Moran","Sykes","Chan","Doherty","Connolly","Joyce","Franklin","Hobbs","Coles","Herbert","Steele","Kerr","Leach","Winter","Owens","Duncan","Naylor","Fleming","Horton","Finch","Fitzgerald","Randall","Carpenter","Marsden","Browne","Garner","Pickering","Hale","Dennis","Vincent","Chadwick","Chandler","Sharpe","Nolan","Lyons","Hurst","Collier","Peacock","Howarth","Faulkner","Rice","Pollard","Welch","Norton","Gough","Sinclair","Blackburn","Bryan","Conway","Power","Cameron","Daly","Allan","Hanson","Gardiner","Boyle","Myers","Turnbull","Wallis","Mahmood","Sims","Swift","Iqbal","Pope","Brady","Chamberlain","Rowley","Tyler","Farmer","Metcalfe","Hilton","Godfrey","Holloway","Parkin","Bray","Talbot","Donnelly","Nixon","Charlton","Benson","Whitehouse","Barry","Hope","Lord","North","Storey","Connor","Potts","Bevan","Hargreaves","Mclean","Mistry","Bruce","Howells","Hyde","Parkes","Wyatt","Fry","Lees","O'donnell","Craig","Forster","Mckenzie","Humphries","Mellor","Carey","Ingram","Summers","Leonard"], + // https://surnames.behindthename.com/top/lists/germany/2017 + "de": ["Müller","Schmidt","Schneider","Fischer","Weber","Meyer","Wagner","Becker","Schulz","Hoffmann","SchƤfer","Koch","Bauer","Richter","Klein","Wolf","Schrƶder","Neumann","Schwarz","Zimmermann","Braun","Krüger","Hofmann","Hartmann","Lange","Schmitt","Werner","Schmitz","Krause","Meier","Lehmann","Schmid","Schulze","Maier","Kƶhler","Herrmann","Kƶnig","Walter","Mayer","Huber","Kaiser","Fuchs","Peters","Lang","Scholz","Mƶller","Weiß","Jung","Hahn","Schubert","Vogel","Friedrich","Keller","Günther","Frank","Berger","Winkler","Roth","Beck","Lorenz","Baumann","Franke","Albrecht","Schuster","Simon","Ludwig","Bƶhm","Winter","Kraus","Martin","Schumacher","KrƤmer","Vogt","Stein","JƤger","Otto","Sommer","Groß","Seidel","Heinrich","Brandt","Haas","Schreiber","Graf","Schulte","Dietrich","Ziegler","Kuhn","Kühn","Pohl","Engel","Horn","Busch","Bergmann","Thomas","Voigt","Sauer","Arnold","Wolff","Pfeiffer"], + // http://www.japantimes.co.jp/life/2009/10/11/lifestyle/japans-top-100-most-common-family-names/ + "jp": ["Sato","Suzuki","Takahashi","Tanaka","Watanabe","Ito","Yamamoto","Nakamura","Kobayashi","Kato","Yoshida","Yamada","Sasaki","Yamaguchi","Saito","Matsumoto","Inoue","Kimura","Hayashi","Shimizu","Yamazaki","Mori","Abe","Ikeda","Hashimoto","Yamashita","Ishikawa","Nakajima","Maeda","Fujita","Ogawa","Goto","Okada","Hasegawa","Murakami","Kondo","Ishii","Saito","Sakamoto","Endo","Aoki","Fujii","Nishimura","Fukuda","Ota","Miura","Fujiwara","Okamoto","Matsuda","Nakagawa","Nakano","Harada","Ono","Tamura","Takeuchi","Kaneko","Wada","Nakayama","Ishida","Ueda","Morita","Hara","Shibata","Sakai","Kudo","Yokoyama","Miyazaki","Miyamoto","Uchida","Takagi","Ando","Taniguchi","Ohno","Maruyama","Imai","Takada","Fujimoto","Takeda","Murata","Ueno","Sugiyama","Masuda","Sugawara","Hirano","Kojima","Otsuka","Chiba","Kubo","Matsui","Iwasaki","Sakurai","Kinoshita","Noguchi","Matsuo","Nomura","Kikuchi","Sano","Onishi","Sugimoto","Arai"], + // http://www.lowchensaustralia.com/names/popular-spanish-names.htm + "es": ["Garcia","Fernandez","Lopez","Martinez","Gonzalez","Rodriguez","Sanchez","Perez","Martin","Gomez","Ruiz","Diaz","Hernandez","Alvarez","Jimenez","Moreno","Munoz","Alonso","Romero","Navarro","Gutierrez","Torres","Dominguez","Gil","Vazquez","Blanco","Serrano","Ramos","Castro","Suarez","Sanz","Rubio","Ortega","Molina","Delgado","Ortiz","Morales","Ramirez","Marin","Iglesias","Santos","Castillo","Garrido","Calvo","Pena","Cruz","Cano","Nunez","Prieto","Diez","Lozano","Vidal","Pascual","Ferrer","Medina","Vega","Leon","Herrero","Vicente","Mendez","Guerrero","Fuentes","Campos","Nieto","Cortes","Caballero","Ibanez","Lorenzo","Pastor","Gimenez","Saez","Soler","Marquez","Carrasco","Herrera","Montero","Arias","Crespo","Flores","Andres","Aguilar","Hidalgo","Cabrera","Mora","Duran","Velasco","Rey","Pardo","Roman","Vila","Bravo","Merino","Moya","Soto","Izquierdo","Reyes","Redondo","Marcos","Carmona","Menendez"], + // Data taken from https://fr.wikipedia.org/wiki/Liste_des_noms_de_famille_les_plus_courants_en_France + "fr": ["Martin","Bernard","Thomas","Petit","Robert","Richard","Durand","Dubois","Moreau","Laurent","Simon","Michel","LefĆØvre","Leroy","Roux","David","Bertrand","Morel","Fournier","Girard","Bonnet","Dupont","Lambert","Fontaine","Rousseau","Vincent","Müller","LefĆØvre","Faure","AndrĆ©","Mercier","Blanc","GuĆ©rin","Boyer","Garnier","Chevalier","FranƧois","Legrand","Gauthier","Garcia","Perrin","Robin","ClĆ©ment","Morin","Nicolas","Henry","Roussel","Matthieu","Gautier","Masson","Marchand","Duval","Denis","Dumont","Marie","Lemaire","NoĆ«l","Meyer","Dufour","Meunier","Brun","Blanchard","Giraud","Joly","RiviĆØre","Lucas","Brunet","Gaillard","Barbier","Arnaud","MartĆ­nez","GĆ©rard","Roche","Renard","Schmitt","Roy","Leroux","Colin","Vidal","Caron","Picard","Roger","Fabre","Aubert","Lemoine","Renaud","Dumas","Lacroix","Olivier","Philippe","Bourgeois","Pierre","BenoĆ®t","Rey","Leclerc","Payet","Rolland","Leclercq","Guillaume","Lecomte","López","Jean","Dupuy","Guillot","Hubert","Berger","Carpentier","SĆ”nchez","Dupuis","Moulin","Louis","Deschamps","Huet","Vasseur","Perez","Boucher","Fleury","Royer","Klein","Jacquet","Adam","Paris","Poirier","Marty","Aubry","Guyot","CarrĆ©","Charles","Renault","Charpentier","MĆ©nard","Maillard","Baron","Bertin","Bailly","HervĆ©","Schneider","FernĆ”ndez","Le GallGall","Collet","LĆ©ger","Bouvier","Julien","PrĆ©vost","Millet","Perrot","Daniel","Le RouxRoux","Cousin","Germain","Breton","Besson","Langlois","RĆ©mi","Le GoffGoff","Pelletier","LĆ©vĆŖque","Perrier","Leblanc","BarrĆ©","Lebrun","Marchal","Weber","Mallet","Hamon","Boulanger","Jacob","Monnier","Michaud","RodrĆ­guez","Guichard","Gillet","Ɖtienne","Grondin","Poulain","Tessier","Chevallier","Collin","Chauvin","Da SilvaSilva","Bouchet","Gay","LemaĆ®tre","BĆ©nard","MarĆ©chal","Humbert","Reynaud","Antoine","Hoarau","Perret","BarthĆ©lemy","Cordier","Pichon","Lejeune","Gilbert","Lamy","Delaunay","Pasquier","Carlier","LaporteLaporte"] + }, - if (this._sessionCache.size >= this._maxCachedSessions) { - // remove the oldest session - const { value: oldestKey } = this._sessionCache.keys().next() - this._sessionCache.delete(oldestKey) - } + // Data taken from http://geoportal.statistics.gov.uk/datasets/ons-postcode-directory-latest-centroids + postcodeAreas: [{code: 'AB'}, {code: 'AL'}, {code: 'B'}, {code: 'BA'}, {code: 'BB'}, {code: 'BD'}, {code: 'BH'}, {code: 'BL'}, {code: 'BN'}, {code: 'BR'}, {code: 'BS'}, {code: 'BT'}, {code: 'CA'}, {code: 'CB'}, {code: 'CF'}, {code: 'CH'}, {code: 'CM'}, {code: 'CO'}, {code: 'CR'}, {code: 'CT'}, {code: 'CV'}, {code: 'CW'}, {code: 'DA'}, {code: 'DD'}, {code: 'DE'}, {code: 'DG'}, {code: 'DH'}, {code: 'DL'}, {code: 'DN'}, {code: 'DT'}, {code: 'DY'}, {code: 'E'}, {code: 'EC'}, {code: 'EH'}, {code: 'EN'}, {code: 'EX'}, {code: 'FK'}, {code: 'FY'}, {code: 'G'}, {code: 'GL'}, {code: 'GU'}, {code: 'GY'}, {code: 'HA'}, {code: 'HD'}, {code: 'HG'}, {code: 'HP'}, {code: 'HR'}, {code: 'HS'}, {code: 'HU'}, {code: 'HX'}, {code: 'IG'}, {code: 'IM'}, {code: 'IP'}, {code: 'IV'}, {code: 'JE'}, {code: 'KA'}, {code: 'KT'}, {code: 'KW'}, {code: 'KY'}, {code: 'L'}, {code: 'LA'}, {code: 'LD'}, {code: 'LE'}, {code: 'LL'}, {code: 'LN'}, {code: 'LS'}, {code: 'LU'}, {code: 'M'}, {code: 'ME'}, {code: 'MK'}, {code: 'ML'}, {code: 'N'}, {code: 'NE'}, {code: 'NG'}, {code: 'NN'}, {code: 'NP'}, {code: 'NR'}, {code: 'NW'}, {code: 'OL'}, {code: 'OX'}, {code: 'PA'}, {code: 'PE'}, {code: 'PH'}, {code: 'PL'}, {code: 'PO'}, {code: 'PR'}, {code: 'RG'}, {code: 'RH'}, {code: 'RM'}, {code: 'S'}, {code: 'SA'}, {code: 'SE'}, {code: 'SG'}, {code: 'SK'}, {code: 'SL'}, {code: 'SM'}, {code: 'SN'}, {code: 'SO'}, {code: 'SP'}, {code: 'SR'}, {code: 'SS'}, {code: 'ST'}, {code: 'SW'}, {code: 'SY'}, {code: 'TA'}, {code: 'TD'}, {code: 'TF'}, {code: 'TN'}, {code: 'TQ'}, {code: 'TR'}, {code: 'TS'}, {code: 'TW'}, {code: 'UB'}, {code: 'W'}, {code: 'WA'}, {code: 'WC'}, {code: 'WD'}, {code: 'WF'}, {code: 'WN'}, {code: 'WR'}, {code: 'WS'}, {code: 'WV'}, {code: 'YO'}, {code: 'ZE'}], - this._sessionCache.set(sessionKey, session) - } - } -} + // Data taken from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 + countries: [{"name":"Afghanistan","abbreviation":"AF"},{"name":"ƅland Islands","abbreviation":"AX"},{"name":"Albania","abbreviation":"AL"},{"name":"Algeria","abbreviation":"DZ"},{"name":"American Samoa","abbreviation":"AS"},{"name":"Andorra","abbreviation":"AD"},{"name":"Angola","abbreviation":"AO"},{"name":"Anguilla","abbreviation":"AI"},{"name":"Antarctica","abbreviation":"AQ"},{"name":"Antigua and Barbuda","abbreviation":"AG"},{"name":"Argentina","abbreviation":"AR"},{"name":"Armenia","abbreviation":"AM"},{"name":"Aruba","abbreviation":"AW"},{"name":"Australia","abbreviation":"AU"},{"name":"Austria","abbreviation":"AT"},{"name":"Azerbaijan","abbreviation":"AZ"},{"name":"Bahamas","abbreviation":"BS"},{"name":"Bahrain","abbreviation":"BH"},{"name":"Bangladesh","abbreviation":"BD"},{"name":"Barbados","abbreviation":"BB"},{"name":"Belarus","abbreviation":"BY"},{"name":"Belgium","abbreviation":"BE"},{"name":"Belize","abbreviation":"BZ"},{"name":"Benin","abbreviation":"BJ"},{"name":"Bermuda","abbreviation":"BM"},{"name":"Bhutan","abbreviation":"BT"},{"name":"Plurinational State of Bolivia","abbreviation":"BO"},{"name":"Bonaire, Sint Eustatius and Saba","abbreviation":"BQ"},{"name":"Bosnia and Herzegovina","abbreviation":"BA"},{"name":"Botswana","abbreviation":"BW"},{"name":"Bouvet Island","abbreviation":"BV"},{"name":"Brazil","abbreviation":"BR"},{"name":"British Indian Ocean Territory","abbreviation":"IO"},{"name":"Brunei Darussalam","abbreviation":"BN"},{"name":"Bulgaria","abbreviation":"BG"},{"name":"Burkina Faso","abbreviation":"BF"},{"name":"Burundi","abbreviation":"BI"},{"name":"Cabo Verde","abbreviation":"CV"},{"name":"Cambodia","abbreviation":"KH"},{"name":"Cameroon","abbreviation":"CM"},{"name":"Canada","abbreviation":"CA"},{"name":"Cayman Islands","abbreviation":"KY"},{"name":"Central African Republic","abbreviation":"CF"},{"name":"Chad","abbreviation":"TD"},{"name":"Chile","abbreviation":"CL"},{"name":"China","abbreviation":"CN"},{"name":"Christmas Island","abbreviation":"CX"},{"name":"Cocos (Keeling) Islands","abbreviation":"CC"},{"name":"Colombia","abbreviation":"CO"},{"name":"Comoros","abbreviation":"KM"},{"name":"Congo","abbreviation":"CG"},{"name":"Democratic Republic of the Congo","abbreviation":"CD"},{"name":"Cook Islands","abbreviation":"CK"},{"name":"Costa Rica","abbreviation":"CR"},{"name":"CĆ“te d'Ivoire","abbreviation":"CI"},{"name":"Croatia","abbreviation":"HR"},{"name":"Cuba","abbreviation":"CU"},{"name":"CuraƧao","abbreviation":"CW"},{"name":"Cyprus","abbreviation":"CY"},{"name":"Czechia","abbreviation":"CZ"},{"name":"Denmark","abbreviation":"DK"},{"name":"Djibouti","abbreviation":"DJ"},{"name":"Dominica","abbreviation":"DM"},{"name":"Dominican Republic","abbreviation":"DO"},{"name":"Ecuador","abbreviation":"EC"},{"name":"Egypt","abbreviation":"EG"},{"name":"El Salvador","abbreviation":"SV"},{"name":"Equatorial Guinea","abbreviation":"GQ"},{"name":"Eritrea","abbreviation":"ER"},{"name":"Estonia","abbreviation":"EE"},{"name":"Eswatini","abbreviation":"SZ"},{"name":"Ethiopia","abbreviation":"ET"},{"name":"Falkland Islands (Malvinas)","abbreviation":"FK"},{"name":"Faroe Islands","abbreviation":"FO"},{"name":"Fiji","abbreviation":"FJ"},{"name":"Finland","abbreviation":"FI"},{"name":"France","abbreviation":"FR"},{"name":"French Guiana","abbreviation":"GF"},{"name":"French Polynesia","abbreviation":"PF"},{"name":"French Southern Territories","abbreviation":"TF"},{"name":"Gabon","abbreviation":"GA"},{"name":"Gambia","abbreviation":"GM"},{"name":"Georgia","abbreviation":"GE"},{"name":"Germany","abbreviation":"DE"},{"name":"Ghana","abbreviation":"GH"},{"name":"Gibraltar","abbreviation":"GI"},{"name":"Greece","abbreviation":"GR"},{"name":"Greenland","abbreviation":"GL"},{"name":"Grenada","abbreviation":"GD"},{"name":"Guadeloupe","abbreviation":"GP"},{"name":"Guam","abbreviation":"GU"},{"name":"Guatemala","abbreviation":"GT"},{"name":"Guernsey","abbreviation":"GG"},{"name":"Guinea","abbreviation":"GN"},{"name":"Guinea-Bissau","abbreviation":"GW"},{"name":"Guyana","abbreviation":"GY"},{"name":"Haiti","abbreviation":"HT"},{"name":"Heard Island and McDonald Islands","abbreviation":"HM"},{"name":"Holy See","abbreviation":"VA"},{"name":"Honduras","abbreviation":"HN"},{"name":"Hong Kong","abbreviation":"HK"},{"name":"Hungary","abbreviation":"HU"},{"name":"Iceland","abbreviation":"IS"},{"name":"India","abbreviation":"IN"},{"name":"Indonesia","abbreviation":"ID"},{"name":"Islamic Republic of Iran","abbreviation":"IR"},{"name":"Iraq","abbreviation":"IQ"},{"name":"Ireland","abbreviation":"IE"},{"name":"Isle of Man","abbreviation":"IM"},{"name":"Israel","abbreviation":"IL"},{"name":"Italy","abbreviation":"IT"},{"name":"Jamaica","abbreviation":"JM"},{"name":"Japan","abbreviation":"JP"},{"name":"Jersey","abbreviation":"JE"},{"name":"Jordan","abbreviation":"JO"},{"name":"Kazakhstan","abbreviation":"KZ"},{"name":"Kenya","abbreviation":"KE"},{"name":"Kiribati","abbreviation":"KI"},{"name":"Democratic People's Republic of Korea","abbreviation":"KP"},{"name":"Republic of Korea","abbreviation":"KR"},{"name":"Kuwait","abbreviation":"KW"},{"name":"Kyrgyzstan","abbreviation":"KG"},{"name":"Lao People's Democratic Republic","abbreviation":"LA"},{"name":"Latvia","abbreviation":"LV"},{"name":"Lebanon","abbreviation":"LB"},{"name":"Lesotho","abbreviation":"LS"},{"name":"Liberia","abbreviation":"LR"},{"name":"Libya","abbreviation":"LY"},{"name":"Liechtenstein","abbreviation":"LI"},{"name":"Lithuania","abbreviation":"LT"},{"name":"Luxembourg","abbreviation":"LU"},{"name":"Macao","abbreviation":"MO"},{"name":"Madagascar","abbreviation":"MG"},{"name":"Malawi","abbreviation":"MW"},{"name":"Malaysia","abbreviation":"MY"},{"name":"Maldives","abbreviation":"MV"},{"name":"Mali","abbreviation":"ML"},{"name":"Malta","abbreviation":"MT"},{"name":"Marshall Islands","abbreviation":"MH"},{"name":"Martinique","abbreviation":"MQ"},{"name":"Mauritania","abbreviation":"MR"},{"name":"Mauritius","abbreviation":"MU"},{"name":"Mayotte","abbreviation":"YT"},{"name":"Mexico","abbreviation":"MX"},{"name":"Federated States of Micronesia","abbreviation":"FM"},{"name":"Republic of Moldova","abbreviation":"MD"},{"name":"Monaco","abbreviation":"MC"},{"name":"Mongolia","abbreviation":"MN"},{"name":"Montenegro","abbreviation":"ME"},{"name":"Montserrat","abbreviation":"MS"},{"name":"Morocco","abbreviation":"MA"},{"name":"Mozambique","abbreviation":"MZ"},{"name":"Myanmar","abbreviation":"MM"},{"name":"Namibia","abbreviation":"NA"},{"name":"Nauru","abbreviation":"NR"},{"name":"Nepal","abbreviation":"NP"},{"name":"Kingdom of the Netherlands","abbreviation":"NL"},{"name":"New Caledonia","abbreviation":"NC"},{"name":"New Zealand","abbreviation":"NZ"},{"name":"Nicaragua","abbreviation":"NI"},{"name":"Niger","abbreviation":"NE"},{"name":"Nigeria","abbreviation":"NG"},{"name":"Niue","abbreviation":"NU"},{"name":"Norfolk Island","abbreviation":"NF"},{"name":"North Macedonia","abbreviation":"MK"},{"name":"Northern Mariana Islands","abbreviation":"MP"},{"name":"Norway","abbreviation":"NO"},{"name":"Oman","abbreviation":"OM"},{"name":"Pakistan","abbreviation":"PK"},{"name":"Palau","abbreviation":"PW"},{"name":"State of Palestine","abbreviation":"PS"},{"name":"Panama","abbreviation":"PA"},{"name":"Papua New Guinea","abbreviation":"PG"},{"name":"Paraguay","abbreviation":"PY"},{"name":"Peru","abbreviation":"PE"},{"name":"Philippines","abbreviation":"PH"},{"name":"Pitcairn","abbreviation":"PN"},{"name":"Poland","abbreviation":"PL"},{"name":"Portugal","abbreviation":"PT"},{"name":"Puerto Rico","abbreviation":"PR"},{"name":"Qatar","abbreviation":"QA"},{"name":"RĆ©union","abbreviation":"RE"},{"name":"Romania","abbreviation":"RO"},{"name":"Russian Federation","abbreviation":"RU"},{"name":"Rwanda","abbreviation":"RW"},{"name":"Saint BarthĆ©lemy","abbreviation":"BL"},{"name":"Saint Helena, Ascension and Tristan da Cunha","abbreviation":"SH"},{"name":"Saint Kitts and Nevis","abbreviation":"KN"},{"name":"Saint Lucia","abbreviation":"LC"},{"name":"Saint Martin (French part)","abbreviation":"MF"},{"name":"Saint Pierre and Miquelon","abbreviation":"PM"},{"name":"Saint Vincent and the Grenadines","abbreviation":"VC"},{"name":"Samoa","abbreviation":"WS"},{"name":"San Marino","abbreviation":"SM"},{"name":"Sao Tome and Principe","abbreviation":"ST"},{"name":"Saudi Arabia","abbreviation":"SA"},{"name":"Senegal","abbreviation":"SN"},{"name":"Serbia","abbreviation":"RS"},{"name":"Seychelles","abbreviation":"SC"},{"name":"Sierra Leone","abbreviation":"SL"},{"name":"Singapore","abbreviation":"SG"},{"name":"Sint Maarten (Dutch part)","abbreviation":"SX"},{"name":"Slovakia","abbreviation":"SK"},{"name":"Slovenia","abbreviation":"SI"},{"name":"Solomon Islands","abbreviation":"SB"},{"name":"Somalia","abbreviation":"SO"},{"name":"South Africa","abbreviation":"ZA"},{"name":"South Georgia and the South Sandwich Islands","abbreviation":"GS"},{"name":"South Sudan","abbreviation":"SS"},{"name":"Spain","abbreviation":"ES"},{"name":"Sri Lanka","abbreviation":"LK"},{"name":"Sudan","abbreviation":"SD"},{"name":"Suriname","abbreviation":"SR"},{"name":"Svalbard and Jan Mayen","abbreviation":"SJ"},{"name":"Sweden","abbreviation":"SE"},{"name":"Switzerland","abbreviation":"CH"},{"name":"Syrian Arab Republic","abbreviation":"SY"},{"name":"Taiwan, Province of China","abbreviation":"TW"},{"name":"Tajikistan","abbreviation":"TJ"},{"name":"United Republic of Tanzania","abbreviation":"TZ"},{"name":"Thailand","abbreviation":"TH"},{"name":"Timor-Leste","abbreviation":"TL"},{"name":"Togo","abbreviation":"TG"},{"name":"Tokelau","abbreviation":"TK"},{"name":"Tonga","abbreviation":"TO"},{"name":"Trinidad and Tobago","abbreviation":"TT"},{"name":"Tunisia","abbreviation":"TN"},{"name":"Türkiye","abbreviation":"TR"},{"name":"Turkmenistan","abbreviation":"TM"},{"name":"Turks and Caicos Islands","abbreviation":"TC"},{"name":"Tuvalu","abbreviation":"TV"},{"name":"Uganda","abbreviation":"UG"},{"name":"Ukraine","abbreviation":"UA"},{"name":"United Arab Emirates","abbreviation":"AE"},{"name":"United Kingdom of Great Britain and Northern Ireland","abbreviation":"GB"},{"name":"United States Minor Outlying Islands","abbreviation":"UM"},{"name":"United States of America","abbreviation":"US"},{"name":"Uruguay","abbreviation":"UY"},{"name":"Uzbekistan","abbreviation":"UZ"},{"name":"Vanuatu","abbreviation":"VU"},{"name":"Bolivarian Republic of Venezuela","abbreviation":"VE"},{"name":"Viet Nam","abbreviation":"VN"},{"name":"Virgin Islands (British)","abbreviation":"VG"},{"name":"Virgin Islands (U.S.)","abbreviation":"VI"},{"name":"Wallis and Futuna","abbreviation":"WF"},{"name":"Western Sahara","abbreviation":"EH"},{"name":"Yemen","abbreviation":"YE"},{"name":"Zambia","abbreviation":"ZM"},{"name":"Zimbabwe","abbreviation":"ZW"}], -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') - } + counties: { + // Data taken from http://www.downloadexcelfiles.com/gb_en/download-excel-file-list-counties-uk + "uk": [ + {name: 'Bath and North East Somerset'}, + {name: 'Aberdeenshire'}, + {name: 'Anglesey'}, + {name: 'Angus'}, + {name: 'Bedford'}, + {name: 'Blackburn with Darwen'}, + {name: 'Blackpool'}, + {name: 'Bournemouth'}, + {name: 'Bracknell Forest'}, + {name: 'Brighton & Hove'}, + {name: 'Bristol'}, + {name: 'Buckinghamshire'}, + {name: 'Cambridgeshire'}, + {name: 'Carmarthenshire'}, + {name: 'Central Bedfordshire'}, + {name: 'Ceredigion'}, + {name: 'Cheshire East'}, + {name: 'Cheshire West and Chester'}, + {name: 'Clackmannanshire'}, + {name: 'Conwy'}, + {name: 'Cornwall'}, + {name: 'County Antrim'}, + {name: 'County Armagh'}, + {name: 'County Down'}, + {name: 'County Durham'}, + {name: 'County Fermanagh'}, + {name: 'County Londonderry'}, + {name: 'County Tyrone'}, + {name: 'Cumbria'}, + {name: 'Darlington'}, + {name: 'Denbighshire'}, + {name: 'Derby'}, + {name: 'Derbyshire'}, + {name: 'Devon'}, + {name: 'Dorset'}, + {name: 'Dumfries and Galloway'}, + {name: 'Dundee'}, + {name: 'East Lothian'}, + {name: 'East Riding of Yorkshire'}, + {name: 'East Sussex'}, + {name: 'Edinburgh?'}, + {name: 'Essex'}, + {name: 'Falkirk'}, + {name: 'Fife'}, + {name: 'Flintshire'}, + {name: 'Gloucestershire'}, + {name: 'Greater London'}, + {name: 'Greater Manchester'}, + {name: 'Gwent'}, + {name: 'Gwynedd'}, + {name: 'Halton'}, + {name: 'Hampshire'}, + {name: 'Hartlepool'}, + {name: 'Herefordshire'}, + {name: 'Hertfordshire'}, + {name: 'Highlands'}, + {name: 'Hull'}, + {name: 'Isle of Wight'}, + {name: 'Isles of Scilly'}, + {name: 'Kent'}, + {name: 'Lancashire'}, + {name: 'Leicester'}, + {name: 'Leicestershire'}, + {name: 'Lincolnshire'}, + {name: 'Lothian'}, + {name: 'Luton'}, + {name: 'Medway'}, + {name: 'Merseyside'}, + {name: 'Mid Glamorgan'}, + {name: 'Middlesbrough'}, + {name: 'Milton Keynes'}, + {name: 'Monmouthshire'}, + {name: 'Moray'}, + {name: 'Norfolk'}, + {name: 'North East Lincolnshire'}, + {name: 'North Lincolnshire'}, + {name: 'North Somerset'}, + {name: 'North Yorkshire'}, + {name: 'Northamptonshire'}, + {name: 'Northumberland'}, + {name: 'Nottingham'}, + {name: 'Nottinghamshire'}, + {name: 'Oxfordshire'}, + {name: 'Pembrokeshire'}, + {name: 'Perth and Kinross'}, + {name: 'Peterborough'}, + {name: 'Plymouth'}, + {name: 'Poole'}, + {name: 'Portsmouth'}, + {name: 'Powys'}, + {name: 'Reading'}, + {name: 'Redcar and Cleveland'}, + {name: 'Rutland'}, + {name: 'Scottish Borders'}, + {name: 'Shropshire'}, + {name: 'Slough'}, + {name: 'Somerset'}, + {name: 'South Glamorgan'}, + {name: 'South Gloucestershire'}, + {name: 'South Yorkshire'}, + {name: 'Southampton'}, + {name: 'Southend-on-Sea'}, + {name: 'Staffordshire'}, + {name: 'Stirlingshire'}, + {name: 'Stockton-on-Tees'}, + {name: 'Stoke-on-Trent'}, + {name: 'Strathclyde'}, + {name: 'Suffolk'}, + {name: 'Surrey'}, + {name: 'Swindon'}, + {name: 'Telford and Wrekin'}, + {name: 'Thurrock'}, + {name: 'Torbay'}, + {name: 'Tyne and Wear'}, + {name: 'Warrington'}, + {name: 'Warwickshire'}, + {name: 'West Berkshire'}, + {name: 'West Glamorgan'}, + {name: 'West Lothian'}, + {name: 'West Midlands'}, + {name: 'West Sussex'}, + {name: 'West Yorkshire'}, + {name: 'Western Isles'}, + {name: 'Wiltshire'}, + {name: 'Windsor and Maidenhead'}, + {name: 'Wokingham'}, + {name: 'Worcestershire'}, + {name: 'Wrexham'}, + {name: 'York'}] + }, + provinces: { + "ca": [ + {name: 'Alberta', abbreviation: 'AB'}, + {name: 'British Columbia', abbreviation: 'BC'}, + {name: 'Manitoba', abbreviation: 'MB'}, + {name: 'New Brunswick', abbreviation: 'NB'}, + {name: 'Newfoundland and Labrador', abbreviation: 'NL'}, + {name: 'Nova Scotia', abbreviation: 'NS'}, + {name: 'Ontario', abbreviation: 'ON'}, + {name: 'Prince Edward Island', abbreviation: 'PE'}, + {name: 'Quebec', abbreviation: 'QC'}, + {name: 'Saskatchewan', abbreviation: 'SK'}, - 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 + // The case could be made that the following are not actually provinces + // since they are technically considered "territories" however they all + // look the same on an envelope! + {name: 'Northwest Territories', abbreviation: 'NT'}, + {name: 'Nunavut', abbreviation: 'NU'}, + {name: 'Yukon', abbreviation: 'YT'} + ], + "it": [ + { name: "Agrigento", abbreviation: "AG", code: 84 }, + { name: "Alessandria", abbreviation: "AL", code: 6 }, + { name: "Ancona", abbreviation: "AN", code: 42 }, + { name: "Aosta", abbreviation: "AO", code: 7 }, + { name: "L'Aquila", abbreviation: "AQ", code: 66 }, + { name: "Arezzo", abbreviation: "AR", code: 51 }, + { name: "Ascoli-Piceno", abbreviation: "AP", code: 44 }, + { name: "Asti", abbreviation: "AT", code: 5 }, + { name: "Avellino", abbreviation: "AV", code: 64 }, + { name: "Bari", abbreviation: "BA", code: 72 }, + { name: "Barletta-Andria-Trani", abbreviation: "BT", code: 72 }, + { name: "Belluno", abbreviation: "BL", code: 25 }, + { name: "Benevento", abbreviation: "BN", code: 62 }, + { name: "Bergamo", abbreviation: "BG", code: 16 }, + { name: "Biella", abbreviation: "BI", code: 96 }, + { name: "Bologna", abbreviation: "BO", code: 37 }, + { name: "Bolzano", abbreviation: "BZ", code: 21 }, + { name: "Brescia", abbreviation: "BS", code: 17 }, + { name: "Brindisi", abbreviation: "BR", code: 74 }, + { name: "Cagliari", abbreviation: "CA", code: 92 }, + { name: "Caltanissetta", abbreviation: "CL", code: 85 }, + { name: "Campobasso", abbreviation: "CB", code: 70 }, + { name: "Carbonia Iglesias", abbreviation: "CI", code: 70 }, + { name: "Caserta", abbreviation: "CE", code: 61 }, + { name: "Catania", abbreviation: "CT", code: 87 }, + { name: "Catanzaro", abbreviation: "CZ", code: 79 }, + { name: "Chieti", abbreviation: "CH", code: 69 }, + { name: "Como", abbreviation: "CO", code: 13 }, + { name: "Cosenza", abbreviation: "CS", code: 78 }, + { name: "Cremona", abbreviation: "CR", code: 19 }, + { name: "Crotone", abbreviation: "KR", code: 101 }, + { name: "Cuneo", abbreviation: "CN", code: 4 }, + { name: "Enna", abbreviation: "EN", code: 86 }, + { name: "Fermo", abbreviation: "FM", code: 86 }, + { name: "Ferrara", abbreviation: "FE", code: 38 }, + { name: "Firenze", abbreviation: "FI", code: 48 }, + { name: "Foggia", abbreviation: "FG", code: 71 }, + { name: "Forli-Cesena", abbreviation: "FC", code: 71 }, + { name: "Frosinone", abbreviation: "FR", code: 60 }, + { name: "Genova", abbreviation: "GE", code: 10 }, + { name: "Gorizia", abbreviation: "GO", code: 31 }, + { name: "Grosseto", abbreviation: "GR", code: 53 }, + { name: "Imperia", abbreviation: "IM", code: 8 }, + { name: "Isernia", abbreviation: "IS", code: 94 }, + { name: "La-Spezia", abbreviation: "SP", code: 66 }, + { name: "Latina", abbreviation: "LT", code: 59 }, + { name: "Lecce", abbreviation: "LE", code: 75 }, + { name: "Lecco", abbreviation: "LC", code: 97 }, + { name: "Livorno", abbreviation: "LI", code: 49 }, + { name: "Lodi", abbreviation: "LO", code: 98 }, + { name: "Lucca", abbreviation: "LU", code: 46 }, + { name: "Macerata", abbreviation: "MC", code: 43 }, + { name: "Mantova", abbreviation: "MN", code: 20 }, + { name: "Massa-Carrara", abbreviation: "MS", code: 45 }, + { name: "Matera", abbreviation: "MT", code: 77 }, + { name: "Medio Campidano", abbreviation: "VS", code: 77 }, + { name: "Messina", abbreviation: "ME", code: 83 }, + { name: "Milano", abbreviation: "MI", code: 15 }, + { name: "Modena", abbreviation: "MO", code: 36 }, + { name: "Monza-Brianza", abbreviation: "MB", code: 36 }, + { name: "Napoli", abbreviation: "NA", code: 63 }, + { name: "Novara", abbreviation: "NO", code: 3 }, + { name: "Nuoro", abbreviation: "NU", code: 91 }, + { name: "Ogliastra", abbreviation: "OG", code: 91 }, + { name: "Olbia Tempio", abbreviation: "OT", code: 91 }, + { name: "Oristano", abbreviation: "OR", code: 95 }, + { name: "Padova", abbreviation: "PD", code: 28 }, + { name: "Palermo", abbreviation: "PA", code: 82 }, + { name: "Parma", abbreviation: "PR", code: 34 }, + { name: "Pavia", abbreviation: "PV", code: 18 }, + { name: "Perugia", abbreviation: "PG", code: 54 }, + { name: "Pesaro-Urbino", abbreviation: "PU", code: 41 }, + { name: "Pescara", abbreviation: "PE", code: 68 }, + { name: "Piacenza", abbreviation: "PC", code: 33 }, + { name: "Pisa", abbreviation: "PI", code: 50 }, + { name: "Pistoia", abbreviation: "PT", code: 47 }, + { name: "Pordenone", abbreviation: "PN", code: 93 }, + { name: "Potenza", abbreviation: "PZ", code: 76 }, + { name: "Prato", abbreviation: "PO", code: 100 }, + { name: "Ragusa", abbreviation: "RG", code: 88 }, + { name: "Ravenna", abbreviation: "RA", code: 39 }, + { name: "Reggio-Calabria", abbreviation: "RC", code: 35 }, + { name: "Reggio-Emilia", abbreviation: "RE", code: 35 }, + { name: "Rieti", abbreviation: "RI", code: 57 }, + { name: "Rimini", abbreviation: "RN", code: 99 }, + { name: "Roma", abbreviation: "Roma", code: 58 }, + { name: "Rovigo", abbreviation: "RO", code: 29 }, + { name: "Salerno", abbreviation: "SA", code: 65 }, + { name: "Sassari", abbreviation: "SS", code: 90 }, + { name: "Savona", abbreviation: "SV", code: 9 }, + { name: "Siena", abbreviation: "SI", code: 52 }, + { name: "Siracusa", abbreviation: "SR", code: 89 }, + { name: "Sondrio", abbreviation: "SO", code: 14 }, + { name: "Taranto", abbreviation: "TA", code: 73 }, + { name: "Teramo", abbreviation: "TE", code: 67 }, + { name: "Terni", abbreviation: "TR", code: 55 }, + { name: "Torino", abbreviation: "TO", code: 1 }, + { name: "Trapani", abbreviation: "TP", code: 81 }, + { name: "Trento", abbreviation: "TN", code: 22 }, + { name: "Treviso", abbreviation: "TV", code: 26 }, + { name: "Trieste", abbreviation: "TS", code: 32 }, + { name: "Udine", abbreviation: "UD", code: 30 }, + { name: "Varese", abbreviation: "VA", code: 12 }, + { name: "Venezia", abbreviation: "VE", code: 27 }, + { name: "Verbania", abbreviation: "VB", code: 27 }, + { name: "Vercelli", abbreviation: "VC", code: 2 }, + { name: "Verona", abbreviation: "VR", code: 23 }, + { name: "Vibo-Valentia", abbreviation: "VV", code: 102 }, + { name: "Vicenza", abbreviation: "VI", code: 24 }, + { name: "Viterbo", abbreviation: "VT", code: 56 } + ] + }, - const sessionKey = servername || hostname - const session = sessionCache.get(sessionKey) || null + // from: https://github.com/samsargent/Useful-Autocomplete-Data/blob/master/data/nationalities.json + nationalities: [ + {name: 'Afghan'}, + {name: 'Albanian'}, + {name: 'Algerian'}, + {name: 'American'}, + {name: 'Andorran'}, + {name: 'Angolan'}, + {name: 'Antiguans'}, + {name: 'Argentinean'}, + {name: 'Armenian'}, + {name: 'Australian'}, + {name: 'Austrian'}, + {name: 'Azerbaijani'}, + {name: 'Bahami'}, + {name: 'Bahraini'}, + {name: 'Bangladeshi'}, + {name: 'Barbadian'}, + {name: 'Barbudans'}, + {name: 'Batswana'}, + {name: 'Belarusian'}, + {name: 'Belgian'}, + {name: 'Belizean'}, + {name: 'Beninese'}, + {name: 'Bhutanese'}, + {name: 'Bolivian'}, + {name: 'Bosnian'}, + {name: 'Brazilian'}, + {name: 'British'}, + {name: 'Bruneian'}, + {name: 'Bulgarian'}, + {name: 'Burkinabe'}, + {name: 'Burmese'}, + {name: 'Burundian'}, + {name: 'Cambodian'}, + {name: 'Cameroonian'}, + {name: 'Canadian'}, + {name: 'Cape Verdean'}, + {name: 'Central African'}, + {name: 'Chadian'}, + {name: 'Chilean'}, + {name: 'Chinese'}, + {name: 'Colombian'}, + {name: 'Comoran'}, + {name: 'Congolese'}, + {name: 'Costa Rican'}, + {name: 'Croatian'}, + {name: 'Cuban'}, + {name: 'Cypriot'}, + {name: 'Czech'}, + {name: 'Danish'}, + {name: 'Djibouti'}, + {name: 'Dominican'}, + {name: 'Dutch'}, + {name: 'East Timorese'}, + {name: 'Ecuadorean'}, + {name: 'Egyptian'}, + {name: 'Emirian'}, + {name: 'Equatorial Guinean'}, + {name: 'Eritrean'}, + {name: 'Estonian'}, + {name: 'Ethiopian'}, + {name: 'Fijian'}, + {name: 'Filipino'}, + {name: 'Finnish'}, + {name: 'French'}, + {name: 'Gabonese'}, + {name: 'Gambian'}, + {name: 'Georgian'}, + {name: 'German'}, + {name: 'Ghanaian'}, + {name: 'Greek'}, + {name: 'Grenadian'}, + {name: 'Guatemalan'}, + {name: 'Guinea-Bissauan'}, + {name: 'Guinean'}, + {name: 'Guyanese'}, + {name: 'Haitian'}, + {name: 'Herzegovinian'}, + {name: 'Honduran'}, + {name: 'Hungarian'}, + {name: 'I-Kiribati'}, + {name: 'Icelander'}, + {name: 'Indian'}, + {name: 'Indonesian'}, + {name: 'Iranian'}, + {name: 'Iraqi'}, + {name: 'Irish'}, + {name: 'Israeli'}, + {name: 'Italian'}, + {name: 'Ivorian'}, + {name: 'Jamaican'}, + {name: 'Japanese'}, + {name: 'Jordanian'}, + {name: 'Kazakhstani'}, + {name: 'Kenyan'}, + {name: 'Kittian and Nevisian'}, + {name: 'Kuwaiti'}, + {name: 'Kyrgyz'}, + {name: 'Laotian'}, + {name: 'Latvian'}, + {name: 'Lebanese'}, + {name: 'Liberian'}, + {name: 'Libyan'}, + {name: 'Liechtensteiner'}, + {name: 'Lithuanian'}, + {name: 'Luxembourger'}, + {name: 'Macedonian'}, + {name: 'Malagasy'}, + {name: 'Malawian'}, + {name: 'Malaysian'}, + {name: 'Maldivan'}, + {name: 'Malian'}, + {name: 'Maltese'}, + {name: 'Marshallese'}, + {name: 'Mauritanian'}, + {name: 'Mauritian'}, + {name: 'Mexican'}, + {name: 'Micronesian'}, + {name: 'Moldovan'}, + {name: 'Monacan'}, + {name: 'Mongolian'}, + {name: 'Moroccan'}, + {name: 'Mosotho'}, + {name: 'Motswana'}, + {name: 'Mozambican'}, + {name: 'Namibian'}, + {name: 'Nauruan'}, + {name: 'Nepalese'}, + {name: 'New Zealander'}, + {name: 'Nicaraguan'}, + {name: 'Nigerian'}, + {name: 'Nigerien'}, + {name: 'North Korean'}, + {name: 'Northern Irish'}, + {name: 'Norwegian'}, + {name: 'Omani'}, + {name: 'Pakistani'}, + {name: 'Palauan'}, + {name: 'Panamanian'}, + {name: 'Papua New Guinean'}, + {name: 'Paraguayan'}, + {name: 'Peruvian'}, + {name: 'Polish'}, + {name: 'Portuguese'}, + {name: 'Qatari'}, + {name: 'Romani'}, + {name: 'Russian'}, + {name: 'Rwandan'}, + {name: 'Saint Lucian'}, + {name: 'Salvadoran'}, + {name: 'Samoan'}, + {name: 'San Marinese'}, + {name: 'Sao Tomean'}, + {name: 'Saudi'}, + {name: 'Scottish'}, + {name: 'Senegalese'}, + {name: 'Serbian'}, + {name: 'Seychellois'}, + {name: 'Sierra Leonean'}, + {name: 'Singaporean'}, + {name: 'Slovakian'}, + {name: 'Slovenian'}, + {name: 'Solomon Islander'}, + {name: 'Somali'}, + {name: 'South African'}, + {name: 'South Korean'}, + {name: 'Spanish'}, + {name: 'Sri Lankan'}, + {name: 'Sudanese'}, + {name: 'Surinamer'}, + {name: 'Swazi'}, + {name: 'Swedish'}, + {name: 'Swiss'}, + {name: 'Syrian'}, + {name: 'Taiwanese'}, + {name: 'Tajik'}, + {name: 'Tanzanian'}, + {name: 'Thai'}, + {name: 'Togolese'}, + {name: 'Tongan'}, + {name: 'Trinidadian or Tobagonian'}, + {name: 'Tunisian'}, + {name: 'Turkish'}, + {name: 'Tuvaluan'}, + {name: 'Ugandan'}, + {name: 'Ukrainian'}, + {name: 'Uruguaya'}, + {name: 'Uzbekistani'}, + {name: 'Venezuela'}, + {name: 'Vietnamese'}, + {name: 'Wels'}, + {name: 'Yemenit'}, + {name: 'Zambia'}, + {name: 'Zimbabwe'}, + ], + // http://www.loc.gov/standards/iso639-2/php/code_list.php (ISO-639-1 codes) + locale_languages: [ + "aa", + "ab", + "ae", + "af", + "ak", + "am", + "an", + "ar", + "as", + "av", + "ay", + "az", + "ba", + "be", + "bg", + "bh", + "bi", + "bm", + "bn", + "bo", + "br", + "bs", + "ca", + "ce", + "ch", + "co", + "cr", + "cs", + "cu", + "cv", + "cy", + "da", + "de", + "dv", + "dz", + "ee", + "el", + "en", + "eo", + "es", + "et", + "eu", + "fa", + "ff", + "fi", + "fj", + "fo", + "fr", + "fy", + "ga", + "gd", + "gl", + "gn", + "gu", + "gv", + "ha", + "he", + "hi", + "ho", + "hr", + "ht", + "hu", + "hy", + "hz", + "ia", + "id", + "ie", + "ig", + "ii", + "ik", + "io", + "is", + "it", + "iu", + "ja", + "jv", + "ka", + "kg", + "ki", + "kj", + "kk", + "kl", + "km", + "kn", + "ko", + "kr", + "ks", + "ku", + "kv", + "kw", + "ky", + "la", + "lb", + "lg", + "li", + "ln", + "lo", + "lt", + "lu", + "lv", + "mg", + "mh", + "mi", + "mk", + "ml", + "mn", + "mr", + "ms", + "mt", + "my", + "na", + "nb", + "nd", + "ne", + "ng", + "nl", + "nn", + "no", + "nr", + "nv", + "ny", + "oc", + "oj", + "om", + "or", + "os", + "pa", + "pi", + "pl", + "ps", + "pt", + "qu", + "rm", + "rn", + "ro", + "ru", + "rw", + "sa", + "sc", + "sd", + "se", + "sg", + "si", + "sk", + "sl", + "sm", + "sn", + "so", + "sq", + "sr", + "ss", + "st", + "su", + "sv", + "sw", + "ta", + "te", + "tg", + "th", + "ti", + "tk", + "tl", + "tn", + "to", + "tr", + "ts", + "tt", + "tw", + "ty", + "ug", + "uk", + "ur", + "uz", + "ve", + "vi", + "vo", + "wa", + "wo", + "xh", + "yi", + "yo", + "za", + "zh", + "zu" + ], - assert(sessionKey) + // From http://data.okfn.org/data/core/language-codes#resource-language-codes-full (IETF language tags) + locale_regions: [ + "agq-CM", + "asa-TZ", + "ast-ES", + "bas-CM", + "bem-ZM", + "bez-TZ", + "brx-IN", + "cgg-UG", + "chr-US", + "dav-KE", + "dje-NE", + "dsb-DE", + "dua-CM", + "dyo-SN", + "ebu-KE", + "ewo-CM", + "fil-PH", + "fur-IT", + "gsw-CH", + "gsw-FR", + "gsw-LI", + "guz-KE", + "haw-US", + "hsb-DE", + "jgo-CM", + "jmc-TZ", + "kab-DZ", + "kam-KE", + "kde-TZ", + "kea-CV", + "khq-ML", + "kkj-CM", + "kln-KE", + "kok-IN", + "ksb-TZ", + "ksf-CM", + "ksh-DE", + "lag-TZ", + "lkt-US", + "luo-KE", + "luy-KE", + "mas-KE", + "mas-TZ", + "mer-KE", + "mfe-MU", + "mgh-MZ", + "mgo-CM", + "mua-CM", + "naq-NA", + "nmg-CM", + "nnh-CM", + "nus-SD", + "nyn-UG", + "rof-TZ", + "rwk-TZ", + "sah-RU", + "saq-KE", + "sbp-TZ", + "seh-MZ", + "ses-ML", + "shi-Latn", + "shi-Latn-MA", + "shi-Tfng", + "shi-Tfng-MA", + "smn-FI", + "teo-KE", + "teo-UG", + "twq-NE", + "tzm-Latn", + "tzm-Latn-MA", + "vai-Latn", + "vai-Latn-LR", + "vai-Vaii", + "vai-Vaii-LR", + "vun-TZ", + "wae-CH", + "xog-UG", + "yav-CM", + "zgh-MA", + "af-NA", + "af-ZA", + "ak-GH", + "am-ET", + "ar-001", + "ar-AE", + "ar-BH", + "ar-DJ", + "ar-DZ", + "ar-EG", + "ar-EH", + "ar-ER", + "ar-IL", + "ar-IQ", + "ar-JO", + "ar-KM", + "ar-KW", + "ar-LB", + "ar-LY", + "ar-MA", + "ar-MR", + "ar-OM", + "ar-PS", + "ar-QA", + "ar-SA", + "ar-SD", + "ar-SO", + "ar-SS", + "ar-SY", + "ar-TD", + "ar-TN", + "ar-YE", + "as-IN", + "az-Cyrl", + "az-Cyrl-AZ", + "az-Latn", + "az-Latn-AZ", + "be-BY", + "bg-BG", + "bm-Latn", + "bm-Latn-ML", + "bn-BD", + "bn-IN", + "bo-CN", + "bo-IN", + "br-FR", + "bs-Cyrl", + "bs-Cyrl-BA", + "bs-Latn", + "bs-Latn-BA", + "ca-AD", + "ca-ES", + "ca-ES-VALENCIA", + "ca-FR", + "ca-IT", + "cs-CZ", + "cy-GB", + "da-DK", + "da-GL", + "de-AT", + "de-BE", + "de-CH", + "de-DE", + "de-LI", + "de-LU", + "dz-BT", + "ee-GH", + "ee-TG", + "el-CY", + "el-GR", + "en-001", + "en-150", + "en-AG", + "en-AI", + "en-AS", + "en-AU", + "en-BB", + "en-BE", + "en-BM", + "en-BS", + "en-BW", + "en-BZ", + "en-CA", + "en-CC", + "en-CK", + "en-CM", + "en-CX", + "en-DG", + "en-DM", + "en-ER", + "en-FJ", + "en-FK", + "en-FM", + "en-GB", + "en-GD", + "en-GG", + "en-GH", + "en-GI", + "en-GM", + "en-GU", + "en-GY", + "en-HK", + "en-IE", + "en-IM", + "en-IN", + "en-IO", + "en-JE", + "en-JM", + "en-KE", + "en-KI", + "en-KN", + "en-KY", + "en-LC", + "en-LR", + "en-LS", + "en-MG", + "en-MH", + "en-MO", + "en-MP", + "en-MS", + "en-MT", + "en-MU", + "en-MW", + "en-MY", + "en-NA", + "en-NF", + "en-NG", + "en-NR", + "en-NU", + "en-NZ", + "en-PG", + "en-PH", + "en-PK", + "en-PN", + "en-PR", + "en-PW", + "en-RW", + "en-SB", + "en-SC", + "en-SD", + "en-SG", + "en-SH", + "en-SL", + "en-SS", + "en-SX", + "en-SZ", + "en-TC", + "en-TK", + "en-TO", + "en-TT", + "en-TV", + "en-TZ", + "en-UG", + "en-UM", + "en-US", + "en-US-POSIX", + "en-VC", + "en-VG", + "en-VI", + "en-VU", + "en-WS", + "en-ZA", + "en-ZM", + "en-ZW", + "eo-001", + "es-419", + "es-AR", + "es-BO", + "es-CL", + "es-CO", + "es-CR", + "es-CU", + "es-DO", + "es-EA", + "es-EC", + "es-ES", + "es-GQ", + "es-GT", + "es-HN", + "es-IC", + "es-MX", + "es-NI", + "es-PA", + "es-PE", + "es-PH", + "es-PR", + "es-PY", + "es-SV", + "es-US", + "es-UY", + "es-VE", + "et-EE", + "eu-ES", + "fa-AF", + "fa-IR", + "ff-CM", + "ff-GN", + "ff-MR", + "ff-SN", + "fi-FI", + "fo-FO", + "fr-BE", + "fr-BF", + "fr-BI", + "fr-BJ", + "fr-BL", + "fr-CA", + "fr-CD", + "fr-CF", + "fr-CG", + "fr-CH", + "fr-CI", + "fr-CM", + "fr-DJ", + "fr-DZ", + "fr-FR", + "fr-GA", + "fr-GF", + "fr-GN", + "fr-GP", + "fr-GQ", + "fr-HT", + "fr-KM", + "fr-LU", + "fr-MA", + "fr-MC", + "fr-MF", + "fr-MG", + "fr-ML", + "fr-MQ", + "fr-MR", + "fr-MU", + "fr-NC", + "fr-NE", + "fr-PF", + "fr-PM", + "fr-RE", + "fr-RW", + "fr-SC", + "fr-SN", + "fr-SY", + "fr-TD", + "fr-TG", + "fr-TN", + "fr-VU", + "fr-WF", + "fr-YT", + "fy-NL", + "ga-IE", + "gd-GB", + "gl-ES", + "gu-IN", + "gv-IM", + "ha-Latn", + "ha-Latn-GH", + "ha-Latn-NE", + "ha-Latn-NG", + "he-IL", + "hi-IN", + "hr-BA", + "hr-HR", + "hu-HU", + "hy-AM", + "id-ID", + "ig-NG", + "ii-CN", + "is-IS", + "it-CH", + "it-IT", + "it-SM", + "ja-JP", + "ka-GE", + "ki-KE", + "kk-Cyrl", + "kk-Cyrl-KZ", + "kl-GL", + "km-KH", + "kn-IN", + "ko-KP", + "ko-KR", + "ks-Arab", + "ks-Arab-IN", + "kw-GB", + "ky-Cyrl", + "ky-Cyrl-KG", + "lb-LU", + "lg-UG", + "ln-AO", + "ln-CD", + "ln-CF", + "ln-CG", + "lo-LA", + "lt-LT", + "lu-CD", + "lv-LV", + "mg-MG", + "mk-MK", + "ml-IN", + "mn-Cyrl", + "mn-Cyrl-MN", + "mr-IN", + "ms-Latn", + "ms-Latn-BN", + "ms-Latn-MY", + "ms-Latn-SG", + "mt-MT", + "my-MM", + "nb-NO", + "nb-SJ", + "nd-ZW", + "ne-IN", + "ne-NP", + "nl-AW", + "nl-BE", + "nl-BQ", + "nl-CW", + "nl-NL", + "nl-SR", + "nl-SX", + "nn-NO", + "om-ET", + "om-KE", + "or-IN", + "os-GE", + "os-RU", + "pa-Arab", + "pa-Arab-PK", + "pa-Guru", + "pa-Guru-IN", + "pl-PL", + "ps-AF", + "pt-AO", + "pt-BR", + "pt-CV", + "pt-GW", + "pt-MO", + "pt-MZ", + "pt-PT", + "pt-ST", + "pt-TL", + "qu-BO", + "qu-EC", + "qu-PE", + "rm-CH", + "rn-BI", + "ro-MD", + "ro-RO", + "ru-BY", + "ru-KG", + "ru-KZ", + "ru-MD", + "ru-RU", + "ru-UA", + "rw-RW", + "se-FI", + "se-NO", + "se-SE", + "sg-CF", + "si-LK", + "sk-SK", + "sl-SI", + "sn-ZW", + "so-DJ", + "so-ET", + "so-KE", + "so-SO", + "sq-AL", + "sq-MK", + "sq-XK", + "sr-Cyrl", + "sr-Cyrl-BA", + "sr-Cyrl-ME", + "sr-Cyrl-RS", + "sr-Cyrl-XK", + "sr-Latn", + "sr-Latn-BA", + "sr-Latn-ME", + "sr-Latn-RS", + "sr-Latn-XK", + "sv-AX", + "sv-FI", + "sv-SE", + "sw-CD", + "sw-KE", + "sw-TZ", + "sw-UG", + "ta-IN", + "ta-LK", + "ta-MY", + "ta-SG", + "te-IN", + "th-TH", + "ti-ER", + "ti-ET", + "to-TO", + "tr-CY", + "tr-TR", + "ug-Arab", + "ug-Arab-CN", + "uk-UA", + "ur-IN", + "ur-PK", + "uz-Arab", + "uz-Arab-AF", + "uz-Cyrl", + "uz-Cyrl-UZ", + "uz-Latn", + "uz-Latn-UZ", + "vi-VN", + "yi-001", + "yo-BJ", + "yo-NG", + "zh-Hans", + "zh-Hans-CN", + "zh-Hans-HK", + "zh-Hans-MO", + "zh-Hans-SG", + "zh-Hant", + "zh-Hant-HK", + "zh-Hant-MO", + "zh-Hant-TW", + "zu-ZA" + ], - 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 - }) + us_states_and_dc: [ + {name: 'Alabama', abbreviation: 'AL'}, + {name: 'Alaska', abbreviation: 'AK'}, + {name: 'Arizona', abbreviation: 'AZ'}, + {name: 'Arkansas', abbreviation: 'AR'}, + {name: 'California', abbreviation: 'CA'}, + {name: 'Colorado', abbreviation: 'CO'}, + {name: 'Connecticut', abbreviation: 'CT'}, + {name: 'Delaware', abbreviation: 'DE'}, + {name: 'District of Columbia', abbreviation: 'DC'}, + {name: 'Florida', abbreviation: 'FL'}, + {name: 'Georgia', abbreviation: 'GA'}, + {name: 'Hawaii', abbreviation: 'HI'}, + {name: 'Idaho', abbreviation: 'ID'}, + {name: 'Illinois', abbreviation: 'IL'}, + {name: 'Indiana', abbreviation: 'IN'}, + {name: 'Iowa', abbreviation: 'IA'}, + {name: 'Kansas', abbreviation: 'KS'}, + {name: 'Kentucky', abbreviation: 'KY'}, + {name: 'Louisiana', abbreviation: 'LA'}, + {name: 'Maine', abbreviation: 'ME'}, + {name: 'Maryland', abbreviation: 'MD'}, + {name: 'Massachusetts', abbreviation: 'MA'}, + {name: 'Michigan', abbreviation: 'MI'}, + {name: 'Minnesota', abbreviation: 'MN'}, + {name: 'Mississippi', abbreviation: 'MS'}, + {name: 'Missouri', abbreviation: 'MO'}, + {name: 'Montana', abbreviation: 'MT'}, + {name: 'Nebraska', abbreviation: 'NE'}, + {name: 'Nevada', abbreviation: 'NV'}, + {name: 'New Hampshire', abbreviation: 'NH'}, + {name: 'New Jersey', abbreviation: 'NJ'}, + {name: 'New Mexico', abbreviation: 'NM'}, + {name: 'New York', abbreviation: 'NY'}, + {name: 'North Carolina', abbreviation: 'NC'}, + {name: 'North Dakota', abbreviation: 'ND'}, + {name: 'Ohio', abbreviation: 'OH'}, + {name: 'Oklahoma', abbreviation: 'OK'}, + {name: 'Oregon', abbreviation: 'OR'}, + {name: 'Pennsylvania', abbreviation: 'PA'}, + {name: 'Rhode Island', abbreviation: 'RI'}, + {name: 'South Carolina', abbreviation: 'SC'}, + {name: 'South Dakota', abbreviation: 'SD'}, + {name: 'Tennessee', abbreviation: 'TN'}, + {name: 'Texas', abbreviation: 'TX'}, + {name: 'Utah', abbreviation: 'UT'}, + {name: 'Vermont', abbreviation: 'VT'}, + {name: 'Virginia', abbreviation: 'VA'}, + {name: 'Washington', abbreviation: 'WA'}, + {name: 'West Virginia', abbreviation: 'WV'}, + {name: 'Wisconsin', abbreviation: 'WI'}, + {name: 'Wyoming', abbreviation: 'WY'} + ], - 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 - }) - } + territories: [ + {name: 'American Samoa', abbreviation: 'AS'}, + {name: 'Federated States of Micronesia', abbreviation: 'FM'}, + {name: 'Guam', abbreviation: 'GU'}, + {name: 'Marshall Islands', abbreviation: 'MH'}, + {name: 'Northern Mariana Islands', abbreviation: 'MP'}, + {name: 'Puerto Rico', abbreviation: 'PR'}, + {name: 'Virgin Islands, U.S.', abbreviation: 'VI'} + ], - // 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) - } + armed_forces: [ + {name: 'Armed Forces Europe', abbreviation: 'AE'}, + {name: 'Armed Forces Pacific', abbreviation: 'AP'}, + {name: 'Armed Forces the Americas', abbreviation: 'AA'} + ], - const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) + country_regions: { + it: [ + { name: "Valle d'Aosta", abbreviation: "VDA" }, + { name: "Piemonte", abbreviation: "PIE" }, + { name: "Lombardia", abbreviation: "LOM" }, + { name: "Veneto", abbreviation: "VEN" }, + { name: "Trentino Alto Adige", abbreviation: "TAA" }, + { name: "Friuli Venezia Giulia", abbreviation: "FVG" }, + { name: "Liguria", abbreviation: "LIG" }, + { name: "Emilia Romagna", abbreviation: "EMR" }, + { name: "Toscana", abbreviation: "TOS" }, + { name: "Umbria", abbreviation: "UMB" }, + { name: "Marche", abbreviation: "MAR" }, + { name: "Abruzzo", abbreviation: "ABR" }, + { name: "Lazio", abbreviation: "LAZ" }, + { name: "Campania", abbreviation: "CAM" }, + { name: "Puglia", abbreviation: "PUG" }, + { name: "Basilicata", abbreviation: "BAS" }, + { name: "Molise", abbreviation: "MOL" }, + { name: "Calabria", abbreviation: "CAL" }, + { name: "Sicilia", abbreviation: "SIC" }, + { name: "Sardegna", abbreviation: "SAR" } + ], + mx: [ + { name: 'Aguascalientes', abbreviation: 'AGU' }, + { name: 'Baja California', abbreviation: 'BCN' }, + { name: 'Baja California Sur', abbreviation: 'BCS' }, + { name: 'Campeche', abbreviation: 'CAM' }, + { name: 'Chiapas', abbreviation: 'CHP' }, + { name: 'Chihuahua', abbreviation: 'CHH' }, + { name: 'Ciudad de MĆ©xico', abbreviation: 'DIF' }, + { name: 'Coahuila', abbreviation: 'COA' }, + { name: 'Colima', abbreviation: 'COL' }, + { name: 'Durango', abbreviation: 'DUR' }, + { name: 'Guanajuato', abbreviation: 'GUA' }, + { name: 'Guerrero', abbreviation: 'GRO' }, + { name: 'Hidalgo', abbreviation: 'HID' }, + { name: 'Jalisco', abbreviation: 'JAL' }, + { name: 'MĆ©xico', abbreviation: 'MEX' }, + { name: 'MichoacĆ”n', abbreviation: 'MIC' }, + { name: 'Morelos', abbreviation: 'MOR' }, + { name: 'Nayarit', abbreviation: 'NAY' }, + { name: 'Nuevo León', abbreviation: 'NLE' }, + { name: 'Oaxaca', abbreviation: 'OAX' }, + { name: 'Puebla', abbreviation: 'PUE' }, + { name: 'QuerĆ©taro', abbreviation: 'QUE' }, + { name: 'Quintana Roo', abbreviation: 'ROO' }, + { name: 'San Luis PotosĆ­', abbreviation: 'SLP' }, + { name: 'Sinaloa', abbreviation: 'SIN' }, + { name: 'Sonora', abbreviation: 'SON' }, + { name: 'Tabasco', abbreviation: 'TAB' }, + { name: 'Tamaulipas', abbreviation: 'TAM' }, + { name: 'Tlaxcala', abbreviation: 'TLA' }, + { name: 'Veracruz', abbreviation: 'VER' }, + { name: 'YucatĆ”n', abbreviation: 'YUC' }, + { name: 'Zacatecas', abbreviation: 'ZAC' } + ] + }, - socket - .setNoDelay(true) - .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { - cancelTimeout() + street_suffixes: { + 'us': [ + {name: 'Avenue', abbreviation: 'Ave'}, + {name: 'Boulevard', abbreviation: 'Blvd'}, + {name: 'Center', abbreviation: 'Ctr'}, + {name: 'Circle', abbreviation: 'Cir'}, + {name: 'Court', abbreviation: 'Ct'}, + {name: 'Drive', abbreviation: 'Dr'}, + {name: 'Extension', abbreviation: 'Ext'}, + {name: 'Glen', abbreviation: 'Gln'}, + {name: 'Grove', abbreviation: 'Grv'}, + {name: 'Heights', abbreviation: 'Hts'}, + {name: 'Highway', abbreviation: 'Hwy'}, + {name: 'Junction', abbreviation: 'Jct'}, + {name: 'Key', abbreviation: 'Key'}, + {name: 'Lane', abbreviation: 'Ln'}, + {name: 'Loop', abbreviation: 'Loop'}, + {name: 'Manor', abbreviation: 'Mnr'}, + {name: 'Mill', abbreviation: 'Mill'}, + {name: 'Park', abbreviation: 'Park'}, + {name: 'Parkway', abbreviation: 'Pkwy'}, + {name: 'Pass', abbreviation: 'Pass'}, + {name: 'Path', abbreviation: 'Path'}, + {name: 'Pike', abbreviation: 'Pike'}, + {name: 'Place', abbreviation: 'Pl'}, + {name: 'Plaza', abbreviation: 'Plz'}, + {name: 'Point', abbreviation: 'Pt'}, + {name: 'Ridge', abbreviation: 'Rdg'}, + {name: 'River', abbreviation: 'Riv'}, + {name: 'Road', abbreviation: 'Rd'}, + {name: 'Square', abbreviation: 'Sq'}, + {name: 'Street', abbreviation: 'St'}, + {name: 'Terrace', abbreviation: 'Ter'}, + {name: 'Trail', abbreviation: 'Trl'}, + {name: 'Turnpike', abbreviation: 'Tpke'}, + {name: 'View', abbreviation: 'Vw'}, + {name: 'Way', abbreviation: 'Way'} + ], + 'it': [ + { name: 'Accesso', abbreviation: 'Acc.' }, + { name: 'Alzaia', abbreviation: 'Alz.' }, + { name: 'Arco', abbreviation: 'Arco' }, + { name: 'Archivolto', abbreviation: 'Acv.' }, + { name: 'Arena', abbreviation: 'Arena' }, + { name: 'Argine', abbreviation: 'Argine' }, + { name: 'Bacino', abbreviation: 'Bacino' }, + { name: 'Banchi', abbreviation: 'Banchi' }, + { name: 'Banchina', abbreviation: 'Ban.' }, + { name: 'Bastioni', abbreviation: 'Bas.' }, + { name: 'Belvedere', abbreviation: 'Belv.' }, + { name: 'Borgata', abbreviation: 'B.ta' }, + { name: 'Borgo', abbreviation: 'B.go' }, + { name: 'Calata', abbreviation: 'Cal.' }, + { name: 'Calle', abbreviation: 'Calle' }, + { name: 'Campiello', abbreviation: 'Cam.' }, + { name: 'Campo', abbreviation: 'Cam.' }, + { name: 'Canale', abbreviation: 'Can.' }, + { name: 'Carraia', abbreviation: 'Carr.' }, + { name: 'Cascina', abbreviation: 'Cascina' }, + { name: 'Case sparse', abbreviation: 'c.s.' }, + { name: 'Cavalcavia', abbreviation: 'Cv.' }, + { name: 'Circonvallazione', abbreviation: 'Cv.' }, + { name: 'Complanare', abbreviation: 'C.re' }, + { name: 'Contrada', abbreviation: 'C.da' }, + { name: 'Corso', abbreviation: 'C.so' }, + { name: 'Corte', abbreviation: 'C.te' }, + { name: 'Cortile', abbreviation: 'C.le' }, + { name: 'Diramazione', abbreviation: 'Dir.' }, + { name: 'Fondaco', abbreviation: 'F.co' }, + { name: 'Fondamenta', abbreviation: 'F.ta' }, + { name: 'Fondo', abbreviation: 'F.do' }, + { name: 'Frazione', abbreviation: 'Fr.' }, + { name: 'Isola', abbreviation: 'Is.' }, + { name: 'Largo', abbreviation: 'L.go' }, + { name: 'Litoranea', abbreviation: 'Lit.' }, + { name: 'Lungolago', abbreviation: 'L.go lago' }, + { name: 'Lungo Po', abbreviation: 'l.go Po' }, + { name: 'Molo', abbreviation: 'Molo' }, + { name: 'Mura', abbreviation: 'Mura' }, + { name: 'Passaggio privato', abbreviation: 'pass. priv.' }, + { name: 'Passeggiata', abbreviation: 'Pass.' }, + { name: 'Piazza', abbreviation: 'P.zza' }, + { name: 'Piazzale', abbreviation: 'P.le' }, + { name: 'Ponte', abbreviation: 'P.te' }, + { name: 'Portico', abbreviation: 'P.co' }, + { name: 'Rampa', abbreviation: 'Rampa' }, + { name: 'Regione', abbreviation: 'Reg.' }, + { name: 'Rione', abbreviation: 'R.ne' }, + { name: 'Rio', abbreviation: 'Rio' }, + { name: 'Ripa', abbreviation: 'Ripa' }, + { name: 'Riva', abbreviation: 'Riva' }, + { name: 'Rondò', abbreviation: 'Rondò' }, + { name: 'Rotonda', abbreviation: 'Rot.' }, + { name: 'Sagrato', abbreviation: 'Sagr.' }, + { name: 'Salita', abbreviation: 'Sal.' }, + { name: 'Scalinata', abbreviation: 'Scal.' }, + { name: 'Scalone', abbreviation: 'Scal.' }, + { name: 'Slargo', abbreviation: 'Sl.' }, + { name: 'Sottoportico', abbreviation: 'Sott.' }, + { name: 'Strada', abbreviation: 'Str.' }, + { name: 'Stradale', abbreviation: 'Str.le' }, + { name: 'Strettoia', abbreviation: 'Strett.' }, + { name: 'Traversa', abbreviation: 'Trav.' }, + { name: 'Via', abbreviation: 'V.' }, + { name: 'Viale', abbreviation: 'V.le' }, + { name: 'Vicinale', abbreviation: 'Vic.le' }, + { name: 'Vicolo', abbreviation: 'Vic.' } + ], + 'uk' : [ + {name: 'Avenue', abbreviation: 'Ave'}, + {name: 'Close', abbreviation: 'Cl'}, + {name: 'Court', abbreviation: 'Ct'}, + {name: 'Crescent', abbreviation: 'Cr'}, + {name: 'Drive', abbreviation: 'Dr'}, + {name: 'Garden', abbreviation: 'Gdn'}, + {name: 'Gardens', abbreviation: 'Gdns'}, + {name: 'Green', abbreviation: 'Gn'}, + {name: 'Grove', abbreviation: 'Gr'}, + {name: 'Lane', abbreviation: 'Ln'}, + {name: 'Mount', abbreviation: 'Mt'}, + {name: 'Place', abbreviation: 'Pl'}, + {name: 'Park', abbreviation: 'Pk'}, + {name: 'Ridge', abbreviation: 'Rdg'}, + {name: 'Road', abbreviation: 'Rd'}, + {name: 'Square', abbreviation: 'Sq'}, + {name: 'Street', abbreviation: 'St'}, + {name: 'Terrace', abbreviation: 'Ter'}, + {name: 'Valley', abbreviation: 'Val'} + ] + }, - if (callback) { - const cb = callback - callback = null - cb(null, this) - } - }) - .on('error', function (err) { - cancelTimeout() + months: [ + {name: 'January', short_name: 'Jan', numeric: '01', days: 31}, + // Not messing with leap years... + {name: 'February', short_name: 'Feb', numeric: '02', days: 28}, + {name: 'March', short_name: 'Mar', numeric: '03', days: 31}, + {name: 'April', short_name: 'Apr', numeric: '04', days: 30}, + {name: 'May', short_name: 'May', numeric: '05', days: 31}, + {name: 'June', short_name: 'Jun', numeric: '06', days: 30}, + {name: 'July', short_name: 'Jul', numeric: '07', days: 31}, + {name: 'August', short_name: 'Aug', numeric: '08', days: 31}, + {name: 'September', short_name: 'Sep', numeric: '09', days: 30}, + {name: 'October', short_name: 'Oct', numeric: '10', days: 31}, + {name: 'November', short_name: 'Nov', numeric: '11', days: 30}, + {name: 'December', short_name: 'Dec', numeric: '12', days: 31} + ], - if (callback) { - const cb = callback - callback = null - cb(err) - } - }) + // http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29 + cc_types: [ + {name: "American Express", short_name: 'amex', prefix: '34', length: 15}, + {name: "Bankcard", short_name: 'bankcard', prefix: '5610', length: 16}, + {name: "China UnionPay", short_name: 'chinaunion', prefix: '62', length: 16}, + {name: "Diners Club Carte Blanche", short_name: 'dccarte', prefix: '300', length: 14}, + {name: "Diners Club enRoute", short_name: 'dcenroute', prefix: '2014', length: 15}, + {name: "Diners Club International", short_name: 'dcintl', prefix: '36', length: 14}, + {name: "Diners Club United States & Canada", short_name: 'dcusc', prefix: '54', length: 16}, + {name: "Discover Card", short_name: 'discover', prefix: '6011', length: 16}, + {name: "InstaPayment", short_name: 'instapay', prefix: '637', length: 16}, + {name: "JCB", short_name: 'jcb', prefix: '3528', length: 16}, + {name: "Laser", short_name: 'laser', prefix: '6304', length: 16}, + {name: "Maestro", short_name: 'maestro', prefix: '5018', length: 16}, + {name: "Mastercard", short_name: 'mc', prefix: '51', length: 16}, + {name: "Solo", short_name: 'solo', prefix: '6334', length: 16}, + {name: "Switch", short_name: 'switch', prefix: '4903', length: 16}, + {name: "Visa", short_name: 'visa', prefix: '4', length: 16}, + {name: "Visa Electron", short_name: 'electron', prefix: '4026', length: 16} + ], - return socket - } -} + //return all world currency by ISO 4217 + currency_types: [ + {'code' : 'AED', 'name' : 'United Arab Emirates Dirham'}, + {'code' : 'AFN', 'name' : 'Afghanistan Afghani'}, + {'code' : 'ALL', 'name' : 'Albania Lek'}, + {'code' : 'AMD', 'name' : 'Armenia Dram'}, + {'code' : 'ANG', 'name' : 'Netherlands Antilles Guilder'}, + {'code' : 'AOA', 'name' : 'Angola Kwanza'}, + {'code' : 'ARS', 'name' : 'Argentina Peso'}, + {'code' : 'AUD', 'name' : 'Australia Dollar'}, + {'code' : 'AWG', 'name' : 'Aruba Guilder'}, + {'code' : 'AZN', 'name' : 'Azerbaijan New Manat'}, + {'code' : 'BAM', 'name' : 'Bosnia and Herzegovina Convertible Marka'}, + {'code' : 'BBD', 'name' : 'Barbados Dollar'}, + {'code' : 'BDT', 'name' : 'Bangladesh Taka'}, + {'code' : 'BGN', 'name' : 'Bulgaria Lev'}, + {'code' : 'BHD', 'name' : 'Bahrain Dinar'}, + {'code' : 'BIF', 'name' : 'Burundi Franc'}, + {'code' : 'BMD', 'name' : 'Bermuda Dollar'}, + {'code' : 'BND', 'name' : 'Brunei Darussalam Dollar'}, + {'code' : 'BOB', 'name' : 'Bolivia Boliviano'}, + {'code' : 'BRL', 'name' : 'Brazil Real'}, + {'code' : 'BSD', 'name' : 'Bahamas Dollar'}, + {'code' : 'BTN', 'name' : 'Bhutan Ngultrum'}, + {'code' : 'BWP', 'name' : 'Botswana Pula'}, + {'code' : 'BYR', 'name' : 'Belarus Ruble'}, + {'code' : 'BZD', 'name' : 'Belize Dollar'}, + {'code' : 'CAD', 'name' : 'Canada Dollar'}, + {'code' : 'CDF', 'name' : 'Congo/Kinshasa Franc'}, + {'code' : 'CHF', 'name' : 'Switzerland Franc'}, + {'code' : 'CLP', 'name' : 'Chile Peso'}, + {'code' : 'CNY', 'name' : 'China Yuan Renminbi'}, + {'code' : 'COP', 'name' : 'Colombia Peso'}, + {'code' : 'CRC', 'name' : 'Costa Rica Colon'}, + {'code' : 'CUC', 'name' : 'Cuba Convertible Peso'}, + {'code' : 'CUP', 'name' : 'Cuba Peso'}, + {'code' : 'CVE', 'name' : 'Cape Verde Escudo'}, + {'code' : 'CZK', 'name' : 'Czech Republic Koruna'}, + {'code' : 'DJF', 'name' : 'Djibouti Franc'}, + {'code' : 'DKK', 'name' : 'Denmark Krone'}, + {'code' : 'DOP', 'name' : 'Dominican Republic Peso'}, + {'code' : 'DZD', 'name' : 'Algeria Dinar'}, + {'code' : 'EGP', 'name' : 'Egypt Pound'}, + {'code' : 'ERN', 'name' : 'Eritrea Nakfa'}, + {'code' : 'ETB', 'name' : 'Ethiopia Birr'}, + {'code' : 'EUR', 'name' : 'Euro Member Countries'}, + {'code' : 'FJD', 'name' : 'Fiji Dollar'}, + {'code' : 'FKP', 'name' : 'Falkland Islands (Malvinas) Pound'}, + {'code' : 'GBP', 'name' : 'United Kingdom Pound'}, + {'code' : 'GEL', 'name' : 'Georgia Lari'}, + {'code' : 'GGP', 'name' : 'Guernsey Pound'}, + {'code' : 'GHS', 'name' : 'Ghana Cedi'}, + {'code' : 'GIP', 'name' : 'Gibraltar Pound'}, + {'code' : 'GMD', 'name' : 'Gambia Dalasi'}, + {'code' : 'GNF', 'name' : 'Guinea Franc'}, + {'code' : 'GTQ', 'name' : 'Guatemala Quetzal'}, + {'code' : 'GYD', 'name' : 'Guyana Dollar'}, + {'code' : 'HKD', 'name' : 'Hong Kong Dollar'}, + {'code' : 'HNL', 'name' : 'Honduras Lempira'}, + {'code' : 'HRK', 'name' : 'Croatia Kuna'}, + {'code' : 'HTG', 'name' : 'Haiti Gourde'}, + {'code' : 'HUF', 'name' : 'Hungary Forint'}, + {'code' : 'IDR', 'name' : 'Indonesia Rupiah'}, + {'code' : 'ILS', 'name' : 'Israel Shekel'}, + {'code' : 'IMP', 'name' : 'Isle of Man Pound'}, + {'code' : 'INR', 'name' : 'India Rupee'}, + {'code' : 'IQD', 'name' : 'Iraq Dinar'}, + {'code' : 'IRR', 'name' : 'Iran Rial'}, + {'code' : 'ISK', 'name' : 'Iceland Krona'}, + {'code' : 'JEP', 'name' : 'Jersey Pound'}, + {'code' : 'JMD', 'name' : 'Jamaica Dollar'}, + {'code' : 'JOD', 'name' : 'Jordan Dinar'}, + {'code' : 'JPY', 'name' : 'Japan Yen'}, + {'code' : 'KES', 'name' : 'Kenya Shilling'}, + {'code' : 'KGS', 'name' : 'Kyrgyzstan Som'}, + {'code' : 'KHR', 'name' : 'Cambodia Riel'}, + {'code' : 'KMF', 'name' : 'Comoros Franc'}, + {'code' : 'KPW', 'name' : 'Korea (North) Won'}, + {'code' : 'KRW', 'name' : 'Korea (South) Won'}, + {'code' : 'KWD', 'name' : 'Kuwait Dinar'}, + {'code' : 'KYD', 'name' : 'Cayman Islands Dollar'}, + {'code' : 'KZT', 'name' : 'Kazakhstan Tenge'}, + {'code' : 'LAK', 'name' : 'Laos Kip'}, + {'code' : 'LBP', 'name' : 'Lebanon Pound'}, + {'code' : 'LKR', 'name' : 'Sri Lanka Rupee'}, + {'code' : 'LRD', 'name' : 'Liberia Dollar'}, + {'code' : 'LSL', 'name' : 'Lesotho Loti'}, + {'code' : 'LTL', 'name' : 'Lithuania Litas'}, + {'code' : 'LYD', 'name' : 'Libya Dinar'}, + {'code' : 'MAD', 'name' : 'Morocco Dirham'}, + {'code' : 'MDL', 'name' : 'Moldova Leu'}, + {'code' : 'MGA', 'name' : 'Madagascar Ariary'}, + {'code' : 'MKD', 'name' : 'Macedonia Denar'}, + {'code' : 'MMK', 'name' : 'Myanmar (Burma) Kyat'}, + {'code' : 'MNT', 'name' : 'Mongolia Tughrik'}, + {'code' : 'MOP', 'name' : 'Macau Pataca'}, + {'code' : 'MRO', 'name' : 'Mauritania Ouguiya'}, + {'code' : 'MUR', 'name' : 'Mauritius Rupee'}, + {'code' : 'MVR', 'name' : 'Maldives (Maldive Islands) Rufiyaa'}, + {'code' : 'MWK', 'name' : 'Malawi Kwacha'}, + {'code' : 'MXN', 'name' : 'Mexico Peso'}, + {'code' : 'MYR', 'name' : 'Malaysia Ringgit'}, + {'code' : 'MZN', 'name' : 'Mozambique Metical'}, + {'code' : 'NAD', 'name' : 'Namibia Dollar'}, + {'code' : 'NGN', 'name' : 'Nigeria Naira'}, + {'code' : 'NIO', 'name' : 'Nicaragua Cordoba'}, + {'code' : 'NOK', 'name' : 'Norway Krone'}, + {'code' : 'NPR', 'name' : 'Nepal Rupee'}, + {'code' : 'NZD', 'name' : 'New Zealand Dollar'}, + {'code' : 'OMR', 'name' : 'Oman Rial'}, + {'code' : 'PAB', 'name' : 'Panama Balboa'}, + {'code' : 'PEN', 'name' : 'Peru Nuevo Sol'}, + {'code' : 'PGK', 'name' : 'Papua New Guinea Kina'}, + {'code' : 'PHP', 'name' : 'Philippines Peso'}, + {'code' : 'PKR', 'name' : 'Pakistan Rupee'}, + {'code' : 'PLN', 'name' : 'Poland Zloty'}, + {'code' : 'PYG', 'name' : 'Paraguay Guarani'}, + {'code' : 'QAR', 'name' : 'Qatar Riyal'}, + {'code' : 'RON', 'name' : 'Romania New Leu'}, + {'code' : 'RSD', 'name' : 'Serbia Dinar'}, + {'code' : 'RUB', 'name' : 'Russia Ruble'}, + {'code' : 'RWF', 'name' : 'Rwanda Franc'}, + {'code' : 'SAR', 'name' : 'Saudi Arabia Riyal'}, + {'code' : 'SBD', 'name' : 'Solomon Islands Dollar'}, + {'code' : 'SCR', 'name' : 'Seychelles Rupee'}, + {'code' : 'SDG', 'name' : 'Sudan Pound'}, + {'code' : 'SEK', 'name' : 'Sweden Krona'}, + {'code' : 'SGD', 'name' : 'Singapore Dollar'}, + {'code' : 'SHP', 'name' : 'Saint Helena Pound'}, + {'code' : 'SLL', 'name' : 'Sierra Leone Leone'}, + {'code' : 'SOS', 'name' : 'Somalia Shilling'}, + {'code' : 'SPL', 'name' : 'Seborga Luigino'}, + {'code' : 'SRD', 'name' : 'Suriname Dollar'}, + {'code' : 'STD', 'name' : 'SĆ£o TomĆ© and PrĆ­ncipe Dobra'}, + {'code' : 'SVC', 'name' : 'El Salvador Colon'}, + {'code' : 'SYP', 'name' : 'Syria Pound'}, + {'code' : 'SZL', 'name' : 'Swaziland Lilangeni'}, + {'code' : 'THB', 'name' : 'Thailand Baht'}, + {'code' : 'TJS', 'name' : 'Tajikistan Somoni'}, + {'code' : 'TMT', 'name' : 'Turkmenistan Manat'}, + {'code' : 'TND', 'name' : 'Tunisia Dinar'}, + {'code' : 'TOP', 'name' : 'Tonga Pa\'anga'}, + {'code' : 'TRY', 'name' : 'Turkey Lira'}, + {'code' : 'TTD', 'name' : 'Trinidad and Tobago Dollar'}, + {'code' : 'TVD', 'name' : 'Tuvalu Dollar'}, + {'code' : 'TWD', 'name' : 'Taiwan New Dollar'}, + {'code' : 'TZS', 'name' : 'Tanzania Shilling'}, + {'code' : 'UAH', 'name' : 'Ukraine Hryvnia'}, + {'code' : 'UGX', 'name' : 'Uganda Shilling'}, + {'code' : 'USD', 'name' : 'United States Dollar'}, + {'code' : 'UYU', 'name' : 'Uruguay Peso'}, + {'code' : 'UZS', 'name' : 'Uzbekistan Som'}, + {'code' : 'VEF', 'name' : 'Venezuela Bolivar'}, + {'code' : 'VND', 'name' : 'Viet Nam Dong'}, + {'code' : 'VUV', 'name' : 'Vanuatu Vatu'}, + {'code' : 'WST', 'name' : 'Samoa Tala'}, + {'code' : 'XAF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BEAC) CFA Franc BEAC'}, + {'code' : 'XCD', 'name' : 'East Caribbean Dollar'}, + {'code' : 'XDR', 'name' : 'International Monetary Fund (IMF) Special Drawing Rights'}, + {'code' : 'XOF', 'name' : 'CommunautĆ© FinanciĆØre Africaine (BCEAO) Franc'}, + {'code' : 'XPF', 'name' : 'Comptoirs FranƧais du Pacifique (CFP) Franc'}, + {'code' : 'YER', 'name' : 'Yemen Rial'}, + {'code' : 'ZAR', 'name' : 'South Africa Rand'}, + {'code' : 'ZMW', 'name' : 'Zambia Kwacha'}, + {'code' : 'ZWD', 'name' : 'Zimbabwe Dollar'} + ], -function setupTimeout (onConnectTimeout, timeout) { - if (!timeout) { - return () => {} - } + // return the names of all valide colors + colorNames : [ "AliceBlue", "Black", "Navy", "DarkBlue", "MediumBlue", "Blue", "DarkGreen", "Green", "Teal", "DarkCyan", "DeepSkyBlue", "DarkTurquoise", "MediumSpringGreen", "Lime", "SpringGreen", + "Aqua", "Cyan", "MidnightBlue", "DodgerBlue", "LightSeaGreen", "ForestGreen", "SeaGreen", "DarkSlateGray", "LimeGreen", "MediumSeaGreen", "Turquoise", "RoyalBlue", "SteelBlue", "DarkSlateBlue", "MediumTurquoise", + "Indigo", "DarkOliveGreen", "CadetBlue", "CornflowerBlue", "RebeccaPurple", "MediumAquaMarine", "DimGray", "SlateBlue", "OliveDrab", "SlateGray", "LightSlateGray", "MediumSlateBlue", "LawnGreen", "Chartreuse", + "Aquamarine", "Maroon", "Purple", "Olive", "Gray", "SkyBlue", "LightSkyBlue", "BlueViolet", "DarkRed", "DarkMagenta", "SaddleBrown", "Ivory", "White", + "DarkSeaGreen", "LightGreen", "MediumPurple", "DarkViolet", "PaleGreen", "DarkOrchid", "YellowGreen", "Sienna", "Brown", "DarkGray", "LightBlue", "GreenYellow", "PaleTurquoise", "LightSteelBlue", "PowderBlue", + "FireBrick", "DarkGoldenRod", "MediumOrchid", "RosyBrown", "DarkKhaki", "Silver", "MediumVioletRed", "IndianRed", "Peru", "Chocolate", "Tan", "LightGray", "Thistle", "Orchid", "GoldenRod", "PaleVioletRed", + "Crimson", "Gainsboro", "Plum", "BurlyWood", "LightCyan", "Lavender", "DarkSalmon", "Violet", "PaleGoldenRod", "LightCoral", "Khaki", "AliceBlue", "HoneyDew", "Azure", "SandyBrown", "Wheat", "Beige", "WhiteSmoke", + "MintCream", "GhostWhite", "Salmon", "AntiqueWhite", "Linen", "LightGoldenRodYellow", "OldLace", "Red", "Fuchsia", "Magenta", "DeepPink", "OrangeRed", "Tomato", "HotPink", "Coral", "DarkOrange", "LightSalmon", "Orange", + "LightPink", "Pink", "Gold", "PeachPuff", "NavajoWhite", "Moccasin", "Bisque", "MistyRose", "BlanchedAlmond", "PapayaWhip", "LavenderBlush", "SeaShell", "Cornsilk", "LemonChiffon", "FloralWhite", "Snow", "Yellow", "LightYellow" + ], - 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) - } -} + // Data taken from https://www.sec.gov/rules/other/4-460list.htm + company: [ "3Com Corp", + "3M Company", + "A.G. Edwards Inc.", + "Abbott Laboratories", + "Abercrombie & Fitch Co.", + "ABM Industries Incorporated", + "Ace Hardware Corporation", + "ACT Manufacturing Inc.", + "Acterna Corp.", + "Adams Resources & Energy, Inc.", + "ADC Telecommunications, Inc.", + "Adelphia Communications Corporation", + "Administaff, Inc.", + "Adobe Systems Incorporated", + "Adolph Coors Company", + "Advance Auto Parts, Inc.", + "Advanced Micro Devices, Inc.", + "AdvancePCS, Inc.", + "Advantica Restaurant Group, Inc.", + "The AES Corporation", + "Aetna Inc.", + "Affiliated Computer Services, Inc.", + "AFLAC Incorporated", + "AGCO Corporation", + "Agilent Technologies, Inc.", + "Agway Inc.", + "Apartment Investment and Management Company", + "Air Products and Chemicals, Inc.", + "Airborne, Inc.", + "Airgas, Inc.", + "AK Steel Holding Corporation", + "Alaska Air Group, Inc.", + "Alberto-Culver Company", + "Albertson's, Inc.", + "Alcoa Inc.", + "Alleghany Corporation", + "Allegheny Energy, Inc.", + "Allegheny Technologies Incorporated", + "Allergan, Inc.", + "ALLETE, Inc.", + "Alliant Energy Corporation", + "Allied Waste Industries, Inc.", + "Allmerica Financial Corporation", + "The Allstate Corporation", + "ALLTEL Corporation", + "The Alpine Group, Inc.", + "Amazon.com, Inc.", + "AMC Entertainment Inc.", + "American Power Conversion Corporation", + "Amerada Hess Corporation", + "AMERCO", + "Ameren Corporation", + "America West Holdings Corporation", + "American Axle & Manufacturing Holdings, Inc.", + "American Eagle Outfitters, Inc.", + "American Electric Power Company, Inc.", + "American Express Company", + "American Financial Group, Inc.", + "American Greetings Corporation", + "American International Group, Inc.", + "American Standard Companies Inc.", + "American Water Works Company, Inc.", + "AmerisourceBergen Corporation", + "Ames Department Stores, Inc.", + "Amgen Inc.", + "Amkor Technology, Inc.", + "AMR Corporation", + "AmSouth Bancorp.", + "Amtran, Inc.", + "Anadarko Petroleum Corporation", + "Analog Devices, Inc.", + "Anheuser-Busch Companies, Inc.", + "Anixter International Inc.", + "AnnTaylor Inc.", + "Anthem, Inc.", + "AOL Time Warner Inc.", + "Aon Corporation", + "Apache Corporation", + "Apple Computer, Inc.", + "Applera Corporation", + "Applied Industrial Technologies, Inc.", + "Applied Materials, Inc.", + "Aquila, Inc.", + "ARAMARK Corporation", + "Arch Coal, Inc.", + "Archer Daniels Midland Company", + "Arkansas Best Corporation", + "Armstrong Holdings, Inc.", + "Arrow Electronics, Inc.", + "ArvinMeritor, Inc.", + "Ashland Inc.", + "Astoria Financial Corporation", + "AT&T Corp.", + "Atmel Corporation", + "Atmos Energy Corporation", + "Audiovox Corporation", + "Autoliv, Inc.", + "Automatic Data Processing, Inc.", + "AutoNation, Inc.", + "AutoZone, Inc.", + "Avaya Inc.", + "Avery Dennison Corporation", + "Avista Corporation", + "Avnet, Inc.", + "Avon Products, Inc.", + "Baker Hughes Incorporated", + "Ball Corporation", + "Bank of America Corporation", + "The Bank of New York Company, Inc.", + "Bank One Corporation", + "Banknorth Group, Inc.", + "Banta Corporation", + "Barnes & Noble, Inc.", + "Bausch & Lomb Incorporated", + "Baxter International Inc.", + "BB&T Corporation", + "The Bear Stearns Companies Inc.", + "Beazer Homes USA, Inc.", + "Beckman Coulter, Inc.", + "Becton, Dickinson and Company", + "Bed Bath & Beyond Inc.", + "Belk, Inc.", + "Bell Microproducts Inc.", + "BellSouth Corporation", + "Belo Corp.", + "Bemis Company, Inc.", + "Benchmark Electronics, Inc.", + "Berkshire Hathaway Inc.", + "Best Buy Co., Inc.", + "Bethlehem Steel Corporation", + "Beverly Enterprises, Inc.", + "Big Lots, Inc.", + "BJ Services Company", + "BJ's Wholesale Club, Inc.", + "The Black & Decker Corporation", + "Black Hills Corporation", + "BMC Software, Inc.", + "The Boeing Company", + "Boise Cascade Corporation", + "Borders Group, Inc.", + "BorgWarner Inc.", + "Boston Scientific Corporation", + "Bowater Incorporated", + "Briggs & Stratton Corporation", + "Brightpoint, Inc.", + "Brinker International, Inc.", + "Bristol-Myers Squibb Company", + "Broadwing, Inc.", + "Brown Shoe Company, Inc.", + "Brown-Forman Corporation", + "Brunswick Corporation", + "Budget Group, Inc.", + "Burlington Coat Factory Warehouse Corporation", + "Burlington Industries, Inc.", + "Burlington Northern Santa Fe Corporation", + "Burlington Resources Inc.", + "C. H. Robinson Worldwide Inc.", + "Cablevision Systems Corp", + "Cabot Corp", + "Cadence Design Systems, Inc.", + "Calpine Corp.", + "Campbell Soup Co.", + "Capital One Financial Corp.", + "Cardinal Health Inc.", + "Caremark Rx Inc.", + "Carlisle Cos. Inc.", + "Carpenter Technology Corp.", + "Casey's General Stores Inc.", + "Caterpillar Inc.", + "CBRL Group Inc.", + "CDI Corp.", + "CDW Computer Centers Inc.", + "CellStar Corp.", + "Cendant Corp", + "Cenex Harvest States Cooperatives", + "Centex Corp.", + "CenturyTel Inc.", + "Ceridian Corp.", + "CH2M Hill Cos. Ltd.", + "Champion Enterprises Inc.", + "Charles Schwab Corp.", + "Charming Shoppes Inc.", + "Charter Communications Inc.", + "Charter One Financial Inc.", + "ChevronTexaco Corp.", + "Chiquita Brands International Inc.", + "Chubb Corp", + "Ciena Corp.", + "Cigna Corp", + "Cincinnati Financial Corp.", + "Cinergy Corp.", + "Cintas Corp.", + "Circuit City Stores Inc.", + "Cisco Systems Inc.", + "Citigroup, Inc", + "Citizens Communications Co.", + "CKE Restaurants Inc.", + "Clear Channel Communications Inc.", + "The Clorox Co.", + "CMGI Inc.", + "CMS Energy Corp.", + "CNF Inc.", + "Coca-Cola Co.", + "Coca-Cola Enterprises Inc.", + "Colgate-Palmolive Co.", + "Collins & Aikman Corp.", + "Comcast Corp.", + "Comdisco Inc.", + "Comerica Inc.", + "Comfort Systems USA Inc.", + "Commercial Metals Co.", + "Community Health Systems Inc.", + "Compass Bancshares Inc", + "Computer Associates International Inc.", + "Computer Sciences Corp.", + "Compuware Corp.", + "Comverse Technology Inc.", + "ConAgra Foods Inc.", + "Concord EFS Inc.", + "Conectiv, Inc", + "Conoco Inc", + "Conseco Inc.", + "Consolidated Freightways Corp.", + "Consolidated Edison Inc.", + "Constellation Brands Inc.", + "Constellation Emergy Group Inc.", + "Continental Airlines Inc.", + "Convergys Corp.", + "Cooper Cameron Corp.", + "Cooper Industries Ltd.", + "Cooper Tire & Rubber Co.", + "Corn Products International Inc.", + "Corning Inc.", + "Costco Wholesale Corp.", + "Countrywide Credit Industries Inc.", + "Coventry Health Care Inc.", + "Cox Communications Inc.", + "Crane Co.", + "Crompton Corp.", + "Crown Cork & Seal Co. Inc.", + "CSK Auto Corp.", + "CSX Corp.", + "Cummins Inc.", + "CVS Corp.", + "Cytec Industries Inc.", + "D&K Healthcare Resources, Inc.", + "D.R. Horton Inc.", + "Dana Corporation", + "Danaher Corporation", + "Darden Restaurants Inc.", + "DaVita Inc.", + "Dean Foods Company", + "Deere & Company", + "Del Monte Foods Co", + "Dell Computer Corporation", + "Delphi Corp.", + "Delta Air Lines Inc.", + "Deluxe Corporation", + "Devon Energy Corporation", + "Di Giorgio Corporation", + "Dial Corporation", + "Diebold Incorporated", + "Dillard's Inc.", + "DIMON Incorporated", + "Dole Food Company, Inc.", + "Dollar General Corporation", + "Dollar Tree Stores, Inc.", + "Dominion Resources, Inc.", + "Domino's Pizza LLC", + "Dover Corporation, Inc.", + "Dow Chemical Company", + "Dow Jones & Company, Inc.", + "DPL Inc.", + "DQE Inc.", + "Dreyer's Grand Ice Cream, Inc.", + "DST Systems, Inc.", + "DTE Energy Co.", + "E.I. Du Pont de Nemours and Company", + "Duke Energy Corp", + "Dun & Bradstreet Inc.", + "DURA Automotive Systems Inc.", + "DynCorp", + "Dynegy Inc.", + "E*Trade Group, Inc.", + "E.W. Scripps Company", + "Earthlink, Inc.", + "Eastman Chemical Company", + "Eastman Kodak Company", + "Eaton Corporation", + "Echostar Communications Corporation", + "Ecolab Inc.", + "Edison International", + "EGL Inc.", + "El Paso Corporation", + "Electronic Arts Inc.", + "Electronic Data Systems Corp.", + "Eli Lilly and Company", + "EMC Corporation", + "Emcor Group Inc.", + "Emerson Electric Co.", + "Encompass Services Corporation", + "Energizer Holdings Inc.", + "Energy East Corporation", + "Engelhard Corporation", + "Enron Corp.", + "Entergy Corporation", + "Enterprise Products Partners L.P.", + "EOG Resources, Inc.", + "Equifax Inc.", + "Equitable Resources Inc.", + "Equity Office Properties Trust", + "Equity Residential Properties Trust", + "Estee Lauder Companies Inc.", + "Exelon Corporation", + "Exide Technologies", + "Expeditors International of Washington Inc.", + "Express Scripts Inc.", + "ExxonMobil Corporation", + "Fairchild Semiconductor International Inc.", + "Family Dollar Stores Inc.", + "Farmland Industries Inc.", + "Federal Mogul Corp.", + "Federated Department Stores Inc.", + "Federal Express Corp.", + "Felcor Lodging Trust Inc.", + "Ferro Corp.", + "Fidelity National Financial Inc.", + "Fifth Third Bancorp", + "First American Financial Corp.", + "First Data Corp.", + "First National of Nebraska Inc.", + "First Tennessee National Corp.", + "FirstEnergy Corp.", + "Fiserv Inc.", + "Fisher Scientific International Inc.", + "FleetBoston Financial Co.", + "Fleetwood Enterprises Inc.", + "Fleming Companies Inc.", + "Flowers Foods Inc.", + "Flowserv Corp", + "Fluor Corp", + "FMC Corp", + "Foamex International Inc", + "Foot Locker Inc", + "Footstar Inc.", + "Ford Motor Co", + "Forest Laboratories Inc.", + "Fortune Brands Inc.", + "Foster Wheeler Ltd.", + "FPL Group Inc.", + "Franklin Resources Inc.", + "Freeport McMoran Copper & Gold Inc.", + "Frontier Oil Corp", + "Furniture Brands International Inc.", + "Gannett Co., Inc.", + "Gap Inc.", + "Gateway Inc.", + "GATX Corporation", + "Gemstar-TV Guide International Inc.", + "GenCorp Inc.", + "General Cable Corporation", + "General Dynamics Corporation", + "General Electric Company", + "General Mills Inc", + "General Motors Corporation", + "Genesis Health Ventures Inc.", + "Gentek Inc.", + "Gentiva Health Services Inc.", + "Genuine Parts Company", + "Genuity Inc.", + "Genzyme Corporation", + "Georgia Gulf Corporation", + "Georgia-Pacific Corporation", + "Gillette Company", + "Gold Kist Inc.", + "Golden State Bancorp Inc.", + "Golden West Financial Corporation", + "Goldman Sachs Group Inc.", + "Goodrich Corporation", + "The Goodyear Tire & Rubber Company", + "Granite Construction Incorporated", + "Graybar Electric Company Inc.", + "Great Lakes Chemical Corporation", + "Great Plains Energy Inc.", + "GreenPoint Financial Corp.", + "Greif Bros. Corporation", + "Grey Global Group Inc.", + "Group 1 Automotive Inc.", + "Guidant Corporation", + "H&R Block Inc.", + "H.B. Fuller Company", + "H.J. Heinz Company", + "Halliburton Co.", + "Harley-Davidson Inc.", + "Harman International Industries Inc.", + "Harrah's Entertainment Inc.", + "Harris Corp.", + "Harsco Corp.", + "Hartford Financial Services Group Inc.", + "Hasbro Inc.", + "Hawaiian Electric Industries Inc.", + "HCA Inc.", + "Health Management Associates Inc.", + "Health Net Inc.", + "Healthsouth Corp", + "Henry Schein Inc.", + "Hercules Inc.", + "Herman Miller Inc.", + "Hershey Foods Corp.", + "Hewlett-Packard Company", + "Hibernia Corp.", + "Hillenbrand Industries Inc.", + "Hilton Hotels Corp.", + "Hollywood Entertainment Corp.", + "Home Depot Inc.", + "Hon Industries Inc.", + "Honeywell International Inc.", + "Hormel Foods Corp.", + "Host Marriott Corp.", + "Household International Corp.", + "Hovnanian Enterprises Inc.", + "Hub Group Inc.", + "Hubbell Inc.", + "Hughes Supply Inc.", + "Humana Inc.", + "Huntington Bancshares Inc.", + "Idacorp Inc.", + "IDT Corporation", + "IKON Office Solutions Inc.", + "Illinois Tool Works Inc.", + "IMC Global Inc.", + "Imperial Sugar Company", + "IMS Health Inc.", + "Ingles Market Inc", + "Ingram Micro Inc.", + "Insight Enterprises Inc.", + "Integrated Electrical Services Inc.", + "Intel Corporation", + "International Paper Co.", + "Interpublic Group of Companies Inc.", + "Interstate Bakeries Corporation", + "International Business Machines Corp.", + "International Flavors & Fragrances Inc.", + "International Multifoods Corporation", + "Intuit Inc.", + "IT Group Inc.", + "ITT Industries Inc.", + "Ivax Corp.", + "J.B. Hunt Transport Services Inc.", + "J.C. Penny Co.", + "J.P. Morgan Chase & Co.", + "Jabil Circuit Inc.", + "Jack In The Box Inc.", + "Jacobs Engineering Group Inc.", + "JDS Uniphase Corp.", + "Jefferson-Pilot Co.", + "John Hancock Financial Services Inc.", + "Johnson & Johnson", + "Johnson Controls Inc.", + "Jones Apparel Group Inc.", + "KB Home", + "Kellogg Company", + "Kellwood Company", + "Kelly Services Inc.", + "Kemet Corp.", + "Kennametal Inc.", + "Kerr-McGee Corporation", + "KeyCorp", + "KeySpan Corp.", + "Kimball International Inc.", + "Kimberly-Clark Corporation", + "Kindred Healthcare Inc.", + "KLA-Tencor Corporation", + "K-Mart Corp.", + "Knight-Ridder Inc.", + "Kohl's Corp.", + "KPMG Consulting Inc.", + "Kroger Co.", + "L-3 Communications Holdings Inc.", + "Laboratory Corporation of America Holdings", + "Lam Research Corporation", + "LandAmerica Financial Group Inc.", + "Lands' End Inc.", + "Landstar System Inc.", + "La-Z-Boy Inc.", + "Lear Corporation", + "Legg Mason Inc.", + "Leggett & Platt Inc.", + "Lehman Brothers Holdings Inc.", + "Lennar Corporation", + "Lennox International Inc.", + "Level 3 Communications Inc.", + "Levi Strauss & Co.", + "Lexmark International Inc.", + "Limited Inc.", + "Lincoln National Corporation", + "Linens 'n Things Inc.", + "Lithia Motors Inc.", + "Liz Claiborne Inc.", + "Lockheed Martin Corporation", + "Loews Corporation", + "Longs Drug Stores Corporation", + "Louisiana-Pacific Corporation", + "Lowe's Companies Inc.", + "LSI Logic Corporation", + "The LTV Corporation", + "The Lubrizol Corporation", + "Lucent Technologies Inc.", + "Lyondell Chemical Company", + "M & T Bank Corporation", + "Magellan Health Services Inc.", + "Mail-Well Inc.", + "Mandalay Resort Group", + "Manor Care Inc.", + "Manpower Inc.", + "Marathon Oil Corporation", + "Mariner Health Care Inc.", + "Markel Corporation", + "Marriott International Inc.", + "Marsh & McLennan Companies Inc.", + "Marsh Supermarkets Inc.", + "Marshall & Ilsley Corporation", + "Martin Marietta Materials Inc.", + "Masco Corporation", + "Massey Energy Company", + "MasTec Inc.", + "Mattel Inc.", + "Maxim Integrated Products Inc.", + "Maxtor Corporation", + "Maxxam Inc.", + "The May Department Stores Company", + "Maytag Corporation", + "MBNA Corporation", + "McCormick & Company Incorporated", + "McDonald's Corporation", + "The McGraw-Hill Companies Inc.", + "McKesson Corporation", + "McLeodUSA Incorporated", + "M.D.C. Holdings Inc.", + "MDU Resources Group Inc.", + "MeadWestvaco Corporation", + "Medtronic Inc.", + "Mellon Financial Corporation", + "The Men's Wearhouse Inc.", + "Merck & Co., Inc.", + "Mercury General Corporation", + "Merrill Lynch & Co. Inc.", + "Metaldyne Corporation", + "Metals USA Inc.", + "MetLife Inc.", + "Metris Companies Inc", + "MGIC Investment Corporation", + "MGM Mirage", + "Michaels Stores Inc.", + "Micron Technology Inc.", + "Microsoft Corporation", + "Milacron Inc.", + "Millennium Chemicals Inc.", + "Mirant Corporation", + "Mohawk Industries Inc.", + "Molex Incorporated", + "The MONY Group Inc.", + "Morgan Stanley Dean Witter & Co.", + "Motorola Inc.", + "MPS Group Inc.", + "Murphy Oil Corporation", + "Nabors Industries Inc", + "Nacco Industries Inc", + "Nash Finch Company", + "National City Corp.", + "National Commerce Financial Corporation", + "National Fuel Gas Company", + "National Oilwell Inc", + "National Rural Utilities Cooperative Finance Corporation", + "National Semiconductor Corporation", + "National Service Industries Inc", + "Navistar International Corporation", + "NCR Corporation", + "The Neiman Marcus Group Inc.", + "New Jersey Resources Corporation", + "New York Times Company", + "Newell Rubbermaid Inc", + "Newmont Mining Corporation", + "Nextel Communications Inc", + "Nicor Inc", + "Nike Inc", + "NiSource Inc", + "Noble Energy Inc", + "Nordstrom Inc", + "Norfolk Southern Corporation", + "Nortek Inc", + "North Fork Bancorporation Inc", + "Northeast Utilities System", + "Northern Trust Corporation", + "Northrop Grumman Corporation", + "NorthWestern Corporation", + "Novellus Systems Inc", + "NSTAR", + "NTL Incorporated", + "Nucor Corp", + "Nvidia Corp", + "NVR Inc", + "Northwest Airlines Corp", + "Occidental Petroleum Corp", + "Ocean Energy Inc", + "Office Depot Inc.", + "OfficeMax Inc", + "OGE Energy Corp", + "Oglethorpe Power Corp.", + "Ohio Casualty Corp.", + "Old Republic International Corp.", + "Olin Corp.", + "OM Group Inc", + "Omnicare Inc", + "Omnicom Group", + "On Semiconductor Corp", + "ONEOK Inc", + "Oracle Corp", + "Oshkosh Truck Corp", + "Outback Steakhouse Inc.", + "Owens & Minor Inc.", + "Owens Corning", + "Owens-Illinois Inc", + "Oxford Health Plans Inc", + "Paccar Inc", + "PacifiCare Health Systems Inc", + "Packaging Corp. of America", + "Pactiv Corp", + "Pall Corp", + "Pantry Inc", + "Park Place Entertainment Corp", + "Parker Hannifin Corp.", + "Pathmark Stores Inc.", + "Paychex Inc", + "Payless Shoesource Inc", + "Penn Traffic Co.", + "Pennzoil-Quaker State Company", + "Pentair Inc", + "Peoples Energy Corp.", + "PeopleSoft Inc", + "Pep Boys Manny, Moe & Jack", + "Potomac Electric Power Co.", + "Pepsi Bottling Group Inc.", + "PepsiAmericas Inc.", + "PepsiCo Inc.", + "Performance Food Group Co.", + "Perini Corp", + "PerkinElmer Inc", + "Perot Systems Corp", + "Petco Animal Supplies Inc.", + "Peter Kiewit Sons', Inc.", + "PETsMART Inc", + "Pfizer Inc", + "Pacific Gas & Electric Corp.", + "Pharmacia Corp", + "Phar Mor Inc.", + "Phelps Dodge Corp.", + "Philip Morris Companies Inc.", + "Phillips Petroleum Co", + "Phillips Van Heusen Corp.", + "Phoenix Companies Inc", + "Pier 1 Imports Inc.", + "Pilgrim's Pride Corporation", + "Pinnacle West Capital Corp", + "Pioneer-Standard Electronics Inc.", + "Pitney Bowes Inc.", + "Pittston Brinks Group", + "Plains All American Pipeline LP", + "PNC Financial Services Group Inc.", + "PNM Resources Inc", + "Polaris Industries Inc.", + "Polo Ralph Lauren Corp", + "PolyOne Corp", + "Popular Inc", + "Potlatch Corp", + "PPG Industries Inc", + "PPL Corp", + "Praxair Inc", + "Precision Castparts Corp", + "Premcor Inc.", + "Pride International Inc", + "Primedia Inc", + "Principal Financial Group Inc.", + "Procter & Gamble Co.", + "Pro-Fac Cooperative Inc.", + "Progress Energy Inc", + "Progressive Corporation", + "Protective Life Corp", + "Provident Financial Group", + "Providian Financial Corp.", + "Prudential Financial Inc.", + "PSS World Medical Inc", + "Public Service Enterprise Group Inc.", + "Publix Super Markets Inc.", + "Puget Energy Inc.", + "Pulte Homes Inc", + "Qualcomm Inc", + "Quanta Services Inc.", + "Quantum Corp", + "Quest Diagnostics Inc.", + "Questar Corp", + "Quintiles Transnational", + "Qwest Communications Intl Inc", + "R.J. Reynolds Tobacco Company", + "R.R. Donnelley & Sons Company", + "Radio Shack Corporation", + "Raymond James Financial Inc.", + "Raytheon Company", + "Reader's Digest Association Inc.", + "Reebok International Ltd.", + "Regions Financial Corp.", + "Regis Corporation", + "Reliance Steel & Aluminum Co.", + "Reliant Energy Inc.", + "Rent A Center Inc", + "Republic Services Inc", + "Revlon Inc", + "RGS Energy Group Inc", + "Rite Aid Corp", + "Riverwood Holding Inc.", + "RoadwayCorp", + "Robert Half International Inc.", + "Rock-Tenn Co", + "Rockwell Automation Inc", + "Rockwell Collins Inc", + "Rohm & Haas Co.", + "Ross Stores Inc", + "RPM Inc.", + "Ruddick Corp", + "Ryder System Inc", + "Ryerson Tull Inc", + "Ryland Group Inc.", + "Sabre Holdings Corp", + "Safeco Corp", + "Safeguard Scientifics Inc.", + "Safeway Inc", + "Saks Inc", + "Sanmina-SCI Inc", + "Sara Lee Corp", + "SBC Communications Inc", + "Scana Corp.", + "Schering-Plough Corp", + "Scholastic Corp", + "SCI Systems Onc.", + "Science Applications Intl. Inc.", + "Scientific-Atlanta Inc", + "Scotts Company", + "Seaboard Corp", + "Sealed Air Corp", + "Sears Roebuck & Co", + "Sempra Energy", + "Sequa Corp", + "Service Corp. International", + "ServiceMaster Co", + "Shaw Group Inc", + "Sherwin-Williams Company", + "Shopko Stores Inc", + "Siebel Systems Inc", + "Sierra Health Services Inc", + "Sierra Pacific Resources", + "Silgan Holdings Inc.", + "Silicon Graphics Inc", + "Simon Property Group Inc", + "SLM Corporation", + "Smith International Inc", + "Smithfield Foods Inc", + "Smurfit-Stone Container Corp", + "Snap-On Inc", + "Solectron Corp", + "Solutia Inc", + "Sonic Automotive Inc.", + "Sonoco Products Co.", + "Southern Company", + "Southern Union Company", + "SouthTrust Corp.", + "Southwest Airlines Co", + "Southwest Gas Corp", + "Sovereign Bancorp Inc.", + "Spartan Stores Inc", + "Spherion Corp", + "Sports Authority Inc", + "Sprint Corp.", + "SPX Corp", + "St. Jude Medical Inc", + "St. Paul Cos.", + "Staff Leasing Inc.", + "StanCorp Financial Group Inc", + "Standard Pacific Corp.", + "Stanley Works", + "Staples Inc", + "Starbucks Corp", + "Starwood Hotels & Resorts Worldwide Inc", + "State Street Corp.", + "Stater Bros. Holdings Inc.", + "Steelcase Inc", + "Stein Mart Inc", + "Stewart & Stevenson Services Inc", + "Stewart Information Services Corp", + "Stilwell Financial Inc", + "Storage Technology Corporation", + "Stryker Corp", + "Sun Healthcare Group Inc.", + "Sun Microsystems Inc.", + "SunGard Data Systems Inc.", + "Sunoco Inc.", + "SunTrust Banks Inc", + "Supervalu Inc", + "Swift Transportation, Co., Inc", + "Symbol Technologies Inc", + "Synovus Financial Corp.", + "Sysco Corp", + "Systemax Inc.", + "Target Corp.", + "Tech Data Corporation", + "TECO Energy Inc", + "Tecumseh Products Company", + "Tektronix Inc", + "Teleflex Incorporated", + "Telephone & Data Systems Inc", + "Tellabs Inc.", + "Temple-Inland Inc", + "Tenet Healthcare Corporation", + "Tenneco Automotive Inc.", + "Teradyne Inc", + "Terex Corp", + "Tesoro Petroleum Corp.", + "Texas Industries Inc.", + "Texas Instruments Incorporated", + "Textron Inc", + "Thermo Electron Corporation", + "Thomas & Betts Corporation", + "Tiffany & Co", + "Timken Company", + "TJX Companies Inc", + "TMP Worldwide Inc", + "Toll Brothers Inc", + "Torchmark Corporation", + "Toro Company", + "Tower Automotive Inc.", + "Toys 'R' Us Inc", + "Trans World Entertainment Corp.", + "TransMontaigne Inc", + "Transocean Inc", + "TravelCenters of America Inc.", + "Triad Hospitals Inc", + "Tribune Company", + "Trigon Healthcare Inc.", + "Trinity Industries Inc", + "Trump Hotels & Casino Resorts Inc.", + "TruServ Corporation", + "TRW Inc", + "TXU Corp", + "Tyson Foods Inc", + "U.S. Bancorp", + "U.S. Industries Inc.", + "UAL Corporation", + "UGI Corporation", + "Unified Western Grocers Inc", + "Union Pacific Corporation", + "Union Planters Corp", + "Unisource Energy Corp", + "Unisys Corporation", + "United Auto Group Inc", + "United Defense Industries Inc.", + "United Parcel Service Inc", + "United Rentals Inc", + "United Stationers Inc", + "United Technologies Corporation", + "UnitedHealth Group Incorporated", + "Unitrin Inc", + "Universal Corporation", + "Universal Forest Products Inc", + "Universal Health Services Inc", + "Unocal Corporation", + "Unova Inc", + "UnumProvident Corporation", + "URS Corporation", + "US Airways Group Inc", + "US Oncology Inc", + "USA Interactive", + "USFreighways Corporation", + "USG Corporation", + "UST Inc", + "Valero Energy Corporation", + "Valspar Corporation", + "Value City Department Stores Inc", + "Varco International Inc", + "Vectren Corporation", + "Veritas Software Corporation", + "Verizon Communications Inc", + "VF Corporation", + "Viacom Inc", + "Viad Corp", + "Viasystems Group Inc", + "Vishay Intertechnology Inc", + "Visteon Corporation", + "Volt Information Sciences Inc", + "Vulcan Materials Company", + "W.R. Berkley Corporation", + "W.R. Grace & Co", + "W.W. Grainger Inc", + "Wachovia Corporation", + "Wakenhut Corporation", + "Walgreen Co", + "Wallace Computer Services Inc", + "Wal-Mart Stores Inc", + "Walt Disney Co", + "Walter Industries Inc", + "Washington Mutual Inc", + "Washington Post Co.", + "Waste Management Inc", + "Watsco Inc", + "Weatherford International Inc", + "Weis Markets Inc.", + "Wellpoint Health Networks Inc", + "Wells Fargo & Company", + "Wendy's International Inc", + "Werner Enterprises Inc", + "WESCO International Inc", + "Western Digital Inc", + "Western Gas Resources Inc", + "WestPoint Stevens Inc", + "Weyerhauser Company", + "WGL Holdings Inc", + "Whirlpool Corporation", + "Whole Foods Market Inc", + "Willamette Industries Inc.", + "Williams Companies Inc", + "Williams Sonoma Inc", + "Winn Dixie Stores Inc", + "Wisconsin Energy Corporation", + "Wm Wrigley Jr Company", + "World Fuel Services Corporation", + "WorldCom Inc", + "Worthington Industries Inc", + "WPS Resources Corporation", + "Wyeth", + "Wyndham International Inc", + "Xcel Energy Inc", + "Xerox Corp", + "Xilinx Inc", + "XO Communications Inc", + "Yellow Corporation", + "York International Corp", + "Yum Brands Inc.", + "Zale Corporation", + "Zions Bancorporation" + ], -function onConnectTimeout (socket) { - util.destroy(socket, new ConnectTimeoutError()) -} + fileExtension : { + "raster" : ["bmp", "gif", "gpl", "ico", "jpeg", "psd", "png", "psp", "raw", "tiff"], + "vector" : ["3dv", "amf", "awg", "ai", "cgm", "cdr", "cmx", "dxf", "e2d", "egt", "eps", "fs", "odg", "svg", "xar"], + "3d" : ["3dmf", "3dm", "3mf", "3ds", "an8", "aoi", "blend", "cal3d", "cob", "ctm", "iob", "jas", "max", "mb", "mdx", "obj", "x", "x3d"], + "document" : ["doc", "docx", "dot", "html", "xml", "odt", "odm", "ott", "csv", "rtf", "tex", "xhtml", "xps"] + }, -module.exports = buildConnector + // Data taken from https://github.com/dmfilipenko/timezones.json/blob/master/timezones.json + timezones: [ + { + "name": "Dateline Standard Time", + "abbr": "DST", + "offset": -12, + "isdst": false, + "text": "(UTC-12:00) International Date Line West", + "utc": [ + "Etc/GMT+12" + ] + }, + { + "name": "UTC-11", + "abbr": "U", + "offset": -11, + "isdst": false, + "text": "(UTC-11:00) Coordinated Universal Time-11", + "utc": [ + "Etc/GMT+11", + "Pacific/Midway", + "Pacific/Niue", + "Pacific/Pago_Pago" + ] + }, + { + "name": "Hawaiian Standard Time", + "abbr": "HST", + "offset": -10, + "isdst": false, + "text": "(UTC-10:00) Hawaii", + "utc": [ + "Etc/GMT+10", + "Pacific/Honolulu", + "Pacific/Johnston", + "Pacific/Rarotonga", + "Pacific/Tahiti" + ] + }, + { + "name": "Alaskan Standard Time", + "abbr": "AKDT", + "offset": -8, + "isdst": true, + "text": "(UTC-09:00) Alaska", + "utc": [ + "America/Anchorage", + "America/Juneau", + "America/Nome", + "America/Sitka", + "America/Yakutat" + ] + }, + { + "name": "Pacific Standard Time (Mexico)", + "abbr": "PDT", + "offset": -7, + "isdst": true, + "text": "(UTC-08:00) Baja California", + "utc": [ + "America/Santa_Isabel" + ] + }, + { + "name": "Pacific Daylight Time", + "abbr": "PDT", + "offset": -7, + "isdst": true, + "text": "(UTC-07:00) Pacific Time (US & Canada)", + "utc": [ + "America/Dawson", + "America/Los_Angeles", + "America/Tijuana", + "America/Vancouver", + "America/Whitehorse" + ] + }, + { + "name": "Pacific Standard Time", + "abbr": "PST", + "offset": -8, + "isdst": false, + "text": "(UTC-08:00) Pacific Time (US & Canada)", + "utc": [ + "America/Dawson", + "America/Los_Angeles", + "America/Tijuana", + "America/Vancouver", + "America/Whitehorse", + "PST8PDT" + ] + }, + { + "name": "US Mountain Standard Time", + "abbr": "UMST", + "offset": -7, + "isdst": false, + "text": "(UTC-07:00) Arizona", + "utc": [ + "America/Creston", + "America/Dawson_Creek", + "America/Hermosillo", + "America/Phoenix", + "Etc/GMT+7" + ] + }, + { + "name": "Mountain Standard Time (Mexico)", + "abbr": "MDT", + "offset": -6, + "isdst": true, + "text": "(UTC-07:00) Chihuahua, La Paz, Mazatlan", + "utc": [ + "America/Chihuahua", + "America/Mazatlan" + ] + }, + { + "name": "Mountain Standard Time", + "abbr": "MDT", + "offset": -6, + "isdst": true, + "text": "(UTC-07:00) Mountain Time (US & Canada)", + "utc": [ + "America/Boise", + "America/Cambridge_Bay", + "America/Denver", + "America/Edmonton", + "America/Inuvik", + "America/Ojinaga", + "America/Yellowknife", + "MST7MDT" + ] + }, + { + "name": "Central America Standard Time", + "abbr": "CAST", + "offset": -6, + "isdst": false, + "text": "(UTC-06:00) Central America", + "utc": [ + "America/Belize", + "America/Costa_Rica", + "America/El_Salvador", + "America/Guatemala", + "America/Managua", + "America/Tegucigalpa", + "Etc/GMT+6", + "Pacific/Galapagos" + ] + }, + { + "name": "Central Standard Time", + "abbr": "CDT", + "offset": -5, + "isdst": true, + "text": "(UTC-06:00) Central Time (US & Canada)", + "utc": [ + "America/Chicago", + "America/Indiana/Knox", + "America/Indiana/Tell_City", + "America/Matamoros", + "America/Menominee", + "America/North_Dakota/Beulah", + "America/North_Dakota/Center", + "America/North_Dakota/New_Salem", + "America/Rainy_River", + "America/Rankin_Inlet", + "America/Resolute", + "America/Winnipeg", + "CST6CDT" + ] + }, + { + "name": "Central Standard Time (Mexico)", + "abbr": "CDT", + "offset": -5, + "isdst": true, + "text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey", + "utc": [ + "America/Bahia_Banderas", + "America/Cancun", + "America/Merida", + "America/Mexico_City", + "America/Monterrey" + ] + }, + { + "name": "Canada Central Standard Time", + "abbr": "CCST", + "offset": -6, + "isdst": false, + "text": "(UTC-06:00) Saskatchewan", + "utc": [ + "America/Regina", + "America/Swift_Current" + ] + }, + { + "name": "SA Pacific Standard Time", + "abbr": "SPST", + "offset": -5, + "isdst": false, + "text": "(UTC-05:00) Bogota, Lima, Quito", + "utc": [ + "America/Bogota", + "America/Cayman", + "America/Coral_Harbour", + "America/Eirunepe", + "America/Guayaquil", + "America/Jamaica", + "America/Lima", + "America/Panama", + "America/Rio_Branco", + "Etc/GMT+5" + ] + }, + { + "name": "Eastern Standard Time", + "abbr": "EDT", + "offset": -4, + "isdst": true, + "text": "(UTC-05:00) Eastern Time (US & Canada)", + "utc": [ + "America/Detroit", + "America/Havana", + "America/Indiana/Petersburg", + "America/Indiana/Vincennes", + "America/Indiana/Winamac", + "America/Iqaluit", + "America/Kentucky/Monticello", + "America/Louisville", + "America/Montreal", + "America/Nassau", + "America/New_York", + "America/Nipigon", + "America/Pangnirtung", + "America/Port-au-Prince", + "America/Thunder_Bay", + "America/Toronto", + "EST5EDT" + ] + }, + { + "name": "US Eastern Standard Time", + "abbr": "UEDT", + "offset": -4, + "isdst": true, + "text": "(UTC-05:00) Indiana (East)", + "utc": [ + "America/Indiana/Marengo", + "America/Indiana/Vevay", + "America/Indianapolis" + ] + }, + { + "name": "Venezuela Standard Time", + "abbr": "VST", + "offset": -4.5, + "isdst": false, + "text": "(UTC-04:30) Caracas", + "utc": [ + "America/Caracas" + ] + }, + { + "name": "Paraguay Standard Time", + "abbr": "PYT", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Asuncion", + "utc": [ + "America/Asuncion" + ] + }, + { + "name": "Atlantic Standard Time", + "abbr": "ADT", + "offset": -3, + "isdst": true, + "text": "(UTC-04:00) Atlantic Time (Canada)", + "utc": [ + "America/Glace_Bay", + "America/Goose_Bay", + "America/Halifax", + "America/Moncton", + "America/Thule", + "Atlantic/Bermuda" + ] + }, + { + "name": "Central Brazilian Standard Time", + "abbr": "CBST", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Cuiaba", + "utc": [ + "America/Campo_Grande", + "America/Cuiaba" + ] + }, + { + "name": "SA Western Standard Time", + "abbr": "SWST", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Georgetown, La Paz, Manaus, San Juan", + "utc": [ + "America/Anguilla", + "America/Antigua", + "America/Aruba", + "America/Barbados", + "America/Blanc-Sablon", + "America/Boa_Vista", + "America/Curacao", + "America/Dominica", + "America/Grand_Turk", + "America/Grenada", + "America/Guadeloupe", + "America/Guyana", + "America/Kralendijk", + "America/La_Paz", + "America/Lower_Princes", + "America/Manaus", + "America/Marigot", + "America/Martinique", + "America/Montserrat", + "America/Port_of_Spain", + "America/Porto_Velho", + "America/Puerto_Rico", + "America/Santo_Domingo", + "America/St_Barthelemy", + "America/St_Kitts", + "America/St_Lucia", + "America/St_Thomas", + "America/St_Vincent", + "America/Tortola", + "Etc/GMT+4" + ] + }, + { + "name": "Pacific SA Standard Time", + "abbr": "PSST", + "offset": -4, + "isdst": false, + "text": "(UTC-04:00) Santiago", + "utc": [ + "America/Santiago", + "Antarctica/Palmer" + ] + }, + { + "name": "Newfoundland Standard Time", + "abbr": "NDT", + "offset": -2.5, + "isdst": true, + "text": "(UTC-03:30) Newfoundland", + "utc": [ + "America/St_Johns" + ] + }, + { + "name": "E. South America Standard Time", + "abbr": "ESAST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Brasilia", + "utc": [ + "America/Sao_Paulo" + ] + }, + { + "name": "Argentina Standard Time", + "abbr": "AST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Buenos Aires", + "utc": [ + "America/Argentina/La_Rioja", + "America/Argentina/Rio_Gallegos", + "America/Argentina/Salta", + "America/Argentina/San_Juan", + "America/Argentina/San_Luis", + "America/Argentina/Tucuman", + "America/Argentina/Ushuaia", + "America/Buenos_Aires", + "America/Catamarca", + "America/Cordoba", + "America/Jujuy", + "America/Mendoza" + ] + }, + { + "name": "SA Eastern Standard Time", + "abbr": "SEST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Cayenne, Fortaleza", + "utc": [ + "America/Araguaina", + "America/Belem", + "America/Cayenne", + "America/Fortaleza", + "America/Maceio", + "America/Paramaribo", + "America/Recife", + "America/Santarem", + "Antarctica/Rothera", + "Atlantic/Stanley", + "Etc/GMT+3" + ] + }, + { + "name": "Greenland Standard Time", + "abbr": "GDT", + "offset": -3, + "isdst": true, + "text": "(UTC-03:00) Greenland", + "utc": [ + "America/Godthab" + ] + }, + { + "name": "Montevideo Standard Time", + "abbr": "MST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Montevideo", + "utc": [ + "America/Montevideo" + ] + }, + { + "name": "Bahia Standard Time", + "abbr": "BST", + "offset": -3, + "isdst": false, + "text": "(UTC-03:00) Salvador", + "utc": [ + "America/Bahia" + ] + }, + { + "name": "UTC-02", + "abbr": "U", + "offset": -2, + "isdst": false, + "text": "(UTC-02:00) Coordinated Universal Time-02", + "utc": [ + "America/Noronha", + "Atlantic/South_Georgia", + "Etc/GMT+2" + ] + }, + { + "name": "Mid-Atlantic Standard Time", + "abbr": "MDT", + "offset": -1, + "isdst": true, + "text": "(UTC-02:00) Mid-Atlantic - Old", + "utc": [] + }, + { + "name": "Azores Standard Time", + "abbr": "ADT", + "offset": 0, + "isdst": true, + "text": "(UTC-01:00) Azores", + "utc": [ + "America/Scoresbysund", + "Atlantic/Azores" + ] + }, + { + "name": "Cape Verde Standard Time", + "abbr": "CVST", + "offset": -1, + "isdst": false, + "text": "(UTC-01:00) Cape Verde Is.", + "utc": [ + "Atlantic/Cape_Verde", + "Etc/GMT+1" + ] + }, + { + "name": "Morocco Standard Time", + "abbr": "MDT", + "offset": 1, + "isdst": true, + "text": "(UTC) Casablanca", + "utc": [ + "Africa/Casablanca", + "Africa/El_Aaiun" + ] + }, + { + "name": "UTC", + "abbr": "UTC", + "offset": 0, + "isdst": false, + "text": "(UTC) Coordinated Universal Time", + "utc": [ + "America/Danmarkshavn", + "Etc/GMT" + ] + }, + { + "name": "GMT Standard Time", + "abbr": "GMT", + "offset": 0, + "isdst": false, + "text": "(UTC) Edinburgh, London", + "utc": [ + "Europe/Isle_of_Man", + "Europe/Guernsey", + "Europe/Jersey", + "Europe/London" + ] + }, + { + "name": "British Summer Time", + "abbr": "BST", + "offset": 1, + "isdst": true, + "text": "(UTC+01:00) Edinburgh, London", + "utc": [ + "Europe/Isle_of_Man", + "Europe/Guernsey", + "Europe/Jersey", + "Europe/London" + ] + }, + { + "name": "GMT Standard Time", + "abbr": "GDT", + "offset": 1, + "isdst": true, + "text": "(UTC) Dublin, Lisbon", + "utc": [ + "Atlantic/Canary", + "Atlantic/Faeroe", + "Atlantic/Madeira", + "Europe/Dublin", + "Europe/Lisbon" + ] + }, + { + "name": "Greenwich Standard Time", + "abbr": "GST", + "offset": 0, + "isdst": false, + "text": "(UTC) Monrovia, Reykjavik", + "utc": [ + "Africa/Abidjan", + "Africa/Accra", + "Africa/Bamako", + "Africa/Banjul", + "Africa/Bissau", + "Africa/Conakry", + "Africa/Dakar", + "Africa/Freetown", + "Africa/Lome", + "Africa/Monrovia", + "Africa/Nouakchott", + "Africa/Ouagadougou", + "Africa/Sao_Tome", + "Atlantic/Reykjavik", + "Atlantic/St_Helena" + ] + }, + { + "name": "W. Europe Standard Time", + "abbr": "WEDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", + "utc": [ + "Arctic/Longyearbyen", + "Europe/Amsterdam", + "Europe/Andorra", + "Europe/Berlin", + "Europe/Busingen", + "Europe/Gibraltar", + "Europe/Luxembourg", + "Europe/Malta", + "Europe/Monaco", + "Europe/Oslo", + "Europe/Rome", + "Europe/San_Marino", + "Europe/Stockholm", + "Europe/Vaduz", + "Europe/Vatican", + "Europe/Vienna", + "Europe/Zurich" + ] + }, + { + "name": "Central Europe Standard Time", + "abbr": "CEDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", + "utc": [ + "Europe/Belgrade", + "Europe/Bratislava", + "Europe/Budapest", + "Europe/Ljubljana", + "Europe/Podgorica", + "Europe/Prague", + "Europe/Tirane" + ] + }, + { + "name": "Romance Standard Time", + "abbr": "RDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Brussels, Copenhagen, Madrid, Paris", + "utc": [ + "Africa/Ceuta", + "Europe/Brussels", + "Europe/Copenhagen", + "Europe/Madrid", + "Europe/Paris" + ] + }, + { + "name": "Central European Standard Time", + "abbr": "CEDT", + "offset": 2, + "isdst": true, + "text": "(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb", + "utc": [ + "Europe/Sarajevo", + "Europe/Skopje", + "Europe/Warsaw", + "Europe/Zagreb" + ] + }, + { + "name": "W. Central Africa Standard Time", + "abbr": "WCAST", + "offset": 1, + "isdst": false, + "text": "(UTC+01:00) West Central Africa", + "utc": [ + "Africa/Algiers", + "Africa/Bangui", + "Africa/Brazzaville", + "Africa/Douala", + "Africa/Kinshasa", + "Africa/Lagos", + "Africa/Libreville", + "Africa/Luanda", + "Africa/Malabo", + "Africa/Ndjamena", + "Africa/Niamey", + "Africa/Porto-Novo", + "Africa/Tunis", + "Etc/GMT-1" + ] + }, + { + "name": "Namibia Standard Time", + "abbr": "NST", + "offset": 1, + "isdst": false, + "text": "(UTC+01:00) Windhoek", + "utc": [ + "Africa/Windhoek" + ] + }, + { + "name": "GTB Standard Time", + "abbr": "GDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Athens, Bucharest", + "utc": [ + "Asia/Nicosia", + "Europe/Athens", + "Europe/Bucharest", + "Europe/Chisinau" + ] + }, + { + "name": "Middle East Standard Time", + "abbr": "MEDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Beirut", + "utc": [ + "Asia/Beirut" + ] + }, + { + "name": "Egypt Standard Time", + "abbr": "EST", + "offset": 2, + "isdst": false, + "text": "(UTC+02:00) Cairo", + "utc": [ + "Africa/Cairo" + ] + }, + { + "name": "Syria Standard Time", + "abbr": "SDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Damascus", + "utc": [ + "Asia/Damascus" + ] + }, + { + "name": "E. Europe Standard Time", + "abbr": "EEDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) E. Europe", + "utc": [ + "Asia/Nicosia", + "Europe/Athens", + "Europe/Bucharest", + "Europe/Chisinau", + "Europe/Helsinki", + "Europe/Kiev", + "Europe/Mariehamn", + "Europe/Nicosia", + "Europe/Riga", + "Europe/Sofia", + "Europe/Tallinn", + "Europe/Uzhgorod", + "Europe/Vilnius", + "Europe/Zaporozhye" + ] + }, + { + "name": "South Africa Standard Time", + "abbr": "SAST", + "offset": 2, + "isdst": false, + "text": "(UTC+02:00) Harare, Pretoria", + "utc": [ + "Africa/Blantyre", + "Africa/Bujumbura", + "Africa/Gaborone", + "Africa/Harare", + "Africa/Johannesburg", + "Africa/Kigali", + "Africa/Lubumbashi", + "Africa/Lusaka", + "Africa/Maputo", + "Africa/Maseru", + "Africa/Mbabane", + "Etc/GMT-2" + ] + }, + { + "name": "FLE Standard Time", + "abbr": "FDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", + "utc": [ + "Europe/Helsinki", + "Europe/Kiev", + "Europe/Mariehamn", + "Europe/Riga", + "Europe/Sofia", + "Europe/Tallinn", + "Europe/Uzhgorod", + "Europe/Vilnius", + "Europe/Zaporozhye" + ] + }, + { + "name": "Turkey Standard Time", + "abbr": "TDT", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Istanbul", + "utc": [ + "Europe/Istanbul" + ] + }, + { + "name": "Israel Standard Time", + "abbr": "JDT", + "offset": 3, + "isdst": true, + "text": "(UTC+02:00) Jerusalem", + "utc": [ + "Asia/Jerusalem" + ] + }, + { + "name": "Libya Standard Time", + "abbr": "LST", + "offset": 2, + "isdst": false, + "text": "(UTC+02:00) Tripoli", + "utc": [ + "Africa/Tripoli" + ] + }, + { + "name": "Jordan Standard Time", + "abbr": "JST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Amman", + "utc": [ + "Asia/Amman" + ] + }, + { + "name": "Arabic Standard Time", + "abbr": "AST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Baghdad", + "utc": [ + "Asia/Baghdad" + ] + }, + { + "name": "Kaliningrad Standard Time", + "abbr": "KST", + "offset": 3, + "isdst": false, + "text": "(UTC+02:00) Kaliningrad", + "utc": [ + "Europe/Kaliningrad" + ] + }, + { + "name": "Arab Standard Time", + "abbr": "AST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Kuwait, Riyadh", + "utc": [ + "Asia/Aden", + "Asia/Bahrain", + "Asia/Kuwait", + "Asia/Qatar", + "Asia/Riyadh" + ] + }, + { + "name": "E. Africa Standard Time", + "abbr": "EAST", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Nairobi", + "utc": [ + "Africa/Addis_Ababa", + "Africa/Asmera", + "Africa/Dar_es_Salaam", + "Africa/Djibouti", + "Africa/Juba", + "Africa/Kampala", + "Africa/Khartoum", + "Africa/Mogadishu", + "Africa/Nairobi", + "Antarctica/Syowa", + "Etc/GMT-3", + "Indian/Antananarivo", + "Indian/Comoro", + "Indian/Mayotte" + ] + }, + { + "name": "Moscow Standard Time", + "abbr": "MSK", + "offset": 3, + "isdst": false, + "text": "(UTC+03:00) Moscow, St. Petersburg, Volgograd, Minsk", + "utc": [ + "Europe/Kirov", + "Europe/Moscow", + "Europe/Simferopol", + "Europe/Volgograd", + "Europe/Minsk" + ] + }, + { + "name": "Samara Time", + "abbr": "SAMT", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Samara, Ulyanovsk, Saratov", + "utc": [ + "Europe/Astrakhan", + "Europe/Samara", + "Europe/Ulyanovsk" + ] + }, + { + "name": "Iran Standard Time", + "abbr": "IDT", + "offset": 4.5, + "isdst": true, + "text": "(UTC+03:30) Tehran", + "utc": [ + "Asia/Tehran" + ] + }, + { + "name": "Arabian Standard Time", + "abbr": "AST", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Abu Dhabi, Muscat", + "utc": [ + "Asia/Dubai", + "Asia/Muscat", + "Etc/GMT-4" + ] + }, + { + "name": "Azerbaijan Standard Time", + "abbr": "ADT", + "offset": 5, + "isdst": true, + "text": "(UTC+04:00) Baku", + "utc": [ + "Asia/Baku" + ] + }, + { + "name": "Mauritius Standard Time", + "abbr": "MST", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Port Louis", + "utc": [ + "Indian/Mahe", + "Indian/Mauritius", + "Indian/Reunion" + ] + }, + { + "name": "Georgian Standard Time", + "abbr": "GET", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Tbilisi", + "utc": [ + "Asia/Tbilisi" + ] + }, + { + "name": "Caucasus Standard Time", + "abbr": "CST", + "offset": 4, + "isdst": false, + "text": "(UTC+04:00) Yerevan", + "utc": [ + "Asia/Yerevan" + ] + }, + { + "name": "Afghanistan Standard Time", + "abbr": "AST", + "offset": 4.5, + "isdst": false, + "text": "(UTC+04:30) Kabul", + "utc": [ + "Asia/Kabul" + ] + }, + { + "name": "West Asia Standard Time", + "abbr": "WAST", + "offset": 5, + "isdst": false, + "text": "(UTC+05:00) Ashgabat, Tashkent", + "utc": [ + "Antarctica/Mawson", + "Asia/Aqtau", + "Asia/Aqtobe", + "Asia/Ashgabat", + "Asia/Dushanbe", + "Asia/Oral", + "Asia/Samarkand", + "Asia/Tashkent", + "Etc/GMT-5", + "Indian/Kerguelen", + "Indian/Maldives" + ] + }, + { + "name": "Yekaterinburg Time", + "abbr": "YEKT", + "offset": 5, + "isdst": false, + "text": "(UTC+05:00) Yekaterinburg", + "utc": [ + "Asia/Yekaterinburg" + ] + }, + { + "name": "Pakistan Standard Time", + "abbr": "PKT", + "offset": 5, + "isdst": false, + "text": "(UTC+05:00) Islamabad, Karachi", + "utc": [ + "Asia/Karachi" + ] + }, + { + "name": "India Standard Time", + "abbr": "IST", + "offset": 5.5, + "isdst": false, + "text": "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi", + "utc": [ + "Asia/Kolkata" + ] + }, + { + "name": "Sri Lanka Standard Time", + "abbr": "SLST", + "offset": 5.5, + "isdst": false, + "text": "(UTC+05:30) Sri Jayawardenepura", + "utc": [ + "Asia/Colombo" + ] + }, + { + "name": "Nepal Standard Time", + "abbr": "NST", + "offset": 5.75, + "isdst": false, + "text": "(UTC+05:45) Kathmandu", + "utc": [ + "Asia/Kathmandu" + ] + }, + { + "name": "Central Asia Standard Time", + "abbr": "CAST", + "offset": 6, + "isdst": false, + "text": "(UTC+06:00) Nur-Sultan (Astana)", + "utc": [ + "Antarctica/Vostok", + "Asia/Almaty", + "Asia/Bishkek", + "Asia/Qyzylorda", + "Asia/Urumqi", + "Etc/GMT-6", + "Indian/Chagos" + ] + }, + { + "name": "Bangladesh Standard Time", + "abbr": "BST", + "offset": 6, + "isdst": false, + "text": "(UTC+06:00) Dhaka", + "utc": [ + "Asia/Dhaka", + "Asia/Thimphu" + ] + }, + { + "name": "Myanmar Standard Time", + "abbr": "MST", + "offset": 6.5, + "isdst": false, + "text": "(UTC+06:30) Yangon (Rangoon)", + "utc": [ + "Asia/Rangoon", + "Indian/Cocos" + ] + }, + { + "name": "SE Asia Standard Time", + "abbr": "SAST", + "offset": 7, + "isdst": false, + "text": "(UTC+07:00) Bangkok, Hanoi, Jakarta", + "utc": [ + "Antarctica/Davis", + "Asia/Bangkok", + "Asia/Hovd", + "Asia/Jakarta", + "Asia/Phnom_Penh", + "Asia/Pontianak", + "Asia/Saigon", + "Asia/Vientiane", + "Etc/GMT-7", + "Indian/Christmas" + ] + }, + { + "name": "N. Central Asia Standard Time", + "abbr": "NCAST", + "offset": 7, + "isdst": false, + "text": "(UTC+07:00) Novosibirsk", + "utc": [ + "Asia/Novokuznetsk", + "Asia/Novosibirsk", + "Asia/Omsk" + ] + }, + { + "name": "China Standard Time", + "abbr": "CST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi", + "utc": [ + "Asia/Hong_Kong", + "Asia/Macau", + "Asia/Shanghai" + ] + }, + { + "name": "North Asia Standard Time", + "abbr": "NAST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Krasnoyarsk", + "utc": [ + "Asia/Krasnoyarsk" + ] + }, + { + "name": "Singapore Standard Time", + "abbr": "MPST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Kuala Lumpur, Singapore", + "utc": [ + "Asia/Brunei", + "Asia/Kuala_Lumpur", + "Asia/Kuching", + "Asia/Makassar", + "Asia/Manila", + "Asia/Singapore", + "Etc/GMT-8" + ] + }, + { + "name": "W. Australia Standard Time", + "abbr": "WAST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Perth", + "utc": [ + "Antarctica/Casey", + "Australia/Perth" + ] + }, + { + "name": "Taipei Standard Time", + "abbr": "TST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Taipei", + "utc": [ + "Asia/Taipei" + ] + }, + { + "name": "Ulaanbaatar Standard Time", + "abbr": "UST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Ulaanbaatar", + "utc": [ + "Asia/Choibalsan", + "Asia/Ulaanbaatar" + ] + }, + { + "name": "North Asia East Standard Time", + "abbr": "NAEST", + "offset": 8, + "isdst": false, + "text": "(UTC+08:00) Irkutsk", + "utc": [ + "Asia/Irkutsk" + ] + }, + { + "name": "Japan Standard Time", + "abbr": "JST", + "offset": 9, + "isdst": false, + "text": "(UTC+09:00) Osaka, Sapporo, Tokyo", + "utc": [ + "Asia/Dili", + "Asia/Jayapura", + "Asia/Tokyo", + "Etc/GMT-9", + "Pacific/Palau" + ] + }, + { + "name": "Korea Standard Time", + "abbr": "KST", + "offset": 9, + "isdst": false, + "text": "(UTC+09:00) Seoul", + "utc": [ + "Asia/Pyongyang", + "Asia/Seoul" + ] + }, + { + "name": "Cen. Australia Standard Time", + "abbr": "CAST", + "offset": 9.5, + "isdst": false, + "text": "(UTC+09:30) Adelaide", + "utc": [ + "Australia/Adelaide", + "Australia/Broken_Hill" + ] + }, + { + "name": "AUS Central Standard Time", + "abbr": "ACST", + "offset": 9.5, + "isdst": false, + "text": "(UTC+09:30) Darwin", + "utc": [ + "Australia/Darwin" + ] + }, + { + "name": "E. Australia Standard Time", + "abbr": "EAST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Brisbane", + "utc": [ + "Australia/Brisbane", + "Australia/Lindeman" + ] + }, + { + "name": "AUS Eastern Standard Time", + "abbr": "AEST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Canberra, Melbourne, Sydney", + "utc": [ + "Australia/Melbourne", + "Australia/Sydney" + ] + }, + { + "name": "West Pacific Standard Time", + "abbr": "WPST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Guam, Port Moresby", + "utc": [ + "Antarctica/DumontDUrville", + "Etc/GMT-10", + "Pacific/Guam", + "Pacific/Port_Moresby", + "Pacific/Saipan", + "Pacific/Truk" + ] + }, + { + "name": "Tasmania Standard Time", + "abbr": "TST", + "offset": 10, + "isdst": false, + "text": "(UTC+10:00) Hobart", + "utc": [ + "Australia/Currie", + "Australia/Hobart" + ] + }, + { + "name": "Yakutsk Standard Time", + "abbr": "YST", + "offset": 9, + "isdst": false, + "text": "(UTC+09:00) Yakutsk", + "utc": [ + "Asia/Chita", + "Asia/Khandyga", + "Asia/Yakutsk" + ] + }, + { + "name": "Central Pacific Standard Time", + "abbr": "CPST", + "offset": 11, + "isdst": false, + "text": "(UTC+11:00) Solomon Is., New Caledonia", + "utc": [ + "Antarctica/Macquarie", + "Etc/GMT-11", + "Pacific/Efate", + "Pacific/Guadalcanal", + "Pacific/Kosrae", + "Pacific/Noumea", + "Pacific/Ponape" + ] + }, + { + "name": "Vladivostok Standard Time", + "abbr": "VST", + "offset": 11, + "isdst": false, + "text": "(UTC+11:00) Vladivostok", + "utc": [ + "Asia/Sakhalin", + "Asia/Ust-Nera", + "Asia/Vladivostok" + ] + }, + { + "name": "New Zealand Standard Time", + "abbr": "NZST", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Auckland, Wellington", + "utc": [ + "Antarctica/McMurdo", + "Pacific/Auckland" + ] + }, + { + "name": "UTC+12", + "abbr": "U", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Coordinated Universal Time+12", + "utc": [ + "Etc/GMT-12", + "Pacific/Funafuti", + "Pacific/Kwajalein", + "Pacific/Majuro", + "Pacific/Nauru", + "Pacific/Tarawa", + "Pacific/Wake", + "Pacific/Wallis" + ] + }, + { + "name": "Fiji Standard Time", + "abbr": "FST", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Fiji", + "utc": [ + "Pacific/Fiji" + ] + }, + { + "name": "Magadan Standard Time", + "abbr": "MST", + "offset": 12, + "isdst": false, + "text": "(UTC+12:00) Magadan", + "utc": [ + "Asia/Anadyr", + "Asia/Kamchatka", + "Asia/Magadan", + "Asia/Srednekolymsk" + ] + }, + { + "name": "Kamchatka Standard Time", + "abbr": "KDT", + "offset": 13, + "isdst": true, + "text": "(UTC+12:00) Petropavlovsk-Kamchatsky - Old", + "utc": [ + "Asia/Kamchatka" + ] + }, + { + "name": "Tonga Standard Time", + "abbr": "TST", + "offset": 13, + "isdst": false, + "text": "(UTC+13:00) Nuku'alofa", + "utc": [ + "Etc/GMT-13", + "Pacific/Enderbury", + "Pacific/Fakaofo", + "Pacific/Tongatapu" + ] + }, + { + "name": "Samoa Standard Time", + "abbr": "SST", + "offset": 13, + "isdst": false, + "text": "(UTC+13:00) Samoa", + "utc": [ + "Pacific/Apia" + ] + } + ], + //List source: http://answers.google.com/answers/threadview/id/589312.html + profession: [ + "Airline Pilot", + "Academic Team", + "Accountant", + "Account Executive", + "Actor", + "Actuary", + "Acquisition Analyst", + "Administrative Asst.", + "Administrative Analyst", + "Administrator", + "Advertising Director", + "Aerospace Engineer", + "Agent", + "Agricultural Inspector", + "Agricultural Scientist", + "Air Traffic Controller", + "Animal Trainer", + "Anthropologist", + "Appraiser", + "Architect", + "Art Director", + "Artist", + "Astronomer", + "Athletic Coach", + "Auditor", + "Author", + "Baker", + "Banker", + "Bankruptcy Attorney", + "Benefits Manager", + "Biologist", + "Bio-feedback Specialist", + "Biomedical Engineer", + "Biotechnical Researcher", + "Broadcaster", + "Broker", + "Building Manager", + "Building Contractor", + "Building Inspector", + "Business Analyst", + "Business Planner", + "Business Manager", + "Buyer", + "Call Center Manager", + "Career Counselor", + "Cash Manager", + "Ceramic Engineer", + "Chief Executive Officer", + "Chief Operation Officer", + "Chef", + "Chemical Engineer", + "Chemist", + "Child Care Manager", + "Chief Medical Officer", + "Chiropractor", + "Cinematographer", + "City Housing Manager", + "City Manager", + "Civil Engineer", + "Claims Manager", + "Clinical Research Assistant", + "Collections Manager", + "Compliance Manager", + "Comptroller", + "Computer Manager", + "Commercial Artist", + "Communications Affairs Director", + "Communications Director", + "Communications Engineer", + "Compensation Analyst", + "Computer Programmer", + "Computer Ops. Manager", + "Computer Engineer", + "Computer Operator", + "Computer Graphics Specialist", + "Construction Engineer", + "Construction Manager", + "Consultant", + "Consumer Relations Manager", + "Contract Administrator", + "Copyright Attorney", + "Copywriter", + "Corporate Planner", + "Corrections Officer", + "Cosmetologist", + "Credit Analyst", + "Cruise Director", + "Chief Information Officer", + "Chief Technology Officer", + "Customer Service Manager", + "Cryptologist", + "Dancer", + "Data Security Manager", + "Database Manager", + "Day Care Instructor", + "Dentist", + "Designer", + "Design Engineer", + "Desktop Publisher", + "Developer", + "Development Officer", + "Diamond Merchant", + "Dietitian", + "Direct Marketer", + "Director", + "Distribution Manager", + "Diversity Manager", + "Economist", + "EEO Compliance Manager", + "Editor", + "Education Adminator", + "Electrical Engineer", + "Electro Optical Engineer", + "Electronics Engineer", + "Embassy Management", + "Employment Agent", + "Engineer Technician", + "Entrepreneur", + "Environmental Analyst", + "Environmental Attorney", + "Environmental Engineer", + "Environmental Specialist", + "Escrow Officer", + "Estimator", + "Executive Assistant", + "Executive Director", + "Executive Recruiter", + "Facilities Manager", + "Family Counselor", + "Fashion Events Manager", + "Fashion Merchandiser", + "Fast Food Manager", + "Film Producer", + "Film Production Assistant", + "Financial Analyst", + "Financial Planner", + "Financier", + "Fine Artist", + "Wildlife Specialist", + "Fitness Consultant", + "Flight Attendant", + "Flight Engineer", + "Floral Designer", + "Food & Beverage Director", + "Food Service Manager", + "Forestry Technician", + "Franchise Management", + "Franchise Sales", + "Fraud Investigator", + "Freelance Writer", + "Fund Raiser", + "General Manager", + "Geologist", + "General Counsel", + "Geriatric Specialist", + "Gerontologist", + "Glamour Photographer", + "Golf Club Manager", + "Gourmet Chef", + "Graphic Designer", + "Grounds Keeper", + "Hazardous Waste Manager", + "Health Care Manager", + "Health Therapist", + "Health Service Administrator", + "Hearing Officer", + "Home Economist", + "Horticulturist", + "Hospital Administrator", + "Hotel Manager", + "Human Resources Manager", + "Importer", + "Industrial Designer", + "Industrial Engineer", + "Information Director", + "Inside Sales", + "Insurance Adjuster", + "Interior Decorator", + "Internal Controls Director", + "International Acct.", + "International Courier", + "International Lawyer", + "Interpreter", + "Investigator", + "Investment Banker", + "Investment Manager", + "IT Architect", + "IT Project Manager", + "IT Systems Analyst", + "Jeweler", + "Joint Venture Manager", + "Journalist", + "Labor Negotiator", + "Labor Organizer", + "Labor Relations Manager", + "Lab Services Director", + "Lab Technician", + "Land Developer", + "Landscape Architect", + "Law Enforcement Officer", + "Lawyer", + "Lead Software Engineer", + "Lead Software Test Engineer", + "Leasing Manager", + "Legal Secretary", + "Library Manager", + "Litigation Attorney", + "Loan Officer", + "Lobbyist", + "Logistics Manager", + "Maintenance Manager", + "Management Consultant", + "Managed Care Director", + "Managing Partner", + "Manufacturing Director", + "Manpower Planner", + "Marine Biologist", + "Market Res. Analyst", + "Marketing Director", + "Materials Manager", + "Mathematician", + "Membership Chairman", + "Mechanic", + "Mechanical Engineer", + "Media Buyer", + "Medical Investor", + "Medical Secretary", + "Medical Technician", + "Mental Health Counselor", + "Merchandiser", + "Metallurgical Engineering", + "Meteorologist", + "Microbiologist", + "MIS Manager", + "Motion Picture Director", + "Multimedia Director", + "Musician", + "Network Administrator", + "Network Specialist", + "Network Operator", + "New Product Manager", + "Novelist", + "Nuclear Engineer", + "Nuclear Specialist", + "Nutritionist", + "Nursing Administrator", + "Occupational Therapist", + "Oceanographer", + "Office Manager", + "Operations Manager", + "Operations Research Director", + "Optical Technician", + "Optometrist", + "Organizational Development Manager", + "Outplacement Specialist", + "Paralegal", + "Park Ranger", + "Patent Attorney", + "Payroll Specialist", + "Personnel Specialist", + "Petroleum Engineer", + "Pharmacist", + "Photographer", + "Physical Therapist", + "Physician", + "Physician Assistant", + "Physicist", + "Planning Director", + "Podiatrist", + "Political Analyst", + "Political Scientist", + "Politician", + "Portfolio Manager", + "Preschool Management", + "Preschool Teacher", + "Principal", + "Private Banker", + "Private Investigator", + "Probation Officer", + "Process Engineer", + "Producer", + "Product Manager", + "Product Engineer", + "Production Engineer", + "Production Planner", + "Professional Athlete", + "Professional Coach", + "Professor", + "Project Engineer", + "Project Manager", + "Program Manager", + "Property Manager", + "Public Administrator", + "Public Safety Director", + "PR Specialist", + "Publisher", + "Purchasing Agent", + "Publishing Director", + "Quality Assurance Specialist", + "Quality Control Engineer", + "Quality Control Inspector", + "Radiology Manager", + "Railroad Engineer", + "Real Estate Broker", + "Recreational Director", + "Recruiter", + "Redevelopment Specialist", + "Regulatory Affairs Manager", + "Registered Nurse", + "Rehabilitation Counselor", + "Relocation Manager", + "Reporter", + "Research Specialist", + "Restaurant Manager", + "Retail Store Manager", + "Risk Analyst", + "Safety Engineer", + "Sales Engineer", + "Sales Trainer", + "Sales Promotion Manager", + "Sales Representative", + "Sales Manager", + "Service Manager", + "Sanitation Engineer", + "Scientific Programmer", + "Scientific Writer", + "Securities Analyst", + "Security Consultant", + "Security Director", + "Seminar Presenter", + "Ship's Officer", + "Singer", + "Social Director", + "Social Program Planner", + "Social Research", + "Social Scientist", + "Social Worker", + "Sociologist", + "Software Developer", + "Software Engineer", + "Software Test Engineer", + "Soil Scientist", + "Special Events Manager", + "Special Education Teacher", + "Special Projects Director", + "Speech Pathologist", + "Speech Writer", + "Sports Event Manager", + "Statistician", + "Store Manager", + "Strategic Alliance Director", + "Strategic Planning Director", + "Stress Reduction Specialist", + "Stockbroker", + "Surveyor", + "Structural Engineer", + "Superintendent", + "Supply Chain Director", + "System Engineer", + "Systems Analyst", + "Systems Programmer", + "System Administrator", + "Tax Specialist", + "Teacher", + "Technical Support Specialist", + "Technical Illustrator", + "Technical Writer", + "Technology Director", + "Telecom Analyst", + "Telemarketer", + "Theatrical Director", + "Title Examiner", + "Tour Escort", + "Tour Guide Director", + "Traffic Manager", + "Trainer Translator", + "Transportation Manager", + "Travel Agent", + "Treasurer", + "TV Programmer", + "Underwriter", + "Union Representative", + "University Administrator", + "University Dean", + "Urban Planner", + "Veterinarian", + "Vendor Relations Director", + "Viticulturist", + "Warehouse Manager" + ], + animals : { + //list of ocean animals comes from https://owlcation.com/stem/list-of-ocean-animals + "ocean" : ["Acantharea","Anemone","Angelfish King","Ahi Tuna","Albacore","American Oyster","Anchovy","Armored Snail","Arctic Char","Atlantic Bluefin Tuna","Atlantic Cod","Atlantic Goliath Grouper","Atlantic Trumpetfish","Atlantic Wolffish","Baleen Whale","Banded Butterflyfish","Banded Coral Shrimp","Banded Sea Krait","Barnacle","Barndoor Skate","Barracuda","Basking Shark","Bass","Beluga Whale","Bluebanded Goby","Bluehead Wrasse","Bluefish","Bluestreak Cleaner-Wrasse","Blue Marlin","Blue Shark","Blue Spiny Lobster","Blue Tang","Blue Whale","Broadclub Cuttlefish","Bull Shark","Chambered Nautilus","Chilean Basket Star","Chilean Jack Mackerel","Chinook Salmon","Christmas Tree Worm","Clam","Clown Anemonefish","Clown Triggerfish","Cod","Coelacanth","Cockscomb Cup Coral","Common Fangtooth","Conch","Cookiecutter Shark","Copepod","Coral","Corydoras","Cownose Ray","Crab","Crown-of-Thorns Starfish","Cushion Star","Cuttlefish","California Sea Otters","Dolphin","Dolphinfish","Dory","Devil Fish","Dugong","Dumbo Octopus","Dungeness Crab","Eccentric Sand Dollar","Edible Sea Cucumber","Eel","Elephant Seal","Elkhorn Coral","Emperor Shrimp","Estuarine Crocodile","Fathead Sculpin","Fiddler Crab","Fin Whale","Flameback","Flamingo Tongue Snail","Flashlight Fish","Flatback Turtle","Flatfish","Flying Fish","Flounder","Fluke","French Angelfish","Frilled Shark","Fugu (also called Pufferfish)","Gar","Geoduck","Giant Barrel Sponge","Giant Caribbean Sea Anemone","Giant Clam","Giant Isopod","Giant Kingfish","Giant Oarfish","Giant Pacific Octopus","Giant Pyrosome","Giant Sea Star","Giant Squid","Glowing Sucker Octopus","Giant Tube Worm","Goblin Shark","Goosefish","Great White Shark","Greenland Shark","Grey Atlantic Seal","Grouper","Grunion","Guineafowl Puffer","Haddock","Hake","Halibut","Hammerhead Shark","Hapuka","Harbor Porpoise","Harbor Seal","Hatchetfish","Hawaiian Monk Seal","Hawksbill Turtle","Hector's Dolphin","Hermit Crab","Herring","Hoki","Horn Shark","Horseshoe Crab","Humpback Anglerfish","Humpback Whale","Icefish","Imperator Angelfish","Irukandji Jellyfish","Isopod","Ivory Bush Coral","Japanese Spider Crab","Jellyfish","John Dory","Juan Fernandez Fur Seal","Killer Whale","Kiwa Hirsuta","Krill","Lagoon Triggerfish","Lamprey","Leafy Seadragon","Leopard Seal","Limpet","Ling","Lionfish","Lions Mane Jellyfish","Lobe Coral","Lobster","Loggerhead Turtle","Longnose Sawshark","Longsnout Seahorse","Lophelia Coral","Marrus Orthocanna","Manatee","Manta Ray","Marlin","Megamouth Shark","Mexican Lookdown","Mimic Octopus","Moon Jelly","Mollusk","Monkfish","Moray Eel","Mullet","Mussel","Megaladon","Napoleon Wrasse","Nassau Grouper","Narwhal","Nautilus","Needlefish","Northern Seahorse","North Atlantic Right Whale","Northern Red Snapper","Norway Lobster","Nudibranch","Nurse Shark","Oarfish","Ocean Sunfish","Oceanic Whitetip Shark","Octopus","Olive Sea Snake","Orange Roughy","Ostracod","Otter","Oyster","Pacific Angelshark","Pacific Blackdragon","Pacific Halibut","Pacific Sardine","Pacific Sea Nettle Jellyfish","Pacific White Sided Dolphin","Pantropical Spotted Dolphin","Patagonian Toothfish","Peacock Mantis Shrimp","Pelagic Thresher Shark","Penguin","Peruvian Anchoveta","Pilchard","Pink Salmon","Pinniped","Plankton","Porpoise","Polar Bear","Portuguese Man o' War","Pycnogonid Sea Spider","Quahog","Queen Angelfish","Queen Conch","Queen Parrotfish","Queensland Grouper","Ragfish","Ratfish","Rattail Fish","Ray","Red Drum","Red King Crab","Ringed Seal","Risso's Dolphin","Ross Seals","Sablefish","Salmon","Sand Dollar","Sandbar Shark","Sawfish","Sarcastic Fringehead","Scalloped Hammerhead Shark","Seahorse","Sea Cucumber","Sea Lion","Sea Urchin","Seal","Shark","Shortfin Mako Shark","Shovelnose Guitarfish","Shrimp","Silverside Fish","Skipjack Tuna","Slender Snipe Eel","Smalltooth Sawfish","Smelts","Sockeye Salmon","Southern Stingray","Sponge","Spotted Porcupinefish","Spotted Dolphin","Spotted Eagle Ray","Spotted Moray","Squid","Squidworm","Starfish","Stickleback","Stonefish","Stoplight Loosejaw","Sturgeon","Swordfish","Tan Bristlemouth","Tasseled Wobbegong","Terrible Claw Lobster","Threespot Damselfish","Tiger Prawn","Tiger Shark","Tilefish","Toadfish","Tropical Two-Wing Flyfish","Tuna","Umbrella Squid","Velvet Crab","Venus Flytrap Sea Anemone","Vigtorniella Worm","Viperfish","Vampire Squid","Vaquita","Wahoo","Walrus","West Indian Manatee","Whale","Whale Shark","Whiptail Gulper","White-Beaked Dolphin","White-Ring Garden Eel","White Shrimp","Wobbegong","Wrasse","Wreckfish","Xiphosura","Yellowtail Damselfish","Yelloweye Rockfish","Yellow Cup Black Coral","Yellow Tube Sponge","Yellowfin Tuna","Zebrashark","Zooplankton"], + //list of desert, grassland, and forest animals comes from http://www.skyenimals.com/ + "desert" : ["Aardwolf","Addax","African Wild Ass","Ant","Antelope","Armadillo","Baboon","Badger","Bat","Bearded Dragon","Beetle","Bird","Black-footed Cat","Boa","Brown Bear","Bustard","Butterfly","Camel","Caracal","Caracara","Caterpillar","Centipede","Cheetah","Chipmunk","Chuckwalla","Climbing Mouse","Coati","Cobra","Cotton Rat","Cougar","Courser","Crane Fly","Crow","Dassie Rat","Dove","Dunnart","Eagle","Echidna","Elephant","Emu","Falcon","Fly","Fox","Frogmouth","Gecko","Geoffroy's Cat","Gerbil","Grasshopper","Guanaco","Gundi","Hamster","Hawk","Hedgehog","Hyena","Hyrax","Jackal","Kangaroo","Kangaroo Rat","Kestrel","Kowari","Kultarr","Leopard","Lion","Macaw","Meerkat","Mouse","Oryx","Ostrich","Owl","Pronghorn","Python","Rabbit","Raccoon","Rattlesnake","Rhinoceros","Sand Cat","Spectacled Bear","Spiny Mouse","Starling","Stick Bug","Tarantula","Tit","Toad","Tortoise","Tyrant Flycatcher","Viper","Vulture","Waxwing","Xerus","Zebra"], + "grassland" : ["Aardvark","Aardwolf","Accentor","African Buffalo","African Wild Dog","Alpaca","Anaconda","Ant","Anteater","Antelope","Armadillo","Baboon","Badger","Bandicoot","Barbet","Bat","Bee","Bee-eater","Beetle","Bird","Bison","Black-footed Cat","Black-footed Ferret","Bluebird","Boa","Bowerbird","Brown Bear","Bush Dog","Bushshrike","Bustard","Butterfly","Buzzard","Caracal","Caracara","Cardinal","Caterpillar","Cheetah","Chipmunk","Civet","Climbing Mouse","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Common Genet","Cotton Rat","Cougar","Courser","Coyote","Crane","Crane Fly","Cricket","Crow","Culpeo","Death Adder","Deer","Deer Mouse","Dingo","Dinosaur","Dove","Drongo","Duck","Duiker","Dunnart","Eagle","Echidna","Elephant","Elk","Emu","Falcon","Finch","Flea","Fly","Flying Frog","Fox","Frog","Frogmouth","Garter Snake","Gazelle","Gecko","Geoffroy's Cat","Gerbil","Giant Tortoise","Giraffe","Grasshopper","Grison","Groundhog","Grouse","Guanaco","Guinea Pig","Hamster","Harrier","Hartebeest","Hawk","Hedgehog","Helmetshrike","Hippopotamus","Hornbill","Hyena","Hyrax","Impala","Jackal","Jaguar","Jaguarundi","Kangaroo","Kangaroo Rat","Kestrel","Kultarr","Ladybug","Leopard","Lion","Macaw","Meerkat","Mouse","Newt","Oryx","Ostrich","Owl","Pangolin","Pheasant","Prairie Dog","Pronghorn","Przewalski's Horse","Python","Quoll","Rabbit","Raven","Rhinoceros","Shelduck","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Tamandua","Tasmanian Devil","Thornbill","Thrush","Toad","Tortoise"], + "forest" : ["Agouti","Anaconda","Anoa","Ant","Anteater","Antelope","Armadillo","Asian Black Bear","Aye-aye","Babirusa","Baboon","Badger","Bandicoot","Banteng","Barbet","Basilisk","Bat","Bearded Dragon","Bee","Bee-eater","Beetle","Bettong","Binturong","Bird-of-paradise","Bongo","Bowerbird","Bulbul","Bush Dog","Bushbaby","Bushshrike","Butterfly","Buzzard","Caecilian","Cardinal","Cassowary","Caterpillar","Centipede","Chameleon","Chimpanzee","Cicada","Civet","Clouded Leopard","Coati","Cobra","Cockatoo","Cockroach","Colugo","Cotinga","Cotton Rat","Cougar","Crane Fly","Cricket","Crocodile","Crow","Cuckoo","Cuscus","Death Adder","Deer","Dhole","Dingo","Dinosaur","Drongo","Duck","Duiker","Eagle","Echidna","Elephant","Finch","Flat-headed Cat","Flea","Flowerpecker","Fly","Flying Frog","Fossa","Frog","Frogmouth","Gaur","Gecko","Gorilla","Grison","Hawaiian Honeycreeper","Hawk","Hedgehog","Helmetshrike","Hornbill","Hyrax","Iguana","Jackal","Jaguar","Jaguarundi","Kestrel","Ladybug","Lemur","Leopard","Lion","Macaw","Mandrill","Margay","Monkey","Mouse","Mouse Deer","Newt","Okapi","Old World Flycatcher","Orangutan","Owl","Pangolin","Peafowl","Pheasant","Possum","Python","Quokka","Rabbit","Raccoon","Red Panda","Red River Hog","Rhinoceros","Sloth Bear","Spectacled Bear","Squirrel","Starling","Stick Bug","Sun Bear","Tamandua","Tamarin","Tapir","Tarantula","Thrush","Tiger","Tit","Toad","Tortoise","Toucan","Trogon","Trumpeter","Turaco","Turtle","Tyrant Flycatcher","Viper","Vulture","Wallaby","Warbler","Wasp","Waxwing","Weaver","Weaver-finch","Whistler","White-eye","Whydah","Woodswallow","Worm","Wren","Xenops","Yellowjacket","Accentor","African Buffalo","American Black Bear","Anole","Bird","Bison","Boa","Brown Bear","Chipmunk","Common Genet","Copperhead","Coyote","Deer Mouse","Dormouse","Elk","Emu","Fisher","Fox","Garter Snake","Giant Panda","Giant Tortoise","Groundhog","Grouse","Guanaco","Himalayan Tahr","Kangaroo","Koala","Numbat","Quoll","Raccoon dog","Tasmanian Devil","Thornbill","Turkey","Vole","Weasel","Wildcat","Wolf","Wombat","Woodchuck","Woodpecker"], + //list of farm animals comes from https://www.buzzle.com/articles/farm-animals-list.html + "farm" : ["Alpaca","Buffalo","Banteng","Cow","Cat","Chicken","Carp","Camel","Donkey","Dog","Duck","Emu","Goat","Gayal","Guinea","Goose","Horse","Honey","Llama","Pig","Pigeon","Rhea","Rabbit","Sheep","Silkworm","Turkey","Yak","Zebu"], + //list of pet animals comes from https://www.dogbreedinfo.com/pets/pet.htm + "pet" : ["Bearded Dragon","Birds","Burro","Cats","Chameleons","Chickens","Chinchillas","Chinese Water Dragon","Cows","Dogs","Donkey","Ducks","Ferrets","Fish","Geckos","Geese","Gerbils","Goats","Guinea Fowl","Guinea Pigs","Hamsters","Hedgehogs","Horses","Iguanas","Llamas","Lizards","Mice","Mule","Peafowl","Pigs and Hogs","Pigeons","Ponies","Pot Bellied Pig","Rabbits","Rats","Sheep","Skinks","Snakes","Stick Insects","Sugar Gliders","Tarantula","Turkeys","Turtles"], + //list of zoo animals comes from https://bronxzoo.com/animals + "zoo" : ["Aardvark","African Wild Dog","Aldabra Tortoise","American Alligator","American Bison","Amur Tiger","Anaconda","Andean Condor","Asian Elephant","Baby Doll Sheep","Bald Eagle","Barred Owl","Blue Iguana","Boer Goat","California Sea Lion","Caribbean Flamingo","Chinchilla","Collared Lemur","Coquerel's Sifaka","Cuban Amazon Parrot","Ebony Langur","Fennec Fox","Fossa","Gelada","Giant Anteater","Giraffe","Gorilla","Grizzly Bear","Henkel's Leaf-tailed Gecko","Indian Gharial","Indian Rhinoceros","King Cobra","King Vulture","Komodo Dragon","Linne's Two-toed Sloth","Lion","Little Penguin","Madagascar Tree Boa","Magellanic Penguin","Malayan Tapir","Malayan Tiger","Matschies Tree Kangaroo","Mini Donkey","Monarch Butterfly","Nile crocodile","North American Porcupine","Nubian Ibex","Okapi","Poison Dart Frog","Polar Bear","Pygmy Marmoset","Radiated Tortoise","Red Panda","Red Ruffed Lemur","Ring-tailed Lemur","Ring-tailed Mongoose","Rock Hyrax","Small Clawed Asian Otter","Snow Leopard","Snowy Owl","Southern White-faced Owl","Southern White Rhinocerous","Squirrel Monkey","Tufted Puffin","White Cheeked Gibbon","White-throated Bee Eater","Zebra"] + }, + primes: [ + // 1230 first primes, i.e. all primes up to the first one greater than 10000, inclusive. + 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,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979,1987,1993,1997,1999,2003,2011,2017,2027,2029,2039,2053,2063,2069,2081,2083,2087,2089,2099,2111,2113,2129,2131,2137,2141,2143,2153,2161,2179,2203,2207,2213,2221,2237,2239,2243,2251,2267,2269,2273,2281,2287,2293,2297,2309,2311,2333,2339,2341,2347,2351,2357,2371,2377,2381,2383,2389,2393,2399,2411,2417,2423,2437,2441,2447,2459,2467,2473,2477,2503,2521,2531,2539,2543,2549,2551,2557,2579,2591,2593,2609,2617,2621,2633,2647,2657,2659,2663,2671,2677,2683,2687,2689,2693,2699,2707,2711,2713,2719,2729,2731,2741,2749,2753,2767,2777,2789,2791,2797,2801,2803,2819,2833,2837,2843,2851,2857,2861,2879,2887,2897,2903,2909,2917,2927,2939,2953,2957,2963,2969,2971,2999,3001,3011,3019,3023,3037,3041,3049,3061,3067,3079,3083,3089,3109,3119,3121,3137,3163,3167,3169,3181,3187,3191,3203,3209,3217,3221,3229,3251,3253,3257,3259,3271,3299,3301,3307,3313,3319,3323,3329,3331,3343,3347,3359,3361,3371,3373,3389,3391,3407,3413,3433,3449,3457,3461,3463,3467,3469,3491,3499,3511,3517,3527,3529,3533,3539,3541,3547,3557,3559,3571,3581,3583,3593,3607,3613,3617,3623,3631,3637,3643,3659,3671,3673,3677,3691,3697,3701,3709,3719,3727,3733,3739,3761,3767,3769,3779,3793,3797,3803,3821,3823,3833,3847,3851,3853,3863,3877,3881,3889,3907,3911,3917,3919,3923,3929,3931,3943,3947,3967,3989,4001,4003,4007,4013,4019,4021,4027,4049,4051,4057,4073,4079,4091,4093,4099,4111,4127,4129,4133,4139,4153,4157,4159,4177,4201,4211,4217,4219,4229,4231,4241,4243,4253,4259,4261,4271,4273,4283,4289,4297,4327,4337,4339,4349,4357,4363,4373,4391,4397,4409,4421,4423,4441,4447,4451,4457,4463,4481,4483,4493,4507,4513,4517,4519,4523,4547,4549,4561,4567,4583,4591,4597,4603,4621,4637,4639,4643,4649,4651,4657,4663,4673,4679,4691,4703,4721,4723,4729,4733,4751,4759,4783,4787,4789,4793,4799,4801,4813,4817,4831,4861,4871,4877,4889,4903,4909,4919,4931,4933,4937,4943,4951,4957,4967,4969,4973,4987,4993,4999,5003,5009,5011,5021,5023,5039,5051,5059,5077,5081,5087,5099,5101,5107,5113,5119,5147,5153,5167,5171,5179,5189,5197,5209,5227,5231,5233,5237,5261,5273,5279,5281,5297,5303,5309,5323,5333,5347,5351,5381,5387,5393,5399,5407,5413,5417,5419,5431,5437,5441,5443,5449,5471,5477,5479,5483,5501,5503,5507,5519,5521,5527,5531,5557,5563,5569,5573,5581,5591,5623,5639,5641,5647,5651,5653,5657,5659,5669,5683,5689,5693,5701,5711,5717,5737,5741,5743,5749,5779,5783,5791,5801,5807,5813,5821,5827,5839,5843,5849,5851,5857,5861,5867,5869,5879,5881,5897,5903,5923,5927,5939,5953,5981,5987,6007,6011,6029,6037,6043,6047,6053,6067,6073,6079,6089,6091,6101,6113,6121,6131,6133,6143,6151,6163,6173,6197,6199,6203,6211,6217,6221,6229,6247,6257,6263,6269,6271,6277,6287,6299,6301,6311,6317,6323,6329,6337,6343,6353,6359,6361,6367,6373,6379,6389,6397,6421,6427,6449,6451,6469,6473,6481,6491,6521,6529,6547,6551,6553,6563,6569,6571,6577,6581,6599,6607,6619,6637,6653,6659,6661,6673,6679,6689,6691,6701,6703,6709,6719,6733,6737,6761,6763,6779,6781,6791,6793,6803,6823,6827,6829,6833,6841,6857,6863,6869,6871,6883,6899,6907,6911,6917,6947,6949,6959,6961,6967,6971,6977,6983,6991,6997,7001,7013,7019,7027,7039,7043,7057,7069,7079,7103,7109,7121,7127,7129,7151,7159,7177,7187,7193,7207,7211,7213,7219,7229,7237,7243,7247,7253,7283,7297,7307,7309,7321,7331,7333,7349,7351,7369,7393,7411,7417,7433,7451,7457,7459,7477,7481,7487,7489,7499,7507,7517,7523,7529,7537,7541,7547,7549,7559,7561,7573,7577,7583,7589,7591,7603,7607,7621,7639,7643,7649,7669,7673,7681,7687,7691,7699,7703,7717,7723,7727,7741,7753,7757,7759,7789,7793,7817,7823,7829,7841,7853,7867,7873,7877,7879,7883,7901,7907,7919,7927,7933,7937,7949,7951,7963,7993,8009,8011,8017,8039,8053,8059,8069,8081,8087,8089,8093,8101,8111,8117,8123,8147,8161,8167,8171,8179,8191,8209,8219,8221,8231,8233,8237,8243,8263,8269,8273,8287,8291,8293,8297,8311,8317,8329,8353,8363,8369,8377,8387,8389,8419,8423,8429,8431,8443,8447,8461,8467,8501,8513,8521,8527,8537,8539,8543,8563,8573,8581,8597,8599,8609,8623,8627,8629,8641,8647,8663,8669,8677,8681,8689,8693,8699,8707,8713,8719,8731,8737,8741,8747,8753,8761,8779,8783,8803,8807,8819,8821,8831,8837,8839,8849,8861,8863,8867,8887,8893,8923,8929,8933,8941,8951,8963,8969,8971,8999,9001,9007,9011,9013,9029,9041,9043,9049,9059,9067,9091,9103,9109,9127,9133,9137,9151,9157,9161,9173,9181,9187,9199,9203,9209,9221,9227,9239,9241,9257,9277,9281,9283,9293,9311,9319,9323,9337,9341,9343,9349,9371,9377,9391,9397,9403,9413,9419,9421,9431,9433,9437,9439,9461,9463,9467,9473,9479,9491,9497,9511,9521,9533,9539,9547,9551,9587,9601,9613,9619,9623,9629,9631,9643,9649,9661,9677,9679,9689,9697,9719,9721,9733,9739,9743,9749,9767,9769,9781,9787,9791,9803,9811,9817,9829,9833,9839,9851,9857,9859,9871,9883,9887,9901,9907,9923,9929,9931,9941,9949,9967,9973,10007 + ], + emotions: [ + "love", + "joy", + "surprise", + "anger", + "sadness", + "fear" + ], + music_genres: { + 'general': [ + 'Rock', + 'Pop', + 'Hip-Hop', + 'Jazz', + 'Classical', + 'Electronic', + 'Country', + 'R&B', + 'Reggae', + 'Blues', + 'Metal', + 'Folk', + 'Alternative', + 'Punk', + 'Disco', + 'Funk', + 'Techno', + 'Indie', + 'Gospel', + 'Dance', + 'Children\'s', + 'World' + ], + 'alternative': [ + 'Art Punk', + 'Alternative Rock', + 'Britpunk', + 'College Rock', + 'Crossover Thrash', + 'Crust Punk', + 'Emo / Emocore', + 'Experimental Rock', + 'Folk Punk', + 'Goth / Gothic Rock', + 'Grunge', + 'Hardcore Punk', + 'Hard Rock', + 'Indie Rock', + 'Lo-fi', + 'Musique ConcrĆØte', + 'New Wave', + 'Progressive Rock', + 'Punk', + 'Shoegaze', + 'Steampunk', + ], 'blues': [ + 'Acoustic Blues', + 'African Blues', + 'Blues Rock', + 'Blues Shouter', + 'British Blues', + 'Canadian Blues', + 'Chicago Blues', + 'Classic Blues', + 'Classic Female Blues', + 'Contemporary Blues', + 'Country Blues', + 'Dark Blues', + 'Delta Blues', + 'Detroit Blues', + 'Doom Blues', + 'Electric Blues', + 'Folk Blues', + 'Gospel Blues', + 'Harmonica Blues', + 'Hill Country Blues', + 'Hokum Blues', + 'Jazz Blues', + 'Jump Blues', + 'Kansas City Blues', + 'Louisiana Blues', + 'Memphis Blues', + 'Modern Blues', + 'New Orlean Blues', + 'NY Blues', + 'Piano Blues', + 'Piedmont Blues', + 'Punk Blues', + 'Ragtime Blues', + 'Rhythm Blues', + 'Soul Blues', + 'St.Louis Blues', + 'Soul Blues', + 'Swamp Blues', + 'Texas Blues', + 'Urban Blues', + 'Vandeville', + 'West Coast Blues', + ], 'children\'s': [ + 'Lullabies', + 'Sing - Along', + 'Stories' + ], 'classical': [ + 'Avant-Garde', + 'Ballet', + 'Baroque', + 'Cantata', + 'Chamber Music', + 'String Quartet', + 'Chant', + 'Choral', + 'Classical Crossover', + 'Concerto', + 'Concerto Grosso', + 'Contemporary Classical', + 'Early Music', + 'Expressionist', + 'High Classical', + 'Impressionist', + 'Mass Requiem', + 'Medieval', + 'Minimalism', + 'Modern Composition', + 'Modern Classical', + 'Opera', + 'Oratorio', + 'Orchestral', + 'Organum', + 'Renaissance', + 'Romantic (early period)', + 'Romantic (later period)', + 'Sonata', + 'Symphonic', + 'Symphony', + 'Twelve-tone', + 'Wedding Music' + ], 'country': [ + 'Alternative Country', + 'Americana', + 'Australian Country', + 'Bakersfield Sound', + 'Bluegrass', + 'Blues Country', + 'Cajun Fiddle Tunes', + 'Christian Country', + 'Classic Country', + 'Close Harmony', + 'Contemporary Bluegrass', + 'Contemporary Country', + 'Country Gospel', + 'Country Pop', + 'Country Rap', + 'Country Rock', + 'Country Soul', + 'Cowboy / Western', + 'Cowpunk', + 'Dansband', + 'Honky Tonk', + 'Franco-Country', + 'Gulf and Western', + 'Hellbilly Music', + 'Honky Tonk', + 'Instrumental Country', + 'Lubbock Sound', + 'Nashville Sound', + 'Neotraditional Country', + 'Outlaw Country', + 'Progressive', + 'Psychobilly / Punkabilly', + 'Red Dirt', + 'Sertanejo', + 'Texas County', + 'Traditional Bluegrass', + 'Traditional Country', + 'Truck-Driving Country', + 'Urban Cowboy', + 'Western Swing' + ], 'dance': [ + 'Club / Club Dance', + 'Breakcore', + 'Breakbeat / Breakstep', + 'Chillstep', + 'Deep House', + 'Dubstep', + 'Dancehall', + 'Electro House', + 'Electroswing', + 'Exercise', + 'Future Garage', + 'Garage', + 'Glitch Hop', + 'Glitch Pop', + 'Grime', + 'Hardcore', + 'Hard Dance', + 'Hi-NRG / Eurodance', + 'Horrorcore', + 'House', + 'Jackin House', + 'Jungle / Drum n bass', + 'Liquid Dub', + 'Regstep', + 'Speedcore', + 'Techno', + 'Trance', + 'Trap' + ], electronic: [ + '2-Step', + '8bit', + 'Ambient', + 'Asian Underground', + 'Bassline', + 'Chillwave', + 'Chiptune', + 'Crunk', + 'Downtempo', + 'Drum & Bass', + 'Hard Step', + 'Electro', + 'Electro-swing', + 'Electroacoustic', + 'Electronica', + 'Electronic Rock', + 'Eurodance', + 'Hardstyle', + 'Hi-Nrg', + 'IDM/Experimental', + 'Industrial', + 'Trip Hop', + 'Vaporwave', + 'UK Garage', + 'House', + 'Dubstep', + 'Deep House', + 'EDM', + 'Future Bass', + 'Psychedelic trance' + ], 'jazz' : [ + 'Acid Jazz', + 'Afro-Cuban Jazz', + 'Avant-Garde Jazz', + 'Bebop', + 'Big Band', + 'Blue Note', + 'British Dance Band (Jazz)', + 'Cape Jazz', + 'Chamber Jazz', + 'Contemporary Jazz', + 'Continental Jazz', + 'Cool Jazz', + 'Crossover Jazz', + 'Dark Jazz', + 'Dixieland', + 'Early Jazz', + 'Electro Swing (Jazz)', + 'Ethio-jazz', + 'Ethno-Jazz', + 'European Free Jazz', + 'Free Funk (Avant-Garde / Funk Jazz)', + 'Free Jazz', + 'Fusion', + 'Gypsy Jazz', + 'Hard Bop', + 'Indo Jazz', + 'Jazz Blues', + 'Jazz-Funk (see Free Funk)', + 'Jazz-Fusion', + 'Jazz Rap', + 'Jazz Rock', + 'Kansas City Jazz', + 'Latin Jazz', + 'M-Base Jazz', + 'Mainstream Jazz', + 'Modal Jazz', + 'Neo-Bop', + 'Neo-Swing', + 'Nu Jazz', + 'Orchestral Jazz', + 'Post-Bop', + 'Punk Jazz', + 'Ragtime', + 'Ska Jazz', + 'Skiffle (also Folk)', + 'Smooth Jazz', + 'Soul Jazz', + 'Swing Jazz', + 'Straight-Ahead Jazz', + 'Trad Jazz', + 'Third Stream', + 'Jazz-Funk', + 'Free Jazz', + 'West Coast Jazz' + ], 'metal': [ + 'Heavy Metal', + 'Speed Metal', + 'Thrash Metal', + 'Power Metal', + 'Death Metal', + 'Black Metal', + 'Pagan Metal', + 'Viking Metal', + 'Folk Metal', + 'Symphonic Metal', + 'Gothic Metal', + 'Glam Metal', + 'Hair Metal', + 'Doom Metal', + 'Groove Metal', + 'Industrial Metal', + 'Modern Metal', + 'Neoclassical Metal', + 'New Wave Of British Heavy Metal', + 'Post Metal', + 'Progressive Metal', + 'Avantgarde Metal', + 'Sludge', + 'Djent', + 'Drone', + 'Kawaii Metal', + 'Pirate Metal', + 'Nu Metal', + 'Neue Deutsche HƤrte', + 'Math Metal', + 'Crossover', + 'Grindcore', + 'Hardcore', + 'Metalcore', + 'Deathcore', + 'Post Hardcore', + 'Mathcore' + ], 'folk': [ + 'American Folk Revival', + 'Anti - Folk', + 'British Folk Revival', + 'Contemporary Folk', + 'Filk Music', + 'Freak Folk', + 'Indie Folk', + 'Industrial Folk', + 'Neofolk', + 'Progressive Folk', + 'Psychedelic Folk', + 'Sung Poetry', + 'Techno - Folk', + 'Folk Rock', + 'Old-time Music', + 'Bluegrass', + 'Appalachian', + 'Roots Revival', + 'Celtic', + 'Indie Folk' + ], 'pop': [ + 'Adult Contemporary', + 'Arab Pop', + 'Baroque', + 'Britpop', + 'Bubblegum Pop', + 'Chamber Pop', + 'Chanson', + 'Christian Pop', + 'Classical Crossover', + 'Europop', + 'Austropop', + 'Balkan Pop', + 'French Pop', + 'Korean Pop', + 'Japanese Pop', + 'Chinese Pop', + 'Latin Pop', + 'LaĆÆkó', + 'Nederpop', + 'Russian Pop', + 'Dance Pop', + 'Dream Pop', + 'Electro Pop', + 'Iranian Pop', + 'Jangle Pop', + 'Latin Ballad', + 'Levenslied', + 'Louisiana Swamp Pop', + 'Mexican Pop', + 'Motorpop', + 'New Romanticism', + 'Orchestral Pop', + 'Pop Rap', + 'Popera', + 'Pop / Rock', + 'Pop Punk', + 'Power Pop', + 'Psychedelic Pop', + 'Russian Pop', + 'Schlager', + 'Soft Rock', + 'Sophisti - Pop', + 'Space Age Pop', + 'Sunshine Pop', + 'Surf Pop', + 'Synthpop', + 'Teen Pop', + 'Traditional Pop Music', + 'Turkish Pop', + 'Vispop', + 'Wonky Pop' + ], 'r&b': [ + '(Carolina) Beach Music', + 'Contemporary R & B', + 'Disco', + 'Doo Wop', + 'Funk', + 'Modern Soul', + 'Motown', + 'Neo - Soul', + 'Northern Soul', + 'Psychedelic Soul', + 'Quiet Storm', + 'Soul', + 'Soul Blues', + 'Southern Soul' + ], 'reggae': [ + '2 - Tone', + 'Dub', + 'Roots Reggae', + 'Reggae Fusion', + 'Reggae en EspaƱol', + 'Spanish Reggae', + 'Reggae 110', + 'Reggae Bultrón', + 'Romantic Flow', + 'Lovers Rock', + 'Raggamuffin', + 'Ragga', + 'Dancehall', + 'Ska', + ], 'rock': [ + 'Acid Rock', + 'Adult - Oriented Rock', + 'Afro Punk', + 'Adult Alternative', + 'Alternative Rock', + 'American Traditional Rock', + 'Anatolian Rock', + 'Arena Rock', + 'Art Rock', + 'Blues - Rock', + 'British Invasion', + 'Cock Rock', + 'Death Metal / Black Metal', + 'Doom Metal', + 'Glam Rock', + 'Gothic Metal', + 'Grind Core', + 'Hair Metal', + 'Hard Rock', + 'Math Metal', + 'Math Rock', + 'Metal', + 'Metal Core', + 'Noise Rock', + 'Jam Bands', + 'Post Punk', + 'Post Rock', + 'Prog - Rock / Art Rock', + 'Progressive Metal', + 'Psychedelic', + 'Rock & Roll', + 'Rockabilly', + 'Roots Rock', + 'Singer / Songwriter', + 'Southern Rock', + 'Spazzcore', + 'Stoner Metal', + 'Surf', + 'Technical Death Metal', + 'Tex - Mex', + 'Thrash Metal', + 'Time Lord Rock(Trock)', + 'Trip - hop', + 'Yacht Rock', + 'School House Rock' + ], 'hip-hop': [ + 'Alternative Rap', + 'Avant - Garde', + 'Bounce', + 'Chap Hop', + 'Christian Hip Hop', + 'Conscious Hip Hop', + 'Country - Rap', + 'Grunk', + 'Crunkcore', + 'Cumbia Rap', + 'Dirty South', + 'East Coast', + 'Brick City Club', + 'Hardcore Hip Hop', + 'Mafioso Rap', + 'New Jersey Hip Hop', + 'Freestyle Rap', + 'G - Funk', + 'Gangsta Rap', + 'Golden Age', + 'Grime', + 'Hardcore Rap', + 'Hip - Hop', + 'Hip Pop', + 'Horrorcore', + 'Hyphy', + 'Industrial Hip Hop', + 'Instrumental Hip Hop', + 'Jazz Rap', + 'Latin Rap', + 'Low Bap', + 'Lyrical Hip Hop', + 'Merenrap', + 'Midwest Hip Hop', + 'Chicago Hip Hop', + 'Detroit Hip Hop', + 'Horrorcore', + 'St.Louis Hip Hop', + 'Twin Cities Hip Hop', + 'Motswako', + 'Nerdcore', + 'New Jack Swing', + 'New School Hip Hop', + 'Old School Rap', + 'Rap', + 'Trap', + 'Turntablism', + 'Underground Rap', + 'West Coast Rap', + 'East Coast Rap', + 'Trap', + 'UK Grime', + 'Hyphy', + 'Emo-rap', + 'Cloud rap', + 'G-funk', + 'Boom Bap', + 'Mumble', + 'Drill', + 'UK Drill', + 'Soundcloud Rap', + 'Lo-fi' + ], 'punk': [ + 'Afro-punk', + 'Anarcho punk', + 'Art punk', + 'Christian punk', + 'Crust punk', + 'Deathrock', + 'Egg punk', + 'Garage punk', + 'Glam punk', + 'Hardcore punk', + 'Horror punk', + 'Incelcore/e-punk', + 'Oi!', + 'Peace punk', + 'Punk pathetique', + 'Queercore', + 'Riot Grrrl', + 'Skate punk', + 'Street punk', + 'Taqwacore', + 'Trallpunk' + ], 'disco': [ + 'Nu-disco', + 'Disco-funk', + 'Hi-NRG', + 'Italo Disco', + 'Eurodisco', + 'Boogie', + 'Space Disco', + 'Post-disco', + 'Electro Disco', + 'Disco House', + 'Disco Pop', + 'Soulful House' + ], 'funk': [ + 'Funk Rock', + 'P-Funk (Parliament-Funkadelic)', + 'Psychedelic Funk', + 'Funk Metal', + 'Electro-Funk', + 'Go-go', + 'Boogie-Funk', + 'Jazz-Funk', + 'Soul-Funk', + 'Funky Disco', + 'Nu-Funk', + 'Afrobeat', + 'Latin Funk', + 'G-Funk', + 'Acid Jazz', + 'Funktronica', + 'Folk-Funk', + 'Space Funk', + 'Ambient Funk', + 'Hard Funk', + 'Fusion Funk' + ], 'techno': [ + 'Acid Techno', + 'Ambient Techno', + 'Detroit Techno', + 'Dub Techno', + 'Minimal Techno', + 'Industrial Techno', + 'Hard Techno', + 'Trance', + 'Progressive Techno', + 'Tech House', + 'Electronica', + 'Breakbeat Techno', + 'Electro Techno', + 'Melodic Techno', + 'Experimental Techno', + 'Dark Techno', + 'Ebm', + 'Hypnotic Techno', + 'Psychedelic Techno', + 'Rave Techno', + 'Techno-Pop' + ], 'indie': [ + 'Indie Rock', + 'Indie Pop', + 'Indie Folk', + 'Indie Electronic', + 'Indie Punk', + 'Indie Hip-Hop', + 'Dream Pop', + 'Shoegaze', + 'Lo-fi', + 'Chillwave', + 'Freak Folk', + 'Noise Pop', + 'Math Rock', + 'Post-Punk', + 'Garage Rock', + 'Experimental Indie', + 'Surf Rock', + 'Alternative Country', + 'Indie Soul', + 'Art Rock', + 'Indie R&B', + 'Indietronica', + 'Emo', + 'Post-Rock', + 'Indie Pop-Rock', + 'Indie Synthpop', + 'Noise Rock', + 'Psych Folk', + 'Indie Blues' + ], 'gospel': [ + 'Traditional Gospel', + 'Contemporary Gospel', + 'Southern Gospel', + 'Black Gospel', + 'Urban Contemporary Gospel', + 'Gospel Blues', + 'Bluegrass Gospel', + 'Country Gospel', + 'Praise and Worship', + 'Christian Hip-Hop', + 'Gospel Jazz', + 'Reggae Gospel', + 'African Gospel', + 'Latin Gospel', + 'R&B Gospel', + 'Gospel Choir', + 'Acappella Gospel', + 'Instrumental Gospel', + 'Gospel Rap' + ], 'world': [ + 'African', + 'Arabic', + 'Asian', + 'Caribbean', + 'Celtic', + 'European', + 'Latin American', + 'Middle Eastern', + 'Native American', + 'Polynesian', + 'Reggae', + 'Ska', + 'Salsa', + 'Flamenco', + 'Bossa Nova', + 'Tango', + 'Fado', + 'Klezmer', + 'Balkan', + 'Afrobeat', + 'Mongolian Throat Singing', + 'Indian Classical', + 'Gamelan', + 'Sufi Music', + 'Zydeco', + 'Kora Music', + 'Andean Music', + 'Irish Traditional', + 'Gypsy Jazz', + 'Bollywood', + 'Bhangra', + 'Jawaiian', + 'Hawaiian Slack Key Guitar', + 'Calypso', + 'Cuban Son', + 'Taiko Drumming', + 'African Highlife', + 'Merengue', + 'Tuvan Throat Singing' + ] + }, + // Data sourced from https://unicode.org/emoji/charts/full-emoji-list.html + emojis: { + "smileys_and_emotion": [ + "0x1f600", + "0x1f603", + "0x1f604", + "0x1f601", + "0x1f606", + "0x1f605", + "0x1f923", + "0x1f602", + "0x1f642", + "0x1f643", + "0x1fae0", + "0x1f609", + "0x1f60a", + "0x1f607", + "0x1f970", + "0x1f60d", + "0x1f929", + "0x1f618", + "0x1f617", + "0x263a", + "0x1f61a", + "0x1f619", + "0x1f972", + "0x1f60b", + "0x1f61b", + "0x1f61c", + "0x1f92a", + "0x1f61d", + "0x1f911", + "0x1f917", + "0x1f92d", + "0x1fae2", + "0x1fae3", + "0x1f92b", + "0x1f914", + "0x1fae1", + "0x1f910", + "0x1f928", + "0x1f610", + "0x1f611", + "0x1f636", + "0x1fae5", + "0x1f636", + "0x200d", + "0x1f32b", + "0xfe0f", + "0x1f60f", + "0x1f612", + "0x1f644", + "0x1f62c", + "0x1f62e", + "0x200d", + "0x1f4a8", + "0x1f925", + "0x1fae8", + "0x1f642", + "0x200d", + "0x2194", + "0xfe0f", + "0x1f642", + "0x200d", + "0x2195", + "0xfe0f", + "0x1f60c", + "0x1f614", + "0x1f62a", + "0x1f924", + "0x1f634", + "0x1f637", + "0x1f912", + "0x1f915", + "0x1f922", + "0x1f92e", + "0x1f927", + "0x1f975", + "0x1f976", + "0x1f974", + "0x1f635", + "0x1f635", + "0x200d", + "0x1f4ab", + "0x1f92f", + "0x1f920", + "0x1f973", + "0x1f978", + "0x1f60e", + "0x1f913", + "0x1f9d0", + "0x1f615", + "0x1fae4", + "0x1f61f", + "0x1f641", + "0x2639", + "0x1f62e", + "0x1f62f", + "0x1f632", + "0x1f633", + "0x1f97a", + "0x1f979", + "0x1f626", + "0x1f627", + "0x1f628", + "0x1f630", + "0x1f625", + "0x1f622", + "0x1f62d", + "0x1f631", + "0x1f616", + "0x1f623", + "0x1f61e", + "0x1f613", + "0x1f629", + "0x1f62b", + "0x1f971", + "0x1f624", + "0x1f621", + "0x1f620", + "0x1f92c", + "0x1f608", + "0x1f47f", + "0x1f480", + "0x2620", + "0x1f4a9", + "0x1f921", + "0x1f479", + "0x1f47a", + "0x1f47b", + "0x1f47d", + "0x1f47e", + "0x1f916", + "0x1f63a", + "0x1f638", + "0x1f639", + "0x1f63b", + "0x1f63c", + "0x1f63d", + "0x1f640", + "0x1f63f", + "0x1f63e", + "0x1f648", + "0x1f649", + "0x1f64a", + "0x1f48c", + "0x1f498", + "0x1f49d", + "0x1f496", + "0x1f497", + "0x1f493", + "0x1f49e", + "0x1f495", + "0x1f49f", + "0x2763", + "0x1f494", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f525", + "0x2764", + "0xfe0f", + "0x200d", + "0x1fa79", + "0x2764", + "0x1fa77", + "0x1f9e1", + "0x1f49b", + "0x1f49a", + "0x1f499", + "0x1fa75", + "0x1f49c", + "0x1f90e", + "0x1f5a4", + "0x1fa76", + "0x1f90d", + "0x1f48b", + "0x1f4af", + "0x1f4a2", + "0x1f4a5", + "0x1f4ab", + "0x1f4a6", + "0x1f4a8", + "0x1f573", + "0x1f4ac", + "0x1f441", + "0xfe0f", + "0x200d", + "0x1f5e8", + "0xfe0f", + "0x1f5e8", + "0x1f5ef", + "0x1f4ad", + "0x1f4a4" + ], + "people_and_body": [ + "0x1f44b", + "0x1f91a", + "0x1f590", + "0x270b", + "0x1f596", + "0x1faf1", + "0x1faf2", + "0x1faf3", + "0x1faf4", + "0x1faf7", + "0x1faf8", + "0x1f44c", + "0x1f90c", + "0x1f90f", + "0x270c", + "0x1f91e", + "0x1faf0", + "0x1f91f", + "0x1f918", + "0x1f919", + "0x1f448", + "0x1f449", + "0x1f446", + "0x1f595", + "0x1f447", + "0x261d", + "0x1faf5", + "0x1f44d", + "0x1f44e", + "0x270a", + "0x1f44a", + "0x1f91b", + "0x1f91c", + "0x1f44f", + "0x1f64c", + "0x1faf6", + "0x1f450", + "0x1f932", + "0x1f91d", + "0x1f64f", + "0x270d", + "0x1f485", + "0x1f933", + "0x1f4aa", + "0x1f9be", + "0x1f9bf", + "0x1f9b5", + "0x1f9b6", + "0x1f442", + "0x1f9bb", + "0x1f443", + "0x1f9e0", + "0x1fac0", + "0x1fac1", + "0x1f9b7", + "0x1f9b4", + "0x1f440", + "0x1f441", + "0x1f445", + "0x1f444", + "0x1fae6", + "0x1f476", + "0x1f9d2", + "0x1f466", + "0x1f467", + "0x1f9d1", + "0x1f471", + "0x1f468", + "0x1f9d4", + "0x1f9d4", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d4", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9b0", + "0x1f468", + "0x200d", + "0x1f9b1", + "0x1f468", + "0x200d", + "0x1f9b3", + "0x1f468", + "0x200d", + "0x1f9b2", + "0x1f469", + "0x1f469", + "0x200d", + "0x1f9b0", + "0x1f9d1", + "0x200d", + "0x1f9b0", + "0x1f469", + "0x200d", + "0x1f9b1", + "0x1f9d1", + "0x200d", + "0x1f9b1", + "0x1f469", + "0x200d", + "0x1f9b3", + "0x1f9d1", + "0x200d", + "0x1f9b3", + "0x1f469", + "0x200d", + "0x1f9b2", + "0x1f9d1", + "0x200d", + "0x1f9b2", + "0x1f471", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f471", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d3", + "0x1f474", + "0x1f475", + "0x1f64d", + "0x1f64d", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f64d", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f64e", + "0x1f64e", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f64e", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f645", + "0x1f645", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f645", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f646", + "0x1f646", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f646", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f481", + "0x1f481", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f481", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f64b", + "0x1f64b", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f64b", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9cf", + "0x1f9cf", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9cf", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f647", + "0x1f647", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f647", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f926", + "0x1f926", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f926", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f937", + "0x1f937", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f937", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x2695", + "0xfe0f", + "0x1f468", + "0x200d", + "0x2695", + "0xfe0f", + "0x1f469", + "0x200d", + "0x2695", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f393", + "0x1f468", + "0x200d", + "0x1f393", + "0x1f469", + "0x200d", + "0x1f393", + "0x1f9d1", + "0x200d", + "0x1f3eb", + "0x1f468", + "0x200d", + "0x1f3eb", + "0x1f469", + "0x200d", + "0x1f3eb", + "0x1f9d1", + "0x200d", + "0x2696", + "0xfe0f", + "0x1f468", + "0x200d", + "0x2696", + "0xfe0f", + "0x1f469", + "0x200d", + "0x2696", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f33e", + "0x1f468", + "0x200d", + "0x1f33e", + "0x1f469", + "0x200d", + "0x1f33e", + "0x1f9d1", + "0x200d", + "0x1f373", + "0x1f468", + "0x200d", + "0x1f373", + "0x1f469", + "0x200d", + "0x1f373", + "0x1f9d1", + "0x200d", + "0x1f527", + "0x1f468", + "0x200d", + "0x1f527", + "0x1f469", + "0x200d", + "0x1f527", + "0x1f9d1", + "0x200d", + "0x1f3ed", + "0x1f468", + "0x200d", + "0x1f3ed", + "0x1f469", + "0x200d", + "0x1f3ed", + "0x1f9d1", + "0x200d", + "0x1f4bc", + "0x1f468", + "0x200d", + "0x1f4bc", + "0x1f469", + "0x200d", + "0x1f4bc", + "0x1f9d1", + "0x200d", + "0x1f52c", + "0x1f468", + "0x200d", + "0x1f52c", + "0x1f469", + "0x200d", + "0x1f52c", + "0x1f9d1", + "0x200d", + "0x1f4bb", + "0x1f468", + "0x200d", + "0x1f4bb", + "0x1f469", + "0x200d", + "0x1f4bb", + "0x1f9d1", + "0x200d", + "0x1f3a4", + "0x1f468", + "0x200d", + "0x1f3a4", + "0x1f469", + "0x200d", + "0x1f3a4", + "0x1f9d1", + "0x200d", + "0x1f3a8", + "0x1f468", + "0x200d", + "0x1f3a8", + "0x1f469", + "0x200d", + "0x1f3a8", + "0x1f9d1", + "0x200d", + "0x2708", + "0xfe0f", + "0x1f468", + "0x200d", + "0x2708", + "0xfe0f", + "0x1f469", + "0x200d", + "0x2708", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f680", + "0x1f468", + "0x200d", + "0x1f680", + "0x1f469", + "0x200d", + "0x1f680", + "0x1f9d1", + "0x200d", + "0x1f692", + "0x1f468", + "0x200d", + "0x1f692", + "0x1f469", + "0x200d", + "0x1f692", + "0x1f46e", + "0x1f46e", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f46e", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f575", + "0x1f575", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f575", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f482", + "0x1f482", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f482", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f977", + "0x1f477", + "0x1f477", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f477", + "0x200d", + "0x2640", + "0xfe0f", + "0x1fac5", + "0x1f934", + "0x1f478", + "0x1f473", + "0x1f473", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f473", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f472", + "0x1f9d5", + "0x1f935", + "0x1f935", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f935", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f470", + "0x1f470", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f470", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f930", + "0x1fac3", + "0x1fac4", + "0x1f931", + "0x1f469", + "0x200d", + "0x1f37c", + "0x1f468", + "0x200d", + "0x1f37c", + "0x1f9d1", + "0x200d", + "0x1f37c", + "0x1f47c", + "0x1f385", + "0x1f936", + "0x1f9d1", + "0x200d", + "0x1f384", + "0x1f9b8", + "0x1f9b8", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9b8", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9b9", + "0x1f9b9", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9b9", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d9", + "0x1f9d9", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d9", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9da", + "0x1f9da", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9da", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9db", + "0x1f9db", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9db", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9dc", + "0x1f9dc", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9dc", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9dd", + "0x1f9dd", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9dd", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9de", + "0x1f9de", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9de", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9df", + "0x1f9df", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9df", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9cc", + "0x1f486", + "0x1f486", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f486", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f487", + "0x1f487", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f487", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b6", + "0x1f6b6", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x2640", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f6b6", + "0x200d", + "0x2642", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9cd", + "0x1f9cd", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9cd", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9ce", + "0x1f9ce", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x2640", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9ce", + "0x200d", + "0x2642", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f9af", + "0x1f9d1", + "0x200d", + "0x1f9af", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9af", + "0x1f468", + "0x200d", + "0x1f9af", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f469", + "0x200d", + "0x1f9af", + "0x1f469", + "0x200d", + "0x1f9af", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f9bc", + "0x1f9d1", + "0x200d", + "0x1f9bc", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9bc", + "0x1f468", + "0x200d", + "0x1f9bc", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f469", + "0x200d", + "0x1f9bc", + "0x1f469", + "0x200d", + "0x1f9bc", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f9d1", + "0x200d", + "0x1f9bd", + "0x1f9d1", + "0x200d", + "0x1f9bd", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f468", + "0x200d", + "0x1f9bd", + "0x1f468", + "0x200d", + "0x1f9bd", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f469", + "0x200d", + "0x1f9bd", + "0x1f469", + "0x200d", + "0x1f9bd", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f3c3", + "0x1f3c3", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x2640", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f3c3", + "0x200d", + "0x2642", + "0xfe0f", + "0x200d", + "0x27a1", + "0xfe0f", + "0x1f483", + "0x1f57a", + "0x1f574", + "0x1f46f", + "0x1f46f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f46f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d6", + "0x1f9d6", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d6", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d7", + "0x1f9d7", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d7", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93a", + "0x1f3c7", + "0x26f7", + "0x1f3c2", + "0x1f3cc", + "0x1f3cc", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3cc", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3c4", + "0x1f3c4", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3c4", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6a3", + "0x1f6a3", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6a3", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3ca", + "0x1f3ca", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3ca", + "0x200d", + "0x2640", + "0xfe0f", + "0x26f9", + "0x26f9", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x26f9", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f3cb", + "0x1f3cb", + "0xfe0f", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f3cb", + "0xfe0f", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b4", + "0x1f6b4", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6b4", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6b5", + "0x1f6b5", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f6b5", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f938", + "0x1f938", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f938", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93c", + "0x1f93c", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f93c", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93d", + "0x1f93d", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f93d", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f93e", + "0x1f93e", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f93e", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f939", + "0x1f939", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f939", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f9d8", + "0x1f9d8", + "0x200d", + "0x2642", + "0xfe0f", + "0x1f9d8", + "0x200d", + "0x2640", + "0xfe0f", + "0x1f6c0", + "0x1f6cc", + "0x1f9d1", + "0x200d", + "0x1f91d", + "0x200d", + "0x1f9d1", + "0x1f46d", + "0x1f46b", + "0x1f46c", + "0x1f48f", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f48b", + "0x200d", + "0x1f468", + "0x1f468", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f48b", + "0x200d", + "0x1f468", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f48b", + "0x200d", + "0x1f469", + "0x1f491", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f468", + "0x1f468", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f468", + "0x1f469", + "0x200d", + "0x2764", + "0xfe0f", + "0x200d", + "0x1f469", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f467", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f468", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f466", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f467", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f466", + "0x1f469", + "0x200d", + "0x1f467", + "0x200d", + "0x1f467", + "0x1f5e3", + "0x1f464", + "0x1f465", + "0x1fac2", + "0x1f46a", + "0x1f9d1", + "0x200d", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x1f9d1", + "0x200d", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x200d", + "0x1f9d2", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x1f9d1", + "0x200d", + "0x1f9d2", + "0x200d", + "0x1f9d2", + "0x1f463" + ], + "animals_and_nature": [ + "0x1f435", + "0x1f412", + "0x1f98d", + "0x1f9a7", + "0x1f436", + "0x1f415", + "0x1f9ae", + "0x1f415", + "0x200d", + "0x1f9ba", + "0x1f429", + "0x1f43a", + "0x1f98a", + "0x1f99d", + "0x1f431", + "0x1f408", + "0x1f408", + "0x200d", + "0x2b1b", + "0x1f981", + "0x1f42f", + "0x1f405", + "0x1f406", + "0x1f434", + "0x1face", + "0x1facf", + "0x1f40e", + "0x1f984", + "0x1f993", + "0x1f98c", + "0x1f9ac", + "0x1f42e", + "0x1f402", + "0x1f403", + "0x1f404", + "0x1f437", + "0x1f416", + "0x1f417", + "0x1f43d", + "0x1f40f", + "0x1f411", + "0x1f410", + "0x1f42a", + "0x1f42b", + "0x1f999", + "0x1f992", + "0x1f418", + "0x1f9a3", + "0x1f98f", + "0x1f99b", + "0x1f42d", + "0x1f401", + "0x1f400", + "0x1f439", + "0x1f430", + "0x1f407", + "0x1f43f", + "0x1f9ab", + "0x1f994", + "0x1f987", + "0x1f43b", + "0x1f43b", + "0x200d", + "0x2744", + "0xfe0f", + "0x1f428", + "0x1f43c", + "0x1f9a5", + "0x1f9a6", + "0x1f9a8", + "0x1f998", + "0x1f9a1", + "0x1f43e", + "0x1f983", + "0x1f414", + "0x1f413", + "0x1f423", + "0x1f424", + "0x1f425", + "0x1f426", + "0x1f427", + "0x1f54a", + "0x1f985", + "0x1f986", + "0x1f9a2", + "0x1f989", + "0x1f9a4", + "0x1fab6", + "0x1f9a9", + "0x1f99a", + "0x1f99c", + "0x1fabd", + "0x1f426", + "0x200d", + "0x2b1b", + "0x1fabf", + "0x1f426", + "0x200d", + "0x1f525", + "0x1f438", + "0x1f40a", + "0x1f422", + "0x1f98e", + "0x1f40d", + "0x1f432", + "0x1f409", + "0x1f995", + "0x1f996", + "0x1f433", + "0x1f40b", + "0x1f42c", + "0x1f9ad", + "0x1f41f", + "0x1f420", + "0x1f421", + "0x1f988", + "0x1f419", + "0x1f41a", + "0x1fab8", + "0x1fabc", + "0x1f40c", + "0x1f98b", + "0x1f41b", + "0x1f41c", + "0x1f41d", + "0x1fab2", + "0x1f41e", + "0x1f997", + "0x1fab3", + "0x1f577", + "0x1f578", + "0x1f982", + "0x1f99f", + "0x1fab0", + "0x1fab1", + "0x1f9a0", + "0x1f490", + "0x1f338", + "0x1f4ae", + "0x1fab7", + "0x1f3f5", + "0x1f339", + "0x1f940", + "0x1f33a", + "0x1f33b", + "0x1f33c", + "0x1f337", + "0x1fabb", + "0x1f331", + "0x1fab4", + "0x1f332", + "0x1f333", + "0x1f334", + "0x1f335", + "0x1f33e", + "0x1f33f", + "0x2618", + "0x1f340", + "0x1f341", + "0x1f342", + "0x1f343", + "0x1fab9", + "0x1faba", + "0x1f344" + ], + "food_and_drink": [ + "0x1f347", + "0x1f348", + "0x1f349", + "0x1f34a", + "0x1f34b", + "0x1f34b", + "0x200d", + "0x1f7e9", + "0x1f34c", + "0x1f34d", + "0x1f96d", + "0x1f34e", + "0x1f34f", + "0x1f350", + "0x1f351", + "0x1f352", + "0x1f353", + "0x1fad0", + "0x1f95d", + "0x1f345", + "0x1fad2", + "0x1f965", + "0x1f951", + "0x1f346", + "0x1f954", + "0x1f955", + "0x1f33d", + "0x1f336", + "0x1fad1", + "0x1f952", + "0x1f96c", + "0x1f966", + "0x1f9c4", + "0x1f9c5", + "0x1f95c", + "0x1fad8", + "0x1f330", + "0x1fada", + "0x1fadb", + "0x1f344", + "0x200d", + "0x1f7eb", + "0x1f35e", + "0x1f950", + "0x1f956", + "0x1fad3", + "0x1f968", + "0x1f96f", + "0x1f95e", + "0x1f9c7", + "0x1f9c0", + "0x1f356", + "0x1f357", + "0x1f969", + "0x1f953", + "0x1f354", + "0x1f35f", + "0x1f355", + "0x1f32d", + "0x1f96a", + "0x1f32e", + "0x1f32f", + "0x1fad4", + "0x1f959", + "0x1f9c6", + "0x1f95a", + "0x1f373", + "0x1f958", + "0x1f372", + "0x1fad5", + "0x1f963", + "0x1f957", + "0x1f37f", + "0x1f9c8", + "0x1f9c2", + "0x1f96b", + "0x1f371", + "0x1f358", + "0x1f359", + "0x1f35a", + "0x1f35b", + "0x1f35c", + "0x1f35d", + "0x1f360", + "0x1f362", + "0x1f363", + "0x1f364", + "0x1f365", + "0x1f96e", + "0x1f361", + "0x1f95f", + "0x1f960", + "0x1f961", + "0x1f980", + "0x1f99e", + "0x1f990", + "0x1f991", + "0x1f9aa", + "0x1f366", + "0x1f367", + "0x1f368", + "0x1f369", + "0x1f36a", + "0x1f382", + "0x1f370", + "0x1f9c1", + "0x1f967", + "0x1f36b", + "0x1f36c", + "0x1f36d", + "0x1f36e", + "0x1f36f", + "0x1f37c", + "0x1f95b", + "0x2615", + "0x1fad6", + "0x1f375", + "0x1f376", + "0x1f37e", + "0x1f377", + "0x1f378", + "0x1f379", + "0x1f37a", + "0x1f37b", + "0x1f942", + "0x1f943", + "0x1fad7", + "0x1f964", + "0x1f9cb", + "0x1f9c3", + "0x1f9c9", + "0x1f9ca", + "0x1f962", + "0x1f37d", + "0x1f374", + "0x1f944", + "0x1f52a", + "0x1fad9", + "0x1f3fa" + ], + "travel_and_places": [ + "0x1f30d", + "0x1f30e", + "0x1f30f", + "0x1f310", + "0x1f5fa", + "0x1f5fe", + "0x1f9ed", + "0x1f3d4", + "0x26f0", + "0x1f30b", + "0x1f5fb", + "0x1f3d5", + "0x1f3d6", + "0x1f3dc", + "0x1f3dd", + "0x1f3de", + "0x1f3df", + "0x1f3db", + "0x1f3d7", + "0x1f9f1", + "0x1faa8", + "0x1fab5", + "0x1f6d6", + "0x1f3d8", + "0x1f3da", + "0x1f3e0", + "0x1f3e1", + "0x1f3e2", + "0x1f3e3", + "0x1f3e4", + "0x1f3e5", + "0x1f3e6", + "0x1f3e8", + "0x1f3e9", + "0x1f3ea", + "0x1f3eb", + "0x1f3ec", + "0x1f3ed", + "0x1f3ef", + "0x1f3f0", + "0x1f492", + "0x1f5fc", + "0x1f5fd", + "0x26ea", + "0x1f54c", + "0x1f6d5", + "0x1f54d", + "0x26e9", + "0x1f54b", + "0x26f2", + "0x26fa", + "0x1f301", + "0x1f303", + "0x1f3d9", + "0x1f304", + "0x1f305", + "0x1f306", + "0x1f307", + "0x1f309", + "0x2668", + "0x1f3a0", + "0x1f6dd", + "0x1f3a1", + "0x1f3a2", + "0x1f488", + "0x1f3aa", + "0x1f682", + "0x1f683", + "0x1f684", + "0x1f685", + "0x1f686", + "0x1f687", + "0x1f688", + "0x1f689", + "0x1f68a", + "0x1f69d", + "0x1f69e", + "0x1f68b", + "0x1f68c", + "0x1f68d", + "0x1f68e", + "0x1f690", + "0x1f691", + "0x1f692", + "0x1f693", + "0x1f694", + "0x1f695", + "0x1f696", + "0x1f697", + "0x1f698", + "0x1f699", + "0x1f6fb", + "0x1f69a", + "0x1f69b", + "0x1f69c", + "0x1f3ce", + "0x1f3cd", + "0x1f6f5", + "0x1f9bd", + "0x1f9bc", + "0x1f6fa", + "0x1f6b2", + "0x1f6f4", + "0x1f6f9", + "0x1f6fc", + "0x1f68f", + "0x1f6e3", + "0x1f6e4", + "0x1f6e2", + "0x26fd", + "0x1f6de", + "0x1f6a8", + "0x1f6a5", + "0x1f6a6", + "0x1f6d1", + "0x1f6a7", + "0x2693", + "0x1f6df", + "0x26f5", + "0x1f6f6", + "0x1f6a4", + "0x1f6f3", + "0x26f4", + "0x1f6e5", + "0x1f6a2", + "0x2708", + "0x1f6e9", + "0x1f6eb", + "0x1f6ec", + "0x1fa82", + "0x1f4ba", + "0x1f681", + "0x1f69f", + "0x1f6a0", + "0x1f6a1", + "0x1f6f0", + "0x1f680", + "0x1f6f8", + "0x1f6ce", + "0x1f9f3", + "0x231b", + "0x23f3", + "0x231a", + "0x23f0", + "0x23f1", + "0x23f2", + "0x1f570", + "0x1f55b", + "0x1f567", + "0x1f550", + "0x1f55c", + "0x1f551", + "0x1f55d", + "0x1f552", + "0x1f55e", + "0x1f553", + "0x1f55f", + "0x1f554", + "0x1f560", + "0x1f555", + "0x1f561", + "0x1f556", + "0x1f562", + "0x1f557", + "0x1f563", + "0x1f558", + "0x1f564", + "0x1f559", + "0x1f565", + "0x1f55a", + "0x1f566", + "0x1f311", + "0x1f312", + "0x1f313", + "0x1f314", + "0x1f315", + "0x1f316", + "0x1f317", + "0x1f318", + "0x1f319", + "0x1f31a", + "0x1f31b", + "0x1f31c", + "0x1f321", + "0x2600", + "0x1f31d", + "0x1f31e", + "0x1fa90", + "0x2b50", + "0x1f31f", + "0x1f320", + "0x1f30c", + "0x2601", + "0x26c5", + "0x26c8", + "0x1f324", + "0x1f325", + "0x1f326", + "0x1f327", + "0x1f328", + "0x1f329", + "0x1f32a", + "0x1f32b", + "0x1f32c", + "0x1f300", + "0x1f308", + "0x1f302", + "0x2602", + "0x2614", + "0x26f1", + "0x26a1", + "0x2744", + "0x2603", + "0x26c4", + "0x2604", + "0x1f525", + "0x1f4a7", + "0x1f30a" + ], + "activities": [ + "0x1f383", + "0x1f384", + "0x1f386", + "0x1f387", + "0x1f9e8", + "0x2728", + "0x1f388", + "0x1f389", + "0x1f38a", + "0x1f38b", + "0x1f38d", + "0x1f38e", + "0x1f38f", + "0x1f390", + "0x1f391", + "0x1f9e7", + "0x1f380", + "0x1f381", + "0x1f397", + "0x1f39f", + "0x1f3ab", + "0x1f396", + "0x1f3c6", + "0x1f3c5", + "0x1f947", + "0x1f948", + "0x1f949", + "0x26bd", + "0x26be", + "0x1f94e", + "0x1f3c0", + "0x1f3d0", + "0x1f3c8", + "0x1f3c9", + "0x1f3be", + "0x1f94f", + "0x1f3b3", + "0x1f3cf", + "0x1f3d1", + "0x1f3d2", + "0x1f94d", + "0x1f3d3", + "0x1f3f8", + "0x1f94a", + "0x1f94b", + "0x1f945", + "0x26f3", + "0x26f8", + "0x1f3a3", + "0x1f93f", + "0x1f3bd", + "0x1f3bf", + "0x1f6f7", + "0x1f94c", + "0x1f3af", + "0x1fa80", + "0x1fa81", + "0x1f52b", + "0x1f3b1", + "0x1f52e", + "0x1fa84", + "0x1f3ae", + "0x1f579", + "0x1f3b0", + "0x1f3b2", + "0x1f9e9", + "0x1f9f8", + "0x1fa85", + "0x1faa9", + "0x1fa86", + "0x2660", + "0x2665", + "0x2666", + "0x2663", + "0x265f", + "0x1f0cf", + "0x1f004", + "0x1f3b4", + "0x1f3ad", + "0x1f5bc", + "0x1f3a8", + "0x1f9f5", + "0x1faa1", + "0x1f9f6", + "0x1faa2" + ], + "objects": [ + "0x1f453", + "0x1f576", + "0x1f97d", + "0x1f97c", + "0x1f9ba", + "0x1f454", + "0x1f455", + "0x1f456", + "0x1f9e3", + "0x1f9e4", + "0x1f9e5", + "0x1f9e6", + "0x1f457", + "0x1f458", + "0x1f97b", + "0x1fa71", + "0x1fa72", + "0x1fa73", + "0x1f459", + "0x1f45a", + "0x1faad", + "0x1f45b", + "0x1f45c", + "0x1f45d", + "0x1f6cd", + "0x1f392", + "0x1fa74", + "0x1f45e", + "0x1f45f", + "0x1f97e", + "0x1f97f", + "0x1f460", + "0x1f461", + "0x1fa70", + "0x1f462", + "0x1faae", + "0x1f451", + "0x1f452", + "0x1f3a9", + "0x1f393", + "0x1f9e2", + "0x1fa96", + "0x26d1", + "0x1f4ff", + "0x1f484", + "0x1f48d", + "0x1f48e", + "0x1f507", + "0x1f508", + "0x1f509", + "0x1f50a", + "0x1f4e2", + "0x1f4e3", + "0x1f4ef", + "0x1f514", + "0x1f515", + "0x1f3bc", + "0x1f3b5", + "0x1f3b6", + "0x1f399", + "0x1f39a", + "0x1f39b", + "0x1f3a4", + "0x1f3a7", + "0x1f4fb", + "0x1f3b7", + "0x1fa97", + "0x1f3b8", + "0x1f3b9", + "0x1f3ba", + "0x1f3bb", + "0x1fa95", + "0x1f941", + "0x1fa98", + "0x1fa87", + "0x1fa88", + "0x1f4f1", + "0x1f4f2", + "0x260e", + "0x1f4de", + "0x1f4df", + "0x1f4e0", + "0x1f50b", + "0x1faab", + "0x1f50c", + "0x1f4bb", + "0x1f5a5", + "0x1f5a8", + "0x2328", + "0x1f5b1", + "0x1f5b2", + "0x1f4bd", + "0x1f4be", + "0x1f4bf", + "0x1f4c0", + "0x1f9ee", + "0x1f3a5", + "0x1f39e", + "0x1f4fd", + "0x1f3ac", + "0x1f4fa", + "0x1f4f7", + "0x1f4f8", + "0x1f4f9", + "0x1f4fc", + "0x1f50d", + "0x1f50e", + "0x1f56f", + "0x1f4a1", + "0x1f526", + "0x1f3ee", + "0x1fa94", + "0x1f4d4", + "0x1f4d5", + "0x1f4d6", + "0x1f4d7", + "0x1f4d8", + "0x1f4d9", + "0x1f4da", + "0x1f4d3", + "0x1f4d2", + "0x1f4c3", + "0x1f4dc", + "0x1f4c4", + "0x1f4f0", + "0x1f5de", + "0x1f4d1", + "0x1f516", + "0x1f3f7", + "0x1f4b0", + "0x1fa99", + "0x1f4b4", + "0x1f4b5", + "0x1f4b6", + "0x1f4b7", + "0x1f4b8", + "0x1f4b3", + "0x1f9fe", + "0x1f4b9", + "0x2709", + "0x1f4e7", + "0x1f4e8", + "0x1f4e9", + "0x1f4e4", + "0x1f4e5", + "0x1f4e6", + "0x1f4eb", + "0x1f4ea", + "0x1f4ec", + "0x1f4ed", + "0x1f4ee", + "0x1f5f3", + "0x270f", + "0x2712", + "0x1f58b", + "0x1f58a", + "0x1f58c", + "0x1f58d", + "0x1f4dd", + "0x1f4bc", + "0x1f4c1", + "0x1f4c2", + "0x1f5c2", + "0x1f4c5", + "0x1f4c6", + "0x1f5d2", + "0x1f5d3", + "0x1f4c7", + "0x1f4c8", + "0x1f4c9", + "0x1f4ca", + "0x1f4cb", + "0x1f4cc", + "0x1f4cd", + "0x1f4ce", + "0x1f587", + "0x1f4cf", + "0x1f4d0", + "0x2702", + "0x1f5c3", + "0x1f5c4", + "0x1f5d1", + "0x1f512", + "0x1f513", + "0x1f50f", + "0x1f510", + "0x1f511", + "0x1f5dd", + "0x1f528", + "0x1fa93", + "0x26cf", + "0x2692", + "0x1f6e0", + "0x1f5e1", + "0x2694", + "0x1f4a3", + "0x1fa83", + "0x1f3f9", + "0x1f6e1", + "0x1fa9a", + "0x1f527", + "0x1fa9b", + "0x1f529", + "0x2699", + "0x1f5dc", + "0x2696", + "0x1f9af", + "0x1f517", + "0x26d3", + "0xfe0f", + "0x200d", + "0x1f4a5", + "0x26d3", + "0x1fa9d", + "0x1f9f0", + "0x1f9f2", + "0x1fa9c", + "0x2697", + "0x1f9ea", + "0x1f9eb", + "0x1f9ec", + "0x1f52c", + "0x1f52d", + "0x1f4e1", + "0x1f489", + "0x1fa78", + "0x1f48a", + "0x1fa79", + "0x1fa7c", + "0x1fa7a", + "0x1fa7b", + "0x1f6aa", + "0x1f6d7", + "0x1fa9e", + "0x1fa9f", + "0x1f6cf", + "0x1f6cb", + "0x1fa91", + "0x1f6bd", + "0x1faa0", + "0x1f6bf", + "0x1f6c1", + "0x1faa4", + "0x1fa92", + "0x1f9f4", + "0x1f9f7", + "0x1f9f9", + "0x1f9fa", + "0x1f9fb", + "0x1faa3", + "0x1f9fc", + "0x1fae7", + "0x1faa5", + "0x1f9fd", + "0x1f9ef", + "0x1f6d2", + "0x1f6ac", + "0x26b0", + "0x1faa6", + "0x26b1", + "0x1f9ff", + "0x1faac", + "0x1f5ff", + "0x1faa7", + "0x1faaa" + ], + "symbols": [ + "0x1f3e7", + "0x1f6ae", + "0x1f6b0", + "0x267f", + "0x1f6b9", + "0x1f6ba", + "0x1f6bb", + "0x1f6bc", + "0x1f6be", + "0x1f6c2", + "0x1f6c3", + "0x1f6c4", + "0x1f6c5", + "0x26a0", + "0x1f6b8", + "0x26d4", + "0x1f6ab", + "0x1f6b3", + "0x1f6ad", + "0x1f6af", + "0x1f6b1", + "0x1f6b7", + "0x1f4f5", + "0x1f51e", + "0x2622", + "0x2623", + "0x2b06", + "0x2197", + "0x27a1", + "0x2198", + "0x2b07", + "0x2199", + "0x2b05", + "0x2196", + "0x2195", + "0x2194", + "0x21a9", + "0x21aa", + "0x2934", + "0x2935", + "0x1f503", + "0x1f504", + "0x1f519", + "0x1f51a", + "0x1f51b", + "0x1f51c", + "0x1f51d", + "0x1f6d0", + "0x269b", + "0x1f549", + "0x2721", + "0x2638", + "0x262f", + "0x271d", + "0x2626", + "0x262a", + "0x262e", + "0x1f54e", + "0x1f52f", + "0x1faaf", + "0x2648", + "0x2649", + "0x264a", + "0x264b", + "0x264c", + "0x264d", + "0x264e", + "0x264f", + "0x2650", + "0x2651", + "0x2652", + "0x2653", + "0x26ce", + "0x1f500", + "0x1f501", + "0x1f502", + "0x25b6", + "0x23e9", + "0x23ed", + "0x23ef", + "0x25c0", + "0x23ea", + "0x23ee", + "0x1f53c", + "0x23eb", + "0x1f53d", + "0x23ec", + "0x23f8", + "0x23f9", + "0x23fa", + "0x23cf", + "0x1f3a6", + "0x1f505", + "0x1f506", + "0x1f4f6", + "0x1f6dc", + "0x1f4f3", + "0x1f4f4", + "0x2640", + "0x2642", + "0x26a7", + "0x2716", + "0x2795", + "0x2796", + "0x2797", + "0x1f7f0", + "0x267e", + "0x203c", + "0x2049", + "0x2753", + "0x2754", + "0x2755", + "0x2757", + "0x3030", + "0x1f4b1", + "0x1f4b2", + "0x2695", + "0x267b", + "0x269c", + "0x1f531", + "0x1f4db", + "0x1f530", + "0x2b55", + "0x2705", + "0x2611", + "0x2714", + "0x274c", + "0x274e", + "0x27b0", + "0x27bf", + "0x303d", + "0x2733", + "0x2734", + "0x2747", + "0x00a9", + "0x00ae", + "0x2122", + "0x0023", + "0xfe0f", + "0x20e3", + "0x002a", + "0xfe0f", + "0x20e3", + "0x0030", + "0xfe0f", + "0x20e3", + "0x0031", + "0xfe0f", + "0x20e3", + "0x0032", + "0xfe0f", + "0x20e3", + "0x0033", + "0xfe0f", + "0x20e3", + "0x0034", + "0xfe0f", + "0x20e3", + "0x0035", + "0xfe0f", + "0x20e3", + "0x0036", + "0xfe0f", + "0x20e3", + "0x0037", + "0xfe0f", + "0x20e3", + "0x0038", + "0xfe0f", + "0x20e3", + "0x0039", + "0xfe0f", + "0x20e3", + "0x1f51f", + "0x1f520", + "0x1f521", + "0x1f522", + "0x1f523", + "0x1f524", + "0x1f170", + "0x1f18e", + "0x1f171", + "0x1f191", + "0x1f192", + "0x1f193", + "0x2139", + "0x1f194", + "0x24c2", + "0x1f195", + "0x1f196", + "0x1f17e", + "0x1f197", + "0x1f17f", + "0x1f198", + "0x1f199", + "0x1f19a", + "0x1f201", + "0x1f202", + "0x1f237", + "0x1f236", + "0x1f22f", + "0x1f250", + "0x1f239", + "0x1f21a", + "0x1f232", + "0x1f251", + "0x1f238", + "0x1f234", + "0x1f233", + "0x3297", + "0x3299", + "0x1f23a", + "0x1f235", + "0x1f534", + "0x1f7e0", + "0x1f7e1", + "0x1f7e2", + "0x1f535", + "0x1f7e3", + "0x1f7e4", + "0x26ab", + "0x26aa", + "0x1f7e5", + "0x1f7e7", + "0x1f7e8", + "0x1f7e9", + "0x1f7e6", + "0x1f7ea", + "0x1f7eb", + "0x2b1b", + "0x2b1c", + "0x25fc", + "0x25fb", + "0x25fe", + "0x25fd", + "0x25aa", + "0x25ab", + "0x1f536", + "0x1f537", + "0x1f538", + "0x1f539", + "0x1f53a", + "0x1f53b", + "0x1f4a0", + "0x1f518", + "0x1f533", + "0x1f532" + ], + "flags": [ + "0x1f3c1", + "0x1f6a9", + "0x1f38c", + "0x1f3f4", + "0x1f3f3", + "0x1f3f3", + "0xfe0f", + "0x200d", + "0x1f308", + "0x1f3f3", + "0xfe0f", + "0x200d", + "0x26a7", + "0xfe0f", + "0x1f3f4", + "0x200d", + "0x2620", + "0xfe0f", + "0x1f1e6", + "0x1f1e8", + "0x1f1e6", + "0x1f1e9", + "0x1f1e6", + "0x1f1ea", + "0x1f1e6", + "0x1f1eb", + "0x1f1e6", + "0x1f1ec", + "0x1f1e6", + "0x1f1ee", + "0x1f1e6", + "0x1f1f1", + "0x1f1e6", + "0x1f1f2", + "0x1f1e6", + "0x1f1f4", + "0x1f1e6", + "0x1f1f6", + "0x1f1e6", + "0x1f1f7", + "0x1f1e6", + "0x1f1f8", + "0x1f1e6", + "0x1f1f9", + "0x1f1e6", + "0x1f1fa", + "0x1f1e6", + "0x1f1fc", + "0x1f1e6", + "0x1f1fd", + "0x1f1e6", + "0x1f1ff", + "0x1f1e7", + "0x1f1e6", + "0x1f1e7", + "0x1f1e7", + "0x1f1e7", + "0x1f1e9", + "0x1f1e7", + "0x1f1ea", + "0x1f1e7", + "0x1f1eb", + "0x1f1e7", + "0x1f1ec", + "0x1f1e7", + "0x1f1ed", + "0x1f1e7", + "0x1f1ee", + "0x1f1e7", + "0x1f1ef", + "0x1f1e7", + "0x1f1f1", + "0x1f1e7", + "0x1f1f2", + "0x1f1e7", + "0x1f1f3", + "0x1f1e7", + "0x1f1f4", + "0x1f1e7", + "0x1f1f6", + "0x1f1e7", + "0x1f1f7", + "0x1f1e7", + "0x1f1f8", + "0x1f1e7", + "0x1f1f9", + "0x1f1e7", + "0x1f1fb", + "0x1f1e7", + "0x1f1fc", + "0x1f1e7", + "0x1f1fe", + "0x1f1e7", + "0x1f1ff", + "0x1f1e8", + "0x1f1e6", + "0x1f1e8", + "0x1f1e8", + "0x1f1e8", + "0x1f1e9", + "0x1f1e8", + "0x1f1eb", + "0x1f1e8", + "0x1f1ec", + "0x1f1e8", + "0x1f1ed", + "0x1f1e8", + "0x1f1ee", + "0x1f1e8", + "0x1f1f0", + "0x1f1e8", + "0x1f1f1", + "0x1f1e8", + "0x1f1f2", + "0x1f1e8", + "0x1f1f3", + "0x1f1e8", + "0x1f1f4", + "0x1f1e8", + "0x1f1f5", + "0x1f1e8", + "0x1f1f7", + "0x1f1e8", + "0x1f1fa", + "0x1f1e8", + "0x1f1fb", + "0x1f1e8", + "0x1f1fc", + "0x1f1e8", + "0x1f1fd", + "0x1f1e8", + "0x1f1fe", + "0x1f1e8", + "0x1f1ff", + "0x1f1e9", + "0x1f1ea", + "0x1f1e9", + "0x1f1ec", + "0x1f1e9", + "0x1f1ef", + "0x1f1e9", + "0x1f1f0", + "0x1f1e9", + "0x1f1f2", + "0x1f1e9", + "0x1f1f4", + "0x1f1e9", + "0x1f1ff", + "0x1f1ea", + "0x1f1e6", + "0x1f1ea", + "0x1f1e8", + "0x1f1ea", + "0x1f1ea", + "0x1f1ea", + "0x1f1ec", + "0x1f1ea", + "0x1f1ed", + "0x1f1ea", + "0x1f1f7", + "0x1f1ea", + "0x1f1f8", + "0x1f1ea", + "0x1f1f9", + "0x1f1ea", + "0x1f1fa", + "0x1f1eb", + "0x1f1ee", + "0x1f1eb", + "0x1f1ef", + "0x1f1eb", + "0x1f1f0", + "0x1f1eb", + "0x1f1f2", + "0x1f1eb", + "0x1f1f4", + "0x1f1eb", + "0x1f1f7", + "0x1f1ec", + "0x1f1e6", + "0x1f1ec", + "0x1f1e7", + "0x1f1ec", + "0x1f1e9", + "0x1f1ec", + "0x1f1ea", + "0x1f1ec", + "0x1f1eb", + "0x1f1ec", + "0x1f1ec", + "0x1f1ec", + "0x1f1ed", + "0x1f1ec", + "0x1f1ee", + "0x1f1ec", + "0x1f1f1", + "0x1f1ec", + "0x1f1f2", + "0x1f1ec", + "0x1f1f3", + "0x1f1ec", + "0x1f1f5", + "0x1f1ec", + "0x1f1f6", + "0x1f1ec", + "0x1f1f7", + "0x1f1ec", + "0x1f1f8", + "0x1f1ec", + "0x1f1f9", + "0x1f1ec", + "0x1f1fa", + "0x1f1ec", + "0x1f1fc", + "0x1f1ec", + "0x1f1fe", + "0x1f1ed", + "0x1f1f0", + "0x1f1ed", + "0x1f1f2", + "0x1f1ed", + "0x1f1f3", + "0x1f1ed", + "0x1f1f7", + "0x1f1ed", + "0x1f1f9", + "0x1f1ed", + "0x1f1fa", + "0x1f1ee", + "0x1f1e8", + "0x1f1ee", + "0x1f1e9", + "0x1f1ee", + "0x1f1ea", + "0x1f1ee", + "0x1f1f1", + "0x1f1ee", + "0x1f1f2", + "0x1f1ee", + "0x1f1f3", + "0x1f1ee", + "0x1f1f4", + "0x1f1ee", + "0x1f1f6", + "0x1f1ee", + "0x1f1f7", + "0x1f1ee", + "0x1f1f8", + "0x1f1ee", + "0x1f1f9", + "0x1f1ef", + "0x1f1ea", + "0x1f1ef", + "0x1f1f2", + "0x1f1ef", + "0x1f1f4", + "0x1f1ef", + "0x1f1f5", + "0x1f1f0", + "0x1f1ea", + "0x1f1f0", + "0x1f1ec", + "0x1f1f0", + "0x1f1ed", + "0x1f1f0", + "0x1f1ee", + "0x1f1f0", + "0x1f1f2", + "0x1f1f0", + "0x1f1f3", + "0x1f1f0", + "0x1f1f5", + "0x1f1f0", + "0x1f1f7", + "0x1f1f0", + "0x1f1fc", + "0x1f1f0", + "0x1f1fe", + "0x1f1f0", + "0x1f1ff", + "0x1f1f1", + "0x1f1e6", + "0x1f1f1", + "0x1f1e7", + "0x1f1f1", + "0x1f1e8", + "0x1f1f1", + "0x1f1ee", + "0x1f1f1", + "0x1f1f0", + "0x1f1f1", + "0x1f1f7", + "0x1f1f1", + "0x1f1f8", + "0x1f1f1", + "0x1f1f9", + "0x1f1f1", + "0x1f1fa", + "0x1f1f1", + "0x1f1fb", + "0x1f1f1", + "0x1f1fe", + "0x1f1f2", + "0x1f1e6", + "0x1f1f2", + "0x1f1e8", + "0x1f1f2", + "0x1f1e9", + "0x1f1f2", + "0x1f1ea", + "0x1f1f2", + "0x1f1eb", + "0x1f1f2", + "0x1f1ec", + "0x1f1f2", + "0x1f1ed", + "0x1f1f2", + "0x1f1f0", + "0x1f1f2", + "0x1f1f1", + "0x1f1f2", + "0x1f1f2", + "0x1f1f2", + "0x1f1f3", + "0x1f1f2", + "0x1f1f4", + "0x1f1f2", + "0x1f1f5", + "0x1f1f2", + "0x1f1f6", + "0x1f1f2", + "0x1f1f7", + "0x1f1f2", + "0x1f1f8", + "0x1f1f2", + "0x1f1f9", + "0x1f1f2", + "0x1f1fa", + "0x1f1f2", + "0x1f1fb", + "0x1f1f2", + "0x1f1fc", + "0x1f1f2", + "0x1f1fd", + "0x1f1f2", + "0x1f1fe", + "0x1f1f2", + "0x1f1ff", + "0x1f1f3", + "0x1f1e6", + "0x1f1f3", + "0x1f1e8", + "0x1f1f3", + "0x1f1ea", + "0x1f1f3", + "0x1f1eb", + "0x1f1f3", + "0x1f1ec", + "0x1f1f3", + "0x1f1ee", + "0x1f1f3", + "0x1f1f1", + "0x1f1f3", + "0x1f1f4", + "0x1f1f3", + "0x1f1f5", + "0x1f1f3", + "0x1f1f7", + "0x1f1f3", + "0x1f1fa", + "0x1f1f3", + "0x1f1ff", + "0x1f1f4", + "0x1f1f2", + "0x1f1f5", + "0x1f1e6", + "0x1f1f5", + "0x1f1ea", + "0x1f1f5", + "0x1f1eb", + "0x1f1f5", + "0x1f1ec", + "0x1f1f5", + "0x1f1ed", + "0x1f1f5", + "0x1f1f0", + "0x1f1f5", + "0x1f1f1", + "0x1f1f5", + "0x1f1f2", + "0x1f1f5", + "0x1f1f3", + "0x1f1f5", + "0x1f1f7", + "0x1f1f5", + "0x1f1f8", + "0x1f1f5", + "0x1f1f9", + "0x1f1f5", + "0x1f1fc", + "0x1f1f5", + "0x1f1fe", + "0x1f1f6", + "0x1f1e6", + "0x1f1f7", + "0x1f1ea", + "0x1f1f7", + "0x1f1f4", + "0x1f1f7", + "0x1f1f8", + "0x1f1f7", + "0x1f1fa", + "0x1f1f7", + "0x1f1fc", + "0x1f1f8", + "0x1f1e6", + "0x1f1f8", + "0x1f1e7", + "0x1f1f8", + "0x1f1e8", + "0x1f1f8", + "0x1f1e9", + "0x1f1f8", + "0x1f1ea", + "0x1f1f8", + "0x1f1ec", + "0x1f1f8", + "0x1f1ed", + "0x1f1f8", + "0x1f1ee", + "0x1f1f8", + "0x1f1ef", + "0x1f1f8", + "0x1f1f0", + "0x1f1f8", + "0x1f1f1", + "0x1f1f8", + "0x1f1f2", + "0x1f1f8", + "0x1f1f3", + "0x1f1f8", + "0x1f1f4", + "0x1f1f8", + "0x1f1f7", + "0x1f1f8", + "0x1f1f8", + "0x1f1f8", + "0x1f1f9", + "0x1f1f8", + "0x1f1fb", + "0x1f1f8", + "0x1f1fd", + "0x1f1f8", + "0x1f1fe", + "0x1f1f8", + "0x1f1ff", + "0x1f1f9", + "0x1f1e6", + "0x1f1f9", + "0x1f1e8", + "0x1f1f9", + "0x1f1e9", + "0x1f1f9", + "0x1f1eb", + "0x1f1f9", + "0x1f1ec", + "0x1f1f9", + "0x1f1ed", + "0x1f1f9", + "0x1f1ef", + "0x1f1f9", + "0x1f1f0", + "0x1f1f9", + "0x1f1f1", + "0x1f1f9", + "0x1f1f2", + "0x1f1f9", + "0x1f1f3", + "0x1f1f9", + "0x1f1f4", + "0x1f1f9", + "0x1f1f7", + "0x1f1f9", + "0x1f1f9", + "0x1f1f9", + "0x1f1fb", + "0x1f1f9", + "0x1f1fc", + "0x1f1f9", + "0x1f1ff", + "0x1f1fa", + "0x1f1e6", + "0x1f1fa", + "0x1f1ec", + "0x1f1fa", + "0x1f1f2", + "0x1f1fa", + "0x1f1f3", + "0x1f1fa", + "0x1f1f8", + "0x1f1fa", + "0x1f1fe", + "0x1f1fa", + "0x1f1ff", + "0x1f1fb", + "0x1f1e6", + "0x1f1fb", + "0x1f1e8", + "0x1f1fb", + "0x1f1ea", + "0x1f1fb", + "0x1f1ec", + "0x1f1fb", + "0x1f1ee", + "0x1f1fb", + "0x1f1f3", + "0x1f1fb", + "0x1f1fa", + "0x1f1fc", + "0x1f1eb", + "0x1f1fc", + "0x1f1f8", + "0x1f1fd", + "0x1f1f0", + "0x1f1fe", + "0x1f1ea", + "0x1f1fe", + "0x1f1f9", + "0x1f1ff", + "0x1f1e6", + "0x1f1ff", + "0x1f1f2", + "0x1f1ff", + "0x1f1fc", + "0x1f3f4", + "0xe0067", + "0xe0062", + "0xe0065", + "0xe006e", + "0xe0067", + "0xe007f", + "0x1f3f4", + "0xe0067", + "0xe0062", + "0xe0073", + "0xe0063", + "0xe0074", + "0xe007f", + "0x1f3f4", + "0xe0067", + "0xe0062", + "0xe0077", + "0xe006c", + "0xe0073", + "0xe007f" + ] + } + }; -/***/ }), + var o_hasOwnProperty = Object.prototype.hasOwnProperty; + var o_keys = (Object.keys || function(obj) { + var result = []; + for (var key in obj) { + if (o_hasOwnProperty.call(obj, key)) { + result.push(key); + } + } -/***/ 14462: -/***/ ((module) => { + return result; + }); -"use strict"; + function _copyObject(source, target) { + var keys = o_keys(source); + var key; -/** @type {Record} */ -const headerNameLowerCasedRecord = {} + for (var i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + target[key] = source[key] || target[key]; + } + } -// https://developer.mozilla.org/docs/Web/HTTP/Headers -const wellknownHeaderNames = [ - 'Accept', - 'Accept-Encoding', - 'Accept-Language', - 'Accept-Ranges', - 'Access-Control-Allow-Credentials', - 'Access-Control-Allow-Headers', - 'Access-Control-Allow-Methods', - 'Access-Control-Allow-Origin', - 'Access-Control-Expose-Headers', - 'Access-Control-Max-Age', - 'Access-Control-Request-Headers', - 'Access-Control-Request-Method', - 'Age', - 'Allow', - 'Alt-Svc', - 'Alt-Used', - 'Authorization', - 'Cache-Control', - 'Clear-Site-Data', - 'Connection', - 'Content-Disposition', - 'Content-Encoding', - 'Content-Language', - 'Content-Length', - 'Content-Location', - 'Content-Range', - 'Content-Security-Policy', - 'Content-Security-Policy-Report-Only', - 'Content-Type', - 'Cookie', - 'Cross-Origin-Embedder-Policy', - 'Cross-Origin-Opener-Policy', - 'Cross-Origin-Resource-Policy', - 'Date', - 'Device-Memory', - 'Downlink', - 'ECT', - 'ETag', - 'Expect', - 'Expect-CT', - 'Expires', - 'Forwarded', - 'From', - 'Host', - 'If-Match', - 'If-Modified-Since', - 'If-None-Match', - 'If-Range', - 'If-Unmodified-Since', - 'Keep-Alive', - 'Last-Modified', - 'Link', - 'Location', - 'Max-Forwards', - 'Origin', - 'Permissions-Policy', - 'Pragma', - 'Proxy-Authenticate', - 'Proxy-Authorization', - 'RTT', - 'Range', - 'Referer', - 'Referrer-Policy', - 'Refresh', - 'Retry-After', - 'Sec-WebSocket-Accept', - 'Sec-WebSocket-Extensions', - 'Sec-WebSocket-Key', - 'Sec-WebSocket-Protocol', - 'Sec-WebSocket-Version', - 'Server', - 'Server-Timing', - 'Service-Worker-Allowed', - 'Service-Worker-Navigation-Preload', - 'Set-Cookie', - 'SourceMap', - 'Strict-Transport-Security', - 'Supports-Loading-Mode', - 'TE', - 'Timing-Allow-Origin', - 'Trailer', - 'Transfer-Encoding', - 'Upgrade', - 'Upgrade-Insecure-Requests', - 'User-Agent', - 'Vary', - 'Via', - 'WWW-Authenticate', - 'X-Content-Type-Options', - 'X-DNS-Prefetch-Control', - 'X-Frame-Options', - 'X-Permitted-Cross-Domain-Policies', - 'X-Powered-By', - 'X-Requested-With', - 'X-XSS-Protection' -] + function _copyArray(source, target) { + for (var i = 0, l = source.length; i < l; i++) { + target[i] = source[i]; + } + } -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = wellknownHeaderNames[i] - const lowerCasedKey = key.toLowerCase() - headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = - lowerCasedKey -} + function copyObject(source, _target) { + var isArray = Array.isArray(source); + var target = _target || (isArray ? new Array(source.length) : {}); -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(headerNameLowerCasedRecord, null) + if (isArray) { + _copyArray(source, target); + } else { + _copyObject(source, target); + } -module.exports = { - wellknownHeaderNames, - headerNameLowerCasedRecord -} + return target; + } + /** Get the data based on key**/ + Chance.prototype.get = function (name) { + return copyObject(data[name]); + }; -/***/ }), + // Mac Address + Chance.prototype.mac_address = function(options){ + // typically mac addresses are separated by ":" + // however they can also be separated by "-" + // the network variant uses a dot every fourth byte -/***/ 48045: -/***/ ((module) => { + options = initOptions(options); + if(!options.separator) { + options.separator = options.networkVersion ? "." : ":"; + } -"use strict"; + var mac_pool="ABCDEF1234567890", + mac = ""; + if(!options.networkVersion) { + mac = this.n(this.string, 6, { pool: mac_pool, length:2 }).join(options.separator); + } else { + mac = this.n(this.string, 3, { pool: mac_pool, length:4 }).join(options.separator); + } + return mac; + }; -class UndiciError extends Error { - constructor (message) { - super(message) - this.name = 'UndiciError' - this.code = 'UND_ERR' - } -} + Chance.prototype.normal = function (options) { + options = initOptions(options, {mean : 0, dev : 1, pool : []}); -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' - } -} + testRange( + options.pool.constructor !== Array, + "Chance: The pool option must be a valid array." + ); + testRange( + typeof options.mean !== 'number', + "Chance: Mean (mean) must be a number" + ); + testRange( + typeof options.dev !== 'number', + "Chance: Standard deviation (dev) must be a number" + ); -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' - } -} + // If a pool has been passed, then we are returning an item from that pool, + // using the normal distribution settings that were passed in + if (options.pool.length > 0) { + return this.normal_pool(options); + } -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' - } -} + // The Marsaglia Polar method + var s, u, v, norm, + mean = options.mean, + dev = options.dev; -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' - } -} + do { + // U and V are from the uniform distribution on (-1, 1) + u = this.random() * 2 - 1; + v = this.random() * 2 - 1; -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 - } -} + s = u * u + v * v; + } while (s >= 1); -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' - } -} + // Compute the standard normal variate + norm = u * Math.sqrt(-2 * Math.log(s) / s); -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' - } -} + // Shape and scale + return dev * norm + mean; + }; -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' - } -} + Chance.prototype.normal_pool = function(options) { + var performanceCounter = 0; + do { + var idx = Math.round(this.normal({ mean: options.mean, dev: options.dev })); + if (idx < options.pool.length && idx >= 0) { + return options.pool[idx]; + } else { + performanceCounter++; + } + } while(performanceCounter < 100); -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' - } -} + throw new RangeError("Chance: Your pool is too small for the given mean and standard deviation. Please adjust."); + }; -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' - } -} + Chance.prototype.radio = function (options) { + // Initial Letter (Typically Designated by Side of Mississippi River) + options = initOptions(options, {side : "?"}); + var fl = ""; + switch (options.side.toLowerCase()) { + case "east": + case "e": + fl = "W"; + break; + case "west": + case "w": + fl = "K"; + break; + default: + fl = this.character({pool: "KW"}); + break; + } -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' - } -} + return fl + this.character({alpha: true, casing: "upper"}) + + this.character({alpha: true, casing: "upper"}) + + this.character({alpha: true, casing: "upper"}); + }; -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' - } -} + // Set the data as key and data or the data map + Chance.prototype.set = function (name, values) { + if (typeof name === "string") { + data[name] = values; + } else { + data = copyObject(name, data); + } + }; -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' - } -} + Chance.prototype.tv = function (options) { + return this.radio(options); + }; -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 - } -} + // ID number for Brazil companies + Chance.prototype.cnpj = function () { + var n = this.n(this.natural, 8, { max: 9 }); + var d1 = 2+n[7]*6+n[6]*7+n[5]*8+n[4]*9+n[3]*2+n[2]*3+n[1]*4+n[0]*5; + d1 = 11 - (d1 % 11); + if (d1>=10){ + d1 = 0; + } + var d2 = d1*2+3+n[7]*7+n[6]*8+n[5]*9+n[4]*2+n[3]*3+n[2]*4+n[1]*5+n[0]*6; + d2 = 11 - (d2 % 11); + if (d2>=10){ + d2 = 0; + } + return ''+n[0]+n[1]+'.'+n[2]+n[3]+n[4]+'.'+n[5]+n[6]+n[7]+'/0001-'+d1+d2; + }; -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' - } -} + Chance.prototype.emotion = function () { + return this.pick(this.get("emotions")); + }; -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' - } -} + // -- End Miscellaneous -- -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 - } -} + Chance.prototype.mersenne_twister = function (seed) { + return new MersenneTwister(seed); + }; -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' - } -} + Chance.prototype.blueimp_md5 = function () { + return new BlueImpMD5(); + }; -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 - } -} + // Mersenne Twister from https://gist.github.com/banksean/300494 + /* + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. -module.exports = { - HTTPParserError, - UndiciError, - HeadersTimeoutError, - HeadersOverflowError, - BodyTimeoutError, - RequestContentLengthMismatchError, - ConnectTimeoutError, - ResponseStatusCodeError, - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError, - ClientDestroyedError, - ClientClosedError, - InformationalError, - SocketError, - NotSupportedError, - ResponseContentLengthMismatchError, - BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError, - RequestRetryError -} + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. -/***/ }), + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: -/***/ 62905: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. -"use strict"; + 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 names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. -const { - InvalidArgumentError, - NotSupportedError -} = __nccwpck_require__(48045) -const assert = __nccwpck_require__(39491) -const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(72785) -const util = __nccwpck_require__(83983) + 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. -// 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!#$%&'*+.|~]+$/ + Any feedback is very welcome. + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) + */ + var MersenneTwister = function (seed) { + if (seed === undefined) { + // kept random number same size as time used previously to ensure no unexpected results downstream + seed = Math.floor(Math.random()*Math.pow(10,13)); + } + /* Period parameters */ + this.N = 624; + this.M = 397; + this.MATRIX_A = 0x9908b0df; /* constant vector a */ + this.UPPER_MASK = 0x80000000; /* most significant w-r bits */ + this.LOWER_MASK = 0x7fffffff; /* least significant r bits */ -/** - * 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]/ + this.mt = new Array(this.N); /* the array for the state vector */ + this.mti = this.N + 1; /* mti==N + 1 means mt[N] is not initialized */ -// Verifies that a given path is valid does not contain control chars \x00 to \x20 -const invalidPathRegex = /[^\u0021-\u00ff]/ + this.init_genrand(seed); + }; -const kHandler = Symbol('handler') + /* initializes mt[N] with a seed */ + MersenneTwister.prototype.init_genrand = function (s) { + this.mt[0] = s >>> 0; + for (this.mti = 1; this.mti < this.N; this.mti++) { + s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30); + this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti; + /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ + /* In the previous versions, MSBs of the seed affect */ + /* only MSBs of the array mt[]. */ + /* 2002/01/09 modified by Makoto Matsumoto */ + this.mt[this.mti] >>>= 0; + /* for >32 bit machines */ + } + }; -const channels = {} + /* initialize by an array with array-length */ + /* init_key is the array for initializing keys */ + /* key_length is its length */ + /* slight change for C++, 2004/2/26 */ + MersenneTwister.prototype.init_by_array = function (init_key, key_length) { + var i = 1, j = 0, k, s; + this.init_genrand(19650218); + k = (this.N > key_length ? this.N : key_length); + for (; k; k--) { + s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); + this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525))) + init_key[j] + j; /* non linear */ + this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ + i++; + j++; + if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } + if (j >= key_length) { j = 0; } + } + for (k = this.N - 1; k; k--) { + s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30); + this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i; /* non linear */ + this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */ + i++; + if (i >= this.N) { this.mt[0] = this.mt[this.N - 1]; i = 1; } + } -let extractBody + this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ + }; -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 } -} + /* generates a random number on [0,0xffffffff]-interval */ + MersenneTwister.prototype.genrand_int32 = function () { + var y; + var mag01 = new Array(0x0, this.MATRIX_A); + /* mag01[x] = x * MATRIX_A for x=0,1 */ -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 (this.mti >= this.N) { /* generate N words at one time */ + var kk; - 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 (this.mti === this.N + 1) { /* if init_genrand() has not been called, */ + this.init_genrand(5489); /* a default initial seed is used */ + } + for (kk = 0; kk < this.N - this.M; kk++) { + y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); + this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 0x1]; + } + for (;kk < this.N - 1; kk++) { + y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk + 1]&this.LOWER_MASK); + this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 0x1]; + } + y = (this.mt[this.N - 1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK); + this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; - if (upgrade && typeof upgrade !== 'string') { - throw new InvalidArgumentError('upgrade must be a string') - } + this.mti = 0; + } - if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('invalid headersTimeout') - } + y = this.mt[this.mti++]; - if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('invalid bodyTimeout') - } + /* Tempering */ + y ^= (y >>> 11); + y ^= (y << 7) & 0x9d2c5680; + y ^= (y << 15) & 0xefc60000; + y ^= (y >>> 18); - if (reset != null && typeof reset !== 'boolean') { - throw new InvalidArgumentError('invalid reset') - } + return y >>> 0; + }; - if (expectContinue != null && typeof expectContinue !== 'boolean') { - throw new InvalidArgumentError('invalid expectContinue') - } + /* generates a random number on [0,0x7fffffff]-interval */ + MersenneTwister.prototype.genrand_int31 = function () { + return (this.genrand_int32() >>> 1); + }; - this.headersTimeout = headersTimeout + /* generates a random number on [0,1]-real-interval */ + MersenneTwister.prototype.genrand_real1 = function () { + return this.genrand_int32() * (1.0 / 4294967295.0); + /* divided by 2^32-1 */ + }; - this.bodyTimeout = bodyTimeout + /* generates a random number on [0,1)-real-interval */ + MersenneTwister.prototype.random = function () { + return this.genrand_int32() * (1.0 / 4294967296.0); + /* divided by 2^32 */ + }; - this.throwOnError = throwOnError === true + /* generates a random number on (0,1)-real-interval */ + MersenneTwister.prototype.genrand_real3 = function () { + return (this.genrand_int32() + 0.5) * (1.0 / 4294967296.0); + /* divided by 2^32 */ + }; - this.method = method + /* generates a random number on [0,1) with 53-bit resolution*/ + MersenneTwister.prototype.genrand_res53 = function () { + var a = this.genrand_int32()>>>5, b = this.genrand_int32()>>>6; + return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); + }; - this.abort = null + // BlueImp MD5 hashing algorithm from https://github.com/blueimp/JavaScript-MD5 + var BlueImpMD5 = function () {}; - if (body == null) { - this.body = null - } else if (util.isStream(body)) { - this.body = body + BlueImpMD5.prototype.VERSION = '1.0.1'; - const rState = this.body._readableState - if (!rState || !rState.autoDestroy) { - this.endHandler = function autoDestroy () { - util.destroy(this) - } - this.body.on('end', this.endHandler) - } + /* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + BlueImpMD5.prototype.safe_add = function safe_add(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF), + msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); + }; - 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') - } + /* + * Bitwise rotate a 32-bit number to the left. + */ + BlueImpMD5.prototype.bit_roll = function (num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); + }; - this.completed = false + /* + * These functions implement the five basic operations the algorithm uses. + */ + BlueImpMD5.prototype.md5_cmn = function (q, a, b, x, s, t) { + return this.safe_add(this.bit_roll(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s), b); + }; + BlueImpMD5.prototype.md5_ff = function (a, b, c, d, x, s, t) { + return this.md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); + }; + BlueImpMD5.prototype.md5_gg = function (a, b, c, d, x, s, t) { + return this.md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); + }; + BlueImpMD5.prototype.md5_hh = function (a, b, c, d, x, s, t) { + return this.md5_cmn(b ^ c ^ d, a, b, x, s, t); + }; + BlueImpMD5.prototype.md5_ii = function (a, b, c, d, x, s, t) { + return this.md5_cmn(c ^ (b | (~d)), a, b, x, s, t); + }; - this.aborted = false + /* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + BlueImpMD5.prototype.binl_md5 = function (x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << (len % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; - this.upgrade = upgrade || null + var i, olda, oldb, oldc, oldd, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; - this.path = query ? util.buildURL(path, query) : path + for (i = 0; i < x.length; i += 16) { + olda = a; + oldb = b; + oldc = c; + oldd = d; - this.origin = origin + a = this.md5_ff(a, b, c, d, x[i], 7, -680876936); + d = this.md5_ff(d, a, b, c, x[i + 1], 12, -389564586); + c = this.md5_ff(c, d, a, b, x[i + 2], 17, 606105819); + b = this.md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = this.md5_ff(a, b, c, d, x[i + 4], 7, -176418897); + d = this.md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = this.md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = this.md5_ff(b, c, d, a, x[i + 7], 22, -45705983); + a = this.md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = this.md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = this.md5_ff(c, d, a, b, x[i + 10], 17, -42063); + b = this.md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = this.md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = this.md5_ff(d, a, b, c, x[i + 13], 12, -40341101); + c = this.md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = this.md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); - this.idempotent = idempotent == null - ? method === 'HEAD' || method === 'GET' - : idempotent + a = this.md5_gg(a, b, c, d, x[i + 1], 5, -165796510); + d = this.md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = this.md5_gg(c, d, a, b, x[i + 11], 14, 643717713); + b = this.md5_gg(b, c, d, a, x[i], 20, -373897302); + a = this.md5_gg(a, b, c, d, x[i + 5], 5, -701558691); + d = this.md5_gg(d, a, b, c, x[i + 10], 9, 38016083); + c = this.md5_gg(c, d, a, b, x[i + 15], 14, -660478335); + b = this.md5_gg(b, c, d, a, x[i + 4], 20, -405537848); + a = this.md5_gg(a, b, c, d, x[i + 9], 5, 568446438); + d = this.md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = this.md5_gg(c, d, a, b, x[i + 3], 14, -187363961); + b = this.md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = this.md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = this.md5_gg(d, a, b, c, x[i + 2], 9, -51403784); + c = this.md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = this.md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); - this.blocking = blocking == null ? false : blocking + a = this.md5_hh(a, b, c, d, x[i + 5], 4, -378558); + d = this.md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = this.md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = this.md5_hh(b, c, d, a, x[i + 14], 23, -35309556); + a = this.md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = this.md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = this.md5_hh(c, d, a, b, x[i + 7], 16, -155497632); + b = this.md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = this.md5_hh(a, b, c, d, x[i + 13], 4, 681279174); + d = this.md5_hh(d, a, b, c, x[i], 11, -358537222); + c = this.md5_hh(c, d, a, b, x[i + 3], 16, -722521979); + b = this.md5_hh(b, c, d, a, x[i + 6], 23, 76029189); + a = this.md5_hh(a, b, c, d, x[i + 9], 4, -640364487); + d = this.md5_hh(d, a, b, c, x[i + 12], 11, -421815835); + c = this.md5_hh(c, d, a, b, x[i + 15], 16, 530742520); + b = this.md5_hh(b, c, d, a, x[i + 2], 23, -995338651); - this.reset = reset == null ? null : reset + a = this.md5_ii(a, b, c, d, x[i], 6, -198630844); + d = this.md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = this.md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = this.md5_ii(b, c, d, a, x[i + 5], 21, -57434055); + a = this.md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = this.md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = this.md5_ii(c, d, a, b, x[i + 10], 15, -1051523); + b = this.md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = this.md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = this.md5_ii(d, a, b, c, x[i + 15], 10, -30611744); + c = this.md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = this.md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = this.md5_ii(a, b, c, d, x[i + 4], 6, -145523070); + d = this.md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = this.md5_ii(c, d, a, b, x[i + 2], 15, 718787259); + b = this.md5_ii(b, c, d, a, x[i + 9], 21, -343485551); - this.host = null + a = this.safe_add(a, olda); + b = this.safe_add(b, oldb); + c = this.safe_add(c, oldc); + d = this.safe_add(d, oldd); + } + return [a, b, c, d]; + }; - this.contentLength = null + /* + * Convert an array of little-endian words to a string + */ + BlueImpMD5.prototype.binl2rstr = function (input) { + var i, + output = ''; + for (i = 0; i < input.length * 32; i += 8) { + output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); + } + return output; + }; - this.contentType = null + /* + * Convert a raw string to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + BlueImpMD5.prototype.rstr2binl = function (input) { + var i, + output = []; + output[(input.length >> 2) - 1] = undefined; + for (i = 0; i < output.length; i += 1) { + output[i] = 0; + } + for (i = 0; i < input.length * 8; i += 8) { + output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); + } + return output; + }; - this.headers = '' + /* + * Calculate the MD5 of a raw string + */ + BlueImpMD5.prototype.rstr_md5 = function (s) { + return this.binl2rstr(this.binl_md5(this.rstr2binl(s), s.length * 8)); + }; - // Only for H2 - this.expectContinue = expectContinue != null ? expectContinue : false + /* + * Calculate the HMAC-MD5, of a key and some data (raw strings) + */ + BlueImpMD5.prototype.rstr_hmac_md5 = function (key, data) { + var i, + bkey = this.rstr2binl(key), + ipad = [], + opad = [], + hash; + ipad[15] = opad[15] = undefined; + if (bkey.length > 16) { + bkey = this.binl_md5(bkey, key.length * 8); + } + for (i = 0; i < 16; i += 1) { + ipad[i] = bkey[i] ^ 0x36363636; + opad[i] = bkey[i] ^ 0x5C5C5C5C; + } + hash = this.binl_md5(ipad.concat(this.rstr2binl(data)), 512 + data.length * 8); + return this.binl2rstr(this.binl_md5(opad.concat(hash), 512 + 128)); + }; - 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') - } + /* + * Convert a raw string to a hex string + */ + BlueImpMD5.prototype.rstr2hex = function (input) { + var hex_tab = '0123456789abcdef', + output = '', + x, + i; + for (i = 0; i < input.length; i += 1) { + x = input.charCodeAt(i); + output += hex_tab.charAt((x >>> 4) & 0x0F) + + hex_tab.charAt(x & 0x0F); + } + return output; + }; - 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.') - } + /* + * Encode a string as utf-8 + */ + BlueImpMD5.prototype.str2rstr_utf8 = function (input) { + return unescape(encodeURIComponent(input)); + }; - if (!extractBody) { - extractBody = (__nccwpck_require__(41472).extractBody) - } + /* + * Take string arguments and return either raw or hex encoded strings + */ + BlueImpMD5.prototype.raw_md5 = function (s) { + return this.rstr_md5(this.str2rstr_utf8(s)); + }; + BlueImpMD5.prototype.hex_md5 = function (s) { + return this.rstr2hex(this.raw_md5(s)); + }; + BlueImpMD5.prototype.raw_hmac_md5 = function (k, d) { + return this.rstr_hmac_md5(this.str2rstr_utf8(k), this.str2rstr_utf8(d)); + }; + BlueImpMD5.prototype.hex_hmac_md5 = function (k, d) { + return this.rstr2hex(this.raw_hmac_md5(k, d)); + }; - 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` - } + BlueImpMD5.prototype.md5 = function (string, key, raw) { + if (!key) { + if (!raw) { + return this.hex_md5(string); + } - util.validateHandler(handler, method, upgrade) + return this.raw_md5(string); + } - this.servername = util.getServerName(this.host) + if (!raw) { + return this.hex_hmac_md5(key, string); + } - this[kHandler] = handler + return this.raw_hmac_md5(key, string); + }; - if (channels.create.hasSubscribers) { - channels.create.publish({ request: this }) + // CommonJS module + if (true) { + if ( true && module.exports) { + exports = module.exports = Chance; + } + exports.Chance = Chance; } - } - onBodySent (chunk) { - if (this[kHandler].onBodySent) { - try { - return this[kHandler].onBodySent(chunk) - } catch (err) { - this.abort(err) - } + // Register as an anonymous AMD module + if (typeof define === 'function' && define.amd) { + define([], function () { + return Chance; + }); } - } - onRequestSent () { - if (channels.bodySent.hasSubscribers) { - channels.bodySent.publish({ request: this }) + // if there is a importsScrips object define chance for worker + // allows worker to use full Chance functionality with seed + if (typeof importScripts !== 'undefined') { + chance = new Chance(); + self.Chance = Chance; } - if (this[kHandler].onRequestSent) { - try { - return this[kHandler].onRequestSent() - } catch (err) { - this.abort(err) - } + // If there is a window object, that at least has a document property, + // instantiate and define chance on the window + if (typeof window === "object" && typeof window.document === "object") { + window.Chance = Chance; + window.chance = new Chance(); } - } - - 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 } }) - } +/***/ 3733: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - return this[kHandler].onHeaders(statusCode, headers, resume, statusText) - } catch (err) { - this.abort(err) - } - } +"use strict"; - onData (chunk) { - assert(!this.aborted) - assert(!this.completed) +const cliBoxes = __nccwpck_require__(94); - try { - return this[kHandler].onData(chunk) - } catch (err) { - this.abort(err) - return false - } - } +module.exports = cliBoxes; +// TODO: Remove this for the next major release +module.exports["default"] = cliBoxes; - onUpgrade (statusCode, headers, socket) { - assert(!this.aborted) - assert(!this.completed) - return this[kHandler].onUpgrade(statusCode, headers, socket) - } +/***/ }), - onComplete (trailers) { - this.onFinally() +/***/ 8932: +/***/ ((__unused_webpack_module, exports) => { - assert(!this.aborted) +"use strict"; - 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) - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - onError (error) { - this.onFinally() +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }) - } + /* istanbul ignore next */ - if (this.aborted) { - return + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } - this.aborted = true - return this[kHandler].onError(error) + this.name = 'Deprecation'; } - 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 - } - } +exports.Deprecation = Deprecation; - // 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 } +/***/ 8212: +/***/ ((module) => { - const request = new Request(origin, opts, handler) +module.exports = () => { + // https://mths.be/emoji + return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; +}; - 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 - } +/***/ 4882: +/***/ ((module) => { - static [kHTTP2CopyHeaders] (raw) { - const rawHeaders = raw.split('\r\n') - const headers = {} +"use strict"; +/* eslint-disable yoda */ - for (const header of rawHeaders) { - const [key, value] = header.split(': ') - if (value == null || value.length === 0) continue +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } - if (headers[key]) headers[key] += `,${value}` - else headers[key] = value - } + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } - return headers - } -} + return false; +}; -function processHeaderValue (key, val, skipAppend) { - if (val && typeof val === 'object') { - throw new InvalidArgumentError(`invalid ${key} header`) - } +module.exports = isFullwidthCodePoint; +module.exports["default"] = isFullwidthCodePoint; - val = val != null ? `${val}` : '' - if (headerCharRegex.exec(val) !== null) { - throw new InvalidArgumentError(`invalid ${key} header`) - } +/***/ }), - return skipAppend ? val : `${key}: ${val}\r\n` -} +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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 +var wrappy = __nccwpck_require__(2940) +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 +} - 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) - } +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 } -module.exports = Request + +/***/ }), + +/***/ 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); /***/ }), -/***/ 72785: -/***/ ((module) => { +/***/ 4294: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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') -} +module.exports = __nccwpck_require__(4219); /***/ }), -/***/ 83983: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4219: +/***/ ((__unused_webpack_module, 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 { headerNameLowerCasedRecord } = __nccwpck_require__(14462) +var net = __nccwpck_require__(1808); +var tls = __nccwpck_require__(4404); +var http = __nccwpck_require__(3685); +var https = __nccwpck_require__(5687); +var events = __nccwpck_require__(2361); +var assert = __nccwpck_require__(9491); +var util = __nccwpck_require__(3837); -const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) -function nop () {} +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; -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 httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; } -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 httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; } -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.') - } +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} - if (url.origin != null && typeof url.origin !== 'string') { - throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') - } +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - 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) - } +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 = []; - if (path && !path.startsWith('/')) { - path = `/${path}` + 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; + } } - // 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 + socket.destroy(); + self.removeSocket(socket); + }); } +util.inherits(TunnelingAgent, events.EventEmitter); -function parseOrigin (url) { - url = parseURL(url) +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - if (url.pathname !== '/' || url.search || url.hash) { - throw new InvalidArgumentError('invalid url') + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; } - return url -} - -function getHostname (host) { - if (host[0] === '[') { - const idx = host.indexOf(']') + // 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); - assert(idx !== -1) - return host.substring(1, idx) - } + function onFree() { + self.emit('free', socket, options); + } - const idx = host.indexOf(':') - if (idx === -1) return host + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; - return host.substring(0, idx) -} +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); -// 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 + 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; } - - assert.strictEqual(typeof host, 'string') - - const servername = getHostname(host) - if (net.isIP(servername)) { - return '' + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); } - return servername -} - -function deepClone (obj) { - return JSON.parse(JSON.stringify(obj)) -} - -function isAsyncIterable (obj) { - return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') -} + 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 isIterable (obj) { - return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) -} + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } -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 + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); } - return null -} + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); -function isDestroyed (stream) { - return !stream || !!(stream.destroyed || stream[kDestroyed]) -} + 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 isReadableAborted (stream) { - const state = stream && stream._readableState - return isDestroyed(stream) && state && !state.endEmitted -} + function onError(cause) { + connectReq.removeAllListeners(); -function destroy (stream, err) { - if (stream == null || !isStream(stream) || isDestroyed(stream)) { - return + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); } +}; - if (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) +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; } + this.sockets.splice(pos, 1); - if (stream.destroyed !== true) { - stream[kDestroyed] = true + 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); + }); } -} +}; -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 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 + }); -/** - * Retrieves a header name and returns its lowercase value. - * @param {string | Buffer} value Header name - * @returns {string} - */ -function headerNameToString (value) { - return headerNameLowerCasedRecord[value] || value.toLowerCase() + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); } -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] +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 +} - 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 +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]; + } } - 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 + return target; } -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 +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 { - ret.push(key, val) + args.unshift('TUNNEL:'); } + console.error.apply(console, args); } +} else { + debug = function() {}; +} +exports.debug = debug; // for test - // 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) +/***/ 1773: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const Client = __nccwpck_require__(3598) +const Dispatcher = __nccwpck_require__(412) +const errors = __nccwpck_require__(8045) +const Pool = __nccwpck_require__(4634) +const BalancedPool = __nccwpck_require__(7931) +const Agent = __nccwpck_require__(7890) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(4059) +const buildConnector = __nccwpck_require__(2067) +const MockClient = __nccwpck_require__(8687) +const MockAgent = __nccwpck_require__(6771) +const MockPool = __nccwpck_require__(6193) +const mockErrors = __nccwpck_require__(888) +const ProxyAgent = __nccwpck_require__(7858) +const RetryHandler = __nccwpck_require__(2286) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(1892) +const DecoratorHandler = __nccwpck_require__(6930) +const RedirectHandler = __nccwpck_require__(2860) +const createRedirectInterceptor = __nccwpck_require__(8861) + +let hasCrypto +try { + __nccwpck_require__(6113) + hasCrypto = true +} catch { + hasCrypto = false } -function validateHandler (handler, method, upgrade) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } +Object.assign(Dispatcher.prototype, api) - if (typeof handler.onConnect !== 'function') { - throw new InvalidArgumentError('invalid onConnect method') - } +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 - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor - if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { - throw new InvalidArgumentError('invalid onBodySent method') - } +module.exports.buildConnector = buildConnector +module.exports.errors = errors - 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') +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null } - if (typeof handler.onData !== 'function') { - throw new InvalidArgumentError('invalid onData method') + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') } - if (typeof handler.onComplete !== 'function') { - throw new InvalidArgumentError('invalid onComplete method') + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - } -} -// 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) - )) -} + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } -function isErrored (body) { - return !!(body && ( - stream.isErrored - ? stream.isErrored(body) - : /state: 'errored'/.test(nodeUtil.inspect(body) - ))) -} + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } -function isReadable (body) { - return !!(body && ( - stream.isReadable - ? stream.isReadable(body) - : /state: 'readable'/.test(nodeUtil.inspect(body) - ))) -} + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } -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 - } -} + url = util.parseURL(url) + } -async function * convertIterableToBuffer (iterable) { - for await (const chunk of iterable) { - yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + 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) } } -let ReadableStream -function ReadableStreamFrom (iterable) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(35356).ReadableStream) - } +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher - if (ReadableStream.from) { - return ReadableStream.from(convertIterableToBuffer(iterable)) - } +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__(4881).fetch) + } - 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() + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) } - }, - 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 } } -} + module.exports.Headers = __nccwpck_require__(554).Headers + module.exports.Response = __nccwpck_require__(7823).Response + module.exports.Request = __nccwpck_require__(8359).Request + module.exports.FormData = __nccwpck_require__(2015).FormData + module.exports.File = __nccwpck_require__(8511).File + module.exports.FileReader = __nccwpck_require__(1446).FileReader -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 { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(1246) + + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin + + const { CacheStorage } = __nccwpck_require__(7907) + const { kConstruct } = __nccwpck_require__(9174) + + // 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) } -const hasToWellFormed = !!String.prototype.toWellFormed +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(1724) -/** - * @param {string} val - */ -function toUSVString (val) { - if (hasToWellFormed) { - return `${val}`.toWellFormed() - } else if (nodeUtil.toUSVString) { - return nodeUtil.toUSVString(val) - } + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie - return `${val}` + const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) + + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType } -// 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 } +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = __nccwpck_require__(4284) - 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 + module.exports.WebSocket = WebSocket } -const kEnumerableProperty = Object.create(null) -kEnumerableProperty.enumerable = true +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 = { - kEnumerableProperty, - nop, - isDisturbed, - isErrored, - isReadable, - toUSVString, - isReadableAborted, - isBlobLike, - parseOrigin, - parseURL, - getServerName, - isStream, - isIterable, - isAsyncIterable, - isDestroyed, - headerNameToString, - 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'] -} +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors /***/ }), -/***/ 74839: +/***/ 7890: /***/ ((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 { InvalidArgumentError } = __nccwpck_require__(8045) +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(2785) +const DispatcherBase = __nccwpck_require__(4839) +const Pool = __nccwpck_require__(4634) +const Client = __nccwpck_require__(3598) +const util = __nccwpck_require__(3983) +const createRedirectInterceptor = __nccwpck_require__(8861) +const { WeakRef, FinalizationRegistry } = __nccwpck_require__(6436)() -const kDestroyed = Symbol('destroyed') -const kClosed = Symbol('closed') -const kOnDestroyed = Symbol('onDestroyed') -const kOnClosed = Symbol('onClosed') -const kInterceptedDispatch = Symbol('Intercepted Dispatch') +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') -class DispatcherBase extends Dispatcher { - constructor () { +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() - this[kDestroyed] = false - this[kOnDestroyed] = null - this[kClosed] = false - this[kOnClosed] = [] - } + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } - get destroyed () { - return this[kDestroyed] - } + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } - get closed () { - return this[kClosed] - } + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - get interceptors () { - return this[kInterceptors] - } + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } - 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] = 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) } - } + }) - this[kInterceptors] = newInterceptors - } + const agent = this - close (callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - this.close((err, data) => { - return err ? reject(err) : resolve(data) - }) - }) + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) } - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) } - if (this[kDestroyed]) { - queueMicrotask(() => callback(new ClientDestroyedError(), null)) - return + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) } - if (this[kClosed]) { - if (this[kOnClosed]) { - this[kOnClosed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) } + } - 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) + 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] } } - - // Should not error. - this[kClose]() - .then(() => this.destroy()) - .then(() => { - queueMicrotask(onClosed) - }) + return ret } - 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) - }) - }) + [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.') } - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + const ref = this[kClients].get(key) - if (this[kDestroyed]) { - if (this[kOnDestroyed]) { - this[kOnDestroyed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } + 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]) - if (!err) { - err = new ClientDestroyedError() + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) } - this[kDestroyed] = true - this[kOnDestroyed] = this[kOnDestroyed] || [] - this[kOnDestroyed].push(callback) + return dispatcher.dispatch(opts, handler) + } - const onDestroyed = () => { - const callbacks = this[kOnDestroyed] - this[kOnDestroyed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) + 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()) } } - // Should not error. - this[kDestroy](err).then(() => { - queueMicrotask(onDestroyed) - }) + await Promise.all(closePromises) } - [kInterceptedDispatch] (opts, handler) { - if (!this[kInterceptors] || this[kInterceptors].length === 0) { - this[kInterceptedDispatch] = this[kDispatch] - return this[kDispatch](opts, handler) + 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)) + } } - 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) + await Promise.all(destroyPromises) } +} - dispatch (opts, handler) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } +module.exports = Agent - 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() - } +/***/ 7032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this[kInterceptedDispatch](opts, handler) - } catch (err) { - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } +const { addAbortListener } = __nccwpck_require__(3983) +const { RequestAbortedError } = __nccwpck_require__(8045) - handler.onError(err) +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') - return false - } +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) } } -module.exports = DispatcherBase - - -/***/ }), +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null -/***/ 60412: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!signal) { + return + } -"use strict"; + if (signal.aborted) { + abort(self) + return + } + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } -const EventEmitter = __nccwpck_require__(82361) + addAbortListener(self[kSignal], self[kListener]) +} -class Dispatcher extends EventEmitter { - dispatch () { - throw new Error('not implemented') +function removeSignal (self) { + if (!self[kSignal]) { + return } - close () { - throw new Error('not implemented') + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) } - destroy () { - throw new Error('not implemented') - } + self[kSignal] = null + self[kListener] = null } -module.exports = Dispatcher +module.exports = { + addSignal, + removeSignal +} /***/ }), -/***/ 41472: +/***/ 9744: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Busboy = __nccwpck_require__(50727) -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) +const { AsyncResource } = __nccwpck_require__(852) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) -let random -try { - const crypto = __nccwpck_require__(6005) - random = (max) => crypto.randomInt(0, max) -} catch { - random = (max) => Math.floor(Math.random(max)) -} +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } -let ReadableStream = globalThis.ReadableStream + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile -const textEncoder = new TextEncoder() -const textDecoder = new TextDecoder() + const { signal, opaque, responseHeaders } = opts -// https://fetch.spec.whatwg.org/#concept-bodyinit-extract -function extractBody (object, keepalive = false) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(35356).ReadableStream) + 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) } - // 1. Let stream be null. - let stream = null + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - // 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 + 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 }) } - // 5. Assert: stream is a ReadableStream object. - assert(isReadableStreamLike(stream)) + 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 - // 6. Let action be null. - let action = null - // 7. Let source be null. - let source = null +/***/ }), - // 8. Let length be null. - let length = null +/***/ 8752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 9. Let type be null. - let type = null +"use strict"; - // 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 +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(2781) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) - // 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 +const kResume = Symbol('resume') - // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. - source = object.toString() +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) - // 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 + this[kResume] = null + } - // Set source to a copy of the bytes held by object. - source = new Uint8Array(object.slice()) - } else if (ArrayBuffer.isView(object)) { - // BufferSource/ArrayBufferView + _read () { + const { [kResume]: resume } = this - // 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${`${random(1e11)}`.padStart(11, '0')}` - const prefix = `--${boundary}\r\nContent-Disposition: form-data` + if (resume) { + this[kResume] = null + resume() + } + } - /*! 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') + _destroy (err, callback) { + this._read() - // 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. + callback(err) + } +} - const blobParts = [] - const rn = new Uint8Array([13, 10]) // '\r\n' - length = 0 - let hasUnknownSizeValue = false +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } - 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 - } - } - } + _read () { + this[kResume]() + } - const chunk = textEncoder.encode(`--${boundary}--`) - blobParts.push(chunk) - length += chunk.byteLength - if (hasUnknownSizeValue) { - length = null + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() } - // Set source to object. - source = object + callback(err) + } +} - action = async function * () { - for (const part of blobParts) { - if (part.stream) { - yield * part.stream() - } else { - yield part - } - } +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - // 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 + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } - // Set length to object’s size. - length = object.size + const { signal, method, opaque, onInfo, responseHeaders } = opts - // If object’s type attribute is not the empty byte sequence, set - // type to its value. - if (object.type) { - type = object.type + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } - } else if (typeof object[Symbol.asyncIterator] === 'function') { - // If keepalive is true, then throw a TypeError. - if (keepalive) { - throw new TypeError('keepalive') + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') } - // 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' - ) + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') } - stream = - object instanceof ReadableStream ? object : ReadableStreamFrom(object) - } + super('UNDICI_PIPELINE') - // 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) - } + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null - // 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]() + 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() + } }, - async pull (controller) { - const { value, done } = await iterator.next() - if (done) { - // When running action is done, close stream. - queueMicrotask(() => { - controller.close() - }) + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() } 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)) - } + req[kResume] = callback } - return controller.desiredSize > 0 - }, - async cancel (reason) { - await iterator.return() }, - type: undefined - }) - } + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this - // 13. Let body be a body whose stream is stream, source is source, - // and length is length. - const body = { stream, source, length } + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } - // 14. Return (body, type). - return [body, type] -} + if (abort && err) { + abort() + } -// https://fetch.spec.whatwg.org/#bodyinit-safely-extract -function safelyExtractBody (object, keepalive = false) { - if (!ReadableStream) { - // istanbul ignore next - ReadableStream = (__nccwpck_require__(35356).ReadableStream) - } + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) - // To safely extract a body and a `Content-Type` value from - // a byte sequence or BodyInit object object, run these steps: + removeSignal(this) - // 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.') - } + callback(err) + } + }).on('prefinish', () => { + const { req } = this - // 2. Return the results of extracting object. - return extractBody(object, keepalive) -} + // Node < 15 does not call _final in same tick. + req.push(null) + }) -function cloneBody (body) { - // To clone a body body, run these steps: + this.res = null - // https://fetch.spec.whatwg.org/#concept-body-clone + addSignal(this, signal) + } - // 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() + onConnect (abort, context) { + const { ret, res } = this - // 2. Set body’s stream to out1. - body.stream = out1 + assert(!res, 'pipeline cannot be retried') - // 3. Return a body whose stream is out2 and other members are copied from body. - return { - stream: finalClone, - length: body.length, - source: body.source - } -} + if (ret.destroyed) { + throw new RequestAbortedError() + } -async function * consumeBody (body) { - if (body) { - if (isUint8Array(body)) { - yield body - } else { - const stream = body.stream + this.abort = abort + this.context = context + } - if (util.isDisturbed(stream)) { - throw new TypeError('The body has already been consumed.') - } + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this - if (stream.locked) { - throw new TypeError('The stream is locked.') + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) } + return + } - // Compat. - stream[kBodyUsed] = true + this.res = new PipelineResponse(resume) - yield * stream + 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 } - } -} -function throwIfAborted (state) { - if (state.aborted) { - throw new DOMException('The operation was aborted.', 'AbortError') - } -} + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } -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) + body + .on('data', (chunk) => { + const { ret, body } = this - if (mimeType === 'failure') { - mimeType = '' - } else if (mimeType) { - mimeType = serializeAMimeType(mimeType) + if (!ret.push(chunk) && body.pause) { + body.pause() } + }) + .on('error', (err) => { + const { ret } = this - // 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) - }, + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this - 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) - }, + ret.push(null) + }) + .on('close', () => { + const { ret } = this - 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) - }, + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) - async formData () { - webidl.brandCheck(this, instance) + this.body = body + } - throwIfAborted(this[kState]) + onData (chunk) { + const { res } = this + return res.push(chunk) + } - const contentType = this.headers.get('Content-Type') + onComplete (trailers) { + const { res } = this + res.push(null) + } - // 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 + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} - const responseFormData = new FormData() +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) + } +} - let busboy +module.exports = pipeline - 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 = '' +/***/ 5448: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - value.on('data', (chunk) => { - base64chunk += chunk.toString().replace(/[\r\n]/gm, '') +"use strict"; - 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 Readable = __nccwpck_require__(3858) +const { + InvalidArgumentError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) - const busboyResolve = new Promise((resolve, reject) => { - busboy.on('finish', resolve) - busboy.on('error', (err) => reject(new TypeError(err))) - }) +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) - busboy.end() - await busboyResolve + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts - return responseFormData - } else if (/application\/x-www-form-urlencoded/.test(contentType)) { - // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - // 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 }) + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } - 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 }) - } + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - // 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() + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - throwIfAborted(this[kState]) + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } - // Otherwise, throw a TypeError. - throw webidl.errors.exception({ - header: `${instance.name}.formData`, - message: 'Could not parse content as FormData.' - }) + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) } + throw err } - } - return methods -} + 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 -function mixinBody (prototype) { - Object.assign(prototype.prototype, bodyMixinMethods(prototype)) -} + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } -/** - * @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) + addSignal(this, signal) + } - throwIfAborted(object[kState]) + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } - // 1. If object is unusable, then return a promise rejected - // with a TypeError. - if (bodyUnusable(object[kState].body)) { - throw new TypeError('Body is unusable') + this.abort = abort + this.context = context } - // 2. Let promise be a new promise. - const promise = createDeferredPromise() + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this - // 3. Let errorSteps given error be to reject promise with error. - const errorSteps = (error) => promise.reject(error) + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - // 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) + 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 + }) + } } } - // 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 + onData (chunk) { + const { res } = this + return res.push(chunk) } - // 6. Otherwise, fully read object’s body given successSteps, - // errorSteps, and object’s relevant global object. - await fullyReadBody(object[kState].body, successSteps, errorSteps) + onComplete (trailers) { + const { res } = this - // 7. Return promise. - return promise.promise -} + removeSignal(this) -// 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)) -} + util.parseHeaders(trailers, this.trailers) -/** - * @see https://encoding.spec.whatwg.org/#utf-8-decode - * @param {Buffer} buffer - */ -function utf8DecodeBytes (buffer) { - if (buffer.length === 0) { - return '' + res.push(null) } - // 1. Let buffer be the result of peeking three bytes from - // ioQueue, converted to a byte sequence. + onError (err) { + const { res, callback, body, opaque } = this - // 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) - } + removeSignal(this) - // 3. Process a queue with an instance of UTF-8’s - // decoder, ioQueue, output, and "replacement". - const output = textDecoder.decode(buffer) + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } - // 4. Return output. - return output -} + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } -/** - * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value - * @param {Uint8Array} bytes - */ -function parseJSONFromBytes (bytes) { - return JSON.parse(utf8DecodeBytes(bytes)) + if (body) { + this.body = null + util.destroy(body, err) + } + } } -/** - * @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' +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } - return parseMIMEType(contentType) + 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 = { - extractBody, - safelyExtractBody, - cloneBody, - mixinBody -} +module.exports = request +module.exports.RequestHandler = RequestHandler /***/ }), -/***/ 41037: +/***/ 5395: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(71267) +const { finished, PassThrough } = __nccwpck_require__(2781) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7474) +const { AsyncResource } = __nccwpck_require__(852) +const { addSignal, removeSignal } = __nccwpck_require__(7032) -const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] -const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } -const nullBodyStatus = [101, 204, 205, 304] + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts -const redirectStatus = [301, 302, 303, 307, 308] -const redirectStatusSet = new Set(redirectStatus) + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } -// 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' -] + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } -const badPortsSet = new Set(badPorts) + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } -// 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) + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } -const requestRedirect = ['follow', 'manual', 'error'] + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } -const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] -const safeMethodsSet = new Set(safeMethods) + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } -const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + 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 -const requestCredentials = ['omit', 'same-origin', 'include'] + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } -const requestCache = [ - 'default', - 'no-store', - 'reload', - 'no-cache', - 'force-cache', - 'only-if-cached' -] + addSignal(this, signal) + } -// 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' -] + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -// https://fetch.spec.whatwg.org/#enumdef-requestduplex -const requestDuplex = [ - 'half' -] + this.abort = abort + this.context = context + } -// http://fetch.spec.whatwg.org/#forbidden-method -const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] -const forbiddenMethodsSet = new Set(forbiddenMethods) + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this -const subresource = [ - 'audio', - 'audioworklet', - 'font', - 'image', - 'manifest', - 'paintworklet', - 'script', - 'style', - 'track', - 'video', - 'xslt', - '' -] -const subresourceSet = new Set(subresource) + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) -/** @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 - } -})() + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } -let channel + this.factory = null -/** @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') - } + let res - if (!channel) { - channel = new MessageChannel() - } - channel.port1.unref() - channel.port2.unref() - channel.port1.postMessage(value, options?.transfer) - return receiveMessageOnPort(channel.port2).message - } + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() -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 -} + 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') + } -/***/ 685: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this -const assert = __nccwpck_require__(39491) -const { atob } = __nccwpck_require__(14300) -const { isomorphicDecode } = __nccwpck_require__(52538) + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } -const encoder = new TextEncoder() + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) -/** - * @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 + if (err) { + abort() + } + }) + } -// 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:') + res.on('drain', resume) - // 2. Let input be the result of running the URL - // serializer on dataURL with exclude fragment - // set to true. - let input = URLSerializer(dataURL, true) + this.res = res - // 3. Remove the leading "data:" string from input. - input = input.slice(5) + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this - // 4. Let position point at the start of input. - const position = { position: 0 } + return res ? res.write(chunk) : true + } - // 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 - ) + onComplete (trailers) { + const { res } = this - // 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) + removeSignal(this) - // 7. If position is past the end of input, then - // return failure - if (position.position >= input.length) { - return 'failure' - } + if (!res) { + return + } - // 8. Advance position by 1. - position.position++ + this.trailers = util.parseHeaders(trailers) - // 9. Let encodedBody be the remainder of input. - const encodedBody = input.slice(mimeTypeLength + 1) + res.end() + } - // 10. Let body be the percent-decoding of encodedBody. - let body = stringPercentDecode(encodedBody) + onError (err) { + const { res, callback, opaque, body } = this - // 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) + removeSignal(this) - // 2. Set body to the forgiving-base64 decode of - // stringBody. - body = forgivingBase64(stringBody) + this.factory = null - // 3. If body is failure, then return failure. - if (body === 'failure') { - return 'failure' + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - // 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)+$/, '') + if (body) { + this.body = null + util.destroy(body, err) + } + } +} - // 6. Remove the last U+003B (;) code point from mimeType. - mimeType = mimeType.slice(0, -1) +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) + }) + }) } - // 12. If mimeType starts with U+003B (;), then prepend - // "text/plain" to mimeType. - if (mimeType.startsWith(';')) { - mimeType = 'text/plain' + mimeType + 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 })) } +} - // 13. Let mimeTypeRecord be the result of parsing - // mimeType. - let mimeTypeRecord = parseMIMEType(mimeType) +module.exports = stream - // 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 - } +/***/ 6923: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const href = url.href - const hashLength = url.hash.length +"use strict"; - 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 = '' +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8045) +const { AsyncResource } = __nccwpck_require__(852) +const util = __nccwpck_require__(3983) +const { addSignal, removeSignal } = __nccwpck_require__(7032) +const assert = __nccwpck_require__(9491) - // 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] +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } - // 2. Advance position by 1. - position.position++ - } + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - // 3. Return result. - return result -} + const { signal, opaque, responseHeaders } = opts -/** - * 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 (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - if (idx === -1) { - position.position = input.length - return input.slice(start) + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) } - position.position = idx - return input.slice(start, position.position) -} + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } -// 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) + this.abort = abort + this.context = null + } - // 2. Return the percent-decoding of bytes. - return percentDecode(bytes) -} + onHeaders () { + throw new SocketError('bad upgrade', null) + } -// 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 = [] + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this - // 2. For each byte byte in input: - for (let i = 0; i < input.length; i++) { - const byte = input[i] + assert.strictEqual(statusCode, 101) - // 1. If byte is not 0x25 (%), then append byte to output. - if (byte !== 0x25) { - output.push(byte) + removeSignal(this) - // 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) + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } - // 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) + onError (err) { + const { callback, opaque } = this - // 2. Append a byte whose value is bytePoint to output. - output.push(bytePoint) + removeSignal(this) - // 3. Skip the next two bytes in input. - i += 2 + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } } +} - // 3. Return output. - return Uint8Array.from(output) +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 })) + } } -// 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) +module.exports = upgrade - // 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' - } +/***/ 4059: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 5. If position is past the end of input, then return - // failure - if (position.position > input.length) { - return 'failure' - } +"use strict"; - // 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 - ) +module.exports.request = __nccwpck_require__(5448) +module.exports.stream = __nccwpck_require__(5395) +module.exports.pipeline = __nccwpck_require__(8752) +module.exports.upgrade = __nccwpck_require__(6923) +module.exports.connect = __nccwpck_require__(9744) - // 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() +/***/ 3858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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}` - } +"use strict"; +// Ported from https://github.com/nodejs/undici/pull/907 - // 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 - ) +const assert = __nccwpck_require__(9491) +const { Readable } = __nccwpck_require__(2781) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3983) - // 4. Set parameterName to parameterName, in ASCII - // lowercase. - parameterName = parameterName.toLowerCase() +let Blob - // 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 - } +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') - // 2. Advance position by 1. (This skips past U+003D (=).) - position.position++ - } +const noop = () => {} - // 6. If position is past the end of input, then break. - if (position.position > input.length) { - break - } +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) - // 7. Let parameterValue be null. - let parameterValue = null + this._readableState.dataEmitted = false - // 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) + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType - // 2. Collect a sequence of code points that are not - // U+003B (;) from input, given position. - collectASequenceOfCodePointsFast( - ';', - input, - position - ) + // 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 + } - // 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 - ) + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } - // 2. Remove any trailing HTTP whitespace from parameterValue. - parameterValue = removeHTTPWhitespace(parameterValue, false, true) + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } - // 3. If parameterValue is the empty string, then continue. - if (parameterValue.length === 0) { - continue - } + if (err) { + this[kAbort]() } - // 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) + 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) } - // 12. Return mimeType. - return mimeType -} + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) + } -// 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 + 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 + } - // 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(/=?=$/, '') + removeListener (ev, ...args) { + return this.off(ev, ...args) } - // 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' + 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) } - // 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' + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') } - const binary = atob(data) - const bytes = new Uint8Array(binary.length) + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } - for (let byte = 0; byte < binary.length; byte++) { - bytes[byte] = binary.charCodeAt(byte) + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') } - return bytes -} + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } -// 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 + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } - // 2. Let value be the empty string. - let value = '' + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } - // 3. Assert: the code point at position within input - // is U+0022 ("). - assert(input[position.position] === '"') + // 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] + } - // 4. Advance position by 1. - position.position++ + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal - // 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 - ) + 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) + } + } - // 2. If position is past the end of input, then break. - if (position.position >= input.length) { - break + if (this.closed) { + return Promise.resolve(null) } - // 3. Let quoteOrBackslash be the code point at position within - // input. - const quoteOrBackslash = input[position.position] + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop - // 4. Advance position by 1. - position.position++ + 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() + }) + } +} - // 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 - } +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} - // 2. Append the code point at position within input to value. - value += input[position.position] +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} - // 3. Advance position by 1. - position.position++ +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') + } - // 6. Otherwise: - } else { - // 1. Assert: quoteOrBackslash is U+0022 ("). - assert(quoteOrBackslash === '"') + assert(!stream[kConsume]) - // 2. Break. - break + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] } - } - // 6. If the extract-value flag is set, then return value. - if (extractValue) { - return value - } + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) - // 7. Return the code points from positionStart to position, - // inclusive, within input. - return input.slice(positionStart, position.position) + process.nextTick(consumeStart, stream[kConsume]) + }) } -/** - * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type - */ -function serializeAMimeType (mimeType) { - assert(mimeType !== 'failure') - const { parameters, essence } = mimeType +function consumeStart (consume) { + if (consume.body === null) { + return + } - // 1. Let serialization be the concatenation of mimeType’s - // type, U+002F (/), and mimeType’s subtype. - let serialization = essence + const { _readableState: state } = consume.stream - // 2. For each name → value of mimeType’s parameters: - for (let [name, value] of parameters.entries()) { - // 1. Append U+003B (;) to serialization. - serialization += ';' + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } - // 2. Append name to serialization. - serialization += name + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } - // 3. Append U+003D (=) to serialization. - serialization += '=' + consume.stream.resume() - // 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') + while (consume.stream.read() != null) { + // Loop + } +} - // 2. Prepend U+0022 (") to value. - value = '"' + value +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume - // 3. Append U+0022 (") to value. - value += '"' + 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__(4300).Blob) + } + resolve(new Blob(body, { type: stream[kContentType] })) } - // 5. Append value to serialization. - serialization += value + consumeFinish(consume) + } catch (err) { + stream.destroy(err) } - - // 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 === ' ' +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) } -/** - * @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++); +function consumeFinish (consume, err) { + if (consume.body === null) { + return } - if (trailing) { - for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + if (err) { + consume.reject(err) + } else { + consume.resolve() } - return str.slice(lead, trail + 1) + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null } -/** - * @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++); +/***/ 7474: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const assert = __nccwpck_require__(9491) +const { + ResponseStatusCodeError +} = __nccwpck_require__(8045) +const { toUSVString } = __nccwpck_require__(3983) + +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 (trailing) { - for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return } - return str.slice(lead, trail + 1) -} + 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 + } -module.exports = { - dataURLProcessor, - URLSerializer, - collectASequenceOfCodePoints, - collectASequenceOfCodePointsFast, - stringPercentDecode, - parseMIMEType, - collectAnHTTPQuotedString, - serializeAMimeType + 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 } + /***/ }), -/***/ 78511: +/***/ 7931: /***/ ((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() +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(3198) +const Pool = __nccwpck_require__(4634) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const { parseOrigin } = __nccwpck_require__(3983) +const kFactory = Symbol('factory') -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' }) +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') - fileBits = webidl.converters['sequence'](fileBits) - fileName = webidl.converters.USVString(fileName) - options = webidl.converters.FilePropertyBag(options) +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. - // Note: Blob handles this for us +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} - // 2. Let n be the fileName argument to the constructor. - const n = fileName +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 - // 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 + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 - // eslint-disable-next-line no-labels - substep: { - if (t) { - t = parseMIMEType(t) + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } - if (t === 'failure') { - t = '' - // eslint-disable-next-line no-labels - break substep - } + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } - t = serializeAMimeType(t).toLowerCase() - } + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory - // 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 + for (const upstream of upstreams) { + this.addUpstream(upstream) } + this._updateBalancedPoolStats() + } - // 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. + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - super(processBlobParts(fileBits, options), { type: t }) - this[kState] = { - name: n, - lastModified: d, - type: t + 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])) - get name () { - webidl.brandCheck(this, File) + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) - return this[kState].name - } + 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] + } - get lastModified () { - webidl.brandCheck(this, File) + this._updateBalancedPoolStats() - return this[kState].lastModified + return this } - get type () { - webidl.brandCheck(this, File) - - return this[kState].type + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) } -} -class FileLike { - constructor (blobLike, fileName, options = {}) { - // TODO: argument idl type check + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - // 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: + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. + if (pool) { + this[kRemoveClient](pool) + } - // 2. Let n be the fileName argument to the constructor. - const n = fileName + return this + } - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } - // 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 + [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() + } - // 2. Convert every character in t to ASCII lowercase. - // TODO + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) - // 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() + if (!dispatcher) { + return + } - // 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. + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - this[kState] = { - blobLike, - name: n, - type: t, - lastModified: d + if (allClientsBusy) { + return } - } - - stream (...args) { - webidl.brandCheck(this, FileLike) - return this[kState].blobLike.stream(...args) - } + let counter = 0 - arrayBuffer (...args) { - webidl.brandCheck(this, FileLike) + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) - return this[kState].blobLike.arrayBuffer(...args) - } + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] - slice (...args) { - webidl.brandCheck(this, FileLike) + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } - return this[kState].blobLike.slice(...args) - } + // 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] - text (...args) { - webidl.brandCheck(this, FileLike) + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } - return this[kState].blobLike.text(...args) + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] } +} - get size () { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.size - } +module.exports = BalancedPool - get type () { - webidl.brandCheck(this, FileLike) - return this[kState].blobLike.type - } +/***/ }), - get name () { - webidl.brandCheck(this, FileLike) +/***/ 6101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this[kState].name - } +"use strict"; - get lastModified () { - webidl.brandCheck(this, FileLike) - return this[kState].lastModified - } +const { kConstruct } = __nccwpck_require__(9174) +const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(2396) +const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3983) +const { kHeadersList } = __nccwpck_require__(2785) +const { webidl } = __nccwpck_require__(1744) +const { Response, cloneResponse } = __nccwpck_require__(7823) +const { Request } = __nccwpck_require__(8359) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { fetching } = __nccwpck_require__(4881) +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(2538) +const assert = __nccwpck_require__(9491) +const { getGlobalDispatcher } = __nccwpck_require__(1892) - get [Symbol.toStringTag] () { - return 'File' - } -} +/** + * @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 + */ -Object.defineProperties(File.prototype, { - [Symbol.toStringTag]: { - value: 'File', - configurable: true - }, - name: kEnumerableProperty, - lastModified: kEnumerableProperty -}) +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ -webidl.converters.Blob = webidl.interfaceConverter(Blob) +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList -webidl.converters.BlobPart = function (V, opts) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() } - if ( - ArrayBuffer.isView(V) || - types.isAnyArrayBuffer(V) - ) { - return webidl.converters.BufferSource(V, opts) - } + this.#relevantRequestResponseList = arguments[1] } - return webidl.converters.USVString(V, opts) -} + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.BlobPart -) + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) -// 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() + const p = await this.matchAll(request, options) - if (value !== 'native') { - value = 'transparent' - } + if (p.length === 0) { + return + } - return value - }, - defaultValue: 'transparent' + return p[0] } -]) -/** - * @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 = [] + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) - // 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 + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - // 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) - } + // 1. + let r = null - // 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) - ) + // 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] } - } 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' - } + // 5. + // 5.1 + const responses = [] - return s.replace(/\r?\n/g, nativeLineEnding) -} + // 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) -// 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' - ) - ) -} + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } -module.exports = { File, FileLike, isFileLike } + // 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' -/***/ 72015: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + responseList.push(responseObject) + } -"use strict"; + // 6. + return Object.freeze(responseList) + } + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) -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) + request = webidl.converters.RequestInfo(request) -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile + // 1. + const requests = [request] -// 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'] - }) - } + // 2. + const responseArrayPromise = this.addAll(requests) - this[kState] = [] + // 3. + return await responseArrayPromise } - append (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" - ) - } + requests = webidl.converters['sequence'](requests) - // 1. Let value be value if given; otherwise blobValue. + // 1. + const responsePromises = [] - 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. + const requestList = [] - // 2. Let entry be the result of creating an entry with - // name, value, and filename if given. - const entry = makeEntry(name, value, filename) + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } - // 3. Append entry to this’s entry list. - this[kState].push(entry) - } + // 3.1 + const r = request[kState] - delete (name) { - webidl.brandCheck(this, FormData) + // 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.' + }) + } + } - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] - name = webidl.converters.USVString(name) + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] - // 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) - } + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) + } - get (name) { - webidl.brandCheck(this, FormData) + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + // 5.5 + requestList.push(r) - name = webidl.converters.USVString(name) + // 5.6 + const responsePromise = createDeferredPromise() - // 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 - } + // 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. Return the value of the first entry whose name is name from - // this’s entry list. - return this[kState][idx].value - } + // 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' + })) - getAll (name) { - webidl.brandCheck(this, FormData) + for (const controller of fetchControllers) { + controller.abort() + } - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } - name = webidl.converters.USVString(name) + // 2. + responsePromise.resolve(response) + } + })) - // 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) - } + // 5.8 + responsePromises.push(responsePromise.promise) + } - has (name) { - webidl.brandCheck(this, FormData) + // 6. + const p = Promise.all(responsePromises) - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) + // 7. + const responses = await p - name = webidl.converters.USVString(name) + // 7.1 + const operations = [] - // 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 - } + // 7.2 + let index = 0 - set (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) + // 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 + } - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + operations.push(operation) // 7.3.5 - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" - ) + index++ // 7.3.6 } - // The set(name, value) and set(name, blobValue, filename) method steps - // are: + // 7.5 + const cacheJobPromise = createDeferredPromise() - // 1. Let value be value if given; otherwise blobValue. + // 7.6.1 + let errorData = null - 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 + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } - // 2. Let entry be the result of creating an entry with name, value, and - // filename if given. - const entry = makeEntry(name, value, filename) + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) - // 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) - } + // 7.7 + return cacheJobPromise.promise } - entries () { - webidl.brandCheck(this, FormData) + async put (request, response) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key+value' - ) - } + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response) - keys () { - webidl.brandCheck(this, FormData) + // 1. + let innerRequest = null - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key' - ) - } + // 2. + if (request instanceof Request) { + innerRequest = request[kState] + } else { // 3. + innerRequest = new Request(request)[kState] + } - values () { - webidl.brandCheck(this, FormData) + // 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' + }) + } - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'value' - ) - } + // 5. + const innerResponse = response[kState] - /** - * @param {(value: string, key: string, self: FormData) => void} callbackFn - * @param {unknown} thisArg - */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, FormData) + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) + } - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." - ) + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } } - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) + // 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' + }) } - } -} -FormData.prototype[Symbol.iterator] = FormData.prototype.entries + // 9. + const clonedResponse = cloneResponse(innerResponse) -Object.defineProperties(FormData.prototype, { - [Symbol.toStringTag]: { - value: 'FormData', - configurable: true - } -}) + // 10. + const bodyReadPromise = createDeferredPromise() -/** - * @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') + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream - // 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: + // 11.2 + const reader = stream.getReader() - // 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 }) + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) } - // 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 - } + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] - value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile - ? new File([value], filename, options) - : new FileLike(value, filename, options) + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. } - } - - // 4. Return an entry whose name is name and whose value is value. - return { name, value } -} - -module.exports = { FormData } - -/***/ }), + // 17. + operations.push(operation) -/***/ 71246: -/***/ ((module) => { + // 19. + const bytes = await bodyReadPromise.promise -"use strict"; + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } + // 19.1 + const cacheJobPromise = createDeferredPromise() -// In case of breaking changes, increase the version -// number to avoid conflicts. -const globalOrigin = Symbol.for('undici.globalOrigin.1') + // 19.2.1 + let errorData = null -function getGlobalOrigin () { - return globalThis[globalOrigin] -} + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } -function setGlobalOrigin (newOrigin) { - if (newOrigin === undefined) { - Object.defineProperty(globalThis, globalOrigin, { - value: undefined, - writable: true, - enumerable: false, - configurable: false + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } }) - return + return cacheJobPromise.promise } - const parsedURL = new URL(newOrigin) + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) - if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { - throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) - } + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - Object.defineProperty(globalThis, globalOrigin, { - value: parsedURL, - writable: true, - enumerable: false, - configurable: false - }) -} + /** + * @type {Request} + */ + let r = null -module.exports = { - getGlobalOrigin, - setGlobalOrigin -} + 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] + } -/***/ 10554: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** @type {CacheBatchOperation[]} */ + const operations = [] -"use strict"; -// https://github.com/Ethan-Arrowood/undici-fetch + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } + operations.push(operation) + const cacheJobPromise = createDeferredPromise() -const { kHeadersList, kConstruct } = __nccwpck_require__(72785) -const { kGuard } = __nccwpck_require__(15861) -const { kEnumerableProperty } = __nccwpck_require__(83983) -const { - makeIterator, - isValidHeaderName, - isValidHeaderValue -} = __nccwpck_require__(52538) -const util = __nccwpck_require__(73837) -const { webidl } = __nccwpck_require__(21744) -const assert = __nccwpck_require__(39491) + let errorData = null + let requestResponses -const kHeadersMap = Symbol('headers map') -const kHeadersSortedMap = Symbol('headers map sorted') + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } -/** - * @param {number} code - */ -function isHTTPWhiteSpaceCharCode (code) { - return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 -} + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) -/** - * @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 + return cacheJobPromise.promise + } - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + /** + * @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) - return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) -} + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) -function fill (headers, object) { - // To fill a Headers object headers with a given object object, run these steps: + // 1. + let r = null - // 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. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] - // 2. Append (header’s first item, header’s second item) to headers. - appendHeader(headers, header[0], header[1]) + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } } - } 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'] - }) - } -} + // 4. + const promise = createDeferredPromise() -/** - * @see https://fetch.spec.whatwg.org/#concept-headers-append - */ -function appendHeader (headers, name, value) { - // 1. Normalize value. - value = headerValueNormalize(value) + // 5. + // 5.1 + const requests = [] - // 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' - }) - } + // 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) - // 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 - } + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } - // 6. Otherwise, if headers’s guard is "response" and name is a - // forbidden response-header name, return. + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] - // 7. Append (name, value) to headers’s header list. - return headers[kHeadersList].append(name, value) + // 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 - // 8. If headers’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from headers -} + // 5.4.2.1 + requestList.push(requestObject) + } -class HeadersList { - /** @type {[string, string][]|null} */ - cookies = null + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) - 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 - } + return promise.promise } - // 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() + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList - return this[kHeadersMap].has(name) - } + // 2. + const backupCache = [...cache] - clear () { - this[kHeadersMap].clear() - this[kHeadersSortedMap] = null - this.cookies = null - } + // 3. + const addedItems = [] - // https://fetch.spec.whatwg.org/#concept-header-list-append - append (name, value) { - this[kHeadersSortedMap] = null + // 4.1 + const resultList = [] - // 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) + 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"' + }) + } - // 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 }) - } + // 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' + }) + } - if (lowercaseName === 'set-cookie') { - this.cookies ??= [] - this.cookies.push(value) - } - } + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } - // https://fetch.spec.whatwg.org/#concept-header-list-set - set (name, value) { - this[kHeadersSortedMap] = null - const lowercaseName = name.toLowerCase() + // 4.2.4 + let requestResponses - if (lowercaseName === 'set-cookie') { - this.cookies = [value] - } + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) - // 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 }) - } + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } - // https://fetch.spec.whatwg.org/#concept-header-list-delete - delete (name) { - this[kHeadersSortedMap] = null + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - name = name.toLowerCase() + // 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' + }) + } - if (name === 'set-cookie') { - this.cookies = null - } + // 4.2.6.2 + const r = operation.request - this[kHeadersMap].delete(name) - } + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } - // https://fetch.spec.whatwg.org/#concept-header-list-get - get (name) { - const value = this[kHeadersMap].get(name.toLowerCase()) + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } - // 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 - } + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } - * [Symbol.iterator] () { - // use the lowercased name - for (const [name, { value }] of this[kHeadersMap]) { - yield [name, value] - } - } + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) - get entries () { - const headers = {} + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) - if (this[kHeadersMap].size) { - for (const { name, value } of this[kHeadersMap].values()) { - headers[name] = value - } - } + // 4.2.6.7.1 + cache.splice(idx, 1) + } - return headers - } -} + // 4.2.6.8 + cache.push([operation.request, operation.response]) -// https://fetch.spec.whatwg.org/#headers-class -class Headers { - constructor (init = undefined) { - if (init === kConstruct) { - return - } - this[kHeadersList] = new HeadersList() + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } - // The new Headers(init) constructor steps are: + // 4.2.7 + resultList.push([operation.request, operation.response]) + } - // 1. Set this’s guard to "none". - this[kGuard] = 'none' + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 - // 2. If init is given, then fill this with init. - if (init !== undefined) { - init = webidl.converters.HeadersInit(init) - fill(this, init) + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e } } - // https://fetch.spec.whatwg.org/#dom-headers-append - append (name, value) { - webidl.brandCheck(this, Headers) + /** + * @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 = [] - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) + const storage = targetStorage ?? this.#relevantRequestResponseList - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } - return appendHeader(this, name, value) + return resultList } - // https://fetch.spec.whatwg.org/#dom-headers-delete - delete (name) { - webidl.brandCheck(this, Headers) + /** + * @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 + // } - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + const queryURL = new URL(requestQuery.url) - name = webidl.converters.ByteString(name) + const cachedURL = new URL(request.url) - // 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' - }) - } + if (options?.ignoreSearch) { + cachedURL.search = '' - // 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 + queryURL.search = '' } - // 6. If this’s header list does not contain name, then - // return. - if (!this[kHeadersList].contains(name)) { - return + if (!urlEquals(queryURL, cachedURL, true)) { + return false } - // 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) - } + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } - // https://fetch.spec.whatwg.org/#dom-headers-get - get (name) { - webidl.brandCheck(this, Headers) + const fieldValues = getFieldValues(response.headersList.get('vary')) - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } - name = webidl.converters.ByteString(name) + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) - // 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' - }) + // 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 + } } - // 2. Return the result of getting name from this’s header - // list. - return this[kHeadersList].get(name) + return true } +} - // https://fetch.spec.whatwg.org/#dom-headers-has - has (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) - name = webidl.converters.ByteString(name) +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 + } +] - // 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' - }) - } +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) - // 2. Return true if this’s header list contains name; - // otherwise false. - return this[kHeadersList].contains(name) +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString } +]) - // https://fetch.spec.whatwg.org/#dom-headers-set - set (name, value) { - webidl.brandCheck(this, Headers) +webidl.converters.Response = webidl.interfaceConverter(Response) - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) +module.exports = { + Cache +} - // 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 - } +/***/ 7907: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) - } +"use strict"; - // 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 { kConstruct } = __nccwpck_require__(9174) +const { Cache } = __nccwpck_require__(6101) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) - const list = this[kHeadersList].cookies +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map 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: + async match (request, options = {}) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.match' }) - // 1. Let value be the result of getting name from list. + request = webidl.converters.RequestInfo(request) + options = webidl.converters.MultiCacheQueryOptions(options) - // 2. Assert: value is non-null. - assert(value !== null) + // 1. + if (options.cacheName != null) { + // 1.1.1.1 + if (this.#caches.has(options.cacheName)) { + // 1.1.1.1.1 + const cacheList = this.#caches.get(options.cacheName) + const cache = new Cache(kConstruct, cacheList) - // 3. Append (name, value) to headers. - headers.push([name, value]) + return await cache.match(request, options) } - } + } else { // 2. + // 2.2 + for (const cacheList of this.#caches.values()) { + const cache = new Cache(kConstruct, cacheList) - this[kHeadersList][kHeadersSortedMap] = headers + // 2.2.1.2 + const response = await cache.match(request, options) - // 4. Return headers. - return headers + if (response !== undefined) { + return response + } + } + } } - keys () { - webidl.brandCheck(this, Headers) + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-has + * @param {string} cacheName + * @returns {Promise} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key') - } + cacheName = webidl.converters.DOMString(cacheName) - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key' - ) + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) } - values () { - webidl.brandCheck(this, Headers) + /** + * @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' }) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'value') - } + cacheName = webidl.converters.DOMString(cacheName) - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'value' - ) - } + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') - entries () { - webidl.brandCheck(this, Headers) + // 2.1.1 + const cache = this.#caches.get(cacheName) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key+value') + // 2.1.1.1 + return new Cache(kConstruct, cache) } - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key+value' - ) + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) } /** - * @param {(value: string, key: string, self: Headers) => void} callbackFn - * @param {unknown} thisArg + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." - ) - } + cacheName = webidl.converters.DOMString(cacheName) - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) - } + return this.#caches.delete(cacheName) } - [Symbol.for('nodejs.util.inspect.custom')] () { - webidl.brandCheck(this, Headers) + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) - return this[kHeadersList] + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] } } -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 }, +Object.defineProperties(CacheStorage.prototype, { [Symbol.toStringTag]: { - value: 'Headers', + value: 'CacheStorage', configurable: true }, - [util.inspect.custom]: { - enumerable: false - } + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty }) -webidl.converters.HeadersInit = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (V[Symbol.iterator]) { - return webidl.converters['sequence>'](V) - } +module.exports = { + CacheStorage +} - return webidl.converters['record'](V) - } - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] - }) -} +/***/ }), + +/***/ 9174: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + module.exports = { - fill, - Headers, - HeadersList + kConstruct: (__nccwpck_require__(2785).kConstruct) } /***/ }), -/***/ 74881: +/***/ 2396: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// https://github.com/Ethan-Arrowood/undici-fetch +const assert = __nccwpck_require__(9491) +const { URLSerializer } = __nccwpck_require__(685) +const { isValidHeaderName } = __nccwpck_require__(2538) -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'] +/** + * @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) -/** @type {import('buffer').resolveObjectURL} */ -let resolveObjectURL -let ReadableStream = globalThis.ReadableStream + const serializedB = URLSerializer(B, excludeFragment) -class Fetch extends EE { - constructor (dispatcher) { - super() + return serializedA === serializedB +} - 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) - } +/** + * @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) - terminate (reason) { - if (this.state !== 'ongoing') { - return + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue } - this.state = 'terminated' - this.connection?.destroy(reason) - this.emit('terminated', reason) + values.push(value) } - // https://fetch.spec.whatwg.org/#fetch-controller-abort - abort (error) { - if (this.state !== 'ongoing') { - return - } + return values +} - // 1. Set controller’s state to "aborted". - this.state = 'aborted' +module.exports = { + urlEquals, + fieldValues +} - // 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 +/***/ 3598: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.connection?.destroy(error) - this.emit('terminated', error) - } -} +"use strict"; +// @ts-check -// 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 +/* global WebAssembly */ - try { - requestObject = new Request(input, init) - } catch (e) { - p.reject(e) - return p.promise +const assert = __nccwpck_require__(9491) +const net = __nccwpck_require__(1808) +const http = __nccwpck_require__(3685) +const { pipeline } = __nccwpck_require__(2781) +const util = __nccwpck_require__(3983) +const timers = __nccwpck_require__(9459) +const Request = __nccwpck_require__(2905) +const DispatcherBase = __nccwpck_require__(4839) +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) +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__(2785) + +/** @type {import('http2')} */ +let http2 +try { + http2 = __nccwpck_require__(5158) +} 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 - // 3. Let request be requestObject’s request. - const request = requestObject[kState] +// Experimental +let h2ExperimentalWarned = false - // 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) +const FastBuffer = Buffer[Symbol.species] - // 2. Return p. - return p.promise - } +const kClosedResolve = Symbol('kClosedResolve') - // 5. Let globalObject be request’s client’s global object. - const globalObject = request.client.globalObject +const channels = {} - // 6. If globalObject is a ServiceWorkerGlobalScope object, then set - // request’s service-workers mode to "none". - if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { - request.serviceWorkers = 'none' - } +try { + const diagnosticsChannel = __nccwpck_require__(7643) + 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') + } - // 7. Let responseObject be null. - let responseObject = null + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } - // 8. Let relevantRealm be this’s relevant Realm. - const relevantRealm = null + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } - // 9. Let locallyAborted be false. - let locallyAborted = false + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } - // 10. Let controller be null. - let controller = null + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } - // 11. Add the following abort steps to requestObject’s signal: - addAbortListener( - requestObject.signal, - () => { - // 1. Set locallyAborted to true. - locallyAborted = true + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } - // 2. Assert: controller is non-null. - assert(controller != null) + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } - // 3. Abort controller with requestObject’s signal’s abort reason. - controller.abort(requestObject.signal.reason) + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } - // 4. Abort the fetch() call with p, request, responseObject, - // and requestObject’s signal’s abort reason. - abortFetch(p, request, responseObject, requestObject.signal.reason) + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') } - ) - // 12. Let handleFetchDone given response response be to finalize and - // report timing with response, globalObject, and "fetch". - const handleFetchDone = (response) => - finalizeAndReportTiming(response, 'fetch') + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - // 13. Set controller to the result of calling fetch given request, - // with processResponseEndOfBody set to handleFetchDone, and processResponse - // given response being these substeps: + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } - const processResponse = (response) => { - // 1. If locallyAborted is true, terminate these substeps. - if (locallyAborted) { - return Promise.resolve() + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') } - // 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. + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } - // 2. Abort the fetch() call with p, request, responseObject, and - // deserializedError. + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } - abortFetch(p, request, responseObject, controller.serializedAbortReason) - return Promise.resolve() + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') } - // 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() + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') } - // 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 + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } - // 5. Resolve p with responseObject. - p.resolve(responseObject) - } + 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' - controller = fetching({ - request, - processResponseEndOfBody: handleFetchDone, - processResponse, - dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici - }) + // 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}` : ''}` - // 14. Return p. - return p.promise -} + // 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). -// 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 + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 } - // 2. If response’s URL list is null or empty, then return. - if (!response.urlList?.length) { - return + get pipelining () { + return this[kPipelining] } - // 3. Let originalURL be response’s URL list[0]. - const originalURL = response.urlList[0] + set pipelining (value) { + this[kPipelining] = value + resume(this, true) + } - // 4. Let timingInfo be response’s timing info. - let timingInfo = response.timingInfo + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } - // 5. Let cacheState be response’s cache state. - let cacheState = response.cacheState + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } - // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. - if (!urlIsHttpHttpsScheme(originalURL)) { - return + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] } - // 7. If timingInfo is null, then return. - if (timingInfo === null) { - return + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed } - // 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 - }) + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) + } - // 2. Set cacheState to the empty string. - cacheState = '' + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) } - // 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() + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin - // 10. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler) - // 11. Mark resource timing for timingInfo, originalURL, initiatorType, - // global, and cacheState. - markResourceTiming( - timingInfo, - originalURL, - initiatorType, - globalThis, - cacheState - ) -} + 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) + } -// 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) - } -} + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } -// 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') + return this[kNeedDrain] < 2 } - // 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 + 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 } - throw err }) } - // 3. If responseObject is null, then return. - if (responseObject == null) { - return - } + 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) + } - // 4. Let response be responseObject’s response. - const response = responseObject[kState] + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } - // 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 + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null } - throw err + + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) + } + + resume(this) }) } } -// 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 +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - // 2. Let crossOriginIsolatedCapability be false. - let crossOriginIsolatedCapability = false + this[kSocket][kError] = err - // 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 + onError(this[kClient], err) +} - // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin - // isolated capability. - crossOriginIsolatedCapability = - request.client.crossOriginIsolatedCapability +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) } +} - // 4. If useParallelQueue is true, then set taskDestination to the result of - // starting a new parallel queue. - // TODO +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) +} - // 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 - }) +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 - // 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 - } + if (client.destroyed) { + assert(this[kPending] === 0) - // 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) + // 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 - // 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' + errorRequest(client, request, err) } - // 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 + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', + client[kUrl], + [client], + err + ) + + resume(client) +} + +const constants = __nccwpck_require__(953) +const createRedirectInterceptor = __nccwpck_require__(8861) +const EMPTY_BUF = Buffer.alloc(0) + +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(1145) : undefined + + let mod + try { + mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(5627), '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__(1145), 'base64')) } - // 10. If all of the following conditions are true: - // TODO + 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 + } - // 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() + /* eslint-enable camelcase */ } - } - - // 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 +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() - // 3. Append `Accept`/value to request’s header list. - request.headersList.append('accept', value) - } +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null - // 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', '*') - } +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 - // 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 - } +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) - // 15. If request is a subresource request, then: - if (subresourceSet.has(request.destination)) { - // TODO - } + 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) - // 16. Run main fetch given fetchParams. - mainFetch(fetchParams) - .catch(err => { - fetchParams.controller.terminate(err) - }) + this.bytesRead = 0 - // 17. Return fetchParam's controller - return fetchParams.controller -} + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } -// 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 + 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() + } + } + } - // 2. Let response be null. - let response = null + resume () { + if (this.socket.destroyed || !this.paused) { + return + } - // 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') - } + assert(this.ptr != null) + assert(currentParser == null) - // 4. Run report Content Security Policy violations for request. - // TODO + this.llhttp.llhttp_resume(this.ptr) - // 5. Upgrade request to a potentially trustworthy URL, if appropriate. - tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } - // 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') + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() } - // 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 + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } } - // 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) - } + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) - // 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 + const { socket, llhttp } = this - // 10. If recursive is false, then run the remaining steps in parallel. - // TODO + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } - // 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) + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) - 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' + // 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 - // 2. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) + 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 } - // request’s mode is "same-origin" - if (request.mode === 'same-origin') { - // 1. Return a network error. - return makeNetworkError('request mode cannot be "same-origin"') - } + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr - // 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' - ) + 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() + + ')' } - - // 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) + throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) } + } catch (err) { + util.destroy(socket, err) + } + } - // 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') - } + destroy () { + assert(this.ptr != null) + assert(currentParser == null) - // - 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 + this.llhttp.llhttp_free(this.ptr) + this.ptr = null - // Otherwise - // 1. Set request’s response tainting to "cors". - request.responseTainting = 'cors' + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null - // 2. Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) - })() + this.paused = false } - // 12. If recursive is true, then return response. - if (recursive) { - return response + onStatus (buf) { + this.statusText = buf.toString() } - // 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 + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 } - // 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) + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 } } - // 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 + onHeaderField (buf) { + const len = this.headers.length - // 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) - } + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } - // 16. If request’s timing allow failed flag is unset, then set - // internalResponse’s timing allow passed flag. - if (!request.timingAllowFailed) { - response.timingAllowPassed = true + this.trackHeader(buf.length) } - // 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 + onHeaderValue (buf) { + let len = this.headers.length - // 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() - } + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } - // 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 - } + 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() + } - // 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)) + this.trackHeader(buf.length) + } - // 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 + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) } + } - // 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] + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this - // 3. Run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) - } + assert(upgrade) - // 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) - } -} + const request = client[kQueue][client[kRunningIdx]] + assert(request) -// 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)) - } + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') - // 2. Let request be fetchParams’s request. - const { request } = fetchParams + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null - const { protocol: scheme } = requestCurrentURL(request) + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - // 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. + socket.unshift(head) - // Otherwise, return a network error. - return Promise.resolve(makeNetworkError('about scheme is not supported')) - } - case 'blob:': { - if (!resolveObjectURL) { - resolveObjectURL = (__nccwpck_require__(14300).resolveObjectURL) - } + socket[kParser].destroy() + socket[kParser] = null - // 1. Let blobURLEntry be request’s current URL’s blob URL entry. - const blobURLEntry = requestCurrentURL(request) + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) - // 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.')) - } + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) - const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } - // 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')) - } + resume(client) + } - // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. - const bodyWithType = safelyExtractBody(blobURLEntryObject) + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this - // 4. Let body be bodyWithType’s body. - const body = bodyWithType[0] + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } - // 5. Let length be body’s length, serialized and isomorphic encoded. - const length = isomorphicEncode(`${body.length}`) + const request = client[kQueue][client[kRunningIdx]] - // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. - const type = bodyWithType[1] ?? '' + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -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 }] - ] - }) + assert(!this.upgrade) + assert(this.statusCode < 200) - response.body = body + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } - return Promise.resolve(response) + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 } - 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')) - } + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) - // 3. Let mimeType be dataURLStruct’s MIME type, serialized. - const mimeType = serializeAMimeType(dataURLStruct.mimeType) + 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') + ) - // 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...')) + 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() + } } - case 'http:': - case 'https:': { - // Return the result of running HTTP fetch given fetchParams. - return httpFetch(fetchParams) - .catch((err) => makeNetworkError(err)) + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 } - default: { - return Promise.resolve(makeNetworkError('unknown scheme')) + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 } - } -} -// https://fetch.spec.whatwg.org/#finalize-response -function finalizeResponse (fetchParams, response) { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - // 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)) - } -} + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null -// 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]] + 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 + } - // 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 - }) - } + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false - // 2. Let processResponseEndOfBody be the following steps: - const processResponseEndOfBody = () => { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true + if (request.aborted) { + return -1 + } - // 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)) + if (request.method === 'HEAD') { + return 1 } - } - // 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)) - } + if (statusCode < 200) { + return 1 + } - // 4. If response’s body is null, then run processResponseEndOfBody. - if (response.body == null) { - processResponseEndOfBody() - } else { - // 5. Otherwise: + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } - // 1. Let transformStream be a new a TransformStream. + return pause ? constants.ERROR.PAUSED : 0 + } - // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, - // enqueues chunk in transformStream. - const identityTransformAlgorithm = (chunk, controller) => { - controller.enqueue(chunk) + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 } - // 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 + 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() } - }) + } - // 4. Set response’s body to the result of piping response’s body through transformStream. - response.body = { stream: response.body.stream.pipeThrough(transformStream) } - } + assert(statusCode >= 200) - // 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) + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } - // 2. Let processBodyError be this step: run fetchParams’s process - // response consume body given response and failure. - const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + this.bytesRead += buf.length - // 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) + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED } - 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 + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this - // 3. Let actualResponse be null. - let actualResponse = null + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } - // 4. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo + if (upgrade) { + return + } - // 5. If request’s service-workers mode is "all", then: - if (request.serviceWorkers === 'all') { - // TODO - } + const request = client[kQueue][client[kRunningIdx]] + assert(request) - // 6. If response is null, then: - if (response === null) { - // 1. If makeCORSPreflight is true and one of these conditions is true: - // TODO + assert(statusCode >= 100) - // 2. If request’s redirect mode is "follow", then set request’s - // service-workers mode to "none". - if (request.redirect === 'follow') { - request.serviceWorkers = 'none' - } + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' - // 3. Set response and actualResponse to the result of running - // HTTP-network-or-cache fetch given fetchParams. - actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - // 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') + if (statusCode < 200) { + return } - // 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 + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 } - } - // 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') - } + request.onComplete(headers) - // 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() - } + client[kQueue][client[kRunningIdx]++] = null - // 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) + 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 { - assert(false) + resume(client) } } - - // 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 - ) +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser - // 4. If locationURL is null, then return response. - if (locationURL == null) { - return response + /* 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()) } - } catch (err) { - // 5. If locationURL is failure, then return a network error. - return Promise.resolve(makeNetworkError(err)) + } 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')) } +} - // 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')) +function onSocketReadable () { + const { [kParser]: parser } = this + if (parser) { + parser.readMore() } +} - // 7. If request’s redirect count is 20, then return a network error. - if (request.redirectCount === 20) { - return Promise.resolve(makeNetworkError('redirect count exceeded')) - } +function onSocketError (err) { + const { [kClient]: client, [kParser]: parser } = this - // 8. Increase request’s redirect count by 1. - request.redirectCount += 1 + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - // 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"')) + 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 + } } - // 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"' - )) - } + this[kError] = err - // 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()) - } + onError(this[kClient], err) +} - // 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` +function onError (client, err) { if ( - ([301, 302].includes(actualResponse.status) && request.method === 'POST') || - (actualResponse.status === 303 && - !GET_OR_HEAD.includes(request.method)) + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' ) { - // then: - // 1. Set request’s method to `GET` and request’s body to null. - request.method = 'GET' - request.body = null + // 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) + } +} - // 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) +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 } } - // 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') + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} - // https://fetch.spec.whatwg.org/#authentication-entries - request.headersList.delete('proxy-authorization', true) +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this - // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. - request.headersList.delete('cookie') - request.headersList.delete('host') - } + 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() + } - // 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] + this[kParser].destroy() + this[kParser] = null } - // 15. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) - // 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) + client[kSocket] = null - // 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 + 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) } - // 18. Append locationURL to request’s URL list. - request.urlList.push(locationURL) + client[kPendingIdx] = client[kRunningIdx] - // 19. Invoke set request’s referrer policy on redirect on request and - // actualResponse. - setRequestReferrerPolicyOnRedirect(request, actualResponse) + assert(client[kRunning] === 0) - // 20. Return the result of running main fetch given fetchParams and true. - return mainFetch(fetchParams, true) + client.emit('disconnect', client[kUrl], [client], err) + + resume(client) } -// 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 +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) - // 2. Let httpFetchParams be null. - let httpFetchParams = null + let { host, hostname, protocol, port } = client[kUrl] - // 3. Let httpRequest be null. - let httpRequest = null + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') - // 4. Let response be null. - let response = null + assert(idx !== -1) + const ip = hostname.substring(1, idx) - // 5. Let storedResponse be null. - // TODO: cache + assert(net.isIP(ip)) + hostname = ip + } - // 6. Let httpCache be null. - const httpCache = null + client[kConnecting] = true - // 7. Let the revalidatingFlag be unset. - const revalidatingFlag = false + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } - // 8. Run these steps, but abort when the ongoing fetch is terminated: + 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) + } + }) + }) - // 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: + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return + } - // 1. Set httpRequest to a clone of request. - httpRequest = makeRequest(request) + client[kConnecting] = false - // 2. Set httpFetchParams to a copy of fetchParams. - httpFetchParams = { ...fetchParams } + assert(socket) - // 3. Set httpFetchParams’s request to httpRequest. - httpFetchParams.request = httpRequest - } + 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' + }) + } - // 3. Let includeCredentials be true if one of - const includeCredentials = - request.credentials === 'include' || - (request.credentials === 'same-origin' && - request.responseTainting === 'basic') + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) - // 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 + 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() - // 5. Let contentLengthHeaderValue be null. - let contentLengthHeaderValue = null + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + } else { + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = 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' - } + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) + } - // 7. If contentLength is non-null, then set contentLengthHeaderValue to - // contentLength, serialized and isomorphic encoded. - if (contentLength != null) { - contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) - } + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null - // 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) - } + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) - // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, - // contentLengthHeaderValue) to httpRequest’s header list. + client[kSocket] = socket - // 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. - } + 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 + } - // 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)) - } + client[kConnecting] = false - // 12. Append a request `Origin` header for httpRequest. - appendRequestOriginHeader(httpRequest) + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } - // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] - appendFetchMetadata(httpRequest) + 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) + } - // 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') + client.emit('connectionError', client[kUrl], [client], err) } - // 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' + resume(client) +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return } - // 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') + 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 } +} - // 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') +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return } - // 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') + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return } - } - // 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') - } + const socket = client[kSocket] - // 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') + 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) + } + } } - } - httpRequest.headersList.delete('host') + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) + } + continue + } - // 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 - } + if (client[kPending] === 0) { + return + } - // 21. If there’s a proxy-authentication entry, use it as appropriate. - // TODO: proxy-authentication + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } - // 22. Set httpCache to the result of determining the HTTP cache - // partition, given httpRequest. - // TODO: cache + const request = client[kQueue][client[kPendingIdx]] - // 23. If httpCache is null, then set httpRequest’s cache mode to - // "no-store". - if (httpCache == null) { - httpRequest.cache = 'no-store' - } + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } - // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", - // then: - if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { - // TODO: cache - } + client[kServerName] = request.servername - // 9. If aborted, then return the appropriate network error for fetchParams. - // TODO + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return + } + } - // 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') + if (client[kConnecting]) { + return } - // 2. Let forwardResponse be the result of running HTTP-network fetch - // given httpFetchParams, includeCredentials, and isNewConnectionFetch. - const forwardResponse = await httpNetworkFetch( - httpFetchParams, - includeCredentials, - isNewConnectionFetch - ) + if (!socket && !client[kHTTP2Session]) { + connect(client) + return + } - // 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 + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return } - // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, - // then: - if (revalidatingFlag && forwardResponse.status === 304) { - // TODO: cache + 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 } - // 5. If response is null, then: - if (response == null) { - // 1. Set response to forwardResponse. - response = forwardResponse + 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. - // 2. Store httpRequest and forwardResponse in httpCache, as per the - // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] - // TODO: cache + // 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) } } +} - // 11. Set response’s URL list to a clone of httpRequest’s URL list. - response.urlList = [...httpRequest.urlList] +// 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' +} - // 12. If httpRequest’s header list contains `Range`, then set response’s - // range-requested flag. - if (httpRequest.headersList.contains('range')) { - response.rangeRequested = true +function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request) + return } - // 13. Set response’s request-includes-credentials to includeCredentials. - response.requestIncludesCredentials = includeCredentials + const { body, method, path, host, upgrade, headers, blocking, reset } = request - // 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 + // 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 - // 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() - } + // 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. - // 2. ??? + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) - } + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } - // 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? + const bodyLength = util.bodyLength(body) - // 5. Set response to the result of running HTTP-network-or-cache fetch given - // fetchParams. - // TODO - return makeNetworkError('proxy authentication required') + let contentLength = bodyLength + + if (contentLength === null) { + contentLength = request.contentLength } - // 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: + 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. - // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) + 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 } - // 2. Set response to the result of running HTTP-network-or-cache - // fetch given fetchParams, isAuthenticationFetch, and true. + process.emitWarning(new RequestContentLengthMismatchError()) + } - // 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() + const socket = client[kSocket] - response = await httpNetworkOrCacheFetch( - fetchParams, - isAuthenticationFetch, - true - ) - } + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } - // 17. If isAuthenticationFetch is true, then create an authentication entry - if (isAuthenticationFetch) { - // TODO + errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) } - // 18. Return response. - return response -} + if (request.aborted) { + return false + } -// https://fetch.spec.whatwg.org/#http-network-fetch -async function httpNetworkFetch ( - fetchParams, - includeCredentials = false, - forceNewConnection = false -) { - assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + 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. - 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')) - } - } + socket[kReset] = true } - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let response be null. - let response = null + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. - // 3. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo + socket[kReset] = true + } - // 4. Let httpCache be the result of determining the HTTP cache partition, - // given request. - // TODO: cache - const httpCache = null + if (reset != null) { + socket[kReset] = reset + } - // 5. If httpCache is null, then set request’s cache mode to "no-store". - if (httpCache == null) { - request.cache = 'no-store' + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true } - // 6. Let networkPartitionKey be the result of determining the network - // partition key given request. - // TODO + if (blocking) { + socket[kBlocking] = true + } - // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise - // "no". - const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + let header = `${method} ${path} HTTP/1.1\r\n` - // 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 + if (typeof host === 'string') { + header += `host: ${host}\r\n` } else { - // Let connection be the result of obtaining a connection, given - // networkPartitionKey, request’s current URL’s origin, - // includeCredentials, and forceNewConnection. - // TODO + header += client[kHostHeader] } - // 9. Run these steps, but abort when the ongoing fetch is terminated: + 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' + } - // 1. If connection is failure, then return a network error. + if (headers) { + header += headers + } - // 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. + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } - // 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. + /* 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') - // 4. Set timingInfo’s final network-request start time to the coarsened - // shared current time given fetchParams’s cross-origin isolated - // capability. + 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) + } - // 5. Set response to the result of making an HTTP request over connection - // using request with the following caveats: + return true +} - // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] - // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request - // - 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. + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders - // - 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). + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } - // - Wait until all the headers are transmitted. + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } - // - 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. + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) + } - // - 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 (request.aborted) { + return false + } - // - If the HTTP request results in a TLS client certificate dialog, then: + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + const h2State = client[kHTTP2SessionState] - // 1. If request’s window is an environment settings object, make the - // dialog available in request’s window. + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method - // 2. Otherwise, return a network error. + 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 }) - // 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: + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) + } - // 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 - } + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) - // 2. Run this step in parallel: transmit bytes. - yield bytes + return true + } - // 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) - } + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT - // 2. Let processEndOfBody be these steps: - const processEndOfBody = () => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' - // 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() - } - } + // 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 - // 3. Let processBodyError given e be these steps: - const processBodyError = (e) => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } + // 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. - // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. - if (e.name === 'AbortError') { - fetchParams.controller.abort() - } else { - fetchParams.controller.terminate(e) - } - } + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - // 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) - } - })() + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) } - try { - // socket is only provided for websockets - const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + let contentLength = util.bodyLength(body) - if (socket) { - response = makeResponse({ status, statusText, headersList, socket }) - } else { - const iterator = body[Symbol.asyncIterator]() - fetchParams.controller.next = () => iterator.next() + if (contentLength == null) { + contentLength = request.contentLength + } - 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() + 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. - // 2. Return the appropriate network error for fetchParams. - return makeAppropriateNetworkError(fetchParams, err) + 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 } - return makeNetworkError(err) + process.emitWarning(new RequestContentLengthMismatchError()) } - // 11. Let pullAlgorithm be an action that resumes the ongoing fetch - // if it is suspended. - const pullAlgorithm = () => { - fetchParams.controller.resume() + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` } - // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s - // controller with reason, given reason. - const cancelAlgorithm = (reason) => { - fetchParams.controller.abort(reason) + 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() } - // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by - // the user agent. - // TODO + // Increment counter as we have new several streams open + ++h2State.openStreams - // 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 + 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() + } + }) - // 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) - } + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) { + session.unref() + } + }) - 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 - } + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) } - ) + }) - // 17. Run these steps, but abort when the ongoing fetch is terminated: + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) - // 1. Set response’s body to a new body whose stream is stream. - response.body = { stream } + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) - // 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 + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) - // 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 + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) - // 18. If aborted, then: - // TODO + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) - // 19. Run these steps in parallel: + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) - // 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... + return true - // 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() + 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) + } + } +} - if (isAborted(fetchParams)) { - break - } +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') - bytes = done ? undefined : value - } catch (err) { - if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { - // zlib doesn't like empty streams. - bytes = undefined + 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 { - 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 + request.onRequestSent() } } + ) - 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) + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) - return - } + function onPipeData (chunk) { + request.onBodySent(chunk) + } - // 5. Increase timingInfo’s decoded body size by bytes’s length. - timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + return + } - // 6. If bytes is failure, then terminate fetchParams’s controller. - if (isFailure) { - fetchParams.controller.terminate(bytes) - return - } + let finished = false - // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes - // into stream. - fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - // 8. If stream is errored, then terminate the ongoing fetch. - if (isErrored(stream)) { - fetchParams.controller.terminate() - return - } + const onData = function (chunk) { + if (finished) { + return + } - // 9. If stream doesn’t need more data ask the user agent to suspend - // the ongoing fetch. - if (!fetchParams.controller.controller.desiredSize) { - return + try { + if (!writer.write(chunk) && this.pause) { + this.pause() } + } catch (err) { + util.destroy(this, err) } } - - // 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 - })) - } + const onDrain = function () { + if (finished) { + return } - // 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() + 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 + } - // 20. Return response. - return response + finished = true - async function dispatch ({ body }) { - const url = requestCurrentURL(request) - /** @type {import('../..').Agent} */ - const agent = fetchParams.controller.dispatcher + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) - 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, + socket + .off('drain', onDrain) + .off('error', onFinished) - onConnect (abort) { - // TODO (fix): Do we need connection here? - const { connection } = fetchParams.controller + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) - if (connection.destroyed) { - abort(new DOMException('The operation was aborted.', 'AbortError')) - } else { - fetchParams.controller.on('terminated', abort) - this.abort = connection.abort = abort - } - }, + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } - onHeaders (status, headersList, resume, statusText) { - if (status < 200) { - return - } + writer.destroy(err) - let codings = [] - let location = '' + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } - const headers = new Headers() + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) - // 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 - } + if (body.resume) { + body.resume() + } - 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 - } + socket + .on('drain', onDrain) + .on('error', onFinished) +} - headers[kHeadersList].append(key, val) - } - } +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') - this.body = new Readable({ read: resume }) + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } - const decoders = [] + const buffer = Buffer.from(await body.arrayBuffer()) - const willFollow = request.redirect === 'follow' && - location && - redirectStatusSet.has(status) + 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() + } - // 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 - } - } - } + request.onBodySent(buffer) + request.onRequestSent() - resolve({ - status, - statusText, - headersList: headers[kHeadersList], - body: decoders.length - ? pipeline(this.body, ...decoders, () => { }) - : this.body.on('error', () => {}) - }) + if (!expectsPayload) { + socket[kReset] = true + } - return true - }, + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) + } +} - onData (chunk) { - if (fetchParams.controller.dump) { - return - } +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') - // 1. If one or more bytes have been transmitted from response’s - // message body, then: + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } - // 1. Let bytes be the transmitted bytes. - const bytes = chunk + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) - // 2. Let codings be the result of extracting header list values - // given `Content-Encoding` and response’s header list. - // See pullAlgorithm. + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) - // 3. Increase timingInfo’s encoded body size by bytes’s length. - timingInfo.encodedBodySize += bytes.byteLength + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) - // 4. See pullAlgorithm... + 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] + } - return this.body.push(bytes) - }, + 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) + } - onComplete () { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } + 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] + } - fetchParams.controller.ended = true + if (!writer.write(chunk)) { + await waitForDrain() + } + } - this.body.push(null) - }, + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} - onError (error) { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } +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 - this.body?.destroy(error) + socket[kWriting] = true + } - fetchParams.controller.terminate(error) + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this - reject(error) - }, + if (socket[kError]) { + throw socket[kError] + } - onUpgrade (status, headersList, socket) { - if (status !== 101) { - return - } + if (socket.destroyed) { + return false + } - const headers = new Headers() + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } - headers[kHeadersList].append(key, val) - } + process.emitWarning(new RequestContentLengthMismatchError()) + } - resolve({ - status, - statusText: STATUS_CODES[status], - headersList: headers[kHeadersList], - socket - }) + socket.cork() - return true - } + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true } - )) - } -} -module.exports = { - fetch, - Fetch, - fetching, - finalizeAndReportTiming -} + 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 -/***/ 48359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const ret = socket.write(chunk) -"use strict"; -/* globals AbortController */ + 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() + } + } + } -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) + return ret + } -let TransformStream = globalThis.TransformStream + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() -const kAbortController = Symbol('abortController') + socket[kWriting] = false -const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { - signal.removeEventListener('abort', abort) -}) + if (socket[kError]) { + throw socket[kError] + } -// https://fetch.spec.whatwg.org/#request-class -class Request { - // https://fetch.spec.whatwg.org/#dom-request - constructor (input, init = {}) { - if (input === kConstruct) { + if (socket.destroyed) { return } - webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) - - input = webidl.converters.RequestInfo(input) - init = webidl.converters.RequestInit(init) + 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. - // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object - this[kRealm] = { - settingsObject: { - baseUrl: getGlobalOrigin(), - get origin () { - return this.baseUrl?.origin - }, - policyContainer: makePolicyContainer() + 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') } - // 1. Let request be null. - let request = null + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } - // 2. Let fallbackMode be null. - let fallbackMode = null + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } - // 3. Let baseURL be this’s relevant settings object’s API base URL. - const baseUrl = this[kRealm].settingsObject.baseUrl + resume(client) + } - // 4. Let signal be null. - let signal = null + destroy (err) { + const { socket, client } = this - // 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 }) - } + socket[kWriting] = false - // 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 - ) - } + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) + } + } +} - // 4. Set request to a new request whose URL is parsedURL. - request = makeRequest({ urlList: [parsedURL] }) +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} - // 5. Set fallbackMode to "cors". - fallbackMode = 'cors' - } else { - // 6. Otherwise: +module.exports = Client - // 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] - } +/***/ 6436: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 7. Let origin be this’s relevant settings object’s origin. - const origin = this[kRealm].settingsObject.origin +"use strict"; - // 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 - } +/* istanbul ignore file: only for Node 12 */ - // 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`) - } +const { kConnected, kSize } = __nccwpck_require__(2785) - // 11. If init["window"] exists, then set window to "no-window". - if ('window' in init) { - window = 'no-window' - } +class CompatWeakRef { + constructor (value) { + this.value = value + } - // 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] - }) + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} - const initHasKey = Object.keys(init).length !== 0 +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer + } - // 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' - } + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } + } +} - // 2. Unset request’s reload-navigation flag. - request.reloadNavigation = false +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 + } +} - // 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' +/***/ 663: +/***/ ((module) => { - // 6. Set request’s referrer policy to the empty string. - request.referrerPolicy = '' +"use strict"; - // 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] - } +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 - // 14. If init["referrer"] exists, then: - if (init.referrer !== undefined) { - // 1. Let referrer be init["referrer"]. - const referrer = init.referrer +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 - // 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 }) - } +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} - // 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 - } +/***/ 1724: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 17. If mode is "navigate", then throw a TypeError. - if (mode === 'navigate') { - throw webidl.errors.exception({ - header: 'Request constructor', - message: 'invalid request mode navigate.' - }) - } +"use strict"; - // 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 - } +const { parseSetCookie } = __nccwpck_require__(4408) +const { stringify } = __nccwpck_require__(3121) +const { webidl } = __nccwpck_require__(1744) +const { Headers } = __nccwpck_require__(554) - // 18. If init["cache"] exists, then set request’s cache mode to it. - if (init.cache !== undefined) { - request.cache = init.cache - } +/** + * @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 + */ - // 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" - ) - } +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) - // 22. If init["redirect"] exists, then set request’s redirect mode to it. - if (init.redirect !== undefined) { - request.redirect = init.redirect - } + webidl.brandCheck(headers, Headers, { strict: false }) - // 23. If init["integrity"] exists, then set request’s integrity metadata to it. - if (init.integrity != null) { - request.integrity = String(init.integrity) - } + const cookie = headers.get('cookie') + const out = {} - // 24. If init["keepalive"] exists, then set request’s keepalive to it. - if (init.keepalive !== undefined) { - request.keepalive = Boolean(init.keepalive) - } + if (!cookie) { + return out + } - // 25. If init["method"] exists, then: - if (init.method !== undefined) { - // 1. Let method be init["method"]. - let method = init.method + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') - // 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.`) - } + out[name.trim()] = value.join('=') + } - if (forbiddenMethodsSet.has(method.toUpperCase())) { - throw new TypeError(`'${method}' HTTP method is unsupported.`) - } + return out +} - // 3. Normalize method. - method = normalizeMethodRecord[method] ?? normalizeMethod(method) +/** + * @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' }) - // 4. Set request’s method to method. - request.method = method - } + webidl.brandCheck(headers, Headers, { strict: false }) - // 26. If init["signal"] exists, then set signal to it. - if (init.signal !== undefined) { - signal = init.signal - } + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) - // 27. Set this’s request to request. - this[kState] = request + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} - // 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] +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) - // 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." - ) - } + webidl.brandCheck(headers, Headers, { strict: false }) - 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 cookies = headers.getSetCookie() - const acRef = new WeakRef(ac) - const abort = function () { - const ac = acRef.deref() - if (ac !== undefined) { - ac.abort(this.reason) - } - } + if (!cookies) { + return [] + } - // 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 {} + return cookies.map((pair) => parseSetCookie(pair)) +} - util.addAbortListener(signal, abort) - requestFinalizer.register(ac, { signal, abort }) - } - } +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) - // 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] + webidl.brandCheck(headers, Headers, { strict: false }) - // 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.` - ) - } + cookie = webidl.converters.Cookie(cookie) - // 2. Set this’s headers’s guard to "request-no-cors". - this[kHeaders][kGuard] = 'request-no-cors' - } + const str = stringify(cookie) - // 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) + if (str) { + headers.append('Set-Cookie', stringify(cookie)) + } +} - // 3. Empty this’s headers’s header list. - headersList.clear() +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 + } +]) - // 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) +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) } - } - // 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 + 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: [] + } +]) - // 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.') - } +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} - // 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) - } - } +/***/ 4408: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 37. Let inputOrInitBody be initBody if it is non-null; otherwise - // inputBody. - const inputOrInitBody = initBody ?? inputBody +"use strict"; - // 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"' - ) - } +const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(663) +const { isCTLExcludingHtab } = __nccwpck_require__(3121) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(685) +const assert = __nccwpck_require__(9491) - // 3. Set this’s request’s use-CORS-preflight flag. - request.useCORSPreflightFlag = true - } +/** + * @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 + } - // 39. Let finalBody be inputOrInitBody. - let finalBody = inputOrInitBody + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' - // 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. 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 } - // 2. Set finalBody to the result of creating a proxy for inputBody. - if (!TransformStream) { - TransformStream = (__nccwpck_require__(35356).TransformStream) - } + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: - // 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 - } - } + // 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 + } - // 41. Set this’s request’s body to finalBody. - this[kState].body = finalBody + // 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) } - // Returns request’s HTTP method, which is "GET" by default. - get method () { - webidl.brandCheck(this, Request) + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() - // The method getter steps are to return this’s request’s method. - return this[kState].method + // 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 } - // Returns the URL of request as a string. - get url () { - webidl.brandCheck(this, Request) + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } +} - // The url getter steps are to return this’s request’s URL, serialized. - return URLSerializer(this[kState].url) +/** + * 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 } - // 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) + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) - // The headers getter steps are to return this’s headers. - return this[kHeaders] - } + let cookieAv = '' - // Returns the kind of resource requested by request, e.g., "document" - // or "script". - get destination () { - webidl.brandCheck(this, Request) + // 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: - // The destination getter are to return this’s request’s destination. - return this[kState].destination + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' } - // 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) + // Let the cookie-av string be the characters consumed in this step. - // 1. If this’s request’s referrer is "no-referrer", then return the - // empty string. - if (this[kState].referrer === 'no-referrer') { - return '' - } + let attributeName = '' + let attributeValue = '' - // 2. If this’s request’s referrer is "client", then return - // "about:client". - if (this[kState].referrer === 'client') { - return 'about:client' - } + // 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 } - // Return this’s request’s referrer, serialized. - return this[kState].referrer.toString() + 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 } - // 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) + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() - // The referrerPolicy getter steps are to return this’s request’s referrer policy. - return this[kState].referrerPolicy + // 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) } - // 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) + // 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) + } - // The mode getter steps are to return this’s request’s mode. - return this[kState].mode - } + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) - // 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 - } + // 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). - // 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) + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) - // The cache getter steps are to return this’s request’s cache mode. - return this[kState].cache - } + // 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 - // 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) + // 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. - // The redirect getter steps are to return this’s request’s redirect mode. - return this[kState].redirect - } + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue - // 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) + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } - // The integrity getter steps are to return this’s request’s integrity - // metadata. - return this[kState].integrity - } + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() - // Returns a boolean indicating whether or not request can outlive the - // global in which it was created. - get keepalive () { - webidl.brandCheck(this, Request) + // 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. - // The keepalive getter steps are to return this’s request’s keepalive. - return this[kState].keepalive - } + // 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: - // Returns a boolean indicating whether or not request is for a reload - // navigation. - get isReloadNavigation () { - webidl.brandCheck(this, Request) + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } - // The isReloadNavigation getter steps are to return true if this’s - // request’s reload-navigation flag is set; otherwise false. - return this[kState].reloadNavigation - } + // 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. - // 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) + 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. - // The isHistoryNavigation getter steps are to return true if this’s request’s - // history-navigation flag is set; otherwise false. - return this[kState].historyNavigation - } + 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: - // 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) + // 1. Let enforcement be "Default". + let enforcement = 'Default' - // The signal getter steps are to return this’s signal. - return this[kSignal] - } + 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' + } - get body () { - webidl.brandCheck(this, Request) + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } - return this[kState].body ? this[kState].body.stream : null - } + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } - get bodyUsed () { - webidl.brandCheck(this, Request) + // 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 ??= [] - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } - get duplex () { - webidl.brandCheck(this, Request) + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} - return 'half' - } +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} - // 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]) +/***/ 3121: +/***/ ((module) => { - // 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] +"use strict"; - // 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 +/** + * @param {string} value + * @returns {boolean} + */ +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false } -} -mixinBody(Request) + for (const char of value) { + const code = char.charCodeAt(0) -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() + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } } - 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 }) +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) - // 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) + 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') + } } - - // 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 +/** + 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') + } } -}) +} -webidl.converters.Request = webidl.interfaceConverter( - Request -) +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) -// https://fetch.spec.whatwg.org/#requestinfo -webidl.converters.RequestInfo = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } } +} - if (V instanceof Request) { - return webidl.converters.Request(V) +/** + * 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') } - - return webidl.converters.USVString(V) } -webidl.converters.AbortSignal = webidl.interfaceConverter( - AbortSignal -) +/** + * @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] -// 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 - } -]) + 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 -module.exports = { Request, makeRequest } + 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) -/***/ 27823: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } -"use strict"; + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] -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 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') -const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(35356).ReadableStream) -const textEncoder = new TextEncoder('utf-8') + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` +} -// https://fetch.spec.whatwg.org/#response-class -class Response { - // Creates network error Response. - static error () { - // TODO - const relevantRealm = { settingsObject: {} } +/** + 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') + } +} - // 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 +/** + * @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 } - // https://fetch.spec.whatwg.org/#dom-response-json - static json (data, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + validateCookieName(cookie.name) + validateCookieValue(cookie.value) - if (init !== null) { - init = webidl.converters.ResponseInit(init) - } + const out = [`${cookie.name}=${cookie.value}`] - // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = textEncoder.encode( - serializeJavascriptValueToJSONString(data) - ) + // 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 + } - // 2. Let body be the result of extracting bytes. - const body = extractBody(bytes) + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } - // 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 + if (cookie.secure) { + out.push('Secure') + } - // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). - initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + if (cookie.httpOnly) { + out.push('HttpOnly') + } - // 5. Return responseObject. - return responseObject + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) } - // Creates a redirect Response that redirects to url with status status. - static redirect (url, status = 302) { - const relevantRealm = { settingsObject: {} } + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } - url = webidl.converters.USVString(url) - status = webidl.converters['unsigned short'](status) + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } - // 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 - }) - } + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } - // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatusSet.has(status)) { - throw new RangeError('Invalid status code ' + status) + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') } - // 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 + const [key, ...value] = part.split('=') - // 5. Set responseObject’s response’s status to status. - responseObject[kState].status = status + out.push(`${key.trim()}=${value.join('=')}`) + } - // 6. Let value be parsedURL, serialized and isomorphic encoded. - const value = isomorphicEncode(URLSerializer(parsedURL)) + return out.join('; ') +} - // 7. Append `Location`/value to responseObject’s response’s header list. - responseObject[kState].headersList.append('location', value) +module.exports = { + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify +} - // 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) +/***/ 2067: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // TODO - this[kRealm] = { settingsObject: {} } +"use strict"; - // 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] +const net = __nccwpck_require__(1808) +const assert = __nccwpck_require__(9491) +const util = __nccwpck_require__(3983) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8045) - // 3. Let bodyWithType be null. - let bodyWithType = null +let tls // include tls conditionally since it is not always available - // 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 } +// 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) + } + }) } - // 5. Perform initialize a response given this, init, and bodyWithType. - initializeResponse(this, init, bodyWithType) - } + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } - // Returns response’s type, e.g., "cors". - get type () { - webidl.brandCheck(this, Response) + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } - // The type getter steps are to return this’s response’s type. - return this[kState].type + 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() + } - // Returns response’s URL, if it has one; otherwise the empty string. - get url () { - webidl.brandCheck(this, Response) + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } - const urlList = this[kState].urlList + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } - // 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 (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } - if (url === null) { - return '' + this._sessionCache.set(sessionKey, session) } + } +} - return URLSerializer(url, true) +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') } - // Returns whether response was obtained through a redirect. - get redirected () { - webidl.brandCheck(this, Response) + 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__(4404) + } + servername = servername || options.servername || util.getServerName(host) || null - // 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 - } + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null - // Returns response’s status. - get status () { - webidl.brandCheck(this, Response) + assert(sessionKey) - // The status getter steps are to return this’s response’s status. - return this[kState].status - } + 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 + }) - // Returns whether response’s status is an ok status. - get ok () { - webidl.brandCheck(this, Response) + 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 + }) + } - // 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 - } + // 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) + } - // Returns response’s status message. - get statusText () { - webidl.brandCheck(this, Response) + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) - // The statusText getter steps are to return this’s response’s status - // message. - return this[kState].statusText - } + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() - // Returns response’s headers as Headers. - get headers () { - webidl.brandCheck(this, Response) + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + cancelTimeout() - // The headers getter steps are to return this’s headers. - return this[kHeaders] + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket } +} - get body () { - webidl.brandCheck(this, Response) +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} + } - return this[kState].body ? this[kState].body.stream : null + 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) } +} - get bodyUsed () { - webidl.brandCheck(this, Response) +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } +module.exports = buildConnector - // 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.' - }) - } +/***/ }), + +/***/ 4462: +/***/ ((module) => { + +"use strict"; + + +/** @type {Record} */ +const headerNameLowerCasedRecord = {} + +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] - // 2. Let clonedResponse be the result of cloning this’s response. - const clonedResponse = cloneResponse(this[kState]) +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} - // 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] +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) - return clonedResponseObject - } +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord } -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: +/***/ 8045: +/***/ ((module) => { - // 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 - ) - } +"use strict"; - // 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) +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' } - - // 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] : [] +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' } } -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' - }) +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' + } } -function makeFilteredResponse (response, state) { - state = { - internalResponse: response, - ...state +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' } - - 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) +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' } } -// 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 })) +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 + } } -// 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.') +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' } +} - // 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') - } +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' } +} - // 3. Set response’s response’s status to init["status"]. - if ('status' in init && init.status != null) { - response[kState].status = init.status +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' } +} - // 4. Set response’s response’s status message to init["statusText"]. - if ('statusText' in init && init.statusText != null) { - response[kState].statusText = init.statusText +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' } +} - // 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) +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' } +} - // 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) - } +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' } } -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) +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' } +} - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) +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' } +} - if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { - return webidl.converters.BufferSource(V) +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 } +} - if (util.isFormDataLike(V)) { - return webidl.converters.FormData(V, { strict: false }) +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' } +} - if (V instanceof URLSearchParams) { - return webidl.converters.URLSearchParams(V) +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' } - - 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) +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 } +} - // Note: the spec doesn't include async iterables, - // this is an undici extension. - if (V?.[Symbol.asyncIterator]) { - return V +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' } - - 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 +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 = { - makeNetworkError, - makeResponse, - makeAppropriateNetworkError, - filterResponse, - Response, - cloneResponse + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError } /***/ }), -/***/ 15861: -/***/ ((module) => { +/***/ 2905: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = { - kUrl: Symbol('url'), - kHeaders: Symbol('headers'), - kSignal: Symbol('signal'), - kState: Symbol('state'), - kGuard: Symbol('guard'), - kRealm: Symbol('realm') -} - +const { + InvalidArgumentError, + NotSupportedError +} = __nccwpck_require__(8045) +const assert = __nccwpck_require__(9491) +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(2785) +const util = __nccwpck_require__(3983) -/***/ }), +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js -/***/ 52538: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * 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!#$%&'*+.|~]+$/ -"use strict"; +/** + * 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 { 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) +const kHandler = Symbol('handler') -let supportedHashes = [] +const channels = {} -// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable -/** @type {import('crypto')|undefined} */ -let crypto +let extractBody try { - crypto = __nccwpck_require__(6113) - const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] - supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) -/* c8 ignore next 3 */ + const diagnosticsChannel = __nccwpck_require__(7643) + 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 } } -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() -} +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') + } -// 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 - } + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } - // 2. Let location be the result of extracting header list values given - // `Location` and response’s header list. - let location = response.headersList.get('location') + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } - // 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)) - } + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } - // 4. If location is a URL whose fragment is null, then set location’s - // fragment to requestFragment. - if (location && !location.hash) { - location.hash = requestFragment - } + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } - // 5. Return location. - return location -} + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } -/** @returns {URL} */ -function requestCurrentURL (request) { - return request.urlList[request.urlList.length - 1] -} + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } -function requestBadPort (request) { - // 1. Let url be request’s current URL. - const url = requestCurrentURL(request) + this.headersTimeout = headersTimeout - // 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' - } + this.bodyTimeout = bodyTimeout - // 3. Return allowed. - return 'allowed' -} + this.throwOnError = throwOnError === true -function isErrorLike (object) { - return object instanceof Error || ( - object?.constructor?.name === 'Error' || - object?.constructor?.name === 'DOMException' - ) -} + this.method = method -// 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 -} + this.abort = null -/** - * @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 - } -} + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body -/** - * @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 + 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') } - } - return true -} -/** - * @see https://fetch.spec.whatwg.org/#header-name - * @param {string} potentialValue - */ -function isValidHeaderName (potentialValue) { - return isValidHTTPToken(potentialValue) -} + this.completed = false -/** - * @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 - } + this.aborted = false - if ( - potentialValue.includes('\0') || - potentialValue.includes('\r') || - potentialValue.includes('\n') - ) { - return false - } + this.upgrade = upgrade || null - return true -} + this.path = query ? util.buildURL(path, query) : path -// 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. + this.origin = origin - // 1. Let policy be the result of executing § 8.1 Parse a referrer policy - // from a Referrer-Policy header on actualResponse. + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent - // 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(',') + this.blocking = blocking == null ? false : blocking - // 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 - } - } - } + this.reset = reset == null ? null : reset - // 2. If policy is not the empty string, then set request’s referrer policy to policy. - if (policy !== '') { - request.referrerPolicy = policy - } -} + this.host = null -// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check -function crossOriginResourcePolicyCheck () { - // TODO - return 'allowed' -} + this.contentLength = null -// https://fetch.spec.whatwg.org/#concept-cors-check -function corsCheck () { - // TODO - return 'success' -} + this.contentType = null -// https://fetch.spec.whatwg.org/#concept-tao-check -function TAOCheck () { - // TODO - return 'success' -} + this.headers = '' -function appendFetchMetadata (httpRequest) { - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header - // TODO + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + 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') + } - // 1. Assert: r’s url is a potentially trustworthy URL. - // TODO + 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.') + } - // 2. Let header be a Structured Header whose value is a token. - let header = null + if (!extractBody) { + extractBody = (__nccwpck_require__(1472).extractBody) + } - // 3. Set header’s value to r’s mode. - header = httpRequest.mode + 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` + } - // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. - httpRequest.headersList.set('sec-fetch-mode', header) + util.validateHandler(handler, method, upgrade) - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header - // TODO + this.servername = util.getServerName(this.host) - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header - // TODO -} + this[kHandler] = handler -// 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 + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } - // 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) + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } } + } - // 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. + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) } - if (serializedOrigin) { - // 2. Append (`Origin`, serializedOrigin) to request’s header list. - request.headersList.append('origin', serializedOrigin) + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } } } -} -function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { - // TODO - return performance.now() -} + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) -// 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 + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } } -} -// 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' + 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) + } } -} -// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container -function clonePolicyContainer (policyContainer) { - return { - referrerPolicy: policyContainer.referrerPolicy + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } } -} -// 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 + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally() - // Note: policy cannot (shouldn't) be null or an empty string. - assert(policy) + assert(!this.aborted) - // 2. Let environment be request’s client. + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } - let referrerSource = null + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } - // 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. + onError (error) { + this.onFinally() - const globalOrigin = getGlobalOrigin() + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } - if (!globalOrigin || globalOrigin.origin === 'null') { - return 'no-referrer' + if (this.aborted) { + return } + this.aborted = true - // 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 + return this[kHandler].onError(error) } - // 4. Let request’s referrerURL be the result of stripping referrerSource for - // use as a referrer. - let referrerURL = stripURLForReferrer(referrerSource) + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } - // 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) + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } - // 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 + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this } - const areSameOrigin = sameOrigin(request, referrerURL) - const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && - !isURLPotentiallyTrustworthy(request.url) + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } - // 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) + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } - // 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 - } + const request = new Request(origin, opts, handler) - // 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' - } + request.headers = {} - // 3. Return referrerOrigin. - return referrerOrigin + 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') } - 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' + return request } - // 3. Set url’s username to the empty string. - url.username = '' + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} - // 4. Set url’s password to the empty string. - url.password = '' + for (const header of rawHeaders) { + const [key, value] = header.split(': ') - // 5. Set url’s fragment to null. - url.hash = '' + if (value == null || value.length === 0) continue - // 6. If the origin-only flag is true, then: - if (originOnly) { - // 1. Set url’s path to Ā« the empty string Ā». - url.pathname = '' + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value + } - // 2. Set url’s query to null. - url.search = '' + return headers } - - // 7. Return url. - return url } -function isURLPotentiallyTrustworthy (url) { - if (!(url instanceof URL)) { - return false +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) } - // If child of about, return true - if (url.href === 'about:blank' || url.href === 'about:srcdoc') { - return true + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) } - // If scheme is data, return true - if (url.protocol === 'data:') return true + return skipAppend ? val : `${key}: ${val}\r\n` +} - // If file, return true - if (url.protocol === 'file:') return true +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 + } - return isOriginPotentiallyTrustworthy(url.origin) + 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) + } + } +} - function isOriginPotentiallyTrustworthy (origin) { - // If origin is explicitly null, return false - if (origin == null || origin === 'null') return false +module.exports = Request - 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 - } +/***/ 2785: +/***/ ((module) => { - // If any other, return false - return false - } +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') } -/** - * @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 - } +/***/ 3983: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 3. If response is not eligible for integrity validation, return false. - // TODO +"use strict"; - // 4. If parsedMetadata is the empty set, return true. - if (parsedMetadata.length === 0) { - return true - } - // 5. Let metadata be the result of getting the strongest - // metadata from parsedMetadata. - const strongest = getStrongestMetadata(parsedMetadata) - const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) +const assert = __nccwpck_require__(9491) +const { kDestroyed, kBodyUsed } = __nccwpck_require__(2785) +const { IncomingMessage } = __nccwpck_require__(3685) +const stream = __nccwpck_require__(2781) +const net = __nccwpck_require__(1808) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { Blob } = __nccwpck_require__(4300) +const nodeUtil = __nccwpck_require__(3837) +const { stringify } = __nccwpck_require__(3477) +const { headerNameLowerCasedRecord } = __nccwpck_require__(4462) - // 6. For each item in metadata: - for (const item of metadata) { - // 1. Let algorithm be the alg component of item. - const algorithm = item.algo +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) - // 2. Let expectedValue be the val component of item. - const expectedValue = item.hash +function nop () {} - // 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. +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} - // 3. Let actualValue be the result of applying algorithm to bytes. - let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') +// 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]) + ) +} - if (actualValue[actualValue.length - 1] === '=') { - if (actualValue[actualValue.length - 2] === '=') { - actualValue = actualValue.slice(0, -2) - } else { - actualValue = actualValue.slice(0, -1) - } - } +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } - // 4. If actualValue is a case-sensitive match for expectedValue, - // return true. - if (compareBase64Mixed(actualValue, expectedValue)) { - return true - } + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified } - // 7. Return false. - return false + return url } -// 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-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) -/** - * @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 = [] + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } - // 2. Let empty be equal to true. - let empty = true + return url + } - // 3. For each token returned by splitting metadata on spaces: - for (const token of metadata.split(' ')) { - // 1. Set empty to false. - empty = false + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } - // 2. Parse token as a hash-with-options. - const parsedToken = parseHashWithOptions.exec(token) + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } - // 3. If token does not parse, continue to the next token. - if ( - parsedToken === null || - parsedToken.groups === undefined || - parsedToken.groups.algo === 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 + 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.') } - // 4. Let algorithm be the hash-algo component of token. - const algorithm = parsedToken.groups.algo.toLowerCase() + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } - // 5. If algorithm is a hash function recognized by the user - // agent, add the parsed token to result. - if (supportedHashes.includes(algorithm)) { - result.push(parsedToken.groups) + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') } - } - // 4. Return no metadata if empty is true, otherwise return result. - if (empty === true) { - return 'no metadata' - } + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } - return result -} + 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 || ''}` -/** - * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList - */ -function getStrongestMetadata (metadataList) { - // Let algorithm be the algo component of the first item in metadataList. - // Can be sha256 - let algorithm = metadataList[0].algo - // If the algorithm is sha512, then it is the strongest - // and we can return immediately - if (algorithm[3] === '5') { - return algorithm - } + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1) + } - for (let i = 1; i < metadataList.length; ++i) { - const metadata = metadataList[i] - // If the algorithm is sha512, then it is the strongest - // and we can break the loop immediately - if (metadata.algo[3] === '5') { - algorithm = 'sha512' - break - // If the algorithm is sha384, then a potential sha256 or sha384 is ignored - } else if (algorithm[3] === '3') { - continue - // algorithm is sha256, check if algorithm is sha384 and if so, set it as - // the strongest - } else if (metadata.algo[3] === '3') { - algorithm = 'sha384' + 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 algorithm + + return url } -function filterMetadataListByAlgorithm (metadataList, algorithm) { - if (metadataList.length === 1) { - return metadataList - } +function parseOrigin (url) { + url = parseURL(url) - let pos = 0 - for (let i = 0; i < metadataList.length; ++i) { - if (metadataList[i].algo === algorithm) { - metadataList[pos++] = metadataList[i] - } + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') } - metadataList.length = pos - - return metadataList + return url } -/** - * Compares two base64 strings, allowing for base64url - * in the second string. - * -* @param {string} actualValue always base64 - * @param {string} expectedValue base64 or base64url - * @returns {boolean} - */ -function compareBase64Mixed (actualValue, expectedValue) { - if (actualValue.length !== expectedValue.length) { - return false - } - for (let i = 0; i < actualValue.length; ++i) { - if (actualValue[i] !== expectedValue[i]) { - if ( - (actualValue[i] === '+' && expectedValue[i] === '-') || - (actualValue[i] === '/' && expectedValue[i] === '_') - ) { - continue - } - return false - } +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) } - return true -} + const idx = host.indexOf(':') + if (idx === -1) return host -// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request -function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { - // TODO + return host.substring(0, idx) } -/** - * @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 +// 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 } - // 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 + assert.strictEqual(typeof host, 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' } - // 3. Return false. - return false + return servername } -function createDeferredPromise () { - let res - let rej - const promise = new Promise((resolve, reject) => { - res = resolve - rej = reject - }) - - return { promise, resolve: res, reject: rej } +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) } -function isAborted (fetchParams) { - return fetchParams.controller.state === 'aborted' +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') } -function isCancelled (fetchParams) { - return fetchParams.controller.state === 'aborted' || - fetchParams.controller.state === 'terminated' +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) } -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' -} +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 + } -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(normalizeMethodRecord, null) + return null +} -/** - * @see https://fetch.spec.whatwg.org/#concept-method-normalize - * @param {string} method - */ -function normalizeMethod (method) { - return normalizeMethodRecord[method.toLowerCase()] ?? method +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) } -// 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) +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} - // 2. If result is undefined, then throw a TypeError. - if (result === undefined) { - throw new TypeError('Value is not JSON serializable') +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return } - // 3. Assert: result is a string. - assert(typeof result === 'string') + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } - // 4. Return result. - return result + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } } -// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object -const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) +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 +} /** - * @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 + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} */ -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. +function headerNameToString (value) { + return headerNameLowerCasedRecord[value] || value.toLowerCase() +} - // 3. Let object be ? ToObject(thisValue). +function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers - // 4. If object is a platform object, then perform a security - // check, passing: + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] - // 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.` - ) + 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')) + } + } - // 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() + // 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') + } - // 9. Let len be the length of values. - const len = values.length + return obj +} - // 10. If index is greater than or equal to len, then return - // CreateIterResultObject(undefined, true). - if (index >= len) { - return { value: undefined, done: true } - } +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 - // 11. Let pair be the entry in values at index index. - const pair = values[index] + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + const val = headers[n + 1].toString('utf8') - // 12. Set object’s index to index + 1. - object.index = index + 1 + 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) + } + } - // 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` + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') } - // 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) + return ret } -// https://webidl.spec.whatwg.org/#iterator-result -function iteratorResult (pair, kind) { - let result +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} - // 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 - } +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') } - // 2. Return CreateIterResultObject(result, false). - return { value: result, done: false } -} + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } -/** - * @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. + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } - // 2. Let successSteps given a byte sequence bytes be to queue a - // fetch task to run processBody given bytes, with taskDestination. - const successSteps = processBody + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } - // 3. Let errorSteps be to queue a fetch task to run processBodyError, - // with taskDestination. - const errorSteps = processBodyError + 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') + } - // 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 + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } - try { - reader = body.stream.getReader() - } catch (e) { - errorSteps(e) - return + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } } +} - // 5. Read all bytes from reader, given successSteps and errorSteps. - try { - const result = await readAllBytes(reader) - successSteps(result) - } catch (e) { - errorSteps(e) - } +// 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) + )) } -/** @type {ReadableStream} */ -let ReadableStream = globalThis.ReadableStream +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} -function isReadableStreamLike (stream) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(35356).ReadableStream) - } +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} - return stream instanceof ReadableStream || ( - stream[Symbol.toStringTag] === 'ReadableStream' && - typeof stream.tee === 'function' - ) +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 + } } -const MAXIMUM_ARGUMENT_LENGTH = 65535 +async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + } +} -/** - * @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. +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } - if (input.length < MAXIMUM_ARGUMENT_LENGTH) { - return String.fromCharCode(...input) + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) } - return input.reduce((previous, current) => previous + String.fromCharCode(current), '') + 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' + ) } -/** - * @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')) { +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 } } } -/** - * @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. +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) } -/** - * @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:' -} +const hasToWellFormed = !!String.prototype.toWellFormed /** - * @param {string|URL} url + * @param {string} val */ -function urlHasHttpsScheme (url) { - if (typeof url === 'string') { - return url.startsWith('https:') +function toUSVString (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) } - return url.protocol === 'https:' + return `${val}` } -/** - * @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 +// 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 } - return protocol === 'http:' || protocol === 'https:' + 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 } -/** - * 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)) +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true module.exports = { - isAborted, - isCancelled, - createDeferredPromise, - ReadableStreamFrom, + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, toUSVString, - tryUpgradeRequestToAPotentiallyTrustworthyURL, - coarsenedSharedCurrentTime, - determineRequestsReferrer, - makePolicyContainer, - clonePolicyContainer, - appendFetchMetadata, - appendRequestOriginHeader, - TAOCheck, - corsCheck, - crossOriginResourcePolicyCheck, - createOpaqueTimingInfo, - setRequestReferrerPolicyOnRedirect, - isValidHTTPToken, - requestBadPort, - requestCurrentURL, - responseURL, - responseLocationURL, + isReadableAborted, isBlobLike, - isURLPotentiallyTrustworthy, - isValidReasonPhrase, - sameOrigin, - normalizeMethod, - serializeJavascriptValueToJSONString, - makeIterator, - isValidHeaderName, - isValidHeaderValue, - hasOwn, - isErrorLike, - fullyReadBody, - bytesMatch, - isReadableStreamLike, - readableStreamClose, - isomorphicEncode, - isomorphicDecode, - urlIsLocal, - urlHasHttpsScheme, - urlIsHttpHttpsScheme, - readAllBytes, - normalizeMethodRecord, - parseMetadata + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + 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'] } /***/ }), -/***/ 21744: +/***/ 4839: /***/ ((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(', ')}.` +const Dispatcher = __nccwpck_require__(412) +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = __nccwpck_require__(8045) +const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(2785) - return webidl.errors.exception({ - header: context.prefix, - message - }) -} +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') -webidl.errors.invalidArgument = function (context) { - return webidl.errors.exception({ - header: context.prefix, - message: `"${context.value}" is an invalid ${context.type}.` - }) -} +class DispatcherBase extends Dispatcher { + constructor () { + super() -// 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] + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] } -} -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 - }) + get destroyed () { + return this[kDestroyed] } -} - -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' - } + get closed () { + return this[kClosed] } -} - -// 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 + get interceptors () { + return this[kInterceptors] } - // 4. Let x be ? ToNumber(V). - let x = Number(V) + 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') + } + } + } - // 5. If x is āˆ’0, then set x to +0. - if (x === 0) { - x = 0 + this[kInterceptors] = newInterceptors } - // 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.` + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) }) } - // 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}.` - }) + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - // 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) + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return } - // 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) - } + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } - // 12. Otherwise, return x. - return x -} + this[kClosed] = true + this[kOnClosed].push(callback) -// 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)) + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } - // 2. If n < 0, then return -1 Ɨ r. - if (n < 0) { - return -1 * r + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) } - // 3. Otherwise, return r. - return r -} + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } -// 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.` + 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) + }) }) } - // 2. Let method be ? GetMethod(V, @@iterator). - /** @type {Generator} */ - const method = V?.[Symbol.iterator]?.() - const seq = [] + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - // 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.' - }) + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return } - // https://webidl.spec.whatwg.org/#create-sequence-from-iterable - while (true) { - const { done, value } = method.next() + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) - if (done) { - break + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) } - - seq.push(converter(value)) } - return seq + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) } -} -// 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.` - }) + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) } - // 2. Let result be a new empty instance of record. - const result = {} + 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) + } - if (!types.isProxy(O)) { - // Object.keys only returns enumerable properties - const keys = Object.keys(O) + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } - for (const key of keys) { - // 1. Let typedKey be key converted to an IDL value of type K. - const typedKey = keyConverter(key) + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } - // 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]) + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue + if (this[kClosed]) { + throw new ClientClosedError() } - // 5. Return result. - return result + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false } + } +} - // 3. Let keys be ? O.[[OwnPropertyKeys]](). - const keys = Reflect.ownKeys(O) +module.exports = DispatcherBase - // 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]) +/***/ 412: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } - } +"use strict"; - // 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}.` - }) - } +const EventEmitter = __nccwpck_require__(2361) - return V +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') } -} -webidl.dictionaryConverter = function (converters) { - return (dictionary) => { - const type = webidl.util.Type(dictionary) - const dict = {} + close () { + throw new Error('not implemented') + } - 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.` - }) - } + destroy () { + throw new Error('not implemented') + } +} - for (const options of converters) { - const { key, defaultValue, required, converter } = options +module.exports = Dispatcher - 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 - } +/***/ 1472: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) +"use strict"; - 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 - } - } +const Busboy = __nccwpck_require__(727) +const util = __nccwpck_require__(3983) +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = __nccwpck_require__(2538) +const { FormData } = __nccwpck_require__(2015) +const { kState } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { DOMException, structuredClone } = __nccwpck_require__(1037) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { isErrored } = __nccwpck_require__(3983) +const { isUint8Array, isArrayBuffer } = __nccwpck_require__(9830) +const { File: UndiciFile } = __nccwpck_require__(8511) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) - return dict - } +let random +try { + const crypto = __nccwpck_require__(6005) + random = (max) => crypto.randomInt(0, max) +} catch { + random = (max) => Math.floor(Math.random(max)) } -webidl.nullableConverter = function (converter) { - return (V) => { - if (V === null) { - return V - } +let ReadableStream = globalThis.ReadableStream - return converter(V) - } -} +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() -// 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 '' +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) } - // 2. Let x be ? ToString(V). - if (typeof V === 'symbol') { - throw new TypeError('Could not convert argument of type symbol to string.') - } + // 1. Let stream be null. + let stream = null - // 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) -} + // 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 + }) + } -// 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) + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) - // 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.` - ) - } - } + // 6. Let action be null. + let action = null - // 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 -} + // 7. Let source be null. + let source = null -// https://webidl.spec.whatwg.org/#es-USVString -webidl.converters.USVString = toUSVString + // 8. Let length be null. + let length = null -// 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) + // 9. Let type be null. + let type = null - // 2. Return the IDL boolean value that is the one that represents - // the same truth value as the ECMAScript Boolean value x. - return x -} + // 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 -// https://webidl.spec.whatwg.org/#es-any -webidl.converters.any = function (V) { - return V -} + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams -// 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') + // 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 - // 2. Return the IDL long long value that represents - // the same numeric value as x. - return x -} + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() -// 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') + // 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 - // 2. Return the IDL unsigned long long value that - // represents the same numeric value as x. - return x -} + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView -// 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') + // 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${`${random(1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` - // 2. Return the IDL unsigned long value that - // represents the same numeric value as x. - return x -} + /*! 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') -// 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) + // 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. - // 2. Return the IDL unsigned short value that represents - // the same numeric value as x. - return x -} + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false -// 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'] - }) - } + 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 + } + } + } - // 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.' - }) - } + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } - // 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. + // Set source to object. + source = object - // 4. Return the IDL ArrayBuffer value that is a - // reference to the same object as V. - return V -} + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } -webidl.converters.TypedArray = function (V, T, opts = {}) { - // 1. Let T be the IDL type V is being converted to. + // 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 - // 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] - }) - } + // Set source to object. + source = object - // 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.' - }) - } + // Set length to object’s size. + length = object.size - // 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 + // 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') + } - // 5. Return the IDL value of type T that is a reference - // to the same object as V. - return V -} + // 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' + ) + } -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.' - }) + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) } - // 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.' + // 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 }) } - // 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 + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } - // 4. Return the IDL DataView value that is a reference - // to the same object as V. - return V + // 14. Return (body, type). + return [body, type] } -// https://webidl.spec.whatwg.org/#BufferSource -webidl.converters.BufferSource = function (V, opts = {}) { - if (types.isAnyArrayBuffer(V)) { - return webidl.converters.ArrayBuffer(V, opts) +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = (__nccwpck_require__(5356).ReadableStream) } - if (types.isTypedArray(V)) { - return webidl.converters.TypedArray(V, V.constructor) - } + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: - if (types.isDataView(V)) { - return webidl.converters.DataView(V, opts) + // 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.') } - throw new TypeError(`Could not convert ${V} to a BufferSource.`) + // 2. Return the results of extracting object. + return extractBody(object, keepalive) } -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.ByteString -) - -webidl.converters['sequence>'] = webidl.sequenceConverter( - webidl.converters['sequence'] -) +function cloneBody (body) { + // To clone a body body, run these steps: -webidl.converters['record'] = webidl.recordConverter( - webidl.converters.ByteString, - webidl.converters.ByteString -) + // https://fetch.spec.whatwg.org/#concept-body-clone -module.exports = { - webidl -} + // 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 + } +} -/***/ 84854: -/***/ ((module) => { +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream -"use strict"; + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } + if (stream.locked) { + throw new TypeError('The stream is locked.') + } -/** - * @see https://encoding.spec.whatwg.org/#concept-encoding-get - * @param {string|undefined} label - */ -function getEncoding (label) { - if (!label) { - return 'failure' - } + // Compat. + stream[kBodyUsed] = true - // 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' + yield * stream + } } } -module.exports = { - getEncoding +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) + } -/***/ 1446: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, -"use strict"; + 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) + }, -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) + 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) + }, -class FileReader extends EventTarget { - constructor () { - super() + async formData () { + webidl.brandCheck(this, instance) - this[kState] = 'empty' - this[kResult] = null - this[kError] = null - this[kEvents] = { - loadend: null, - error: null, - abort: null, - load: null, - progress: null, - loadstart: null - } - } + throwIfAborted(this[kState]) - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer - * @param {import('buffer').Blob} blob - */ - readAsArrayBuffer (blob) { - webidl.brandCheck(this, FileReader) + const contentType = this.headers.get('Content-Type') - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) + // 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 - blob = webidl.converters.Blob(blob, { strict: false }) + const responseFormData = new FormData() - // The readAsArrayBuffer(blob) method, when invoked, - // must initiate a read operation for blob with ArrayBuffer. - readOperation(this, blob, 'ArrayBuffer') - } + let busboy - /** - * @see https://w3c.github.io/FileAPI/#readAsBinaryString - * @param {import('buffer').Blob} blob - */ - readAsBinaryString (blob) { - webidl.brandCheck(this, FileReader) + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] - blob = webidl.converters.Blob(blob, { strict: false }) + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' - // The readAsBinaryString(blob) method, when invoked, - // must initiate a read operation for blob with BinaryString. - readOperation(this, blob, 'BinaryString') - } + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') - /** - * @see https://w3c.github.io/FileAPI/#readAsDataText - * @param {import('buffer').Blob} blob - * @param {string?} encoding - */ - readAsText (blob, encoding = undefined) { - webidl.brandCheck(this, FileReader) + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + 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 })) + }) + } + }) - blob = webidl.converters.Blob(blob, { strict: false }) + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) - if (encoding !== undefined) { - encoding = webidl.converters.DOMString(encoding) - } + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) + busboy.end() + await busboyResolve - // The readAsText(blob, encoding) method, when invoked, - // must initiate a read operation for blob with Text and encoding. - readOperation(this, blob, 'Text', encoding) - } + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL - * @param {import('buffer').Blob} blob - */ - readAsDataURL (blob) { - webidl.brandCheck(this, FileReader) + // 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 }) - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) + 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 }) + } - blob = webidl.converters.Blob(blob, { strict: false }) + // 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() - // The readAsDataURL(blob) method, when invoked, must - // initiate a read operation for blob with DataURL. - readOperation(this, blob, 'DataURL') - } + throwIfAborted(this[kState]) - /** - * @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 + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) + } } + } - // 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 - } + return methods +} - // 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 +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} - // 4. Terminate the algorithm for the read method being processed. - // TODO +/** + * @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) - // 5. Fire a progress event called abort at this. - fireAProgressEvent('abort', this) + throwIfAborted(object[kState]) - // 6. If this's state is not "loading", fire a progress - // event called loadend at this. - if (this[kState] !== 'loading') { - fireAProgressEvent('loadend', this) - } + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') } - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate - */ - get readyState () { - webidl.brandCheck(this, FileReader) + // 2. Let promise be a new promise. + const promise = createDeferredPromise() - switch (this[kState]) { - case 'empty': return this.EMPTY - case 'loading': return this.LOADING - case 'done': return this.DONE + // 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) } } - /** - * @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] + // 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 } - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-error - */ - get error () { - webidl.brandCheck(this, FileReader) + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) - // The error attribute’s getter, when invoked, must return - // this's error. - return this[kError] + // 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 '' } - get onloadend () { - webidl.brandCheck(this, FileReader) + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. - return this[kEvents].loadend + // 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) } - set onloadend (fn) { - webidl.brandCheck(this, FileReader) + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) - if (this[kEvents].loadend) { - this.removeEventListener('loadend', this[kEvents].loadend) - } + // 4. Return output. + return output +} - if (typeof fn === 'function') { - this[kEvents].loadend = fn - this.addEventListener('loadend', fn) - } else { - this[kEvents].loadend = null - } - } +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} - get onerror () { - webidl.brandCheck(this, FileReader) +/** + * @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') - return this[kEvents].error + if (contentType === null) { + return 'failure' } - set onerror (fn) { - webidl.brandCheck(this, FileReader) + return parseMIMEType(contentType) +} - if (this[kEvents].error) { - this.removeEventListener('error', this[kEvents].error) - } +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody +} - 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 - } +/***/ 1037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - set onloadstart (fn) { - webidl.brandCheck(this, FileReader) +"use strict"; - 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 - } - } +const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(1267) - get onprogress () { - webidl.brandCheck(this, FileReader) +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) - return this[kEvents].progress - } +const nullBodyStatus = [101, 204, 205, 304] - set onprogress (fn) { - webidl.brandCheck(this, FileReader) +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) - if (this[kEvents].progress) { - this.removeEventListener('progress', this[kEvents].progress) - } +// 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' +] - if (typeof fn === 'function') { - this[kEvents].progress = fn - this.addEventListener('progress', fn) - } else { - this[kEvents].progress = null - } - } +const badPortsSet = new Set(badPorts) - get onload () { - webidl.brandCheck(this, FileReader) +// 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) - return this[kEvents].load - } +const requestRedirect = ['follow', 'manual', 'error'] - set onload (fn) { - webidl.brandCheck(this, FileReader) +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) - if (this[kEvents].load) { - this.removeEventListener('load', this[kEvents].load) - } +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] - if (typeof fn === 'function') { - this[kEvents].load = fn - this.addEventListener('load', fn) - } else { - this[kEvents].load = null - } - } +const requestCredentials = ['omit', 'same-origin', 'include'] - get onabort () { - webidl.brandCheck(this, FileReader) +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] - return this[kEvents].abort - } +// 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' +] - set onabort (fn) { - webidl.brandCheck(this, FileReader) +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] - if (this[kEvents].abort) { - this.removeEventListener('abort', this[kEvents].abort) - } +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) - if (typeof fn === 'function') { - this[kEvents].abort = fn - this.addEventListener('abort', fn) - } else { - this[kEvents].abort = null - } +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 } -} +})() -// 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 +let channel -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 - } -}) +/** @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') + } -Object.defineProperties(FileReader, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors -}) + if (!channel) { + channel = new MessageChannel() + } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } module.exports = { - FileReader + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet } /***/ }), -/***/ 55504: +/***/ 685: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - +const assert = __nccwpck_require__(9491) +const { atob } = __nccwpck_require__(4300) +const { isomorphicDecode } = __nccwpck_require__(2538) -const { webidl } = __nccwpck_require__(21744) - -const kState = Symbol('ProgressEvent state') +const encoder = new TextEncoder() /** - * @see https://xhr.spec.whatwg.org/#progressevent + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point */ -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 - } - } +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 - get lengthComputable () { - webidl.brandCheck(this, ProgressEvent) +// 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:') - return this[kState].lengthComputable - } + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) - get loaded () { - webidl.brandCheck(this, ProgressEvent) + // 3. Remove the leading "data:" string from input. + input = input.slice(5) - return this[kState].loaded - } + // 4. Let position point at the start of input. + const position = { position: 0 } - get total () { - webidl.brandCheck(this, ProgressEvent) + // 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 + ) - return this[kState].total - } -} + // 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) -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 + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' } -]) - -module.exports = { - ProgressEvent -} + // 8. Advance position by 1. + position.position++ -/***/ }), + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) -/***/ 29054: -/***/ ((module) => { + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) -"use strict"; + // 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) -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') -} + // 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)+$/, '') -/***/ 87530: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } -"use strict"; + // 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) -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) + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false + // 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 /** - * @see https://w3c.github.io/FileAPI/#readOperation - * @param {import('./filereader').FileReader} fr - * @param {import('buffer').Blob} blob - * @param {string} type - * @param {string?} encodingName + * @param {URL} url + * @param {boolean} excludeFragment */ -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') +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href } - // 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() + const href = url.href + const hashLength = url.hash.length - // 7. Let bytes be an empty byte sequence. - /** @type {Uint8Array[]} */ - const bytes = [] + return hashLength === 0 ? href : href.substring(0, href.length - hashLength) +} - // 8. Let chunkPromise be the result of reading a chunk from - // stream with reader. - let chunkPromise = reader.read() +// 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 = '' - // 9. Let isFirstChunk be true. - let isFirstChunk = true + // 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] - // 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. Advance position by 1. + position.position++ + } - // 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. Return result. + return result +} - // 3. Set isFirstChunk to false. - isFirstChunk = false +/** + * 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 - // 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. + if (idx === -1) { + position.position = input.length + return input.slice(start) + } - // 2. Append bs to bytes. - bytes.push(value) + position.position = idx + return input.slice(start, position.position) +} - // 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) - }) - } +// 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) - // 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. Return the percent-decoding of bytes. + return percentDecode(bytes) +} - // 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) +// 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 = [] - // 4. Else: + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] - if (fr[kAborted]) { - return - } + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) - // 1. Set fr’s result to result. - fr[kResult] = result + // 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) - // 2. Fire a progress event called load at the fr. - fireAProgressEvent('load', fr) - } catch (error) { - // 3. If package data threw an exception error: + // 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) - // 1. Set fr’s error to error. - fr[kError] = error + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) - // 2. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) - } + // 3. Skip the next two bytes in input. + i += 2 + } + } - // 5. If fr’s state is not "loading", fire a progress - // event called loadend at the fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) + // 3. Return output. + return Uint8Array.from(output) +} - break - } - } catch (error) { - if (fr[kAborted]) { - return - } +// 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) - // 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. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } - // 2. Set fr’s error to error. - fr[kError] = error + // 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 + ) - // 3. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) + // 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' + } - // 4. If fr’s state is not "loading", fire a progress - // event called loadend at fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } - break - } - } - })() -} + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ -/** - * @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 - }) + // 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 + ) - reader.dispatchEvent(event) -} + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) -/** - * @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: + // 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' + } - 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]. + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() - // 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:' + // 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}` + } - const parsed = parseMIMEType(mimeType || 'application/octet-stream') + // 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++ - if (parsed !== 'failure') { - dataURL += serializeAMimeType(parsed) - } + // 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 + ) - dataURL += ';base64,' + // 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 + ) - const decoder = new StringDecoder('latin1') + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() - for (const chunk of bytes) { - dataURL += btoa(decoder.write(chunk)) + // 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 } - dataURL += btoa(decoder.end()) - - return dataURL + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ } - 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) + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } - // 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')) - } - } + // 7. Let parameterValue be null. + let parameterValue = null - // 4. If encoding is failure, then set encoding to UTF-8. - if (encoding === 'failure') { - encoding = 'UTF-8' - } + // 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) - // 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) + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) - 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 = '' + // 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 + ) - const decoder = new StringDecoder('latin1') + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) - for (const chunk of bytes) { - binaryString += decoder.write(chunk) + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue } + } - binaryString += decoder.end() - - return binaryString + // 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) } } -} -/** - * @see https://encoding.spec.whatwg.org/#decode - * @param {Uint8Array[]} ioQueue - * @param {string} encoding - */ -function decode (ioQueue, encoding) { - const bytes = combineByteSequences(ioQueue) + // 12. Return mimeType. + return mimeType +} - // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. - const BOMEncoding = BOMSniffing(bytes) +// 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 - let slice = 0 + // 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(/=?=$/, '') + } - // 2. If BOMEncoding is non-null: - if (BOMEncoding !== null) { - // 1. Set encoding to BOMEncoding. - encoding = BOMEncoding + // 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' + } - // 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 + // 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' } - // 3. Process a queue with an instance of encoding’s - // decoder, ioQueue, output, and "replacement". + const binary = atob(data) + const bytes = new Uint8Array(binary.length) - // 4. Return output. + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) + } - const sliced = bytes.slice(slice) - return new TextDecoder(encoding).decode(sliced) + return bytes } +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string /** - * @see https://encoding.spec.whatwg.org/#bom-sniff - * @param {Uint8Array} ioQueue + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue */ -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' - } +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position - return null -} + // 2. Let value be the empty string. + let value = '' -/** - * @param {Uint8Array[]} sequences - */ -function combineByteSequences (sequences) { - const size = sequences.reduce((a, b) => { - return a + b.byteLength - }, 0) + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') - let offset = 0 + // 4. Advance position by 1. + position.position++ - return sequences.reduce((a, b) => { - a.set(b, offset) - offset += b.byteLength - return a - }, new Uint8Array(size)) -} + // 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 + ) -module.exports = { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent -} + // 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++ -/***/ 21892: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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 + } -"use strict"; + // 2. Append the code point at position within input to value. + value += input[position.position] + // 3. Advance position by 1. + position.position++ -// 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) + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') -if (getGlobalDispatcher() === undefined) { - setGlobalDispatcher(new Agent()) -} + // 2. Break. + break + } + } -function setGlobalDispatcher (agent) { - if (!agent || typeof agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument agent must implement Agent') + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value } - Object.defineProperty(globalThis, globalDispatcher, { - value: agent, - writable: true, - enumerable: false, - configurable: false - }) -} -function getGlobalDispatcher () { - return globalThis[globalDispatcher] + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) } -module.exports = { - setGlobalDispatcher, - getGlobalDispatcher -} +/** + * @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 += ';' -/***/ 46930: -/***/ ((module) => { + // 2. Append name to serialization. + serialization += name -"use strict"; + // 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') -module.exports = class DecoratorHandler { - constructor (handler) { - this.handler = handler - } + // 2. Prepend U+0022 (") to value. + value = '"' + value - onConnect (...args) { - return this.handler.onConnect(...args) - } + // 3. Append U+0022 (") to value. + value += '"' + } - onError (...args) { - return this.handler.onError(...args) + // 5. Append value to serialization. + serialization += value } - onUpgrade (...args) { - return this.handler.onUpgrade(...args) - } + // 3. Return serialization. + return serialization +} - onHeaders (...args) { - return this.handler.onHeaders(...args) - } +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ +function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' +} - onData (...args) { - return this.handler.onData(...args) - } +/** + * @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 - onComplete (...args) { - return this.handler.onComplete(...args) + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); } - onBodySent (...args) { - return this.handler.onBodySent(...args) + 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 -/***/ 72860: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + } -"use strict"; + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } + return str.slice(lead, trail + 1) +} -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) +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} -const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] -const kBody = Symbol('body') +/***/ }), -class BodyAsyncIterable { - constructor (body) { - this[kBody] = body - this[kBodyUsed] = false - } +/***/ 8511: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - async * [Symbol.asyncIterator] () { - assert(!this[kBodyUsed], 'disturbed') - this[kBodyUsed] = true - yield * this[kBody] - } -} +"use strict"; -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) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) +const { types } = __nccwpck_require__(3837) +const { kState } = __nccwpck_require__(5861) +const { isBlobLike } = __nccwpck_require__(2538) +const { webidl } = __nccwpck_require__(1744) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(685) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const encoder = new TextEncoder() - 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 = [] +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' }) - 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) - }) - } + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) - 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) - } - } + // 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 - onConnect (abort) { - this.abort = abort - this.handler.onConnect(abort, { history: this.history }) - } + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: - onUpgrade (statusCode, headers, socket) { - this.handler.onUpgrade(statusCode, headers, socket) - } + // 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 - onError (error) { - this.handler.onError(error) - } + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) - onHeaders (statusCode, headers, resume, statusText) { - this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) - ? null - : parseLocation(statusCode, headers) + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep + } - if (this.opts.origin) { - this.history.push(new URL(this.opts.path, this.opts.origin)) - } + t = serializeAMimeType(t).toLowerCase() + } - if (!this.location) { - return this.handler.onHeaders(statusCode, headers, resume, statusText) + // 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 } - 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 + // 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. - // 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 + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t } } - onData (chunk) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 + get name () { + webidl.brandCheck(this, File) - TLDR: undici always ignores 3xx response bodies. + return this[kState].name + } - 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. + get lastModified () { + webidl.brandCheck(this, File) - 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. + return this[kState].lastModified + } - 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) - } + get type () { + webidl.brandCheck(this, File) + + return this[kState].type } +} - onComplete (trailers) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check - TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections - and neither are useful if present. + // 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: - See comment on onData method above for more detailed informations. - */ + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. - this.location = null - this.abort = null + // 2. Let n be the fileName argument to the constructor. + const n = fileName - this.dispatch(this.opts, this) - } else { - this.handler.onComplete(trailers) - } - } + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: - onBodySent (chunk) { - if (this.handler.onBodySent) { - this.handler.onBodySent(chunk) - } - } -} + // 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 -function parseLocation (statusCode, headers) { - if (redirectableStatusCodes.indexOf(statusCode) === -1) { - return null - } + // 2. Convert every character in t to ASCII lowercase. + // TODO - for (let i = 0; i < headers.length; i += 2) { - if (headers[i].toString().toLowerCase() === 'location') { - return headers[i + 1] - } - } -} + // 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() -// https://tools.ietf.org/html/rfc7231#section-6.4.4 -function shouldRemoveHeader (header, removeContent, unknownOrigin) { - if (header.length === 4) { - return util.headerNameToString(header) === 'host' - } - if (removeContent && util.headerNameToString(header).startsWith('content-')) { - return true - } - if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { - const name = util.headerNameToString(header) - return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' - } - return false -} + // 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. -// 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]) - } + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d } - } else { - assert(headers == null, 'headers must be an object or an array') } - return ret -} -module.exports = RedirectHandler + stream (...args) { + webidl.brandCheck(this, FileLike) + return this[kState].blobLike.stream(...args) + } -/***/ }), + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) -/***/ 82286: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return this[kState].blobLike.arrayBuffer(...args) + } -const assert = __nccwpck_require__(39491) + slice (...args) { + webidl.brandCheck(this, FileLike) -const { kRetryHandlerDefaultRetry } = __nccwpck_require__(72785) -const { RequestRetryError } = __nccwpck_require__(48045) -const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(83983) + return this[kState].blobLike.slice(...args) + } -function calculateRetryAfterHeader (retryAfter) { - const current = Date.now() - const diff = new Date(retryAfter).getTime() - current + text (...args) { + webidl.brandCheck(this, FileLike) - return diff -} + return this[kState].blobLike.text(...args) + } -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 ?? {} + get size () { + webidl.brandCheck(this, FileLike) - 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' - ] - } + return this[kState].blobLike.size + } - this.retryCount = 0 - this.start = 0 - this.end = null - this.etag = null - this.resume = null + get type () { + webidl.brandCheck(this, FileLike) - // Handle possible onConnect duplication - this.handler.onConnect(reason => { - this.aborted = true - if (this.abort) { - this.abort(reason) - } else { - this.reason = reason - } - }) + return this[kState].blobLike.type } - onRequestSent () { - if (this.handler.onRequestSent) { - this.handler.onRequestSent() - } - } + get name () { + webidl.brandCheck(this, FileLike) - onUpgrade (statusCode, headers, socket) { - if (this.handler.onUpgrade) { - this.handler.onUpgrade(statusCode, headers, socket) - } + return this[kState].name } - onConnect (abort) { - if (this.aborted) { - abort(this.reason) - } else { - this.abort = abort - } - } + get lastModified () { + webidl.brandCheck(this, FileLike) - onBodySent (chunk) { - if (this.handler.onBodySent) return this.handler.onBodySent(chunk) + return this[kState].lastModified } - 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 + get [Symbol.toStringTag] () { + return 'File' + } +} - currentTimeout = - currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout +Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty +}) - // 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 - } +webidl.converters.Blob = webidl.interfaceConverter(Blob) - // 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 +webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) } - // 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) + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) ) { - cb(err) - return + return webidl.converters.BufferSource(V, opts) } + } - // If we reached the max number of retries - if (counter > maxRetries) { - cb(err) - return - } + return webidl.converters.USVString(V, opts) +} - let retryAfterHeader = headers != null && headers['retry-after'] - if (retryAfterHeader) { - retryAfterHeader = Number(retryAfterHeader) - retryAfterHeader = isNaN(retryAfterHeader) - ? calculateRetryAfterHeader(retryAfterHeader) - : retryAfterHeader * 1e3 // Retry-After is in seconds - } +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart +) - const retryTimeout = - retryAfterHeader > 0 - ? Math.min(retryAfterHeader, maxTimeout) - : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) +// 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() - state.currentTimeout = retryTimeout + if (value !== 'native') { + value = 'transparent' + } - setTimeout(() => cb(null), retryTimeout) + return value + }, + defaultValue: 'transparent' } +]) - 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 - } +/** + * @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 = [] - // Checkpoint for resume from where we left it - if (this.resume != null) { - this.resume = null + // 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 - if (statusCode !== 206) { - return true + // 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) } - const contentRange = parseRangeHeader(headers['content-range']) - // If no content range - if (!contentRange) { - this.abort( - new RequestRetryError('Content-Range mismatch', statusCode, { - headers, - count: this.retryCount - }) + // 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) ) - return false } + } 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' + ) + ) +} - // 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 - } +module.exports = { File, FileLike, isFileLike } - 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 - } +/***/ 2015: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.end == null) { - if (statusCode === 206) { - // First time we receive 206 - const range = parseRangeHeader(headers['content-range']) +"use strict"; - if (range == null) { - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } - const { start, size, end = size } = range +const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(2538) +const { kState } = __nccwpck_require__(5861) +const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(8511) +const { webidl } = __nccwpck_require__(1744) +const { Blob, File: NativeFile } = __nccwpck_require__(4300) - 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' - ) +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile - this.start = start - this.end = end - } +// 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'] + }) + } - // 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 - } + this[kState] = [] + } - assert(Number.isFinite(this.start)) - assert( - this.end == null || Number.isFinite(this.end), - 'invalid content-length' - ) + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) - this.resume = resume - this.etag = headers.etag != null ? headers.etag : null + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" ) } - const err = new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) + // 1. Let value be value if given; otherwise blobValue. - this.abort(err) + 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 - return false + // 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) } - onData (chunk) { - this.start += chunk.length + delete (name) { + webidl.brandCheck(this, FormData) - return this.handler.onData(chunk) - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) - onComplete (rawTrailers) { - this.retryCount = 0 - return this.handler.onComplete(rawTrailers) + 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) } - onError (err) { - if (this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) + 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 } - this.retryOpts.retry( - err, - { - state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, - opts: { retryOptions: this.retryOpts, ...this.opts } - }, - onRetry.bind(this) - ) + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } - function onRetry (err) { - if (err != null || this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } + getAll (name) { + webidl.brandCheck(this, FormData) - if (this.start !== 0) { - this.opts = { - ...this.opts, - headers: { - ...this.opts.headers, - range: `bytes=${this.start}-${this.end ?? ''}` - } - } - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) - try { - this.dispatch(this.opts, this) - } catch (err) { - this.handler.onError(err) - } - } + 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) } -} -module.exports = RetryHandler + has (name) { + webidl.brandCheck(this, FormData) + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) -/***/ }), + name = webidl.converters.USVString(name) -/***/ 38861: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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 + } -"use strict"; + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) -const RedirectHandler = __nccwpck_require__(72860) + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } -function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { - return (dispatch) => { - return function Intercept (opts, handler) { - const { maxRedirections = defaultMaxRedirections } = opts + // The set(name, value) and set(name, blobValue, filename) method steps + // are: - if (!maxRedirections) { - return dispatch(opts, handler) - } + // 1. Let value be value if given; otherwise blobValue. - const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) - opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. - return dispatch(opts, redirectHandler) + 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) } } -} -module.exports = createRedirectInterceptor + 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' + ) + } -/***/ 30953: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + values () { + webidl.brandCheck(this, FormData) -"use strict"; + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } -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); + /** + * @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]) + } + } } -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 + +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 */ -exports.HEADER_CHARS = ['\t']; -for (let i = 32; i <= 255; i++) { - if (i !== 127) { - exports.HEADER_CHARS.push(i); +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 } } -// ',' = \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 + +module.exports = { FormData } + /***/ }), -/***/ 61145: +/***/ 1246: /***/ ((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=' +"use strict"; -/***/ }), +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') -/***/ 95627: -/***/ ((module) => { +function getGlobalOrigin () { + return globalThis[globalOrigin] +} -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==' +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + return + } -/***/ }), + const parsedURL = new URL(newOrigin) -/***/ 41891: -/***/ ((__unused_webpack_module, exports) => { + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } -"use strict"; + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} -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; +module.exports = { + getGlobalOrigin, + setGlobalOrigin } -exports.enumToMap = enumToMap; -//# sourceMappingURL=utils.js.map + /***/ }), -/***/ 66771: +/***/ 554: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch -const { kClients } = __nccwpck_require__(72785) -const Agent = __nccwpck_require__(7890) + +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const { kGuard } = __nccwpck_require__(5861) +const { kEnumerableProperty } = __nccwpck_require__(3983) 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) + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = __nccwpck_require__(2538) +const util = __nccwpck_require__(3837) +const { webidl } = __nccwpck_require__(1744) +const assert = __nccwpck_require__(9491) -class FakeWeakRef { - constructor (value) { - this.value = value - } +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') - deref () { - return this.value - } +/** + * @param {number} code + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 } -class MockAgent extends Dispatcher { - constructor (opts) { - super(opts) +/** + * @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 - this[kNetConnect] = true - this[kIsMockActive] = true + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i - // Instantiate Agent and encapsulate - if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') + 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]) } - const agent = opts && opts.agent ? opts.agent : new Agent(opts) - this[kAgent] = agent + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw - this[kClients] = agent[kClients] - this[kOptions] = buildMockOptions(opts) + // 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'] + }) } +} - get (origin) { - let dispatcher = this[kMockAgentGet](origin) +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) - if (!dispatcher) { - dispatcher = this[kFactory](origin) - this[kMockAgentSet](origin, dispatcher) - } - return dispatcher + // 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' + }) } - dispatch (opts, handler) { - // Call MockAgent.get to perform additional setup before dispatching as normal - this.get(opts.origin) - return this[kAgent].dispatch(opts, handler) + // 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 } - async close () { - await this[kAgent].close() - this[kClients].clear() + // 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 + } } - deactivate () { - this[kIsMockActive] = false + // 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) } - activate () { - this[kIsMockActive] = true + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null } - 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 + // 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 { - throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + this.cookies ??= [] + this.cookies.push(value) } } - disableNetConnect () { - this[kNetConnect] = false + // 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 }) } - // This is required to bypass issues caused by using global symbols - see: - // https://github.com/nodejs/undici/issues/1447 - get isMockActive () { - return this[kIsMockActive] + // 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) } - [kMockAgentSet] (origin, dispatcher) { - this[kClients].set(origin, new FakeWeakRef(dispatcher)) + // 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 } - [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) + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } } - [kMockAgentGet] (origin) { - // First check if we can immediately find it - const ref = this[kClients].get(origin) - if (ref) { - return ref.deref() + get entries () { + const headers = {} + + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value + } } - // 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 + return headers + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + if (init === kConstruct) { + return } + this[kHeadersList] = new HeadersList() - // 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 - } + // 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) } } - [kGetNetConnect] () { - return this[kNetConnect] + // 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) } - pendingInterceptors () { - const mockAgentClients = this[kClients] + // 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 + } - return Array.from(mockAgentClients.entries()) - .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) - .filter(({ pending }) => pending) + // 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) } - assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { - const pending = this.pendingInterceptors() + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) - if (pending.length === 0) { - return - } + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) - const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) + name = webidl.converters.ByteString(name) - throw new UndiciError(` -${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + // 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' + }) + } -${pendingInterceptorsFormatter.format(pending)} -`.trim()) + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) } -} -module.exports = MockAgent + // 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) -/***/ 58687: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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' + }) + } -"use strict"; + // 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) -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) + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) -/** - * MockClient provides an API that extends the Client to influence the mockDispatches. - */ -class MockClient extends Client { - constructor (origin, opts) { - super(origin, opts) + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') + // 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' + }) } - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) + // 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 + } - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] + // 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) } - get [Symbols.kConnected] () { - return this[kConnected] - } + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) - } + // 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. - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + const list = this[kHeadersList].cookies + + if (list) { + return [...list] + } + + return [] } -} -module.exports = MockClient + // 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 -/***/ 50888: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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. -"use strict"; + // 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. -const { UndiciError } = __nccwpck_require__(48045) + // 2. Assert: value is non-null. + assert(value !== null) -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' - } -} + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } -module.exports = { - MockNotMatchedError -} + this[kHeadersList][kHeadersSortedMap] = headers + // 4. Return headers. + return headers + } -/***/ }), + keys () { + webidl.brandCheck(this, Headers) -/***/ 90410: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key') + } -"use strict"; + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } + values () { + webidl.brandCheck(this, Headers) -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) + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'value') + } -/** - * Defines the scope API for an interceptor reply - */ -class MockScope { - constructor (mockDispatch) { - this[kMockDispatch] = mockDispatch + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) } - /** - * 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') + entries () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key+value') } - this[kMockDispatch].delay = waitInMs - return this + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) } /** - * For a defined reply, never mark as consumed. + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg */ - persist () { - this[kMockDispatch].persist = true - return this - } + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) - /** - * 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') + 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'." + ) } - this[kMockDispatch].times = repeatTimes - return this + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, 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() - } + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) - this[kDispatchKey] = buildKey(opts) - this[kDispatches] = mockDispatches - this[kDefaultHeaders] = {} - this[kDefaultTrailers] = {} - this[kContentLength] = false + return this[kHeadersList] } +} - 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 } +Headers.prototype[Symbol.iterator] = Headers.prototype.entries - return { statusCode, data, headers, trailers } +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 + }, + [util.inspect.custom]: { + enumerable: false } +}) - 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') +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) } - /** - * 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) + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} - // Check if it is in the right format - if (typeof resolvedData !== 'object') { - throw new InvalidArgumentError('reply options callback must return an object') - } +module.exports = { + fill, + Headers, + HeadersList +} - 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) +/***/ 4881: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) - } +"use strict"; +// https://github.com/Ethan-Arrowood/undici-fetch - /** - * 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') - } +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = __nccwpck_require__(7823) +const { Headers } = __nccwpck_require__(554) +const { Request, makeRequest } = __nccwpck_require__(8359) +const zlib = __nccwpck_require__(9796) +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__(2538) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const assert = __nccwpck_require__(9491) +const { safelyExtractBody } = __nccwpck_require__(1472) +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = __nccwpck_require__(1037) +const { kHeadersList } = __nccwpck_require__(2785) +const EE = __nccwpck_require__(2361) +const { Readable, pipeline } = __nccwpck_require__(2781) +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3983) +const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(685) +const { TransformStream } = __nccwpck_require__(5356) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { webidl } = __nccwpck_require__(1744) +const { STATUS_CODES } = __nccwpck_require__(3685) +const GET_OR_HEAD = ['GET', 'HEAD'] - this[kDefaultHeaders] = headers - return this - } +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream - /** - * Set default reply trailers on the interceptor for subsequent replies - */ - defaultReplyTrailers (trailers) { - if (typeof trailers === 'undefined') { - throw new InvalidArgumentError('trailers must be defined') - } +class Fetch extends EE { + constructor (dispatcher) { + super() - this[kDefaultTrailers] = trailers - return this + 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) } - /** - * Set reply content length header for replies on the interceptor - */ - replyContentLength () { - this[kContentLength] = true - return this - } -} + terminate (reason) { + if (this.state !== 'ongoing') { + return + } -module.exports.MockInterceptor = MockInterceptor -module.exports.MockScope = MockScope + 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' -/***/ 26193: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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') + } -"use strict"; + // 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 -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) + this.connection?.destroy(error) + this.emit('terminated', error) + } +} -/** - * MockPool provides an API that extends the Pool to influence the mockDispatches. - */ -class MockPool extends Pool { - constructor (origin, opts) { - super(origin, opts) +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } + // 1. Let p be a new promise. + const p = createDeferredPromise() - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) + // 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 - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise } - get [Symbols.kConnected] () { - return this[kConnected] - } + // 3. Let request be requestObject’s request. + const request = requestObject[kState] - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) - } + // 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) - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + // 2. Return p. + return p.promise } -} -module.exports = MockPool + // 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 -/***/ 24347: -/***/ ((module) => { + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null -"use strict"; + // 9. Let locallyAborted be false. + let locallyAborted = false + // 10. Let controller be null. + let controller = null -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') -} + // 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) -/***/ 79323: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) + } + ) -"use strict"; + // 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 { 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) + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() + } -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 -} + // 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. -function lowerCaseEntries (headers) { - return Object.fromEntries( - Object.entries(headers).map(([headerName, headerValue]) => { - return [headerName.toLocaleLowerCase(), headerValue] - }) - ) -} + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. -/** - * @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] - } + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return Promise.resolve() } - return undefined - } else if (typeof headers.get === 'function') { - return headers.get(key) - } else { - return lowerCaseEntries(headers)[key.toLocaleLowerCase()] - } -} + // 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() + } -/** @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) -} + // 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 -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 + // 5. Resolve p with responseObject. + p.resolve(responseObject) } - for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { - const headerValue = getHeaderByName(headers, matchHeaderName) + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) - if (!matchValue(matchHeaderValue, headerValue)) { - return false - } - } - return true + // 14. Return p. + return p.promise } -function safeUrl (path) { - if (typeof path !== 'string') { - return path +// 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 } - const pathSegments = path.split('?') - - if (pathSegments.length !== 2) { - return path + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return } - 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 -} + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] -function getResponseData (data) { - if (Buffer.isBuffer(data)) { - return data - } else if (typeof data === 'object') { - return JSON.stringify(data) - } else { - return data.toString() - } -} + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo -function getMockDispatch (mockDispatches, key) { - const basePath = key.query ? buildURL(key.path, key.query) : key.path - const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState - // 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}'`) + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return } - // 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}'`) + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return } - // 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}'`) - } + // 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 + }) - // 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}'`) + // 2. Set cacheState to the empty string. + cacheState = '' } - return matchedMockDispatches[0] -} + // 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() -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 -} + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo -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) - } + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) } -function buildKey (opts) { - const { path, method, body, headers, query } = opts - return { - path, - method, - body, - headers, - query +// 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) } } -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) +// 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') } - 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++ + // 1. Reject promise with error. + p.reject(error) - // 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) } + // 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 + }) } - // 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 + // 3. If responseObject is null, then return. + if (responseObject == null) { + return } - // Handle the request with a delay if necessary - if (typeof delay === 'number' && delay > 0) { - setTimeout(() => { - handleReply(this[kDispatches]) - }, delay) - } else { - handleReply(this[kDispatches]) + // 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 + }) } +} - 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 +// 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 - // 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 - } + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false - const responseData = getResponseData(body) - const responseHeaders = generateKeyValues(headers) - const responseTrailers = generateKeyValues(trailers) + // 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 - handler.abort = nop - handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) - handler.onData(Buffer.from(responseData)) - handler.onComplete(responseTrailers) - deleteMockDispatch(mockDispatches, key) + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability } - function resume () {} - - return true -} + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO -function buildMockDispatch () { - const agent = this[kMockAgent] - const origin = this[kOrigin] - const originalDispatch = this[kOriginalDispatch] + // 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 + }) - 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) - } + // 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 } -} -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 -} + // 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) -function buildMockOptions (opts) { - if (opts) { - const { agent, ...mockOptions } = opts - return mockOptions + // 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' } -} -module.exports = { - getResponseData, - getMockDispatch, - addMockDispatch, - deleteMockDispatch, - buildKey, - generateKeyValues, - matchValue, - getResponse, - getStatusText, - mockDispatch, - buildMockDispatch, - checkNetConnect, - buildMockOptions, - getHeaderByName -} + // 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() + } + } -/***/ 86823: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' -"use strict"; + // 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) + } -const { Transform } = __nccwpck_require__(12781) -const { Console } = __nccwpck_require__(96206) + // 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', '*') + } -/** - * 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) - } - }) + // 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 + } - this.logger = new Console({ - stdout: this.transform, - inspectOptions: { - colors: !disableColors && !process.env.CI - } - }) + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO } - 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 - })) + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) - this.logger.table(withPrettyHeaders) - return this.transform.read().toString() - } + // 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 -/***/ }), - -/***/ 78891: -/***/ ((module) => { + // 2. Let response be null. + let response = null -"use strict"; + // 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 -const singulars = { - pronoun: 'it', - is: 'is', - was: 'was', - this: 'this' -} + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) -const plurals = { - pronoun: 'they', - is: 'are', - was: 'were', - this: 'these' -} + // 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? -module.exports = class Pluralizer { - constructor (singular, plural) { - this.singular = singular - this.plural = plural + // 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 } - pluralize (count) { - const one = count === 1 - const keys = one ? singulars : plurals - const noun = one ? this.singular : this.plural - return { ...keys, count, noun } + // 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 -/***/ 68266: -/***/ ((module) => { + // 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) -"use strict"; -/* eslint-disable */ + 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"') + } -// Extracted from node/lib/internal/fixed_queue.js + // 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' + ) + } -// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. -const kSize = 2048; -const kMask = kSize - 1; + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' -// 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. + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } -class FixedCircularBuffer { - constructor() { - this.bottom = 0; - this.top = 0; - this.list = new Array(kSize); - this.next = null; - } + // 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') + } - isEmpty() { - return this.top === this.bottom; - } + // - 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 - isFull() { - return ((this.top + 1) & kMask) === this.bottom; + // 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) + })() } - push(data) { - this.list[this.top] = data; - this.top = (this.top + 1) & kMask; + // 12. If recursive is true, then return response. + if (recursive) { + return response } - 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; + // 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) + } } -} -module.exports = class FixedQueue { - constructor() { - this.head = this.tail = new FixedCircularBuffer(); + // 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) } - isEmpty() { - return this.head.isEmpty(); + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true } - 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); + // 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() } - 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; + // 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 + } -/***/ 73198: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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 + } -"use strict"; + // 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) + } -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) + // 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) + } +} -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') +// 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)) + } -class PoolBase extends DispatcherBase { - constructor () { - super() + // 2. Let request be fetchParams’s request. + const { request } = fetchParams - this[kQueue] = new FixedQueue() - this[kClients] = [] - this[kQueued] = 0 + const { protocol: scheme } = requestCurrentURL(request) - const pool = this + // 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. - this[kOnDrain] = function onDrain (origin, targets) { - const queue = pool[kQueue] + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = (__nccwpck_require__(4300).resolveObjectURL) + } - let needDrain = false + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) - while (!needDrain) { - const item = queue.shift() - if (!item) { - break - } - pool[kQueued]-- - needDrain = !this.dispatch(item.opts, item.handler) + // 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.')) } - this[kNeedDrain] = needDrain + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) - if (!this[kNeedDrain] && pool[kNeedDrain]) { - pool[kNeedDrain] = false - pool.emit('drain', origin, [pool, ...targets]) + // 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')) } - if (pool[kClosedResolve] && queue.isEmpty()) { - Promise - .all(pool[kClients].map(c => c.close())) - .then(pool[kClosedResolve]) - } - } + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) - this[kOnConnect] = (origin, targets) => { - pool.emit('connect', origin, [pool, ...targets]) - } + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] - this[kOnDisconnect] = (origin, targets, err) => { - pool.emit('disconnect', origin, [pool, ...targets], err) - } + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) - this[kOnConnectionError] = (origin, targets, err) => { - pool.emit('connectionError', origin, [pool, ...targets], err) - } + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' - this[kStats] = new PoolStats(this) - } + // 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 }] + ] + }) - get [kBusy] () { - return this[kNeedDrain] - } + response.body = body - get [kConnected] () { - return this[kClients].filter(client => client[kConnected]).length - } + 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) - get [kFree] () { - return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length - } + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } - get [kPending] () { - let ret = this[kQueued] - for (const { [kPending]: pending } of this[kClients]) { - ret += pending - } - return ret - } + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) - get [kRunning] () { - let ret = 0 - for (const { [kRunning]: running } of this[kClients]) { - ret += running + // 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] + })) } - return ret - } + 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. - get [kSize] () { - let ret = this[kQueued] - for (const { [kSize]: size } of this[kClients]) { - ret += size + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) } - return ret } +} - get stats () { - return this[kStats] - } +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true - async [kClose] () { - if (this[kQueue].isEmpty()) { - return Promise.all(this[kClients].map(c => c.close())) - } else { - return new Promise((resolve) => { - this[kClosedResolve] = resolve - }) - } + // 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)) } +} - async [kDestroy] (err) { - while (true) { - const item = this[kQueue].shift() - if (!item) { - break - } - item.handler.onError(err) - } +// 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]] - return Promise.all(this[kClients].map(c => c.destroy(err))) + // 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 + }) } - [kDispatch] (opts, handler) { - const dispatcher = this[kGetDispatcher]() + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true - 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]() + // 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)) } + } - return !this[kNeedDrain] + // 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)) } - [kAddClient] (client) { - client - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', this[kOnDisconnect]) - .on('connectionError', this[kOnConnectionError]) + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: - this[kClients].push(client) + // 1. Let transformStream be a new a TransformStream. - if (this[kNeedDrain]) { - process.nextTick(() => { - if (this[kNeedDrain]) { - this[kOnDrain](client[kUrl], [this, client]) - } - }) + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) } - return this - } - - [kRemoveClient] (client) { - client.close(() => { - const idx = this[kClients].indexOf(client) - if (idx !== -1) { - this[kClients].splice(idx, 1) + // 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 } }) - 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] + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) } } - get queued () { - return this[kPool][kQueued] - } + // 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) - get running () { - return this[kPool][kRunning] - } + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) - get size () { - return this[kPool][kSize] + // 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() } } -module.exports = PoolStats - +// 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 -/***/ 4634: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 3. Let actualResponse be null. + let actualResponse = null -"use strict"; + // 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 + } -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) + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO -const kOptions = Symbol('options') -const kConnections = Symbol('connections') -const kFactory = Symbol('factory') + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } -function defaultFactory (origin, opts) { - return new Client(origin, opts) -} + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) -class Pool extends PoolBase { - constructor (origin, { - connections, - factory = defaultFactory, - connect, - connectTimeout, - tls, - maxCachedSessions, - socketPath, - autoSelectFamily, - autoSelectFamilyAttemptTimeout, - allowH2, - ...options - } = {}) { - super() + // 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') + } - if (connections != null && (!Number.isFinite(connections) || connections < 0)) { - throw new InvalidArgumentError('invalid connections') + // 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 } + } - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') + // 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() } - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') + // 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) } + } - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) - } + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo - 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 + // 10. Return response. + return response +} - this.on('connectionError', (origin, targets, error) => { - // If a connection error occurs, we remove the client from the pool, - // and emit a connectionError event. They will not be re-used. - // Fixes https://github.com/nodejs/undici/issues/3895 - for (const target of targets) { - // Do not use kRemoveClient here, as it will close the client, - // but the client cannot be closed in this state. - const idx = this[kClients].indexOf(target) - if (idx !== -1) { - this[kClients].splice(idx, 1) - } - } - }) - } +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request - [kGetDispatcher] () { - let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + // 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 - if (dispatcher) { - return dispatcher - } + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL - if (!this[kConnections] || this[kClients].length < this[kConnections]) { - dispatcher = this[kFactory](this[kUrl], this[kOptions]) - this[kAddClient](dispatcher) + 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)) + } - return dispatcher + // 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')) } -} -module.exports = Pool + // 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"')) + } -/***/ 97858: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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"' + )) + } -"use strict"; + // 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 -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) + // 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) + } + } -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') + // 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') -function defaultProtocolPort (protocol) { - return protocol === 'https:' ? 443 : 80 -} + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) -function buildProxyOptions (opts) { - if (typeof opts === 'string') { - opts = { uri: opts } + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') } - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') + // 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] } - return { - uri: opts.uri, - protocol: opts.protocol || 'https' + // 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 } -} -function defaultFactory (origin, opts) { - return new Pool(origin, opts) + // 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) } -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 - : [] +// 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 - if (typeof opts === 'string') { - opts = { uri: opts } - } + // 2. Let httpFetchParams be null. + let httpFetchParams = null - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') - } + // 3. Let httpRequest be null. + let httpRequest = null - const { clientFactory = defaultFactory } = opts + // 4. Let response be null. + let response = null - if (typeof clientFactory !== 'function') { - throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') - } + // 5. Let storedResponse be null. + // TODO: cache - this[kRequestTls] = opts.requestTls - this[kProxyTls] = opts.proxyTls - this[kProxyHeaders] = opts.headers || {} + // 6. Let httpCache be null. + const httpCache = null - const resolvedUrl = new URL(opts.uri) - const { origin, port, host, username, password } = resolvedUrl + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false - 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')}` - } + // 8. Run these steps, but abort when the ongoing fetch is terminated: - 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) - } - } - }) - } + // 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: - 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 - ) - } + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) - async [kClose] () { - await this[kAgent].close() - await this[kClient].close() - } + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } - async [kDestroy] () { - await this[kAgent].destroy() - await this[kClient].destroy() + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest } -} - -/** - * @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] - } + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') - return headersPair - } + // 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 - return headers -} + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null -/** - * @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') + // 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' } -} -module.exports = ProxyAgent + // 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. -/***/ 29459: -/***/ ((module) => { + // 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. + } -"use strict"; + // 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) -let fastNow = Date.now() -let fastNowTimeout + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) -const fastTimers = [] + // 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') + } -function onTimeout () { - fastNow = Date.now() + // 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' + } - let len = fastTimers.length - let idx = 0 - while (idx < len) { - const timer = fastTimers[idx] + // 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') + } - if (timer.state === 0) { - timer.state = fastNow + timer.delay - } else if (timer.state > 0 && fastNow >= timer.state) { - timer.state = -1 - timer.callback(timer.opaque) + // 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') } - if (timer.state === -1) { - timer.state = -2 - if (idx !== len - 1) { - fastTimers[idx] = fastTimers.pop() - } else { - fastTimers.pop() - } - len -= 1 - } else { - idx += 1 + // 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') } } - 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() - } + // 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') } -} -class Timeout { - constructor (callback, delay, opaque) { - this.callback = callback - this.delay = delay - this.opaque = opaque + // 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') + } + } - // -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 + httpRequest.headersList.delete('host') - this.refresh() + // 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 } - refresh () { - if (this.state === -2) { - fastTimers.push(this) - if (!fastNowTimeout || fastTimers.length === 1) { - refreshTimeout() - } - } + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication - this.state = 0 + // 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' } - clear () { - this.state = -1 + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache } -} -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) + // 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 + } -/***/ 35354: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } -"use strict"; + // 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 + } + } -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) + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] -const channels = {} -channels.open = diagnosticsChannel.channel('undici:websocket:open') -channels.close = diagnosticsChannel.channel('undici:websocket:close') -channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true + } -/** @type {import('crypto')} */ -let crypto -try { - crypto = __nccwpck_require__(6113) -} catch { + // 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 -/** - * @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 + // 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() + } - requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + // 2. ??? - // 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' - }) + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } - // Note: undici extension, allow setting custom headers. - if (options.headers) { - const headersList = new Headers(options.headers)[kHeadersList] + // 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? - request.headersList = headersList + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') } - // 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 + // 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: - // 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') + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } - // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s - // header list. - request.headersList.append('sec-websocket-key', keyValue) + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. - // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s - // header list. - request.headersList.append('sec-websocket-version', '13') + // 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() - // 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) + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) } - // 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' + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } - // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to - // request’s header list. - // request.headersList.append('sec-websocket-extensions', permessageDeflate) + // 18. Return response. + return response +} - // 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 - } +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) - // 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 + 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')) } + } + } - // 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. + // 1. Let request be fetchParams’s request. + const request = fetchParams.request - // 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 - } + // 2. Let response be null. + let response = null - // 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 - } + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo - // 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 - } + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null - // 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') + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } - if (secExtension !== null && secExtension !== permessageDeflate) { - failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') - return - } + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO - // 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') + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars - if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { - failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') - return - } + // 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 + } - response.socket.on('data', onSocketData) - response.socket.on('close', onSocketClose) - response.socket.on('error', onSocketError) + // 9. Run these steps, but abort when the ongoing fetch is terminated: - if (channels.open.hasSubscribers) { - channels.open.publish({ - address: response.socket.address(), - protocol: secProtocol, - extensions: secExtension - }) - } + // 1. If connection is failure, then return a network error. - onEstablish(response) - } - }) + // 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. - return controller -} + // 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. -/** - * @param {Buffer} chunk - */ -function onSocketData (chunk) { - if (!this.ws[kByteParser].write(chunk)) { - this.pause() - } -} + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. -/** - * @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 + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: - // 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] + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] - let code = 1005 - let reason = '' + // - 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. - const result = ws[kByteParser].closingInfo + // - 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). - 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 - } + // - Wait until all the headers are transmitted. - // 1. Change the ready state to CLOSED (3). - ws[kReadyState] = states.CLOSED + // - 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. - // 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 + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. - // 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 the HTTP request results in a TLS client certificate dialog, then: - if (channels.close.hasSubscribers) { - channels.close.publish({ - websocket: ws, - code, - reason - }) - } -} + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. -function onSocketError (error) { - const { ws } = this + // 2. Otherwise, return a network error. - ws[kReadyState] = states.CLOSING + // 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: - if (channels.socketError.hasSubscribers) { - channels.socketError.publish(error) - } + // 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 + } - this.destroy() -} + // 2. Run this step in parallel: transmit bytes. + yield bytes -module.exports = { - establishWebSocketConnection -} + // 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() + } + } -/***/ 19188: -/***/ ((module) => { + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } -"use strict"; + // 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) + } + })() + } -// 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' + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() -const states = { - CONNECTING: 0, - OPEN: 1, - CLOSING: 2, - CLOSED: 3 -} + 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() -const opcodes = { - CONTINUATION: 0x0, - TEXT: 0x1, - BINARY: 0x2, - CLOSE: 0x8, - PING: 0x9, - PONG: 0xA -} + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } -const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + return makeNetworkError(err) + } -const parserStates = { - INFO: 0, - PAYLOADLENGTH_16: 2, - PAYLOADLENGTH_64: 3, - READ_DATA: 4 -} + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() + } -const emptyBuffer = Buffer.allocUnsafe(0) + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } -module.exports = { - uid, - staticPropertyDescriptors, - states, - opcodes, - maxUnsigned16Bit, - parserStates, - emptyBuffer -} + // 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__(5356).ReadableStream) + } -/***/ 52611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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 + } + } + ) -"use strict"; + // 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 } -const { webidl } = __nccwpck_require__(21744) -const { kEnumerableProperty } = __nccwpck_require__(83983) -const { MessagePort } = __nccwpck_require__(71267) + // 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 -/** - * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent - */ -class MessageEvent extends Event { - #eventInit + // 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 - constructor (type, eventInitDict = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) + // 18. If aborted, then: + // TODO - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.MessageEventInit(eventInitDict) + // 19. Run these steps in parallel: - super(type, eventInitDict) + // 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... - this.#eventInit = eventInitDict - } + // 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() - get data () { - webidl.brandCheck(this, MessageEvent) + if (isAborted(fetchParams)) { + break + } - return this.#eventInit.data - } + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err - get origin () { - webidl.brandCheck(this, MessageEvent) + // 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 + } + } - return this.#eventInit.origin - } + 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) - get lastEventId () { - webidl.brandCheck(this, MessageEvent) + finalizeResponse(fetchParams, response) - return this.#eventInit.lastEventId - } + return + } - get source () { - webidl.brandCheck(this, MessageEvent) + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 - return this.#eventInit.source - } + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } - get ports () { - webidl.brandCheck(this, MessageEvent) + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) - if (!Object.isFrozen(this.#eventInit.ports)) { - Object.freeze(this.#eventInit.ports) - } + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } - return this.#eventInit.ports + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } + } } - initMessageEvent ( - type, - bubbles = false, - cancelable = false, - data = null, - origin = '', - lastEventId = '', - source = null, - ports = [] - ) { - webidl.brandCheck(this, MessageEvent) + // 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 - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + // 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 + })) + } + } - return new MessageEvent(type, { - bubbles, cancelable, data, origin, lastEventId, source, ports - }) + // 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() } -} - -/** - * @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) + // 20. Return response. + return response - super(type, eventInitDict) + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher - this.#eventInit = eventInitDict - } + 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, - get wasClean () { - webidl.brandCheck(this, CloseEvent) + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller - return this.#eventInit.wasClean - } + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, - get code () { - webidl.brandCheck(this, CloseEvent) + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } - return this.#eventInit.code - } + let codings = [] + let location = '' - get reason () { - webidl.brandCheck(this, CloseEvent) + const headers = new Headers() - return this.#eventInit.reason - } -} + // 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 + } -// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface -class ErrorEvent extends Event { - #eventInit + 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 + } - constructor (type, eventInitDict) { - webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) + headers[kHeadersList].append(key, val) + } + } - super(type, eventInitDict) + this.body = new Readable({ read: resume }) - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + const decoders = [] - this.#eventInit = eventInitDict - } + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) - get message () { - webidl.brandCheck(this, ErrorEvent) + // 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 + } + } + } - return this.#eventInit.message - } + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) - get filename () { - webidl.brandCheck(this, ErrorEvent) + return true + }, - return this.#eventInit.filename - } + onData (chunk) { + if (fetchParams.controller.dump) { + return + } - get lineno () { - webidl.brandCheck(this, ErrorEvent) + // 1. If one or more bytes have been transmitted from response’s + // message body, then: - return this.#eventInit.lineno - } + // 1. Let bytes be the transmitted bytes. + const bytes = chunk - get colno () { - webidl.brandCheck(this, ErrorEvent) + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. - return this.#eventInit.colno - } + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength - get error () { - webidl.brandCheck(this, ErrorEvent) + // 4. See pullAlgorithm... - return this.#eventInit.error - } -} + return this.body.push(bytes) + }, -Object.defineProperties(MessageEvent.prototype, { - [Symbol.toStringTag]: { - value: 'MessageEvent', - configurable: true - }, - data: kEnumerableProperty, - origin: kEnumerableProperty, - lastEventId: kEnumerableProperty, - source: kEnumerableProperty, - ports: kEnumerableProperty, - initMessageEvent: kEnumerableProperty -}) + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } -Object.defineProperties(CloseEvent.prototype, { - [Symbol.toStringTag]: { - value: 'CloseEvent', - configurable: true - }, - reason: kEnumerableProperty, - code: kEnumerableProperty, - wasClean: kEnumerableProperty -}) + fetchParams.controller.ended = true -Object.defineProperties(ErrorEvent.prototype, { - [Symbol.toStringTag]: { - value: 'ErrorEvent', - configurable: true - }, - message: kEnumerableProperty, - filename: kEnumerableProperty, - lineno: kEnumerableProperty, - colno: kEnumerableProperty, - error: kEnumerableProperty -}) + this.body.push(null) + }, -webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.MessagePort -) + this.body?.destroy(error) -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 - } -] + fetchParams.controller.terminate(error) -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 [] - } - } -]) + reject(error) + }, -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: '' - } -]) + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } -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 + 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 = { - MessageEvent, - CloseEvent, - ErrorEvent + fetch, + Fetch, + fetching, + finalizeAndReportTiming } /***/ }), -/***/ 25444: +/***/ 8359: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/* globals AbortController */ -const { maxUnsigned16Bit } = __nccwpck_require__(19188) -/** @type {import('crypto')} */ -let crypto -try { - crypto = __nccwpck_require__(6113) -} catch { +const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(1472) +const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(554) +const { FinalizationRegistry } = __nccwpck_require__(6436)() +const util = __nccwpck_require__(3983) +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer, + normalizeMethodRecord +} = __nccwpck_require__(2538) +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = __nccwpck_require__(1037) +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(2361) -} +let TransformStream = globalThis.TransformStream -class WebsocketFrameSend { - /** - * @param {Buffer|undefined} data - */ - constructor (data) { - this.frameData = data - this.maskKey = crypto.randomBytes(4) - } +const kAbortController = Symbol('abortController') - createFrame (opcode) { - const bodyLength = this.frameData?.byteLength ?? 0 +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) - /** @type {number} */ - let payloadLength = bodyLength // 0-125 - let offset = 6 +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kConstruct) { + return + } - 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 + 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() + } } - const buffer = Buffer.allocUnsafe(bodyLength + offset) + // 1. Let request be null. + let request = null - // Clear first 2 bytes, everything else is overwritten - buffer[0] = buffer[1] = 0 - buffer[0] |= 0x80 // FIN - buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + // 2. Let fallbackMode be null. + let fallbackMode = null - /*! 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] + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl - buffer[1] = payloadLength + // 4. Let signal be null. + let signal = null - 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) - } + // 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 }) + } - buffer[1] |= 0x80 // MASK + // 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 + ) + } - // mask body - for (let i = 0; i < bodyLength; i++) { - buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + // 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] } - return buffer - } -} + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin -module.exports = { - WebsocketFrameSend -} + // 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`) + } -/***/ 11688: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } -"use strict"; + // 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 -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) + // 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' + } -// 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 + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false -const channels = {} -channels.ping = diagnosticsChannel.channel('undici:websocket:ping') -channels.pong = diagnosticsChannel.channel('undici:websocket:pong') + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false -class ByteParser extends Writable { - #buffers = [] - #byteOffset = 0 + // 4. Set request’s origin to "client". + request.origin = 'client' - #state = parserStates.INFO + // 5. Set request’s referrer to "client" + request.referrer = 'client' - #info = {} - #fragments = [] + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' - constructor (ws) { - super() + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] - this.ws = ws - } + // 8. Set request’s URL list to Ā« request’s URL Ā». + request.urlList = [request.url] + } - /** - * @param {Buffer} chunk - * @param {() => void} callback - */ - _write (chunk, _, callback) { - this.#buffers.push(chunk) - this.#byteOffset += chunk.length + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer - this.run(callback) - } + // 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 }) + } - /** - * 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() + // 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 } + } + } - const buffer = this.consume(2) + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } - this.#info.fin = (buffer[0] & 0x80) !== 0 - this.#info.opcode = buffer[0] & 0x0F + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } - // 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 + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } - this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } - 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 - } + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } - const payloadLength = buffer[1] & 0x7F + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } - 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 - } + // 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" + ) + } - 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 - } + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } - const body = this.consume(payloadLength) + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } - this.#info.closeInfo = this.parseCloseBody(false, body) + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } - 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) + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method - this.ws[kResponse].socket.write( - closeFrame.createFrame(opcodes.CLOSE), - (err) => { - if (!err) { - this.ws[kSentClose] = true - } - } - ) - } + // 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.`) + } - // 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 + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } - this.end() + // 3. Normalize method. + method = normalizeMethodRecord[method] ?? normalizeMethod(method) - 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" + // 4. Set request’s method to method. + request.method = method + } - const body = this.consume(payloadLength) + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } - if (!this.ws[kReceivedClose]) { - const frame = new WebsocketFrameSend(body) + // 27. Set this’s request to request. + this[kState] = request - this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) + // 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] - if (channels.ping.hasSubscribers) { - channels.ping.publish({ - payload: body - }) - } - } + // 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." + ) + } - this.#state = parserStates.INFO + 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 - if (this.#byteOffset > 0) { - continue - } else { - callback() - return + const acRef = new WeakRef(ac) + const abort = function () { + const ac = acRef.deref() + if (ac !== undefined) { + ac.abort(this.reason) } - } 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 - }) + // 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 {} - if (this.#byteOffset > 0) { - continue - } else { - callback() - return - } - } - } else if (this.#state === parserStates.PAYLOADLENGTH_16) { - if (this.#byteOffset < 2) { - return callback() - } + util.addAbortListener(signal, abort) + requestFinalizer.register(ac, { signal, abort }) + } + } - const buffer = this.consume(2) + // 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] - this.#info.payloadLength = buffer.readUInt16BE(0) - this.#state = parserStates.READ_DATA - } else if (this.#state === parserStates.PAYLOADLENGTH_64) { - if (this.#byteOffset < 8) { - return callback() - } + // 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.` + ) + } - const buffer = this.consume(8) - const upper = buffer.readUInt32BE(0) + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } - // 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 - } + // 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) - const lower = buffer.readUInt32BE(4) + // 3. Empty this’s headers’s header list. + headersList.clear() - 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 + // 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) + } + } - const body = this.consume(this.#info.payloadLength) + // 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 - this.#fragments.push(body) + // 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.') + } - // 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) + // 35. Let initBody be null. + let initBody = null - websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) + // 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 - this.#info = {} - this.#fragments.length = 0 - } + // 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) + } + } - this.#state = parserStates.INFO - } + // 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.') } - if (this.#byteOffset > 0) { - continue - } else { - callback() - break + // 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"' + ) } - } - } - /** - * 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 + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true } - if (this.#buffers[0].length === n) { - this.#byteOffset -= this.#buffers[0].length - return this.#buffers.shift() - } + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody - const buffer = Buffer.allocUnsafe(n) - let offset = 0 + // 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.' + ) + } - while (offset !== n) { - const next = this.#buffers[0] - const { length } = next + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = (__nccwpck_require__(5356).TransformStream) + } - 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 + // 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 } } - this.#byteOffset -= n + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } - return buffer + // 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 } - parseCloseBody (onlyCode, data) { - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 - /** @type {number|undefined} */ - let code + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) - 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) - } + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } - if (onlyCode) { - if (!isValidStatusCode(code)) { - return null - } + // 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) - return { code } - } + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 - /** @type {Buffer} */ - let reason = data.subarray(2) + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) - // Remove BOM - if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { - reason = reason.subarray(3) - } + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } - if (code !== undefined && !isValidStatusCode(code)) { - return null + // 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 '' } - try { - // TODO: optimize this - reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) - } catch { - return null + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' } - return { code, reason } + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() } - get closingInfo () { - return this.#info.closeInfo + // 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 } -} -module.exports = { - ByteParser -} + // 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 + } -/***/ 37578: -/***/ ((module) => { + // 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) -"use strict"; + // 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) -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') -} + // 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] + } -/***/ 25515: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + get body () { + webidl.brandCheck(this, Request) -"use strict"; + return this[kState].body ? this[kState].body.stream : null + } + get bodyUsed () { + webidl.brandCheck(this, Request) -const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(37578) -const { states, opcodes } = __nccwpck_require__(19188) -const { MessageEvent, ErrorEvent } = __nccwpck_require__(52611) + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } -/* globals Blob */ + get duplex () { + webidl.brandCheck(this, Request) -/** - * @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 -} + return 'half' + } -/** - * @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 -} + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) -/** - * @param {import('./websocket').WebSocket} ws - */ -function isClosed (ws) { - return ws[kReadyState] === states.CLOSED -} + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } -/** - * @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 clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) - // 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 + // 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. Initialize any other IDL attributes of event as described in the - // invocation of this algorithm. + // 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 - // 5. Return the result of dispatching event at target, with legacy target - // override flag set if set. - target.dispatchEvent(event) + // 4. Return clonedRequestObject. + return clonedRequestObject + } } -/** - * @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 +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 +} - // 2. Let dataForEvent be determined by switching on type and binary type: - let dataForEvent +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: - 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 - } + // 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. 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 - }) + // 3. Return newRequest. + return newRequest } -/** - * @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 +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 } +}) - for (const char of protocol) { - const code = char.charCodeAt(0) +webidl.converters.Request = webidl.interfaceConverter( + Request +) - 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 - } +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) } - 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" - ) + if (V instanceof Request) { + return webidl.converters.Request(V) } - return code >= 3000 && code <= 4999 + return webidl.converters.USVString(V) } -/** - * @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() - } +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) - if (reason) { - fireEvent('error', ws, ErrorEvent, { - error: new Error(reason) - }) +// 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 = { - isEstablished, - isClosing, - isClosed, - fireEvent, - isValidSubprotocol, - isValidStatusCode, - failWebsocketConnection, - websocketMessageReceived -} +module.exports = { Request, makeRequest } /***/ }), -/***/ 54284: +/***/ 7823: /***/ ((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 { Headers, HeadersList, fill } = __nccwpck_require__(554) +const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(1472) +const util = __nccwpck_require__(3983) +const { kEnumerableProperty } = util 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) + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = __nccwpck_require__(2538) +const { + redirectStatusSet, + nullBodyStatus, + DOMException +} = __nccwpck_require__(1037) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(5861) +const { webidl } = __nccwpck_require__(1744) +const { FormData } = __nccwpck_require__(2015) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { URLSerializer } = __nccwpck_require__(685) +const { kHeadersList, kConstruct } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { types } = __nccwpck_require__(3837) -let experimentalWarned = false +const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(5356).ReadableStream) +const textEncoder = new TextEncoder('utf-8') -// https://websockets.spec.whatwg.org/#interface-definition -class WebSocket extends EventTarget { - #events = { - open: null, - error: null, - close: null, - message: null +// 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 } - #bufferedAmount = 0 - #protocol = '' - #extensions = '' + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) - /** - * @param {string} url - * @param {string|string[]} protocols - */ - constructor (url, protocols = []) { - super() + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } - webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) - if (!experimentalWarned) { - experimentalWarned = true - process.emitWarning('WebSockets are experimental, expect them to change at any time.', { - code: 'UNDICI-WS' - }) - } + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) - const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) + // 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 - url = webidl.converters.USVString(url) - protocols = options.protocols + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) - // 1. Let baseURL be this's relevant settings object's API base URL. - const baseURL = getGlobalOrigin() + // 5. Return responseObject. + return responseObject + } - // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. - let urlRecord + // 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 { - urlRecord = new URL(url, baseURL) - } catch (e) { - // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. - throw new DOMException(e, 'SyntaxError') + parsedURL = new URL(url, getGlobalOrigin()) + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) } - // 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:' + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) } - // 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' - ) - } + // 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 - // 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') - } + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status - // 8. If protocols is a string, set protocols to a sequence consisting - // of just that string. - if (typeof protocols === 'string') { - protocols = [protocols] - } + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) - // 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') - } + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) - if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { - throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') - } + // 8. Return responseObject. + return responseObject + } - // 10. Set this's url to urlRecord. - this[kWebSocketURL] = new URL(urlRecord.href) + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) + } - // 11. Let client be this's relevant settings object. + init = webidl.converters.ResponseInit(init) - // 12. Run this step in parallel: + // TODO + this[kRealm] = { settingsObject: {} } - // 1. Establish a WebSocket connection given urlRecord, protocols, - // and client. - this[kController] = establishWebSocketConnection( - urlRecord, - protocols, - this, - (response) => this.#onConnectionEstablished(response), - options - ) + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) - // 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 + // 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] - // The extensions attribute must initially return the empty string. + // 3. Let bodyWithType be null. + let bodyWithType = null - // The protocol attribute must initially return the empty string. + // 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 } + } - // Each WebSocket object has an associated binary type, which is a - // BinaryType. Initially it must be "blob". - this[kBinaryType] = 'blob' + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) } - /** - * @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 }) - } + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) - if (reason !== undefined) { - reason = webidl.converters.USVString(reason) - } + // The type getter steps are to return this’s response’s type. + return this[kState].type + } - // 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') - } - } + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) - let reasonByteLength = 0 + const urlList = this[kState].urlList - // 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) + // 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 (reasonByteLength > 123) { - throw new DOMException( - `Reason must be less than 123 bytes; received ${reasonByteLength}`, - 'SyntaxError' - ) - } + if (url === null) { + return '' } - // 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. + return URLSerializer(url, true) + } - const frame = new WebsocketFrameSend() + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) - // If neither code nor reason is present, the WebSocket Close - // message must not have a body. + // 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 + } - // 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 - } + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) - /** @type {import('stream').Duplex} */ - const socket = this[kResponse].socket + // The status getter steps are to return this’s response’s status. + return this[kState].status + } - socket.write(frame.createFrame(opcodes.CLOSE), (err) => { - if (!err) { - this[kSentClose] = true - } - }) + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) - // 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 - } + // 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 } - /** - * @see https://websockets.spec.whatwg.org/#dom-websocket-send - * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data - */ - send (data) { - webidl.brandCheck(this, WebSocket) + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) - webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } - data = webidl.converters.WebSocketSendData(data) + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) - // 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') - } + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } - // 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 + get body () { + webidl.brandCheck(this, Response) - if (!isEstablished(this) || isClosing(this)) { - return - } + return this[kState].body ? this[kState].body.stream : null + } - /** @type {import('stream').Duplex} */ - const socket = this[kResponse].socket + get bodyUsed () { + webidl.brandCheck(this, Response) - // 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. + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } - const value = Buffer.from(data) - const frame = new WebsocketFrameSend(value) - const buffer = frame.createFrame(opcodes.TEXT) + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength + // 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.' }) - } 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) + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) - 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. + // 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] - const ab = Buffer.from(data, data.byteOffset, data.byteLength) + return clonedResponseObject + } +} - const frame = new WebsocketFrameSend(ab) - const buffer = frame.createFrame(opcodes.BINARY) +mixinBody(Response) - 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. +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 + } +}) - const frame = new WebsocketFrameSend() +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) - data.arrayBuffer().then((ab) => { - const value = Buffer.from(ab) - frame.frameData = value - const buffer = frame.createFrame(opcodes.BINARY) +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - }) - } + // 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 + ) } - get readyState () { - webidl.brandCheck(this, WebSocket) + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) - // The readyState getter steps are to return this's ready state. - return this[kReadyState] + // 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) } - get bufferedAmount () { - webidl.brandCheck(this, WebSocket) + // 4. Return newResponse. + return newResponse +} - return this.#bufferedAmount +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] : [] } +} - get url () { - webidl.brandCheck(this, WebSocket) +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' + }) +} - // The url getter steps are to return this's url, serialized. - return URLSerializer(this[kWebSocketURL]) +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state } - get extensions () { - webidl.brandCheck(this, WebSocket) + 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 + } + }) +} - return this.#extensions - } +// 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. - get protocol () { - webidl.brandCheck(this, WebSocket) + // 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 this.#protocol + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) } +} - get onopen () { - webidl.brandCheck(this, WebSocket) - - return this.#events.open - } +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) - set onopen (fn) { - webidl.brandCheck(this, WebSocket) + // 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 })) +} - if (this.#events.open) { - this.removeEventListener('open', this.#events.open) - } +// 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.') + } - if (typeof fn === 'function') { - this.#events.open = fn - this.addEventListener('open', fn) - } else { - this.#events.open = null + // 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') } } - get onerror () { - webidl.brandCheck(this, WebSocket) - - return this.#events.error + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status } - 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 - } + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText } - get onclose () { - webidl.brandCheck(this, WebSocket) - - return this.#events.close + // 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) } - set onclose (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.close) { - this.removeEventListener('close', this.#events.close) + // 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 + }) } - if (typeof fn === 'function') { - this.#events.close = fn - this.addEventListener('close', fn) - } else { - this.#events.close = null + // 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) } } +} - get onmessage () { - webidl.brandCheck(this, WebSocket) - - return this.#events.message - } +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) - set onmessage (fn) { - webidl.brandCheck(this, WebSocket) +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) - if (this.#events.message) { - this.removeEventListener('message', this.#events.message) - } +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) - if (typeof fn === 'function') { - this.#events.message = fn - this.addEventListener('message', fn) - } else { - this.#events.message = null - } +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) } - get binaryType () { - webidl.brandCheck(this, WebSocket) - - return this[kBinaryType] + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) } - set binaryType (type) { - webidl.brandCheck(this, WebSocket) - - if (type !== 'blob' && type !== 'arraybuffer') { - this[kBinaryType] = 'blob' - } else { - this[kBinaryType] = type - } + if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + return webidl.converters.BufferSource(V) } - /** - * @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) + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) } -} - -// 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 + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) } -}) -Object.defineProperties(WebSocket, { - CONNECTING: staticPropertyDescriptors, - OPEN: staticPropertyDescriptors, - CLOSING: staticPropertyDescriptors, - CLOSED: staticPropertyDescriptors -}) + return webidl.converters.DOMString(V) +} -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.DOMString -) +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } -webidl.converters['DOMString or sequence'] = function (V) { - if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { - return webidl.converters['sequence'](V) + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V } - return webidl.converters.DOMString(V) + return webidl.converters.XMLHttpRequestBodyInit(V) } -// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 -webidl.converters.WebSocketInit = webidl.dictionaryConverter([ +webidl.converters.ResponseInit = webidl.dictionaryConverter([ { - key: 'protocols', - converter: webidl.converters['DOMString or sequence'], - get defaultValue () { - return [] - } + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 }, { - key: 'dispatcher', - converter: (V) => V, - get defaultValue () { - return getGlobalDispatcher() - } + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' }, { key: 'headers', - converter: webidl.nullableConverter(webidl.converters.HeadersInit) + converter: 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) } +module.exports = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse } -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) - } - } +/***/ }), + +/***/ 5861: +/***/ ((module) => { + +"use strict"; - return webidl.converters.USVString(V) -} module.exports = { - WebSocket + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') } /***/ }), -/***/ 45030: -/***/ ((__unused_webpack_module, exports) => { +/***/ 2538: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(1037) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { performance } = __nccwpck_require__(4074) +const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3983) +const assert = __nccwpck_require__(9491) +const { isUint8Array } = __nccwpck_require__(9830) -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; +let supportedHashes = [] + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = __nccwpck_require__(6113) + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} 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 } - if (typeof process === "object" && process.version !== undefined) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + // 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)) } - return ""; + // 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 } -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map +/** @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' + } -/***/ 65278: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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) +} /** - * For Node.js, simply re-export the core `util.deprecate` function. + * @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 + } -module.exports = __nccwpck_require__(73837).deprecate; + 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. -/***/ 82116: -/***/ ((module) => { + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. -"use strict"; + // 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 + } + } + } -var conversions = {}; -module.exports = conversions; + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} -function sign(x) { - return x < 0 ? -1 : 1; +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' } -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); - } +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' } -function createNumberConversion(bitLength, typeOpts) { - if (!typeOpts.unsigned) { - --bitLength; - } - const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); - const upperBound = Math.pow(2, bitLength) - 1; +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} - 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); +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO - return function(V, opts) { - if (!opts) opts = {}; + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header - let x = +V; + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO - if (opts.enforceRange) { - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite number"); - } + // 2. Let header be a Structured Header whose value is a token. + let header = null - x = sign(x) * Math.floor(Math.abs(x)); - if (x < lowerBound || x > upperBound) { - throw new TypeError("Argument is not in byte range"); - } + // 3. Set header’s value to r’s mode. + header = httpRequest.mode - return x; - } + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) - if (!isNaN(x) && opts.clamp) { - x = evenRound(x); + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO - if (x < lowerBound) x = lowerBound; - if (x > upperBound) x = upperBound; - return x; - } + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} - if (!Number.isFinite(x) || x === 0) { - return 0; - } +// 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 - x = sign(x) * Math.floor(Math.abs(x)); - x = x % moduloVal; + // 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) + } - 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; - } + // 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. + } - return x; + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) } + } } -conversions["void"] = function () { - return undefined; -}; +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} -conversions["boolean"] = function (val) { - return !!val; -}; +// 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 + } +} -conversions["byte"] = createNumberConversion(8, { unsigned: false }); -conversions["octet"] = createNumberConversion(8, { unsigned: true }); +// 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' + } +} -conversions["short"] = createNumberConversion(16, { unsigned: false }); -conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} -conversions["long"] = createNumberConversion(32, { unsigned: false }); -conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); +// 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 -conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); -conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) -conversions["double"] = function (V) { - const x = +V; + // 2. Let environment be request’s client. - if (!Number.isFinite(x)) { - throw new TypeError("Argument is not a finite floating-point value"); - } + let referrerSource = null - return x; -}; + // 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. -conversions["unrestricted double"] = function (V) { - const x = +V; + const globalOrigin = getGlobalOrigin() - if (isNaN(x)) { - throw new TypeError("Argument is NaN"); + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' } - return x; -}; + // 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 + } -// not quite valid, but good enough for JS -conversions["float"] = conversions["double"]; -conversions["unrestricted float"] = conversions["unrestricted double"]; + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) -conversions["DOMString"] = function (V, opts) { - if (!opts) opts = {}; + // 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) - if (opts.treatNullAsEmptyString && V === null) { - return ""; - } + // 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 + } - return String(V); -}; + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) -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"); - } - } + // 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) - return x; -}; + // 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 + } -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)); - } - } - } + // 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 + */ - return U.join(''); -}; + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } +} -conversions["Date"] = function (V, opts) { - if (!(V instanceof Date)) { - throw new TypeError("Argument is not a Date object"); - } - if (isNaN(V)) { - return undefined; - } +/** + * @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) - return V; -}; + // 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' + } -conversions["RegExp"] = function (V, opts) { - if (!(V instanceof RegExp)) { - V = new RegExp(V); - } + // 3. Set url’s username to the empty string. + url.username = '' - return V; -}; + // 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 = '' -/***/ 97537: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 2. Set url’s query to null. + url.search = '' + } -"use strict"; + // 7. Return url. + return url +} -const usm = __nccwpck_require__(2158); +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } -exports.implementation = class URLImpl { - constructor(constructorArgs) { - const url = constructorArgs[0]; - const base = constructorArgs[1]; + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } - let parsedBase = null; - if (base !== undefined) { - parsedBase = usm.basicURLParse(base); - if (parsedBase === "failure") { - throw new TypeError("Invalid base URL"); - } - } + // If scheme is data, return true + if (url.protocol === 'data:') return true - const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); - } + // If file, return true + if (url.protocol === 'file:') return true - this._url = parsedURL; + return isOriginPotentiallyTrustworthy(url.origin) - // TODO: query stuff - } + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false - get href() { - return usm.serializeURL(this._url); - } + const originAsURL = new URL(origin) - set href(v) { - const parsedURL = usm.basicURLParse(v); - if (parsedURL === "failure") { - throw new TypeError("Invalid URL"); + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true } - this._url = parsedURL; - } + // 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 + } - get origin() { - return usm.serializeURLOrigin(this._url); + // If any other, return false + return false } +} - get protocol() { - return this._url.scheme + ":"; +/** + * @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 } - set protocol(v) { - usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); - } + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) - get username() { - return this._url.username; + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true } - set username(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } + // 3. If response is not eligible for integrity validation, return false. + // TODO - usm.setTheUsername(this._url, v); + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true } - get password() { - return this._url.password; - } + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) - set password(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; - } + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo - usm.setThePassword(this._url, v); - } + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash - get host() { - const url = this._url; + // 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 (url.host === null) { - return ""; - } + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') - if (url.port === null) { - return usm.serializeHost(url.host); + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) + } else { + actualValue = actualValue.slice(0, -1) + } } - return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); - } - - set host(v) { - if (this._url.cannotBeABaseURL) { - return; + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true } - - usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); } - get hostname() { - if (this._url.host === null) { - return ""; - } + // 7. Return false. + return false +} - return usm.serializeHost(this._url.host); - } +// 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-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i - set hostname(v) { - if (this._url.cannotBeABaseURL) { - return; - } +/** + * @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 = [] - usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); - } + // 2. Let empty be equal to true. + let empty = true - get port() { - if (this._url.port === null) { - return ""; - } + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false - return usm.serializeInteger(this._url.port); - } + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) - set port(v) { - if (usm.cannotHaveAUsernamePasswordPort(this._url)) { - return; + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === 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 } - if (v === "") { - this._url.port = null; - } else { - usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) } } - get pathname() { - if (this._url.cannotBeABaseURL) { - return this._url.path[0]; - } + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } - if (this._url.path.length === 0) { - return ""; - } + return result +} - return "/" + this._url.path.join("/"); +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm } - set pathname(v) { - if (this._url.cannotBeABaseURL) { - return; + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' } + } + return algorithm +} - this._url.path = []; - usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList } - get search() { - if (this._url.query === null || this._url.query === "") { - return ""; + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] } - - return "?" + this._url.query; } - set search(v) { - // TODO: query stuff - - const url = this._url; + metadataList.length = pos - if (v === "") { - url.query = null; - return; - } + return metadataList +} - const input = v[0] === "?" ? v.substring(1) : v; - url.query = ""; - usm.basicURLParse(input, { url, stateOverride: "query" }); +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false } - - get hash() { - if (this._url.fragment === null || this._url.fragment === "") { - return ""; + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false } - - return "#" + this._url.fragment; } - set hash(v) { - if (v === "") { - this._url.fragment = null; - return; - } + return true +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} - const input = v[0] === "#" ? v.substring(1) : v; - this._url.fragment = ""; - usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); +/** + * @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 } - toJSON() { - return this.href; + // 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' +} -/***/ 63394: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} -"use strict"; +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) -const conversions = __nccwpck_require__(82116); -const utils = __nccwpck_require__(83185); -const Impl = __nccwpck_require__(97537); +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizeMethodRecord[method.toLowerCase()] ?? method +} -const impl = utils.implSymbol; +// 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) -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]); + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') } - module.exports.setup(this, args); + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result } -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 -}); +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) -URL.prototype.toString = function () { - if (!this || !module.exports.is(this)) { - throw new TypeError("Illegal invocation"); +/** + * @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 } - 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 -}); + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. -Object.defineProperty(URL.prototype, "password", { - get() { - return this[impl].password; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].password = V; - }, - enumerable: true, - configurable: true -}); + // 2. Let thisValue be the this value. -Object.defineProperty(URL.prototype, "host", { - get() { - return this[impl].host; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].host = V; - }, - enumerable: true, - configurable: true -}); + // 3. Let object be ? ToObject(thisValue). -Object.defineProperty(URL.prototype, "hostname", { - get() { - return this[impl].hostname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hostname = V; - }, - enumerable: true, - configurable: true -}); + // 4. If object is a platform object, then perform a security + // check, passing: -Object.defineProperty(URL.prototype, "port", { - get() { - return this[impl].port; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].port = V; - }, - enumerable: true, - configurable: true -}); + // 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.` + ) + } -Object.defineProperty(URL.prototype, "pathname", { - get() { - return this[impl].pathname; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].pathname = V; - }, - enumerable: true, - configurable: true -}); + // 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() -Object.defineProperty(URL.prototype, "search", { - get() { - return this[impl].search; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].search = V; - }, - enumerable: true, - configurable: true -}); + // 9. Let len be the length of values. + const len = values.length -Object.defineProperty(URL.prototype, "hash", { - get() { - return this[impl].hash; - }, - set(V) { - V = conversions["USVString"](V); - this[impl].hash = V; - }, - enumerable: true, - configurable: true -}); + // 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] -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; + // 12. Set object’s index to index + 1. + object.index = index + 1 - obj[impl] = new Impl.implementation(constructorArgs, privateData); - obj[impl][utils.wrapperSymbol] = obj; - }, - interface: URL, - expose: { - Window: { URL: URL }, - Worker: { URL: URL } + // 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 + } + } -/***/ 28665: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } +} -"use strict"; +/** + * @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 -exports.URL = __nccwpck_require__(63394)["interface"]; -exports.serializeURL = __nccwpck_require__(2158).serializeURL; -exports.serializeURLOrigin = __nccwpck_require__(2158).serializeURLOrigin; -exports.basicURLParse = __nccwpck_require__(2158).basicURLParse; -exports.setTheUsername = __nccwpck_require__(2158).setTheUsername; -exports.setThePassword = __nccwpck_require__(2158).setThePassword; -exports.serializeHost = __nccwpck_require__(2158).serializeHost; -exports.serializeInteger = __nccwpck_require__(2158).serializeInteger; -exports.parseURL = __nccwpck_require__(2158).parseURL; + // 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 + } -/***/ 2158: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader) + successSteps(result) + } catch (e) { + errorSteps(e) + } +} -"use strict"; - -const punycode = __nccwpck_require__(85477); -const tr46 = __nccwpck_require__(84256); - -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 }); -}; +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(5356).ReadableStream) + } -/***/ }), + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} -/***/ 83185: -/***/ ((module) => { +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. -"use strict"; + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) + } + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') +} -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])); +/** + * @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 + } } -}; +} -module.exports.wrapperSymbol = Symbol("wrapper"); -module.exports.implSymbol = Symbol("impl"); +/** + * @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) + } -module.exports.wrapperForImpl = function (impl) { - return impl[module.exports.wrapperSymbol]; -}; + // 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 +} -module.exports.implForWrapper = function (wrapper) { - return wrapper[module.exports.implSymbol]; -}; +/** + * @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') + } -/***/ 62940: -/***/ ((module) => { + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length -// 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) + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } +} - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) + const protocol = url.protocol - return wrapper + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} - 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 +/** + * @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 -/***/ 9887: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + return protocol === 'http:' || protocol === 'https:' +} -"use strict"; +/** + * 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)) -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.mainRun = mainRun; -const core = __importStar(__nccwpck_require__(42186)); -const commit_use_case_1 = __nccwpck_require__(85016); -const issue_comment_use_case_1 = __nccwpck_require__(50854); -const issue_use_case_1 = __nccwpck_require__(58675); -const pull_request_review_comment_use_case_1 = __nccwpck_require__(67883); -const pull_request_use_case_1 = __nccwpck_require__(53478); -const single_action_use_case_1 = __nccwpck_require__(6479); -const logger_1 = __nccwpck_require__(38836); -const constants_1 = __nccwpck_require__(8593); -const chalk_1 = __importDefault(__nccwpck_require__(77037)); -const boxen_1 = __importDefault(__nccwpck_require__(46192)); -const queue_utils_1 = __nccwpck_require__(99800); -async function mainRun(execution) { - const results = []; - await execution.setup(); - if (!execution.welcome) { - /** - * Wait for previous runs to finish - */ - await (0, queue_utils_1.waitForPreviousRuns)(execution).catch((err) => { - (0, logger_1.logError)(`Error waiting for previous runs: ${err}`); - process.exit(1); - }); - } - if (execution.runnedByToken) { - if (execution.isSingleAction && execution.singleAction.validSingleAction) { - (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Executing single action.`); - results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); - return results; - } - (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Ignoring.`); - return results; - } - if (execution.issueNumber === -1) { - if (execution.isSingleAction && execution.singleAction.isSingleActionWithoutIssue) { - results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); - } - else { - (0, logger_1.logInfo)(`Issue number not found. Skipping.`); - } - return results; - } - if (execution.welcome) { - (0, logger_1.logInfo)((0, boxen_1.default)(chalk_1.default.cyan(execution.welcome.title) + '\n' + - execution.welcome.messages.map(message => chalk_1.default.gray(message)).join('\n'), { - padding: 1, - margin: 1, - borderStyle: 'round', - borderColor: 'cyan', - title: constants_1.TITLE, - titleAlignment: 'center' - })); - } - try { - if (execution.isSingleAction) { - results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); - } - else if (execution.isIssue) { - if (execution.issue.isIssueComment) { - results.push(...await new issue_comment_use_case_1.IssueCommentUseCase().invoke(execution)); - } - else { - results.push(...await new issue_use_case_1.IssueUseCase().invoke(execution)); - } - } - else if (execution.isPullRequest) { - if (execution.pullRequest.isPullRequestReviewComment) { - results.push(...await new pull_request_review_comment_use_case_1.PullRequestReviewCommentUseCase().invoke(execution)); - } - else { - results.push(...await new pull_request_use_case_1.PullRequestUseCase().invoke(execution)); - } - } - else if (execution.isPush) { - results.push(...await new commit_use_case_1.CommitUseCase().invoke(execution)); - } - else { - core.setFailed(`Action not handled.`); - } - return results; - } - catch (error) { - core.setFailed(error.message); - return []; - } +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, + parseMetadata } /***/ }), -/***/ 86925: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 1744: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.runGitHubAction = runGitHubAction; -const core = __importStar(__nccwpck_require__(42186)); -const ai_1 = __nccwpck_require__(64470); -const branches_1 = __nccwpck_require__(45308); -const docker_config_1 = __nccwpck_require__(61684); -const emoji_1 = __nccwpck_require__(9463); -const execution_1 = __nccwpck_require__(87550); -const hotfix_1 = __nccwpck_require__(87341); -const images_1 = __nccwpck_require__(51721); -const issue_1 = __nccwpck_require__(42632); -const issue_types_1 = __nccwpck_require__(71975); -const labels_1 = __nccwpck_require__(10818); -const locale_1 = __nccwpck_require__(82152); -const projects_1 = __nccwpck_require__(1938); -const pull_request_1 = __nccwpck_require__(84179); -const release_1 = __nccwpck_require__(12551); -const single_action_1 = __nccwpck_require__(28024); -const size_threshold_1 = __nccwpck_require__(23835); -const size_thresholds_1 = __nccwpck_require__(98237); -const tokens_1 = __nccwpck_require__(53421); -const workflows_1 = __nccwpck_require__(38553); -const project_repository_1 = __nccwpck_require__(67917); -const publish_resume_use_case_1 = __nccwpck_require__(84462); -const store_configuration_use_case_1 = __nccwpck_require__(69714); -const constants_1 = __nccwpck_require__(8593); -const common_action_1 = __nccwpck_require__(9887); -const supabase_config_1 = __nccwpck_require__(149); -const logger_1 = __nccwpck_require__(38836); -async function runGitHubAction() { - const projectRepository = new project_repository_1.ProjectRepository(); - /** - * Debug - */ - const debug = getInput(constants_1.INPUT_KEYS.DEBUG) == 'true'; - /** - * Docker - */ - const dockerContainerName = getInput(constants_1.INPUT_KEYS.DOCKER_CONTAINER_NAME); - const dockerDomain = getInput(constants_1.INPUT_KEYS.DOCKER_DOMAIN); - const dockerPort = parseInt(getInput(constants_1.INPUT_KEYS.DOCKER_PORT)); - const dockerCacheOs = getInput(constants_1.INPUT_KEYS.DOCKER_CACHE_OS); - const dockerCacheArch = getInput(constants_1.INPUT_KEYS.DOCKER_CACHE_ARCH); - /** - * Single action - */ - const singleAction = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION); - const singleActionIssue = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE); - const singleActionVersion = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION); - const singleActionTitle = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE); - const singleActionChangelog = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG); - /** - * Tokens - */ - const token = getInput(constants_1.INPUT_KEYS.TOKEN, { required: true }); - const classicToken = getInput(constants_1.INPUT_KEYS.CLASSIC_TOKEN); - /** - * AI - */ - const openrouterApiKey = getInput(constants_1.INPUT_KEYS.OPENROUTER_API_KEY); - const openrouterModel = getInput(constants_1.INPUT_KEYS.OPENROUTER_MODEL); - const aiPullRequestDescription = getInput(constants_1.INPUT_KEYS.AI_PULL_REQUEST_DESCRIPTION) === 'true'; - const aiMembersOnly = getInput(constants_1.INPUT_KEYS.AI_MEMBERS_ONLY) === 'true'; - const aiIncludeReasoning = getInput(constants_1.INPUT_KEYS.AI_INCLUDE_REASONING) === 'true'; - const aiIgnoreFilesInput = getInput(constants_1.INPUT_KEYS.AI_IGNORE_FILES); - const aiIgnoreFiles = aiIgnoreFilesInput - .split(',') - .map(path => path.trim()) - .filter(path => path.length > 0); - // Provider routing configuration - const openRouterProviderOrderInput = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER); - const openRouterProviderOrder = openRouterProviderOrderInput - .split(',') - .map(provider => provider.trim()) - .filter(provider => provider.length > 0); - const openRouterProviderAllowFallbacks = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS) === 'true'; - const openRouterProviderRequireParameters = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS) === 'true'; - const openRouterProviderDataCollection = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION); - const openRouterProviderIgnoreInput = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE); - const openRouterProviderIgnore = openRouterProviderIgnoreInput - .split(',') - .map(provider => provider.trim()) - .filter(provider => provider.length > 0); - const openRouterProviderQuantizationsInput = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS); - const openRouterProviderQuantizations = openRouterProviderQuantizationsInput - .split(',') - .map(level => level.trim()) - .filter(level => level.length > 0); - const openRouterProviderSort = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT); - const providerRouting = { - ...(openRouterProviderOrder.length > 0 && { order: openRouterProviderOrder }), - ...(openRouterProviderAllowFallbacks !== undefined && { allow_fallbacks: openRouterProviderAllowFallbacks }), - ...(openRouterProviderRequireParameters !== undefined && { require_parameters: openRouterProviderRequireParameters }), - ...(openRouterProviderDataCollection && { data_collection: openRouterProviderDataCollection }), - ...(openRouterProviderIgnore.length > 0 && { ignore: openRouterProviderIgnore }), - ...(openRouterProviderQuantizations.length > 0 && { quantizations: openRouterProviderQuantizations }), - ...(openRouterProviderSort && { sort: openRouterProviderSort }) - }; - /** - * Projects Details - */ - const projectIdsInput = getInput(constants_1.INPUT_KEYS.PROJECT_IDS); - const projectIds = projectIdsInput - .split(',') - .map(id => id.trim()) - .filter(id => id.length > 0); - const projects = []; - for (const projectId of projectIds) { - const detail = await projectRepository.getProjectDetail(projectId, token); - projects.push(detail); - } - const projectColumnIssueCreated = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_CREATED); - const projectColumnPullRequestCreated = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_CREATED); - const projectColumnIssueInProgress = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_IN_PROGRESS); - const projectColumnPullRequestInProgress = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS); - /** - * Images - */ - const imagesOnIssue = getInput(constants_1.INPUT_KEYS.IMAGES_ON_ISSUE) === 'true'; - const imagesOnPullRequest = getInput(constants_1.INPUT_KEYS.IMAGES_ON_PULL_REQUEST) === 'true'; - const imagesOnCommit = getInput(constants_1.INPUT_KEYS.IMAGES_ON_COMMIT) === 'true'; - const imagesIssueAutomaticInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_AUTOMATIC); - const imagesIssueAutomatic = imagesIssueAutomaticInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueAutomatic.length === 0) { - imagesIssueAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.automatic); - } - const imagesIssueFeatureInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_FEATURE); - const imagesIssueFeature = imagesIssueFeatureInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueFeature.length === 0) { - imagesIssueFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.feature); - } - const imagesIssueBugfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_BUGFIX); - const imagesIssueBugfix = imagesIssueBugfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueBugfix.length === 0) { - imagesIssueBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.bugfix); - } - const imagesIssueDocsInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_DOCS); - const imagesIssueDocs = imagesIssueDocsInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueDocs.length === 0) { - imagesIssueDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.docs); - } - const imagesIssueChoreInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_CHORE); - const imagesIssueChore = imagesIssueChoreInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueChore.length === 0) { - imagesIssueChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.chore); - } - const imagesIssueReleaseInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_RELEASE); - const imagesIssueRelease = imagesIssueReleaseInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueRelease.length === 0) { - imagesIssueRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.release); - } - const imagesIssueHotfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_HOTFIX); - const imagesIssueHotfix = imagesIssueHotfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesIssueHotfix.length === 0) { - imagesIssueHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.hotfix); - } - const imagesPullRequestAutomaticInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_AUTOMATIC); - const imagesPullRequestAutomatic = imagesPullRequestAutomaticInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestAutomatic.length === 0) { - imagesPullRequestAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.automatic); - } - const imagesPullRequestFeatureInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_FEATURE); - const imagesPullRequestFeature = imagesPullRequestFeatureInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestFeature.length === 0) { - imagesPullRequestFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.feature); + +const { types } = __nccwpck_require__(3837) +const { hasOwn, toUSVString } = __nccwpck_require__(2538) + +/** @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' } - const imagesPullRequestBugfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_BUGFIX); - const imagesPullRequestBugfix = imagesPullRequestBugfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestBugfix.length === 0) { - imagesPullRequestBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.bugfix); + } +} + +// 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 } - const imagesPullRequestReleaseInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_RELEASE); - const imagesPullRequestRelease = imagesPullRequestReleaseInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestRelease.length === 0) { - imagesPullRequestRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.release); + } 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.` + }) } - const imagesPullRequestHotfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_HOTFIX); - const imagesPullRequestHotfix = imagesPullRequestHotfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestHotfix.length === 0) { - imagesPullRequestHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.hotfix); + + // 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}.` + }) } - const imagesPullRequestDocsInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_DOCS); - const imagesPullRequestDocs = imagesPullRequestDocsInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestDocs.length === 0) { - imagesPullRequestDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.docs); + + // 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) } - const imagesPullRequestChoreInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_CHORE); - const imagesPullRequestChore = imagesPullRequestChoreInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesPullRequestChore.length === 0) { - imagesPullRequestChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.chore); + + // 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.` + }) } - const imagesCommitAutomaticInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_AUTOMATIC); - const imagesCommitAutomatic = imagesCommitAutomaticInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitAutomatic.length === 0) { - imagesCommitAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.automatic); + + // 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.' + }) } - const imagesCommitFeatureInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_FEATURE); - const imagesCommitFeature = imagesCommitFeatureInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitFeature.length === 0) { - imagesCommitFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.feature); + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value)) } - const imagesCommitBugfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_BUGFIX); - const imagesCommitBugfix = imagesCommitBugfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitBugfix.length === 0) { - imagesCommitBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.bugfix); + + 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.` + }) } - const imagesCommitReleaseInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_RELEASE); - const imagesCommitRelease = imagesCommitReleaseInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitRelease.length === 0) { - imagesCommitRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.release); + + // 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 } - const imagesCommitHotfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_HOTFIX); - const imagesCommitHotfix = imagesCommitHotfixInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitHotfix.length === 0) { - imagesCommitHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.hotfix); + + // 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 + } } - const imagesCommitDocsInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_DOCS); - const imagesCommitDocs = imagesCommitDocsInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitDocs.length === 0) { - imagesCommitDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.docs); + + // 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}.` + }) } - const imagesCommitChoreInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_CHORE); - const imagesCommitChore = imagesCommitChoreInput - .split(',') - .map(url => url.trim()) - .filter(url => url.length > 0); - if (imagesCommitChore.length === 0) { - imagesCommitChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.chore); + + 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.` + }) } - /** - * Workflows - */ - const releaseWorkflow = getInput(constants_1.INPUT_KEYS.RELEASE_WORKFLOW); - const hotfixWorkflow = getInput(constants_1.INPUT_KEYS.HOTFIX_WORKFLOW); - /** - * Emoji-title - */ - const titleEmoji = getInput(constants_1.INPUT_KEYS.EMOJI_LABELED_TITLE) === 'true'; - const branchManagementEmoji = getInput(constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_EMOJI); - /** - * Labels - */ - const branchManagementLauncherLabel = getInput(constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_LAUNCHER_LABEL); - const bugfixLabel = getInput(constants_1.INPUT_KEYS.BUGFIX_LABEL); - const bugLabel = getInput(constants_1.INPUT_KEYS.BUG_LABEL); - const hotfixLabel = getInput(constants_1.INPUT_KEYS.HOTFIX_LABEL); - const enhancementLabel = getInput(constants_1.INPUT_KEYS.ENHANCEMENT_LABEL); - const featureLabel = getInput(constants_1.INPUT_KEYS.FEATURE_LABEL); - const releaseLabel = getInput(constants_1.INPUT_KEYS.RELEASE_LABEL); - const questionLabel = getInput(constants_1.INPUT_KEYS.QUESTION_LABEL); - const helpLabel = getInput(constants_1.INPUT_KEYS.HELP_LABEL); - const deployLabel = getInput(constants_1.INPUT_KEYS.DEPLOY_LABEL); - const deployedLabel = getInput(constants_1.INPUT_KEYS.DEPLOYED_LABEL); - const docsLabel = getInput(constants_1.INPUT_KEYS.DOCS_LABEL); - const documentationLabel = getInput(constants_1.INPUT_KEYS.DOCUMENTATION_LABEL); - const choreLabel = getInput(constants_1.INPUT_KEYS.CHORE_LABEL); - const maintenanceLabel = getInput(constants_1.INPUT_KEYS.MAINTENANCE_LABEL); - const priorityHighLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_HIGH_LABEL); - const priorityMediumLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_MEDIUM_LABEL); - const priorityLowLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_LOW_LABEL); - const priorityNoneLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_NONE_LABEL); - const sizeXxlLabel = getInput(constants_1.INPUT_KEYS.SIZE_XXL_LABEL); - const sizeXlLabel = getInput(constants_1.INPUT_KEYS.SIZE_XL_LABEL); - const sizeLLabel = getInput(constants_1.INPUT_KEYS.SIZE_L_LABEL); - const sizeMLabel = getInput(constants_1.INPUT_KEYS.SIZE_M_LABEL); - const sizeSLabel = getInput(constants_1.INPUT_KEYS.SIZE_S_LABEL); - const sizeXsLabel = getInput(constants_1.INPUT_KEYS.SIZE_XS_LABEL); - /** - * Issue Types - */ - const issueTypeBug = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_BUG); - const issueTypeBugDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_DESCRIPTION); - const issueTypeBugColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_COLOR); - const issueTypeHotfix = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX); - const issueTypeHotfixDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_DESCRIPTION); - const issueTypeHotfixColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_COLOR); - const issueTypeFeature = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE); - const issueTypeFeatureDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_DESCRIPTION); - const issueTypeFeatureColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_COLOR); - const issueTypeDocumentation = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION); - const issueTypeDocumentationDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_DESCRIPTION); - const issueTypeDocumentationColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_COLOR); - const issueTypeMaintenance = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE); - const issueTypeMaintenanceDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_DESCRIPTION); - const issueTypeMaintenanceColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_COLOR); - const issueTypeRelease = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE); - const issueTypeReleaseDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_DESCRIPTION); - const issueTypeReleaseColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_COLOR); - const issueTypeQuestion = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION); - const issueTypeQuestionDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_DESCRIPTION); - const issueTypeQuestionColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_COLOR); - const issueTypeHelp = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HELP); - const issueTypeHelpDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_DESCRIPTION); - const issueTypeHelpColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_COLOR); - const issueTypeTask = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_TASK); - const issueTypeTaskDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_DESCRIPTION); - const issueTypeTaskColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_COLOR); - /** - * Locale - */ - const issueLocale = getInput(constants_1.INPUT_KEYS.ISSUES_LOCALE) ?? locale_1.Locale.DEFAULT; - const pullRequestLocale = getInput(constants_1.INPUT_KEYS.PULL_REQUESTS_LOCALE) ?? locale_1.Locale.DEFAULT; - /** - * Size Thresholds - */ - const sizeXxlThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_LINES)) ?? 1000; - const sizeXxlThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_FILES)) ?? 20; - const sizeXxlThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_COMMITS)) ?? 10; - const sizeXlThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_LINES)) ?? 500; - const sizeXlThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_FILES)) ?? 10; - const sizeXlThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_COMMITS)) ?? 5; - const sizeLThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_LINES)) ?? 250; - const sizeLThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_FILES)) ?? 5; - const sizeLThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_COMMITS)) ?? 3; - const sizeMThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_LINES)) ?? 100; - const sizeMThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_FILES)) ?? 3; - const sizeMThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_COMMITS)) ?? 2; - const sizeSThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_LINES)) ?? 50; - const sizeSThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_FILES)) ?? 2; - const sizeSThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_COMMITS)) ?? 1; - const sizeXsThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_LINES)) ?? 25; - const sizeXsThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_FILES)) ?? 1; - const sizeXsThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_COMMITS)) ?? 1; - /** - * Branches - */ - const mainBranch = getInput(constants_1.INPUT_KEYS.MAIN_BRANCH); - const developmentBranch = getInput(constants_1.INPUT_KEYS.DEVELOPMENT_BRANCH); - const featureTree = getInput(constants_1.INPUT_KEYS.FEATURE_TREE); - const bugfixTree = getInput(constants_1.INPUT_KEYS.BUGFIX_TREE); - const hotfixTree = getInput(constants_1.INPUT_KEYS.HOTFIX_TREE); - const releaseTree = getInput(constants_1.INPUT_KEYS.RELEASE_TREE); - const docsTree = getInput(constants_1.INPUT_KEYS.DOCS_TREE); - const choreTree = getInput(constants_1.INPUT_KEYS.CHORE_TREE); - /** - * Prefix builder - */ - let commitPrefixBuilder = getInput(constants_1.INPUT_KEYS.COMMIT_PREFIX_TRANSFORMS) ?? ''; - if (commitPrefixBuilder.length === 0) { - commitPrefixBuilder = 'replace-slash'; + + 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 + } } - /** - * Issue - */ - const branchManagementAlways = getInput(constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_ALWAYS) === 'true'; - const reopenIssueOnPush = getInput(constants_1.INPUT_KEYS.REOPEN_ISSUE_ON_PUSH) === 'true'; - const issueDesiredAssigneesCount = parseInt(getInput(constants_1.INPUT_KEYS.DESIRED_ASSIGNEES_COUNT)) ?? 0; - /** - * Pull Request - */ - const pullRequestDesiredAssigneesCount = parseInt(getInput(constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_ASSIGNEES_COUNT)) ?? 0; - const pullRequestDesiredReviewersCount = parseInt(getInput(constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_REVIEWERS_COUNT)) ?? 0; - const pullRequestMergeTimeout = parseInt(getInput(constants_1.INPUT_KEYS.PULL_REQUEST_MERGE_TIMEOUT)) ?? 0; - /** - * Supabase - */ - const supabaseUrl = getInput(constants_1.INPUT_KEYS.SUPABASE_URL); - const supabaseKey = getInput(constants_1.INPUT_KEYS.SUPABASE_KEY); - let supabaseConfig = undefined; - if (supabaseUrl.length > 0 && supabaseKey.length > 0) { - supabaseConfig = new supabase_config_1.SupabaseConfig(supabaseUrl, supabaseKey); + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V } - const execution = new execution_1.Execution(debug, new docker_config_1.DockerConfig(dockerContainerName, dockerDomain, dockerPort, dockerCacheOs, dockerCacheArch), new single_action_1.SingleAction(singleAction, singleActionIssue, singleActionVersion, singleActionTitle, singleActionChangelog), commitPrefixBuilder, new issue_1.Issue(branchManagementAlways, reopenIssueOnPush, issueDesiredAssigneesCount), new pull_request_1.PullRequest(pullRequestDesiredAssigneesCount, pullRequestDesiredReviewersCount, pullRequestMergeTimeout), new emoji_1.Emoji(titleEmoji, branchManagementEmoji), new images_1.Images(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, imagesIssueAutomatic, imagesIssueFeature, imagesIssueBugfix, imagesIssueDocs, imagesIssueChore, imagesIssueRelease, imagesIssueHotfix, imagesPullRequestAutomatic, imagesPullRequestFeature, imagesPullRequestBugfix, imagesPullRequestRelease, imagesPullRequestHotfix, imagesPullRequestDocs, imagesPullRequestChore, imagesCommitAutomatic, imagesCommitFeature, imagesCommitBugfix, imagesCommitRelease, imagesCommitHotfix, imagesCommitDocs, imagesCommitChore), new tokens_1.Tokens(token, classicToken), new ai_1.Ai(openrouterApiKey, openrouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, Object.keys(providerRouting).length > 0 ? providerRouting : undefined), new labels_1.Labels(branchManagementLauncherLabel, bugLabel, bugfixLabel, hotfixLabel, enhancementLabel, featureLabel, releaseLabel, questionLabel, helpLabel, deployLabel, deployedLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel, priorityHighLabel, priorityMediumLabel, priorityLowLabel, priorityNoneLabel, sizeXxlLabel, sizeXlLabel, sizeLLabel, sizeMLabel, sizeSLabel, sizeXsLabel), new issue_types_1.IssueTypes(issueTypeTask, issueTypeTaskDescription, issueTypeTaskColor, issueTypeBug, issueTypeBugDescription, issueTypeBugColor, issueTypeFeature, issueTypeFeatureDescription, issueTypeFeatureColor, issueTypeDocumentation, issueTypeDocumentationDescription, issueTypeDocumentationColor, issueTypeMaintenance, issueTypeMaintenanceDescription, issueTypeMaintenanceColor, issueTypeHotfix, issueTypeHotfixDescription, issueTypeHotfixColor, issueTypeRelease, issueTypeReleaseDescription, issueTypeReleaseColor, issueTypeQuestion, issueTypeQuestionDescription, issueTypeQuestionColor, issueTypeHelp, issueTypeHelpDescription, issueTypeHelpColor), new locale_1.Locale(issueLocale, pullRequestLocale), new size_thresholds_1.SizeThresholds(new size_threshold_1.SizeThreshold(sizeXxlThresholdLines, sizeXxlThresholdFiles, sizeXxlThresholdCommits), new size_threshold_1.SizeThreshold(sizeXlThresholdLines, sizeXlThresholdFiles, sizeXlThresholdCommits), new size_threshold_1.SizeThreshold(sizeLThresholdLines, sizeLThresholdFiles, sizeLThresholdCommits), new size_threshold_1.SizeThreshold(sizeMThresholdLines, sizeMThresholdFiles, sizeMThresholdCommits), new size_threshold_1.SizeThreshold(sizeSThresholdLines, sizeSThresholdFiles, sizeSThresholdCommits), new size_threshold_1.SizeThreshold(sizeXsThresholdLines, sizeXsThresholdFiles, sizeXsThresholdCommits)), new branches_1.Branches(mainBranch, developmentBranch, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree), new release_1.Release(), new hotfix_1.Hotfix(), new workflows_1.Workflows(releaseWorkflow, hotfixWorkflow), new projects_1.Projects(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress), supabaseConfig, undefined, undefined); - const results = await (0, common_action_1.mainRun)(execution); - await finishWithResults(execution, results); + + 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 +} + + +/***/ }), + +/***/ 4854: +/***/ ((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' + } } -async function finishWithResults(execution, results) { - execution.currentConfiguration.results = results; - await new publish_resume_use_case_1.PublishResultUseCase().invoke(execution); - await new store_configuration_use_case_1.StoreConfigurationUseCase().invoke(execution); - /** - * If a single action is executed and the last step failed, throw an error - */ - if (execution.isSingleAction && execution.singleAction.throwError) { - setFirstErrorIfExists(results); - } + +module.exports = { + getEncoding } -function getInput(key, options) { - try { - const inputVarsJson = process.env.INPUT_VARS_JSON; - if (inputVarsJson) { - const inputVars = JSON.parse(inputVarsJson); - const value = inputVars[`INPUT_${key.toUpperCase()}`]; - if (value !== undefined) { - return value; - } - } + + +/***/ }), + +/***/ 1446: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = __nccwpck_require__(7530) +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = __nccwpck_require__(9054) +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) + +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 } - catch (error) { - (0, logger_1.logError)(`Error parsing INPUT_VARS_JSON: ${JSON.stringify(error, null, 2)}`); + } + + /** + * @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) } - // Fallback to core.getInput - return core.getInput(key, options); -} -function setFirstErrorIfExists(results) { - for (const result of results) { - if (result.errors && result.errors.length > 0) { - core.setFailed(result.errors[0]); - return; - } + + // 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 } -} -runGitHubAction(); + // 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 -/***/ 64470: -/***/ ((__unused_webpack_module, exports) => { + // 4. Terminate the algorithm for the read method being processed. + // TODO -"use strict"; + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Ai = void 0; -class Ai { - constructor(openRouterApiKey, openRouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, providerRouting) { - this.openRouterApiKey = openRouterApiKey; - this.openRouterModel = openRouterModel; - this.aiPullRequestDescription = aiPullRequestDescription; - this.aiMembersOnly = aiMembersOnly; - this.aiIgnoreFiles = aiIgnoreFiles; - this.aiIncludeReasoning = aiIncludeReasoning; - this.providerRouting = providerRouting || {}; + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) } - getOpenRouterApiKey() { - return this.openRouterApiKey; + } + + /** + * @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 } - getAiPullRequestDescription() { - return this.aiPullRequestDescription; + } + + /** + * @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) } - getAiMembersOnly() { - return this.aiMembersOnly; + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null } - getAiIgnoreFiles() { - return this.aiIgnoreFiles; + } + + 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) } - getAiIncludeReasoning() { - return this.aiIncludeReasoning; + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null } - getOpenRouterModel() { - return this.openRouterModel; + } + + 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) } - getProviderRouting() { - return this.providerRouting; + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null } -} -exports.Ai = Ai; + } + get onprogress () { + webidl.brandCheck(this, FileReader) -/***/ }), + return this[kEvents].progress + } -/***/ 12141: -/***/ ((__unused_webpack_module, exports) => { + set onprogress (fn) { + webidl.brandCheck(this, FileReader) -"use strict"; + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BranchConfiguration = void 0; -class BranchConfiguration { - constructor(data) { - this.name = data['name'] ?? ''; - this.oid = data['oid'] ?? ''; - this.children = []; - if (data['children'] !== undefined && data['children'].length > 0) { - for (let child of data['children']) { - this.children.push(new BranchConfiguration(child)); - } - } + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null } -} -exports.BranchConfiguration = BranchConfiguration; + } + get onload () { + webidl.brandCheck(this, FileReader) -/***/ }), + return this[kEvents].load + } -/***/ 45308: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + set onload (fn) { + webidl.brandCheck(this, FileReader) -"use strict"; + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } -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]; } }; + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Branches = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class Branches { - get defaultBranch() { - return github.context.payload.repository?.default_branch ?? ''; + } + + 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) } - constructor(main, development, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree) { - this.main = main; - this.development = development; - this.featureTree = featureTree; - this.bugfixTree = bugfixTree; - this.hotfixTree = hotfixTree; - this.releaseTree = releaseTree; - this.docsTree = docsTree; - this.choreTree = choreTree; + + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null } + } } -exports.Branches = Branches; +// 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 -/***/ }), - -/***/ 2469: -/***/ ((__unused_webpack_module, exports) => { +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 + } +}) -"use strict"; +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChunkedFile = void 0; -class ChunkedFile { - constructor(path, index, type, content, shasum, chunks) { - this.shasum = ''; - this.vector = []; - this.path = path; - this.index = index; - this.content = content; - this.chunks = chunks; - this.shasum = shasum; - this.type = type; - } +module.exports = { + FileReader } -exports.ChunkedFile = ChunkedFile; /***/ }), -/***/ 64370: -/***/ ((__unused_webpack_module, exports) => { +/***/ 5504: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ChunkedFileChunk = void 0; -class ChunkedFileChunk { - constructor(owner, repository, branch, path, type, index, chunkIndex, chunk, shasum, vector) { - this.shasum = ''; - this.vector = []; - this.owner = owner; - this.repository = repository; - this.branch = branch; - this.path = path; - this.type = type; - this.index = index; - this.chunkIndex = chunkIndex; - this.chunk = chunk; - this.shasum = shasum; - this.vector = vector; - } -} -exports.ChunkedFileChunk = ChunkedFileChunk; +const { webidl } = __nccwpck_require__(1744) -/***/ }), +const kState = Symbol('ProgressEvent state') -/***/ 83993: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) -"use strict"; + super(type, eventInitDict) -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Commit = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class Commit { - constructor(inputs = undefined) { - this.inputs = undefined; - this.inputs = inputs; - } - get branchReference() { - return this.inputs?.commits?.ref ?? github.context.payload.ref ?? ''; - } - get branch() { - return this.branchReference.replace('refs/heads/', ''); - } - get commits() { - return github.context.payload.commits || []; + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total } -} -exports.Commit = Commit; - - -/***/ }), + } -/***/ 41106: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) -"use strict"; + return this[kState].lengthComputable + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Config = void 0; -const branch_configuration_1 = __nccwpck_require__(12141); -class Config { - constructor(data) { - this.results = []; - this.branchType = data['branchType'] ?? ''; - this.hotfixOriginBranch = data['hotfixOriginBranch']; - this.hotfixBranch = data['hotfixBranch']; - this.releaseBranch = data['releaseBranch']; - this.parentBranch = data['parentBranch']; - this.workingBranch = data['workingBranch']; - if (data['branchConfiguration'] !== undefined) { - this.branchConfiguration = new branch_configuration_1.BranchConfiguration(data['branchConfiguration']); - } - } -} -exports.Config = Config; + get loaded () { + webidl.brandCheck(this, ProgressEvent) + return this[kState].loaded + } -/***/ }), + get total () { + webidl.brandCheck(this, ProgressEvent) -/***/ 61684: -/***/ ((__unused_webpack_module, exports) => { + return this[kState].total + } +} -"use strict"; +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 + } +]) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DockerConfig = void 0; -class DockerConfig { - constructor(containerName, domain, port, cacheOs, cacheArch) { - this.containerName = containerName; - this.domain = domain; - this.port = port; - this.cacheOs = cacheOs; - this.cacheArch = cacheArch; - } - getContainerName() { - return this.containerName; - } - getDomain() { - return this.domain; - } - getPort() { - return this.port; - } - getCacheOs() { - return this.cacheOs; - } - getCacheArch() { - return this.cacheArch; - } +module.exports = { + ProgressEvent } -exports.DockerConfig = DockerConfig; /***/ }), -/***/ 9463: -/***/ ((__unused_webpack_module, exports) => { +/***/ 9054: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Emoji = void 0; -class Emoji { - constructor(emojiLabeledTitle, branchManagementEmoji) { - this.emojiLabeledTitle = emojiLabeledTitle; - this.branchManagementEmoji = branchManagementEmoji; - } + +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') } -exports.Emoji = Emoji; /***/ }), -/***/ 87550: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 7530: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Execution = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const configuration_handler_1 = __nccwpck_require__(34509); -const get_hotfix_version_use_case_1 = __nccwpck_require__(8243); -const get_release_type_use_case_1 = __nccwpck_require__(35966); -const get_release_version_use_case_1 = __nccwpck_require__(3827); -const constants_1 = __nccwpck_require__(8593); -const label_utils_1 = __nccwpck_require__(31479); -const logger_1 = __nccwpck_require__(38836); -const title_utils_1 = __nccwpck_require__(26676); -const version_utils_1 = __nccwpck_require__(29887); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const commit_1 = __nccwpck_require__(83993); -const config_1 = __nccwpck_require__(41106); -class Execution { - get eventName() { - return this.inputs?.eventName ?? github.context.eventName; - } - get actor() { - return this.inputs?.actor ?? github.context.actor; - } - get isSingleAction() { - return this.singleAction.enabledSingleAction; - } - get isIssue() { - return this.issue.isIssue || this.issue.isIssueComment || this.singleAction.isIssue; - } - get isPullRequest() { - return this.pullRequest.isPullRequest || this.pullRequest.isPullRequestReviewComment || this.singleAction.isPullRequest; - } - get isPush() { - return this.eventName === 'push'; - } - get repo() { - return this.inputs?.repo?.repo ?? github.context.repo.repo; - } - get owner() { - return this.inputs?.repo?.owner ?? github.context.repo.owner; - } - get isFeature() { - return this.issueType === this.branches.featureTree; - } - get isBugfix() { - return this.issueType === this.branches.bugfixTree; - } - get isDocs() { - return this.issueType === this.branches.docsTree; - } - get isChore() { - return this.issueType === this.branches.choreTree; - } - get isBranched() { - return this.issue.branchManagementAlways || - this.labels.containsBranchedLabel || - this.labels.isMandatoryBranchedLabel; - } - get issueNotBranched() { - return this.isIssue && !this.isBranched; - } - get managementBranch() { - return (0, label_utils_1.branchesForManagement)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); - } - get issueType() { - return (0, label_utils_1.typesForIssue)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); - } - get cleanIssueBranches() { - return this.isIssue - && this.previousConfiguration !== undefined - && this.previousConfiguration?.branchType != this.currentConfiguration.branchType; - } - get commit() { - return new commit_1.Commit(this.inputs); - } - get runnedByToken() { - return this.tokenUser === this.actor; - } - constructor(debug, dockerConfig, singleAction, commitPrefixBuilder, issue, pullRequest, emoji, giphy, tokens, ai, labels, issueTypes, locale, sizeThresholds, branches, release, hotfix, workflows, project, supabaseConfig, welcome, inputs) { - this.debug = false; - /** - * Every usage of this field should be checked. - * PRs with no issue ID in the head branch won't have it. - * - * master <- develop - */ - this.issueNumber = -1; - this.commitPrefixBuilderParams = {}; - this.setup = async () => { - (0, logger_1.setGlobalLoggerDebug)(this.debug, this.inputs === undefined); - const issueRepository = new issue_repository_1.IssueRepository(); - const projectRepository = new project_repository_1.ProjectRepository(); - this.tokenUser = await projectRepository.getUserFromToken(this.tokens.token); - if (!this.tokenUser) { - throw new Error('Failed to get user from token'); - } - /** - * Set the issue number - */ - if (this.isSingleAction) { - /** - * Single actions can run as isolated processes or as part of a workflow. - * In the case of a workflow, the issue number is got from the workflow. - * In the case of a single action, the issue number is set. - */ - if (this.inputs?.[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]) { - this.issueNumber = this.inputs[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]; - this.singleAction.issue = this.issueNumber; - } - else if (this.isIssue) { - this.singleAction.isIssue = true; - this.issueNumber = this.issue.number; - this.singleAction.issue = this.issueNumber; - } - else if (this.isPullRequest) { - this.singleAction.isPullRequest = true; - this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); - this.singleAction.issue = this.issueNumber; - } - else if (this.isPush) { - this.singleAction.isPush = true; - this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); - this.singleAction.issue = this.issueNumber; - } - else { - this.singleAction.isPullRequest = await issueRepository.isPullRequest(this.owner, this.repo, this.singleAction.issue, this.tokens.token); - this.singleAction.isIssue = await issueRepository.isIssue(this.owner, this.repo, this.singleAction.issue, this.tokens.token); - if (this.singleAction.isIssue) { - this.issueNumber = this.singleAction.issue; - } - else if (this.singleAction.isPullRequest) { - const head = await issueRepository.getHeadBranch(this.owner, this.repo, this.singleAction.issue, this.tokens.token); - if (head === undefined) { - return; - } - this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(head); - } - } - } - else if (this.isIssue) { - this.issueNumber = this.issue.number; - } - else if (this.isPullRequest) { - this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); - } - else if (this.isPush) { - this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); - } - this.previousConfiguration = await new configuration_handler_1.ConfigurationHandler().get(this); - /** - * Get labels of issue - */ - this.labels.currentIssueLabels = await issueRepository.getLabels(this.owner, this.repo, this.issueNumber, this.tokens.token); - /** - * Contains release label - */ - this.release.active = this.labels.isRelease; - this.hotfix.active = this.labels.isHotfix; - /** - * Get previous state - */ - if (this.release.active) { - const previousReleaseBranch = this.previousConfiguration?.releaseBranch; - if (previousReleaseBranch) { - this.release.version = previousReleaseBranch.split('/')[1] ?? ''; - this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; - this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; - this.currentConfiguration.releaseBranch = this.release.branch; - } - } - else if (this.hotfix.active) { - const previousHotfixOriginBranch = this.previousConfiguration?.hotfixOriginBranch; - if (previousHotfixOriginBranch) { - this.hotfix.baseVersion = previousHotfixOriginBranch.split('/v')[1] ?? ''; - this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; - this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; - this.currentConfiguration.parentBranch = this.hotfix.baseBranch; - } - const previousHotfixBranch = this.previousConfiguration?.hotfixBranch; - if (previousHotfixBranch) { - this.hotfix.version = previousHotfixBranch.split('/')[1] ?? ''; - this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; - this.currentConfiguration.hotfixBranch = this.hotfix.branch; - } - } - else { - this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; - } - if (this.isSingleAction) { - /** - * Nothing to do here (for now) - */ - } - else if (this.isIssue) { - const branchRepository = new branch_repository_1.BranchRepository(); - if (this.release.active && this.release.version === undefined) { - const versionResult = await new get_release_version_use_case_1.GetReleaseVersionUseCase().invoke(this); - const versionInfo = versionResult[versionResult.length - 1]; - if (versionInfo.executed && versionInfo.success) { - this.release.version = versionInfo.payload['releaseVersion']; - } - else { - const typeResult = await new get_release_type_use_case_1.GetReleaseTypeUseCase().invoke(this); - const typeInfo = typeResult[typeResult.length - 1]; - if (typeInfo.executed && typeInfo.success) { - this.release.type = typeInfo.payload['releaseType']; - if (this.release.type === undefined) { - return; - } - const lastTag = await branchRepository.getLatestTag(); - if (lastTag === undefined) { - return; - } - this.release.version = (0, version_utils_1.incrementVersion)(lastTag, this.release.type); - } - } - this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; - } - else if (this.hotfix.active && this.hotfix.version === undefined) { - const versionResult = await new get_hotfix_version_use_case_1.GetHotfixVersionUseCase().invoke(this); - const versionInfo = versionResult[versionResult.length - 1]; - if (versionInfo.executed && versionInfo.success) { - this.hotfix.baseVersion = versionInfo.payload['baseVersion']; - this.hotfix.version = versionInfo.payload['hotfixVersion']; - } - else { - this.hotfix.baseVersion = await branchRepository.getLatestTag(); - if (this.hotfix.baseVersion === undefined) { - return; - } - this.hotfix.version = (0, version_utils_1.incrementVersion)(this.hotfix.baseVersion, 'Patch'); - } - this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; - this.currentConfiguration.hotfixBranch = this.hotfix.branch; - this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; - this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; - } - } - else if (this.isPullRequest) { - this.labels.currentPullRequestLabels = await issueRepository.getLabels(this.owner, this.repo, this.pullRequest.number, this.tokens.token); - this.release.active = this.pullRequest.base.indexOf(`${this.branches.releaseTree}/`) > -1; - this.hotfix.active = this.pullRequest.base.indexOf(`${this.branches.hotfixTree}/`) > -1; - } - this.currentConfiguration.branchType = this.issueType; - (0, logger_1.logDebugInfo)(`Current configuration: ${JSON.stringify(this.currentConfiguration, null, 2)}`); - }; - this.debug = debug; - this.dockerConfig = dockerConfig; - this.singleAction = singleAction; - this.commitPrefixBuilder = commitPrefixBuilder; - this.issue = issue; - this.pullRequest = pullRequest; - this.images = giphy; - this.tokens = tokens; - this.ai = ai; - this.emoji = emoji; - this.labels = labels; - this.issueTypes = issueTypes; - this.locale = locale; - this.sizeThresholds = sizeThresholds; - this.branches = branches; - this.release = release; - this.hotfix = hotfix; - this.project = project; - this.workflows = workflows; - this.currentConfiguration = new config_1.Config({}); - this.supabaseConfig = supabaseConfig; - this.inputs = inputs; - this.welcome = welcome; - } + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = __nccwpck_require__(9054) +const { ProgressEvent } = __nccwpck_require__(5504) +const { getEncoding } = __nccwpck_require__(4854) +const { DOMException } = __nccwpck_require__(1037) +const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(685) +const { types } = __nccwpck_require__(3837) +const { StringDecoder } = __nccwpck_require__(1576) +const { btoa } = __nccwpck_require__(4300) + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false } -exports.Execution = Execution; +/** + * @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' -/***/ 87341: -/***/ ((__unused_webpack_module, exports) => { + // 3. Set fr’s result to null. + fr[kResult] = null -"use strict"; + // 4. Set fr’s error to null. + fr[kError] = null -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Hotfix = void 0; -class Hotfix { - constructor() { - this.active = false; - } -} -exports.Hotfix = Hotfix; + // 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 = [] -/***/ 51721: -/***/ ((__unused_webpack_module, exports) => { + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() -"use strict"; + // 9. Let isFirstChunk be true. + let isFirstChunk = true -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Images = void 0; -class Images { - constructor(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, cleanUpGifs, featureGifs, bugfixGifs, docsGifs, choreGifs, releaseGifs, hotfixGifs, prLinkGifs, prFeatureGifs, prBugfixGifs, prReleaseGifs, prHotfixGifs, prDocsGifs, prChoreGifs, commitAutomaticActions, commitFeatureGifs, commitBugfixGifs, commitReleaseGifs, commitHotfixGifs, commitDocsGifs, commitChoreGifs) { - this.imagesOnIssue = imagesOnIssue; - this.imagesOnPullRequest = imagesOnPullRequest; - this.imagesOnCommit = imagesOnCommit; - this.issueAutomaticActions = cleanUpGifs; - this.issueFeatureGifs = featureGifs; - this.issueBugfixGifs = bugfixGifs; - this.issueReleaseGifs = releaseGifs; - this.issueHotfixGifs = hotfixGifs; - this.issueDocsGifs = docsGifs; - this.issueChoreGifs = choreGifs; - this.pullRequestAutomaticActions = prLinkGifs; - this.pullRequestFeatureGifs = prFeatureGifs; - this.pullRequestBugfixGifs = prBugfixGifs; - this.pullRequestReleaseGifs = prReleaseGifs; - this.pullRequestHotfixGifs = prHotfixGifs; - this.pullRequestDocsGifs = prDocsGifs; - this.pullRequestChoreGifs = prChoreGifs; - this.commitAutomaticActions = commitAutomaticActions; - this.commitFeatureGifs = commitFeatureGifs; - this.commitBugfixGifs = commitBugfixGifs; - this.commitReleaseGifs = commitReleaseGifs; - this.commitHotfixGifs = commitHotfixGifs; - this.commitDocsGifs = commitDocsGifs; - this.commitChoreGifs = commitChoreGifs; - } -} -exports.Images = Images; + // 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 -/***/ 42632: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + // 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. -"use strict"; + // 2. Append bs to bytes. + bytes.push(value) -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Issue = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class Issue { - get title() { - return this.inputs?.issue?.title ?? github.context.payload.issue?.title ?? ''; - } - get number() { - return this.inputs?.issue?.number ?? github.context.payload.issue?.number ?? -1; - } - get creator() { - return this.inputs?.issue?.user?.login ?? github.context.payload.issue?.user.login ?? ''; - } - get url() { - return this.inputs?.issue?.html_url ?? github.context.payload.issue?.html_url ?? ''; - } - get body() { - return this.inputs?.issue?.body ?? github.context.payload.issue?.body ?? ''; - } - get opened() { - return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); - } - get labeled() { - return (this.inputs?.action ?? github.context.payload.action) === 'labeled'; - } - get labelAdded() { - return this.inputs?.label?.name ?? github.context.payload.label?.name ?? ''; - } - get isIssue() { - return (this.inputs?.eventName ?? github.context.eventName) === 'issues'; - } - get isIssueComment() { - return (this.inputs?.eventName ?? github.context.eventName) === 'issue_comment'; - } - get commentId() { - return this.inputs?.comment?.id ?? github.context.payload.comment?.id ?? -1; - } - get commentBody() { - return this.inputs?.comment?.body ?? github.context.payload.comment?.body ?? ''; - } - get commentAuthor() { - return this.inputs?.comment?.user?.login ?? github.context.payload.comment?.user.login ?? ''; - } - get commentUrl() { - return this.inputs?.comment?.html_url ?? github.context.payload.comment?.html_url ?? ''; - } - constructor(branchManagementAlways, reopenOnPush, desiredAssigneesCount, inputs = undefined) { - this.inputs = undefined; - this.branchManagementAlways = branchManagementAlways; - this.reopenOnPush = reopenOnPush; - this.desiredAssigneesCount = desiredAssigneesCount; - this.inputs = inputs; - } -} -exports.Issue = Issue; + // 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) -/***/ 71975: -/***/ ((__unused_webpack_module, exports) => { + // 4. Else: -"use strict"; + if (fr[kAborted]) { + return + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueTypes = void 0; -class IssueTypes { - constructor(task, taskDescription, taskColor, bug, bugDescription, bugColor, feature, featureDescription, featureColor, documentation, documentationDescription, documentationColor, maintenance, maintenanceDescription, maintenanceColor, hotfix, hotfixDescription, hotfixColor, release, releaseDescription, releaseColor, question, questionDescription, questionColor, help, helpDescription, helpColor) { - this.task = task; - this.taskDescription = taskDescription; - this.taskColor = taskColor; - this.bug = bug; - this.bugDescription = bugDescription; - this.bugColor = bugColor; - this.feature = feature; - this.featureDescription = featureDescription; - this.featureColor = featureColor; - this.documentation = documentation; - this.documentationDescription = documentationDescription; - this.documentationColor = documentationColor; - this.maintenance = maintenance; - this.maintenanceDescription = maintenanceDescription; - this.maintenanceColor = maintenanceColor; - this.hotfix = hotfix; - this.hotfixDescription = hotfixDescription; - this.hotfixColor = hotfixColor; - this.release = release; - this.releaseDescription = releaseDescription; - this.releaseColor = releaseColor; - this.question = question; - this.questionDescription = questionDescription; - this.questionColor = questionColor; - this.help = help; - this.helpDescription = helpDescription; - this.helpColor = helpColor; - } -} -exports.IssueTypes = IssueTypes; + // 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 -/***/ 10818: -/***/ ((__unused_webpack_module, exports) => { + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } -"use strict"; + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Labels = void 0; -class Labels { - get isMandatoryBranchedLabel() { - return this.isHotfix || this.isRelease; - } - get containsBranchedLabel() { - return this.currentIssueLabels.includes(this.branchManagementLauncherLabel); - } - get isDeploy() { - return this.currentIssueLabels.includes(this.deploy); - } - get isDeployed() { - return this.currentIssueLabels.includes(this.deployed); - } - get isHelp() { - return this.currentIssueLabels.includes(this.help); - } - get isQuestion() { - return this.currentIssueLabels.includes(this.question); - } - get isFeature() { - return this.currentIssueLabels.includes(this.feature); - } - get isEnhancement() { - return this.currentIssueLabels.includes(this.enhancement); - } - get isBugfix() { - return this.currentIssueLabels.includes(this.bugfix); - } - get isBug() { - return this.currentIssueLabels.includes(this.bug); - } - get isHotfix() { - return this.currentIssueLabels.includes(this.hotfix); - } - get isRelease() { - return this.currentIssueLabels.includes(this.release); - } - get isDocs() { - return this.currentIssueLabels.includes(this.docs); - } - get isDocumentation() { - return this.currentIssueLabels.includes(this.documentation); - } - get isChore() { - return this.currentIssueLabels.includes(this.chore); - } - get isMaintenance() { - return this.currentIssueLabels.includes(this.maintenance); - } - get sizeLabels() { - return [this.sizeXxl, this.sizeXl, this.sizeL, this.sizeM, this.sizeS, this.sizeXs]; - } - get sizedLabelOnIssue() { - if (this.currentIssueLabels.includes(this.sizeXxl)) { - return this.sizeXxl; - } - else if (this.currentIssueLabels.includes(this.sizeXl)) { - return this.sizeXl; - } - else if (this.currentIssueLabels.includes(this.sizeL)) { - return this.sizeL; - } - else if (this.currentIssueLabels.includes(this.sizeM)) { - return this.sizeM; - } - else if (this.currentIssueLabels.includes(this.sizeS)) { - return this.sizeS; - } - else if (this.currentIssueLabels.includes(this.sizeXs)) { - return this.sizeXs; - } - return undefined; - } - get sizedLabelOnPullRequest() { - if (this.currentPullRequestLabels.includes(this.sizeXxl)) { - return this.sizeXxl; - } - else if (this.currentPullRequestLabels.includes(this.sizeXl)) { - return this.sizeXl; - } - else if (this.currentPullRequestLabels.includes(this.sizeL)) { - return this.sizeL; - } - else if (this.currentPullRequestLabels.includes(this.sizeM)) { - return this.sizeM; - } - else if (this.currentPullRequestLabels.includes(this.sizeS)) { - return this.sizeS; - } - else if (this.currentPullRequestLabels.includes(this.sizeXs)) { - return this.sizeXs; - } - return undefined; - } - get isIssueSized() { - return this.sizedLabelOnIssue !== undefined; - } - get isPullRequestSized() { - return this.sizedLabelOnPullRequest !== undefined; - } - get priorityLabels() { - return [this.priorityHigh, this.priorityMedium, this.priorityLow, this.priorityNone]; - } - get priorityLabelOnIssue() { - if (this.currentIssueLabels.includes(this.priorityHigh)) { - return this.priorityHigh; - } - else if (this.currentIssueLabels.includes(this.priorityMedium)) { - return this.priorityMedium; - } - else if (this.currentIssueLabels.includes(this.priorityLow)) { - return this.priorityLow; + break } - else if (this.currentIssueLabels.includes(this.priorityNone)) { - return this.priorityNone; + } catch (error) { + if (fr[kAborted]) { + return } - return undefined; + + // 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 + } } - get priorityLabelOnIssueProcessable() { - return this.currentIssueLabels.includes(this.priorityHigh) || - this.currentIssueLabels.includes(this.priorityMedium) || - this.currentIssueLabels.includes(this.priorityLow); + })() +} + +/** + * @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 } - get priorityLabelOnPullRequest() { - if (this.currentPullRequestLabels.includes(this.priorityHigh)) { - return this.priorityHigh; - } - else if (this.currentPullRequestLabels.includes(this.priorityMedium)) { - return this.priorityMedium; - } - else if (this.currentPullRequestLabels.includes(this.priorityLow)) { - return this.priorityLow; - } - else if (this.currentPullRequestLabels.includes(this.priorityNone)) { - return this.priorityNone; + 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')) } - return undefined; - } - get priorityLabelOnPullRequestProcessable() { - return this.currentPullRequestLabels.includes(this.priorityHigh) || - this.currentPullRequestLabels.includes(this.priorityMedium) || - this.currentPullRequestLabels.includes(this.priorityLow); - } - get isIssuePrioritized() { - return this.priorityLabelOnIssue !== undefined && this.priorityLabelOnIssue !== this.priorityNone; + } + + // 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) } - get isPullRequestPrioritized() { - return this.priorityLabelOnPullRequest !== undefined && this.priorityLabelOnPullRequest !== this.priorityNone; + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) + + return sequence.buffer } - constructor(branchManagementLauncherLabel, bug, bugfix, hotfix, enhancement, feature, release, question, help, deploy, deployed, docs, documentation, chore, maintenance, priorityHigh, priorityMedium, priorityLow, priorityNone, sizeXxl, sizeXl, sizeL, sizeM, sizeS, sizeXs) { - this.currentIssueLabels = []; - this.currentPullRequestLabels = []; - this.branchManagementLauncherLabel = branchManagementLauncherLabel; - this.bug = bug; - this.bugfix = bugfix; - this.hotfix = hotfix; - this.enhancement = enhancement; - this.feature = feature; - this.release = release; - this.question = question; - this.help = help; - this.deploy = deploy; - this.deployed = deployed; - this.docs = docs; - this.documentation = documentation; - this.chore = chore; - this.maintenance = maintenance; - this.sizeXxl = sizeXxl; - this.sizeXl = sizeXl; - this.sizeL = sizeL; - this.sizeM = sizeM; - this.sizeS = sizeS; - this.sizeXs = sizeXs; - this.priorityHigh = priorityHigh; - this.priorityMedium = priorityMedium; - this.priorityLow = priorityLow; - this.priorityNone = priorityNone; + 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 } + } } -exports.Labels = Labels; +/** + * @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) -/***/ 82152: -/***/ ((__unused_webpack_module, exports) => { + let slice = 0 -"use strict"; + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Locale = void 0; -class Locale { - constructor(issue, pullRequest) { - this.issue = issue; - this.pullRequest = pullRequest; - } + // 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) } -exports.Locale = Locale; -Locale.DEFAULT = 'en-US'; +/** + * @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' + } -/***/ 52298: -/***/ ((__unused_webpack_module, exports) => { + return null +} -"use strict"; +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Milestone = void 0; -class Milestone { - constructor(id, title, description) { - this.id = id; - this.title = title; - this.description = description; - } + 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 } -exports.Milestone = Milestone; /***/ }), -/***/ 93765: -/***/ ((__unused_webpack_module, exports) => { +/***/ 1892: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProjectDetail = void 0; -class ProjectDetail { - constructor(data) { - this.id = data[`id`] ?? ''; - this.title = data[`title`] ?? ''; - this.type = data[`type`] ?? ''; - this.owner = data[`owner`] ?? ''; - this.url = data[`url`] ?? ''; - this.number = data[`number`] ?? -1; - } + +// 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__(8045) +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 } -exports.ProjectDetail = ProjectDetail; /***/ }), -/***/ 1938: -/***/ ((__unused_webpack_module, exports) => { +/***/ 6930: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Projects = void 0; -class Projects { - constructor(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress) { - this.projects = projects; - this.projectColumnIssueCreated = projectColumnIssueCreated; - this.projectColumnPullRequestCreated = projectColumnPullRequestCreated; - this.projectColumnIssueInProgress = projectColumnIssueInProgress; - this.projectColumnPullRequestInProgress = projectColumnPullRequestInProgress; - } - getProjects() { - return this.projects; - } - getProjectColumnIssueCreated() { - return this.projectColumnIssueCreated; - } - getProjectColumnPullRequestCreated() { - return this.projectColumnPullRequestCreated; - } - getProjectColumnIssueInProgress() { - return this.projectColumnIssueInProgress; - } - getProjectColumnPullRequestInProgress() { - return this.projectColumnPullRequestInProgress; - } + +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) + } } -exports.Projects = Projects; /***/ }), -/***/ 84179: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 2860: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequest = void 0; -const github = __importStar(__nccwpck_require__(95438)); -class PullRequest { - get action() { - return this.inputs?.action ?? github.context.payload.action ?? ''; - } - get id() { - return this.inputs?.pull_request?.node_id ?? github.context.payload.pull_request?.node_id ?? ''; - } - get title() { - return this.inputs?.pull_request?.title ?? github.context.payload.pull_request?.title ?? ''; - } - get creator() { - return this.inputs?.pull_request?.user?.login ?? github.context.payload.pull_request?.user.login ?? ''; - } - get number() { - return this.inputs?.pull_request?.number ?? github.context.payload.pull_request?.number ?? -1; - } - get url() { - return this.inputs?.pull_request?.html_url ?? github.context.payload.pull_request?.html_url ?? ''; - } - get body() { - return this.inputs?.pull_request?.body ?? github.context.payload.pull_request?.body ?? ''; - } - get head() { - return this.inputs?.pull_request?.head?.ref ?? github.context.payload.pull_request?.head.ref ?? ''; - } - get base() { - return this.inputs?.pull_request?.base?.ref ?? github.context.payload.pull_request?.base.ref ?? ''; - } - get isMerged() { - return this.inputs?.pull_request?.merged ?? github.context.payload.pull_request?.merged ?? false; - } - get opened() { - return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); - } - get isOpened() { - return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'open' - && this.action !== 'closed'; - } - get isClosed() { - return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'closed' - || this.action === 'closed'; - } - get isSynchronize() { - return this.action === 'synchronize'; + +const util = __nccwpck_require__(3983) +const { kBodyUsed } = __nccwpck_require__(2785) +const assert = __nccwpck_require__(9491) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const EE = __nccwpck_require__(2361) + +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') } - get isPullRequest() { - return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request'; + + 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) } - get isPullRequestReviewComment() { - return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request_review_comment'; + } + + 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)) } - get commentId() { - return this.inputs?.pull_request_review_comment?.id ?? github.context.payload.pull_request_review_comment?.id ?? -1; + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) } - get commentBody() { - return this.inputs?.pull_request_review_comment?.body ?? github.context.payload.pull_request_review_comment?.body ?? ''; + + 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 } - get commentAuthor() { - return this.inputs?.pull_request_review_comment?.user?.login ?? github.context.payload.pull_request_review_comment?.user.login ?? ''; + } + + 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) } - get commentUrl() { - return this.inputs?.pull_request_review_comment?.html_url ?? github.context.payload.pull_request_review_comment?.html_url ?? ''; + } + + 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) } - constructor(desiredAssigneesCount, desiredReviewersCount, mergeTimeout, inputs = undefined) { - this.inputs = undefined; - this.desiredAssigneesCount = desiredAssigneesCount; - this.desiredReviewersCount = desiredReviewersCount; - this.mergeTimeout = mergeTimeout; - this.inputs = inputs; + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) } + } } -exports.PullRequest = PullRequest; - -/***/ }), +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } -/***/ 12551: -/***/ ((__unused_webpack_module, exports) => { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } +} -"use strict"; +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Release = void 0; -class Release { - constructor() { - this.active = false; +// 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 } -exports.Release = Release; + +module.exports = RedirectHandler /***/ }), -/***/ 27305: -/***/ ((__unused_webpack_module, exports) => { +/***/ 2286: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +const assert = __nccwpck_require__(9491) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Result = void 0; -class Result { - constructor(data) { - this.id = data['id'] ?? ''; - this.success = data['success'] ?? false; - this.executed = data['executed'] ?? false; - this.steps = data['steps'] ?? []; - this.errors = data['errors'] ?? []; - this.payload = data['payload']; - this.reminders = data['reminders'] ?? []; - } +const { kRetryHandlerDefaultRetry } = __nccwpck_require__(2785) +const { RequestRetryError } = __nccwpck_require__(8045) +const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3983) + +function calculateRetryAfterHeader (retryAfter) { + const current = Date.now() + const diff = new Date(retryAfter).getTime() - current + + return diff } -exports.Result = Result; +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' + ] + } -/***/ 28024: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.retryCount = 0 + this.start = 0 + this.end = null + this.etag = null + this.resume = null -"use strict"; + // Handle possible onConnect duplication + this.handler.onConnect(reason => { + this.aborted = true + if (this.abort) { + this.abort(reason) + } else { + this.reason = reason + } + }) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SingleAction = void 0; -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class SingleAction { - get isDeployedAction() { - return this.currentSingleAction === constants_1.ACTIONS.DEPLOYED; - } - get isCompileVectorServerAction() { - return this.currentSingleAction === constants_1.ACTIONS.COMPILE_VECTOR_SERVER; - } - get isVectorAction() { - return this.currentSingleAction === constants_1.ACTIONS.VECTOR || this.currentSingleAction === constants_1.ACTIONS.VECTOR_LOCAL; - } - get isVectorLocalAction() { - return this.currentSingleAction === constants_1.ACTIONS.VECTOR_LOCAL; - } - get isVectorRemovalAction() { - return this.currentSingleAction === constants_1.ACTIONS.VECTOR_REMOVAL; - } - get isPublishGithubAction() { - return this.currentSingleAction === constants_1.ACTIONS.PUBLISH_GITHUB_ACTION; + onRequestSent () { + if (this.handler.onRequestSent) { + this.handler.onRequestSent() } - get isCreateReleaseAction() { - return this.currentSingleAction === constants_1.ACTIONS.CREATE_RELEASE; + } + + onUpgrade (statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket) } - get isCreateTagAction() { - return this.currentSingleAction === constants_1.ACTIONS.CREATE_TAG; + } + + onConnect (abort) { + if (this.aborted) { + abort(this.reason) + } else { + this.abort = abort } - get enabledSingleAction() { - return this.currentSingleAction.length > 0; + } + + 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 } - get validSingleAction() { - return this.enabledSingleAction && - (this.issue > 0 || this.isSingleActionWithoutIssue) && - this.actions.indexOf(this.currentSingleAction) > -1; + + // 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 } - get isSingleActionWithoutIssue() { - return this.actionsWithoutIssue.indexOf(this.currentSingleAction) > -1; + + // 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 } - get throwError() { - return this.actionsThrowError.indexOf(this.currentSingleAction) > -1; + + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return } - constructor(currentSingleAction, issue, version, title, changelog) { - this.actions = [ - constants_1.ACTIONS.DEPLOYED, - constants_1.ACTIONS.COMPILE_VECTOR_SERVER, - constants_1.ACTIONS.VECTOR, - constants_1.ACTIONS.VECTOR_LOCAL, - constants_1.ACTIONS.VECTOR_REMOVAL, - constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, - constants_1.ACTIONS.CREATE_TAG, - constants_1.ACTIONS.CREATE_RELEASE, - ]; - /** - * Actions that throw an error if the last step failed - */ - this.actionsThrowError = [ - constants_1.ACTIONS.VECTOR, - constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, - constants_1.ACTIONS.CREATE_RELEASE, - constants_1.ACTIONS.DEPLOYED, - constants_1.ACTIONS.CREATE_TAG, - ]; - /** - * Actions that do not require an issue - */ - this.actionsWithoutIssue = [ - constants_1.ACTIONS.VECTOR, - constants_1.ACTIONS.VECTOR_LOCAL, - constants_1.ACTIONS.COMPILE_VECTOR_SERVER, - ]; - this.isIssue = false; - this.isPullRequest = false; - this.isPush = false; - /** - * Properties - */ - this.issue = -1; - this.version = ''; - this.title = ''; - this.changelog = ''; - this.version = version; - this.title = title; - this.changelog = changelog; - if (!this.isSingleActionWithoutIssue) { - try { - this.issue = parseInt(issue); - } - catch (error) { - (0, logger_1.logError)(`Issue ${issue} is not a number.`); - (0, logger_1.logError)(error); - } - } - else { - this.issue = 0; - } - this.currentSingleAction = currentSingleAction; + + let retryAfterHeader = headers != null && headers['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(retryAfterHeader) + : retryAfterHeader * 1e3 // Retry-After is in seconds } -} -exports.SingleAction = SingleAction; + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) -/***/ }), + state.currentTimeout = retryTimeout -/***/ 23835: -/***/ ((__unused_webpack_module, exports) => { + setTimeout(() => cb(null), retryTimeout) + } -"use strict"; + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SizeThreshold = void 0; -class SizeThreshold { - constructor(lines, files, commits) { - this.lines = lines; - this.files = files; - this.commits = commits; + this.retryCount += 1 + + if (statusCode >= 300) { + this.abort( + new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) + ) + return false } -} -exports.SizeThreshold = SizeThreshold; + // Checkpoint for resume from where we left it + if (this.resume != null) { + this.resume = null -/***/ }), + if (statusCode !== 206) { + return true + } -/***/ 98237: -/***/ ((__unused_webpack_module, exports) => { + 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 + } -"use strict"; + // 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 + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SizeThresholds = void 0; -class SizeThresholds { - constructor(xxl, xl, l, m, s, xs) { - this.xxl = xxl; - this.xl = xl; - this.l = l; - this.m = m; - this.s = s; - this.xs = xs; - } -} -exports.SizeThresholds = SizeThresholds; + 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 + } -/***/ 149: -/***/ ((__unused_webpack_module, exports) => { + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) -"use strict"; + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SupabaseConfig = void 0; -class SupabaseConfig { - constructor(url, key) { - this.url = url; - this.key = key; - } - getUrl() { - return this.url; - } - getKey() { - return this.key; - } -} -exports.SupabaseConfig = SupabaseConfig; + 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 + } -/***/ 53421: -/***/ ((__unused_webpack_module, exports) => { + // 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 + } -"use strict"; + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Tokens = void 0; -class Tokens { - constructor(token, classicToken) { - this.token = token; - this.classicToken = classicToken; + this.resume = resume + this.etag = headers.etag != null ? headers.etag : null + + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) } -} -exports.Tokens = Tokens; + const err = new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) -/***/ }), + this.abort(err) -/***/ 6845: -/***/ ((__unused_webpack_module, exports) => { + return false + } -"use strict"; + onData (chunk) { + this.start += chunk.length -// types.ts (o donde quieras definir tus modelos) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WorkflowRun = void 0; -class WorkflowRun { - // puedes agregar mĆ”s campos si los usas - constructor(data) { - this.id = data.id; - this.name = data.name; - this.head_branch = data.head_branch; - this.head_sha = data.head_sha; - this.run_number = data.run_number; - this.event = data.event; - this.status = data.status; - this.conclusion = data.conclusion; - this.created_at = data.created_at; - this.updated_at = data.updated_at; - this.url = data.url; - this.html_url = data.html_url; - } - isActive() { - return this.status === "in_progress" || this.status === "queued"; - } -} -exports.WorkflowRun = WorkflowRun; + 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) + ) -/***/ 38553: -/***/ ((__unused_webpack_module, exports) => { + function onRetry (err) { + if (err != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } -"use strict"; + if (this.start !== 0) { + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + range: `bytes=${this.start}-${this.end ?? ''}` + } + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Workflows = void 0; -class Workflows { - constructor(release, hotfix) { - this.release = release; - this.hotfix = hotfix; + try { + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onError(err) + } } + } } -exports.Workflows = Workflows; + +module.exports = RetryHandler /***/ }), -/***/ 68307: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 8861: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AiRepository = void 0; -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class AiRepository { - constructor() { - this.ask = async (ai, prompt) => { - const model = ai.getOpenRouterModel(); - const apiKey = ai.getOpenRouterApiKey(); - const providerRouting = ai.getProviderRouting(); - if (!model || !apiKey) { - (0, logger_1.logError)('Missing required AI configuration'); - return undefined; - } - (0, logger_1.logDebugInfo)(`šŸ”Ž Model: ${model}`); - (0, logger_1.logDebugInfo)(`šŸ”Ž API Key: ***`); - (0, logger_1.logDebugInfo)(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); - const url = `https://openrouter.ai/api/v1/chat/completions`; - try { - // logDebugInfo(`Sending prompt to ${model}: ${prompt}`); - const requestBody = { - model: model, - messages: [ - { role: 'user', content: prompt }, - ], - }; - // Add provider routing configuration if it exists and has properties - if (Object.keys(providerRouting).length > 0) { - requestBody.provider = providerRouting; - } - const response = await fetch(url, { - method: 'POST', - headers: { - Authorization: `Bearer ${apiKey}`, - 'HTTP-Referer': constants_1.REPO_URL, - 'X-Title': constants_1.TITLE, - 'Content-Type': 'application/json', - }, - body: JSON.stringify(requestBody), - }); - if (!response.ok) { - const errorText = await response.text(); - console.error('API Response:', errorText); - (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); - return undefined; - } - const data = await response.json(); - if (!data.choices || data.choices.length === 0) { - (0, logger_1.logError)('No response content received from API'); - return undefined; - } - (0, logger_1.logDebugInfo)(`Successfully received response from ${model}`); - return data.choices[0].message.content; - } - catch (error) { - (0, logger_1.logError)(`Error querying ${model}: ${error}`); - return undefined; - } - }; - this.askJson = async (ai, prompt) => { - const result = await this.ask(ai, prompt); - if (!result) { - return undefined; - } - // Clean the response by removing ```json markers if present - const cleanedResult = result - .replace(/^```json\n?/, '') // Remove ```json at the start - .replace(/\n?```$/, '') // Remove ``` at the end - .trim(); - return JSON.parse(cleanedResult); - }; - } -} -exports.AiRepository = AiRepository; - -/***/ }), +const RedirectHandler = __nccwpck_require__(2860) -/***/ 37701: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts -"use strict"; + if (!maxRedirections) { + return dispatch(opts, handler) + } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BranchRepository = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const exec = __importStar(__nccwpck_require__(71514)); -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const version_utils_1 = __nccwpck_require__(29887); -const result_1 = __nccwpck_require__(27305); -class BranchRepository { - constructor() { - this.fetchRemoteBranches = async () => { - try { - (0, logger_1.logDebugInfo)('Fetching tags and forcing fetch...'); - await exec.exec('git', ['fetch', '--tags', '--force']); - (0, logger_1.logDebugInfo)('Fetching all remote branches with verbose output...'); - await exec.exec('git', ['fetch', '--all', '-v']); - (0, logger_1.logDebugInfo)('Successfully fetched all remote branches.'); - } - catch (error) { - core.setFailed(`Error fetching remote branches: ${error}`); - } - }; - this.getLatestTag = async () => { - try { - (0, logger_1.logDebugInfo)('Fetching the latest tag...'); - await exec.exec('git', ['fetch', '--tags']); - const tags = []; - await exec.exec('git', ['tag', '--sort=-creatordate'], { - listeners: { - stdout: (data) => { - tags.push(...data.toString().split('\n').map((v, i, a) => { - return v.replace('v', ''); - })); - }, - }, - }); - const validTags = tags.filter(tag => /\d+\.\d+\.\d+$/.test(tag)); - if (validTags.length > 0) { - const latestTag = (0, version_utils_1.getLatestVersion)(validTags); - (0, logger_1.logDebugInfo)(`Latest tag: ${latestTag}`); - return latestTag; - } - else { - (0, logger_1.logDebugInfo)('No valid tags found.'); - return undefined; - } - } - catch (error) { - core.setFailed(`Error fetching the latest tag: ${error}`); - return undefined; - } - }; - this.getCommitTag = async (latestTag) => { - try { - if (!latestTag) { - core.setFailed('No LATEST_TAG found in the environment'); - return; - } - let tagVersion; - if (latestTag.startsWith('v')) { - tagVersion = latestTag; - } - else { - tagVersion = `v${latestTag}`; - } - (0, logger_1.logDebugInfo)(`Fetching commit hash for the tag: ${tagVersion}`); - let commitOid = ''; - await exec.exec('git', ['rev-list', '-n', '1', tagVersion], { - listeners: { - stdout: (data) => { - commitOid = data.toString().trim(); - }, - }, - }); - if (commitOid) { - (0, logger_1.logDebugInfo)(`Commit tag: ${commitOid}`); - return commitOid; - } - else { - core.setFailed('No commit found for the tag'); - } - } - catch (error) { - core.setFailed(`Error fetching the commit hash: ${error}`); - } - return undefined; - }; - /** - * Returns replaced branch (if any). - * - * @param param - * @param repository - * @param owner - * @param token - * @param issueNumber - * @param issueTitle - * @param branchType - * @param developmentBranch - * @param hotfixBranch - * @param isHotfix - */ - this.manageBranches = async (param, owner, repository, issueNumber, issueTitle, branchType, developmentBranch, hotfixBranch, isHotfix, token) => { - const result = []; - try { - (0, logger_1.logDebugInfo)(`Managing branches`); - const branches = await this.getListOfBranches(owner, repository, token); - (0, logger_1.logDebugInfo)(JSON.stringify(branches, null, 2)); - if (hotfixBranch === undefined && isHotfix) { - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Tried to prepare the hotfix branch of the issue, but hotfix branch was not found.`, - ], - })); - return result; - } - const octokit = github.getOctokit(token); - const sanitizedTitle = this.formatBranchName(issueTitle, issueNumber); - const newBranchName = `${branchType}/${issueNumber}-${sanitizedTitle}`; - if (branches.indexOf(newBranchName) > -1) { - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: false, - })); - return result; - } - const branchTypes = [ - param.branches.featureTree, - param.branches.bugfixTree, - param.branches.docsTree, - param.branches.choreTree, - ]; - /** - * Default base branch name. (ex. [develop]) - */ - let baseBranchName = developmentBranch; - if (!isHotfix) { - /** - * Check if it is a branch switch: feature/123-bla <-> bugfix/123-bla - */ - (0, logger_1.logDebugInfo)(`Searching for branches related to issue #${issueNumber}...`); - const { data } = await octokit.rest.repos.listBranches({ - owner: owner, - repo: repository, - }); - for (const type of branchTypes) { - const prefix = `${type}/${issueNumber}-`; - try { - const matchingBranch = data.find(branch => branch.name.indexOf(prefix) > -1); - if (matchingBranch) { - baseBranchName = matchingBranch.name; - (0, logger_1.logDebugInfo)(`Found previous issue branch: ${baseBranchName}`); - // TODO replacedBranchName = baseBranchName - break; - } - } - catch (error) { - (0, logger_1.logError)(`Error while listing branches: ${error}`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Error while listing branches.`, - ], - error: error, - })); - } - } - } - else { - baseBranchName = hotfixBranch ?? developmentBranch; - } - param.currentConfiguration.parentBranch = baseBranchName; - (0, logger_1.logDebugInfo)(`============================================================================================`); - (0, logger_1.logDebugInfo)(`Base branch: ${baseBranchName}`); - (0, logger_1.logDebugInfo)(`New branch: ${newBranchName}`); - result.push(...await this.createLinkedBranch(owner, repository, baseBranchName, newBranchName, issueNumber, undefined, token)); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Tried to prepare the hotfix to the issue, but there was a problem.`, - ], - error: error, - })); - } - return result; - }; - this.formatBranchName = (issueTitle, issueNumber) => { - let sanitizedTitle = issueTitle.toLowerCase() - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - sanitizedTitle = sanitizedTitle.replace(/[^a-z0-9 ]/g, '').replace(/ /g, '-'); - const issuePrefix = `${issueNumber}-`; - if (sanitizedTitle.startsWith(issuePrefix)) { - sanitizedTitle = sanitizedTitle.substring(issuePrefix.length); - } - sanitizedTitle = sanitizedTitle.replace(/-+/g, '-'); - sanitizedTitle = sanitizedTitle.replace(/^-|-$/g, ''); - return sanitizedTitle; - }; - this.createLinkedBranch = async (owner, repo, baseBranchName, newBranchName, issueNumber, oid, token) => { - const result = []; - try { - (0, logger_1.logDebugInfo)(`Creating linked branch ${newBranchName} from ${oid ?? baseBranchName}`); - let ref = `heads/${baseBranchName}`; - if (baseBranchName.indexOf('tags/') > -1) { - ref = baseBranchName; - } - const octokit = github.getOctokit(token); - const { repository } = await octokit.graphql(` - query($repo: String!, $owner: String!, $issueNumber: Int!) { - repository(name: $repo, owner: $owner) { - id - issue(number: $issueNumber) { - id - } - ref(qualifiedName: "refs/${ref}") { - target { - ... on Commit { - oid - } - } - } - } - } - `, { - repo: repo, - owner: owner, - issueNumber: issueNumber - }); - (0, logger_1.logDebugInfo)(`Repository information retrieved: ${JSON.stringify(repository?.ref)}`); - const repositoryId = repository?.id ?? undefined; - const issueId = repository?.issue?.id ?? undefined; - const branchOid = oid ?? repository?.ref?.target?.oid ?? undefined; - if (repositoryId === undefined || issueNumber === undefined || branchOid === undefined) { - (0, logger_1.logError)(`Error searching repository "${baseBranchName}": id: ${repositoryId}, oid: ${branchOid}), issue #${issueNumber}`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Error linking branch ${newBranchName} to issue: Repository not found.`, - ], - })); - return result; - } - (0, logger_1.logDebugInfo)(`Linking branch "${newBranchName}" (oid: ${branchOid}) to issue #${issueNumber}`); - const mutationResponse = await octokit.graphql(` - mutation($issueId: ID!, $name: String!, $repositoryId: ID!, $oid: GitObjectID!) { - createLinkedBranch(input: { - issueId: $issueId, - name: $name, - repositoryId: $repositoryId, - oid: $oid, - }) { - linkedBranch { - id - ref { - name - } - } - } - } - `, { - issueId: issueId, - name: `/${newBranchName}`, - repositoryId: repositoryId, - oid: branchOid, - }); - (0, logger_1.logDebugInfo)(`Linked branch: ${JSON.stringify(mutationResponse.createLinkedBranch?.linkedBranch)}`); - const baseBranchUrl = `https://github.com/${owner}/${repo}/tree/${baseBranchName}`; - const newBranchUrl = `https://github.com/${owner}/${repo}/tree/${newBranchName}`; - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: true, - payload: { - baseBranchName: baseBranchName, - baseBranchUrl: baseBranchUrl, - newBranchName: newBranchName, - newBranchUrl: newBranchUrl, - }, - })); - } - catch (error) { - (0, logger_1.logError)(`Error Linking branch "${error}"`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Tried to link branch to the issue, but there was a problem.`, - ], - error: error, - })); - } - return result; - }; - this.removeBranch = async (owner, repository, branch, token) => { - const octokit = github.getOctokit(token); - const ref = `heads/${branch}`; - try { - const { data } = await octokit.rest.git.getRef({ - owner: owner, - repo: repository, - ref, - }); - (0, logger_1.logDebugInfo)(`Branch found: ${data.ref}`); - await octokit.rest.git.deleteRef({ - owner: owner, - repo: repository, - ref, - }); - (0, logger_1.logDebugInfo)(`Successfully deleted branch: ${branch}`); - return true; - } - catch (error) { - (0, logger_1.logError)(`Error processing branch ${branch}: ${error}`); - throw error; - } - }; - this.getListOfBranches = async (owner, repository, token) => { - const octokit = github.getOctokit(token); - const allBranches = []; - let page = 1; - while (true) { - const { data } = await octokit.rest.repos.listBranches({ - owner: owner, - repo: repository, - per_page: 100, - page: page, - }); - if (data.length === 0) { - break; - } - allBranches.push(...data.map(branch => branch.name)); - page++; - } - return allBranches; - }; - this.executeWorkflow = async (owner, repository, branch, workflow, inputs, token) => { - const octokit = github.getOctokit(token); - return octokit.rest.actions.createWorkflowDispatch({ - owner: owner, - repo: repository, - workflow_id: workflow, - ref: branch, - inputs: inputs - }); - }; - this.mergeBranch = async (owner, repository, head, base, timeout, token) => { - const result = []; - try { - const octokit = github.getOctokit(token); - (0, logger_1.logDebugInfo)(`Creating merge from ${head} into ${base}`); - // Build PR body with commit list - const prBody = `šŸš€ Automated Merge + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } +} -This PR merges **${head}** into **${base}**. +module.exports = createRedirectInterceptor -**Commits included:**`; - // We need PAT for creating PR to ensure it can trigger workflows - const { data: pullRequest } = await octokit.rest.pulls.create({ - owner: owner, - repo: repository, - head: head, - base: base, - title: `Merge ${head} into ${base}`, - body: prBody, - }); - (0, logger_1.logDebugInfo)(`Pull request #${pullRequest.number} created, getting commits...`); - // Get all commits in the PR - const { data: commits } = await octokit.rest.pulls.listCommits({ - owner: owner, - repo: repository, - pull_number: pullRequest.number - }); - const commitMessages = commits.map(commit => commit.commit.message); - (0, logger_1.logDebugInfo)(`Found ${commitMessages.length} commits in PR`); - // Update PR with commit list and footer - await octokit.rest.pulls.update({ - owner: owner, - repo: repository, - pull_number: pullRequest.number, - body: prBody + '\n' + commitMessages.map(msg => `- ${msg}`).join('\n') + - '\n\nThis PR was automatically created by [`git-board-flow`](https://github.com/landamessenger/git-board-flow).' - }); - const iteration = 10; - if (timeout > iteration) { - // Wait for checks to complete - can use regular token for reading checks - let checksCompleted = false; - let attempts = 0; - const maxAttempts = timeout > iteration ? Math.floor(timeout / iteration) : iteration; - while (!checksCompleted && attempts < maxAttempts) { - const { data: checkRuns } = await octokit.rest.checks.listForRef({ - owner: owner, - repo: repository, - ref: head, - }); - // Get commit status checks for the PR head commit - const { data: commitStatus } = await octokit.rest.repos.getCombinedStatusForRef({ - owner: owner, - repo: repository, - ref: head - }); - (0, logger_1.logDebugInfo)(`Combined status state: ${commitStatus.state}`); - (0, logger_1.logDebugInfo)(`Number of check runs: ${checkRuns.check_runs.length}`); - // If there are check runs, prioritize those over status checks - if (checkRuns.check_runs.length > 0) { - const pendingCheckRuns = checkRuns.check_runs.filter(check => check.status !== 'completed'); - if (pendingCheckRuns.length === 0) { - checksCompleted = true; - (0, logger_1.logDebugInfo)('All check runs have completed.'); - // Verify if all checks passed - const failedChecks = checkRuns.check_runs.filter(check => check.conclusion === 'failure'); - if (failedChecks.length > 0) { - throw new Error(`Checks failed: ${failedChecks.map(check => check.name).join(', ')}`); - } - } - else { - (0, logger_1.logDebugInfo)(`Waiting for ${pendingCheckRuns.length} check runs to complete:`); - pendingCheckRuns.forEach(check => { - (0, logger_1.logDebugInfo)(` - ${check.name} (Status: ${check.status})`); - }); - await new Promise(resolve => setTimeout(resolve, iteration * 1000)); - attempts++; - continue; - } - } - else { - // Fall back to status checks if no check runs exist - const pendingChecks = commitStatus.statuses.filter(status => { - (0, logger_1.logDebugInfo)(`Status check: ${status.context} (State: ${status.state})`); - return status.state === 'pending'; - }); - if (pendingChecks.length === 0) { - checksCompleted = true; - (0, logger_1.logDebugInfo)('All status checks have completed.'); - } - else { - (0, logger_1.logDebugInfo)(`Waiting for ${pendingChecks.length} status checks to complete:`); - pendingChecks.forEach(check => { - (0, logger_1.logDebugInfo)(` - ${check.context} (State: ${check.state})`); - }); - await new Promise(resolve => setTimeout(resolve, iteration * 1000)); - attempts++; - } - } - } - if (!checksCompleted) { - throw new Error('Timed out waiting for checks to complete'); - } - } - // Need PAT for merging to ensure it can trigger subsequent workflows - await octokit.rest.pulls.merge({ - owner: owner, - repo: repository, - pull_number: pullRequest.number, - merge_method: 'merge', - commit_title: `Merge ${head} into ${base}. Forced merge with PAT token.`, - }); - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: true, - steps: [ - `The branch \`${head}\` was merged into \`${base}\`.`, - ], - })); - } - catch (error) { - (0, logger_1.logError)(`Error in PR workflow: ${error}`); - // If the PR workflow fails, we try to merge directly - need PAT for direct merge to ensure it can trigger workflows - try { - const octokit = github.getOctokit(token); - await octokit.rest.repos.merge({ - owner: owner, - repo: repository, - base: base, - head: head, - commit_message: `Forced merge of ${head} into ${base}. Automated merge with PAT token.`, - }); - result.push(new result_1.Result({ - id: 'branch_repository', - success: true, - executed: true, - steps: [ - `The branch \`${head}\` was merged into \`${base}\` using direct merge.`, - ], - })); - return result; - } - catch (directMergeError) { - (0, logger_1.logError)(`Error in direct merge attempt: ${directMergeError}`); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - steps: [ - `Failed to merge branch \`${head}\` into \`${base}\`.`, - ], - })); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - error: error, - })); - result.push(new result_1.Result({ - id: 'branch_repository', - success: false, - executed: true, - error: directMergeError, - })); - } - } - return result; - }; - this.getChanges = async (owner, repository, head, base, token) => { - const octokit = github.getOctokit(token); - try { - (0, logger_1.logDebugInfo)(`Comparing branches: ${head} with ${base}`); - let headRef = `heads/${head}`; - if (head.indexOf('tags/') > -1) { - headRef = head; - } - let baseRef = `heads/${base}`; - if (base.indexOf('tags/') > -1) { - baseRef = base; - } - const { data: comparison } = await octokit.rest.repos.compareCommits({ - owner: owner, - repo: repository, - base: baseRef, - head: headRef, - }); - return { - aheadBy: comparison.ahead_by, - behindBy: comparison.behind_by, - totalCommits: comparison.total_commits, - files: (comparison.files || []).map(file => ({ - filename: file.filename, - status: file.status, - additions: file.additions, - deletions: file.deletions, - changes: file.changes, - blobUrl: file.blob_url, - rawUrl: file.raw_url, - contentsUrl: file.contents_url, - patch: file.patch - })), - commits: comparison.commits.map(commit => ({ - sha: commit.sha, - message: commit.commit.message, - author: commit.commit.author || { name: 'Unknown', email: 'unknown@example.com', date: new Date().toISOString() }, - date: commit.commit.author?.date || new Date().toISOString() - })) - }; - } - catch (error) { - (0, logger_1.logError)(`Error comparing branches: ${error}`); - throw error; - } - }; - this.getSizeCategoryAndReason = async (owner, repository, head, base, sizeThresholds, labels, token) => { - try { - const headBranchChanges = await this.getChanges(owner, repository, head, base, token); - const totalChanges = headBranchChanges.files.reduce((sum, file) => sum + file.changes, 0); - const totalFiles = headBranchChanges.files.length; - const totalCommits = headBranchChanges.totalCommits; - let sizeCategory; - let githubSize; - let sizeReason; - if (totalChanges > sizeThresholds.xxl.lines || totalFiles > sizeThresholds.xxl.files || totalCommits > sizeThresholds.xxl.commits) { - sizeCategory = labels.sizeXxl; - githubSize = `XL`; - sizeReason = totalChanges > sizeThresholds.xxl.lines ? `More than ${sizeThresholds.xxl.lines} lines changed` : - totalFiles > sizeThresholds.xxl.files ? `More than ${sizeThresholds.xxl.files} files modified` : - `More than ${sizeThresholds.xxl.commits} commits`; - } - else if (totalChanges > sizeThresholds.xl.lines || totalFiles > sizeThresholds.xl.files || totalCommits > sizeThresholds.xl.commits) { - sizeCategory = labels.sizeXl; - githubSize = `XL`; - sizeReason = totalChanges > sizeThresholds.xl.lines ? `More than ${sizeThresholds.xl.lines} lines changed` : - totalFiles > sizeThresholds.xl.files ? `More than ${sizeThresholds.xl.files} files modified` : - `More than ${sizeThresholds.xl.commits} commits`; - } - else if (totalChanges > sizeThresholds.l.lines || totalFiles > sizeThresholds.l.files || totalCommits > sizeThresholds.l.commits) { - sizeCategory = labels.sizeL; - githubSize = `L`; - sizeReason = totalChanges > sizeThresholds.l.lines ? `More than ${sizeThresholds.l.lines} lines changed` : - totalFiles > sizeThresholds.l.files ? `More than ${sizeThresholds.l.files} files modified` : - `More than ${sizeThresholds.l.commits} commits`; - } - else if (totalChanges > sizeThresholds.m.lines || totalFiles > sizeThresholds.m.files || totalCommits > sizeThresholds.m.commits) { - sizeCategory = labels.sizeM; - githubSize = `M`; - sizeReason = totalChanges > sizeThresholds.m.lines ? `More than ${sizeThresholds.m.lines} lines changed` : - totalFiles > sizeThresholds.m.files ? `More than ${sizeThresholds.m.files} files modified` : - `More than ${sizeThresholds.m.commits} commits`; - } - else if (totalChanges > sizeThresholds.s.lines || totalFiles > sizeThresholds.s.files || totalCommits > sizeThresholds.s.commits) { - sizeCategory = labels.sizeS; - githubSize = `S`; - sizeReason = totalChanges > sizeThresholds.s.lines ? `More than ${sizeThresholds.s.lines} lines changed` : - totalFiles > sizeThresholds.s.files ? `More than ${sizeThresholds.s.files} files modified` : - `More than ${sizeThresholds.s.commits} commits`; - } - else { - sizeCategory = labels.sizeXs; - githubSize = `XS`; - sizeReason = `Small changes (${totalChanges} lines, ${totalFiles} files)`; - } - return { - size: sizeCategory, - githubSize: githubSize, - reason: sizeReason - }; - } - catch (error) { - (0, logger_1.logError)(`Error comparing branches: ${error}`); - throw error; - } - }; + +/***/ }), + +/***/ 953: +/***/ ((__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__(1891); +// 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); } } -exports.BranchRepository = BranchRepository; +// ',' = \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 + +/***/ }), + +/***/ 1145: +/***/ ((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=' /***/ }), -/***/ 19097: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 5627: +/***/ ((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==' + + +/***/ }), + +/***/ 1891: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DockerRepository = void 0; -const dockerode_1 = __importDefault(__nccwpck_require__(14571)); -const path_1 = __importDefault(__nccwpck_require__(71017)); -const axios_1 = __importDefault(__nccwpck_require__(88757)); -const logger_1 = __nccwpck_require__(38836); -const child_process_1 = __nccwpck_require__(32081); -class DockerRepository { - constructor() { - // ============================== - // šŸ”§ Core Docker Lifecycle - // ============================== - this.prepareLocalVectorServer = async (param) => { - (0, logger_1.logDebugInfo)('🐳 🟔 Preparing local vector server...'); - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - try { - // Authenticate with registry - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - // Check if image already exists locally - const localImageExists = await this.imageExists(param); - if (localImageExists) { - (0, logger_1.logDebugInfo)(`🐳 🟢 Local image ${imageName} already exists, skipping pull`); - return; - } - // Check if multi-architecture image exists in registry - const registryImageExists = await this.checkMultiArchImageInRegistry(param); - if (!registryImageExists) { - throw new Error(`Multi-architecture image not found in registry: ${registryImageName}. Please build the image first using PrepareAIContainerUseCase.`); - } - // Pull the multi-architecture image from registry - (0, logger_1.logDebugInfo)(`🐳 🟔 Pulling multi-architecture image from registry: ${registryImageName}`); - try { - (0, child_process_1.execSync)(`docker pull ${registryImageName}`, { - stdio: 'inherit', - env: { ...process.env, DOCKER_BUILDKIT: '1' } - }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Successfully pulled multi-architecture image: ${registryImageName}`); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Failed to pull image: ${error}`); - throw error; - } - // Tag the pulled image with local name for consistency - (0, child_process_1.execSync)(`docker tag ${registryImageName} ${imageName}`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-architecture image pulled and tagged successfully: ${imageName}`); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Failed to prepare local vector server: ${error}`); - throw error; - } - }; - this.checkVersionExistsInRegistry = async (param) => { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - try { - (0, logger_1.logDebugInfo)(`🐳 🟔 Checking if version already exists in registry: ${registryImageName}`); - // Try to inspect the manifest to check if version exists - const output = (0, child_process_1.execSync)(`docker manifest inspect ${registryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - // Check if the manifest contains both architectures (multi-arch image) - const hasAmd64 = output.includes('"architecture": "amd64"'); - const hasArm64 = output.includes('"architecture": "arm64"'); - const versionExists = hasAmd64 && hasArm64; - (0, logger_1.logDebugInfo)(`🐳 🟔 Version ${imageName} exists in registry: ${versionExists}`); - return versionExists; - } - catch (error) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Version ${imageName} not found in registry: ${error}`); - return false; - } - }; - this.startContainer = async (param) => { - (0, logger_1.logDebugInfo)('🐳 🟔 Starting Docker container...'); - const isRunning = await this.isContainerRunning(param); - if (isRunning) { - (0, logger_1.logDebugInfo)('🐳 🟢 Docker container is ready'); - return; - } - try { - /* - if (this.shouldUsePrebuiltImage()) { - const imageExists = await this.imageExists(param); - if (!imageExists) { - const pulled = await this.pullPrebuiltImage(param); - if (!pulled) throw new Error('Prebuilt image not available'); - } - } else if (this.shouldUseLocalImage()) { - const imageExists = await this.imageExists(param); - if (!imageExists) await this.buildImage(param); - }*/ - await this.runContainer(param); - (0, logger_1.logDebugInfo)('🐳 🟢 Container started successfully'); - } - catch (error) { - (0, logger_1.logError)('Error starting container: ' + error); - throw error; - } - }; - this.runContainer = async (param) => { - const container = await this.getContainer(param); - const info = await container.inspect(); - if (info.State.Status !== 'running') - await container.start(); - await this.waitForContainer(param); - }; - this.imageExists = async (param) => { - const images = await this.docker.listImages(); - return images.some(img => img.RepoTags && img.RepoTags.includes(this.getImageNameWithTag(param))); - }; - this.pullPrebuiltImage = async (param) => { - try { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - const stream = await this.docker.pull(registryImageName); - await new Promise((resolve, reject) => { - this.docker.modem.followProgress(stream, (err) => { - if (err) - reject(err); - else - resolve(true); - }); - }); - return true; - } - catch { - return false; - } - }; - // ============================== - // 🧱 Build Image - // ============================== - this.buildImage = async (param) => { - // const imageName = this.getImageNameWithTag(param); - // const archType = this.getArchitectureType(); - // Check if Docker Buildx is available for multi-architecture builds - const buildxAvailable = await this.checkDockerBuildxAvailable(); - if (buildxAvailable) { - await this.buildMultiArchImage(param); - } - /* else { - logDebugInfo(`🐳 🟔 Building single-architecture Docker image: ${imageName} for architecture: ${archType}`); - await this.buildSingleArchImage(param, imageName, archType); - }*/ - (0, logger_1.logDebugInfo)('🐳 🟢 Docker image built successfully'); - }; - /*private async buildSingleArchImage(param: Execution, imageName: string, archType: string): Promise { - const stream = await this.docker.buildImage({ - context: this.dockerDir, - src: ['Dockerfile', 'requirements.txt', 'main.py'], - }, { - t: imageName, - dockerfile: 'Dockerfile', - buildargs: {}, - nocache: false, - platform: `linux/${archType}`, - }); - - await new Promise((resolve, reject) => { - this.docker.modem.followProgress(stream, (err: any, res: any) => { - if (err) reject(err); - else resolve(res); - }, (event: any) => { - if (event.stream) logDebugInfo(`🐳 🟔 ${event.stream.trim()}`); - }); - }); - }*/ - // ============================== - // 🧩 Manifest / Registry Handling - // ============================== - /*checkImageInRegistry = async (param: Execution): Promise => { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - const archType = this.getArchitectureType(); - const dockerPlatform = `linux/${archType}`; - - try { - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - const manifestProcess = spawn('docker', ['manifest', 'inspect', registryImageName]); - - const output = await new Promise((resolve) => { - let data = ''; - manifestProcess.stdout.on('data', (chunk) => data += chunk.toString()); - manifestProcess.on('close', () => resolve(data)); - }); - - logDebugInfo(`🐳 🟔 Manifest output: ${output}`); - - if (output.includes(`"${archType}"`)) { - logDebugInfo(`🐳 🟢 Image already has platform ${dockerPlatform}`); - return true; - } else if (output.includes('"architecture"')) { - logDebugInfo(`🐳 🟔 Image exists but missing ${dockerPlatform}`); - return false; - } - return false; - } catch { - logDebugInfo(`🐳 🟔 No manifest found for ${registryImageName}`); - return false; - } - }*/ - /* - pushImageToRegistry = async (param: Execution, imageName: string): Promise => { - const buildxAvailable = await this.checkDockerBuildxAvailable(); - - if (buildxAvailable) { - // For multi-architecture builds, the image is already pushed during build - logDebugInfo('🐳 🟢 Multi-architecture image already pushed during build process'); - return; - } - - // Fallback to single-architecture push for systems without Buildx - const archType = this.getArchitectureType(); - const dockerPlatform = `linux/${archType}`; - const registryImageName = `ghcr.io/${param.owner}/${imageName}:latest`; - - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - - // Tag + Push architecture-specific image - execSync(`docker tag ${imageName}:latest ${registryImageName}`, { stdio: 'inherit' }); - execSync(`docker push ${registryImageName}`, { stdio: 'inherit' }); - - // Merge with existing manifest if necessary - try { - const manifestExists = await this.checkImageInRegistry(param); - if (manifestExists) { - logDebugInfo(`🐳 🟔 Amending existing manifest with ${dockerPlatform}...`); - execSync(`docker manifest create ${registryImageName} --amend ${registryImageName}`, { stdio: 'inherit' }); - } else { - logDebugInfo(`🐳 🟔 Creating new manifest list for ${dockerPlatform}...`); - execSync(`docker manifest create ${registryImageName} ${registryImageName}`, { stdio: 'inherit' }); - } - - execSync(`docker manifest push ${registryImageName}`, { stdio: 'inherit' }); - logDebugInfo(`🐳 🟢 Multi-arch manifest updated successfully for ${dockerPlatform}`); - } catch (err) { - logError(`🐳 šŸ”“ Manifest merge failed: ${err}`); - } - }*/ - this.authenticateWithRegistry = async (organizationName, token) => { - try { - (0, logger_1.logDebugInfo)(`🐳 🟔 Authenticating with GitHub Container Registry as ${organizationName}`); - (0, child_process_1.execSync)(`echo ${token} | docker login ghcr.io -u ${organizationName} --password-stdin`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Authenticated successfully`); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Docker login error: ${error.message}`); - throw error; - } - }; - this.getEmbedding = async (param, textInstructionsPairs) => { - try { - const request = { - instructions: textInstructionsPairs.map(pair => pair[0]), - texts: textInstructionsPairs.map(pair => pair[1]) - }; - const response = await axios_1.default.post(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/embed`, request, { - headers: { - 'Content-Type': 'application/json', - }, - family: 4 - }); - const data = response.data; - return data.embeddings; - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Error getting embedding: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getSystemInfo = async (param) => { - const response = await axios_1.default.get(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/system-info`, { - family: 4 - }); - return response.data; - }; - this.stopContainer = async (param) => { - (0, logger_1.logDebugInfo)('🐳 🟠 Stopping Docker container...'); - if (!this.isContainerRunning(param)) - return; - const containerId = await this.getContainerIdByName(param); - if (!containerId) - return; - try { - const container = this.docker.getContainer(containerId); - await container.stop(); - await container.remove(); - (0, logger_1.logDebugInfo)('🐳 ⚪ Docker container stopped'); - // Clean up dangling images after stopping (only on self-hosted runners) - if (this.isSelfHostedRunner()) { - await this.cleanupDanglingImages(); - await this.cleanupBuildxBuilder(); - } - } - catch (error) { - (0, logger_1.logError)('🐳 šŸ”“ Error stopping container: ' + error); - } - }; - this.cleanupDanglingImages = async () => { - try { - const images = await this.docker.listImages({ filters: { dangling: ['true'] } }); - if (images.length > 0) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Found ${images.length} dangling images, cleaning up...`); - let removedCount = 0; - for (const image of images) { - try { - // Force remove to handle different Docker managers (OrbStack, Colima, Docker Desktop) - await this.docker.getImage(image.Id).remove({ force: true }); - removedCount++; - (0, logger_1.logDebugInfo)(`🐳 🟔 Removed dangling image: ${image.Id.substring(0, 12)}`); - } - catch (error) { - (0, logger_1.logDebugError)(`Error removing dangling image ${image.Id}: ${error}`); - } - } - (0, logger_1.logDebugInfo)(`🐳 🟢 Dangling images cleanup completed: ${removedCount}/${images.length} removed`); - } - } - catch (error) { - (0, logger_1.logDebugError)('Error cleaning up dangling images: ' + error); - } - }; - this.cleanupBuildxBuilder = async () => { - try { - const builderName = 'git-board-flow-multiarch'; - const listCommand = ['docker', 'buildx', 'ls']; - const output = (0, child_process_1.execSync)(listCommand.join(' '), { encoding: 'utf8', stdio: 'pipe' }); - if (output.includes(builderName)) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Cleaning up Buildx builder '${builderName}'...`); - (0, child_process_1.execSync)(`docker buildx rm ${builderName}`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Buildx builder '${builderName}' removed successfully`); - } - } - catch (error) { - (0, logger_1.logDebugError)(`Error cleaning up Buildx builder: ${error}`); - } - }; - this.docker = new dockerode_1.default(); - this.dockerDir = path_1.default.join(process.cwd(), 'docker'); - } - isGitHubActions() { - return process.env.GITHUB_ACTIONS === 'true'; - } - isSelfHostedRunner() { - return process.env.RUNNER_TEMP?.includes('actions-runner') || - process.env.GITHUB_RUN_ID === undefined || - process.env.GITHUB_HOSTED === 'false'; - } - shouldUsePrebuiltImage() { - return this.isGitHubActions() && !this.isSelfHostedRunner(); - } - shouldUseLocalImage() { - return !this.isGitHubActions() || this.isSelfHostedRunner(); - } - getArchitectureType() { - const platform = process.platform; - const arch = process.arch; - if (platform === 'darwin' && arch === 'arm64') - return 'arm64'; - if (platform === 'darwin' && arch === 'x64') - return 'amd64'; - if (platform === 'linux' && arch === 'x64') - return 'amd64'; - if (platform === 'linux' && arch === 'arm64') - return 'arm64'; - if (platform === 'linux' && arch === 'arm') - return 'armv7'; - if (platform === 'win32' && arch === 'x64') - return 'amd64'; - (0, logger_1.logDebugInfo)(`🐳 🟔 Unknown architecture: ${platform}/${arch}, defaulting to amd64`); - return 'amd64'; - } - async checkMultiArchImageInRegistry(param) { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - try { - (0, logger_1.logDebugInfo)(`🐳 🟔 Checking multi-architecture image in registry: ${registryImageName}`); - // Try to inspect the manifest to check if multi-arch image exists - const output = (0, child_process_1.execSync)(`docker manifest inspect ${registryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - (0, logger_1.logDebugInfo)(`🐳 🟔 Manifest output: ${output.substring(0, 500)}...`); - // Check if the manifest contains both architectures - const hasAmd64 = output.includes('"architecture": "amd64"'); - const hasArm64 = output.includes('"architecture": "arm64"'); - (0, logger_1.logDebugInfo)(`🐳 🟔 Registry image check - AMD64: ${hasAmd64}, ARM64: ${hasArm64}`); - return hasAmd64 && hasArm64; - } - catch (error) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Multi-architecture image not found in registry: ${registryImageName} - ${error}`); - // If specific version not found, try latest tag as fallback - if (!imageName.includes('latest')) { - (0, logger_1.logDebugInfo)(`🐳 🟔 Trying latest tag as fallback...`); - const latestImageName = `${this.getImageName(param)}:latest`; - const latestRegistryImageName = `ghcr.io/${param.owner}/${latestImageName}`; - try { - const latestOutput = (0, child_process_1.execSync)(`docker manifest inspect ${latestRegistryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - const hasAmd64Latest = latestOutput.includes('"architecture": "amd64"'); - const hasArm64Latest = latestOutput.includes('"architecture": "arm64"'); - if (hasAmd64Latest && hasArm64Latest) { - (0, logger_1.logDebugInfo)(`🐳 🟢 Found latest multi-architecture image, will use that instead`); - return true; - } - } - catch { - (0, logger_1.logDebugInfo)(`🐳 🟔 Latest image also not found in registry`); - } - } - return false; +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 + +/***/ }), + +/***/ 6771: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kClients } = __nccwpck_require__(2785) +const Agent = __nccwpck_require__(7890) +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = __nccwpck_require__(4347) +const MockClient = __nccwpck_require__(8687) +const MockPool = __nccwpck_require__(6193) +const { matchValue, buildMockOptions } = __nccwpck_require__(9323) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8045) +const Dispatcher = __nccwpck_require__(412) +const Pluralizer = __nccwpck_require__(8891) +const PendingInterceptorsFormatter = __nccwpck_require__(6823) + +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 + + +/***/ }), + +/***/ 8687: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { promisify } = __nccwpck_require__(3837) +const Client = __nccwpck_require__(3598) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) + +/** + * 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 + + +/***/ }), + +/***/ 888: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { UndiciError } = __nccwpck_require__(8045) + +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 +} + + +/***/ }), + +/***/ 410: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = __nccwpck_require__(4347) +const { InvalidArgumentError } = __nccwpck_require__(8045) +const { buildURL } = __nccwpck_require__(3983) + +/** + * 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') } - getImageName(param) { - return param.dockerConfig.getContainerName(); + if (typeof opts.method === 'undefined') { + opts.method = 'GET' } - getImageNameWithTag(param) { - const version = this.generateImageVersion(param); - return `${this.getImageName(param)}:${version}`; + // 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 + } } - generateImageVersion(param) { - if (param.singleAction.version.length > 0) { - return `v${param.singleAction.version}`; - } - // Fallback to latest - return 'latest'; + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() } - generateImageTags(param) { - const baseImageName = this.getImageName(param); - const tags = []; - // Always include the specific version - const version = this.generateImageVersion(param); - tags.push(`${baseImageName}:${version}`); - tags.push(`${baseImageName}:latest`); - return tags; + + 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') } - async checkDockerBuildxAvailable() { - try { - // Check if Docker Buildx is installed - (0, child_process_1.execSync)('docker buildx version', { stdio: 'pipe' }); - // Check if we can create a multi-platform builder - try { - const testBuilderName = 'test-multiarch-builder'; - (0, child_process_1.execSync)(`docker buildx create --name ${testBuilderName} --driver docker-container --platform linux/amd64,linux/arm64`, { stdio: 'pipe' }); - (0, child_process_1.execSync)(`docker buildx rm ${testBuilderName}`, { stdio: 'pipe' }); - (0, logger_1.logDebugInfo)('🐳 🟢 Docker Buildx supports multi-platform builds'); - return true; - } - catch { - (0, logger_1.logDebugInfo)('🐳 🟔 Docker Buildx available but multi-platform not supported, will create custom builder'); - return true; // Still return true, we'll handle the builder creation in buildMultiArchImage - } - } - catch { - (0, logger_1.logDebugInfo)('🐳 🟔 Docker Buildx not available, falling back to single-architecture build'); - return false; - } + if (typeof data === 'undefined') { + throw new InvalidArgumentError('data must be defined') } - async buildMultiArchImage(param) { - const imageTags = this.generateImageTags(param); - const registryImageTags = imageTags.map(tag => `ghcr.io/${param.owner}/${tag}`); - (0, logger_1.logDebugInfo)(`🐳 🟔 Building multi-architecture Docker image with tags: ${imageTags.join(', ')}`); - (0, logger_1.logDebugInfo)(`🐳 🟔 Registry tags: ${registryImageTags.join(', ')}`); - // Authenticate with registry before building - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - // Create or use a multi-platform builder - const builderName = 'git-board-flow-multiarch'; - await this.ensureMultiPlatformBuilder(builderName); - // Build and push multi-architecture image using Docker Buildx - const buildCommand = [ - 'docker', 'buildx', 'build', - '--builder', builderName, - '--platform', 'linux/amd64,linux/arm64', - ...registryImageTags.flatMap(tag => ['--tag', tag]), - '--push', - '--file', path_1.default.join(this.dockerDir, 'Dockerfile'), - this.dockerDir - ]; - (0, logger_1.logDebugInfo)(`🐳 🟔 Executing: ${buildCommand.join(' ')}`); - try { - (0, child_process_1.execSync)(buildCommand.join(' '), { - stdio: 'inherit', - env: { ...process.env, DOCKER_BUILDKIT: '1' } - }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-architecture image built and pushed successfully with tags: ${imageTags.join(', ')}`); - await this.cleanupDanglingImages(); - await this.cleanupBuildxBuilder(); - } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Multi-architecture build failed: ${error}`); - throw error; - } + if (typeof responseOptions !== 'object') { + throw new InvalidArgumentError('responseOptions must be an object') } - async ensureMultiPlatformBuilder(builderName) { - try { - // Check if builder already exists - const listCommand = ['docker', 'buildx', 'ls']; - const output = (0, child_process_1.execSync)(listCommand.join(' '), { encoding: 'utf8', stdio: 'pipe' }); - if (output.includes(builderName)) { - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-platform builder '${builderName}' already exists`); - return; - } - // Create new multi-platform builder - (0, logger_1.logDebugInfo)(`🐳 🟔 Creating multi-platform builder '${builderName}'...`); - const createCommand = [ - 'docker', 'buildx', 'create', - '--name', builderName, - '--driver', 'docker-container', - '--platform', 'linux/amd64,linux/arm64' - ]; - (0, child_process_1.execSync)(createCommand.join(' '), { stdio: 'inherit' }); - // Start the builder - const startCommand = ['docker', 'buildx', 'inspect', '--bootstrap', builderName]; - (0, child_process_1.execSync)(startCommand.join(' '), { stdio: 'inherit' }); - (0, logger_1.logDebugInfo)(`🐳 🟢 Multi-platform builder '${builderName}' created and started successfully`); + } + + /** + * 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') } - catch (error) { - (0, logger_1.logError)(`🐳 šŸ”“ Failed to create multi-platform builder: ${error}`); - throw error; + + 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) } - // ============================== - // 🧼 Misc Helpers - // ============================== - async getContainer(param) { - const containerId = await this.getContainerIdByName(param); - const imageName = this.getImageNameWithTag(param); - if (containerId) - return this.docker.getContainer(containerId); - return this.docker.createContainer({ - Image: imageName, - ExposedPorts: { [`${param.dockerConfig.getPort()}/tcp`]: {} }, - HostConfig: { - PortBindings: { [`${param.dockerConfig.getPort()}/tcp`]: [{ HostPort: param.dockerConfig.getPort().toString() }] }, - }, - name: this.getImageName(param), - }); - } - async waitForContainer(param) { - const maxAttempts = 30; - const interval = 2000; - for (let i = 0; i < maxAttempts; i++) { - try { - const res = await axios_1.default.get(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/health`); - if (res.data.status === 'ready') - return; - } - catch { } - await new Promise(r => setTimeout(r, interval)); - } - throw new Error('Container did not become ready'); + + // 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') } - async getContainerIdByName(param) { - const containers = await this.docker.listContainers({ all: true }); - const found = containers.find(c => c.Names.includes(`/${this.getImageName(param)}`)); - return found?.Id || ''; + + 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') } - async isContainerRunning(param) { - const containers = await this.docker.listContainers({ all: true }); - const container = containers.find(c => c.Names.includes(`/${this.getImageName(param)}`)); - return container?.State === 'running'; + + 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 + } } -exports.DockerRepository = DockerRepository; + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope /***/ }), -/***/ 81503: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 6193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.FileRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const chunked_file_1 = __nccwpck_require__(2469); -const crypto_1 = __nccwpck_require__(6113); -class FileRepository { - constructor() { - this.getFileContent = async (owner, repository, path, token, branch) => { - const octokit = github.getOctokit(token); - try { - const { data } = await octokit.rest.repos.getContent({ - owner, - repo: repository, - path, - ref: branch - }); - if ('content' in data) { - return Buffer.from(data.content, 'base64').toString(); - } - return ''; - } - catch (error) { - (0, logger_1.logError)(`Error getting file content: ${error}.`); - return ''; - } - }; - this.getRepositoryContent = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { - const octokit = github.getOctokit(token); - const fileContents = new Map(); - try { - const getContentRecursively = async (path = '') => { - const { data } = await octokit.rest.repos.getContent({ - owner, - repo: repository, - path, - ref: branch - }); - if (Array.isArray(data)) { - const promises = []; - for (const item of data) { - if (item.type === 'file') { - if (this.isMediaOrPdfFile(item.path) || this.shouldIgnoreFile(item.path, ignoreFiles)) { - ignoredFiles(item.path); - continue; - } - progress(item.path); - const filePromise = (async () => { - const content = await this.getFileContent(owner, repository, item.path, token, branch); - fileContents.set(item.path, content); - })(); - promises.push(filePromise); - } - else if (item.type === 'dir') { - promises.push(getContentRecursively(item.path)); - } - } - await Promise.all(promises); - } - }; - await getContentRecursively(); - return fileContents; - } - catch (error) { - (0, logger_1.logError)(`Error getting repository content: ${error}.`); - return new Map(); - } - }; - this.getChunkedRepositoryContent = async (owner, repository, branch, chunkSize, token, ignoreFiles, progress, ignoredFiles) => { - const fileContents = await this.getRepositoryContent(owner, repository, token, branch, ignoreFiles, progress, ignoredFiles); - const chunkedFilesMap = new Map(); - for (const [path, content] of fileContents.entries()) { - const shasum = this.calculateShasum(content); - chunkedFilesMap.set(path, [ - ...this.getChunksByLines(path, content, shasum, chunkSize), - ...this.getChunksByBlocks(path, content, shasum, chunkSize), - ]); - } - return chunkedFilesMap; - }; - this.getChunksByLines = (path, content, shasum, chunkSize) => { - const chunkedFiles = []; - const lines = content.split('\n'); - const chunks = []; - let currentChunk = []; - for (const line of lines) { - if (this.shouldIgnoreLine(line)) { - continue; - } - currentChunk.push(line.trim()); - if (currentChunk.length >= chunkSize) { - chunks.push([...currentChunk]); - currentChunk = []; - } - } - // Add the last chunk if it's not empty - if (currentChunk.length > 0) { - chunks.push(currentChunk); - } - // Create ChunkedFile objects for each chunk - chunks.forEach((chunkLines, index) => { - const chunkContent = chunkLines.join('\n'); - chunkedFiles.push(new chunked_file_1.ChunkedFile(path, index, 'line', chunkContent, shasum, chunkLines)); - }); - return chunkedFiles; - }; - this.getChunksByBlocks = (path, content, shasum, chunkSize) => { - const chunkedFiles = []; - const blocks = this.extractCodeBlocks(content); - const chunks = []; - let currentChunk = []; - for (const block of blocks) { - currentChunk.push(block.content); - if (currentChunk.length >= chunkSize) { - chunks.push([...currentChunk]); - currentChunk = []; - } - } - // Add the last chunk if it's not empty - if (currentChunk.length > 0) { - chunks.push(currentChunk); - } - // Create ChunkedFile objects for each chunk - chunks.forEach((chunkLines, index) => { - const chunkContent = chunkLines.join('\n'); - chunkedFiles.push(new chunked_file_1.ChunkedFile(path, index, 'block', chunkContent, shasum, chunkLines)); - }); - return chunkedFiles; - }; - this.extractCodeBlocks = (code) => { - const lines = code.split('\n'); - const blocks = []; - let currentBlock; - let braceDepth = 0; - let indentLevel = 0; - const startBlock = (type, name, line, lineNumber) => { - currentBlock = { - type, - name, - content: line + '\n', - startLine: lineNumber, - endLine: lineNumber, - }; - braceDepth = (line.match(/{/g) || []).length - (line.match(/}/g) || []).length; - indentLevel = line.match(/^(\s*)/)?.[1].length ?? 0; - }; - const endBlock = (lineNumber) => { - if (currentBlock) { - currentBlock.endLine = lineNumber; - blocks.push(currentBlock); - currentBlock = undefined; - } - }; - lines.forEach((line, idx) => { - const trimmed = line.trim(); - const lineNumber = idx + 1; - // Detect class or function headers - const functionMatch = trimmed.match(/(?:function|def|fn|async|const|let)\s+(\w+)/); - const classMatch = trimmed.match(/class\s+(\w+)/); - if (!currentBlock && functionMatch) { - startBlock('function', functionMatch[1], line, lineNumber); - } - else if (!currentBlock && classMatch) { - startBlock('class', classMatch[1], line, lineNumber); - } - else if (currentBlock) { - currentBlock.content += line + '\n'; - // Update brace depth - braceDepth += (line.match(/{/g) || []).length; - braceDepth -= (line.match(/}/g) || []).length; - // Or detect dedentation (for Python-style) - const currentIndent = line.match(/^(\s*)/)?.[1].length ?? 0; - const dedented = currentIndent < indentLevel; - if (braceDepth <= 0 && trimmed.endsWith('}') || dedented) { - endBlock(lineNumber); - } - } - }); - // Catch any unfinished block - if (currentBlock) { - currentBlock.endLine = lines.length; - blocks.push(currentBlock); - } - return blocks; - }; - this.shouldIgnoreLine = (line) => { - const trimmed = line.trim(); - return (trimmed === '' || - /^[}\]);]+;?$/.test(trimmed) || - /^import\s.+from\s.+;?$/.test(trimmed) || - /^(return|break|continue|pass);?$/.test(trimmed) || - /^\/\/[-=]*$/.test(trimmed) || // comentarios de separación - /^\/\/\s*(TODO|FIXME)?\s*$/i.test(trimmed) || - /^[\]],?;?$/.test(trimmed) || - /^try\s*{$/.test(trimmed) || - /^}\s*else\s*{$/.test(trimmed) || - /^`;?$/.test(trimmed) || - /^\/\*\*$/.test(trimmed) || - /^\*\/$/.test(trimmed)); - }; - this.getFileTree = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { - const fileContents = await this.getRepositoryContent(owner, repository, token, branch, ignoreFiles, progress, ignoredFiles); - // Create root nodes for both trees - const rootWithContent = { - name: repository, - type: 'directory', - path: '', - children: [] - }; - const rootWithoutContent = { - name: repository, - type: 'directory', - path: '', - children: [] - }; - // Process each file path to build both trees - for (const [filePath, content] of fileContents.entries()) { - const parts = filePath.split('/'); - let currentLevelWithContent = rootWithContent; - let currentLevelWithoutContent = rootWithoutContent; - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - const isLastPart = i === parts.length - 1; - const currentPath = parts.slice(0, i + 1).join('/'); - // Find or create the node in the content tree - let nodeWithContent = currentLevelWithContent.children?.find(n => n.name === part); - if (!nodeWithContent) { - nodeWithContent = { - name: part, - type: isLastPart ? 'file' : 'directory', - path: currentPath, - children: isLastPart ? undefined : [], - content: isLastPart ? content : undefined - }; - if (!currentLevelWithContent.children) { - currentLevelWithContent.children = []; - } - currentLevelWithContent.children.push(nodeWithContent); - } - // Find or create the node in the no-content tree - let nodeWithoutContent = currentLevelWithoutContent.children?.find(n => n.name === part); - if (!nodeWithoutContent) { - nodeWithoutContent = { - name: part, - type: isLastPart ? 'file' : 'directory', - path: currentPath, - children: isLastPart ? undefined : [] - }; - if (!currentLevelWithoutContent.children) { - currentLevelWithoutContent.children = []; - } - currentLevelWithoutContent.children.push(nodeWithoutContent); - } - if (!isLastPart) { - currentLevelWithContent = nodeWithContent; - currentLevelWithoutContent = nodeWithoutContent; - } - } - } - return { - withContent: rootWithContent, - withoutContent: rootWithoutContent - }; - }; - } - isMediaOrPdfFile(path) { - const mediaExtensions = [ - // Image formats - '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico', - // Audio formats - '.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', - // Video formats - '.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', - // PDF - '.pdf' - ]; - const extension = path.toLowerCase().substring(path.lastIndexOf('.')); - return mediaExtensions.includes(extension); + +const { promisify } = __nccwpck_require__(3837) +const Pool = __nccwpck_require__(4634) +const { buildMockDispatch } = __nccwpck_require__(9323) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(4347) +const { MockInterceptor } = __nccwpck_require__(410) +const Symbols = __nccwpck_require__(2785) +const { InvalidArgumentError } = __nccwpck_require__(8045) + +/** + * 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') } - shouldIgnoreFile(filename, ignorePatterns) { - // First check for .DS_Store - if (filename.endsWith('.DS_Store')) { - return true; - } - return ignorePatterns.some(pattern => { - // Convert glob pattern to regex - const regexPattern = pattern - .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) - .replace(/\*/g, '.*') // Convert * to match anything - .replace(/\//g, '\\/'); // Escape forward slashes - // Allow pattern ending on /* to ignore also subdirectories and files inside - if (pattern.endsWith("/*")) { - return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); - } - const regex = new RegExp(`^${regexPattern}$`); - return regex.test(filename); - }); + + 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 + + +/***/ }), + +/***/ 4347: +/***/ ((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') +} + + +/***/ }), + +/***/ 9323: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { MockNotMatchedError } = __nccwpck_require__(888) +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = __nccwpck_require__(4347) +const { buildURL, nop } = __nccwpck_require__(3983) +const { STATUS_CODES } = __nccwpck_require__(3685) +const { + types: { + isPromise + } +} = __nccwpck_require__(3837) + +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] + } } - shuffleArray(array) { - return [...array].sort(() => Math.random() - 0.5); + + 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) } - calculateShasum(content) { - return (0, crypto_1.createHash)('sha256').update(content).digest('hex'); + 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 } -exports.FileRepository = FileRepository; +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } -/***/ }), + const pathSegments = path.split('?') -/***/ 40057: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if (pathSegments.length !== 2) { + return path + } -"use strict"; + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} -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]; } }; +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 } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueRepository = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const milestone_1 = __nccwpck_require__(52298); -class IssueRepository { - constructor() { - this.updateTitleIssueFormat = async (owner, repository, version, issueTitle, issueNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { - try { - const octokit = github.getOctokit(token); - let emoji = 'šŸ¤–'; - const branched = branchManagementAlways || labels.containsBranchedLabel; - if (labels.isHotfix && branched) { - emoji = `šŸ”„${branchManagementEmoji}`; - } - else if (labels.isRelease && branched) { - emoji = `šŸš€${branchManagementEmoji}`; - } - else if ((labels.isBugfix || labels.isBug) && branched) { - emoji = `šŸ›${branchManagementEmoji}`; - } - else if ((labels.isFeature || labels.isEnhancement) && branched) { - emoji = `✨${branchManagementEmoji}`; - } - else if ((labels.isDocs || labels.isDocumentation) && branched) { - emoji = `šŸ“${branchManagementEmoji}`; - } - else if ((labels.isChore || labels.isMaintenance) && branched) { - emoji = `šŸ”§${branchManagementEmoji}`; - } - else if (labels.isHotfix) { - emoji = 'šŸ”„'; - } - else if (labels.isRelease) { - emoji = 'šŸš€'; - } - else if ((labels.isDocs || labels.isDocumentation)) { - emoji = 'šŸ“'; - } - else if (labels.isChore || labels.isMaintenance) { - emoji = 'šŸ”§'; - } - else if (labels.isBugfix || labels.isBug) { - emoji = 'šŸ›'; - } - else if (labels.isFeature || labels.isEnhancement) { - emoji = '✨'; - } - else if (labels.isHelp) { - emoji = 'šŸ†˜'; - } - else if (labels.isQuestion) { - emoji = 'ā“'; - } - let sanitizedTitle = issueTitle - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - let formattedTitle = `${emoji} - ${sanitizedTitle}`; - if (version.length > 0) { - formattedTitle = `${emoji} - ${version} - ${sanitizedTitle}`; - } - if (formattedTitle !== issueTitle) { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - title: formattedTitle, - }); - (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); - return formattedTitle; - } - return undefined; - } - catch (error) { - core.setFailed(`Failed to check or update issue title: ${error}`); - return undefined; - } - }; - this.updateTitlePullRequestFormat = async (owner, repository, pullRequestTitle, issueTitle, issueNumber, pullRequestNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { - try { - const octokit = github.getOctokit(token); - let emoji = 'šŸ¤–'; - const branched = branchManagementAlways || labels.containsBranchedLabel; - if (labels.isHotfix && branched) { - emoji = `šŸ”„${branchManagementEmoji}`; - } - else if (labels.isRelease && branched) { - emoji = `šŸš€${branchManagementEmoji}`; - } - else if ((labels.isBugfix || labels.isBug) && branched) { - emoji = `šŸ›${branchManagementEmoji}`; - } - else if ((labels.isFeature || labels.isEnhancement) && branched) { - emoji = `✨${branchManagementEmoji}`; - } - else if ((labels.isDocs || labels.isDocumentation) && branched) { - emoji = `šŸ“${branchManagementEmoji}`; - } - else if ((labels.isChore || labels.isMaintenance) && branched) { - emoji = `šŸ”§${branchManagementEmoji}`; - } - else if (labels.isHotfix) { - emoji = 'šŸ”„'; - } - else if (labels.isRelease) { - emoji = 'šŸš€'; - } - else if (labels.isBugfix || labels.isBug) { - emoji = 'šŸ›'; - } - else if (labels.isFeature || labels.isEnhancement) { - emoji = '✨'; - } - else if (labels.isDocs || labels.isDocumentation) { - emoji = 'šŸ“'; - } - else if (labels.isChore || labels.isMaintenance) { - emoji = 'šŸ”§'; - } - else if (labels.isHelp) { - emoji = 'šŸ†˜'; - } - else if (labels.isQuestion) { - emoji = 'ā“'; - } - let sanitizedTitle = issueTitle - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 ]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - const formattedTitle = `[#${issueNumber}] ${emoji} - ${sanitizedTitle}`; - if (formattedTitle !== pullRequestTitle) { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: pullRequestNumber, - title: formattedTitle, - }); - (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); - return formattedTitle; - } - return undefined; - } - catch (error) { - core.setFailed(`Failed to check or update issue title: ${error}`); - return undefined; - } - }; - this.cleanTitle = async (owner, repository, issueTitle, issueNumber, token) => { - try { - const octokit = github.getOctokit(token); - let sanitizedTitle = issueTitle - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 ]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - if (sanitizedTitle !== issueTitle) { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - title: sanitizedTitle, - }); - (0, logger_1.logDebugInfo)(`Issue title updated to: ${sanitizedTitle}`); - return sanitizedTitle; - } - return undefined; - } - catch (error) { - core.setFailed(`Failed to check or update issue title: ${error}`); - return undefined; - } - }; - this.updateDescription = async (owner, repo, issueNumber, description, token) => { - const octokit = github.getOctokit(token); - try { - await octokit.rest.issues.update({ - owner, - repo, - issue_number: issueNumber, - body: description, - }); - } - catch (error) { - (0, logger_1.logError)(`Error updating issue description: ${error}`); - throw error; - } - }; - this.getDescription = async (owner, repo, issueNumber, token) => { - if (issueNumber === -1) { - return undefined; - } - const octokit = github.getOctokit(token); - try { - const { data: issue } = await octokit.rest.issues.get({ - owner, - repo, - issue_number: issueNumber, - }); - return issue.body ?? ''; - } - catch (error) { - (0, logger_1.logError)(`Error reading issue #${issueNumber} description: ${error}`); - return undefined; - } - }; - this.getId = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const issueQuery = ` - query($repo: String!, $owner: String!, $issueNumber: Int!) { - repository(name: $repo, owner: $owner) { - issue(number: $issueNumber) { - id - } - } + 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)`) } - `; - const issueResult = await octokit.graphql(issueQuery, { - owner: owner, - repo: repository, - issueNumber, - }); - const issueId = issueResult.repository.issue.id; - (0, logger_1.logDebugInfo)(`Fetched issue ID: ${issueId}`); - return issueId; - }; - this.getMilestone = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - if (issue.milestone) { - return new milestone_1.Milestone(issue.milestone.id, issue.milestone.title, issue.milestone.description ?? ''); - } - else { - return undefined; - } - }; - this.getTitle = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - return issue.title; - } - catch (error) { - (0, logger_1.logError)(`Failed to fetch the issue title: ${error}`); - return undefined; - } - }; - this.getLabels = async (owner, repository, issueNumber, token) => { - if (issueNumber === -1) { - return []; - } - const octokit = github.getOctokit(token); - const { data: labels } = await octokit.rest.issues.listLabelsOnIssue({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - return labels.map(label => label.name); - }; - this.setLabels = async (owner, repository, issueNumber, labels, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.issues.setLabels({ - owner: owner, - repo: repository, - issue_number: issueNumber, - labels: labels, - }); - }; - this.isIssue = async (owner, repository, issueNumber, token) => { - const isPullRequest = await this.isPullRequest(owner, repository, issueNumber, token); - return !isPullRequest; - }; - this.isPullRequest = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - return !!data.pull_request; - }; - this.getHeadBranch = async (owner, repository, issueNumber, token) => { - const isPr = await this.isPullRequest(owner, repository, issueNumber, token); - if (!isPr) { - return undefined; - } - const octokit = github.getOctokit(token); - const pullRequest = await octokit.rest.pulls.get({ - owner, - repo: repository, - pull_number: issueNumber, - }); - return pullRequest.data.head.ref; - }; - this.addComment = async (owner, repository, issueNumber, comment, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.issues.createComment({ - owner: owner, - repo: repository, - issue_number: issueNumber, - body: comment, - }); - (0, logger_1.logDebugInfo)(`Comment added to Issue ${issueNumber}.`); - }; - this.updateComment = async (owner, repository, issueNumber, commentId, comment, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.issues.updateComment({ - owner: owner, - repo: repository, - comment_id: commentId, - body: comment, - }); - (0, logger_1.logDebugInfo)(`Comment ${commentId} updated in Issue ${issueNumber}.`); - }; - this.closeIssue = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); - if (issue.state === 'open') { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - state: 'closed', - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been closed.`); - return true; - } - else { - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already closed.`); - return false; - } - }; - this.openIssue = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner: owner, - repo: repository, - issue_number: issueNumber, - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); - if (issue.state === 'closed') { - await octokit.rest.issues.update({ - owner: owner, - repo: repository, - issue_number: issueNumber, - state: 'open', - }); - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been re-opened.`); - return true; - } - else { - (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already opened.`); - return false; - } - }; - this.getCurrentAssignees = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data: issue } = await octokit.rest.issues.get({ - owner, - repo: repository, - issue_number: issueNumber, - }); - const assignees = issue.assignees; - if (assignees === undefined || assignees === null) { - return []; - } - return assignees.map((assignee) => assignee.login); - } - catch (error) { - (0, logger_1.logError)(`Error getting members of issue: ${error}.`); - return []; - } - }; - this.assignMembersToIssue = async (owner, repository, issueNumber, members, token) => { - const octokit = github.getOctokit(token); - try { - if (members.length === 0) { - (0, logger_1.logDebugInfo)(`No members provided for assignment. Skipping operation.`); - return []; - } - const { data: updatedIssue } = await octokit.rest.issues.addAssignees({ - owner, - repo: repository, - issue_number: issueNumber, - assignees: members, - }); - const updatedAssignees = updatedIssue.assignees || []; - return updatedAssignees.map((assignee) => assignee.login); - } - catch (error) { - (0, logger_1.logError)(`Error assigning members to issue: ${error}.`); - return []; - } - }; - this.getIssueDescription = async (owner, repository, issueNumber, token) => { - const octokit = github.getOctokit(token); - const { data: issue } = await octokit.rest.issues.get({ - owner, - repo: repository, - issue_number: issueNumber, - }); - return issue.body ?? ''; - }; - this.setIssueType = async (owner, repository, issueNumber, labels, issueTypes, token) => { - try { - let issueType = issueTypes.task; - let issueTypeDescription = issueTypes.taskDescription; - let issueTypeColor = issueTypes.taskColor; - if (labels.isHotfix) { - issueType = issueTypes.hotfix; - issueTypeDescription = issueTypes.hotfixDescription; - issueTypeColor = issueTypes.hotfixColor; - } - else if (labels.isRelease) { - issueType = issueTypes.release; - issueTypeDescription = issueTypes.releaseDescription; - issueTypeColor = issueTypes.releaseColor; - } - else if ((labels.isDocs || labels.isDocumentation)) { - issueType = issueTypes.documentation; - issueTypeDescription = issueTypes.documentationDescription; - issueTypeColor = issueTypes.documentationColor; - } - else if (labels.isChore || labels.isMaintenance) { - issueType = issueTypes.maintenance; - issueTypeDescription = issueTypes.maintenanceDescription; - issueTypeColor = issueTypes.maintenanceColor; - } - else if (labels.isBugfix || labels.isBug) { - issueType = issueTypes.bug; - issueTypeDescription = issueTypes.bugDescription; - issueTypeColor = issueTypes.bugColor; - } - else if (labels.isFeature || labels.isEnhancement) { - issueType = issueTypes.feature; - issueTypeDescription = issueTypes.featureDescription; - issueTypeColor = issueTypes.featureColor; - } - else if (labels.isHelp) { - issueType = issueTypes.help; - issueTypeDescription = issueTypes.helpDescription; - issueTypeColor = issueTypes.helpColor; - } - else if (labels.isQuestion) { - issueType = issueTypes.question; - issueTypeDescription = issueTypes.questionDescription; - issueTypeColor = issueTypes.questionColor; - } - const octokit = github.getOctokit(token); - (0, logger_1.logDebugInfo)(`Setting issue type for issue ${issueNumber} to ${issueType}`); - (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); - (0, logger_1.logDebugInfo)(`Issue Type: ${issueType}`); - (0, logger_1.logDebugInfo)(`Issue Type Description: ${issueTypeDescription}`); - (0, logger_1.logDebugInfo)(`Issue Type Color: ${issueTypeColor}`); - // Try to update the issue with the issue type using GraphQL - const issueId = await this.getId(owner, repository, issueNumber, token); - // First, try to find existing issue types in the organization - const { organization } = await octokit.graphql(` - query ($owner: String!) { - organization(login: $owner) { - id - issueTypes(first: 20) { - nodes { - id - name - } - } - } - } - `, { owner }); - (0, logger_1.logDebugInfo)(`Organization ID: ${organization.id}`); - (0, logger_1.logDebugInfo)(`Organization issue types: ${JSON.stringify(organization.issueTypes.nodes)}`); - // Check if the issue type already exists - const existingType = organization.issueTypes.nodes.find((type) => type.name.toLowerCase() === issueType.toLowerCase()); - let issueTypeId; - if (existingType) { - issueTypeId = existingType.id; - (0, logger_1.logDebugInfo)(`Found existing issue type "${issueType}" with ID: ${issueTypeId}`); - } - else { - // Try to create the issue type using GraphQL - try { - (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); - const createResult = await octokit.graphql(` - mutation ($ownerId: ID!, $name: String!, $description: String!, $color: IssueTypeColor!, $isEnabled: Boolean!) { - createIssueType(input: { - ownerId: $ownerId, - name: $name, - description: $description, - color: $color, - isEnabled: $isEnabled - }) { - issueType { - id - } - } - } - `, { - ownerId: organization.id, - name: issueType, - description: issueTypeDescription, - color: issueTypeColor.toUpperCase(), - isEnabled: true, - }); - issueTypeId = createResult.createIssueType.issueType.id; - (0, logger_1.logDebugInfo)(`Created new issue type "${issueType}" with ID: ${issueTypeId}`); - } - catch (createError) { - (0, logger_1.logError)(`Failed to create issue type "${issueType}": ${createError}`); - // If creation fails, we'll fall back to using labels - (0, logger_1.logDebugInfo)(`Falling back to using labels for issue type classification`); - return; - } - } - // Update the issue with the issue type using GraphQL - await octokit.graphql(` - mutation ($issueId: ID!, $issueTypeId: ID!) { - updateIssueIssueType(input: { - issueId: $issueId, - issueTypeId: $issueTypeId - }) { - issue { - id - issueType { - id - name - } - } - } - } - `, { - issueId, - issueTypeId, - }); - (0, logger_1.logDebugInfo)(`Successfully updated issue type to ${issueType}`); - } - catch (error) { - (0, logger_1.logError)(`Failed to update issue type: ${error}`); - // Don't throw the error to prevent breaking the main flow - // The issue will still be processed with labels - (0, logger_1.logDebugInfo)(`Continuing with issue processing despite issue type update failure`); - throw error; - } - }; + 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 +} + + +/***/ }), + +/***/ 6823: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Transform } = __nccwpck_require__(2781) +const { Console } = __nccwpck_require__(6206) + +/** + * 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() + } +} + + +/***/ }), + +/***/ 8891: +/***/ ((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 } + } } -exports.IssueRepository = IssueRepository; /***/ }), -/***/ 67917: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 8266: +/***/ ((module) => { "use strict"; +/* eslint-disable */ -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]; } }; + + +// 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(); } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ProjectRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -const project_detail_1 = __nccwpck_require__(93765); -class ProjectRepository { - constructor() { - this.priorityLabel = "Priority"; - this.sizeLabel = "Size"; - this.statusLabel = "Status"; - /** - * Retrieves detailed information about a GitHub project - * @param projectId - The project number/ID - * @param token - GitHub authentication token - * @returns Promise - The project details - * @throws {Error} If the project is not found or if there are authentication/network issues - */ - this.getProjectDetail = async (projectId, token) => { - try { - // Validate projectId is a valid number - const projectNumber = parseInt(projectId, 10); - if (isNaN(projectNumber)) { - throw new Error(`Invalid project ID: ${projectId}. Must be a valid number.`); - } - const octokit = github.getOctokit(token); - const { data: owner } = await octokit.rest.users.getByUsername({ - username: github.context.repo.owner - }).catch(error => { - throw new Error(`Failed to get owner information: ${error.message}`); - }); - const ownerType = owner.type === 'Organization' ? 'orgs' : 'users'; - const projectUrl = `https://github.com/${ownerType}/${github.context.repo.owner}/projects/${projectId}`; - const ownerQueryField = ownerType === 'orgs' ? 'organization' : 'user'; - const queryProject = ` - query($ownerName: String!, $projectNumber: Int!) { - ${ownerQueryField}(login: $ownerName) { - projectV2(number: $projectNumber) { - id - title - url - } - } - } - `; - const projectResult = await octokit.graphql(queryProject, { - ownerName: github.context.repo.owner, - projectNumber: projectNumber, - }).catch(error => { - throw new Error(`Failed to fetch project data: ${error.message}`); - }); - const projectData = projectResult[ownerQueryField]?.projectV2; - if (!projectData) { - throw new Error(`Project not found: ${projectUrl}`); - } - (0, logger_1.logDebugInfo)(`Project ID: ${projectData.id}`); - (0, logger_1.logDebugInfo)(`Project Title: ${projectData.title}`); - (0, logger_1.logDebugInfo)(`Project URL: ${projectData.url}`); - return new project_detail_1.ProjectDetail({ - id: projectData.id, - title: projectData.title, - url: projectData.url, - type: ownerQueryField, - owner: github.context.repo.owner, - number: projectNumber, - }); - } - catch (error) { - const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; - (0, logger_1.logError)(`Error in getProjectDetail: ${errorMessage}`); - throw error; - } - }; - this.getContentId = async (project, owner, repo, issueOrPullRequestNumber, token) => { - const octokit = github.getOctokit(token); - // Search for the issue or pull request ID in the repository - const issueOrPrQuery = ` - query($owner: String!, $repo: String!, $number: Int!) { - repository(owner: $owner, name: $repo) { - issueOrPullRequest: issueOrPullRequest(number: $number) { - ... on Issue { - id - } - ... on PullRequest { - id - } - } + 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; + } +}; + + +/***/ }), + +/***/ 3198: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const DispatcherBase = __nccwpck_require__(4839) +const FixedQueue = __nccwpck_require__(8266) +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(2785) +const PoolStats = __nccwpck_require__(9689) + +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 } - }`; - const issueOrPrResult = await octokit.graphql(issueOrPrQuery, { - owner, - repo, - number: issueOrPullRequestNumber - }); - if (!issueOrPrResult.repository.issueOrPullRequest) { - console.error(`Issue or PR #${issueOrPullRequestNumber} not found.`); - return undefined; - } - const contentId = issueOrPrResult.repository.issueOrPullRequest.id; - // Search for the item ID in the project with pagination - let cursor = null; - let projectItemId = undefined; - do { - const projectQuery = ` - query($projectId: ID!, $cursor: String) { - node(id: $projectId) { - ... on ProjectV2 { - items(first: 100, after: $cursor) { - pageInfo { - hasNextPage - endCursor - } - nodes { - id - content { - ... on Issue { - id - } - ... on PullRequest { - id - } - } - } - } - } - } - }`; - const projectResult = await octokit.graphql(projectQuery, { - projectId: project.id, - cursor - }); - const items = projectResult.node.items.nodes; - const foundItem = items.find((item) => item.content?.id === contentId); - if (foundItem) { - projectItemId = foundItem.id; - break; - } - cursor = projectResult.node.items.pageInfo.hasNextPage - ? projectResult.node.items.pageInfo.endCursor - : null; - } while (cursor); - return projectItemId; - }; - this.isContentLinked = async (project, contentId, token) => { - const octokit = github.getOctokit(token); - let hasNextPage = true; - let endCursor = null; - let allItems = []; - while (hasNextPage) { - const query = ` - query($projectId: ID!, $after: String) { - node(id: $projectId) { - ... on ProjectV2 { - items(first: 100, after: $after) { - nodes { - content { - ... on PullRequest { - id - } - ... on Issue { - id - } - } - } - pageInfo { - hasNextPage - endCursor - } - } + 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 +} + + +/***/ }), + +/***/ 9689: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(2785) +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__(3198) +const Client = __nccwpck_require__(3598) +const { + InvalidArgumentError +} = __nccwpck_require__(8045) +const util = __nccwpck_require__(3983) +const { kUrl, kInterceptors } = __nccwpck_require__(2785) +const buildConnector = __nccwpck_require__(2067) + +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 + + this.on('connectionError', (origin, targets, error) => { + // If a connection error occurs, we remove the client from the pool, + // and emit a connectionError event. They will not be re-used. + // Fixes https://github.com/nodejs/undici/issues/3895 + for (const target of targets) { + // Do not use kRemoveClient here, as it will close the client, + // but the client cannot be closed in this state. + const idx = this[kClients].indexOf(target) + if (idx !== -1) { + this[kClients].splice(idx, 1) } } + }) + } + + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher } - `; - // logDebugInfo(`Query: ${query}`); - // logDebugInfo(`Project ID: ${project.id}`); - // logDebugInfo(`Content ID: ${contentId}`); - // logDebugInfo(`After cursor: ${endCursor}`); - const result = await octokit.graphql(query, { - projectId: project.id, - after: endCursor, - }); - // logDebugInfo(`Result: ${JSON.stringify(result, null, 2)}`); - const items = result.node.items.nodes; - allItems = allItems.concat(items); - hasNextPage = result.node.items.pageInfo.hasNextPage; - endCursor = result.node.items.pageInfo.endCursor; - } - return allItems.some((item) => item.content && item.content.id === contentId); - }; - this.linkContentId = async (project, contentId, token) => { - const alreadyLinked = await this.isContentLinked(project, contentId, token); - if (alreadyLinked) { - (0, logger_1.logDebugInfo)(`Content ${contentId} is already linked to project ${project.id}.`); - return false; - } - const octokit = github.getOctokit(token); - const linkMutation = ` - mutation($projectId: ID!, $contentId: ID!) { - addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) { - item { - id - } - } - } - `; - const linkResult = await octokit.graphql(linkMutation, { - projectId: project.id, - contentId: contentId, - }); - (0, logger_1.logDebugInfo)(`Linked ${contentId} with id ${linkResult.addProjectV2ItemById.item.id} to project ${project.id}`); - return true; - }; - this.setSingleSelectFieldValue = async (project, owner, repo, issueOrPullRequestNumber, fieldName, fieldValue, token) => { - const contentId = await this.getContentId(project, owner, repo, issueOrPullRequestNumber, token); - if (!contentId) { - (0, logger_1.logError)(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); - throw new Error(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); - } - (0, logger_1.logDebugInfo)(`Content ID: ${contentId}`); - const octokit = github.getOctokit(token); - // Get the field ID and current value - const fieldQuery = ` - query($projectId: ID!, $after: String) { - node(id: $projectId) { - ... on ProjectV2 { - fields(first: 20) { - nodes { - ... on ProjectV2SingleSelectField { - id - name - options { - id - name - } - } - } - } - items(first: 100, after: $after) { - pageInfo { - hasNextPage - endCursor - } - nodes { - id - fieldValues(first: 20) { - nodes { - ... on ProjectV2ItemFieldSingleSelectValue { - field { - ... on ProjectV2SingleSelectField { - name - } - } - optionId - } - } - } - } - } - } - } - }`; - let hasNextPage = true; - let endCursor = null; - let currentItem = null; - // Get the field and option information from the first page - const initialFieldResult = await octokit.graphql(fieldQuery, { - projectId: project.id, - after: null - }); - const targetField = initialFieldResult.node.fields.nodes.find((f) => f.name === fieldName); - (0, logger_1.logDebugInfo)(`Target field: ${JSON.stringify(targetField, null, 2)}`); - if (!targetField) { - (0, logger_1.logError)(`Field '${fieldName}' not found or is not a single-select field.`); - throw new Error(`Field '${fieldName}' not found or is not a single-select field.`); - } - const targetOption = targetField.options.find((opt) => opt.name === fieldValue); - (0, logger_1.logDebugInfo)(`Target option: ${JSON.stringify(targetOption, null, 2)}`); - if (!targetOption) { - (0, logger_1.logError)(`Option '${fieldValue}' not found for field '${fieldName}'.`); - throw new Error(`Option '${fieldValue}' not found for field '${fieldName}'.`); - } - // Now search for the item through all pages - while (hasNextPage) { - const fieldResult = await octokit.graphql(fieldQuery, { - projectId: project.id, - after: endCursor - }); - // logDebugInfo(`Field result: ${JSON.stringify(fieldResult, null, 2)}`); - // Check current value in current page - currentItem = fieldResult.node.items.nodes.find((item) => item.id === contentId); - if (currentItem) { - // logDebugInfo(`Current item: ${JSON.stringify(currentItem, null, 2)}`); - const currentFieldValue = currentItem.fieldValues.nodes.find((value) => value.field?.name === fieldName); - if (currentFieldValue && currentFieldValue.optionId === targetOption.id) { - (0, logger_1.logDebugInfo)(`Field '${fieldName}' is already set to '${fieldValue}'. No update needed.`); - return false; - } - break; // Found the item, no need to continue pagination - } - hasNextPage = fieldResult.node.items.pageInfo.hasNextPage; - endCursor = fieldResult.node.items.pageInfo.endCursor; - } - (0, logger_1.logDebugInfo)(`Target field ID: ${targetField.id}`); - (0, logger_1.logDebugInfo)(`Target option ID: ${targetOption.id}`); - const mutation = ` - mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { - updateProjectV2ItemFieldValue( - input: { - projectId: $projectId, - itemId: $itemId, - fieldId: $fieldId, - value: { singleSelectOptionId: $optionId } - } - ) { - projectV2Item { - id - } - } - }`; - const mutationResult = await octokit.graphql(mutation, { - projectId: project.id, - itemId: contentId, - fieldId: targetField.id, - optionId: targetOption.id - }); - return !!mutationResult.updateProjectV2ItemFieldValue.projectV2Item; - }; - this.setTaskPriority = async (project, owner, repo, issueOrPullRequestNumber, priorityLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.priorityLabel, priorityLabel, token); - this.setTaskSize = async (project, owner, repo, issueOrPullRequestNumber, sizeLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.sizeLabel, sizeLabel, token); - this.moveIssueToColumn = async (project, owner, repo, issueOrPullRequestNumber, columnName, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.statusLabel, columnName, token); - this.getRandomMembers = async (organization, membersToAdd, currentMembers, token) => { - if (membersToAdd === 0) { - return []; - } - const octokit = github.getOctokit(token); - try { - const { data: teams } = await octokit.rest.teams.list({ - org: organization, - }); - if (teams.length === 0) { - (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); - return []; - } - const membersSet = new Set(); - for (const team of teams) { - (0, logger_1.logDebugInfo)(`Checking team: ${team.slug}`); - const { data: members } = await octokit.rest.teams.listMembersInOrg({ - org: organization, - team_slug: team.slug, - }); - (0, logger_1.logDebugInfo)(`Members: ${members.length}`); - members.forEach((member) => membersSet.add(member.login)); - } - const allMembers = Array.from(membersSet); - const availableMembers = allMembers.filter((member) => !currentMembers.includes(member)); - if (availableMembers.length === 0) { - (0, logger_1.logDebugInfo)(`No available members to assign for organization ${organization}.`); - return []; - } - if (membersToAdd >= availableMembers.length) { - (0, logger_1.logDebugInfo)(`Requested size (${membersToAdd}) exceeds available members (${availableMembers.length}). Returning all available members.`); - return availableMembers; - } - const shuffled = availableMembers.sort(() => Math.random() - 0.5); - return shuffled.slice(0, membersToAdd); - } - catch (error) { - (0, logger_1.logError)(`Error getting random members: ${error}.`); - } - return []; - }; - this.getAllMembers = async (organization, token) => { - const octokit = github.getOctokit(token); - try { - const { data: teams } = await octokit.rest.teams.list({ - org: organization, - }); - if (teams.length === 0) { - (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); - return []; - } - const membersSet = new Set(); - for (const team of teams) { - const { data: members } = await octokit.rest.teams.listMembersInOrg({ - org: organization, - team_slug: team.slug, - }); - members.forEach((member) => membersSet.add(member.login)); - } - return Array.from(membersSet); - } - catch (error) { - (0, logger_1.logError)(`Error getting all members: ${error}.`); - } - return []; - }; - this.getUserFromToken = async (token) => { - const octokit = github.getOctokit(token); - const { data: user } = await octokit.rest.users.getAuthenticated(); - return user.login; - }; - this.findTag = async (owner, repo, tag, token) => { - const octokit = github.getOctokit(token); - try { - const { data: foundTag } = await octokit.rest.git.getRef({ - owner, - repo, - ref: `tags/${tag}`, - }); - return foundTag; - } - catch (err) { - return undefined; - } - }; - this.getTagSHA = async (owner, repo, tag, token) => { - const foundTag = await this.findTag(owner, repo, tag, token); - if (!foundTag) { - (0, logger_1.logError)(`The '${tag}' tag does not exist in the remote repository`); - return undefined; - } - return foundTag.object.sha; - }; - this.updateTag = async (owner, repo, sourceTag, targetTag, token) => { - const sourceTagSHA = await this.getTagSHA(owner, repo, sourceTag, token); - if (!sourceTagSHA) { - (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); - return; - } - const foundTargetTag = await this.findTag(owner, repo, targetTag, token); - const refName = `tags/${targetTag}`; - const octokit = github.getOctokit(token); - if (foundTargetTag) { - (0, logger_1.logDebugInfo)(`Updating the '${targetTag}' tag to point to the '${sourceTag}' tag`); - await octokit.rest.git.updateRef({ - owner, - repo, - ref: refName, - sha: sourceTagSHA, - force: true, - }); - } - else { - (0, logger_1.logDebugInfo)(`Creating the '${targetTag}' tag from the '${sourceTag}' tag`); - await octokit.rest.git.createRef({ - owner, - repo, - ref: `refs/${refName}`, - sha: sourceTagSHA, - }); - } - }; - this.updateRelease = async (owner, repo, sourceTag, targetTag, token) => { - // Get the release associated with sourceTag - const octokit = github.getOctokit(token); - const { data: sourceRelease } = await octokit.rest.repos.getReleaseByTag({ - owner, - repo, - tag: sourceTag, - }); - if (!sourceRelease.name || !sourceRelease.body) { - (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); - return undefined; - } - (0, logger_1.logDebugInfo)(`Found release for sourceTag '${sourceTag}': ${sourceRelease.name}`); - // Check if there is a release for targetTag - const { data: releases } = await octokit.rest.repos.listReleases({ - owner, - repo, - }); - const targetRelease = releases.find(r => r.tag_name === targetTag); - let targetReleaseId; - if (targetRelease) { - (0, logger_1.logDebugInfo)(`Updating release for targetTag '${targetTag}'`); - // Update the target release with the content from the source release - await octokit.rest.repos.updateRelease({ - owner, - repo, - release_id: targetRelease.id, - name: sourceRelease.name, - body: sourceRelease.body, - draft: sourceRelease.draft, - prerelease: sourceRelease.prerelease, - }); - targetReleaseId = targetRelease.id; - } - else { - console.log(`Creating new release for targetTag '${targetTag}'`); - // Create a new release for targetTag if it doesn't exist - const { data: newRelease } = await octokit.rest.repos.createRelease({ - owner, - repo, - tag_name: targetTag, - name: sourceRelease.name, - body: sourceRelease.body, - draft: sourceRelease.draft, - prerelease: sourceRelease.prerelease, - }); - targetReleaseId = newRelease.id; - } - (0, logger_1.logInfo)(`Updated release for targetTag '${targetTag}'`); - return targetReleaseId.toString(); - }; - this.createRelease = async (owner, repo, version, title, changelog, token) => { - try { - const octokit = github.getOctokit(token); - const { data: release } = await octokit.rest.repos.createRelease({ - owner, - repo, - tag_name: `v${version}`, - name: `v${version} - ${title}`, - body: changelog, - draft: false, - prerelease: false, - }); - return release.html_url; - } - catch (error) { - (0, logger_1.logError)(`Error creating release: ${error}`); - return undefined; - } - }; - this.createTag = async (owner, repo, branch, tag, token) => { - const octokit = github.getOctokit(token); - try { - // Check if tag already exists - const existingTag = await this.findTag(owner, repo, tag, token); - if (existingTag) { - (0, logger_1.logInfo)(`Tag '${tag}' already exists in repository ${owner}/${repo}`); - return existingTag.object.sha; - } - // Get the latest commit SHA from the specified branch - const { data: ref } = await octokit.rest.git.getRef({ - owner, - repo, - ref: `heads/${branch}`, - }); - // Create the tag - await octokit.rest.git.createRef({ - owner, - repo, - ref: `refs/tags/${tag}`, - sha: ref.object.sha, - }); - (0, logger_1.logInfo)(`Created tag '${tag}' in repository ${owner}/${repo} from branch '${branch}'`); - return ref.object.sha; - } - catch (error) { - (0, logger_1.logError)(`Error creating tag '${tag}': ${JSON.stringify(error, null, 2)}`); - return undefined; + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher + } +} + +module.exports = Pool + + +/***/ }), + +/***/ 7858: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(2785) +const { URL } = __nccwpck_require__(7310) +const Agent = __nccwpck_require__(7890) +const Pool = __nccwpck_require__(4634) +const DispatcherBase = __nccwpck_require__(4839) +const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8045) +const buildConnector = __nccwpck_require__(2067) + +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 + + +/***/ }), + +/***/ 9459: +/***/ ((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) + } + } +} + + +/***/ }), + +/***/ 5354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const diagnosticsChannel = __nccwpck_require__(7643) +const { uid, states } = __nccwpck_require__(9188) +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = __nccwpck_require__(7578) +const { fireEvent, failWebsocketConnection } = __nccwpck_require__(5515) +const { CloseEvent } = __nccwpck_require__(2611) +const { makeRequest } = __nccwpck_require__(8359) +const { fetching } = __nccwpck_require__(4881) +const { Headers } = __nccwpck_require__(554) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { kHeadersList } = __nccwpck_require__(2785) + +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 } -exports.ProjectRepository = ProjectRepository; /***/ }), -/***/ 20634: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 9188: +/***/ ((module) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + +// 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 +} + + +/***/ }), + +/***/ 2611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { webidl } = __nccwpck_require__(1744) +const { kEnumerableProperty } = __nccwpck_require__(3983) +const { MessagePort } = __nccwpck_require__(1267) + +/** + * @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) } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequestRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const logger_1 = __nccwpck_require__(38836); -class PullRequestRepository { - constructor() { - this.isLinked = async (pullRequestUrl) => { - const htmlContent = await fetch(pullRequestUrl).then(res => res.text()); - return !htmlContent.includes('has_github_issues=false'); - }; - this.updateBaseBranch = async (owner, repository, pullRequestNumber, branch, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.pulls.update({ - owner: owner, - repo: repository, - pull_number: pullRequestNumber, - base: branch, - }); - (0, logger_1.logDebugInfo)(`Changed base branch to ${branch}`); - }; - this.updateDescription = async (owner, repository, pullRequestNumber, description, token) => { - const octokit = github.getOctokit(token); - await octokit.rest.pulls.update({ - owner: owner, - repo: repository, - pull_number: pullRequestNumber, - body: description, - }); - (0, logger_1.logDebugInfo)(`Updated PR #${pullRequestNumber} description with: ${description}`); - }; - this.getCurrentReviewers = async (owner, repository, pullNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data } = await octokit.rest.pulls.listRequestedReviewers({ - owner, - repo: repository, - pull_number: pullNumber, - }); - return data.users.map((user) => user.login); - } - catch (error) { - (0, logger_1.logError)(`Error getting reviewers of PR: ${error}.`); - return []; - } - }; - this.addReviewersToPullRequest = async (owner, repository, pullNumber, reviewers, token) => { - const octokit = github.getOctokit(token); - try { - if (reviewers.length === 0) { - (0, logger_1.logDebugInfo)(`No reviewers provided for addition. Skipping operation.`); - return []; - } - const { data } = await octokit.rest.pulls.requestReviewers({ - owner, - repo: repository, - pull_number: pullNumber, - reviewers: reviewers, - }); - const addedReviewers = data.requested_reviewers || []; - return addedReviewers.map((reviewer) => reviewer.login); - } - catch (error) { - (0, logger_1.logError)(`Error adding reviewers to pull request: ${error}.`); - return []; - } - }; - this.getChangedFiles = async (owner, repository, pullNumber, token) => { - const octokit = github.getOctokit(token); - try { - const { data } = await octokit.rest.pulls.listFiles({ - owner, - repo: repository, - pull_number: pullNumber, - }); - return data.map((file) => ({ - filename: file.filename, - status: file.status - })); - } - catch (error) { - (0, logger_1.logError)(`Error getting changed files from pull request: ${error}.`); - return []; - } - }; - this.getPullRequestChanges = async (owner, repository, pullNumber, token) => { - const octokit = github.getOctokit(token); - const allFiles = []; - try { - for await (const response of octokit.paginate.iterator(octokit.rest.pulls.listFiles, { - owner, - repo: repository, - pull_number: pullNumber, - per_page: 100 - })) { - const filesData = response.data; - allFiles.push(...filesData.map((file) => ({ - filename: file.filename, - status: file.status, - additions: file.additions, - deletions: file.deletions, - patch: file.patch || '' - }))); - } - return allFiles; - } - catch (error) { - (0, logger_1.logError)(`Error getting pull request changes: ${error}.`); - return []; - } - }; + + 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 } -exports.PullRequestRepository = PullRequestRepository; /***/ }), -/***/ 79829: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5444: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SupabaseRepository = void 0; -const supabase_js_1 = __nccwpck_require__(91206); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -const chunked_file_chunk_1 = __nccwpck_require__(64370); -class SupabaseRepository { - constructor(config) { - this.CHUNKS_TABLE = 'chunks'; - this.MAX_BATCH_SIZE = 500; - this.DEFAULT_TIMEOUT = 30000; // 30 seconds - this.setChunkedFile = async (owner, repository, branch, chunkedFile) => { - try { - const insertPromises = chunkedFile.chunks.map(async (chunk, index) => { - const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .insert({ - owner, - repository, - branch, - path: chunkedFile.path, - type: chunkedFile.type, - index: chunkedFile.index, - chunk_index: index, - content: chunk, - shasum: chunkedFile.shasum, - vector: chunkedFile.vector[index], - updated_at: new Date().toISOString() - }); - if (error) { - chunkedFile.vector = []; - (0, logger_1.logError)(`Error inserting index ${chunkedFile.index} chunk ${index} for file ${chunkedFile.path}: ${JSON.stringify(chunkedFile, null, 2)}`); - (0, logger_1.logError)(`Inserting error: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }); - await Promise.all(insertPromises); - } - catch (error) { - (0, logger_1.logError)(`Error setting chunked file ${chunkedFile.path}: ${JSON.stringify(error, null, 2)}`); - // throw error; - } - }; - this.removeChunksByShasum = async (owner, repository, branch, shasum) => { - try { - const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .delete() - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('shasum', shasum); - if (error) { - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error removing chunks by shasum: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getChunkedFileByShasum = async (owner, repository, branch, type, shasum) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('type', type) - .eq('shasum', shasum) - .order('chunk_index'); - if (error) { - (0, logger_1.logError)(`Supabase error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - if (!data) { - return []; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.content, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - }; - this.getChunks = async (owner, repository, branch, path, type, index) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('path', path) - .eq('type', type) - .eq('index', index) - .order('chunk_index'); - if (error) { - (0, logger_1.logError)(`Supabase error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - if (!data) { - return []; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.chunk, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - }; - this.getChunksByShasum = async (owner, repository, branch, shasum) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('shasum', shasum) - .order('chunk_index'); - if (error) { - throw error; - } - if (!data) { - return []; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.chunk, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.updateVector = async (owner, repository, branch, path, index, chunkIndex, vector) => { - try { - const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .update({ vector }) - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('path', path) - .eq('index', index) - .eq('chunk_index', chunkIndex); - if (error) { - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error updating vector: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.matchChunks = async (owner, repository, branch, type, queryEmbedding, matchCount = 5) => { - try { - const { data, error } = await this.supabase - .rpc('match_chunks', { - owner_param: owner, - repository_param: repository, - branch_param: branch, - type_param: type, - query_embedding: queryEmbedding, - match_count: matchCount - }); - if (error) { - (0, logger_1.logError)(`Error matching chunks: ${JSON.stringify(error, null, 2)}`); - throw error; - } - return data.map((doc) => new chunked_file_chunk_1.ChunkedFileChunk(doc.owner, doc.repository, doc.branch, doc.path, doc.type, doc.index, doc.chunk_index, doc.content, doc.shasum, doc.vector)); - } - catch (error) { - (0, logger_1.logError)(`Error matching chunks: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.duplicateChunksByBranch = async (owner, repository, sourceBranch, targetBranch) => { - const count = await this.countBranchEntries(owner, repository, sourceBranch); - (0, logger_1.logDebugInfo)(`Counting chunks in branch ${sourceBranch}: ${count}`); - if (count < 10000) { - await this.duplicateBranchEntries(owner, repository, sourceBranch, targetBranch); - } - else { - const filePaths = await this.getDistinctPaths(owner, repository, sourceBranch); - (0, logger_1.logDebugInfo)(`Counting files in branch ${sourceBranch}: ${filePaths.length}`); - for (const path of filePaths) { - await this.duplicateFileEntries(owner, repository, sourceBranch, path, targetBranch); - } - } - }; - this.removeChunksByBranch = async (owner, repository, branch) => { - const count = await this.countBranchEntries(owner, repository, branch); - (0, logger_1.logDebugInfo)(`Counting chunks in branch ${branch}: ${count}`); - if (count < 10000) { - await this.deleteBranchEntries(owner, repository, branch); - } - else { - const filePaths = await this.getDistinctPaths(owner, repository, branch); - (0, logger_1.logDebugInfo)(`Counting files in branch ${branch}: ${filePaths.length}`); - for (const path of filePaths) { - await this.removeChunksByPath(owner, repository, branch, path); - } - } - (0, logger_1.logDebugInfo)(`Checking if all chunks are deleted from branch ${branch}`); - // Retry logic to ensure all chunks are deleted - const maxRetries = 5; - const retryDelay = 10000; // 1 second - let retryCount = 0; - while (retryCount < maxRetries) { - const { data: chunks, error: chunksError } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch); - if (chunksError) { - (0, logger_1.logError)(`Error checking chunks by branch: ${JSON.stringify(chunksError, null, 2)}`); - throw chunksError; - } - if (!chunks || chunks.length === 0) { - // No chunks found, deletion successful - (0, logger_1.logDebugInfo)(`Removed all chunks from branch ${branch}`); - return; - } - retryCount++; - if (retryCount < maxRetries) { - (0, logger_1.logDebugInfo)(`Chunks still present for branch ${branch}, retrying in ${retryDelay}ms (attempt ${retryCount}/${maxRetries})`); - await new Promise(resolve => setTimeout(resolve, retryDelay)); - } - } - // If we reach here, we've exhausted all retries and chunks still exist - (0, logger_1.logError)(`There are still chunks left for this branch after ${maxRetries} attempts: ${branch}`); - throw new Error(`There are still chunks left for this branch after ${maxRetries} attempts: ${branch}`); - }; - this.getDistinctPaths = async (owner, repository, branch) => { - try { - const { data, error } = await this.supabase - .rpc('get_distinct_paths', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - if (error) { - (0, logger_1.logError)(`Error getting distinct paths for ${owner}/${repository}/${branch}: ${JSON.stringify(error, null, 2)}`); - return []; - } - if (!data) { - (0, logger_1.logInfo)(`No data found for ${owner}/${repository}/${branch}`); - return []; - } - const paths = data.map((doc) => doc.path); - return paths; - } - catch (error) { - (0, logger_1.logError)(`Unexpected error getting distinct paths for ${owner}/${repository}/${branch}: ${JSON.stringify(error, null, 2)}`); - if (error instanceof Error) { - (0, logger_1.logError)(`Error details: ${error.message}`); - (0, logger_1.logError)(`Error stack: ${error.stack}`); - } - return []; - } - }; - this.removeChunksByPath = async (owner, repository, branch, path) => { - const { error } = await this.supabase - .rpc('delete_branch_path_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch, - path_param: path - }); - (0, logger_1.logDebugInfo)(`Removed chunks: ${path} [${branch}]`); - if (error) { - (0, logger_1.logError)(`Error removing chunks by path: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getShasumByPath = async (owner, repository, branch, path) => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('path', path) - .order('index') - .order('chunk_index') - .limit(1); - if (error) { - (0, logger_1.logError)(`Supabase error getting chunks by path: ${JSON.stringify(error, null, 2)}`); - return undefined; - } - if (!data) { - return undefined; - } - return data[0].shasum; - } - catch (error) { - // logError(`Error getting shasum by path: ${JSON.stringify(error, null, 2)}`); - return undefined; - } - }; - this.countBranchEntries = async (owner, repository, branch) => { - try { - const { data, error } = await this.supabase - .rpc('count_branch_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - if (error) { - (0, logger_1.logError)(`Error counting branch entries: ${JSON.stringify(error, null, 2)}`); - return 0; - } - return data || 0; - } - catch (error) { - (0, logger_1.logError)(`Error counting branch entries: ${JSON.stringify(error, null, 2)}`); - return 0; - } - }; - this.duplicateFileEntries = async (owner, repository, sourceBranch, path, targetBranch) => { - try { - (0, logger_1.logDebugInfo)(`Duplicating file entries: ${path} [${sourceBranch}] -> [${targetBranch}]`); - const { error } = await this.supabase - .rpc('duplicate_file_entries', { - owner_param: owner, - repository_param: repository, - source_branch_param: sourceBranch, - path_param: path, - target_branch_param: targetBranch - }); - if (error) { - (0, logger_1.logError)(`Error duplicating file entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error duplicating file entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.duplicateBranchEntries = async (owner, repository, sourceBranch, targetBranch) => { - try { - (0, logger_1.logDebugInfo)(`Duplicating branch entries for ${owner}/${repository}/${sourceBranch} to ${targetBranch}`); - const { error } = await this.supabase - .rpc('duplicate_branch_entries', { - owner_param: owner, - repository_param: repository, - source_branch_param: sourceBranch, - target_branch_param: targetBranch - }); - if (error) { - (0, logger_1.logError)(`Error duplicating branch entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - catch (error) { - (0, logger_1.logError)(`Error duplicating branch entries: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.deleteBranchEntries = async (owner, repository, branch) => { - const { error } = await this.supabase - .rpc('delete_branch_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - if (error) { - (0, logger_1.logError)(`Error removing chunks from branch: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }; - this.getVectorOfChunkContent = async (owner, repository, content) => { - try { - const { data, error } = await this.supabase - .rpc('get_vector_of_chunk_content', { - owner_param: owner, - repository_param: repository, - content_param: content - }); - if (error) { - (0, logger_1.logError)(`Error getting vector of chunk content: ${JSON.stringify(error, null, 2)}`); - throw error; - } - // If no data is found, return empty array - if (!data) { - return []; - } - return data; - } - catch (error) { - (0, logger_1.logError)(`Error getting vector of chunk content: ${JSON.stringify(error, null, 2)}`); - return []; - } - }; - const customFetch = async (input, init) => { - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), this.DEFAULT_TIMEOUT); - try { - const response = await fetch(input, { - ...init, - signal: controller.signal - }); - return response; - } - finally { - clearTimeout(timeoutId); - } - }; - this.supabase = (0, supabase_js_1.createClient)(config.getUrl(), config.getKey(), { - global: { - headers: { - 'X-Client-Info': constants_1.COMMAND - }, - fetch: customFetch - }, - db: { - schema: 'public' - }, - auth: { - autoRefreshToken: true, - persistSession: true, - detectSessionInUrl: true - } - }); - } + +const { maxUnsigned16Bit } = __nccwpck_require__(9188) + +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6113) +} catch { + } -exports.SupabaseRepository = SupabaseRepository; +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = crypto.randomBytes(4) + } -/***/ }), + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0 -/***/ 90779: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 -"use strict"; + 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 + } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; + const 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) } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WorkflowRepository = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const workflow_run_1 = __nccwpck_require__(6845); -const constants_1 = __nccwpck_require__(8593); -class WorkflowRepository { - constructor() { - this.getWorkflows = async (params) => { - const octokit = github.getOctokit(params.tokens.token); - const workflows = await octokit.rest.actions.listWorkflowRunsForRepo({ - owner: params.owner, - repo: params.repo, - }); - return workflows.data.workflow_runs.map(w => new workflow_run_1.WorkflowRun({ - id: w.id, - name: w.name ?? 'unknown', - head_branch: w.head_branch, - head_sha: w.head_sha, - run_number: w.run_number, - event: w.event, - status: w.status ?? 'unknown', - conclusion: w.conclusion ?? null, - created_at: w.created_at, - updated_at: w.updated_at, - url: w.url, - html_url: w.html_url, - })); - }; - this.getActivePreviousRuns = async (params) => { - const workflows = await this.getWorkflows(params); - const runId = parseInt(process.env.GITHUB_RUN_ID, 10); - const workflowName = process.env.GITHUB_WORKFLOW; - return workflows.filter((run) => { - const isSameWorkflow = run.name === workflowName; - const isPrevious = run.id < runId; - const isActive = constants_1.WORKFLOW_ACTIVE_STATUSES.includes(run.status); - return isSameWorkflow && isPrevious && isActive; - }); - }; + + 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 + } } -exports.WorkflowRepository = WorkflowRepository; +module.exports = { + WebsocketFrameSend +} + + +/***/ }), + +/***/ 1688: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { Writable } = __nccwpck_require__(2781) +const diagnosticsChannel = __nccwpck_require__(7643) +const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(9188) +const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(7578) +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(5515) +const { WebsocketFrameSend } = __nccwpck_require__(5444) + +// 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 -/***/ 26365: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 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 -"use strict"; + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ContentInterface = void 0; -const logger_1 = __nccwpck_require__(38836); -class ContentInterface { - constructor() { - this.getContent = (description) => { - try { - if (description === undefined) { - return undefined; - } - if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { - return undefined; - } - return description.split(this.startPattern)[1].split(this.endPattern)[0]; - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; - } - }; - this._addContent = (description, content) => { - if (description.indexOf(this.startPattern) === -1 && description.indexOf(this.endPattern) === -1) { - const newContent = `${this.startPattern}\n${content}\n${this.endPattern}`; - return `${description}\n\n${newContent}`; - } - else { - return undefined; - } - }; - this._updateContent = (description, content) => { - if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { - (0, logger_1.logError)(`The content has a problem with open-close tags: ${this.startPattern} / ${this.endPattern}`); - return undefined; - } - const start = description.split(this.startPattern)[0]; - const mid = `${this.startPattern}\n${content}\n${this.endPattern}`; - const end = description.split(this.endPattern)[1]; - return `${start}${mid}${end}`; - }; - this.updateContent = (description, content) => { - try { - if (description === undefined || content === undefined) { - return undefined; - } - const addedContent = this._addContent(description, content); - if (addedContent !== undefined) { - return addedContent; - } - return this._updateContent(description, content); - } - catch (error) { - (0, logger_1.logError)(`Error updating issue description: ${error}`); - return undefined; - } - }; - } - get _id() { - return `git-board-flow-${this.id}`; - } - get startPattern() { - if (this.visibleContent) { - return ``; + 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 } - 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 } - return `${this._id}-end -->`; - } -} -exports.ContentInterface = ContentInterface; + 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) -/***/ 9913: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.#info.closeInfo = this.parseCloseBody(false, body) -"use strict"; + 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) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueContentInterface = void 0; -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -const content_interface_1 = __nccwpck_require__(26365); -class IssueContentInterface extends content_interface_1.ContentInterface { - constructor() { - super(...arguments); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.internalGetter = async (execution) => { - try { - let number = -1; - if (execution.isSingleAction) { - number = execution.issueNumber; - } - else if (execution.isIssue) { - number = execution.issue.number; - } - else if (execution.isPullRequest) { - number = execution.pullRequest.number; - } - else if (execution.isPush) { - number = execution.issueNumber; - } - else { - return undefined; - } - const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); - return this.getContent(description); - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; - } - }; - this.internalUpdate = async (execution, content) => { - try { - let number = -1; - if (execution.isSingleAction) { - if (execution.isIssue) { - number = execution.issue.number; - } - else if (execution.isPullRequest) { - number = execution.pullRequest.number; - } - else if (execution.isPush) { - number = execution.issueNumber; - } - else { - number = execution.singleAction.issue; - } - } - else if (execution.isIssue) { - number = execution.issue.number; - } - else if (execution.isPullRequest) { - number = execution.pullRequest.number; - } - else if (execution.isPush) { - number = execution.issueNumber; - } - else { - return undefined; - } - const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); - const updated = this.updateContent(description, content); - if (updated === undefined) { - return undefined; + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true } - await this.issueRepository.updateDescription(execution.owner, execution.repo, number, updated, execution.tokens.token); - return updated; - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; - } - }; - } -} -exports.IssueContentInterface = IssueContentInterface; + } + ) + } + // 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() -/***/ 34509: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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" -"use strict"; + const body = this.consume(payloadLength) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ConfigurationHandler = void 0; -const config_1 = __nccwpck_require__(41106); -const logger_1 = __nccwpck_require__(38836); -const issue_content_interface_1 = __nccwpck_require__(9913); -class ConfigurationHandler extends issue_content_interface_1.IssueContentInterface { - constructor() { - super(...arguments); - this.update = async (execution) => { - try { - return await this.internalUpdate(execution, JSON.stringify(execution.currentConfiguration, null, 4)); - } - catch (error) { - (0, logger_1.logError)(`Error updating issue description: ${error}`); - return undefined; - } - }; - this.get = async (execution) => { - try { - const config = await this.internalGetter(execution); - if (config === undefined) { - return undefined; - } - const branchConfig = JSON.parse(config); - return new config_1.Config(branchConfig); - } - catch (error) { - (0, logger_1.logError)(`Error reading issue configuration: ${error}`); - throw error; + 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 + }) } - }; - } - get id() { - return 'configuration'; - } - get visibleContent() { - return false; - } -} -exports.ConfigurationHandler = ConfigurationHandler; + } + 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. -/***/ 2430: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const body = this.consume(payloadLength) -"use strict"; + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CreateReleaseUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class CreateReleaseUseCase { - constructor() { - this.taskId = 'CreateReleaseUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - if (param.singleAction.version.length === 0) { - (0, logger_1.logError)(`Version is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` - ], - })); - return result; - } - else if (param.singleAction.title.length === 0) { - (0, logger_1.logError)(`Title is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE} is not set.` - ], - })); + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } } - else if (param.singleAction.changelog.length === 0) { - (0, logger_1.logError)(`Changelog is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG} is not set.` - ], - })); + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() } - try { - const releaseUrl = await this.projectRepository.createRelease(param.owner, param.repo, param.singleAction.version, param.singleAction.title, param.singleAction.changelog, param.tokens.token); - if (releaseUrl) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Created release \`${releaseUrl}\`.`], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Failed to create release.` - ], - })); - } + + 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() } - catch (error) { - (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Failed to create release.`], - errors: [ - JSON.stringify(error) - ], - })); + + 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 } - return result; - } -} -exports.CreateReleaseUseCase = CreateReleaseUseCase; + 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 -/***/ 45279: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const body = this.consume(this.#info.payloadLength) -"use strict"; + this.#fragments.push(body) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CreateTagUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class CreateTagUseCase { - constructor() { - this.taskId = 'CreateTagUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - if (param.singleAction.version.length === 0) { - (0, logger_1.logError)(`Version is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` - ], - })); - return result; - } - else if (param.currentConfiguration.releaseBranch === undefined) { - (0, logger_1.logError)(`Working branch not found in configuration.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Release branch not found in issue configuration.` - ], - })); - return result; - } - try { - const sha1Tag = await this.projectRepository.createTag(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.singleAction.version, param.tokens.token); - if (sha1Tag) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Tag ${param.singleAction.version} is ready: ${sha1Tag}`], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Failed to create tag ${param.singleAction.version}.` - ], - })); - } - } - catch (error) { - (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Failed to create tag ${param.singleAction.version}.`], - errors: [ - JSON.stringify(error) - ], - })); + // 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 } - return result; + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + break + } } -} -exports.CreateTagUseCase = CreateTagUseCase; + } + /** + * 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() + } -/***/ 98293: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const buffer = Buffer.allocUnsafe(n) + let offset = 0 -"use strict"; + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DeployedActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class DeployedActionUseCase { - constructor() { - this.taskId = 'DeployedActionUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.branchRepository = new branch_repository_1.BranchRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (!param.labels.isDeploy) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to set label \`${param.labels.deployed}\` but there was no \`${param.labels.deploy}\` label.`, - ], - })); - return result; - } - if (param.labels.isDeployed) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to set label \`${param.labels.deployed}\` but it was already set.`, - ], - })); - return result; - } - const labelNames = param.labels.currentIssueLabels.filter(name => name !== param.labels.deploy); - labelNames.push(param.labels.deployed); - await this.issueRepository.setLabels(param.owner, param.repo, param.singleAction.issue, labelNames, param.tokens.token); - (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.singleAction.issue}:`); - (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Label \`${param.labels.deployed}\` added after a success deploy.`, - ], - })); - if (param.currentConfiguration.releaseBranch) { - const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDefaultResult); - const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDevelopResult); - } - else if (param.currentConfiguration.hotfixBranch) { - const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.hotfixBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDefaultResult); - const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.branches.defaultBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); - result.push(...mergeToDevelopResult); - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to assign members to issue.`], - error: error, - })); - } - return result; + 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 + } } -} -exports.DeployedActionUseCase = DeployedActionUseCase; + this.#byteOffset -= n -/***/ }), - -/***/ 67336: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return buffer + } -"use strict"; + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PrepareAIContainerUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const docker_repository_1 = __nccwpck_require__(19097); -const logger_1 = __nccwpck_require__(38836); -class PrepareAIContainerUseCase { - constructor() { - this.taskId = 'PrepareAIContainerUseCase'; - this.dockerRepository = new docker_repository_1.DockerRepository(); - /*private async buildAndPushImage(param: Execution): Promise { - const imageName = this.dockerRepository.getImageName(param); - - const localExists = await this.dockerRepository.imageExists(param); - if (!localExists) { - logDebugInfo('🐳 🟔 Local image not found, building...'); - await this.dockerRepository.buildImage(param); - } else { - logDebugInfo('🐳 🟢 Local image already exists, skipping build'); - } - - logInfo('🐳 🟔 Pushing image to registry...'); - // await this.dockerRepository.pushImageToRegistry(param, imageName); - }*/ - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - const version = param.singleAction.version; - if (version.length === 0) { - (0, logger_1.logError)(`No version specified, skipping version check`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`No version specified, skipping build`], - })); - return results; - } - const imageName = this.dockerRepository.getImageNameWithTag(param); - (0, logger_1.logInfo)(`🐳 🟔 Checking if v${version} already exists in registry...`); - (0, logger_1.logInfo)(`🐳 🟔 Image: ${imageName}`); - const versionExists = await this.dockerRepository.checkVersionExistsInRegistry(param); - if (versionExists) { - (0, logger_1.logInfo)(`🐳 🟢 v${version} already exists in registry, skipping build`); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`v${version} already exists in registry: ${imageName}`], - })); - return results; - } - else { - (0, logger_1.logInfo)(`🐳 🟔 v${version} not found in registry, proceeding with build...`); - } - (0, logger_1.logInfo)('🐳 🟔 Building and pushing new image...'); - await this.dockerRepository.buildImage(param); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Image built and pushed successfully: ${this.dockerRepository.getImageName(param)}`], - })); - } - catch (error) { - (0, logger_1.logError)(`Error in ${this.taskId}: ${error}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Error preparing AI container: ${error}`], - })); - } - return results; + 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) } -} -exports.PrepareAIContainerUseCase = PrepareAIContainerUseCase; + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } -/***/ }), + return { code } + } -/***/ 19029: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) -"use strict"; + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PublishGithubActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const constants_1 = __nccwpck_require__(8593); -const logger_1 = __nccwpck_require__(38836); -class PublishGithubActionUseCase { - constructor() { - this.taskId = 'PublishGithubActionUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); + if (code !== undefined && !isValidStatusCode(code)) { + return null } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - if (param.singleAction.version.length === 0) { - (0, logger_1.logError)(`Version is not set.`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` - ], - })); - return result; - } - const sourceTag = `v${param.singleAction.version}`; - const targetTag = sourceTag.split('.')[0]; - try { - await this.projectRepository.updateTag(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); - const releaseId = await this.projectRepository.updateRelease(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); - if (releaseId) { - (0, logger_1.logInfo)(`Updated release \`${targetTag}\` from \`${sourceTag}\`: ${releaseId}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Updated release \`${targetTag}\` from \`${sourceTag}\`.`], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Failed to update release \`${targetTag}\` from \`${sourceTag}\`.` - ], - })); - } - } - catch (error) { - (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Failed to update release \`${targetTag}\` from \`${sourceTag}\`.`], - errors: [ - JSON.stringify(error) - ], - })); - } - return result; + + 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 } -exports.PublishGithubActionUseCase = PublishGithubActionUseCase; /***/ }), -/***/ 17757: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7578: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.VectorActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const docker_repository_1 = __nccwpck_require__(19097); -const file_repository_1 = __nccwpck_require__(81503); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -class VectorActionUseCase { - constructor() { - this.taskId = 'VectorActionUseCase'; - this.dockerRepository = new docker_repository_1.DockerRepository(); - this.fileRepository = new file_repository_1.FileRepository(); - this.CODE_INSTRUCTION_BLOCK = "Represent the code for semantic search"; - this.CODE_INSTRUCTION_LINE = "Represent each line of code for retrieval"; - this.checkChunksInSupabase = async (param, branch, chunkedFilesMap) => { - const results = []; - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - const remotePaths = await supabaseRepository.getDistinctPaths(param.owner, param.repo, branch); - // Get all local paths from chunkedFiles - const localPaths = new Set(Array.from(chunkedFilesMap.keys())); - // Find paths that exist in Supabase but not in the current branch - const pathsToRemove = remotePaths.filter(path => !localPaths.has(path)); - if (pathsToRemove.length > 0 && remotePaths.length > 0) { - (0, logger_1.logInfo)(`šŸ“¦ Found ${pathsToRemove.length} paths to remove from AI index as they no longer exist in the branch ${branch}.`); - for (const path of pathsToRemove) { - try { - await supabaseRepository.removeChunksByPath(param.owner, param.repo, branch, path); - (0, logger_1.logInfo)(`šŸ“¦ āœ… Removed chunks for path: ${path}`); - } - catch (error) { - (0, logger_1.logError)(`šŸ“¦ āŒ Error removing chunks for path ${path}: ${JSON.stringify(error, null, 2)}`); - } - } - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Removed ${pathsToRemove.length} paths from AI index as they no longer exist in \`${branch}\`.`, - ], - })); - } - else { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - return results; - }; - this.uploadChunksToSupabase = async (param, branch, chunkedFilesMap) => { - const results = []; - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - const processedChunkedFiles = []; - const startTime = Date.now(); - const chunkedPaths = Array.from(chunkedFilesMap.keys()); - for (let i = 0; i < chunkedPaths.length; i++) { - const path = chunkedPaths[i]; - const chunkedFiles = chunkedFilesMap.get(path) || []; - const progress = ((i + 1) / chunkedPaths.length) * 100; - const currentTime = Date.now(); - const elapsedTime = (currentTime - startTime) / 1000; // in seconds - const estimatedTotalTime = (elapsedTime / (i + 1)) * chunkedPaths.length; - const remainingTime = estimatedTotalTime - elapsedTime; - (0, logger_1.logSingleLine)(`šŸ”˜ ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Checking [${path}]`); - const remoteShasum = await supabaseRepository.getShasumByPath(param.owner, param.repo, branch, path); - if (remoteShasum) { - if (remoteShasum === chunkedFiles[0].shasum) { - (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File indexed [${path}]`); - continue; - } - else if (remoteShasum !== chunkedFiles[0].shasum) { - (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File has changes and must be reindexed [${path}]`); - await supabaseRepository.removeChunksByPath(param.owner, param.repo, branch, path); - } - } - // Process chunks in parallel with concurrency limit - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const maxWorkers = systemInfo.parameters.max_workers; - const chunkPromises = []; - let activeWorkers = 0; - for (let j = 0; j < chunkedFiles.length; j++) { - const chunkedFile = chunkedFiles[j]; - const chunkProgress = ((j + 1) / chunkedFiles.length) * 100; - // Wait if we have reached the limit of workers - while (activeWorkers >= maxWorkers) { - await Promise.race(chunkPromises); - activeWorkers = chunkPromises.filter(p => !p).length; - } - const processChunk = async () => { - try { - (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Vectorizing [${chunkedFile.path}]`); - const existingVectors = []; - const existingChunks = []; - const chunksToProcess = []; - for (const chunk of chunkedFile.chunks) { - const vector = await supabaseRepository.getVectorOfChunkContent(param.owner, param.repo, chunk); - if (vector.length > 0) { - existingVectors.push(vector); - existingChunks.push(chunk); - } - else { - chunksToProcess.push(chunk); - } - } - const cachedPercentage = (existingChunks.length / chunkedFile.chunks.length) * 100; - (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Vectorizing [${chunkedFile.path}] - ${cachedPercentage.toFixed(1)}% cached`); - let embeddings = []; - let chunks = []; - if (chunksToProcess.length > 0) { - const newEmbeddings = await this.dockerRepository.getEmbedding(param, chunksToProcess.map(chunk => [chunkedFile.type === 'block' ? this.CODE_INSTRUCTION_BLOCK : this.CODE_INSTRUCTION_LINE, chunk])); - embeddings = [...existingVectors, ...newEmbeddings]; - chunks = [...existingChunks, ...chunksToProcess]; - } - else { - embeddings = existingVectors; - chunks = existingChunks; - } - chunkedFile.vector = embeddings; - chunkedFile.chunks = chunks; - (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Storing [${chunkedFile.path}]`); - await supabaseRepository.setChunkedFile(param.owner, param.repo, branch, chunkedFile); - processedChunkedFiles.push(chunkedFile); - } - catch (error) { - (0, logger_1.logError)(`Error processing chunk ${j + 1} of file ${path}: ${JSON.stringify(error, null, 2)}`); - } - }; - const chunkPromise = processChunk(); - chunkPromises.push(chunkPromise); - activeWorkers++; - chunkPromise.finally(() => { - activeWorkers--; - }); - } - // Wait for all chunks of the current file to be processed - await Promise.all(chunkPromises); - } - const totalDurationSeconds = (Date.now() - startTime) / 1000; - (0, logger_1.logInfo)(`šŸ“¦ šŸš€ All chunked files stored ${param.owner}/${param.repo}/${branch}. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, true); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `All chunked files up to date in AI index for \`${branch}\`. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, - ], - })); - return results; - }; - this.duplicateChunksToBranch = async (param, sourceBranch, targetBranch) => { - const results = []; - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - try { - (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Clearing possible existing chunks from ${targetBranch} for ${param.owner}/${param.repo}.`); - await supabaseRepository.removeChunksByBranch(param.owner, param.repo, targetBranch); - (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Duplicating chunks from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`); - await supabaseRepository.duplicateChunksByBranch(param.owner, param.repo, sourceBranch, targetBranch); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Duplicated chunks from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`, - ], - })); - } - catch (error) { - (0, logger_1.logError)(`šŸ“¦ -> šŸ“¦ āŒ Error duplicating chunks from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Error duplicating chunks from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`, - ], - })); - } - return results; - }; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - await this.dockerRepository.prepareLocalVectorServer(param); - const branch = param.commit.branch || param.branches.main; - let duplicationBranch = undefined; - if (branch === param.branches.main && param.singleAction.isVectorLocalAction) { - (0, logger_1.logInfo)(`šŸ“¦ Chunks from [${param.branches.main}] will be duplicated to [${param.branches.development}] for ${param.owner}/${param.repo}.`); - duplicationBranch = param.branches.development; - } - await this.dockerRepository.startContainer(param); - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const chunkSize = systemInfo.parameters.chunk_size; - const maxWorkers = systemInfo.parameters.max_workers; - (0, logger_1.logInfo)(`šŸ§‘ā€šŸ­ Max workers: ${maxWorkers}`); - (0, logger_1.logInfo)(`🚚 Chunk size: ${chunkSize}`); - (0, logger_1.logInfo)(`šŸ“¦ Getting chunks on ${param.owner}/${param.repo}/${branch}`); - const chunkedFilesMap = await this.fileRepository.getChunkedRepositoryContent(param.owner, param.repo, branch, chunkSize, param.tokens.token, param.ai.getAiIgnoreFiles(), (fileName) => { - (0, logger_1.logSingleLine)(`Checking file ${fileName}`); - }, (fileName) => { - (0, logger_1.logSingleLine)(`Ignoring file ${fileName}`); - }); - (0, logger_1.logInfo)(`šŸ“¦ āœ… Files to index: ${chunkedFilesMap.size}`, true); - results.push(...await this.checkChunksInSupabase(param, branch, chunkedFilesMap)); - results.push(...await this.uploadChunksToSupabase(param, branch, chunkedFilesMap)); - if (duplicationBranch) { - results.push(...await this.duplicateChunksToBranch(param, branch, duplicationBranch)); - } - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Vector action executed successfully.`, - ], - })); - } - catch (error) { - (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - errors: [ - `Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`, - ], - })); - } - finally { - await this.dockerRepository.stopContainer(param); - } - return results; - } + +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') } -exports.VectorActionUseCase = VectorActionUseCase; /***/ }), -/***/ 85016: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5515: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CommitUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -const notify_new_commit_on_issue_use_case_1 = __nccwpck_require__(99054); -const check_changes_issue_size_use_case_1 = __nccwpck_require__(15863); -class CommitUseCase { - constructor() { - this.taskId = 'CommitUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - if (param.commit.commits.length === 0) { - (0, logger_1.logDebugInfo)('No commits found in this push.'); - return results; - } - (0, logger_1.logDebugInfo)(`Branch: ${param.commit.branch}`); - (0, logger_1.logDebugInfo)(`Commits detected: ${param.commit.commits.length}`); - (0, logger_1.logDebugInfo)(`Issue number: ${param.issueNumber}`); - results.push(...(await new notify_new_commit_on_issue_use_case_1.NotifyNewCommitOnIssueUseCase().invoke(param))); - results.push(...(await new check_changes_issue_size_use_case_1.CheckChangesIssueSizeUseCase().invoke(param))); - } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error processing the commits.`, - ], - error: error, - })); - } - return results; - } + +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(7578) +const { states, opcodes } = __nccwpck_require__(9188) +const { MessageEvent, ErrorEvent } = __nccwpck_require__(2611) + +/* 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 } -exports.CommitUseCase = CommitUseCase; +/** + * @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. -/***/ 50854: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 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 -"use strict"; + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueCommentUseCase = void 0; -const logger_1 = __nccwpck_require__(38836); -const ask_ai_use_case_1 = __nccwpck_require__(52268); -const check_issue_comment_language_use_case_1 = __nccwpck_require__(90465); -class IssueCommentUseCase { - constructor() { - this.taskId = 'IssueCommentUseCase'; + // 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 } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - results.push(...await new check_issue_comment_language_use_case_1.CheckIssueCommentLanguageUseCase().invoke(param)); - results.push(...await new ask_ai_use_case_1.AskActionUseCase().invoke(param)); - return results; + } 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 + }) } -exports.IssueCommentUseCase = IssueCommentUseCase; +/** + * @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) -/***/ 58675: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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 + } + } -"use strict"; + return true +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.IssueUseCase = void 0; -const logger_1 = __nccwpck_require__(38836); -const check_permissions_use_case_1 = __nccwpck_require__(58749); -const update_title_use_case_1 = __nccwpck_require__(65107); -const assign_members_to_issue_use_case_1 = __nccwpck_require__(53115); -const check_priority_issue_size_use_case_1 = __nccwpck_require__(151); -const close_not_allowed_issue_use_case_1 = __nccwpck_require__(97826); -const label_deploy_added_use_case_1 = __nccwpck_require__(75678); -const label_deployed_added_use_case_1 = __nccwpck_require__(8388); -const link_issue_project_use_case_1 = __nccwpck_require__(67528); -const prepare_branches_use_case_1 = __nccwpck_require__(84423); -const remove_issue_branches_use_case_1 = __nccwpck_require__(92354); -const remove_not_needed_branches_use_case_1 = __nccwpck_require__(90773); -const update_issue_type_use_case_1 = __nccwpck_require__(81652); -class IssueUseCase { - constructor() { - this.taskId = 'IssueUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - const permissionResult = await new check_permissions_use_case_1.CheckPermissionsUseCase().invoke(param); - const lastAction = permissionResult[permissionResult.length - 1]; - if (!lastAction.success && lastAction.executed) { - results.push(...permissionResult); - results.push(...await new close_not_allowed_issue_use_case_1.CloseNotAllowedIssueUseCase().invoke(param)); - return results; - } - if (param.cleanIssueBranches) { - results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); - } - /** - * Assignees - */ - results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); - /** - * Update title - */ - results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); - /** - * Update issue type - */ - results.push(...await new update_issue_type_use_case_1.UpdateIssueTypeUseCase().invoke(param)); - /** - * Link issue to project - */ - results.push(...await new link_issue_project_use_case_1.LinkIssueProjectUseCase().invoke(param)); - /** - * Check priority issue size - */ - results.push(...await new check_priority_issue_size_use_case_1.CheckPriorityIssueSizeUseCase().invoke(param)); - /** - * Prepare branches - */ - if (param.isBranched) { - results.push(...await new prepare_branches_use_case_1.PrepareBranchesUseCase().invoke(param)); - } - else { - results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); - } - /** - * Remove unnecessary branches - */ - results.push(...await new remove_not_needed_branches_use_case_1.RemoveNotNeededBranchesUseCase().invoke(param)); - /** - * Check if deploy label was added - */ - results.push(...await new label_deploy_added_use_case_1.DeployAddedUseCase().invoke(param)); - /** - * Check if deployed label was added - */ - results.push(...await new label_deployed_added_use_case_1.DeployedAddedUseCase().invoke(param)); - return results; - } +/** + * @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 } -exports.IssueUseCase = IssueUseCase; +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws -/***/ }), + controller.abort() -/***/ 67883: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() + } -"use strict"; + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) + } +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequestReviewCommentUseCase = void 0; -const logger_1 = __nccwpck_require__(38836); -const check_pull_request_comment_language_use_case_1 = __nccwpck_require__(87112); -class PullRequestReviewCommentUseCase { - constructor() { - this.taskId = 'PullRequestReviewCommentUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - results.push(...await new check_pull_request_comment_language_use_case_1.CheckPullRequestCommentLanguageUseCase().invoke(param)); - return results; - } +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived } -exports.PullRequestReviewCommentUseCase = PullRequestReviewCommentUseCase; /***/ }), -/***/ 53478: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4284: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PullRequestUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -const update_title_use_case_1 = __nccwpck_require__(65107); -const assign_members_to_issue_use_case_1 = __nccwpck_require__(53115); -const assign_reviewers_to_issue_use_case_1 = __nccwpck_require__(46275); -const close_issue_after_merging_use_case_1 = __nccwpck_require__(35137); -const check_changes_pull_request_size_use_case_1 = __nccwpck_require__(38129); -const check_priority_pull_request_size_use_case_1 = __nccwpck_require__(67383); -const link_pull_request_issue_use_case_1 = __nccwpck_require__(22175); -const link_pull_request_project_use_case_1 = __nccwpck_require__(64311); -const update_pull_request_description_use_case_1 = __nccwpck_require__(50158); -class PullRequestUseCase { - constructor() { - this.taskId = 'PullRequestUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - (0, logger_1.logDebugInfo)(`PR action ${param.pullRequest.action}`); - (0, logger_1.logDebugInfo)(`PR isOpened ${param.pullRequest.isOpened}`); - (0, logger_1.logDebugInfo)(`PR isMerged ${param.pullRequest.isMerged}`); - (0, logger_1.logDebugInfo)(`PR isClosed ${param.pullRequest.isClosed}`); - if (param.pullRequest.isOpened) { - /** - * Update title - */ - results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); - /** - * Assignees - */ - results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); - /** - * Reviewers - */ - results.push(...await new assign_reviewers_to_issue_use_case_1.AssignReviewersToIssueUseCase().invoke(param)); - /** - * Link Pull Request to projects - */ - results.push(...await new link_pull_request_project_use_case_1.LinkPullRequestProjectUseCase().invoke(param)); - /** - * Link Pull Request to issue - */ - results.push(...await new link_pull_request_issue_use_case_1.LinkPullRequestIssueUseCase().invoke(param)); - /** - * Check priority pull request size - */ - results.push(...await new check_priority_pull_request_size_use_case_1.CheckPriorityPullRequestSizeUseCase().invoke(param)); - /** - * Check changes size - */ - results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); - if (param.ai.getAiPullRequestDescription()) { - /** - * Update pull request description - */ - results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); - } - } - else if (param.pullRequest.isSynchronize) { - /** - * Check changes size - */ - results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); - /** - * Pushed changes to the pull request - */ - if (param.ai.getAiPullRequestDescription()) { - /** - * Update pull request description - */ - results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); - } - } - else if (param.pullRequest.isClosed && param.pullRequest.isMerged) { - /** - * Close issue if needed - */ - results.push(...await new close_issue_after_merging_use_case_1.CloseIssueAfterMergingUseCase().invoke(param)); - } - } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error linking projects/issues with pull request.`, - ], - error: error, - })); - } - return results; - } -} -exports.PullRequestUseCase = PullRequestUseCase; +const { webidl } = __nccwpck_require__(1744) +const { DOMException } = __nccwpck_require__(1037) +const { URLSerializer } = __nccwpck_require__(685) +const { getGlobalOrigin } = __nccwpck_require__(1246) +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(9188) +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = __nccwpck_require__(7578) +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(5515) +const { establishWebSocketConnection } = __nccwpck_require__(5354) +const { WebsocketFrameSend } = __nccwpck_require__(5444) +const { ByteParser } = __nccwpck_require__(1688) +const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3983) +const { getGlobalDispatcher } = __nccwpck_require__(1892) +const { types } = __nccwpck_require__(3837) -/***/ }), +let experimentalWarned = false -/***/ 6479: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } -"use strict"; + #bufferedAmount = 0 + #protocol = '' + #extensions = '' -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SingleActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -const deployed_action_use_case_1 = __nccwpck_require__(98293); -const vector_action_use_case_1 = __nccwpck_require__(17757); -const prepare_ai_container_use_case_1 = __nccwpck_require__(67336); -const publish_github_action_use_case_1 = __nccwpck_require__(19029); -const create_release_use_case_1 = __nccwpck_require__(2430); -const create_tag_use_case_1 = __nccwpck_require__(45279); -class SingleActionUseCase { - constructor() { - this.taskId = 'SingleActionUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - if (!param.singleAction.validSingleAction) { - (0, logger_1.logDebugInfo)(`Not a valid single action: ${param.singleAction.currentSingleAction}`); - return results; - } - if (param.singleAction.isCompileVectorServerAction) { - results.push(...await new prepare_ai_container_use_case_1.PrepareAIContainerUseCase().invoke(param)); - } - else if (param.singleAction.isVectorAction) { - // results.push(...await new PrepareLocalVectorServerUseCase().invoke(param)); - results.push(...await new vector_action_use_case_1.VectorActionUseCase().invoke(param)); - } - else if (param.singleAction.isDeployedAction) { - results.push(...await new deployed_action_use_case_1.DeployedActionUseCase().invoke(param)); - } - else if (param.singleAction.isPublishGithubAction) { - results.push(...await new publish_github_action_use_case_1.PublishGithubActionUseCase().invoke(param)); - } - else if (param.singleAction.isCreateReleaseAction) { - results.push(...await new create_release_use_case_1.CreateReleaseUseCase().invoke(param)); - } - else if (param.singleAction.isCreateTagAction) { - results.push(...await new create_tag_use_case_1.CreateTagUseCase().invoke(param)); - } - } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error executing single action: ${param.singleAction.currentSingleAction}.`, - ], - error: error, - })); - } - return results; + /** + * @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' + }) } -} -exports.SingleActionUseCase = SingleActionUseCase; + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) -/***/ }), + url = webidl.converters.USVString(url) + protocols = options.protocols -/***/ 15863: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin() -"use strict"; + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckChangesIssueSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckChangesIssueSizeUseCase { - constructor() { - this.taskId = 'CheckChangesIssueSizeUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.currentConfiguration.parentBranch === undefined) { - (0, logger_1.logDebugInfo)(`Parent branch is undefined.`); - return result; - } - const headBranch = param.commit.branch; - const baseBranch = param.currentConfiguration.parentBranch; - const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, headBranch, baseBranch, param.sizeThresholds, param.labels, param.tokens.token); - (0, logger_1.logDebugInfo)(`Size: ${size}`); - (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); - (0, logger_1.logDebugInfo)(`Reason: ${reason}`); - (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnIssue}`); - if (param.labels.sizedLabelOnIssue !== size) { - const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); - labelNames.push(size); - await this.issueRepository.setLabels(param.owner, param.repo, param.issueNumber, labelNames, param.tokens.token); - for (const project of param.project.getProjects()) { - await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.issueNumber, githubSize, param.tokens.token); - } - (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.issueNumber}:`); - (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `${reason}, so the issue was resized to ${size}.`, - ], - })); - } - else { - (0, logger_1.logDebugInfo)(`The issue is already at the correct size.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the size of the changes, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + + // 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:' } -} -exports.CheckChangesIssueSizeUseCase = CheckChangesIssueSizeUseCase; + // 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') + } -/***/ 99054: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } -"use strict"; + // 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') + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.NotifyNewCommitOnIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const list_utils_1 = __nccwpck_require__(14990); -const logger_1 = __nccwpck_require__(38836); -const execute_script_use_case_1 = __nccwpck_require__(155); -class NotifyNewCommitOnIssueUseCase { - constructor() { - this.taskId = 'NotifyNewCommitOnIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.mergeBranchPattern = 'Merge branch '; - this.ghAction = 'gh-action: '; - this.separator = '------------------------------------------------------'; + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const branchName = param.commit.branch; - let commitPrefix = ''; - if (param.commitPrefixBuilder.length > 0) { - param.commitPrefixBuilderParams = { - branchName: branchName, - }; - const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); - const prefixResult = await executor.invoke(param); - commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; - (0, logger_1.logDebugInfo)(`Commit prefix: ${commitPrefix}`); - } - let title = ''; - let image = ''; - if (param.release.active) { - title = 'šŸš€ Release News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitReleaseGifs); - } - else if (param.hotfix.active) { - title = 'šŸ”„šŸ› Hotfix News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitHotfixGifs); - } - else if (param.isBugfix) { - title = 'šŸ› Bugfix News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitBugfixGifs); - } - else if (param.isFeature) { - title = '✨ Feature News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitFeatureGifs); - } - else if (param.isDocs) { - title = 'šŸ“ Documentation News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitDocsGifs); - } - else if (param.isChore) { - title = 'šŸ”§ Chore News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitChoreGifs); - } - else { - title = 'šŸŖ„ Automatic News'; - image = (0, list_utils_1.getRandomElement)(param.images.commitAutomaticActions); - } - let commentBody = ` -# ${title} -**Changes on branch \`${param.commit.branch}\`:** + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) -`; - let shouldWarn = false; - for (const commit of param.commit.commits) { - commentBody += ` -${this.separator} + // 11. Let client be this's relevant settings object. -- ${commit.id} by **${commit.author.name}** (@${commit.author.username}) -\`\`\` -${commit.message.replaceAll(`${commitPrefix}: `, '')} -\`\`\` + // 12. Run this step in parallel: -`; - if ((commit.message.indexOf(commitPrefix) !== 0 && commitPrefix.length > 0) - && commit.message.indexOf(this.mergeBranchPattern) !== 0 - && commit.message.indexOf(this.ghAction) !== 0) { - shouldWarn = true; - } - } - if (shouldWarn && commitPrefix.length > 0) { - commentBody += ` -${this.separator} -## āš ļø Attention + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) -One or more commits didn't start with the prefix **${commitPrefix}**. + // 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 -\`\`\` -${commitPrefix}: created hello-world app -\`\`\` -`; - } - if (image && param.images.imagesOnCommit) { - commentBody += ` -${this.separator} + // The extensions attribute must initially return the empty string. -![image](${image}) -`; - } - if (param.issue.reopenOnPush) { - const opened = await this.issueRepository.openIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (opened) { - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was re-opened after pushing new commits to the branch \`${branchName}\`.`, param.tokens.token); - } - } - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, commentBody, param.tokens.token); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to notify the new commit on the issue, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + // 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 }) } -} -exports.NotifyNewCommitOnIssueUseCase = NotifyNewCommitOnIssueUseCase; + 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') + } + } -/***/ 52268: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + let reasonByteLength = 0 -"use strict"; + // 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) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AskActionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const docker_repository_1 = __nccwpck_require__(19097); -const file_repository_1 = __nccwpck_require__(81503); -const issue_repository_1 = __nccwpck_require__(40057); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -class AskActionUseCase { - constructor() { - this.taskId = 'AskActionUseCase'; - this.dockerRepository = new docker_repository_1.DockerRepository(); - this.fileRepository = new file_repository_1.FileRepository(); - this.aiRepository = new ai_repository_1.AiRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.CODE_INSTRUCTION_ASK = "Represent the question for retrieving relevant code snippets"; + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - /** - * Check if the user from the token is found. - */ - if (!param.tokenUser) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - errors: [ - `User from token not found.`, - ], - })); - return results; - } - let description = ''; - let commentBody = ''; - /** - * Get the comment body. - */ - if (param.issue.isIssueComment) { - (0, logger_1.logInfo)(`šŸ”Ž Issue comment body: ${param.issue.commentBody}`); - commentBody = param.issue.commentBody; - description = await this.issueRepository.getDescription(param.owner, param.repo, param.issueNumber, param.tokens.token) ?? ''; - } - else if (param.pullRequest.isPullRequestReviewComment) { - (0, logger_1.logInfo)(`šŸ”Ž Pull request review comment body: ${param.pullRequest.commentBody}`); - commentBody = param.pullRequest.commentBody; - description = await this.issueRepository.getDescription(param.owner, param.repo, param.issueNumber, param.tokens.token) ?? ''; - } - else { - (0, logger_1.logError)(`Not a valid comment body.`); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; - } - if (commentBody.length === 0 || !commentBody.includes(`@${param.tokenUser}`)) { - (0, logger_1.logInfo)(`šŸ”Ž Comment body is empty or does not include @${param.tokenUser}`); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; - } - else { - commentBody = commentBody.replace(param.tokenUser, '').trim(); - } - (0, logger_1.logInfo)(`šŸ”Ž Comment body: ${commentBody}`); - if (param.ai.getOpenRouterModel().length === 0 || param.ai.getOpenRouterApiKey().length === 0) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - errors: [ - `OpenRouter model or API key not found.`, - ], - })); - return results; - } - /** - * Check if the supabase config is found. - */ - if (!param.supabaseConfig) { - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - })); - return results; - } - const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - await this.dockerRepository.startContainer(param); - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const chunkSize = systemInfo.parameters.chunk_size; - const maxWorkers = systemInfo.parameters.max_workers; - (0, logger_1.logInfo)(`šŸ§‘ā€šŸ­ Max workers: ${maxWorkers}`); - (0, logger_1.logInfo)(`🚚 Chunk size: ${chunkSize}`); - (0, logger_1.logInfo)(`šŸ“¦ Getting chunked files for ${param.owner}/${param.repo}/${param.commit.branch}`); - const startTime = Date.now(); - const embeddings = await this.dockerRepository.getEmbedding(param, [ - [this.CODE_INSTRUCTION_ASK, commentBody] - ]); - // logInfo(`šŸ”Ž Embeddings: ${JSON.stringify(embeddings, null, 2)}`); - const types = [ - 'line', - 'block' - ]; - const chunks = []; - for (const type of types) { - (0, logger_1.logInfo)(`šŸ“¦ šŸ”Ž Matching chunks for ${param.owner}/${param.repo}/${param.commit.branch}`); - const foundChunks = await supabaseRepository.matchChunks(param.owner, param.repo, param.commit.branch, type, embeddings[0], 5); - for (const chunk of foundChunks) { - (0, logger_1.logDebugInfo)(`šŸ“¦ šŸ”Ž Chunk type: ${type} - ${chunk.path}`); - } - chunks.push(...foundChunks); - } - const { withContent, withoutContent } = await this.fileRepository.getFileTree(param.owner, param.repo, param.tokens.token, param.commit.branch, param.ai.getAiIgnoreFiles(), (fileName) => { - (0, logger_1.logSingleLine)(`Checking file ${fileName}`); - }, (fileName) => { - (0, logger_1.logSingleLine)(`Ignoring file ${fileName}`); - }); - let workComplete = false; - let relatedFiles = new Map(); - let finalResponse = ''; - while (!workComplete) { - const prompt = ` - # Copilot - You are a highly skilled code analysis assistant, currently working on a GitHub issue. Your role is to assist the developer by answering any related questions they may have. I will provide you with: - 1. The issue description - 2. A user's question about a codebase - 3. A file tree representing the structure of the project - 4. The most relevant code snippets from the codebase related to their query + // 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. - ## Your tasks + const frame = new WebsocketFrameSend() - - Analyze the code snippets in the context of the user's question. - - If the provided code snippets are not directly relevant to the question, analyze the file tree structure to identify potential relevant files and directories. - - Use the file tree to provide additional context if needed (e.g., to understand module relationships). - - Strive to find the most appropriate and complete solution to the user's question. - - When in doubt or if you need more context to provide a confident answer, request additional files. - - Provide your answer **only** in a JSON format, following this structure: + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. - { - "text_response": "Your detailed analysis or answer here.", - "action": "none" | "analyze_files", - "related_files": ["optional", "list", "of", "files"], - "complete": true | false - } + // 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) - ## Important guidelines for text_response + // 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') + } - - Start your response directly with the answer or analysis, without introductory phrases like "Based on the provided code snippets..." or "Based on the file tree..." - - Be concise and direct in your response - - Focus on providing the information requested without unnecessary context or explanations - - If you need more information, state it directly without prefacing phrases + // 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 - ## Explanation + if (!isEstablished(this) || isClosing(this)) { + return + } - - If the provided code snippets and file tree are sufficient to confidently answer the question, set "complete": true and "action": "none". - - If you have any doubts or need more context to provide a complete and accurate answer, set "complete": false, "action": "analyze_files", and list the related file paths you need to investigate further in "related_files". - - If the current code snippets are not relevant to the question, analyze the file tree structure to identify potentially relevant files and request them. - - Do not invent file paths; only request files that logically relate to the question based on the information available. - - Always provide a "text_response" with your reasoning, even if requesting more files. - - When requesting additional files, explain in the text_response why you need those specific files to provide a better answer. + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket - ## Important + // 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. - - **Respond only with the JSON object**, without any extra commentary or text outside of the JSON. - - Prioritize accuracy and completeness over speed - it's better to request more files than to provide an incomplete or uncertain answer. - - If the current code snippets are not helpful, use the file tree structure to guide your search for relevant files. + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.TEXT) - ## Information provided + 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. - ### Issue description + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) - \`\`\` - ${description} - \`\`\` + 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. - ### User's question + const ab = Buffer.from(data, data.byteOffset, data.byteLength) - \`\`\` - ${commentBody} - \`\`\` + const frame = new WebsocketFrameSend(ab) + const buffer = frame.createFrame(opcodes.BINARY) - ### File tree + 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. - \`\`\`json - ${JSON.stringify(withoutContent, null, 2)} - \`\`\` + const frame = new WebsocketFrameSend() - ### Relevant code snippets + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) - ${relatedFiles.size > 0 - ? Array.from(relatedFiles.entries()).map(([path, content]) => `\nFile: ${path}\nCode:\n${content}`).join('\n') - : chunks.map(chunk => `\nFile: ${chunk.path}\nCode:\n${chunk.chunk}`).join('\n')} - `; - const jsonResponse = await this.aiRepository.askJson(param.ai, prompt); - if (!jsonResponse) { - (0, logger_1.logError)(`No result from AI.`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error in ${this.taskId}: No result from AI.`, - ], - })); - return results; - } - (0, logger_1.logInfo)(`šŸ”Ž Result: ${JSON.stringify(jsonResponse, null, 2)}`); - workComplete = jsonResponse.complete; - if (jsonResponse.action === 'analyze_files') { - relatedFiles = this.getRelatedFiles(jsonResponse.related_files, withContent); - } - else if (jsonResponse.action === 'none') { - finalResponse = jsonResponse.text_response; - } - } - const totalDurationSeconds = (Date.now() - startTime) / 1000; - (0, logger_1.logInfo)(`šŸ“¦ šŸ”Ž Matched chunks for ${param.owner}/${param.repo}/${param.commit.branch}:\n Total duration: ${Math.ceil(totalDurationSeconds)} seconds`); - let number = 0; - if (param.issue.isIssueComment) { - number = param.issueNumber; - } - else if (param.pullRequest.isPullRequestReviewComment) { - number = param.pullRequest.number; - } - await this.issueRepository.addComment(param.owner, param.repo, number, finalResponse, param.tokens.token); - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - catch (error) { - (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`, - ], - })); - } - finally { - await this.dockerRepository.stopContainer(param); - } - return results; - } - getRelatedFiles(relatedFiles, tree) { - const result = new Map(); - const findFile = (node, targetPath) => { - if (node.path === targetPath) { - return node; - } - if (node.children) { - for (const child of node.children) { - const found = findFile(child, targetPath); - if (found) { - return found; - } - } - } - return null; - }; - for (const filePath of relatedFiles) { - const fileNode = findFile(tree, filePath); - if (fileNode && fileNode.type === 'file' && fileNode.content) { - result.set(filePath, fileNode.content); - } - } - return result; + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) } -} -exports.AskActionUseCase = AskActionUseCase; + } + + 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]) + } -/***/ 58749: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + get extensions () { + webidl.brandCheck(this, WebSocket) -"use strict"; + return this.#extensions + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckPermissionsUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckPermissionsUseCase { - constructor() { - this.taskId = 'CheckPermissionsUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - /** - * If a release/hotfix issue was opened, check if author is a member of the project. - */ - if (param.isIssue && !param.issue.opened) { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue state is not 'opened'.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - else if (param.isPullRequest && !param.pullRequest.opened) { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Pull request state is not 'opened'.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - try { - const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); - const creator = param.isIssue ? param.issue.creator : param.pullRequest.creator; - const creatorIsTeamMember = creator.length > 0 - && currentProjectMembers.indexOf(creator) > -1; - if (param.labels.isMandatoryBranchedLabel) { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); - if (creatorIsTeamMember) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`@${param.issue.creator} was not authorized to create **[${param.labels.currentIssueLabels.join(',')}]** issues.`], - })); - } - } - else { - (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; + 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) } -} -exports.CheckPermissionsUseCase = CheckPermissionsUseCase; + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } -/***/ }), + get onerror () { + webidl.brandCheck(this, WebSocket) -/***/ 155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this.#events.error + } -"use strict"; + set onerror (fn) { + webidl.brandCheck(this, WebSocket) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CommitPrefixBuilderUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -class CommitPrefixBuilderUseCase { - constructor() { - this.taskId = 'CommitPrefixBuilderUseCase'; + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const branchName = param.commitPrefixBuilderParams.branchName; - const transforms = param.commitPrefixBuilder; // Now it's a list of transforms - const commitPrefix = this.applyTransforms(branchName, transforms); - (0, logger_1.logDebugInfo)(`Commit prefix generated: ${commitPrefix}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [], - payload: { - scriptResult: commitPrefix - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [], - error: error, - })); - } - return result; + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null } - applyTransforms(branchName, transforms) { - // Parse the list of transformations - const transformList = transforms.split(',').map(t => t.trim()); - let result = branchName; - // Apply each transformation sequentially - for (const transform of transformList) { - result = this.applyTransform(result, transform); - } - return result; + } + + 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) } - applyTransform(input, transform) { - switch (transform) { - case "replace-slash": - return input.replace("/", "-"); - case "replace-all": - return input.replace(/[^a-zA-Z0-9-]/g, "-"); - case "lowercase": - return input.toLowerCase(); - case "uppercase": - return input.toUpperCase(); - case "kebab-case": - return input - .replace(/[^a-zA-Z0-9-]/g, "-") - .replace(/-+/g, "-") - .replace(/^-|-$/g, "") - .toLowerCase(); - case "snake-case": - return input - .replace(/[^a-zA-Z0-9-]/g, "_") - .replace(/_+/g, "_") - .replace(/^_|_$/g, "") - .toLowerCase(); - case "camel-case": - return input - .replace(/[^a-zA-Z0-9-]/g, "-") - .split("-") - .map((word, index) => index === 0 ? word.toLowerCase() : - word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) - .join(""); - case "trim": - return input.trim(); - case "remove-numbers": - return input.replace(/\d+/g, ""); - case "remove-special": - return input.replace(/[^a-zA-Z0-9]/g, ""); - case "remove-spaces": - return input.replace(/\s+/g, ""); - case "remove-dashes": - return input.replace(/-+/g, ""); - case "remove-underscores": - return input.replace(/_+/g, ""); - case "clean-dashes": - return input.replace(/-+/g, "-").replace(/^-|-$/g, ""); - case "clean-underscores": - return input.replace(/_+/g, "_").replace(/^_|_$/g, ""); - case "prefix": - return `prefix-${input}`; - case "suffix": - return `${input}-suffix`; - default: - // If not recognized, return without changes - (0, logger_1.logDebugInfo)(`Unknown transform: ${transform}, skipping...`); - return input; - } + + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null } -} -exports.CommitPrefixBuilderUseCase = CommitPrefixBuilderUseCase; + } + get onmessage () { + webidl.brandCheck(this, WebSocket) -/***/ }), + return this.#events.message + } -/***/ 8243: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) -"use strict"; + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GetHotfixVersionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class GetHotfixVersionUseCase { - constructor() { - this.taskId = 'GetHotfixVersionUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - let number = -1; - if (param.isSingleAction) { - number = param.singleAction.issue; - } - else if (param.isIssue) { - number = param.issue.number; - } - else if (param.isPullRequest) { - number = param.pullRequest.number; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem identifying the issue.`], - })); - return result; - } - const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); - if (description === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem getting the description.`], - })); - return result; - } - const baseVersion = (0, content_utils_1.extractVersion)('Base Version', description); - const hotfixVersion = (0, content_utils_1.extractVersion)('Hotfix Version', description); - if (baseVersion === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the base version but there was a problem identifying the version.`], - })); - return result; - } - else if (hotfixVersion === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the hotfix version but there was a problem identifying the version.`], - })); - return result; - } - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - payload: { - baseVersion: baseVersion, - hotfixVersion: hotfixVersion, - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; + } + + 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 } -} -exports.GetHotfixVersionUseCase = GetHotfixVersionUseCase; + } + /** + * @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() + }) -/***/ 35966: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + response.socket.ws = this + this[kByteParser] = parser -"use strict"; + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GetReleaseTypeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class GetReleaseTypeUseCase { - constructor() { - this.taskId = 'GetReleaseTypeUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); + // 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 } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - let number = -1; - if (param.isSingleAction) { - number = param.singleAction.issue; - } - else if (param.isIssue) { - number = param.issue.number; - } - else if (param.isPullRequest) { - number = param.pullRequest.number; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the release type but there was a problem identifying the issue.`], - })); - return result; - } - const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); - if (description === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the release type but there was a problem getting the description.`], - })); - return result; - } - const releaseType = (0, content_utils_1.extractReleaseType)('Release Type', description); - if (releaseType === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the release type but there was a problem identifying the type.`], - })); - return result; - } - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - payload: { - releaseType: releaseType, - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; + + // 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) + } } -exports.GetReleaseTypeUseCase = GetReleaseTypeUseCase; +// 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) + } -/***/ 3827: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return webidl.converters.DOMString(V) +} -"use strict"; +// 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) + } +]) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.GetReleaseVersionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class GetReleaseVersionUseCase { - constructor() { - this.taskId = 'GetReleaseVersionUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); +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 }) } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - let number = -1; - if (param.isSingleAction) { - number = param.singleAction.issue; - } - else if (param.isIssue) { - number = param.issue.number; - } - else if (param.isPullRequest) { - number = param.pullRequest.number; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem identifying the issue.`], - })); - return result; - } - const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); - if (description === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to get the version but there was a problem getting the description.`], - })); - return result; - } - const releaseVersion = (0, content_utils_1.extractVersion)('Release Version', description); - if (releaseVersion === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - })); - return result; - } - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - payload: { - releaseVersion: releaseVersion, - } - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to check action permissions.`], - error: error, - })); - } - return result; + + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) } + } + + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket } -exports.GetReleaseVersionUseCase = GetReleaseVersionUseCase; /***/ }), -/***/ 84462: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5030: +/***/ ((__unused_webpack_module, exports) => { "use strict"; + Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PublishResultUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const list_utils_1 = __nccwpck_require__(14990); -const logger_1 = __nccwpck_require__(38836); -/** - * Publish the resume of actions - */ -class PublishResultUseCase { - constructor() { - this.taskId = 'PublishResultUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - try { - /** - * Comment resume of actions - */ - let title = 'šŸŖ„ Automatic Actions'; - let content = ''; - let stupidGif = ''; - let image; - let errors = ''; - let footer = ''; - if (param.isIssue) { - if (param.issueNotBranched) { - title = 'šŸŖ„ Automatic Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.issueAutomaticActions); - } - else if (param.release.active) { - title = 'šŸš€ Release Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.issueReleaseGifs); - } - else if (param.hotfix.active) { - title = 'šŸ”„šŸ› Hotfix Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.issueHotfixGifs); - } - else if (param.isBugfix) { - title = 'šŸ› Bugfix Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.issueBugfixGifs); - } - else if (param.isFeature) { - title = '✨ Feature Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.issueFeatureGifs); - } - else if (param.isDocs) { - title = 'šŸ“ Documentation Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.issueDocsGifs); - } - else if (param.isChore) { - title = 'šŸ”§ Chore Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.issueChoreGifs); - } - } - else if (param.isPullRequest) { - if (param.release.active) { - title = 'šŸš€ Release Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.pullRequestReleaseGifs); - } - else if (param.hotfix.active) { - title = 'šŸ”„šŸ› Hotfix Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.pullRequestHotfixGifs); - } - else if (param.isBugfix) { - title = 'šŸ› Bugfix Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.pullRequestBugfixGifs); - } - else if (param.isFeature) { - title = '✨ Feature Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.pullRequestFeatureGifs); - } - else if (param.isDocs) { - title = 'šŸ“ Documentation Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.pullRequestDocsGifs); - } - else if (param.isChore) { - title = 'šŸ”§ Chore Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.pullRequestChoreGifs); - } - else { - title = 'šŸŖ„ Automatic Actions'; - image = (0, list_utils_1.getRandomElement)(param.images.pullRequestAutomaticActions); - } - } - if (image) { - if (param.isIssue && param.images.imagesOnIssue) { - stupidGif = `![image](${image})`; - } - else if (param.isPullRequest && param.images.imagesOnPullRequest) { - stupidGif = `![image](${image})`; - } - } - let indexStep = 0; - param.currentConfiguration.results.forEach(r => { - for (const step of r.steps) { - content += `${indexStep + 1}. ${step}\n`; - indexStep++; - } - }); - let indexReminder = 0; - param.currentConfiguration.results.forEach(r => { - for (const reminder of r.reminders) { - footer += `${indexReminder + 1}. ${reminder}\n`; - indexReminder++; - } - }); - let indexError = 0; - param.currentConfiguration.results.forEach(r => { - for (const error of r.errors) { - errors += `${indexError + 1}. -\`\`\` -${error} -\`\`\` -`; - indexError++; - } - }); - if (footer.length > 0) { - footer = ` -## Reminder -${footer} -`; - } - if (errors.length > 0) { - errors = ` -## Errors Found +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } -${errors} + if (typeof process === "object" && process.version !== undefined) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } -Check your project configuration, if everything is okay consider [opening an issue](https://github.com/landamessenger/git-board-flow/issues/new/choose). -`; - } - const commentBody = `# ${title} -${content} -${errors.length > 0 ? errors : ''} + return ""; +} -${stupidGif} +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map -${footer} -šŸš€ Happy coding! - `; - if (content.length === 0) { - return; - } - if (param.isSingleAction) { - await this.issueRepository.addComment(param.owner, param.repo, param.singleAction.issue, commentBody, param.tokens.token); - } - else if (param.isIssue) { - await this.issueRepository.addComment(param.owner, param.repo, param.issue.number, commentBody, param.tokens.token); - } - else if (param.isPullRequest) { - await this.issueRepository.addComment(param.owner, param.repo, param.pullRequest.number, commentBody, param.tokens.token); - } - } - catch (error) { - (0, logger_1.logError)(error); - param.currentConfiguration.results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to publish the resume, but there was a problem.`, - ], - error: error, - })); - } - } -} -exports.PublishResultUseCase = PublishResultUseCase; +/***/ }), +/***/ 2940: +/***/ ((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) -/***/ 69714: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') -"use strict"; + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.StoreConfigurationUseCase = void 0; -const configuration_handler_1 = __nccwpck_require__(34509); -const logger_1 = __nccwpck_require__(38836); -/** - * Store las configuration in the description - */ -class StoreConfigurationUseCase { - constructor() { - this.taskId = 'StoreConfigurationUseCase'; - this.handler = new configuration_handler_1.ConfigurationHandler(); + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - try { - await this.handler.update(param); - } - catch (error) { - (0, logger_1.logError)(error); - } + 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 + } } -exports.StoreConfigurationUseCase = StoreConfigurationUseCase; /***/ }), -/***/ 65107: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3752: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UpdateTitleUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class UpdateTitleUseCase { - constructor() { - this.taskId = 'UpdateTitleUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); +exports.mainRun = mainRun; +const core = __importStar(__nccwpck_require__(2186)); +const commit_use_case_1 = __nccwpck_require__(5016); +const issue_comment_use_case_1 = __nccwpck_require__(854); +const issue_use_case_1 = __nccwpck_require__(8675); +const pull_request_review_comment_use_case_1 = __nccwpck_require__(7883); +const pull_request_use_case_1 = __nccwpck_require__(5041); +const single_action_use_case_1 = __nccwpck_require__(6479); +const logger_1 = __nccwpck_require__(8836); +const constants_1 = __nccwpck_require__(8593); +const chalk_1 = __importDefault(__nccwpck_require__(7037)); +const boxen_1 = __importDefault(__nccwpck_require__(6192)); +const queue_utils_1 = __nccwpck_require__(9800); +async function mainRun(execution) { + const results = []; + await execution.setup(); + if (!execution.welcome) { + /** + * Wait for previous runs to finish + */ + await (0, queue_utils_1.waitForPreviousRuns)(execution).catch((err) => { + (0, logger_1.logError)(`Error waiting for previous runs: ${err}`); + process.exit(1); + }); } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.isIssue) { - if (param.emoji.emojiLabeledTitle) { - let _title = await this.issueRepository.getTitle(param.owner, param.repo, param.issue.number, param.tokens.token) ?? param.issue.title; - let _version = ''; - if (param.release.active) { - _version = param.release.version ?? 'Unknown Version'; - } - else if (param.hotfix.active) { - _version = param.hotfix.version ?? 'Unknown Version'; - } - const title = await this.issueRepository.updateTitleIssueFormat(param.owner, param.repo, _version, _title, param.issue.number, param.issue.branchManagementAlways, param.emoji.branchManagementEmoji, param.labels, param.tokens.token); - if (title) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The issue's title was updated from \`${_title}\` to \`${title}\`.`, - ] - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - else if (param.isPullRequest) { - if (param.emoji.emojiLabeledTitle) { - const issueTitle = await this.issueRepository.getTitle(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (issueTitle === undefined) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update title, but there was a problem.`, - ], - })); - return result; - } - const title = await this.issueRepository.updateTitlePullRequestFormat(param.owner, param.repo, param.pullRequest.title, issueTitle, param.issueNumber, param.pullRequest.number, false, '', param.labels, param.tokens.token); - if (title) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The pull request's title was updated from \`${param.pullRequest.title}\` to \`${title}\`.`, - ] - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } + if (execution.runnedByToken) { + if (execution.isSingleAction && execution.singleAction.validSingleAction) { + (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Executing single action.`); + results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); + return results; + } + (0, logger_1.logInfo)(`User from token (${execution.tokenUser}) matches actor. Ignoring.`); + return results; + } + if (execution.issueNumber === -1) { + if (execution.isSingleAction && execution.singleAction.isSingleActionWithoutIssue) { + results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); + } + else { + (0, logger_1.logInfo)(`Issue number not found. Skipping.`); + } + return results; + } + if (execution.welcome) { + (0, logger_1.logInfo)((0, boxen_1.default)(chalk_1.default.cyan(execution.welcome.title) + '\n' + + execution.welcome.messages.map(message => chalk_1.default.gray(message)).join('\n'), { + padding: 1, + margin: 1, + borderStyle: 'round', + borderColor: 'cyan', + title: constants_1.TITLE, + titleAlignment: 'center' + })); + } + try { + if (execution.isSingleAction) { + results.push(...await new single_action_use_case_1.SingleActionUseCase().invoke(execution)); + } + else if (execution.isIssue) { + if (execution.issue.isIssueComment) { + results.push(...await new issue_comment_use_case_1.IssueCommentUseCase().invoke(execution)); + } + else { + results.push(...await new issue_use_case_1.IssueUseCase().invoke(execution)); } } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update title, but there was a problem.`, - ], - error: error, - })); + else if (execution.isPullRequest) { + if (execution.pullRequest.isPullRequestReviewComment) { + results.push(...await new pull_request_review_comment_use_case_1.PullRequestReviewCommentUseCase().invoke(execution)); + } + else { + results.push(...await new pull_request_use_case_1.PullRequestUseCase().invoke(execution)); + } } - return result; + else if (execution.isPush) { + results.push(...await new commit_use_case_1.CommitUseCase().invoke(execution)); + } + else { + core.setFailed(`Action not handled.`); + } + return results; + } + catch (error) { + core.setFailed(error.message); + return []; } } -exports.UpdateTitleUseCase = UpdateTitleUseCase; /***/ }), -/***/ 53115: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 6925: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AssignMemberToIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class AssignMemberToIssueUseCase { - constructor() { - this.taskId = 'AssignMemberToIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); +exports.runGitHubAction = runGitHubAction; +const core = __importStar(__nccwpck_require__(2186)); +const ai_1 = __nccwpck_require__(4470); +const branches_1 = __nccwpck_require__(5308); +const emoji_1 = __nccwpck_require__(9463); +const execution_1 = __nccwpck_require__(7550); +const hotfix_1 = __nccwpck_require__(7341); +const images_1 = __nccwpck_require__(1721); +const issue_1 = __nccwpck_require__(2632); +const issue_types_1 = __nccwpck_require__(1975); +const labels_1 = __nccwpck_require__(818); +const locale_1 = __nccwpck_require__(2152); +const projects_1 = __nccwpck_require__(1938); +const pull_request_1 = __nccwpck_require__(4179); +const release_1 = __nccwpck_require__(2551); +const single_action_1 = __nccwpck_require__(8024); +const size_threshold_1 = __nccwpck_require__(3835); +const size_thresholds_1 = __nccwpck_require__(8237); +const tokens_1 = __nccwpck_require__(3421); +const workflows_1 = __nccwpck_require__(8553); +const project_repository_1 = __nccwpck_require__(7917); +const publish_resume_use_case_1 = __nccwpck_require__(9813); +const store_configuration_use_case_1 = __nccwpck_require__(9714); +const constants_1 = __nccwpck_require__(8593); +const common_action_1 = __nccwpck_require__(3752); +const supabase_config_1 = __nccwpck_require__(149); +const logger_1 = __nccwpck_require__(8836); +async function runGitHubAction() { + const projectRepository = new project_repository_1.ProjectRepository(); + /** + * Debug + */ + const debug = getInput(constants_1.INPUT_KEYS.DEBUG) == 'true'; + /** + * Single action + */ + const singleAction = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION); + const singleActionIssue = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE); + const singleActionVersion = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION); + const singleActionTitle = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE); + const singleActionChangelog = getInput(constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG); + /** + * Tokens + */ + const token = getInput(constants_1.INPUT_KEYS.TOKEN, { required: true }); + /** + * AI + */ + const openrouterApiKey = getInput(constants_1.INPUT_KEYS.OPENROUTER_API_KEY); + const openrouterModel = getInput(constants_1.INPUT_KEYS.OPENROUTER_MODEL); + const aiPullRequestDescription = getInput(constants_1.INPUT_KEYS.AI_PULL_REQUEST_DESCRIPTION) === 'true'; + const aiMembersOnly = getInput(constants_1.INPUT_KEYS.AI_MEMBERS_ONLY) === 'true'; + const aiIncludeReasoning = getInput(constants_1.INPUT_KEYS.AI_INCLUDE_REASONING) === 'true'; + const aiIgnoreFilesInput = getInput(constants_1.INPUT_KEYS.AI_IGNORE_FILES); + const aiIgnoreFiles = aiIgnoreFilesInput + .split(',') + .map(path => path.trim()) + .filter(path => path.length > 0); + // Provider routing configuration + const openRouterProviderOrderInput = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ORDER); + const openRouterProviderOrder = openRouterProviderOrderInput + .split(',') + .map(provider => provider.trim()) + .filter(provider => provider.length > 0); + const openRouterProviderAllowFallbacks = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_ALLOW_FALLBACKS) === 'true'; + const openRouterProviderRequireParameters = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_REQUIRE_PARAMETERS) === 'true'; + const openRouterProviderDataCollection = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_DATA_COLLECTION); + const openRouterProviderIgnoreInput = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_IGNORE); + const openRouterProviderIgnore = openRouterProviderIgnoreInput + .split(',') + .map(provider => provider.trim()) + .filter(provider => provider.length > 0); + const openRouterProviderQuantizationsInput = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_QUANTIZATIONS); + const openRouterProviderQuantizations = openRouterProviderQuantizationsInput + .split(',') + .map(level => level.trim()) + .filter(level => level.length > 0); + const openRouterProviderSort = getInput(constants_1.INPUT_KEYS.OPENROUTER_PROVIDER_SORT); + const providerRouting = { + ...(openRouterProviderOrder.length > 0 && { order: openRouterProviderOrder }), + ...(openRouterProviderAllowFallbacks !== undefined && { allow_fallbacks: openRouterProviderAllowFallbacks }), + ...(openRouterProviderRequireParameters !== undefined && { require_parameters: openRouterProviderRequireParameters }), + ...(openRouterProviderDataCollection && { data_collection: openRouterProviderDataCollection }), + ...(openRouterProviderIgnore.length > 0 && { ignore: openRouterProviderIgnore }), + ...(openRouterProviderQuantizations.length > 0 && { quantizations: openRouterProviderQuantizations }), + ...(openRouterProviderSort && { sort: openRouterProviderSort }) + }; + /** + * Projects Details + */ + const projectIdsInput = getInput(constants_1.INPUT_KEYS.PROJECT_IDS); + const projectIds = projectIdsInput + .split(',') + .map(id => id.trim()) + .filter(id => id.length > 0); + const projects = []; + for (const projectId of projectIds) { + const detail = await projectRepository.getProjectDetail(projectId, token); + projects.push(detail); } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const desiredAssigneesCount = param.isIssue ? - param.issue.desiredAssigneesCount : param.pullRequest.desiredAssigneesCount; - const number = param.isIssue ? param.issue.number : param.pullRequest.number; - const result = []; - try { - (0, logger_1.logDebugInfo)(`#${number} needs ${desiredAssigneesCount} assignees.`); - const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); - const currentMembers = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); - let remainingAssignees = desiredAssigneesCount - currentMembers.length; - const pullRequestCreatorIsTeamMember = param.isPullRequest - && param.pullRequest.creator.length > 0 - && currentProjectMembers.indexOf(param.pullRequest.creator) > -1 - && !currentMembers.includes(param.pullRequest.creator); - const issueCreatorIsTeamMember = param.isIssue - && param.issue.creator.length > 0 - && currentProjectMembers.indexOf(param.issue.creator) > -1 - && !currentMembers.includes(param.issue.creator); - /** - * Assign PR creator if applicable - */ - if (pullRequestCreatorIsTeamMember) { - const creator = param.pullRequest.creator; - await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); - (0, logger_1.logDebugInfo)(`Assigned PR creator @${creator} to #${number}.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`The pull request was assigned to @${creator} (creator).`], - })); - remainingAssignees--; // Reduce the count of required assignees - } - else if (issueCreatorIsTeamMember) { - const creator = param.issue.creator; - await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); - (0, logger_1.logDebugInfo)(`Assigned Issue creator @${creator} to #${number}.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`The issue was assigned to @${creator} (creator).`], - })); - remainingAssignees--; // Reduce the count of required assignees - } - /** - * Exit if no more assignees are needed - */ - if (remainingAssignees <= 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return result; - } - /** - * Assign remaining members randomly - */ - const members = await this.projectRepository.getRandomMembers(param.owner, remainingAssignees, currentMembers, param.tokens.token); - if (members.length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to assign members to issue, but no one was found.`], - })); - return result; - } - const membersAdded = await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, members, param.tokens.token); - for (const member of membersAdded) { - if (members.includes(member)) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - param.isIssue ? `The issue was assigned to @${member}.` : `The pull request was assigned to @${member}.`, - ], - })); - } + const projectColumnIssueCreated = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_CREATED); + const projectColumnPullRequestCreated = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_CREATED); + const projectColumnIssueInProgress = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_ISSUE_IN_PROGRESS); + const projectColumnPullRequestInProgress = getInput(constants_1.INPUT_KEYS.PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS); + /** + * Images + */ + const imagesOnIssue = getInput(constants_1.INPUT_KEYS.IMAGES_ON_ISSUE) === 'true'; + const imagesOnPullRequest = getInput(constants_1.INPUT_KEYS.IMAGES_ON_PULL_REQUEST) === 'true'; + const imagesOnCommit = getInput(constants_1.INPUT_KEYS.IMAGES_ON_COMMIT) === 'true'; + const imagesIssueAutomaticInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_AUTOMATIC); + const imagesIssueAutomatic = imagesIssueAutomaticInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueAutomatic.length === 0) { + imagesIssueAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.automatic); + } + const imagesIssueFeatureInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_FEATURE); + const imagesIssueFeature = imagesIssueFeatureInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueFeature.length === 0) { + imagesIssueFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.feature); + } + const imagesIssueBugfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_BUGFIX); + const imagesIssueBugfix = imagesIssueBugfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueBugfix.length === 0) { + imagesIssueBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.bugfix); + } + const imagesIssueDocsInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_DOCS); + const imagesIssueDocs = imagesIssueDocsInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueDocs.length === 0) { + imagesIssueDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.docs); + } + const imagesIssueChoreInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_CHORE); + const imagesIssueChore = imagesIssueChoreInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueChore.length === 0) { + imagesIssueChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.chore); + } + const imagesIssueReleaseInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_RELEASE); + const imagesIssueRelease = imagesIssueReleaseInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueRelease.length === 0) { + imagesIssueRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.release); + } + const imagesIssueHotfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_ISSUE_HOTFIX); + const imagesIssueHotfix = imagesIssueHotfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesIssueHotfix.length === 0) { + imagesIssueHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.issue.hotfix); + } + const imagesPullRequestAutomaticInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_AUTOMATIC); + const imagesPullRequestAutomatic = imagesPullRequestAutomaticInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestAutomatic.length === 0) { + imagesPullRequestAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.automatic); + } + const imagesPullRequestFeatureInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_FEATURE); + const imagesPullRequestFeature = imagesPullRequestFeatureInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestFeature.length === 0) { + imagesPullRequestFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.feature); + } + const imagesPullRequestBugfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_BUGFIX); + const imagesPullRequestBugfix = imagesPullRequestBugfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestBugfix.length === 0) { + imagesPullRequestBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.bugfix); + } + const imagesPullRequestReleaseInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_RELEASE); + const imagesPullRequestRelease = imagesPullRequestReleaseInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestRelease.length === 0) { + imagesPullRequestRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.release); + } + const imagesPullRequestHotfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_HOTFIX); + const imagesPullRequestHotfix = imagesPullRequestHotfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestHotfix.length === 0) { + imagesPullRequestHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.hotfix); + } + const imagesPullRequestDocsInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_DOCS); + const imagesPullRequestDocs = imagesPullRequestDocsInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestDocs.length === 0) { + imagesPullRequestDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.docs); + } + const imagesPullRequestChoreInput = getInput(constants_1.INPUT_KEYS.IMAGES_PULL_REQUEST_CHORE); + const imagesPullRequestChore = imagesPullRequestChoreInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesPullRequestChore.length === 0) { + imagesPullRequestChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.pullRequest.chore); + } + const imagesCommitAutomaticInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_AUTOMATIC); + const imagesCommitAutomatic = imagesCommitAutomaticInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitAutomatic.length === 0) { + imagesCommitAutomatic.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.automatic); + } + const imagesCommitFeatureInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_FEATURE); + const imagesCommitFeature = imagesCommitFeatureInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitFeature.length === 0) { + imagesCommitFeature.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.feature); + } + const imagesCommitBugfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_BUGFIX); + const imagesCommitBugfix = imagesCommitBugfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitBugfix.length === 0) { + imagesCommitBugfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.bugfix); + } + const imagesCommitReleaseInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_RELEASE); + const imagesCommitRelease = imagesCommitReleaseInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitRelease.length === 0) { + imagesCommitRelease.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.release); + } + const imagesCommitHotfixInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_HOTFIX); + const imagesCommitHotfix = imagesCommitHotfixInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitHotfix.length === 0) { + imagesCommitHotfix.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.hotfix); + } + const imagesCommitDocsInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_DOCS); + const imagesCommitDocs = imagesCommitDocsInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitDocs.length === 0) { + imagesCommitDocs.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.docs); + } + const imagesCommitChoreInput = getInput(constants_1.INPUT_KEYS.IMAGES_COMMIT_CHORE); + const imagesCommitChore = imagesCommitChoreInput + .split(',') + .map(url => url.trim()) + .filter(url => url.length > 0); + if (imagesCommitChore.length === 0) { + imagesCommitChore.push(...constants_1.DEFAULT_IMAGE_CONFIG.commit.chore); + } + /** + * Workflows + */ + const releaseWorkflow = getInput(constants_1.INPUT_KEYS.RELEASE_WORKFLOW); + const hotfixWorkflow = getInput(constants_1.INPUT_KEYS.HOTFIX_WORKFLOW); + /** + * Emoji-title + */ + const titleEmoji = getInput(constants_1.INPUT_KEYS.EMOJI_LABELED_TITLE) === 'true'; + const branchManagementEmoji = getInput(constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_EMOJI); + /** + * Labels + */ + const branchManagementLauncherLabel = getInput(constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_LAUNCHER_LABEL); + const bugfixLabel = getInput(constants_1.INPUT_KEYS.BUGFIX_LABEL); + const bugLabel = getInput(constants_1.INPUT_KEYS.BUG_LABEL); + const hotfixLabel = getInput(constants_1.INPUT_KEYS.HOTFIX_LABEL); + const enhancementLabel = getInput(constants_1.INPUT_KEYS.ENHANCEMENT_LABEL); + const featureLabel = getInput(constants_1.INPUT_KEYS.FEATURE_LABEL); + const releaseLabel = getInput(constants_1.INPUT_KEYS.RELEASE_LABEL); + const questionLabel = getInput(constants_1.INPUT_KEYS.QUESTION_LABEL); + const helpLabel = getInput(constants_1.INPUT_KEYS.HELP_LABEL); + const deployLabel = getInput(constants_1.INPUT_KEYS.DEPLOY_LABEL); + const deployedLabel = getInput(constants_1.INPUT_KEYS.DEPLOYED_LABEL); + const docsLabel = getInput(constants_1.INPUT_KEYS.DOCS_LABEL); + const documentationLabel = getInput(constants_1.INPUT_KEYS.DOCUMENTATION_LABEL); + const choreLabel = getInput(constants_1.INPUT_KEYS.CHORE_LABEL); + const maintenanceLabel = getInput(constants_1.INPUT_KEYS.MAINTENANCE_LABEL); + const priorityHighLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_HIGH_LABEL); + const priorityMediumLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_MEDIUM_LABEL); + const priorityLowLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_LOW_LABEL); + const priorityNoneLabel = getInput(constants_1.INPUT_KEYS.PRIORITY_NONE_LABEL); + const sizeXxlLabel = getInput(constants_1.INPUT_KEYS.SIZE_XXL_LABEL); + const sizeXlLabel = getInput(constants_1.INPUT_KEYS.SIZE_XL_LABEL); + const sizeLLabel = getInput(constants_1.INPUT_KEYS.SIZE_L_LABEL); + const sizeMLabel = getInput(constants_1.INPUT_KEYS.SIZE_M_LABEL); + const sizeSLabel = getInput(constants_1.INPUT_KEYS.SIZE_S_LABEL); + const sizeXsLabel = getInput(constants_1.INPUT_KEYS.SIZE_XS_LABEL); + /** + * Issue Types + */ + const issueTypeBug = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_BUG); + const issueTypeBugDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_DESCRIPTION); + const issueTypeBugColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_BUG_COLOR); + const issueTypeHotfix = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX); + const issueTypeHotfixDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_DESCRIPTION); + const issueTypeHotfixColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HOTFIX_COLOR); + const issueTypeFeature = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE); + const issueTypeFeatureDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_DESCRIPTION); + const issueTypeFeatureColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_FEATURE_COLOR); + const issueTypeDocumentation = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION); + const issueTypeDocumentationDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_DESCRIPTION); + const issueTypeDocumentationColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_DOCUMENTATION_COLOR); + const issueTypeMaintenance = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE); + const issueTypeMaintenanceDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_DESCRIPTION); + const issueTypeMaintenanceColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_MAINTENANCE_COLOR); + const issueTypeRelease = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE); + const issueTypeReleaseDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_DESCRIPTION); + const issueTypeReleaseColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_RELEASE_COLOR); + const issueTypeQuestion = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION); + const issueTypeQuestionDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_DESCRIPTION); + const issueTypeQuestionColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_QUESTION_COLOR); + const issueTypeHelp = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HELP); + const issueTypeHelpDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_DESCRIPTION); + const issueTypeHelpColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_HELP_COLOR); + const issueTypeTask = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_TASK); + const issueTypeTaskDescription = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_DESCRIPTION); + const issueTypeTaskColor = getInput(constants_1.INPUT_KEYS.ISSUE_TYPE_TASK_COLOR); + /** + * Locale + */ + const issueLocale = getInput(constants_1.INPUT_KEYS.ISSUES_LOCALE) ?? locale_1.Locale.DEFAULT; + const pullRequestLocale = getInput(constants_1.INPUT_KEYS.PULL_REQUESTS_LOCALE) ?? locale_1.Locale.DEFAULT; + /** + * Size Thresholds + */ + const sizeXxlThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_LINES)) ?? 1000; + const sizeXxlThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_FILES)) ?? 20; + const sizeXxlThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XXL_THRESHOLD_COMMITS)) ?? 10; + const sizeXlThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_LINES)) ?? 500; + const sizeXlThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_FILES)) ?? 10; + const sizeXlThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XL_THRESHOLD_COMMITS)) ?? 5; + const sizeLThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_LINES)) ?? 250; + const sizeLThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_FILES)) ?? 5; + const sizeLThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_L_THRESHOLD_COMMITS)) ?? 3; + const sizeMThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_LINES)) ?? 100; + const sizeMThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_FILES)) ?? 3; + const sizeMThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_M_THRESHOLD_COMMITS)) ?? 2; + const sizeSThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_LINES)) ?? 50; + const sizeSThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_FILES)) ?? 2; + const sizeSThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_S_THRESHOLD_COMMITS)) ?? 1; + const sizeXsThresholdLines = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_LINES)) ?? 25; + const sizeXsThresholdFiles = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_FILES)) ?? 1; + const sizeXsThresholdCommits = parseInt(getInput(constants_1.INPUT_KEYS.SIZE_XS_THRESHOLD_COMMITS)) ?? 1; + /** + * Branches + */ + const mainBranch = getInput(constants_1.INPUT_KEYS.MAIN_BRANCH); + const developmentBranch = getInput(constants_1.INPUT_KEYS.DEVELOPMENT_BRANCH); + const featureTree = getInput(constants_1.INPUT_KEYS.FEATURE_TREE); + const bugfixTree = getInput(constants_1.INPUT_KEYS.BUGFIX_TREE); + const hotfixTree = getInput(constants_1.INPUT_KEYS.HOTFIX_TREE); + const releaseTree = getInput(constants_1.INPUT_KEYS.RELEASE_TREE); + const docsTree = getInput(constants_1.INPUT_KEYS.DOCS_TREE); + const choreTree = getInput(constants_1.INPUT_KEYS.CHORE_TREE); + /** + * Prefix builder + */ + let commitPrefixBuilder = getInput(constants_1.INPUT_KEYS.COMMIT_PREFIX_TRANSFORMS) ?? ''; + if (commitPrefixBuilder.length === 0) { + commitPrefixBuilder = 'replace-slash'; + } + /** + * Issue + */ + const branchManagementAlways = getInput(constants_1.INPUT_KEYS.BRANCH_MANAGEMENT_ALWAYS) === 'true'; + const reopenIssueOnPush = getInput(constants_1.INPUT_KEYS.REOPEN_ISSUE_ON_PUSH) === 'true'; + const issueDesiredAssigneesCount = parseInt(getInput(constants_1.INPUT_KEYS.DESIRED_ASSIGNEES_COUNT)) ?? 0; + /** + * Pull Request + */ + const pullRequestDesiredAssigneesCount = parseInt(getInput(constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_ASSIGNEES_COUNT)) ?? 0; + const pullRequestDesiredReviewersCount = parseInt(getInput(constants_1.INPUT_KEYS.PULL_REQUEST_DESIRED_REVIEWERS_COUNT)) ?? 0; + const pullRequestMergeTimeout = parseInt(getInput(constants_1.INPUT_KEYS.PULL_REQUEST_MERGE_TIMEOUT)) ?? 0; + /** + * Supabase + */ + const supabaseUrl = getInput(constants_1.INPUT_KEYS.SUPABASE_URL); + const supabaseKey = getInput(constants_1.INPUT_KEYS.SUPABASE_KEY); + let supabaseConfig = undefined; + if (supabaseUrl.length > 0 && supabaseKey.length > 0) { + supabaseConfig = new supabase_config_1.SupabaseConfig(supabaseUrl, supabaseKey); + } + const execution = new execution_1.Execution(debug, new single_action_1.SingleAction(singleAction, singleActionIssue, singleActionVersion, singleActionTitle, singleActionChangelog), commitPrefixBuilder, new issue_1.Issue(branchManagementAlways, reopenIssueOnPush, issueDesiredAssigneesCount), new pull_request_1.PullRequest(pullRequestDesiredAssigneesCount, pullRequestDesiredReviewersCount, pullRequestMergeTimeout), new emoji_1.Emoji(titleEmoji, branchManagementEmoji), new images_1.Images(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, imagesIssueAutomatic, imagesIssueFeature, imagesIssueBugfix, imagesIssueDocs, imagesIssueChore, imagesIssueRelease, imagesIssueHotfix, imagesPullRequestAutomatic, imagesPullRequestFeature, imagesPullRequestBugfix, imagesPullRequestRelease, imagesPullRequestHotfix, imagesPullRequestDocs, imagesPullRequestChore, imagesCommitAutomatic, imagesCommitFeature, imagesCommitBugfix, imagesCommitRelease, imagesCommitHotfix, imagesCommitDocs, imagesCommitChore), new tokens_1.Tokens(token), new ai_1.Ai(openrouterApiKey, openrouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, Object.keys(providerRouting).length > 0 ? providerRouting : undefined), new labels_1.Labels(branchManagementLauncherLabel, bugLabel, bugfixLabel, hotfixLabel, enhancementLabel, featureLabel, releaseLabel, questionLabel, helpLabel, deployLabel, deployedLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel, priorityHighLabel, priorityMediumLabel, priorityLowLabel, priorityNoneLabel, sizeXxlLabel, sizeXlLabel, sizeLLabel, sizeMLabel, sizeSLabel, sizeXsLabel), new issue_types_1.IssueTypes(issueTypeTask, issueTypeTaskDescription, issueTypeTaskColor, issueTypeBug, issueTypeBugDescription, issueTypeBugColor, issueTypeFeature, issueTypeFeatureDescription, issueTypeFeatureColor, issueTypeDocumentation, issueTypeDocumentationDescription, issueTypeDocumentationColor, issueTypeMaintenance, issueTypeMaintenanceDescription, issueTypeMaintenanceColor, issueTypeHotfix, issueTypeHotfixDescription, issueTypeHotfixColor, issueTypeRelease, issueTypeReleaseDescription, issueTypeReleaseColor, issueTypeQuestion, issueTypeQuestionDescription, issueTypeQuestionColor, issueTypeHelp, issueTypeHelpDescription, issueTypeHelpColor), new locale_1.Locale(issueLocale, pullRequestLocale), new size_thresholds_1.SizeThresholds(new size_threshold_1.SizeThreshold(sizeXxlThresholdLines, sizeXxlThresholdFiles, sizeXxlThresholdCommits), new size_threshold_1.SizeThreshold(sizeXlThresholdLines, sizeXlThresholdFiles, sizeXlThresholdCommits), new size_threshold_1.SizeThreshold(sizeLThresholdLines, sizeLThresholdFiles, sizeLThresholdCommits), new size_threshold_1.SizeThreshold(sizeMThresholdLines, sizeMThresholdFiles, sizeMThresholdCommits), new size_threshold_1.SizeThreshold(sizeSThresholdLines, sizeSThresholdFiles, sizeSThresholdCommits), new size_threshold_1.SizeThreshold(sizeXsThresholdLines, sizeXsThresholdFiles, sizeXsThresholdCommits)), new branches_1.Branches(mainBranch, developmentBranch, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree), new release_1.Release(), new hotfix_1.Hotfix(), new workflows_1.Workflows(releaseWorkflow, hotfixWorkflow), new projects_1.Projects(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress), supabaseConfig, undefined, undefined); + const results = await (0, common_action_1.mainRun)(execution); + await finishWithResults(execution, results); +} +async function finishWithResults(execution, results) { + execution.currentConfiguration.results = results; + await new publish_resume_use_case_1.PublishResultUseCase().invoke(execution); + await new store_configuration_use_case_1.StoreConfigurationUseCase().invoke(execution); + /** + * If a single action is executed and the last step failed, throw an error + */ + if (execution.isSingleAction && execution.singleAction.throwError) { + setFirstErrorIfExists(results); + } +} +function getInput(key, options) { + try { + const inputVarsJson = process.env.INPUT_VARS_JSON; + if (inputVarsJson) { + const inputVars = JSON.parse(inputVarsJson); + const value = inputVars[`INPUT_${key.toUpperCase()}`]; + if (value !== undefined) { + return value; } - return result; } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Tried to assign members to issue.`], - error: error, - })); + } + catch (error) { + (0, logger_1.logError)(`Error parsing INPUT_VARS_JSON: ${JSON.stringify(error, null, 2)}`); + } + // Fallback to core.getInput + return core.getInput(key, options); +} +function setFirstErrorIfExists(results) { + for (const result of results) { + if (result.errors && result.errors.length > 0) { + core.setFailed(result.errors[0]); + return; } - return result; } } -exports.AssignMemberToIssueUseCase = AssignMemberToIssueUseCase; +runGitHubAction(); /***/ }), -/***/ 46275: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 4470: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.AssignReviewersToIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const pull_request_repository_1 = __nccwpck_require__(20634); -const logger_1 = __nccwpck_require__(38836); -class AssignReviewersToIssueUseCase { - constructor() { - this.taskId = 'AssignReviewersToIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); +exports.Ai = void 0; +class Ai { + constructor(openRouterApiKey, openRouterModel, aiPullRequestDescription, aiMembersOnly, aiIgnoreFiles, aiIncludeReasoning, providerRouting) { + this.openRouterApiKey = openRouterApiKey; + this.openRouterModel = openRouterModel; + this.aiPullRequestDescription = aiPullRequestDescription; + this.aiMembersOnly = aiMembersOnly; + this.aiIgnoreFiles = aiIgnoreFiles; + this.aiIncludeReasoning = aiIncludeReasoning; + this.providerRouting = providerRouting || {}; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const desiredReviewersCount = param.pullRequest.desiredReviewersCount; - const number = param.pullRequest.number; - const result = []; - try { - (0, logger_1.logDebugInfo)(`#${number} needs ${desiredReviewersCount} reviewers.`); - const currentReviewers = await this.pullRequestRepository.getCurrentReviewers(param.owner, param.repo, number, param.tokens.token); - const currentAssignees = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); - if (currentReviewers.length >= desiredReviewersCount) { - /** - * No more assignees needed - */ - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return result; - } - const missingReviewers = desiredReviewersCount - currentReviewers.length; - (0, logger_1.logDebugInfo)(`#${number} needs ${missingReviewers} more reviewers.`); - const excludeForReview = []; - excludeForReview.push(param.pullRequest.creator); - excludeForReview.push(...currentReviewers); - excludeForReview.push(...currentAssignees); - const members = await this.projectRepository.getRandomMembers(param.owner, missingReviewers, excludeForReview, param.tokens.token); - if (members.length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to assign members as reviewers to pull request, but no one was found.`, - ], - })); - return result; - } - const reviewersAdded = await this.pullRequestRepository.addReviewersToPullRequest(param.owner, param.repo, number, members, param.tokens.token); - for (const member of reviewersAdded) { - if (members.indexOf(member) > -1) - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `@${member} was requested to review the pull request.`, - ], - })); - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to assign members to issue.`, - ], - error: error, - })); - } - return result; + getOpenRouterApiKey() { + return this.openRouterApiKey; + } + getAiPullRequestDescription() { + return this.aiPullRequestDescription; + } + getAiMembersOnly() { + return this.aiMembersOnly; + } + getAiIgnoreFiles() { + return this.aiIgnoreFiles; + } + getAiIncludeReasoning() { + return this.aiIncludeReasoning; + } + getOpenRouterModel() { + return this.openRouterModel; + } + getProviderRouting() { + return this.providerRouting; } } -exports.AssignReviewersToIssueUseCase = AssignReviewersToIssueUseCase; +exports.Ai = Ai; /***/ }), -/***/ 151: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5968: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckPriorityIssueSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckPriorityIssueSizeUseCase { - constructor() { - this.taskId = 'CheckPriorityIssueSizeUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const priority = param.labels.priorityLabelOnIssue; - if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - let priorityLabel = ``; - if (priority === param.labels.priorityHigh) { - priorityLabel = `P0`; - } - else if (priority === param.labels.priorityMedium) { - priorityLabel = `P1`; - } - else if (priority === param.labels.priorityLow) { - priorityLabel = `P2`; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - (0, logger_1.logDebugInfo)(`Priority: ${priority}`); - (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); - for (const project of param.project.getProjects()) { - const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.issueNumber, priorityLabel, param.tokens.token); - if (success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, - ], - })); - } - } +exports.AI_RESPONSE_JSON_SCHEMA = void 0; +/** + * JSON Schema for AiResponse interface + * This schema is used to enforce structured JSON responses from the AI + */ +exports.AI_RESPONSE_JSON_SCHEMA = { + type: "object", + properties: { + text_response: { + type: "string", + description: "The detailed analysis or answer to the user's question" + }, + action: { + type: "string", + enum: ["none", "analyze_files"], + description: "The action to take: 'none' if no additional files are needed, 'analyze_files' if more files are required" + }, + related_files: { + type: "array", + items: { + type: "string" + }, + description: "List of file paths that need to be analyzed if action is 'analyze_files'" + }, + complete: { + type: "boolean", + description: "Whether the response is complete and no further analysis is needed" } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the priority of the issue, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); + }, + required: ["text_response", "action", "related_files", "complete"], + additionalProperties: false +}; + + +/***/ }), + +/***/ 2141: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BranchConfiguration = void 0; +class BranchConfiguration { + constructor(data) { + this.name = data['name'] ?? ''; + this.oid = data['oid'] ?? ''; + this.children = []; + if (data['children'] !== undefined && data['children'].length > 0) { + for (let child of data['children']) { + this.children.push(new BranchConfiguration(child)); + } } - return result; } } -exports.CheckPriorityIssueSizeUseCase = CheckPriorityIssueSizeUseCase; +exports.BranchConfiguration = BranchConfiguration; /***/ }), -/***/ 35137: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 5308: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloseIssueAfterMergingUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -class CloseIssueAfterMergingUseCase { - constructor() { - this.taskId = 'CloseIssueAfterMergingUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.removeBranches = async (supabaseRepository, param, branch) => { - const result = []; - if (!supabaseRepository) { - return result; - } - try { - await supabaseRepository.removeChunksByBranch(param.owner, param.repo, branch); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `AI index was removed from \`${branch}\`.`, - ] - })); - } - catch (error) { - (0, logger_1.logError)(`Error removing chunks: ${JSON.stringify(error, null, 2)}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `There was an error removing the AI index from \`${branch}\`.`, - ], - errors: [ - JSON.stringify(error, null, 2), - ], - })); - } - return result; - }; +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]; } }; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - let supabaseRepository = undefined; - if (param.supabaseConfig) { - supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - } - const result = []; - try { - const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (closed) { - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was closed after merging #${param.pullRequest.number}.`, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `#${param.issueNumber} was automatically closed after merging this pull request.` - ] - })); - result.push(...await this.removeBranches(supabaseRepository, param, param.pullRequest.head.replace('refs/heads/', ''))); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to close issue #${param.issueNumber}, but there was a problem.`, - ], - error: error, - })); - } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Branches = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class Branches { + get defaultBranch() { + return github.context.payload.repository?.default_branch ?? ''; + } + constructor(main, development, featureTree, bugfixTree, hotfixTree, releaseTree, docsTree, choreTree) { + this.main = main; + this.development = development; + this.featureTree = featureTree; + this.bugfixTree = bugfixTree; + this.hotfixTree = hotfixTree; + this.releaseTree = releaseTree; + this.docsTree = docsTree; + this.choreTree = choreTree; } } -exports.CloseIssueAfterMergingUseCase = CloseIssueAfterMergingUseCase; +exports.Branches = Branches; /***/ }), -/***/ 97826: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3993: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CloseNotAllowedIssueUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class CloseNotAllowedIssueUseCase { - constructor() { - this.taskId = 'CloseNotAllowedIssueUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); +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]; } }; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (closed) { - await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue has been closed because the author is not a member of the project. The user may be banned if the fact is repeated.`, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `#${param.issueNumber} was automatically closed because the author is not a member of the project.` - ] - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to close issue #${param.issueNumber}, but there was a problem.`, - ], - error: error, - })); - } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Commit = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class Commit { + constructor(inputs = undefined) { + this.inputs = undefined; + this.inputs = inputs; + } + get branchReference() { + return this.inputs?.commits?.ref ?? github.context.payload.ref ?? ''; + } + get branch() { + return this.branchReference.replace('refs/heads/', ''); + } + get commits() { + return github.context.payload.commits || []; } } -exports.CloseNotAllowedIssueUseCase = CloseNotAllowedIssueUseCase; +exports.Commit = Commit; /***/ }), -/***/ 75678: +/***/ 1106: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DeployAddedUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const content_utils_1 = __nccwpck_require__(17873); -const logger_1 = __nccwpck_require__(38836); -class DeployAddedUseCase { - constructor() { - this.taskId = 'DeployAddedUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.issue.labeled && param.issue.labelAdded === param.labels.deploy) { - (0, logger_1.logDebugInfo)(`Deploying requested.`); - if (param.release.active && param.release.branch !== undefined) { - const sanitizedTitle = param.issue.title - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - const description = param.issue.body?.match(/### Changelog\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; - const escapedDescription = description.replace(/\n/g, '\\n'); - const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; - const parameters = { - version: param.release.version, - title: sanitizedTitle, - changelog: escapedDescription, - issue: `${param.issue.number}`, - }; - await this.branchRepository.executeWorkflow(param.owner, param.repo, param.release.branch, param.workflows.release, parameters, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Executed release workflow [**${param.workflows.release}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.release}) on [**${param.release.branch}**](${releaseUrl}). - -${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}` - ] - })); - } - else if (param.hotfix.active && param.hotfix.branch !== undefined) { - const sanitizedTitle = param.issue.title - .replace(/\b\d+(\.\d+){2,}\b/g, '') - .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') - .replace(/\u200D/g, '') - .replace(/[^\S\r\n]+/g, ' ') - .replace(/[^a-zA-Z0-9 .]/g, '') - .replace(/^-+|-+$/g, '') - .replace(/- -/g, '-').trim() - .replace(/-+/g, '-') - .trim(); - const description = param.issue.body?.match(/### Hotfix Solution\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; - const escapedDescription = description.replace(/\n/g, '\\n'); - const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; - const parameters = { - version: param.hotfix.version, - title: sanitizedTitle, - changelog: escapedDescription, - issue: param.issue.number, - }; - await this.branchRepository.executeWorkflow(param.owner, param.repo, param.hotfix.branch, param.workflows.release, parameters, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Executed hotfix workflow [**${param.workflows.hotfix}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.hotfix}) on [**${param.hotfix.branch}**](${hotfixUrl}). - -${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}\`` - ] - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to work with workflows, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); +exports.Config = void 0; +const branch_configuration_1 = __nccwpck_require__(2141); +class Config { + constructor(data) { + this.results = []; + this.branchType = data['branchType'] ?? ''; + this.hotfixOriginBranch = data['hotfixOriginBranch']; + this.hotfixBranch = data['hotfixBranch']; + this.releaseBranch = data['releaseBranch']; + this.parentBranch = data['parentBranch']; + this.workingBranch = data['workingBranch']; + if (data['branchConfiguration'] !== undefined) { + this.branchConfiguration = new branch_configuration_1.BranchConfiguration(data['branchConfiguration']); } - return result; } } -exports.DeployAddedUseCase = DeployAddedUseCase; +exports.Config = Config; /***/ }), -/***/ 8388: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 9463: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DeployedAddedUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const logger_1 = __nccwpck_require__(38836); -class DeployedAddedUseCase { - constructor() { - this.taskId = 'DeployedAddedUseCase'; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - if (param.issue.labeled && param.issue.labelAdded === param.labels.deployed) { - (0, logger_1.logDebugInfo)(`Deploy complete.`); - if (param.release.active && param.release.branch !== undefined) { - const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Deploy complete from [${param.release.branch}](${releaseUrl})` - ] - })); - } - else if (param.hotfix.active && param.hotfix.branch !== undefined) { - const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Deploy complete from [${param.hotfix.branch}](${hotfixUrl})` - ] - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to complete the deployment, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; +exports.Emoji = void 0; +class Emoji { + constructor(emojiLabeledTitle, branchManagementEmoji) { + this.emojiLabeledTitle = emojiLabeledTitle; + this.branchManagementEmoji = branchManagementEmoji; } } -exports.DeployedAddedUseCase = DeployedAddedUseCase; +exports.Emoji = Emoji; /***/ }), -/***/ 67528: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7550: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LinkIssueProjectUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class LinkIssueProjectUseCase { - constructor() { - this.taskId = 'LinkIssueProjectUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); +exports.Execution = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const configuration_handler_1 = __nccwpck_require__(4509); +const get_hotfix_version_use_case_1 = __nccwpck_require__(8243); +const get_release_type_use_case_1 = __nccwpck_require__(5966); +const get_release_version_use_case_1 = __nccwpck_require__(3827); +const constants_1 = __nccwpck_require__(8593); +const label_utils_1 = __nccwpck_require__(1479); +const logger_1 = __nccwpck_require__(8836); +const title_utils_1 = __nccwpck_require__(6676); +const version_utils_1 = __nccwpck_require__(9887); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const commit_1 = __nccwpck_require__(3993); +const config_1 = __nccwpck_require__(1106); +class Execution { + get eventName() { + return this.inputs?.eventName ?? github.context.eventName; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - const columnName = param.project.getProjectColumnIssueCreated(); - try { - for (const project of param.project.getProjects()) { - const issueId = await this.issueRepository.getId(param.owner, param.repo, param.issue.number, param.tokens.token); - let actionDone = await this.projectRepository.linkContentId(project, issueId, param.tokens.token); - if (actionDone) { - /** - * Wait for 10 seconds to ensure the issue is linked to the project - */ - await new Promise(resolve => setTimeout(resolve, 10000)); - actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issue.number, columnName, param.tokens.token); - if (actionDone) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The issue was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, - ] - })); + get actor() { + return this.inputs?.actor ?? github.context.actor; + } + get isSingleAction() { + return this.singleAction.enabledSingleAction; + } + get isIssue() { + return this.issue.isIssue || this.issue.isIssueComment || this.singleAction.isIssue; + } + get isPullRequest() { + return this.pullRequest.isPullRequest || this.pullRequest.isPullRequestReviewComment || this.singleAction.isPullRequest; + } + get isPush() { + return this.eventName === 'push'; + } + get repo() { + return this.inputs?.repo?.repo ?? github.context.repo.repo; + } + get owner() { + return this.inputs?.repo?.owner ?? github.context.repo.owner; + } + get isFeature() { + return this.issueType === this.branches.featureTree; + } + get isBugfix() { + return this.issueType === this.branches.bugfixTree; + } + get isDocs() { + return this.issueType === this.branches.docsTree; + } + get isChore() { + return this.issueType === this.branches.choreTree; + } + get isBranched() { + return this.issue.branchManagementAlways || + this.labels.containsBranchedLabel || + this.labels.isMandatoryBranchedLabel; + } + get issueNotBranched() { + return this.isIssue && !this.isBranched; + } + get managementBranch() { + return (0, label_utils_1.branchesForManagement)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); + } + get issueType() { + return (0, label_utils_1.typesForIssue)(this, this.labels.currentIssueLabels, this.labels.feature, this.labels.enhancement, this.labels.bugfix, this.labels.bug, this.labels.hotfix, this.labels.release, this.labels.docs, this.labels.documentation, this.labels.chore, this.labels.maintenance); + } + get cleanIssueBranches() { + return this.isIssue + && this.previousConfiguration !== undefined + && this.previousConfiguration?.branchType != this.currentConfiguration.branchType; + } + get commit() { + return new commit_1.Commit(this.inputs); + } + get runnedByToken() { + return this.tokenUser === this.actor; + } + constructor(debug, singleAction, commitPrefixBuilder, issue, pullRequest, emoji, giphy, tokens, ai, labels, issueTypes, locale, sizeThresholds, branches, release, hotfix, workflows, project, supabaseConfig, welcome, inputs) { + this.debug = false; + /** + * Every usage of this field should be checked. + * PRs with no issue ID in the head branch won't have it. + * + * master <- develop + */ + this.issueNumber = -1; + this.commitPrefixBuilderParams = {}; + this.setup = async () => { + (0, logger_1.setGlobalLoggerDebug)(this.debug, this.inputs === undefined); + const issueRepository = new issue_repository_1.IssueRepository(); + const projectRepository = new project_repository_1.ProjectRepository(); + this.tokenUser = await projectRepository.getUserFromToken(this.tokens.token); + if (!this.tokenUser) { + throw new Error('Failed to get user from token'); + } + /** + * Set the issue number + */ + if (this.isSingleAction) { + /** + * Single actions can run as isolated processes or as part of a workflow. + * In the case of a workflow, the issue number is got from the workflow. + * In the case of a single action, the issue number is set. + */ + if (this.inputs?.[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]) { + this.issueNumber = this.inputs[constants_1.INPUT_KEYS.SINGLE_ACTION_ISSUE]; + this.singleAction.issue = this.issueNumber; + } + else if (this.isIssue) { + this.singleAction.isIssue = true; + this.issueNumber = this.issue.number; + this.singleAction.issue = this.issueNumber; + } + else if (this.isPullRequest) { + this.singleAction.isPullRequest = true; + this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); + this.singleAction.issue = this.issueNumber; + } + else if (this.isPush) { + this.singleAction.isPush = true; + this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); + this.singleAction.issue = this.issueNumber; + } + else { + this.singleAction.isPullRequest = await issueRepository.isPullRequest(this.owner, this.repo, this.singleAction.issue, this.tokens.token); + this.singleAction.isIssue = await issueRepository.isIssue(this.owner, this.repo, this.singleAction.issue, this.tokens.token); + if (this.singleAction.isIssue) { + this.issueNumber = this.singleAction.issue; + } + else if (this.singleAction.isPullRequest) { + const head = await issueRepository.getHeadBranch(this.owner, this.repo, this.singleAction.issue, this.tokens.token); + if (head === undefined) { + return; + } + this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(head); + } + } + } + else if (this.isIssue) { + this.issueNumber = this.issue.number; + } + else if (this.isPullRequest) { + this.issueNumber = (0, title_utils_1.extractIssueNumberFromBranch)(this.pullRequest.head); + } + else if (this.isPush) { + this.issueNumber = (0, title_utils_1.extractIssueNumberFromPush)(this.commit.branch); + } + this.previousConfiguration = await new configuration_handler_1.ConfigurationHandler().get(this); + /** + * Get labels of issue + */ + this.labels.currentIssueLabels = await issueRepository.getLabels(this.owner, this.repo, this.issueNumber, this.tokens.token); + /** + * Contains release label + */ + this.release.active = this.labels.isRelease; + this.hotfix.active = this.labels.isHotfix; + /** + * Get previous state + */ + if (this.release.active) { + const previousReleaseBranch = this.previousConfiguration?.releaseBranch; + if (previousReleaseBranch) { + this.release.version = previousReleaseBranch.split('/')[1] ?? ''; + this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; + this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; + this.currentConfiguration.releaseBranch = this.release.branch; + } + } + else if (this.hotfix.active) { + const previousHotfixOriginBranch = this.previousConfiguration?.hotfixOriginBranch; + if (previousHotfixOriginBranch) { + this.hotfix.baseVersion = previousHotfixOriginBranch.split('/v')[1] ?? ''; + this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; + this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; + this.currentConfiguration.parentBranch = this.hotfix.baseBranch; + } + const previousHotfixBranch = this.previousConfiguration?.hotfixBranch; + if (previousHotfixBranch) { + this.hotfix.version = previousHotfixBranch.split('/')[1] ?? ''; + this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; + this.currentConfiguration.hotfixBranch = this.hotfix.branch; + } + } + else { + this.currentConfiguration.parentBranch = this.previousConfiguration?.parentBranch; + } + if (this.isSingleAction) { + /** + * Nothing to do here (for now) + */ + } + else if (this.isIssue) { + const branchRepository = new branch_repository_1.BranchRepository(); + if (this.release.active && this.release.version === undefined) { + const versionResult = await new get_release_version_use_case_1.GetReleaseVersionUseCase().invoke(this); + const versionInfo = versionResult[versionResult.length - 1]; + if (versionInfo.executed && versionInfo.success) { + this.release.version = versionInfo.payload['releaseVersion']; } else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - steps: [] - })); + const typeResult = await new get_release_type_use_case_1.GetReleaseTypeUseCase().invoke(this); + const typeInfo = typeResult[typeResult.length - 1]; + if (typeInfo.executed && typeInfo.success) { + this.release.type = typeInfo.payload['releaseType']; + if (this.release.type === undefined) { + return; + } + const lastTag = await branchRepository.getLatestTag(); + if (lastTag === undefined) { + return; + } + this.release.version = (0, version_utils_1.incrementVersion)(lastTag, this.release.type); + } + } + this.release.branch = `${this.branches.releaseTree}/${this.release.version}`; + } + else if (this.hotfix.active && this.hotfix.version === undefined) { + const versionResult = await new get_hotfix_version_use_case_1.GetHotfixVersionUseCase().invoke(this); + const versionInfo = versionResult[versionResult.length - 1]; + if (versionInfo.executed && versionInfo.success) { + this.hotfix.baseVersion = versionInfo.payload['baseVersion']; + this.hotfix.version = versionInfo.payload['hotfixVersion']; + } + else { + this.hotfix.baseVersion = await branchRepository.getLatestTag(); + if (this.hotfix.baseVersion === undefined) { + return; + } + this.hotfix.version = (0, version_utils_1.incrementVersion)(this.hotfix.baseVersion, 'Patch'); } + this.hotfix.branch = `${this.branches.hotfixTree}/${this.hotfix.version}`; + this.currentConfiguration.hotfixBranch = this.hotfix.branch; + this.hotfix.baseBranch = `tags/v${this.hotfix.baseVersion}`; + this.currentConfiguration.hotfixOriginBranch = this.hotfix.baseBranch; } } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to link issue to project, but there was a problem.`, - ], - error: error, - })); - } - return result; + else if (this.isPullRequest) { + this.labels.currentPullRequestLabels = await issueRepository.getLabels(this.owner, this.repo, this.pullRequest.number, this.tokens.token); + this.release.active = this.pullRequest.base.indexOf(`${this.branches.releaseTree}/`) > -1; + this.hotfix.active = this.pullRequest.base.indexOf(`${this.branches.hotfixTree}/`) > -1; + } + this.currentConfiguration.branchType = this.issueType; + (0, logger_1.logDebugInfo)(`Current configuration: ${JSON.stringify(this.currentConfiguration, null, 2)}`); + }; + this.debug = debug; + this.singleAction = singleAction; + this.commitPrefixBuilder = commitPrefixBuilder; + this.issue = issue; + this.pullRequest = pullRequest; + this.images = giphy; + this.tokens = tokens; + this.ai = ai; + this.emoji = emoji; + this.labels = labels; + this.issueTypes = issueTypes; + this.locale = locale; + this.sizeThresholds = sizeThresholds; + this.branches = branches; + this.release = release; + this.hotfix = hotfix; + this.project = project; + this.workflows = workflows; + this.currentConfiguration = new config_1.Config({}); + this.supabaseConfig = supabaseConfig; + this.inputs = inputs; + this.welcome = welcome; } } -exports.LinkIssueProjectUseCase = LinkIssueProjectUseCase; +exports.Execution = Execution; /***/ }), -/***/ 98203: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7341: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MoveIssueToInProgressUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class MoveIssueToInProgressUseCase { +exports.Hotfix = void 0; +class Hotfix { constructor() { - this.taskId = 'MoveIssueToInProgressUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); + this.active = false; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - const columnName = param.project.getProjectColumnIssueInProgress(); - try { - for (const project of param.project.getProjects()) { - const success = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issueNumber, columnName, param.tokens.token); - if (success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Moved issue to \`${columnName}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, - ], - })); - } - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to move the issue to \`${columnName}\`, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; +} +exports.Hotfix = Hotfix; + + +/***/ }), + +/***/ 1721: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Images = void 0; +class Images { + constructor(imagesOnIssue, imagesOnPullRequest, imagesOnCommit, cleanUpGifs, featureGifs, bugfixGifs, docsGifs, choreGifs, releaseGifs, hotfixGifs, prLinkGifs, prFeatureGifs, prBugfixGifs, prReleaseGifs, prHotfixGifs, prDocsGifs, prChoreGifs, commitAutomaticActions, commitFeatureGifs, commitBugfixGifs, commitReleaseGifs, commitHotfixGifs, commitDocsGifs, commitChoreGifs) { + this.imagesOnIssue = imagesOnIssue; + this.imagesOnPullRequest = imagesOnPullRequest; + this.imagesOnCommit = imagesOnCommit; + this.issueAutomaticActions = cleanUpGifs; + this.issueFeatureGifs = featureGifs; + this.issueBugfixGifs = bugfixGifs; + this.issueReleaseGifs = releaseGifs; + this.issueHotfixGifs = hotfixGifs; + this.issueDocsGifs = docsGifs; + this.issueChoreGifs = choreGifs; + this.pullRequestAutomaticActions = prLinkGifs; + this.pullRequestFeatureGifs = prFeatureGifs; + this.pullRequestBugfixGifs = prBugfixGifs; + this.pullRequestReleaseGifs = prReleaseGifs; + this.pullRequestHotfixGifs = prHotfixGifs; + this.pullRequestDocsGifs = prDocsGifs; + this.pullRequestChoreGifs = prChoreGifs; + this.commitAutomaticActions = commitAutomaticActions; + this.commitFeatureGifs = commitFeatureGifs; + this.commitBugfixGifs = commitBugfixGifs; + this.commitReleaseGifs = commitReleaseGifs; + this.commitHotfixGifs = commitHotfixGifs; + this.commitDocsGifs = commitDocsGifs; + this.commitChoreGifs = commitChoreGifs; } } -exports.MoveIssueToInProgressUseCase = MoveIssueToInProgressUseCase; +exports.Images = Images; /***/ }), -/***/ 84423: +/***/ 2632: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -138604,819 +56413,395 @@ var __importStar = (this && this.__importStar) || (function () { }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PrepareBranchesUseCase = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const supabase_repository_1 = __nccwpck_require__(79829); -const logger_1 = __nccwpck_require__(38836); -const execute_script_use_case_1 = __nccwpck_require__(155); -const move_issue_to_in_progress_1 = __nccwpck_require__(98203); -class PrepareBranchesUseCase { - constructor() { - this.taskId = 'PrepareBranchesUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - this.duplicateChunksByBranch = async (supabaseRepository, param, sourceBranch, targetBranch) => { - const result = []; - if (!supabaseRepository) { - return result; - } - try { - await supabaseRepository.duplicateChunksByBranch(param.owner, param.repo, sourceBranch, targetBranch); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `AI index was duplicated from \`${sourceBranch}\` to \`${targetBranch}\`.`, - ] - })); - } - catch (error) { - (0, logger_1.logError)(`Error duplicating chunks: ${JSON.stringify(error, null, 2)}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `There was an error duplicating the AI index from \`${sourceBranch}\` to \`${targetBranch}\`.`, - ], - errors: [ - JSON.stringify(error, null, 2), - ], - })); - } - return result; - }; +exports.Issue = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class Issue { + get title() { + return this.inputs?.issue?.title ?? github.context.payload.issue?.title ?? ''; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - let supabaseRepository = undefined; - if (param.supabaseConfig) { - supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); - } - const result = []; - try { - const issueTitle = param.issue.title; - if (!param.labels.isMandatoryBranchedLabel && issueTitle.length === 0) { - core.setFailed('Issue title not available.'); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - reminders: [ - `Tried to check the title but no one was found.` - ] - })); - return result; - } - /** - * Fetch all branches/tags - */ - await this.branchRepository.fetchRemoteBranches(); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `Take a coffee break while you work ā˜•.` - ] - })); - const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); - (0, logger_1.logDebugInfo)('Available branches:'); - branches.forEach(branch => { - (0, logger_1.logDebugInfo)(`- ${branch}`); - }); - if (param.hotfix.active) { - if (param.hotfix.baseVersion !== undefined && param.hotfix.version !== undefined && param.hotfix.branch !== undefined && param.hotfix.baseBranch !== undefined) { - const branchOid = await this.branchRepository.getCommitTag(param.hotfix.baseVersion); - const tagUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.baseBranch}`; - const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; - (0, logger_1.logDebugInfo)(`Tag branch: ${param.hotfix.baseBranch}`); - (0, logger_1.logDebugInfo)(`Hotfix branch: ${param.hotfix.branch}`); - param.currentConfiguration.parentBranch = param.hotfix.baseBranch; - param.currentConfiguration.hotfixBranch = param.hotfix.branch; - param.currentConfiguration.workingBranch = param.hotfix.branch; - if (branches.indexOf(param.hotfix.branch) === -1) { - const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.hotfix.baseBranch, param.hotfix.branch, param.issueNumber, branchOid, param.tokens.token); - if (linkResult[linkResult.length - 1].success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The tag [**${param.hotfix.baseBranch}**](${tagUrl}) was used to create the branch [**${param.hotfix.branch}**](${hotfixUrl})`, - ], - })); - (0, logger_1.logDebugInfo)(`Hotfix branch successfully linked to issue: ${JSON.stringify(linkResult)}`); - result.push(...await this.duplicateChunksByBranch(supabaseRepository, param, param.branches.main, param.hotfix.branch)); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch [**${param.hotfix.branch}**](${hotfixUrl}) already exists and will not be created from the tag [**${param.hotfix.baseBranch}**](${tagUrl}).`, - ], - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to create a hotfix but no tag was found.`, - ] - })); - return result; - } - } - else if (param.release.active) { - if (param.release.version !== undefined && param.release.branch !== undefined) { - param.currentConfiguration.releaseBranch = param.release.branch; - param.currentConfiguration.workingBranch = param.release.branch; - (0, logger_1.logDebugInfo)(`Release branch: ${param.release.branch}`); - param.currentConfiguration.parentBranch = param.branches.development; - const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; - const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; - const mainUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.defaultBranch}`; - if (branches.indexOf(param.release.branch) === -1) { - const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.branches.development, param.release.branch, param.issueNumber, undefined, param.tokens.token); - const lastAction = linkResult[linkResult.length - 1]; - const reminders = []; - if (lastAction.success) { - const branchName = lastAction.payload.newBranchName; - let commitPrefix = ''; - if (param.commitPrefixBuilder.length > 0) { - param.commitPrefixBuilderParams = { - branchName: branchName, - }; - const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); - const prefixResult = await executor.invoke(param); - commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; - } - reminders.push(`Before deploying, apply any change needed in [**${param.release.branch}**](${releaseUrl}): -> \`\`\`bash -> git fetch -v && git checkout ${param.release.branch} -> \`\`\` -> -> Version files, changelogs..`); - if (commitPrefix.length > 0) { - reminders.push(`Commit the needed changes with this prefix: -> \`\`\` ->${commitPrefix} -> \`\`\``); - } - reminders.push(...[ - `Create the tag version in [**${param.release.branch}**](${releaseUrl}). -> Avoid using \`git merge --squash\`, otherwise the created tag will be lost.`, - `Add the **${param.labels.deploy}** label to run the \`${param.workflows.release}\` workflow.`, - `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). -> **Quick actions:** -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, - ]); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch [**${param.branches.development}**](${developmentUrl}) was used to create the branch [**${param.release.branch}**](${releaseUrl})`, - ], - reminders: reminders, - })); - (0, logger_1.logDebugInfo)(`Release branch successfully linked to issue: ${JSON.stringify(linkResult)}`); - result.push(...await this.duplicateChunksByBranch(supabaseRepository, param, param.branches.development, param.release.branch)); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). -> **Quick actions:** -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). -> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, - ], - })); - } - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to create a release but no release version was found.`, - ] - })); - } - return result; - } - (0, logger_1.logDebugInfo)(`Branch type: ${param.managementBranch}`); - const branchesResult = await this.branchRepository.manageBranches(param, param.owner, param.repo, param.issueNumber, issueTitle, param.managementBranch, param.branches.development, param.hotfix?.branch, param.hotfix.active, param.tokens.token); - result.push(...branchesResult); - const lastAction = branchesResult[branchesResult.length - 1]; - if (lastAction.success && lastAction.executed) { - const branchName = lastAction.payload.newBranchName; - param.currentConfiguration.workingBranch = branchName; - let commitPrefix = ''; - if (param.commitPrefixBuilder.length > 0) { - param.commitPrefixBuilderParams = { - branchName: branchName, - }; - const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); - const prefixResult = await executor.invoke(param); - commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; - } - const rename = lastAction.payload.baseBranchName.indexOf(`${param.branches.featureTree}/`) > -1 - || lastAction.payload.baseBranchName.indexOf(`${param.branches.bugfixTree}/`) > -1; - let step; - let reminder; - if (rename) { - const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; - step = `The branch **${lastAction.payload.baseBranchName}** was renamed to [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; - reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${param.branches.development}\`](${developmentUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${lastAction.payload.newBranchName}?expand=1)`; - } - else { - step = `The branch [**${lastAction.payload.baseBranchName}**](${lastAction.payload.baseBranchUrl}) was used to create [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; - reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${lastAction.payload.baseBranchName}...${lastAction.payload.newBranchName}?expand=1)`; - } - const reminders = []; - reminders.push(`Check out the branch: -> \`\`\`bash -> git fetch -v && git checkout ${lastAction.payload.newBranchName} -> \`\`\``); - if (commitPrefix.length > 0) { - reminders.push(`Commit the needed changes with this prefix: -> \`\`\` ->${commitPrefix} -> \`\`\``); - } - reminders.push(reminder); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - step, - ], - reminders: reminders, - })); - if (param.hotfix.active) { - const mainBranchUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.main}`; - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `After merging into [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}), open a Pull Request from [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}) to [\`${param.branches.main}\`](${mainBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${lastAction.payload.baseBranchName}?expand=1)`, - `After merging into [\`${param.branches.main}\`](${mainBranchUrl}), create the tag \`${param.hotfix.version}\`.`, - ] - })); - } - result.push(...await this.duplicateChunksByBranch(supabaseRepository, param, param.branches.development, lastAction.payload.newBranchName)); - await new Promise(resolve => setTimeout(resolve, 10000)); - result.push(...await new move_issue_to_in_progress_1.MoveIssueToInProgressUseCase().invoke(param)); - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to prepare the hotfix branch to the issue, but there was a problem.`, - ], - error: error, - })); - } - return result; + get number() { + return this.inputs?.issue?.number ?? github.context.payload.issue?.number ?? -1; + } + get creator() { + return this.inputs?.issue?.user?.login ?? github.context.payload.issue?.user.login ?? ''; + } + get url() { + return this.inputs?.issue?.html_url ?? github.context.payload.issue?.html_url ?? ''; + } + get body() { + return this.inputs?.issue?.body ?? github.context.payload.issue?.body ?? ''; + } + get opened() { + return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); + } + get labeled() { + return (this.inputs?.action ?? github.context.payload.action) === 'labeled'; + } + get labelAdded() { + return this.inputs?.label?.name ?? github.context.payload.label?.name ?? ''; + } + get isIssue() { + return (this.inputs?.eventName ?? github.context.eventName) === 'issues'; + } + get isIssueComment() { + return (this.inputs?.eventName ?? github.context.eventName) === 'issue_comment'; + } + get commentId() { + return this.inputs?.comment?.id ?? github.context.payload.comment?.id ?? -1; + } + get commentBody() { + return this.inputs?.comment?.body ?? github.context.payload.comment?.body ?? ''; + } + get commentAuthor() { + return this.inputs?.comment?.user?.login ?? github.context.payload.comment?.user.login ?? ''; + } + get commentUrl() { + return this.inputs?.comment?.html_url ?? github.context.payload.comment?.html_url ?? ''; + } + constructor(branchManagementAlways, reopenOnPush, desiredAssigneesCount, inputs = undefined) { + this.inputs = undefined; + this.branchManagementAlways = branchManagementAlways; + this.reopenOnPush = reopenOnPush; + this.desiredAssigneesCount = desiredAssigneesCount; + this.inputs = inputs; } } -exports.PrepareBranchesUseCase = PrepareBranchesUseCase; +exports.Issue = Issue; /***/ }), -/***/ 92354: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1975: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RemoveIssueBranchesUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const logger_1 = __nccwpck_require__(38836); -/** - * Remove any branch created for this issue - */ -class RemoveIssueBranchesUseCase { - constructor() { - this.taskId = 'RemoveIssueBranchesUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - try { - const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; - const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); - for (const type of branchTypes) { - (0, logger_1.logDebugInfo)(`Checking branch type ${type}`); - let branchName = ''; - const prefix = `${type}/${param.issueNumber}-`; - (0, logger_1.logDebugInfo)(`Checking prefix ${prefix}`); - const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); - if (!matchingBranch) - continue; - branchName = matchingBranch; - const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); - if (removed) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch \`${branchName}\` was removed.`, - ], - })); - if (param.previousConfiguration?.branchType === param.branches.hotfixTree) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - reminders: [ - `Determine if the \`${param.branches.hotfixTree}\` branch is no longer required and can be removed.`, - ], - })); - } - } - } - } - catch (error) { - (0, logger_1.logError)(error); - results.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update issue's title, but there was a problem.`, - ], - error: error, - })); - } - return results; +exports.IssueTypes = void 0; +class IssueTypes { + constructor(task, taskDescription, taskColor, bug, bugDescription, bugColor, feature, featureDescription, featureColor, documentation, documentationDescription, documentationColor, maintenance, maintenanceDescription, maintenanceColor, hotfix, hotfixDescription, hotfixColor, release, releaseDescription, releaseColor, question, questionDescription, questionColor, help, helpDescription, helpColor) { + this.task = task; + this.taskDescription = taskDescription; + this.taskColor = taskColor; + this.bug = bug; + this.bugDescription = bugDescription; + this.bugColor = bugColor; + this.feature = feature; + this.featureDescription = featureDescription; + this.featureColor = featureColor; + this.documentation = documentation; + this.documentationDescription = documentationDescription; + this.documentationColor = documentationColor; + this.maintenance = maintenance; + this.maintenanceDescription = maintenanceDescription; + this.maintenanceColor = maintenanceColor; + this.hotfix = hotfix; + this.hotfixDescription = hotfixDescription; + this.hotfixColor = hotfixColor; + this.release = release; + this.releaseDescription = releaseDescription; + this.releaseColor = releaseColor; + this.question = question; + this.questionDescription = questionDescription; + this.questionColor = questionColor; + this.help = help; + this.helpDescription = helpDescription; + this.helpColor = helpColor; } } -exports.RemoveIssueBranchesUseCase = RemoveIssueBranchesUseCase; +exports.IssueTypes = IssueTypes; /***/ }), -/***/ 90773: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 818: +/***/ ((__unused_webpack_module, exports) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.RemoveNotNeededBranchesUseCase = void 0; -const core = __importStar(__nccwpck_require__(42186)); -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const logger_1 = __nccwpck_require__(38836); -class RemoveNotNeededBranchesUseCase { - constructor() { - this.taskId = 'RemoveNotNeededBranchesUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); +exports.Labels = void 0; +class Labels { + get isMandatoryBranchedLabel() { + return this.isHotfix || this.isRelease; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const issueTitle = param.issue.title; - if (issueTitle.length === 0) { - core.setFailed('Issue title not available.'); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Tried to remove not needed branches related to the issue, but the issue title was not found.`, - ], - })); - return result; - } - const sanitizedTitle = this.branchRepository.formatBranchName(issueTitle, param.issueNumber); - const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); - const finalBranch = `${param.managementBranch}/${param.issueNumber}-${sanitizedTitle}`; - const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; - for (const type of branchTypes) { - let branchName = `${type}/${param.issueNumber}-${sanitizedTitle}`; - const prefix = `${type}/${param.issueNumber}-`; - if (type !== param.managementBranch) { - const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); - if (!matchingBranch) { - continue; - } - branchName = matchingBranch; - const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); - if (removed) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch \`${branchName}\` was removed.`, - ], - })); - } - else { - (0, logger_1.logError)(`Error deleting ${branchName}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to remove not needed branch \`${branchName}\`, but there was a problem.`, - ], - })); - } - } - else { - for (const branch of branches) { - if (branch.indexOf(prefix) > -1 && branch !== finalBranch) { - const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branch, param.tokens.token); - if (removed) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The branch \`${branch}\` was removed.`, - ], - })); - } - else { - (0, logger_1.logError)(`Error deleting ${branch}`); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to remove not needed branch \`${branch}\`, but there was a problem.`, - ], - })); - } - } - } - } - } + get containsBranchedLabel() { + return this.currentIssueLabels.includes(this.branchManagementLauncherLabel); + } + get isDeploy() { + return this.currentIssueLabels.includes(this.deploy); + } + get isDeployed() { + return this.currentIssueLabels.includes(this.deployed); + } + get isHelp() { + return this.currentIssueLabels.includes(this.help); + } + get isQuestion() { + return this.currentIssueLabels.includes(this.question); + } + get isFeature() { + return this.currentIssueLabels.includes(this.feature); + } + get isEnhancement() { + return this.currentIssueLabels.includes(this.enhancement); + } + get isBugfix() { + return this.currentIssueLabels.includes(this.bugfix); + } + get isBug() { + return this.currentIssueLabels.includes(this.bug); + } + get isHotfix() { + return this.currentIssueLabels.includes(this.hotfix); + } + get isRelease() { + return this.currentIssueLabels.includes(this.release); + } + get isDocs() { + return this.currentIssueLabels.includes(this.docs); + } + get isDocumentation() { + return this.currentIssueLabels.includes(this.documentation); + } + get isChore() { + return this.currentIssueLabels.includes(this.chore); + } + get isMaintenance() { + return this.currentIssueLabels.includes(this.maintenance); + } + get sizeLabels() { + return [this.sizeXxl, this.sizeXl, this.sizeL, this.sizeM, this.sizeS, this.sizeXs]; + } + get sizedLabelOnIssue() { + if (this.currentIssueLabels.includes(this.sizeXxl)) { + return this.sizeXxl; } - catch (error) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to remove not needed branches related to the issue, but there was a problem.`, - ], - error: error, - })); + else if (this.currentIssueLabels.includes(this.sizeXl)) { + return this.sizeXl; } - return result; + else if (this.currentIssueLabels.includes(this.sizeL)) { + return this.sizeL; + } + else if (this.currentIssueLabels.includes(this.sizeM)) { + return this.sizeM; + } + else if (this.currentIssueLabels.includes(this.sizeS)) { + return this.sizeS; + } + else if (this.currentIssueLabels.includes(this.sizeXs)) { + return this.sizeXs; + } + return undefined; + } + get sizedLabelOnPullRequest() { + if (this.currentPullRequestLabels.includes(this.sizeXxl)) { + return this.sizeXxl; + } + else if (this.currentPullRequestLabels.includes(this.sizeXl)) { + return this.sizeXl; + } + else if (this.currentPullRequestLabels.includes(this.sizeL)) { + return this.sizeL; + } + else if (this.currentPullRequestLabels.includes(this.sizeM)) { + return this.sizeM; + } + else if (this.currentPullRequestLabels.includes(this.sizeS)) { + return this.sizeS; + } + else if (this.currentPullRequestLabels.includes(this.sizeXs)) { + return this.sizeXs; + } + return undefined; + } + get isIssueSized() { + return this.sizedLabelOnIssue !== undefined; + } + get isPullRequestSized() { + return this.sizedLabelOnPullRequest !== undefined; + } + get priorityLabels() { + return [this.priorityHigh, this.priorityMedium, this.priorityLow, this.priorityNone]; + } + get priorityLabelOnIssue() { + if (this.currentIssueLabels.includes(this.priorityHigh)) { + return this.priorityHigh; + } + else if (this.currentIssueLabels.includes(this.priorityMedium)) { + return this.priorityMedium; + } + else if (this.currentIssueLabels.includes(this.priorityLow)) { + return this.priorityLow; + } + else if (this.currentIssueLabels.includes(this.priorityNone)) { + return this.priorityNone; + } + return undefined; + } + get priorityLabelOnIssueProcessable() { + return this.currentIssueLabels.includes(this.priorityHigh) || + this.currentIssueLabels.includes(this.priorityMedium) || + this.currentIssueLabels.includes(this.priorityLow); + } + get priorityLabelOnPullRequest() { + if (this.currentPullRequestLabels.includes(this.priorityHigh)) { + return this.priorityHigh; + } + else if (this.currentPullRequestLabels.includes(this.priorityMedium)) { + return this.priorityMedium; + } + else if (this.currentPullRequestLabels.includes(this.priorityLow)) { + return this.priorityLow; + } + else if (this.currentPullRequestLabels.includes(this.priorityNone)) { + return this.priorityNone; + } + return undefined; + } + get priorityLabelOnPullRequestProcessable() { + return this.currentPullRequestLabels.includes(this.priorityHigh) || + this.currentPullRequestLabels.includes(this.priorityMedium) || + this.currentPullRequestLabels.includes(this.priorityLow); + } + get isIssuePrioritized() { + return this.priorityLabelOnIssue !== undefined && this.priorityLabelOnIssue !== this.priorityNone; + } + get isPullRequestPrioritized() { + return this.priorityLabelOnPullRequest !== undefined && this.priorityLabelOnPullRequest !== this.priorityNone; + } + constructor(branchManagementLauncherLabel, bug, bugfix, hotfix, enhancement, feature, release, question, help, deploy, deployed, docs, documentation, chore, maintenance, priorityHigh, priorityMedium, priorityLow, priorityNone, sizeXxl, sizeXl, sizeL, sizeM, sizeS, sizeXs) { + this.currentIssueLabels = []; + this.currentPullRequestLabels = []; + this.branchManagementLauncherLabel = branchManagementLauncherLabel; + this.bug = bug; + this.bugfix = bugfix; + this.hotfix = hotfix; + this.enhancement = enhancement; + this.feature = feature; + this.release = release; + this.question = question; + this.help = help; + this.deploy = deploy; + this.deployed = deployed; + this.docs = docs; + this.documentation = documentation; + this.chore = chore; + this.maintenance = maintenance; + this.sizeXxl = sizeXxl; + this.sizeXl = sizeXl; + this.sizeL = sizeL; + this.sizeM = sizeM; + this.sizeS = sizeS; + this.sizeXs = sizeXs; + this.priorityHigh = priorityHigh; + this.priorityMedium = priorityMedium; + this.priorityLow = priorityLow; + this.priorityNone = priorityNone; } } -exports.RemoveNotNeededBranchesUseCase = RemoveNotNeededBranchesUseCase; +exports.Labels = Labels; /***/ }), -/***/ 81652: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2152: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UpdateIssueTypeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class UpdateIssueTypeUseCase { - constructor() { - this.taskId = 'UpdateIssueTypeUseCase'; - this.issueRepository = new issue_repository_1.IssueRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - await this.issueRepository.setIssueType(param.owner, param.repo, param.issueNumber, param.labels, param.issueTypes, param.tokens.token); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to update issue type, but there was a problem.`, - ], - error: error, - })); - } - return result; +exports.Locale = void 0; +class Locale { + constructor(issue, pullRequest) { + this.issue = issue; + this.pullRequest = pullRequest; } } -exports.UpdateIssueTypeUseCase = UpdateIssueTypeUseCase; +exports.Locale = Locale; +Locale.DEFAULT = 'en-US'; /***/ }), -/***/ 90465: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2298: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckIssueCommentLanguageUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class CheckIssueCommentLanguageUseCase { - constructor() { - this.taskId = 'CheckIssueCommentLanguageUseCase'; - this.aiRepository = new ai_repository_1.AiRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.translatedKey = ``; - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - const commentBody = param.issue.commentBody; - if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; - } - const locale = param.locale.issue; - let prompt = ` - You are a helpful assistant that checks if the text is written in ${locale}. - - Instructions: - 1. Analyze the provided text - 2. If the text is written in ${locale}, respond with exactly "done" - 3. If the text is written in any other language, respond with exactly "must_translate" - 4. Do not provide any explanation or additional text - - The text is: ${commentBody} - `; - let result = await this.aiRepository.ask(param.ai, prompt); - if (result === "done") { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return results; - } - prompt = ` -You are a helpful assistant that translates the text to ${locale}. - -Instructions: -1. Translate the text to ${locale} -2. Do not provide any explanation or additional text -3. Return the translated text only - -The text is: ${commentBody} - `; - result = await this.aiRepository.ask(param.ai, prompt); - const translatedCommentBody = `${result} -> ${commentBody} -${this.translatedKey} -`; - await this.issueRepository.updateComment(param.owner, param.repo, param.issue.number, param.issue.commentId, translatedCommentBody, param.tokens.token); - return results; +exports.Milestone = void 0; +class Milestone { + constructor(id, title, description) { + this.id = id; + this.title = title; + this.description = description; } } -exports.CheckIssueCommentLanguageUseCase = CheckIssueCommentLanguageUseCase; +exports.Milestone = Milestone; /***/ }), -/***/ 38129: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 3765: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckChangesPullRequestSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const branch_repository_1 = __nccwpck_require__(37701); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckChangesPullRequestSizeUseCase { - constructor() { - this.taskId = 'CheckChangesPullRequestSizeUseCase'; - this.branchRepository = new branch_repository_1.BranchRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); - } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, param.pullRequest.head, param.pullRequest.base, param.sizeThresholds, param.labels, param.tokens.token); - (0, logger_1.logDebugInfo)(`Size: ${size}`); - (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); - (0, logger_1.logDebugInfo)(`Reason: ${reason}`); - (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnPullRequest}`); - if (param.labels.sizedLabelOnPullRequest !== size) { - /** - * Even if this is for pull reuqets, we are getting the issue labels for having a mirror of the issue labels on the pull request. - */ - const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); - labelNames.push(size); - await this.issueRepository.setLabels(param.owner, param.repo, param.pullRequest.number, labelNames, param.tokens.token); - for (const project of param.project.getProjects()) { - await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.pullRequest.number, githubSize, param.tokens.token); - } - (0, logger_1.logDebugInfo)(`Updated labels on pull request #${param.pullRequest.number}:`); - (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `${reason}, so the pull request was resized to ${size}.`, - ], - })); - } - else { - (0, logger_1.logDebugInfo)(`The pull request is already at the correct size.`); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the size of the changes, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; +exports.ProjectDetail = void 0; +class ProjectDetail { + constructor(data) { + this.id = data[`id`] ?? ''; + this.title = data[`title`] ?? ''; + this.type = data[`type`] ?? ''; + this.owner = data[`owner`] ?? ''; + this.url = data[`url`] ?? ''; + this.number = data[`number`] ?? -1; } } -exports.CheckChangesPullRequestSizeUseCase = CheckChangesPullRequestSizeUseCase; +exports.ProjectDetail = ProjectDetail; /***/ }), -/***/ 67383: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 1938: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckPriorityPullRequestSizeUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class CheckPriorityPullRequestSizeUseCase { - constructor() { - this.taskId = 'CheckPriorityPullRequestSizeUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); +exports.Projects = void 0; +class Projects { + constructor(projects, projectColumnIssueCreated, projectColumnPullRequestCreated, projectColumnIssueInProgress, projectColumnPullRequestInProgress) { + this.projects = projects; + this.projectColumnIssueCreated = projectColumnIssueCreated; + this.projectColumnPullRequestCreated = projectColumnPullRequestCreated; + this.projectColumnIssueInProgress = projectColumnIssueInProgress; + this.projectColumnPullRequestInProgress = projectColumnPullRequestInProgress; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const priority = param.labels.priorityLabelOnIssue; - if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - let priorityLabel = ``; - if (priority === param.labels.priorityHigh) { - priorityLabel = `P0`; - } - else if (priority === param.labels.priorityMedium) { - priorityLabel = `P1`; - } - else if (priority === param.labels.priorityLow) { - priorityLabel = `P2`; - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return result; - } - (0, logger_1.logDebugInfo)(`Priority: ${priority}`); - (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); - for (const project of param.project.getProjects()) { - const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.pullRequest.number, priorityLabel, param.tokens.token); - if (success) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, - ], - })); - } - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to check the priority of the issue, but there was a problem.`, - ], - errors: [ - error?.toString() ?? 'Unknown error', - ], - })); - } - return result; + getProjects() { + return this.projects; + } + getProjectColumnIssueCreated() { + return this.projectColumnIssueCreated; + } + getProjectColumnPullRequestCreated() { + return this.projectColumnPullRequestCreated; + } + getProjectColumnIssueInProgress() { + return this.projectColumnIssueInProgress; + } + getProjectColumnPullRequestInProgress() { + return this.projectColumnPullRequestInProgress; } } -exports.CheckPriorityPullRequestSizeUseCase = CheckPriorityPullRequestSizeUseCase; +exports.Projects = Projects; /***/ }), -/***/ 22175: +/***/ 4179: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -139455,10008 +56840,12561 @@ var __importStar = (this && this.__importStar) || (function () { }; })(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LinkPullRequestIssueUseCase = void 0; -const github = __importStar(__nccwpck_require__(95438)); -const result_1 = __nccwpck_require__(27305); -const pull_request_repository_1 = __nccwpck_require__(20634); -const logger_1 = __nccwpck_require__(38836); -class LinkPullRequestIssueUseCase { - constructor() { - this.taskId = 'LinkPullRequestIssueUseCase'; - this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); +exports.PullRequest = void 0; +const github = __importStar(__nccwpck_require__(5438)); +class PullRequest { + get action() { + return this.inputs?.action ?? github.context.payload.action ?? ''; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const isLinked = await this.pullRequestRepository.isLinked(github.context.payload.pull_request?.html_url ?? ''); - if (!isLinked) { - /** - * Set the primary/default branch - */ - await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.branches.defaultBranch, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The base branch was temporarily updated to \`${param.branches.defaultBranch}\`.`, - ], - })); - /** - * Update PR's description. - */ - let prBody = param.pullRequest.body; - let updatedBody = `${prBody}\n\nResolves #${param.issueNumber}`; - await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The description was temporarily modified to include a reference to issue **#${param.issueNumber}**.`, - ], - })); - /** - * Await 20 seconds - */ - await new Promise(resolve => setTimeout(resolve, 20 * 1000)); - /** - * Restore the original branch - */ - await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.pullRequest.base, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The base branch was reverted to its original value: \`${param.pullRequest.base}\`.`, - ], - })); - /** - * Restore comment on description - */ - prBody = param.pullRequest.body; - updatedBody = prBody.replace(`\n\nResolves #${param.issueNumber}`, ""); - await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The temporary issue reference **#${param.issueNumber}** was removed from the description.`, - ], - })); - return result; - } - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to link pull request to project, but there was a problem.`, - ], - error: error, - })); - } - return result; + get id() { + return this.inputs?.pull_request?.node_id ?? github.context.payload.pull_request?.node_id ?? ''; } -} -exports.LinkPullRequestIssueUseCase = LinkPullRequestIssueUseCase; - - -/***/ }), - -/***/ 64311: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LinkPullRequestProjectUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const project_repository_1 = __nccwpck_require__(67917); -const logger_1 = __nccwpck_require__(38836); -class LinkPullRequestProjectUseCase { - constructor() { - this.taskId = 'LinkPullRequestProjectUseCase'; - this.projectRepository = new project_repository_1.ProjectRepository(); + get title() { + return this.inputs?.pull_request?.title ?? github.context.payload.pull_request?.title ?? ''; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const result = []; - const columnName = param.project.getProjectColumnPullRequestCreated(); - try { - for (const project of param.project.getProjects()) { - let actionDone = await this.projectRepository.linkContentId(project, param.pullRequest.id, param.tokens.token); - if (actionDone) { - /** - * Wait for 10 seconds to ensure the pull request is linked to the project - */ - await new Promise(resolve => setTimeout(resolve, 10000)); - actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.pullRequest.number, columnName, param.tokens.token); - if (actionDone) { - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The pull request was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, - ], - })); - } - else { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `The pull request was linked to [**${project?.title}**](${project?.url}) but there was an error moving it to the column \`${columnName}\`.`, - ], - })); - } - } - } - return result; - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Tried to link pull request to project, but there was a problem.`, - ], - error: error, - })); - } - return result; + get creator() { + return this.inputs?.pull_request?.user?.login ?? github.context.payload.pull_request?.user.login ?? ''; } -} -exports.LinkPullRequestProjectUseCase = LinkPullRequestProjectUseCase; - - -/***/ }), - -/***/ 50158: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.UpdatePullRequestDescriptionUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const file_repository_1 = __nccwpck_require__(81503); -const issue_repository_1 = __nccwpck_require__(40057); -const project_repository_1 = __nccwpck_require__(67917); -const pull_request_repository_1 = __nccwpck_require__(20634); -const logger_1 = __nccwpck_require__(38836); -class UpdatePullRequestDescriptionUseCase { - constructor() { - this.taskId = 'UpdatePullRequestDescriptionUseCase'; - this.aiRepository = new ai_repository_1.AiRepository(); - this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); - this.fileRepository = new file_repository_1.FileRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.projectRepository = new project_repository_1.ProjectRepository(); + get number() { + return this.inputs?.pull_request?.number ?? github.context.payload.pull_request?.number ?? -1; } - async invoke(param) { - (0, logger_1.logDebugInfo)(`Executing ${this.taskId}.`); - const result = []; - try { - const prNumber = param.pullRequest.number; - const issueDescription = await this.issueRepository.getIssueDescription(param.owner, param.repo, param.issueNumber, param.tokens.token); - if (issueDescription.length === 0) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - steps: [ - `No issue description found. Skipping update pull request description.` - ] - })); - return result; - } - const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); - const pullRequestCreatorIsTeamMember = param.pullRequest.creator.length > 0 - && currentProjectMembers.indexOf(param.pullRequest.creator) > -1; - if (!pullRequestCreatorIsTeamMember && param.ai.getAiMembersOnly()) { - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: false, - steps: [ - `The pull request creator @${param.pullRequest.creator} is not a team member and \`AI members only\` is enabled. Skipping update pull request description.` - ] - })); - return result; - } - const changes = await this.pullRequestRepository.getPullRequestChanges(param.owner, param.repo, prNumber, param.tokens.token); - const changesDescription = await this.processChanges(changes, param.ai, param.owner, param.repo, param.tokens.token, param.pullRequest.base); - const descriptionPrompt = `this an issue descrition. -define a description for the pull request which closes the issue and avoid the use of titles (#, ##, ###). -just a text description:\n\n -${issueDescription}`; - const currentDescription = await this.aiRepository.ask(param.ai, descriptionPrompt); - // Update pull request description - await this.pullRequestRepository.updateDescription(param.owner, param.repo, prNumber, ` -#${param.issueNumber} - -## What does this PR do? - -${currentDescription} - -${changesDescription} -`, param.tokens.token); - result.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - steps: [ - `The description has been updated with AI-generated content.` - ] - })); - } - catch (error) { - (0, logger_1.logError)(error); - result.push(new result_1.Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error updating pull request description: ${error}` - ] - })); - } - return result; + get url() { + return this.inputs?.pull_request?.html_url ?? github.context.payload.pull_request?.html_url ?? ''; } - shouldIgnoreFile(filename, ignorePatterns) { - return ignorePatterns.some(pattern => { - // Convert glob pattern to regex - const regexPattern = pattern - .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) - .replace(/\*/g, '.*') // Convert * to match anything - .replace(/\//g, '\\/'); // Escape forward slashes - // Allow pattern ending on /* to ignore also subdirectories and files inside - if (pattern.endsWith("/*")) { - return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); - } - const regex = new RegExp(`^${regexPattern}$`); - return regex.test(filename); - }); + get body() { + return this.inputs?.pull_request?.body ?? github.context.payload.pull_request?.body ?? ''; } - mergePatchSummaries(summaries) { - const mergedMap = new Map(); - for (const summary of summaries) { - const existing = mergedMap.get(summary.filePath); - if (existing) { - // Merge with existing summary - existing.summary = `${existing.summary}\n${summary.summary}`; - existing.changes = [...new Set([...existing.changes, ...summary.changes])]; - } - else { - // Create new entry - mergedMap.set(summary.filePath, { - filePath: summary.filePath, - summary: summary.summary, - changes: [...summary.changes] - }); - } - } - return Array.from(mergedMap.values()); + get head() { + return this.inputs?.pull_request?.head?.ref ?? github.context.payload.pull_request?.head.ref ?? ''; } - groupFilesByDirectory(files) { - const groups = { - root: [] - }; - files.forEach(file => { - const pathParts = file.filePath.split('/'); - if (pathParts.length > 1) { - const directory = pathParts.slice(0, -1).join('/'); - if (!groups[directory]) { - groups[directory] = []; - } - groups[directory].push(file); - } - else { - groups.root.push(file); - } - }); - return groups; + get base() { + return this.inputs?.pull_request?.base?.ref ?? github.context.payload.pull_request?.base.ref ?? ''; } - formatFileChanges(file) { - let output = `#### \`${file.filePath}\`\n\n`; - output += `${file.summary}\n\n`; - if (file.changes.length > 0) { - output += '**Changes:**\n'; - output += file.changes.map(change => `- ${change}`).join('\n'); - } - output += `\n\n--- \n\n`; - return output; + get isMerged() { + return this.inputs?.pull_request?.merged ?? github.context.payload.pull_request?.merged ?? false; } - async processFile(change, ai, owner, repo, token, baseBranch) { - if (!change.patch) { - return []; - } - // Get the original file content - const originalContent = await this.fileRepository.getFileContent(owner, repo, change.filename, token, baseBranch); - const filePrompt = `Analyze the following code changes and provide a summary in JSON format. - -### **Guidelines**: -- Output must be a **valid JSON** object. -- Provide a high-level summary of the changes. -- List the key changes in detail. -- Pay attention to the file names, don't make mistakes with uppercase, lowercase, or underscores. -- Be careful when composing the response JSON, don't make mistakes with unnecessary commas. - -### **Output Format Example**: -\`\`\`json -{ - "filePath": "src/utils/logger.ts", - "summary": "Refactored logging system for better error handling.", - "changes": [ - "Replaced \`console.error\` with \`logError\`.", - "Added support for async logging.", - "Removed unused function \`debugLog\`." - ] -} -\`\`\` - -### **Metadata**: -- **Filename:** ${change.filename} -- **Status:** ${change.status} -- **Changes:** +${change.additions} / -${change.deletions} - -### **Original File Content**: -\`\`\` -${originalContent} -\`\`\` - -### **Patch**: -${change.patch}`; - const response = await this.aiRepository.ask(ai, filePrompt); - if (!response) { - return []; - } - try { - const cleanResponse = response.replace(/^```json\n?/, '').replace(/\n?```$/, '').trim(); - const patchSummary = JSON.parse(cleanResponse); - return [patchSummary]; - } - catch (error) { - (0, logger_1.logDebugError)(`Response: ${response}`); - (0, logger_1.logError)(`Error parsing JSON response: ${error}`); - return []; - } + get opened() { + return ['opened', 'reopened'].includes(this.inputs?.action ?? github.context.payload.action ?? ''); } - async processChanges(changes, ai, owner, repo, token, baseBranch) { - (0, logger_1.logDebugInfo)(`Processing ${changes.length} changes`); - const processFilePromises = changes.map(async (change) => { - try { - (0, logger_1.logDebugInfo)(`Processing changes for file ${change.filename}`); - const shouldIgnoreFile = this.shouldIgnoreFile(change.filename, ai.getAiIgnoreFiles()); - if (shouldIgnoreFile) { - (0, logger_1.logDebugInfo)(`File ${change.filename} should be ignored`); - return []; - } - return await this.processFile(change, ai, owner, repo, token, baseBranch); - } - catch (error) { - (0, logger_1.logError)(error); - throw new Error(`Error processing file ${change.filename}: ${error}`); - } - }); - const fileDescriptions = (await Promise.all(processFilePromises)).flat(); - // Merge PatchSummary objects for the same file - const mergedFileDescriptions = this.mergePatchSummaries(fileDescriptions); - // Group files by directory - const groupedFiles = this.groupFilesByDirectory(mergedFileDescriptions); - // Generate a structured description - let description = ''; - // Add summary section if there are files - if (mergedFileDescriptions.length > 0) { - description += '## Summary of Changes\n\n'; - description += mergedFileDescriptions.map(file => `- **${file.filePath}**: ${file.summary}`).join('\n'); - description += '\n\n'; - } - // Add detailed changes section - description += '## Detailed Changes\n\n'; - // Process each directory group - for (const [directory, files] of Object.entries(groupedFiles)) { - if (directory === 'root') { - // Files in root directory - description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; - } - else { - // Files in subdirectories - description += `### ${directory}\n\n`; - description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; - } - } - return description; + get isOpened() { + return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'open' + && this.action !== 'closed'; + } + get isClosed() { + return (this.inputs?.pull_request?.state ?? github.context.payload.pull_request?.state) === 'closed' + || this.action === 'closed'; + } + get isSynchronize() { + return this.action === 'synchronize'; + } + get isPullRequest() { + return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request'; + } + get isPullRequestReviewComment() { + return (this.inputs?.eventName ?? github.context.eventName) === 'pull_request_review_comment'; + } + get commentId() { + return this.inputs?.pull_request_review_comment?.id ?? github.context.payload.pull_request_review_comment?.id ?? -1; + } + get commentBody() { + return this.inputs?.pull_request_review_comment?.body ?? github.context.payload.pull_request_review_comment?.body ?? ''; + } + get commentAuthor() { + return this.inputs?.pull_request_review_comment?.user?.login ?? github.context.payload.pull_request_review_comment?.user.login ?? ''; + } + get commentUrl() { + return this.inputs?.pull_request_review_comment?.html_url ?? github.context.payload.pull_request_review_comment?.html_url ?? ''; + } + constructor(desiredAssigneesCount, desiredReviewersCount, mergeTimeout, inputs = undefined) { + this.inputs = undefined; + this.desiredAssigneesCount = desiredAssigneesCount; + this.desiredReviewersCount = desiredReviewersCount; + this.mergeTimeout = mergeTimeout; + this.inputs = inputs; } } -exports.UpdatePullRequestDescriptionUseCase = UpdatePullRequestDescriptionUseCase; +exports.PullRequest = PullRequest; /***/ }), -/***/ 87112: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2551: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.CheckPullRequestCommentLanguageUseCase = void 0; -const result_1 = __nccwpck_require__(27305); -const ai_repository_1 = __nccwpck_require__(68307); -const issue_repository_1 = __nccwpck_require__(40057); -const logger_1 = __nccwpck_require__(38836); -class CheckPullRequestCommentLanguageUseCase { +exports.Release = void 0; +class Release { constructor() { - this.taskId = 'CheckPullRequestCommentLanguageUseCase'; - this.aiRepository = new ai_repository_1.AiRepository(); - this.issueRepository = new issue_repository_1.IssueRepository(); - this.translatedKey = ``; + this.active = false; } - async invoke(param) { - (0, logger_1.logInfo)(`Executing ${this.taskId}.`); - const results = []; - const commentBody = param.pullRequest.commentBody; - if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: false, - })); - return results; - } - const locale = param.locale.pullRequest; - let prompt = ` - You are a helpful assistant that checks if the text is written in ${locale}. - - Instructions: - 1. Analyze the provided text - 2. If the text is written in ${locale}, respond with exactly "done" - 3. If the text is written in any other language, respond with exactly "must_translate" - 4. Do not provide any explanation or additional text - - The text is: ${commentBody} - `; - let result = await this.aiRepository.ask(param.ai, prompt); - if (result === "done") { - results.push(new result_1.Result({ - id: this.taskId, - success: true, - executed: true, - })); - return results; - } - prompt = ` -You are a helpful assistant that translates the text to ${locale}. +} +exports.Release = Release; -Instructions: -1. Translate the text to ${locale} -2. Do not provide any explanation or additional text -3. Return the translated text only -The text is: ${commentBody} - `; - result = await this.aiRepository.ask(param.ai, prompt); - const translatedCommentBody = `${result} -> ${commentBody} -${this.translatedKey} -`; - await this.issueRepository.updateComment(param.owner, param.repo, param.pullRequest.number, param.pullRequest.commentId, translatedCommentBody, param.tokens.token); - return results; +/***/ }), + +/***/ 7305: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Result = void 0; +class Result { + constructor(data) { + this.id = data['id'] ?? ''; + this.success = data['success'] ?? false; + this.executed = data['executed'] ?? false; + this.steps = data['steps'] ?? []; + this.errors = data['errors'] ?? []; + this.payload = data['payload']; + this.reminders = data['reminders'] ?? []; } } -exports.CheckPullRequestCommentLanguageUseCase = CheckPullRequestCommentLanguageUseCase; +exports.Result = Result; /***/ }), -/***/ 8593: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8024: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ACTIONS = exports.ERRORS = exports.INPUT_KEYS = exports.WORKFLOW_ACTIVE_STATUSES = exports.WORKFLOW_STATUS = exports.DEFAULT_IMAGE_CONFIG = exports.REPO_URL = exports.TITLE = exports.COMMAND = void 0; -exports.COMMAND = 'git-board-flow'; -exports.TITLE = 'Git Board Flow'; -exports.REPO_URL = 'https://github.com/landamessenger/git-board-flow'; -exports.DEFAULT_IMAGE_CONFIG = { - issue: { - automatic: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp" - ], - feature: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", - ], - bugfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" - ], - hotfix: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" - ], - release: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", - ], - docs: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", - ], - chore: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", - ], - }, - pullRequest: { - automatic: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - ], - feature: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", - ], - bugfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", - ], - hotfix: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", - ], - release: [ - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", - ], - docs: [ - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", - "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", - "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", - ], - chore: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", - ], - }, - commit: { - automatic: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - feature: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - bugfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - hotfix: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - release: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - docs: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ], - chore: [ - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", - "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", - "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", - "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", - ] +exports.SingleAction = void 0; +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class SingleAction { + get isDeployedAction() { + return this.currentSingleAction === constants_1.ACTIONS.DEPLOYED; } -}; -exports.WORKFLOW_STATUS = { - IN_PROGRESS: 'in_progress', - QUEUED: 'queued', - COMPLETED: 'completed', - FAILED: 'failed', - CANCELLED: 'cancelled', - SKIPPED: 'skipped', - TIMED_OUT: 'timed_out', -}; -exports.WORKFLOW_ACTIVE_STATUSES = [exports.WORKFLOW_STATUS.IN_PROGRESS, exports.WORKFLOW_STATUS.QUEUED]; -exports.INPUT_KEYS = { - // Debug - DEBUG: 'debug', - // Welcome - WELCOME_TITLE: 'welcome-title', - WELCOME_MESSAGES: 'welcome-messages', - // Docker - DOCKER_CONTAINER_NAME: 'docker-container-name', - DOCKER_DOMAIN: 'docker-domain', - DOCKER_PORT: 'docker-port', - DOCKER_CACHE_OS: 'docker-cache-os', - DOCKER_CACHE_ARCH: 'docker-cache-arch', - // Single action - SINGLE_ACTION: 'single-action', - SINGLE_ACTION_ISSUE: 'single-action-issue', - SINGLE_ACTION_VERSION: 'single-action-version', - SINGLE_ACTION_TITLE: 'single-action-title', - SINGLE_ACTION_CHANGELOG: 'single-action-changelog', - // Tokens - TOKEN: 'token', - CLASSIC_TOKEN: 'classic-token', - // AI - OPENROUTER_API_KEY: 'openrouter-api-key', - OPENROUTER_MODEL: 'openrouter-model', - AI_PULL_REQUEST_DESCRIPTION: 'ai-pull-request-description', - AI_MEMBERS_ONLY: 'ai-members-only', - AI_IGNORE_FILES: 'ai-ignore-files', - AI_INCLUDE_REASONING: 'ai-include-reasoning', - OPENROUTER_PROVIDER_ORDER: 'openrouter-provider-order', - OPENROUTER_PROVIDER_ALLOW_FALLBACKS: 'openrouter-provider-allow-fallbacks', - OPENROUTER_PROVIDER_REQUIRE_PARAMETERS: 'openrouter-provider-require-parameters', - OPENROUTER_PROVIDER_DATA_COLLECTION: 'openrouter-provider-data-collection', - OPENROUTER_PROVIDER_IGNORE: 'openrouter-provider-ignore', - OPENROUTER_PROVIDER_QUANTIZATIONS: 'openrouter-provider-quantizations', - OPENROUTER_PROVIDER_SORT: 'openrouter-provider-sort', - // Projects - PROJECT_IDS: 'project-ids', - PROJECT_COLUMN_ISSUE_CREATED: 'project-column-issue-created', - PROJECT_COLUMN_PULL_REQUEST_CREATED: 'project-column-pull-request-created', - PROJECT_COLUMN_ISSUE_IN_PROGRESS: 'project-column-issue-in-progress', - PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS: 'project-column-pull-request-in-progress', - // Images - IMAGES_ON_ISSUE: 'images-on-issue', - IMAGES_ON_PULL_REQUEST: 'images-on-pull-request', - IMAGES_ON_COMMIT: 'images-on-commit', - IMAGES_ISSUE_AUTOMATIC: 'images-issue-automatic', - IMAGES_ISSUE_FEATURE: 'images-issue-feature', - IMAGES_ISSUE_BUGFIX: 'images-issue-bugfix', - IMAGES_ISSUE_DOCS: 'images-issue-docs', - IMAGES_ISSUE_CHORE: 'images-issue-chore', - IMAGES_ISSUE_RELEASE: 'images-issue-release', - IMAGES_ISSUE_HOTFIX: 'images-issue-hotfix', - IMAGES_PULL_REQUEST_AUTOMATIC: 'images-pull-request-automatic', - IMAGES_PULL_REQUEST_FEATURE: 'images-pull-request-feature', - IMAGES_PULL_REQUEST_BUGFIX: 'images-pull-request-bugfix', - IMAGES_PULL_REQUEST_RELEASE: 'images-pull-request-release', - IMAGES_PULL_REQUEST_HOTFIX: 'images-pull-request-hotfix', - IMAGES_PULL_REQUEST_DOCS: 'images-pull-request-docs', - IMAGES_PULL_REQUEST_CHORE: 'images-pull-request-chore', - IMAGES_COMMIT_AUTOMATIC: 'images-commit-automatic', - IMAGES_COMMIT_FEATURE: 'images-commit-feature', - IMAGES_COMMIT_BUGFIX: 'images-commit-bugfix', - IMAGES_COMMIT_RELEASE: 'images-commit-release', - IMAGES_COMMIT_HOTFIX: 'images-commit-hotfix', - IMAGES_COMMIT_DOCS: 'images-commit-docs', - IMAGES_COMMIT_CHORE: 'images-commit-chore', - // Workflows - RELEASE_WORKFLOW: 'release-workflow', - HOTFIX_WORKFLOW: 'hotfix-workflow', - // Emoji - EMOJI_LABELED_TITLE: 'emoji-labeled-title', - BRANCH_MANAGEMENT_EMOJI: 'branch-management-emoji', - // Labels - BRANCH_MANAGEMENT_LAUNCHER_LABEL: 'branch-management-launcher-label', - BUGFIX_LABEL: 'bugfix-label', - BUG_LABEL: 'bug-label', - HOTFIX_LABEL: 'hotfix-label', - ENHANCEMENT_LABEL: 'enhancement-label', - FEATURE_LABEL: 'feature-label', - RELEASE_LABEL: 'release-label', - QUESTION_LABEL: 'question-label', - HELP_LABEL: 'help-label', - DEPLOY_LABEL: 'deploy-label', - DEPLOYED_LABEL: 'deployed-label', - DOCS_LABEL: 'docs-label', - DOCUMENTATION_LABEL: 'documentation-label', - CHORE_LABEL: 'chore-label', - MAINTENANCE_LABEL: 'maintenance-label', - PRIORITY_HIGH_LABEL: 'priority-high-label', - PRIORITY_MEDIUM_LABEL: 'priority-medium-label', - PRIORITY_LOW_LABEL: 'priority-low-label', - PRIORITY_NONE_LABEL: 'priority-none-label', - SIZE_XXL_LABEL: 'size-xxl-label', - SIZE_XL_LABEL: 'size-xl-label', - SIZE_L_LABEL: 'size-l-label', - SIZE_M_LABEL: 'size-m-label', - SIZE_S_LABEL: 'size-s-label', - SIZE_XS_LABEL: 'size-xs-label', - // Issue Types - ISSUE_TYPE_BUG: 'issue-type-bug', - ISSUE_TYPE_BUG_DESCRIPTION: 'issue-type-bug-description', - ISSUE_TYPE_BUG_COLOR: 'issue-type-bug-color', - ISSUE_TYPE_HOTFIX: 'issue-type-hotfix', - ISSUE_TYPE_HOTFIX_DESCRIPTION: 'issue-type-hotfix-description', - ISSUE_TYPE_HOTFIX_COLOR: 'issue-type-hotfix-color', - ISSUE_TYPE_FEATURE: 'issue-type-feature', - ISSUE_TYPE_FEATURE_DESCRIPTION: 'issue-type-feature-description', - ISSUE_TYPE_FEATURE_COLOR: 'issue-type-feature-color', - ISSUE_TYPE_DOCUMENTATION: 'issue-type-documentation', - ISSUE_TYPE_DOCUMENTATION_DESCRIPTION: 'issue-type-documentation-description', - ISSUE_TYPE_DOCUMENTATION_COLOR: 'issue-type-documentation-color', - ISSUE_TYPE_MAINTENANCE: 'issue-type-maintenance', - ISSUE_TYPE_MAINTENANCE_DESCRIPTION: 'issue-type-maintenance-description', - ISSUE_TYPE_MAINTENANCE_COLOR: 'issue-type-maintenance-color', - ISSUE_TYPE_RELEASE: 'issue-type-release', - ISSUE_TYPE_RELEASE_DESCRIPTION: 'issue-type-release-description', - ISSUE_TYPE_RELEASE_COLOR: 'issue-type-release-color', - ISSUE_TYPE_QUESTION: 'issue-type-question', - ISSUE_TYPE_QUESTION_DESCRIPTION: 'issue-type-question-description', - ISSUE_TYPE_QUESTION_COLOR: 'issue-type-question-color', - ISSUE_TYPE_HELP: 'issue-type-help', - ISSUE_TYPE_HELP_DESCRIPTION: 'issue-type-help-description', - ISSUE_TYPE_HELP_COLOR: 'issue-type-help-color', - ISSUE_TYPE_TASK: 'issue-type-task', - ISSUE_TYPE_TASK_DESCRIPTION: 'issue-type-task-description', - ISSUE_TYPE_TASK_COLOR: 'issue-type-task-color', - // Locale - ISSUES_LOCALE: 'issues-locale', - PULL_REQUESTS_LOCALE: 'pull-requests-locale', - // Size Thresholds - SIZE_XXL_THRESHOLD_LINES: 'size-xxl-threshold-lines', - SIZE_XXL_THRESHOLD_FILES: 'size-xxl-threshold-files', - SIZE_XXL_THRESHOLD_COMMITS: 'size-xxl-threshold-commits', - SIZE_XL_THRESHOLD_LINES: 'size-xl-threshold-lines', - SIZE_XL_THRESHOLD_FILES: 'size-xl-threshold-files', - SIZE_XL_THRESHOLD_COMMITS: 'size-xl-threshold-commits', - SIZE_L_THRESHOLD_LINES: 'size-l-threshold-lines', - SIZE_L_THRESHOLD_FILES: 'size-l-threshold-files', - SIZE_L_THRESHOLD_COMMITS: 'size-l-threshold-commits', - SIZE_M_THRESHOLD_LINES: 'size-m-threshold-lines', - SIZE_M_THRESHOLD_FILES: 'size-m-threshold-files', - SIZE_M_THRESHOLD_COMMITS: 'size-m-threshold-commits', - SIZE_S_THRESHOLD_LINES: 'size-s-threshold-lines', - SIZE_S_THRESHOLD_FILES: 'size-s-threshold-files', - SIZE_S_THRESHOLD_COMMITS: 'size-s-threshold-commits', - SIZE_XS_THRESHOLD_LINES: 'size-xs-threshold-lines', - SIZE_XS_THRESHOLD_FILES: 'size-xs-threshold-files', - SIZE_XS_THRESHOLD_COMMITS: 'size-xs-threshold-commits', - // Branches - MAIN_BRANCH: 'main-branch', - DEVELOPMENT_BRANCH: 'development-branch', - FEATURE_TREE: 'feature-tree', - BUGFIX_TREE: 'bugfix-tree', - HOTFIX_TREE: 'hotfix-tree', - RELEASE_TREE: 'release-tree', - DOCS_TREE: 'docs-tree', - CHORE_TREE: 'chore-tree', - // Commit - COMMIT_PREFIX_TRANSFORMS: 'commit-prefix-transforms', - // Issue - BRANCH_MANAGEMENT_ALWAYS: 'branch-management-always', - REOPEN_ISSUE_ON_PUSH: 'reopen-issue-on-push', - DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', - // Pull Request - PULL_REQUEST_DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', - PULL_REQUEST_DESIRED_REVIEWERS_COUNT: 'desired-reviewers-count', - PULL_REQUEST_MERGE_TIMEOUT: 'merge-timeout', - // Supabase - SUPABASE_URL: 'supabase-url', - SUPABASE_KEY: 'supabase-key' -}; -exports.ERRORS = { - GIT_REPOSITORY_NOT_FOUND: 'āŒ Git repository not found' -}; -exports.ACTIONS = { - DEPLOYED: 'deployed_action', - COMPILE_VECTOR_SERVER: 'compile_vector_server', - VECTOR: 'vector_action', - VECTOR_LOCAL: 'vector_local', - VECTOR_REMOVAL: 'vector_removal', - PUBLISH_GITHUB_ACTION: 'publish_github_action', - CREATE_RELEASE: 'create_release', - CREATE_TAG: 'create_tag', -}; + get isAiCacheAction() { + return this.currentSingleAction === constants_1.ACTIONS.AI_CACHE || this.currentSingleAction === constants_1.ACTIONS.AI_CACHE_LOCAL; + } + get isAiCacheLocalAction() { + return this.currentSingleAction === constants_1.ACTIONS.AI_CACHE_LOCAL; + } + get isPublishGithubAction() { + return this.currentSingleAction === constants_1.ACTIONS.PUBLISH_GITHUB_ACTION; + } + get isCreateReleaseAction() { + return this.currentSingleAction === constants_1.ACTIONS.CREATE_RELEASE; + } + get isCreateTagAction() { + return this.currentSingleAction === constants_1.ACTIONS.CREATE_TAG; + } + get isThinkAction() { + return this.currentSingleAction === constants_1.ACTIONS.THINK; + } + get enabledSingleAction() { + return this.currentSingleAction.length > 0; + } + get validSingleAction() { + return this.enabledSingleAction && + (this.issue > 0 || this.isSingleActionWithoutIssue) && + this.actions.indexOf(this.currentSingleAction) > -1; + } + get isSingleActionWithoutIssue() { + return this.actionsWithoutIssue.indexOf(this.currentSingleAction) > -1; + } + get throwError() { + return this.actionsThrowError.indexOf(this.currentSingleAction) > -1; + } + constructor(currentSingleAction, issue, version, title, changelog) { + this.actions = [ + constants_1.ACTIONS.DEPLOYED, + constants_1.ACTIONS.AI_CACHE, + constants_1.ACTIONS.AI_CACHE_LOCAL, + constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, + constants_1.ACTIONS.CREATE_TAG, + constants_1.ACTIONS.CREATE_RELEASE, + constants_1.ACTIONS.THINK, + ]; + /** + * Actions that throw an error if the last step failed + */ + this.actionsThrowError = [ + constants_1.ACTIONS.AI_CACHE, + constants_1.ACTIONS.PUBLISH_GITHUB_ACTION, + constants_1.ACTIONS.CREATE_RELEASE, + constants_1.ACTIONS.DEPLOYED, + constants_1.ACTIONS.CREATE_TAG, + ]; + /** + * Actions that do not require an issue + */ + this.actionsWithoutIssue = [ + constants_1.ACTIONS.AI_CACHE, + constants_1.ACTIONS.AI_CACHE_LOCAL, + constants_1.ACTIONS.THINK, + ]; + this.isIssue = false; + this.isPullRequest = false; + this.isPush = false; + /** + * Properties + */ + this.issue = -1; + this.version = ''; + this.title = ''; + this.changelog = ''; + this.version = version; + this.title = title; + this.changelog = changelog; + if (!this.isSingleActionWithoutIssue) { + try { + this.issue = parseInt(issue); + } + catch (error) { + (0, logger_1.logError)(`Issue ${issue} is not a number.`); + (0, logger_1.logError)(error); + } + } + else { + this.issue = 0; + } + this.currentSingleAction = currentSingleAction; + } +} +exports.SingleAction = SingleAction; /***/ }), -/***/ 17873: +/***/ 3835: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.injectJsonAsMarkdownBlock = exports.extractReleaseType = exports.extractVersion = void 0; -const extractVersion = (pattern, text) => { - const versionPattern = new RegExp(`###\\s*${pattern}\\s+(\\d+\\.\\d+\\.\\d+)`, 'i'); - const match = text.match(versionPattern); - return match ? match[1] : undefined; -}; -exports.extractVersion = extractVersion; -const extractReleaseType = (pattern, text) => { - const releaseTypePattern = new RegExp(`###\\s*${pattern}\\s+(Patch|Minor|Major)`, 'i'); - const match = text.match(releaseTypePattern); - return match ? match[1] : undefined; -}; -exports.extractReleaseType = extractReleaseType; -const injectJsonAsMarkdownBlock = (title, json) => { - const formattedJson = JSON.stringify(json, null, 4) // Pretty-print the JSON with 4 spaces. - .split('\n') // Split into lines. - .map(line => `> ${line}`) // Prefix each line with '> '. - .join('\n'); // Join lines back into a string. - return `> **${title}**\n>\n> \`\`\`json\n${formattedJson}\n> \`\`\``; -}; -exports.injectJsonAsMarkdownBlock = injectJsonAsMarkdownBlock; +exports.SizeThreshold = void 0; +class SizeThreshold { + constructor(lines, files, commits) { + this.lines = lines; + this.files = files; + this.commits = commits; + } +} +exports.SizeThreshold = SizeThreshold; /***/ }), -/***/ 31479: +/***/ 8237: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.typesForIssue = exports.branchesForManagement = void 0; -const branchesForManagement = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { - if (labels.includes(hotfixLabel)) - return params.branches.bugfixTree; - if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) - return params.branches.bugfixTree; - if (labels.includes(releaseLabel)) - return params.branches.releaseTree; - if (labels.includes(docsLabel) || labels.includes(documentationLabel)) - return params.branches.docsTree; - if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) - return params.branches.choreTree; - if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) - return params.branches.featureTree; - return params.branches.featureTree; -}; -exports.branchesForManagement = branchesForManagement; -const typesForIssue = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { - if (labels.includes(hotfixLabel)) - return params.branches.hotfixTree; - if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) - return params.branches.bugfixTree; - if (labels.includes(releaseLabel)) - return params.branches.releaseTree; - if (labels.includes(docsLabel) || labels.includes(documentationLabel)) - return params.branches.docsTree; - if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) - return params.branches.choreTree; - if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) - return params.branches.featureTree; - return params.branches.featureTree; +exports.SizeThresholds = void 0; +class SizeThresholds { + constructor(xxl, xl, l, m, s, xs) { + this.xxl = xxl; + this.xl = xl; + this.l = l; + this.m = m; + this.s = s; + this.xs = xs; + } +} +exports.SizeThresholds = SizeThresholds; + + +/***/ }), + +/***/ 149: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SupabaseConfig = void 0; +class SupabaseConfig { + constructor(url, key) { + this.url = url; + this.key = key; + } + getUrl() { + return this.url; + } + getKey() { + return this.key; + } +} +exports.SupabaseConfig = SupabaseConfig; + + +/***/ }), + +/***/ 7057: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.THINK_RESPONSE_JSON_SCHEMA = void 0; +/** + * JSON Schema for ThinkResponse interface + * This schema is used for structured AI reasoning and analysis responses + */ +exports.THINK_RESPONSE_JSON_SCHEMA = { + type: "object", + properties: { + reasoning: { + type: "string", + description: "Current reasoning step or analysis of the problem" + }, + action: { + type: "string", + enum: ["search_files", "read_file", "analyze_code", "propose_changes", "complete", "update_todos"], + description: "Next action to take in the reasoning process" + }, + files_to_search: { + type: "array", + items: { + type: "string" + }, + description: "List of file paths or patterns to search for (when action is 'search_files')" + }, + files_to_read: { + type: "array", + items: { + type: "string" + }, + description: "List of specific file paths to read in full (when action is 'read_file')" + }, + analyzed_files: { + type: "array", + items: { + type: "object", + properties: { + path: { type: "string" }, + key_findings: { type: "string" }, + relevance: { type: "string", enum: ["high", "medium", "low"] } + }, + required: ["path", "key_findings", "relevance"] + }, + description: "Files that have been analyzed with their findings (when action is 'analyze_code')" + }, + proposed_changes: { + type: "array", + items: { + type: "object", + properties: { + file_path: { type: "string" }, + change_type: { type: "string", enum: ["create", "modify", "delete", "refactor"] }, + description: { type: "string" }, + suggested_code: { type: "string" }, + reasoning: { type: "string" } + }, + required: ["file_path", "change_type", "description", "reasoning"] + }, + description: "Proposed changes to the codebase (when action is 'propose_changes')" + }, + complete: { + type: "boolean", + description: "Whether the reasoning process is complete" + }, + final_analysis: { + type: "string", + description: "Final comprehensive analysis and recommendations (when complete is true)" + }, + todo_updates: { + type: "object", + description: "Updates to the TODO list (when action is 'update_todos' or alongside other actions)", + properties: { + create: { + type: "array", + items: { + type: "object", + properties: { + content: { type: "string" }, + status: { type: "string", enum: ["pending", "in_progress"] } + }, + required: ["content"] + }, + description: "New TODO items to create" + }, + update: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "string" }, + status: { type: "string", enum: ["pending", "in_progress", "completed", "cancelled"] }, + notes: { type: "string" } + }, + required: ["id"] + }, + description: "Updates to existing TODO items" + } + } + } + }, + required: ["reasoning", "action", "complete"], + additionalProperties: false }; -exports.typesForIssue = typesForIssue; /***/ }), -/***/ 14990: +/***/ 3421: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Tokens = void 0; +class Tokens { + constructor(token) { + this.token = token; + } +} +exports.Tokens = Tokens; + + +/***/ }), + +/***/ 6845: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +// types.ts (o donde quieras definir tus modelos) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WorkflowRun = void 0; +class WorkflowRun { + // puedes agregar mĆ”s campos si los usas + constructor(data) { + this.id = data.id; + this.name = data.name; + this.head_branch = data.head_branch; + this.head_sha = data.head_sha; + this.run_number = data.run_number; + this.event = data.event; + this.status = data.status; + this.conclusion = data.conclusion; + this.created_at = data.created_at; + this.updated_at = data.updated_at; + this.url = data.url; + this.html_url = data.html_url; + } + isActive() { + return this.status === "in_progress" || this.status === "queued"; + } +} +exports.WorkflowRun = WorkflowRun; + + +/***/ }), + +/***/ 8553: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Workflows = void 0; +class Workflows { + constructor(release, hotfix) { + this.release = release; + this.hotfix = hotfix; + } +} +exports.Workflows = Workflows; + + +/***/ }), + +/***/ 8307: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AiRepository = void 0; +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +const ai_response_schema_1 = __nccwpck_require__(5968); +const think_response_schema_1 = __nccwpck_require__(7057); +class AiRepository { + constructor() { + this.ask = async (ai, prompt) => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + if (!model || !apiKey) { + (0, logger_1.logError)('Missing required AI configuration'); + return undefined; + } + (0, logger_1.logDebugInfo)(`šŸ”Ž Model: ${model}`); + (0, logger_1.logDebugInfo)(`šŸ”Ž API Key: ***`); + (0, logger_1.logDebugInfo)(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + const url = `https://openrouter.ai/api/v1/chat/completions`; + try { + (0, logger_1.logDebugInfo)(`Sending prompt to ${model}: ${prompt}`); + const requestBody = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + }; + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': constants_1.REPO_URL, + 'X-Title': constants_1.TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + const data = await response.json(); + if (!data.choices || data.choices.length === 0) { + (0, logger_1.logError)('No response content received from API'); + return undefined; + } + // logDebugInfo(`Successfully received response from ${model}`); + return data.choices[0].message.content; + } + catch (error) { + (0, logger_1.logError)(`Error querying ${model}: ${error}`); + return undefined; + } + }; + this.askJson = async (ai, prompt, schema, schemaName = "ai_response") => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + if (!model || !apiKey) { + (0, logger_1.logError)('Missing required AI configuration'); + return undefined; + } + // logDebugInfo(`šŸ”Ž Model: ${model}`); + // logDebugInfo(`šŸ”Ž API Key: ***`); + // logDebugInfo(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + const url = `https://openrouter.ai/api/v1/chat/completions`; + // Use provided schema or default to AI_RESPONSE_JSON_SCHEMA + const responseSchema = schema || ai_response_schema_1.AI_RESPONSE_JSON_SCHEMA; + try { + const requestBody = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + response_format: { + type: "json_schema", + json_schema: { + name: schemaName, + schema: responseSchema, + strict: true + } + } + }; + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': constants_1.REPO_URL, + 'X-Title': constants_1.TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + const data = await response.json(); + if (!data.choices || data.choices.length === 0) { + (0, logger_1.logError)('No response content received from API'); + return undefined; + } + // logDebugInfo(`Successfully received response from ${model}`); + const content = data.choices[0].message.content; + // logDebugInfo(`Response: ${content}`); + return JSON.parse(content); + } + catch (error) { + (0, logger_1.logError)(`Error querying ${model}: ${error}`); + return undefined; + } + }; + this.askThinkJson = async (ai, prompt) => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + if (!model || !apiKey) { + (0, logger_1.logError)('Missing required AI configuration'); + return undefined; + } + (0, logger_1.logDebugInfo)(`šŸ”Ž Model: ${model}`); + (0, logger_1.logDebugInfo)(`šŸ”Ž API Key: ***`); + (0, logger_1.logDebugInfo)(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + const url = `https://openrouter.ai/api/v1/chat/completions`; + try { + const requestBody = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + response_format: { + type: "json_schema", + json_schema: { + name: "think_response", + schema: think_response_schema_1.THINK_RESPONSE_JSON_SCHEMA, + strict: true + } + } + }; + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': constants_1.REPO_URL, + 'X-Title': constants_1.TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + (0, logger_1.logError)(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + const data = await response.json(); + if (!data.choices || data.choices.length === 0) { + (0, logger_1.logError)('No response content received from API'); + return undefined; + } + // logDebugInfo(`Successfully received response from ${model}`); + const content = data.choices[0].message.content; + // logDebugInfo(`Response: ${content}`); + return JSON.parse(content); + } + catch (error) { + (0, logger_1.logError)(`Error querying ${model}: ${error}`); + return undefined; + } + }; + } +} +exports.AiRepository = AiRepository; + + +/***/ }), + +/***/ 7701: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -"use strict"; +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.BranchRepository = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const exec = __importStar(__nccwpck_require__(1514)); +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const version_utils_1 = __nccwpck_require__(9887); +const result_1 = __nccwpck_require__(7305); +class BranchRepository { + constructor() { + this.fetchRemoteBranches = async () => { + try { + (0, logger_1.logDebugInfo)('Fetching tags and forcing fetch...'); + await exec.exec('git', ['fetch', '--tags', '--force']); + (0, logger_1.logDebugInfo)('Fetching all remote branches with verbose output...'); + await exec.exec('git', ['fetch', '--all', '-v']); + (0, logger_1.logDebugInfo)('Successfully fetched all remote branches.'); + } + catch (error) { + core.setFailed(`Error fetching remote branches: ${error}`); + } + }; + this.getLatestTag = async () => { + try { + (0, logger_1.logDebugInfo)('Fetching the latest tag...'); + await exec.exec('git', ['fetch', '--tags']); + const tags = []; + await exec.exec('git', ['tag', '--sort=-creatordate'], { + listeners: { + stdout: (data) => { + tags.push(...data.toString().split('\n').map((v, i, a) => { + return v.replace('v', ''); + })); + }, + }, + }); + const validTags = tags.filter(tag => /\d+\.\d+\.\d+$/.test(tag)); + if (validTags.length > 0) { + const latestTag = (0, version_utils_1.getLatestVersion)(validTags); + (0, logger_1.logDebugInfo)(`Latest tag: ${latestTag}`); + return latestTag; + } + else { + (0, logger_1.logDebugInfo)('No valid tags found.'); + return undefined; + } + } + catch (error) { + core.setFailed(`Error fetching the latest tag: ${error}`); + return undefined; + } + }; + this.getCommitTag = async (latestTag) => { + try { + if (!latestTag) { + core.setFailed('No LATEST_TAG found in the environment'); + return; + } + let tagVersion; + if (latestTag.startsWith('v')) { + tagVersion = latestTag; + } + else { + tagVersion = `v${latestTag}`; + } + (0, logger_1.logDebugInfo)(`Fetching commit hash for the tag: ${tagVersion}`); + let commitOid = ''; + await exec.exec('git', ['rev-list', '-n', '1', tagVersion], { + listeners: { + stdout: (data) => { + commitOid = data.toString().trim(); + }, + }, + }); + if (commitOid) { + (0, logger_1.logDebugInfo)(`Commit tag: ${commitOid}`); + return commitOid; + } + else { + core.setFailed('No commit found for the tag'); + } + } + catch (error) { + core.setFailed(`Error fetching the commit hash: ${error}`); + } + return undefined; + }; + /** + * Returns replaced branch (if any). + * + * @param param + * @param repository + * @param owner + * @param token + * @param issueNumber + * @param issueTitle + * @param branchType + * @param developmentBranch + * @param hotfixBranch + * @param isHotfix + */ + this.manageBranches = async (param, owner, repository, issueNumber, issueTitle, branchType, developmentBranch, hotfixBranch, isHotfix, token) => { + const result = []; + try { + (0, logger_1.logDebugInfo)(`Managing branches`); + const branches = await this.getListOfBranches(owner, repository, token); + (0, logger_1.logDebugInfo)(JSON.stringify(branches, null, 2)); + if (hotfixBranch === undefined && isHotfix) { + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Tried to prepare the hotfix branch of the issue, but hotfix branch was not found.`, + ], + })); + return result; + } + const octokit = github.getOctokit(token); + const sanitizedTitle = this.formatBranchName(issueTitle, issueNumber); + const newBranchName = `${branchType}/${issueNumber}-${sanitizedTitle}`; + if (branches.indexOf(newBranchName) > -1) { + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: false, + })); + return result; + } + const branchTypes = [ + param.branches.featureTree, + param.branches.bugfixTree, + param.branches.docsTree, + param.branches.choreTree, + ]; + /** + * Default base branch name. (ex. [develop]) + */ + let baseBranchName = developmentBranch; + if (!isHotfix) { + /** + * Check if it is a branch switch: feature/123-bla <-> bugfix/123-bla + */ + (0, logger_1.logDebugInfo)(`Searching for branches related to issue #${issueNumber}...`); + const { data } = await octokit.rest.repos.listBranches({ + owner: owner, + repo: repository, + }); + for (const type of branchTypes) { + const prefix = `${type}/${issueNumber}-`; + try { + const matchingBranch = data.find(branch => branch.name.indexOf(prefix) > -1); + if (matchingBranch) { + baseBranchName = matchingBranch.name; + (0, logger_1.logDebugInfo)(`Found previous issue branch: ${baseBranchName}`); + // TODO replacedBranchName = baseBranchName + break; + } + } + catch (error) { + (0, logger_1.logError)(`Error while listing branches: ${error}`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Error while listing branches.`, + ], + error: error, + })); + } + } + } + else { + baseBranchName = hotfixBranch ?? developmentBranch; + } + param.currentConfiguration.parentBranch = baseBranchName; + (0, logger_1.logDebugInfo)(`============================================================================================`); + (0, logger_1.logDebugInfo)(`Base branch: ${baseBranchName}`); + (0, logger_1.logDebugInfo)(`New branch: ${newBranchName}`); + result.push(...await this.createLinkedBranch(owner, repository, baseBranchName, newBranchName, issueNumber, undefined, token)); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Tried to prepare the hotfix to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; + }; + this.formatBranchName = (issueTitle, issueNumber) => { + let sanitizedTitle = issueTitle.toLowerCase() + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + sanitizedTitle = sanitizedTitle.replace(/[^a-z0-9 ]/g, '').replace(/ /g, '-'); + const issuePrefix = `${issueNumber}-`; + if (sanitizedTitle.startsWith(issuePrefix)) { + sanitizedTitle = sanitizedTitle.substring(issuePrefix.length); + } + sanitizedTitle = sanitizedTitle.replace(/-+/g, '-'); + sanitizedTitle = sanitizedTitle.replace(/^-|-$/g, ''); + return sanitizedTitle; + }; + this.createLinkedBranch = async (owner, repo, baseBranchName, newBranchName, issueNumber, oid, token) => { + const result = []; + try { + (0, logger_1.logDebugInfo)(`Creating linked branch ${newBranchName} from ${oid ?? baseBranchName}`); + let ref = `heads/${baseBranchName}`; + if (baseBranchName.indexOf('tags/') > -1) { + ref = baseBranchName; + } + const octokit = github.getOctokit(token); + const { repository } = await octokit.graphql(` + query($repo: String!, $owner: String!, $issueNumber: Int!) { + repository(name: $repo, owner: $owner) { + id + issue(number: $issueNumber) { + id + } + ref(qualifiedName: "refs/${ref}") { + target { + ... on Commit { + oid + } + } + } + } + } + `, { + repo: repo, + owner: owner, + issueNumber: issueNumber + }); + (0, logger_1.logDebugInfo)(`Repository information retrieved: ${JSON.stringify(repository?.ref)}`); + const repositoryId = repository?.id ?? undefined; + const issueId = repository?.issue?.id ?? undefined; + const branchOid = oid ?? repository?.ref?.target?.oid ?? undefined; + if (repositoryId === undefined || issueNumber === undefined || branchOid === undefined) { + (0, logger_1.logError)(`Error searching repository "${baseBranchName}": id: ${repositoryId}, oid: ${branchOid}), issue #${issueNumber}`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Error linking branch ${newBranchName} to issue: Repository not found.`, + ], + })); + return result; + } + (0, logger_1.logDebugInfo)(`Linking branch "${newBranchName}" (oid: ${branchOid}) to issue #${issueNumber}`); + const mutationResponse = await octokit.graphql(` + mutation($issueId: ID!, $name: String!, $repositoryId: ID!, $oid: GitObjectID!) { + createLinkedBranch(input: { + issueId: $issueId, + name: $name, + repositoryId: $repositoryId, + oid: $oid, + }) { + linkedBranch { + id + ref { + name + } + } + } + } + `, { + issueId: issueId, + name: `/${newBranchName}`, + repositoryId: repositoryId, + oid: branchOid, + }); + (0, logger_1.logDebugInfo)(`Linked branch: ${JSON.stringify(mutationResponse.createLinkedBranch?.linkedBranch)}`); + const baseBranchUrl = `https://github.com/${owner}/${repo}/tree/${baseBranchName}`; + const newBranchUrl = `https://github.com/${owner}/${repo}/tree/${newBranchName}`; + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: true, + payload: { + baseBranchName: baseBranchName, + baseBranchUrl: baseBranchUrl, + newBranchName: newBranchName, + newBranchUrl: newBranchUrl, + }, + })); + } + catch (error) { + (0, logger_1.logError)(`Error Linking branch "${error}"`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Tried to link branch to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; + }; + this.removeBranch = async (owner, repository, branch, token) => { + const octokit = github.getOctokit(token); + const ref = `heads/${branch}`; + try { + const { data } = await octokit.rest.git.getRef({ + owner: owner, + repo: repository, + ref, + }); + (0, logger_1.logDebugInfo)(`Branch found: ${data.ref}`); + await octokit.rest.git.deleteRef({ + owner: owner, + repo: repository, + ref, + }); + (0, logger_1.logDebugInfo)(`Successfully deleted branch: ${branch}`); + return true; + } + catch (error) { + (0, logger_1.logError)(`Error processing branch ${branch}: ${error}`); + throw error; + } + }; + this.getListOfBranches = async (owner, repository, token) => { + const octokit = github.getOctokit(token); + const allBranches = []; + let page = 1; + while (true) { + const { data } = await octokit.rest.repos.listBranches({ + owner: owner, + repo: repository, + per_page: 100, + page: page, + }); + if (data.length === 0) { + break; + } + allBranches.push(...data.map(branch => branch.name)); + page++; + } + return allBranches; + }; + this.executeWorkflow = async (owner, repository, branch, workflow, inputs, token) => { + const octokit = github.getOctokit(token); + return octokit.rest.actions.createWorkflowDispatch({ + owner: owner, + repo: repository, + workflow_id: workflow, + ref: branch, + inputs: inputs + }); + }; + this.mergeBranch = async (owner, repository, head, base, timeout, token) => { + const result = []; + try { + const octokit = github.getOctokit(token); + (0, logger_1.logDebugInfo)(`Creating merge from ${head} into ${base}`); + // Build PR body with commit list + const prBody = `šŸš€ Automated Merge + +This PR merges **${head}** into **${base}**. -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getRandomElement = void 0; -const chance_1 = __importDefault(__nccwpck_require__(82983)); -const chance = new chance_1.default(); -const getRandomElement = (list) => { - // Return undefined for empty lists - if (!list?.length) { - return undefined; - } - // Return first element for single item lists - if (list.length === 1) { - return list[0]; +**Commits included:**`; + // We need PAT for creating PR to ensure it can trigger workflows + const { data: pullRequest } = await octokit.rest.pulls.create({ + owner: owner, + repo: repository, + head: head, + base: base, + title: `Merge ${head} into ${base}`, + body: prBody, + }); + (0, logger_1.logDebugInfo)(`Pull request #${pullRequest.number} created, getting commits...`); + // Get all commits in the PR + const { data: commits } = await octokit.rest.pulls.listCommits({ + owner: owner, + repo: repository, + pull_number: pullRequest.number + }); + const commitMessages = commits.map(commit => commit.commit.message); + (0, logger_1.logDebugInfo)(`Found ${commitMessages.length} commits in PR`); + // Update PR with commit list and footer + await octokit.rest.pulls.update({ + owner: owner, + repo: repository, + pull_number: pullRequest.number, + body: prBody + '\n' + commitMessages.map(msg => `- ${msg}`).join('\n') + + '\n\nThis PR was automatically created by [`git-board-flow`](https://github.com/landamessenger/git-board-flow).' + }); + const iteration = 10; + if (timeout > iteration) { + // Wait for checks to complete - can use regular token for reading checks + let checksCompleted = false; + let attempts = 0; + const maxAttempts = timeout > iteration ? Math.floor(timeout / iteration) : iteration; + while (!checksCompleted && attempts < maxAttempts) { + const { data: checkRuns } = await octokit.rest.checks.listForRef({ + owner: owner, + repo: repository, + ref: head, + }); + // Get commit status checks for the PR head commit + const { data: commitStatus } = await octokit.rest.repos.getCombinedStatusForRef({ + owner: owner, + repo: repository, + ref: head + }); + (0, logger_1.logDebugInfo)(`Combined status state: ${commitStatus.state}`); + (0, logger_1.logDebugInfo)(`Number of check runs: ${checkRuns.check_runs.length}`); + // If there are check runs, prioritize those over status checks + if (checkRuns.check_runs.length > 0) { + const pendingCheckRuns = checkRuns.check_runs.filter(check => check.status !== 'completed'); + if (pendingCheckRuns.length === 0) { + checksCompleted = true; + (0, logger_1.logDebugInfo)('All check runs have completed.'); + // Verify if all checks passed + const failedChecks = checkRuns.check_runs.filter(check => check.conclusion === 'failure'); + if (failedChecks.length > 0) { + throw new Error(`Checks failed: ${failedChecks.map(check => check.name).join(', ')}`); + } + } + else { + (0, logger_1.logDebugInfo)(`Waiting for ${pendingCheckRuns.length} check runs to complete:`); + pendingCheckRuns.forEach(check => { + (0, logger_1.logDebugInfo)(` - ${check.name} (Status: ${check.status})`); + }); + await new Promise(resolve => setTimeout(resolve, iteration * 1000)); + attempts++; + continue; + } + } + else { + // Fall back to status checks if no check runs exist + const pendingChecks = commitStatus.statuses.filter(status => { + (0, logger_1.logDebugInfo)(`Status check: ${status.context} (State: ${status.state})`); + return status.state === 'pending'; + }); + if (pendingChecks.length === 0) { + checksCompleted = true; + (0, logger_1.logDebugInfo)('All status checks have completed.'); + } + else { + (0, logger_1.logDebugInfo)(`Waiting for ${pendingChecks.length} status checks to complete:`); + pendingChecks.forEach(check => { + (0, logger_1.logDebugInfo)(` - ${check.context} (State: ${check.state})`); + }); + await new Promise(resolve => setTimeout(resolve, iteration * 1000)); + attempts++; + } + } + } + if (!checksCompleted) { + throw new Error('Timed out waiting for checks to complete'); + } + } + // Need PAT for merging to ensure it can trigger subsequent workflows + await octokit.rest.pulls.merge({ + owner: owner, + repo: repository, + pull_number: pullRequest.number, + merge_method: 'merge', + commit_title: `Merge ${head} into ${base}. Forced merge with PAT token.`, + }); + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: true, + steps: [ + `The branch \`${head}\` was merged into \`${base}\`.`, + ], + })); + } + catch (error) { + (0, logger_1.logError)(`Error in PR workflow: ${error}`); + // If the PR workflow fails, we try to merge directly - need PAT for direct merge to ensure it can trigger workflows + try { + const octokit = github.getOctokit(token); + await octokit.rest.repos.merge({ + owner: owner, + repo: repository, + base: base, + head: head, + commit_message: `Forced merge of ${head} into ${base}. Automated merge with PAT token.`, + }); + result.push(new result_1.Result({ + id: 'branch_repository', + success: true, + executed: true, + steps: [ + `The branch \`${head}\` was merged into \`${base}\` using direct merge.`, + ], + })); + return result; + } + catch (directMergeError) { + (0, logger_1.logError)(`Error in direct merge attempt: ${directMergeError}`); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + steps: [ + `Failed to merge branch \`${head}\` into \`${base}\`.`, + ], + })); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + error: error, + })); + result.push(new result_1.Result({ + id: 'branch_repository', + success: false, + executed: true, + error: directMergeError, + })); + } + } + return result; + }; + this.getChanges = async (owner, repository, head, base, token) => { + const octokit = github.getOctokit(token); + try { + (0, logger_1.logDebugInfo)(`Comparing branches: ${head} with ${base}`); + let headRef = `heads/${head}`; + if (head.indexOf('tags/') > -1) { + headRef = head; + } + let baseRef = `heads/${base}`; + if (base.indexOf('tags/') > -1) { + baseRef = base; + } + const { data: comparison } = await octokit.rest.repos.compareCommits({ + owner: owner, + repo: repository, + base: baseRef, + head: headRef, + }); + return { + aheadBy: comparison.ahead_by, + behindBy: comparison.behind_by, + totalCommits: comparison.total_commits, + files: (comparison.files || []).map(file => ({ + filename: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + changes: file.changes, + blobUrl: file.blob_url, + rawUrl: file.raw_url, + contentsUrl: file.contents_url, + patch: file.patch + })), + commits: comparison.commits.map(commit => ({ + sha: commit.sha, + message: commit.commit.message, + author: commit.commit.author || { name: 'Unknown', email: 'unknown@example.com', date: new Date().toISOString() }, + date: commit.commit.author?.date || new Date().toISOString() + })) + }; + } + catch (error) { + (0, logger_1.logError)(`Error comparing branches: ${error}`); + throw error; + } + }; + this.getSizeCategoryAndReason = async (owner, repository, head, base, sizeThresholds, labels, token) => { + try { + const headBranchChanges = await this.getChanges(owner, repository, head, base, token); + const totalChanges = headBranchChanges.files.reduce((sum, file) => sum + file.changes, 0); + const totalFiles = headBranchChanges.files.length; + const totalCommits = headBranchChanges.totalCommits; + let sizeCategory; + let githubSize; + let sizeReason; + if (totalChanges > sizeThresholds.xxl.lines || totalFiles > sizeThresholds.xxl.files || totalCommits > sizeThresholds.xxl.commits) { + sizeCategory = labels.sizeXxl; + githubSize = `XL`; + sizeReason = totalChanges > sizeThresholds.xxl.lines ? `More than ${sizeThresholds.xxl.lines} lines changed` : + totalFiles > sizeThresholds.xxl.files ? `More than ${sizeThresholds.xxl.files} files modified` : + `More than ${sizeThresholds.xxl.commits} commits`; + } + else if (totalChanges > sizeThresholds.xl.lines || totalFiles > sizeThresholds.xl.files || totalCommits > sizeThresholds.xl.commits) { + sizeCategory = labels.sizeXl; + githubSize = `XL`; + sizeReason = totalChanges > sizeThresholds.xl.lines ? `More than ${sizeThresholds.xl.lines} lines changed` : + totalFiles > sizeThresholds.xl.files ? `More than ${sizeThresholds.xl.files} files modified` : + `More than ${sizeThresholds.xl.commits} commits`; + } + else if (totalChanges > sizeThresholds.l.lines || totalFiles > sizeThresholds.l.files || totalCommits > sizeThresholds.l.commits) { + sizeCategory = labels.sizeL; + githubSize = `L`; + sizeReason = totalChanges > sizeThresholds.l.lines ? `More than ${sizeThresholds.l.lines} lines changed` : + totalFiles > sizeThresholds.l.files ? `More than ${sizeThresholds.l.files} files modified` : + `More than ${sizeThresholds.l.commits} commits`; + } + else if (totalChanges > sizeThresholds.m.lines || totalFiles > sizeThresholds.m.files || totalCommits > sizeThresholds.m.commits) { + sizeCategory = labels.sizeM; + githubSize = `M`; + sizeReason = totalChanges > sizeThresholds.m.lines ? `More than ${sizeThresholds.m.lines} lines changed` : + totalFiles > sizeThresholds.m.files ? `More than ${sizeThresholds.m.files} files modified` : + `More than ${sizeThresholds.m.commits} commits`; + } + else if (totalChanges > sizeThresholds.s.lines || totalFiles > sizeThresholds.s.files || totalCommits > sizeThresholds.s.commits) { + sizeCategory = labels.sizeS; + githubSize = `S`; + sizeReason = totalChanges > sizeThresholds.s.lines ? `More than ${sizeThresholds.s.lines} lines changed` : + totalFiles > sizeThresholds.s.files ? `More than ${sizeThresholds.s.files} files modified` : + `More than ${sizeThresholds.s.commits} commits`; + } + else { + sizeCategory = labels.sizeXs; + githubSize = `XS`; + sizeReason = `Small changes (${totalChanges} lines, ${totalFiles} files)`; + } + return { + size: sizeCategory, + githubSize: githubSize, + reason: sizeReason + }; + } + catch (error) { + (0, logger_1.logError)(`Error comparing branches: ${error}`); + throw error; + } + }; } - // Use chance to get a random index - const randomIndex = chance.integer({ min: 0, max: list.length - 1 }); - return list[randomIndex]; -}; -exports.getRandomElement = getRandomElement; +} +exports.BranchRepository = BranchRepository; /***/ }), -/***/ 38836: +/***/ 1503: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setGlobalLoggerDebug = setGlobalLoggerDebug; -exports.logInfo = logInfo; -exports.logWarning = logWarning; -exports.logError = logError; -exports.logDebugInfo = logDebugInfo; -exports.logDebugWarning = logDebugWarning; -exports.logDebugError = logDebugError; -exports.logSingleLine = logSingleLine; -const readline_1 = __importDefault(__nccwpck_require__(14521)); -let loggerDebug = false; -let loggerRemote = false; -function setGlobalLoggerDebug(debug, isRemote = false) { - loggerDebug = debug; - loggerRemote = isRemote; -} -function logInfo(message, previousWasSingleLine = false) { - if (previousWasSingleLine && !loggerRemote) { - console.log(); +exports.FileRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const crypto_1 = __nccwpck_require__(6113); +class FileRepository { + constructor() { + this.getFileContent = async (owner, repository, path, token, branch) => { + const octokit = github.getOctokit(token); + try { + const { data } = await octokit.rest.repos.getContent({ + owner, + repo: repository, + path, + ref: branch + }); + if ('content' in data) { + return Buffer.from(data.content, 'base64').toString(); + } + return ''; + } + catch (error) { + (0, logger_1.logError)(`Error getting file content: ${error}.`); + return ''; + } + }; + this.getRepositoryContent = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { + const octokit = github.getOctokit(token); + const fileContents = new Map(); + try { + const getContentRecursively = async (path = '') => { + const { data } = await octokit.rest.repos.getContent({ + owner, + repo: repository, + path, + ref: branch + }); + if (Array.isArray(data)) { + const promises = []; + for (const item of data) { + if (item.type === 'file') { + if (this.isMediaOrPdfFile(item.path) || this.shouldIgnoreFile(item.path, ignoreFiles)) { + ignoredFiles(item.path); + continue; + } + progress(item.path); + const filePromise = (async () => { + const content = await this.getFileContent(owner, repository, item.path, token, branch); + fileContents.set(item.path, content); + })(); + promises.push(filePromise); + } + else if (item.type === 'dir') { + promises.push(getContentRecursively(item.path)); + } + } + await Promise.all(promises); + } + }; + await getContentRecursively(); + return fileContents; + } + catch (error) { + (0, logger_1.logError)(`Error getting repository content: ${error}.`); + return new Map(); + } + }; + this.extractCodeBlocks = (code) => { + const lines = code.split('\n'); + const blocks = []; + let currentBlock; + let braceDepth = 0; + let indentLevel = 0; + const startBlock = (type, name, line, lineNumber) => { + currentBlock = { + type, + name, + content: line + '\n', + startLine: lineNumber, + endLine: lineNumber, + }; + braceDepth = (line.match(/{/g) || []).length - (line.match(/}/g) || []).length; + indentLevel = line.match(/^(\s*)/)?.[1].length ?? 0; + }; + const endBlock = (lineNumber) => { + if (currentBlock) { + currentBlock.endLine = lineNumber; + blocks.push(currentBlock); + currentBlock = undefined; + } + }; + lines.forEach((line, idx) => { + const trimmed = line.trim(); + const lineNumber = idx + 1; + // Detect class or function headers + const functionMatch = trimmed.match(/(?:function|def|fn|async|const|let)\s+(\w+)/); + const classMatch = trimmed.match(/class\s+(\w+)/); + if (!currentBlock && functionMatch) { + startBlock('function', functionMatch[1], line, lineNumber); + } + else if (!currentBlock && classMatch) { + startBlock('class', classMatch[1], line, lineNumber); + } + else if (currentBlock) { + currentBlock.content += line + '\n'; + // Update brace depth + braceDepth += (line.match(/{/g) || []).length; + braceDepth -= (line.match(/}/g) || []).length; + // Or detect dedentation (for Python-style) + const currentIndent = line.match(/^(\s*)/)?.[1].length ?? 0; + const dedented = currentIndent < indentLevel; + if (braceDepth <= 0 && trimmed.endsWith('}') || dedented) { + endBlock(lineNumber); + } + } + }); + // Catch any unfinished block + if (currentBlock) { + currentBlock.endLine = lines.length; + blocks.push(currentBlock); + } + return blocks; + }; + this.shouldIgnoreLine = (line) => { + const trimmed = line.trim(); + return (trimmed === '' || + /^[}\]);]+;?$/.test(trimmed) || + /^import\s.+from\s.+;?$/.test(trimmed) || + /^(return|break|continue|pass);?$/.test(trimmed) || + /^\/\/[-=]*$/.test(trimmed) || // comentarios de separación + /^\/\/\s*(TODO|FIXME)?\s*$/i.test(trimmed) || + /^[\]],?;?$/.test(trimmed) || + /^try\s*{$/.test(trimmed) || + /^}\s*else\s*{$/.test(trimmed) || + /^`;?$/.test(trimmed) || + /^\/\*\*$/.test(trimmed) || + /^\*\/$/.test(trimmed)); + }; + this.getFileTree = async (owner, repository, token, branch, ignoreFiles, progress, ignoredFiles) => { + const fileContents = await this.getRepositoryContent(owner, repository, token, branch, ignoreFiles, progress, ignoredFiles); + // Create root nodes for both trees + const rootWithContent = { + name: repository, + type: 'directory', + path: '', + children: [] + }; + const rootWithoutContent = { + name: repository, + type: 'directory', + path: '', + children: [] + }; + // Process each file path to build both trees + for (const [filePath, content] of fileContents.entries()) { + const parts = filePath.split('/'); + let currentLevelWithContent = rootWithContent; + let currentLevelWithoutContent = rootWithoutContent; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + const isLastPart = i === parts.length - 1; + const currentPath = parts.slice(0, i + 1).join('/'); + // Find or create the node in the content tree + let nodeWithContent = currentLevelWithContent.children?.find(n => n.name === part); + if (!nodeWithContent) { + nodeWithContent = { + name: part, + type: isLastPart ? 'file' : 'directory', + path: currentPath, + children: isLastPart ? undefined : [], + content: isLastPart ? content : undefined + }; + if (!currentLevelWithContent.children) { + currentLevelWithContent.children = []; + } + currentLevelWithContent.children.push(nodeWithContent); + } + // Find or create the node in the no-content tree + let nodeWithoutContent = currentLevelWithoutContent.children?.find(n => n.name === part); + if (!nodeWithoutContent) { + nodeWithoutContent = { + name: part, + type: isLastPart ? 'file' : 'directory', + path: currentPath, + children: isLastPart ? undefined : [] + }; + if (!currentLevelWithoutContent.children) { + currentLevelWithoutContent.children = []; + } + currentLevelWithoutContent.children.push(nodeWithoutContent); + } + if (!isLastPart) { + currentLevelWithContent = nodeWithContent; + currentLevelWithoutContent = nodeWithoutContent; + } + } + } + return { + withContent: rootWithContent, + withoutContent: rootWithoutContent + }; + }; } - console.log(message); -} -function logWarning(message) { - console.warn(message); -} -function logError(message) { - console.error(message.toString()); -} -function logDebugInfo(message, previousWasSingleLine = false) { - if (loggerDebug) { - logInfo(message, previousWasSingleLine); + isMediaOrPdfFile(path) { + const mediaExtensions = [ + // Image formats + '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico', + // Audio formats + '.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', + // Video formats + '.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', + // PDF + '.pdf' + ]; + const extension = path.toLowerCase().substring(path.lastIndexOf('.')); + return mediaExtensions.includes(extension); } -} -function logDebugWarning(message) { - if (loggerDebug) { - logWarning(message); + shouldIgnoreFile(filename, ignorePatterns) { + // First check for .DS_Store + if (filename.endsWith('.DS_Store')) { + return true; + } + return ignorePatterns.some(pattern => { + // Convert glob pattern to regex + const regexPattern = pattern + .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) + .replace(/\*/g, '.*') // Convert * to match anything + .replace(/\//g, '\\/'); // Escape forward slashes + // Allow pattern ending on /* to ignore also subdirectories and files inside + if (pattern.endsWith("/*")) { + return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); + } + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(filename); + }); } -} -function logDebugError(message) { - if (loggerDebug) { - logError(message.toString()); + shuffleArray(array) { + return [...array].sort(() => Math.random() - 0.5); } -} -function logSingleLine(message) { - if (loggerRemote) { - console.log(message); - return; + calculateShasum(content) { + return (0, crypto_1.createHash)('sha256').update(content).digest('hex'); } - readline_1.default.clearLine(process.stdout, 0); - readline_1.default.cursorTo(process.stdout, 0); - process.stdout.write(message); } +exports.FileRepository = FileRepository; /***/ }), -/***/ 99800: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 57: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.waitForPreviousRuns = void 0; -const workflow_repository_1 = __nccwpck_require__(90779); -const logger_1 = __nccwpck_require__(38836); -const waitForPreviousRuns = async (params) => { - let attempts = 0; - while (attempts < 2000) { - const workflowRepository = new workflow_repository_1.WorkflowRepository(); - const activeRuns = await workflowRepository.getActivePreviousRuns(params); - if (activeRuns.length === 0) { - (0, logger_1.logDebugInfo)("āœ… No previous runs active. Continuing..."); - return; - } - (0, logger_1.logDebugInfo)(`ā³ Found ${activeRuns.length} previous run(s) still active. Waiting 2s...`); - await new Promise((res) => setTimeout(res, 2000)); - attempts++; +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]; } }; } - throw new Error("Timeout waiting for previous runs to finish."); -}; -exports.waitForPreviousRuns = waitForPreviousRuns; - - -/***/ }), - -/***/ 26676: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.extractVersionFromBranch = exports.extractIssueNumberFromPush = exports.extractIssueNumberFromBranch = void 0; -const logger_1 = __nccwpck_require__(38836); -const extractIssueNumberFromBranch = (branchName) => { - const match = branchName?.match(/[a-zA-Z]+\/([0-9]+)-.*/); - if (match) { - return parseInt(match[1]); - } - else { - (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); - return -1; - } -}; -exports.extractIssueNumberFromBranch = extractIssueNumberFromBranch; -const extractIssueNumberFromPush = (branchName) => { - const issueNumberMatch = branchName.match(/^[^/]+\/(\d+)-/); - if (!issueNumberMatch) { - (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); - return -1; - } - const issueNumber = parseInt(issueNumberMatch[1], 10); - (0, logger_1.logDebugInfo)(`Linked Issue: #${issueNumber}`); - return issueNumber; -}; -exports.extractIssueNumberFromPush = extractIssueNumberFromPush; -const extractVersionFromBranch = (branchName) => { - const match = branchName?.match(/^[^\/]+\/(\d+\.\d+\.\d+)$/); - if (match) { - return match[1]; - } - else { - (0, logger_1.logDebugInfo)('No version found in the branch name.'); - return undefined; +exports.IssueRepository = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const milestone_1 = __nccwpck_require__(2298); +class IssueRepository { + constructor() { + this.updateTitleIssueFormat = async (owner, repository, version, issueTitle, issueNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { + try { + const octokit = github.getOctokit(token); + let emoji = 'šŸ¤–'; + const branched = branchManagementAlways || labels.containsBranchedLabel; + if (labels.isHotfix && branched) { + emoji = `šŸ”„${branchManagementEmoji}`; + } + else if (labels.isRelease && branched) { + emoji = `šŸš€${branchManagementEmoji}`; + } + else if ((labels.isBugfix || labels.isBug) && branched) { + emoji = `šŸ›${branchManagementEmoji}`; + } + else if ((labels.isFeature || labels.isEnhancement) && branched) { + emoji = `✨${branchManagementEmoji}`; + } + else if ((labels.isDocs || labels.isDocumentation) && branched) { + emoji = `šŸ“${branchManagementEmoji}`; + } + else if ((labels.isChore || labels.isMaintenance) && branched) { + emoji = `šŸ”§${branchManagementEmoji}`; + } + else if (labels.isHotfix) { + emoji = 'šŸ”„'; + } + else if (labels.isRelease) { + emoji = 'šŸš€'; + } + else if ((labels.isDocs || labels.isDocumentation)) { + emoji = 'šŸ“'; + } + else if (labels.isChore || labels.isMaintenance) { + emoji = 'šŸ”§'; + } + else if (labels.isBugfix || labels.isBug) { + emoji = 'šŸ›'; + } + else if (labels.isFeature || labels.isEnhancement) { + emoji = '✨'; + } + else if (labels.isHelp) { + emoji = 'šŸ†˜'; + } + else if (labels.isQuestion) { + emoji = 'ā“'; + } + let sanitizedTitle = issueTitle + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + let formattedTitle = `${emoji} - ${sanitizedTitle}`; + if (version.length > 0) { + formattedTitle = `${emoji} - ${version} - ${sanitizedTitle}`; + } + if (formattedTitle !== issueTitle) { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + title: formattedTitle, + }); + (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); + return formattedTitle; + } + return undefined; + } + catch (error) { + core.setFailed(`Failed to check or update issue title: ${error}`); + return undefined; + } + }; + this.updateTitlePullRequestFormat = async (owner, repository, pullRequestTitle, issueTitle, issueNumber, pullRequestNumber, branchManagementAlways, branchManagementEmoji, labels, token) => { + try { + const octokit = github.getOctokit(token); + let emoji = 'šŸ¤–'; + const branched = branchManagementAlways || labels.containsBranchedLabel; + if (labels.isHotfix && branched) { + emoji = `šŸ”„${branchManagementEmoji}`; + } + else if (labels.isRelease && branched) { + emoji = `šŸš€${branchManagementEmoji}`; + } + else if ((labels.isBugfix || labels.isBug) && branched) { + emoji = `šŸ›${branchManagementEmoji}`; + } + else if ((labels.isFeature || labels.isEnhancement) && branched) { + emoji = `✨${branchManagementEmoji}`; + } + else if ((labels.isDocs || labels.isDocumentation) && branched) { + emoji = `šŸ“${branchManagementEmoji}`; + } + else if ((labels.isChore || labels.isMaintenance) && branched) { + emoji = `šŸ”§${branchManagementEmoji}`; + } + else if (labels.isHotfix) { + emoji = 'šŸ”„'; + } + else if (labels.isRelease) { + emoji = 'šŸš€'; + } + else if (labels.isBugfix || labels.isBug) { + emoji = 'šŸ›'; + } + else if (labels.isFeature || labels.isEnhancement) { + emoji = '✨'; + } + else if (labels.isDocs || labels.isDocumentation) { + emoji = 'šŸ“'; + } + else if (labels.isChore || labels.isMaintenance) { + emoji = 'šŸ”§'; + } + else if (labels.isHelp) { + emoji = 'šŸ†˜'; + } + else if (labels.isQuestion) { + emoji = 'ā“'; + } + let sanitizedTitle = issueTitle + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 ]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + const formattedTitle = `[#${issueNumber}] ${emoji} - ${sanitizedTitle}`; + if (formattedTitle !== pullRequestTitle) { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: pullRequestNumber, + title: formattedTitle, + }); + (0, logger_1.logDebugInfo)(`Issue title updated to: ${formattedTitle}`); + return formattedTitle; + } + return undefined; + } + catch (error) { + core.setFailed(`Failed to check or update issue title: ${error}`); + return undefined; + } + }; + this.cleanTitle = async (owner, repository, issueTitle, issueNumber, token) => { + try { + const octokit = github.getOctokit(token); + let sanitizedTitle = issueTitle + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 ]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + if (sanitizedTitle !== issueTitle) { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + title: sanitizedTitle, + }); + (0, logger_1.logDebugInfo)(`Issue title updated to: ${sanitizedTitle}`); + return sanitizedTitle; + } + return undefined; + } + catch (error) { + core.setFailed(`Failed to check or update issue title: ${error}`); + return undefined; + } + }; + this.updateDescription = async (owner, repo, issueNumber, description, token) => { + const octokit = github.getOctokit(token); + try { + await octokit.rest.issues.update({ + owner, + repo, + issue_number: issueNumber, + body: description, + }); + } + catch (error) { + (0, logger_1.logError)(`Error updating issue description: ${error}`); + throw error; + } + }; + this.getDescription = async (owner, repo, issueNumber, token) => { + if (issueNumber === -1) { + return undefined; + } + const octokit = github.getOctokit(token); + try { + const { data: issue } = await octokit.rest.issues.get({ + owner, + repo, + issue_number: issueNumber, + }); + return issue.body ?? ''; + } + catch (error) { + (0, logger_1.logError)(`Error reading issue #${issueNumber} description: ${error}`); + return undefined; + } + }; + this.getId = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const issueQuery = ` + query($repo: String!, $owner: String!, $issueNumber: Int!) { + repository(name: $repo, owner: $owner) { + issue(number: $issueNumber) { + id + } + } + } + `; + const issueResult = await octokit.graphql(issueQuery, { + owner: owner, + repo: repository, + issueNumber, + }); + const issueId = issueResult.repository.issue.id; + (0, logger_1.logDebugInfo)(`Fetched issue ID: ${issueId}`); + return issueId; + }; + this.getMilestone = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + if (issue.milestone) { + return new milestone_1.Milestone(issue.milestone.id, issue.milestone.title, issue.milestone.description ?? ''); + } + else { + return undefined; + } + }; + this.getTitle = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + return issue.title; + } + catch (error) { + (0, logger_1.logError)(`Failed to fetch the issue title: ${error}`); + return undefined; + } + }; + this.getLabels = async (owner, repository, issueNumber, token) => { + if (issueNumber === -1) { + return []; + } + const octokit = github.getOctokit(token); + const { data: labels } = await octokit.rest.issues.listLabelsOnIssue({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + return labels.map(label => label.name); + }; + this.setLabels = async (owner, repository, issueNumber, labels, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.issues.setLabels({ + owner: owner, + repo: repository, + issue_number: issueNumber, + labels: labels, + }); + }; + this.isIssue = async (owner, repository, issueNumber, token) => { + const isPullRequest = await this.isPullRequest(owner, repository, issueNumber, token); + return !isPullRequest; + }; + this.isPullRequest = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + return !!data.pull_request; + }; + this.getHeadBranch = async (owner, repository, issueNumber, token) => { + const isPr = await this.isPullRequest(owner, repository, issueNumber, token); + if (!isPr) { + return undefined; + } + const octokit = github.getOctokit(token); + const pullRequest = await octokit.rest.pulls.get({ + owner, + repo: repository, + pull_number: issueNumber, + }); + return pullRequest.data.head.ref; + }; + this.addComment = async (owner, repository, issueNumber, comment, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.issues.createComment({ + owner: owner, + repo: repository, + issue_number: issueNumber, + body: comment, + }); + (0, logger_1.logDebugInfo)(`Comment added to Issue ${issueNumber}.`); + }; + this.updateComment = async (owner, repository, issueNumber, commentId, comment, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.issues.updateComment({ + owner: owner, + repo: repository, + comment_id: commentId, + body: comment, + }); + (0, logger_1.logDebugInfo)(`Comment ${commentId} updated in Issue ${issueNumber}.`); + }; + this.closeIssue = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); + if (issue.state === 'open') { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + state: 'closed', + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been closed.`); + return true; + } + else { + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already closed.`); + return false; + } + }; + this.openIssue = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner: owner, + repo: repository, + issue_number: issueNumber, + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} state: ${issue.state}`); + if (issue.state === 'closed') { + await octokit.rest.issues.update({ + owner: owner, + repo: repository, + issue_number: issueNumber, + state: 'open', + }); + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} has been re-opened.`); + return true; + } + else { + (0, logger_1.logDebugInfo)(`Issue #${issueNumber} is already opened.`); + return false; + } + }; + this.getCurrentAssignees = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data: issue } = await octokit.rest.issues.get({ + owner, + repo: repository, + issue_number: issueNumber, + }); + const assignees = issue.assignees; + if (assignees === undefined || assignees === null) { + return []; + } + return assignees.map((assignee) => assignee.login); + } + catch (error) { + (0, logger_1.logError)(`Error getting members of issue: ${error}.`); + return []; + } + }; + this.assignMembersToIssue = async (owner, repository, issueNumber, members, token) => { + const octokit = github.getOctokit(token); + try { + if (members.length === 0) { + (0, logger_1.logDebugInfo)(`No members provided for assignment. Skipping operation.`); + return []; + } + const { data: updatedIssue } = await octokit.rest.issues.addAssignees({ + owner, + repo: repository, + issue_number: issueNumber, + assignees: members, + }); + const updatedAssignees = updatedIssue.assignees || []; + return updatedAssignees.map((assignee) => assignee.login); + } + catch (error) { + (0, logger_1.logError)(`Error assigning members to issue: ${error}.`); + return []; + } + }; + this.getIssueDescription = async (owner, repository, issueNumber, token) => { + const octokit = github.getOctokit(token); + const { data: issue } = await octokit.rest.issues.get({ + owner, + repo: repository, + issue_number: issueNumber, + }); + return issue.body ?? ''; + }; + this.setIssueType = async (owner, repository, issueNumber, labels, issueTypes, token) => { + try { + let issueType = issueTypes.task; + let issueTypeDescription = issueTypes.taskDescription; + let issueTypeColor = issueTypes.taskColor; + if (labels.isHotfix) { + issueType = issueTypes.hotfix; + issueTypeDescription = issueTypes.hotfixDescription; + issueTypeColor = issueTypes.hotfixColor; + } + else if (labels.isRelease) { + issueType = issueTypes.release; + issueTypeDescription = issueTypes.releaseDescription; + issueTypeColor = issueTypes.releaseColor; + } + else if ((labels.isDocs || labels.isDocumentation)) { + issueType = issueTypes.documentation; + issueTypeDescription = issueTypes.documentationDescription; + issueTypeColor = issueTypes.documentationColor; + } + else if (labels.isChore || labels.isMaintenance) { + issueType = issueTypes.maintenance; + issueTypeDescription = issueTypes.maintenanceDescription; + issueTypeColor = issueTypes.maintenanceColor; + } + else if (labels.isBugfix || labels.isBug) { + issueType = issueTypes.bug; + issueTypeDescription = issueTypes.bugDescription; + issueTypeColor = issueTypes.bugColor; + } + else if (labels.isFeature || labels.isEnhancement) { + issueType = issueTypes.feature; + issueTypeDescription = issueTypes.featureDescription; + issueTypeColor = issueTypes.featureColor; + } + else if (labels.isHelp) { + issueType = issueTypes.help; + issueTypeDescription = issueTypes.helpDescription; + issueTypeColor = issueTypes.helpColor; + } + else if (labels.isQuestion) { + issueType = issueTypes.question; + issueTypeDescription = issueTypes.questionDescription; + issueTypeColor = issueTypes.questionColor; + } + const octokit = github.getOctokit(token); + (0, logger_1.logDebugInfo)(`Setting issue type for issue ${issueNumber} to ${issueType}`); + (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); + (0, logger_1.logDebugInfo)(`Issue Type: ${issueType}`); + (0, logger_1.logDebugInfo)(`Issue Type Description: ${issueTypeDescription}`); + (0, logger_1.logDebugInfo)(`Issue Type Color: ${issueTypeColor}`); + // Try to update the issue with the issue type using GraphQL + const issueId = await this.getId(owner, repository, issueNumber, token); + // First, try to find existing issue types in the organization + const { organization } = await octokit.graphql(` + query ($owner: String!) { + organization(login: $owner) { + id + issueTypes(first: 20) { + nodes { + id + name + } + } + } + } + `, { owner }); + (0, logger_1.logDebugInfo)(`Organization ID: ${organization.id}`); + (0, logger_1.logDebugInfo)(`Organization issue types: ${JSON.stringify(organization.issueTypes.nodes)}`); + // Check if the issue type already exists + const existingType = organization.issueTypes.nodes.find((type) => type.name.toLowerCase() === issueType.toLowerCase()); + let issueTypeId; + if (existingType) { + issueTypeId = existingType.id; + (0, logger_1.logDebugInfo)(`Found existing issue type "${issueType}" with ID: ${issueTypeId}`); + } + else { + // Try to create the issue type using GraphQL + try { + (0, logger_1.logDebugInfo)(`Creating new issue type "${issueType}" for organization ${owner}...`); + const createResult = await octokit.graphql(` + mutation ($ownerId: ID!, $name: String!, $description: String!, $color: IssueTypeColor!, $isEnabled: Boolean!) { + createIssueType(input: { + ownerId: $ownerId, + name: $name, + description: $description, + color: $color, + isEnabled: $isEnabled + }) { + issueType { + id + } + } + } + `, { + ownerId: organization.id, + name: issueType, + description: issueTypeDescription, + color: issueTypeColor.toUpperCase(), + isEnabled: true, + }); + issueTypeId = createResult.createIssueType.issueType.id; + (0, logger_1.logDebugInfo)(`Created new issue type "${issueType}" with ID: ${issueTypeId}`); + } + catch (createError) { + (0, logger_1.logError)(`Failed to create issue type "${issueType}": ${createError}`); + // If creation fails, we'll fall back to using labels + (0, logger_1.logDebugInfo)(`Falling back to using labels for issue type classification`); + return; + } + } + // Update the issue with the issue type using GraphQL + await octokit.graphql(` + mutation ($issueId: ID!, $issueTypeId: ID!) { + updateIssueIssueType(input: { + issueId: $issueId, + issueTypeId: $issueTypeId + }) { + issue { + id + issueType { + id + name + } + } + } + } + `, { + issueId, + issueTypeId, + }); + (0, logger_1.logDebugInfo)(`Successfully updated issue type to ${issueType}`); + } + catch (error) { + (0, logger_1.logError)(`Failed to update issue type: ${error}`); + // Don't throw the error to prevent breaking the main flow + // The issue will still be processed with labels + (0, logger_1.logDebugInfo)(`Continuing with issue processing despite issue type update failure`); + throw error; + } + }; } -}; -exports.extractVersionFromBranch = extractVersionFromBranch; +} +exports.IssueRepository = IssueRepository; /***/ }), -/***/ 29887: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7917: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getLatestVersion = exports.incrementVersion = void 0; -const logger_1 = __nccwpck_require__(38836); -const incrementVersion = (version, releaseType) => { - (0, logger_1.logDebugInfo)(`Incrementing version ${version}.`); - const versionParts = version.split('.').map(Number); - if (versionParts.length !== 3) { - throw new Error('Invalid version format'); - } - const [major, minor, patch] = versionParts; - switch (releaseType) { - case 'Major': - // Increment the major version and reset minor and patch - return `${major + 1}.0.0`; - case 'Minor': - // Increment the minor version and reset patch - return `${major}.${minor + 1}.0`; - case 'Patch': - // Increment the patch version - return `${major}.${minor}.${patch + 1}`; - default: - throw new Error('Unknown release type'); +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]; } }; } -}; -exports.incrementVersion = incrementVersion; -const getLatestVersion = (versions) => { - return versions - .map(version => version.split('.').map(num => parseInt(num, 10))) - .sort((a, b) => { - for (let i = 0; i < 3; i++) { - if (a[i] > b[i]) - return 1; - if (a[i] < b[i]) - return -1; - } - return 0; - }) - .map(version => version.join('.')) - .pop(); -}; -exports.getLatestVersion = getLatestVersion; - - -/***/ }), - -/***/ 24240: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = require(__nccwpck_require__.ab + "build/Release/cpufeatures.node") - -/***/ }), - -/***/ 29041: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = require(__nccwpck_require__.ab + "lib/protocol/crypto/build/Release/sshcrypto.node") - -/***/ }), - -/***/ 30132: -/***/ ((module) => { - -module.exports = eval("require")("supports-color"); - - -/***/ }), - -/***/ 39491: -/***/ ((module) => { - -"use strict"; -module.exports = require("assert"); - -/***/ }), - -/***/ 50852: -/***/ ((module) => { - -"use strict"; -module.exports = require("async_hooks"); - -/***/ }), - -/***/ 14300: -/***/ ((module) => { - -"use strict"; -module.exports = require("buffer"); - -/***/ }), - -/***/ 32081: -/***/ ((module) => { - -"use strict"; -module.exports = require("child_process"); - -/***/ }), - -/***/ 96206: -/***/ ((module) => { - -"use strict"; -module.exports = require("console"); - -/***/ }), - -/***/ 22057: -/***/ ((module) => { - -"use strict"; -module.exports = require("constants"); - -/***/ }), - -/***/ 6113: -/***/ ((module) => { - -"use strict"; -module.exports = require("crypto"); - -/***/ }), - -/***/ 67643: -/***/ ((module) => { - -"use strict"; -module.exports = require("diagnostics_channel"); - -/***/ }), - -/***/ 9523: -/***/ ((module) => { - -"use strict"; -module.exports = require("dns"); - -/***/ }), - -/***/ 82361: -/***/ ((module) => { - -"use strict"; -module.exports = require("events"); - -/***/ }), - -/***/ 57147: -/***/ ((module) => { - -"use strict"; -module.exports = require("fs"); - -/***/ }), - -/***/ 13685: -/***/ ((module) => { - -"use strict"; -module.exports = require("http"); - -/***/ }), - -/***/ 85158: -/***/ ((module) => { - -"use strict"; -module.exports = require("http2"); - -/***/ }), - -/***/ 95687: -/***/ ((module) => { - -"use strict"; -module.exports = require("https"); - -/***/ }), - -/***/ 41808: -/***/ ((module) => { - -"use strict"; -module.exports = require("net"); - -/***/ }), - -/***/ 6005: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:crypto"); - -/***/ }), - -/***/ 15673: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:events"); - -/***/ }), - -/***/ 97742: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:process"); - -/***/ }), - -/***/ 84492: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:stream"); - -/***/ }), - -/***/ 47261: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:util"); - -/***/ }), - -/***/ 22037: -/***/ ((module) => { - -"use strict"; -module.exports = require("os"); - -/***/ }), - -/***/ 71017: -/***/ ((module) => { - -"use strict"; -module.exports = require("path"); - -/***/ }), - -/***/ 4074: -/***/ ((module) => { - -"use strict"; -module.exports = require("perf_hooks"); - -/***/ }), - -/***/ 77282: -/***/ ((module) => { - -"use strict"; -module.exports = require("process"); - -/***/ }), - -/***/ 85477: -/***/ ((module) => { - -"use strict"; -module.exports = require("punycode"); - -/***/ }), - -/***/ 63477: -/***/ ((module) => { - -"use strict"; -module.exports = require("querystring"); - -/***/ }), - -/***/ 14521: -/***/ ((module) => { - -"use strict"; -module.exports = require("readline"); - -/***/ }), - -/***/ 12781: -/***/ ((module) => { - -"use strict"; -module.exports = require("stream"); - -/***/ }), - -/***/ 35356: -/***/ ((module) => { - -"use strict"; -module.exports = require("stream/web"); - -/***/ }), - -/***/ 71576: -/***/ ((module) => { - -"use strict"; -module.exports = require("string_decoder"); - -/***/ }), - -/***/ 39512: -/***/ ((module) => { - -"use strict"; -module.exports = require("timers"); - -/***/ }), - -/***/ 24404: -/***/ ((module) => { - -"use strict"; -module.exports = require("tls"); - -/***/ }), - -/***/ 76224: -/***/ ((module) => { - -"use strict"; -module.exports = require("tty"); - -/***/ }), - -/***/ 57310: -/***/ ((module) => { - -"use strict"; -module.exports = require("url"); - -/***/ }), - -/***/ 73837: -/***/ ((module) => { - -"use strict"; -module.exports = require("util"); - -/***/ }), - -/***/ 29830: -/***/ ((module) => { - -"use strict"; -module.exports = require("util/types"); - -/***/ }), - -/***/ 71267: -/***/ ((module) => { - -"use strict"; -module.exports = require("worker_threads"); - -/***/ }), - -/***/ 59796: -/***/ ((module) => { - -"use strict"; -module.exports = require("zlib"); - -/***/ }), - -/***/ 92960: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const WritableStream = (__nccwpck_require__(84492).Writable) -const inherits = (__nccwpck_require__(47261).inherits) - -const StreamSearch = __nccwpck_require__(51142) - -const PartStream = __nccwpck_require__(81620) -const HeaderParser = __nccwpck_require__(92032) - -const DASH = 45 -const B_ONEDASH = Buffer.from('-') -const B_CRLF = Buffer.from('\r\n') -const EMPTY_FN = function () {} - -function Dicer (cfg) { - if (!(this instanceof Dicer)) { return new Dicer(cfg) } - WritableStream.call(this, cfg) - - if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - - if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - - this._headerFirst = cfg.headerFirst - - this._dashes = 0 - this._parts = 0 - this._finished = false - this._realFinish = false - this._isPreamble = true - this._justMatched = false - this._firstWrite = true - this._inHeader = true - this._part = undefined - this._cb = undefined - this._ignoreData = false - this._partOpts = { highWaterMark: cfg.partHwm } - this._pause = false - - const self = this - this._hparser = new HeaderParser(cfg) - this._hparser.on('header', function (header) { - self._inHeader = false - self._part.emit('header', header) - }) -} -inherits(Dicer, WritableStream) - -Dicer.prototype.emit = function (ev) { - if (ev === 'finish' && !this._realFinish) { - if (!this._finished) { - const self = this - process.nextTick(function () { - self.emit('error', new Error('Unexpected end of multipart data')) - if (self._part && !self._ignoreData) { - const type = (self._isPreamble ? 'Preamble' : 'Part') - self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) - self._part.push(null) - process.nextTick(function () { - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - return + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ProjectRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +const project_detail_1 = __nccwpck_require__(3765); +class ProjectRepository { + constructor() { + this.priorityLabel = "Priority"; + this.sizeLabel = "Size"; + this.statusLabel = "Status"; + /** + * Retrieves detailed information about a GitHub project + * @param projectId - The project number/ID + * @param token - GitHub authentication token + * @returns Promise - The project details + * @throws {Error} If the project is not found or if there are authentication/network issues + */ + this.getProjectDetail = async (projectId, token) => { + try { + // Validate projectId is a valid number + const projectNumber = parseInt(projectId, 10); + if (isNaN(projectNumber)) { + throw new Error(`Invalid project ID: ${projectId}. Must be a valid number.`); + } + const octokit = github.getOctokit(token); + const { data: owner } = await octokit.rest.users.getByUsername({ + username: github.context.repo.owner + }).catch(error => { + throw new Error(`Failed to get owner information: ${error.message}`); + }); + const ownerType = owner.type === 'Organization' ? 'orgs' : 'users'; + const projectUrl = `https://github.com/${ownerType}/${github.context.repo.owner}/projects/${projectId}`; + const ownerQueryField = ownerType === 'orgs' ? 'organization' : 'user'; + const queryProject = ` + query($ownerName: String!, $projectNumber: Int!) { + ${ownerQueryField}(login: $ownerName) { + projectV2(number: $projectNumber) { + id + title + url + } + } + } + `; + const projectResult = await octokit.graphql(queryProject, { + ownerName: github.context.repo.owner, + projectNumber: projectNumber, + }).catch(error => { + throw new Error(`Failed to fetch project data: ${error.message}`); + }); + const projectData = projectResult[ownerQueryField]?.projectV2; + if (!projectData) { + throw new Error(`Project not found: ${projectUrl}`); + } + (0, logger_1.logDebugInfo)(`Project ID: ${projectData.id}`); + (0, logger_1.logDebugInfo)(`Project Title: ${projectData.title}`); + (0, logger_1.logDebugInfo)(`Project URL: ${projectData.url}`); + return new project_detail_1.ProjectDetail({ + id: projectData.id, + title: projectData.title, + url: projectData.url, + type: ownerQueryField, + owner: github.context.repo.owner, + number: projectNumber, + }); + } + catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + (0, logger_1.logError)(`Error in getProjectDetail: ${errorMessage}`); + throw error; + } + }; + this.getContentId = async (project, owner, repo, issueOrPullRequestNumber, token) => { + const octokit = github.getOctokit(token); + // Search for the issue or pull request ID in the repository + const issueOrPrQuery = ` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + issueOrPullRequest: issueOrPullRequest(number: $number) { + ... on Issue { + id + } + ... on PullRequest { + id + } + } } - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - } - } else { WritableStream.prototype.emit.apply(this, arguments) } -} - -Dicer.prototype._write = function (data, encoding, cb) { - // ignore unexpected data (e.g. extra trailer data after finished) - if (!this._hparser && !this._bparser) { return cb() } - - if (this._headerFirst && this._isPreamble) { - if (!this._part) { - this._part = new PartStream(this._partOpts) - if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + }`; + const issueOrPrResult = await octokit.graphql(issueOrPrQuery, { + owner, + repo, + number: issueOrPullRequestNumber + }); + if (!issueOrPrResult.repository.issueOrPullRequest) { + console.error(`Issue or PR #${issueOrPullRequestNumber} not found.`); + return undefined; + } + const contentId = issueOrPrResult.repository.issueOrPullRequest.id; + // Search for the item ID in the project with pagination + let cursor = null; + let projectItemId = undefined; + do { + const projectQuery = ` + query($projectId: ID!, $cursor: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $cursor) { + pageInfo { + hasNextPage + endCursor + } + nodes { + id + content { + ... on Issue { + id + } + ... on PullRequest { + id + } + } + } + } + } + } + }`; + const projectResult = await octokit.graphql(projectQuery, { + projectId: project.id, + cursor + }); + const items = projectResult.node.items.nodes; + const foundItem = items.find((item) => item.content?.id === contentId); + if (foundItem) { + projectItemId = foundItem.id; + break; + } + cursor = projectResult.node.items.pageInfo.hasNextPage + ? projectResult.node.items.pageInfo.endCursor + : null; + } while (cursor); + return projectItemId; + }; + this.isContentLinked = async (project, contentId, token) => { + const octokit = github.getOctokit(token); + let hasNextPage = true; + let endCursor = null; + let allItems = []; + while (hasNextPage) { + const query = ` + query($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + items(first: 100, after: $after) { + nodes { + content { + ... on PullRequest { + id + } + ... on Issue { + id + } + } + } + pageInfo { + hasNextPage + endCursor + } + } + } + } + } + `; + // logDebugInfo(`Query: ${query}`); + // logDebugInfo(`Project ID: ${project.id}`); + // logDebugInfo(`Content ID: ${contentId}`); + // logDebugInfo(`After cursor: ${endCursor}`); + const result = await octokit.graphql(query, { + projectId: project.id, + after: endCursor, + }); + // logDebugInfo(`Result: ${JSON.stringify(result, null, 2)}`); + const items = result.node.items.nodes; + allItems = allItems.concat(items); + hasNextPage = result.node.items.pageInfo.hasNextPage; + endCursor = result.node.items.pageInfo.endCursor; + } + return allItems.some((item) => item.content && item.content.id === contentId); + }; + this.linkContentId = async (project, contentId, token) => { + const alreadyLinked = await this.isContentLinked(project, contentId, token); + if (alreadyLinked) { + (0, logger_1.logDebugInfo)(`Content ${contentId} is already linked to project ${project.id}.`); + return false; + } + const octokit = github.getOctokit(token); + const linkMutation = ` + mutation($projectId: ID!, $contentId: ID!) { + addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) { + item { + id + } + } + } + `; + const linkResult = await octokit.graphql(linkMutation, { + projectId: project.id, + contentId: contentId, + }); + (0, logger_1.logDebugInfo)(`Linked ${contentId} with id ${linkResult.addProjectV2ItemById.item.id} to project ${project.id}`); + return true; + }; + this.setSingleSelectFieldValue = async (project, owner, repo, issueOrPullRequestNumber, fieldName, fieldValue, token) => { + const contentId = await this.getContentId(project, owner, repo, issueOrPullRequestNumber, token); + if (!contentId) { + (0, logger_1.logError)(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); + throw new Error(`Content ID not found for issue or pull request #${issueOrPullRequestNumber}.`); + } + (0, logger_1.logDebugInfo)(`Content ID: ${contentId}`); + const octokit = github.getOctokit(token); + // Get the field ID and current value + const fieldQuery = ` + query($projectId: ID!, $after: String) { + node(id: $projectId) { + ... on ProjectV2 { + fields(first: 20) { + nodes { + ... on ProjectV2SingleSelectField { + id + name + options { + id + name + } + } + } + } + items(first: 100, after: $after) { + pageInfo { + hasNextPage + endCursor + } + nodes { + id + fieldValues(first: 20) { + nodes { + ... on ProjectV2ItemFieldSingleSelectValue { + field { + ... on ProjectV2SingleSelectField { + name + } + } + optionId + } + } + } + } + } + } + } + }`; + let hasNextPage = true; + let endCursor = null; + let currentItem = null; + // Get the field and option information from the first page + const initialFieldResult = await octokit.graphql(fieldQuery, { + projectId: project.id, + after: null + }); + const targetField = initialFieldResult.node.fields.nodes.find((f) => f.name === fieldName); + (0, logger_1.logDebugInfo)(`Target field: ${JSON.stringify(targetField, null, 2)}`); + if (!targetField) { + (0, logger_1.logError)(`Field '${fieldName}' not found or is not a single-select field.`); + throw new Error(`Field '${fieldName}' not found or is not a single-select field.`); + } + const targetOption = targetField.options.find((opt) => opt.name === fieldValue); + (0, logger_1.logDebugInfo)(`Target option: ${JSON.stringify(targetOption, null, 2)}`); + if (!targetOption) { + (0, logger_1.logError)(`Option '${fieldValue}' not found for field '${fieldName}'.`); + throw new Error(`Option '${fieldValue}' not found for field '${fieldName}'.`); + } + // Now search for the item through all pages + while (hasNextPage) { + const fieldResult = await octokit.graphql(fieldQuery, { + projectId: project.id, + after: endCursor + }); + // logDebugInfo(`Field result: ${JSON.stringify(fieldResult, null, 2)}`); + // Check current value in current page + currentItem = fieldResult.node.items.nodes.find((item) => item.id === contentId); + if (currentItem) { + // logDebugInfo(`Current item: ${JSON.stringify(currentItem, null, 2)}`); + const currentFieldValue = currentItem.fieldValues.nodes.find((value) => value.field?.name === fieldName); + if (currentFieldValue && currentFieldValue.optionId === targetOption.id) { + (0, logger_1.logDebugInfo)(`Field '${fieldName}' is already set to '${fieldValue}'. No update needed.`); + return false; + } + break; // Found the item, no need to continue pagination + } + hasNextPage = fieldResult.node.items.pageInfo.hasNextPage; + endCursor = fieldResult.node.items.pageInfo.endCursor; + } + (0, logger_1.logDebugInfo)(`Target field ID: ${targetField.id}`); + (0, logger_1.logDebugInfo)(`Target option ID: ${targetOption.id}`); + const mutation = ` + mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { + updateProjectV2ItemFieldValue( + input: { + projectId: $projectId, + itemId: $itemId, + fieldId: $fieldId, + value: { singleSelectOptionId: $optionId } + } + ) { + projectV2Item { + id + } + } + }`; + const mutationResult = await octokit.graphql(mutation, { + projectId: project.id, + itemId: contentId, + fieldId: targetField.id, + optionId: targetOption.id + }); + return !!mutationResult.updateProjectV2ItemFieldValue.projectV2Item; + }; + this.setTaskPriority = async (project, owner, repo, issueOrPullRequestNumber, priorityLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.priorityLabel, priorityLabel, token); + this.setTaskSize = async (project, owner, repo, issueOrPullRequestNumber, sizeLabel, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.sizeLabel, sizeLabel, token); + this.moveIssueToColumn = async (project, owner, repo, issueOrPullRequestNumber, columnName, token) => this.setSingleSelectFieldValue(project, owner, repo, issueOrPullRequestNumber, this.statusLabel, columnName, token); + this.getRandomMembers = async (organization, membersToAdd, currentMembers, token) => { + if (membersToAdd === 0) { + return []; + } + const octokit = github.getOctokit(token); + try { + const { data: teams } = await octokit.rest.teams.list({ + org: organization, + }); + if (teams.length === 0) { + (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); + return []; + } + const membersSet = new Set(); + for (const team of teams) { + (0, logger_1.logDebugInfo)(`Checking team: ${team.slug}`); + const { data: members } = await octokit.rest.teams.listMembersInOrg({ + org: organization, + team_slug: team.slug, + }); + (0, logger_1.logDebugInfo)(`Members: ${members.length}`); + members.forEach((member) => membersSet.add(member.login)); + } + const allMembers = Array.from(membersSet); + const availableMembers = allMembers.filter((member) => !currentMembers.includes(member)); + if (availableMembers.length === 0) { + (0, logger_1.logDebugInfo)(`No available members to assign for organization ${organization}.`); + return []; + } + if (membersToAdd >= availableMembers.length) { + (0, logger_1.logDebugInfo)(`Requested size (${membersToAdd}) exceeds available members (${availableMembers.length}). Returning all available members.`); + return availableMembers; + } + const shuffled = availableMembers.sort(() => Math.random() - 0.5); + return shuffled.slice(0, membersToAdd); + } + catch (error) { + (0, logger_1.logError)(`Error getting random members: ${error}.`); + } + return []; + }; + this.getAllMembers = async (organization, token) => { + const octokit = github.getOctokit(token); + try { + const { data: teams } = await octokit.rest.teams.list({ + org: organization, + }); + if (teams.length === 0) { + (0, logger_1.logDebugInfo)(`${organization} doesn't have any team.`); + return []; + } + const membersSet = new Set(); + for (const team of teams) { + const { data: members } = await octokit.rest.teams.listMembersInOrg({ + org: organization, + team_slug: team.slug, + }); + members.forEach((member) => membersSet.add(member.login)); + } + return Array.from(membersSet); + } + catch (error) { + (0, logger_1.logError)(`Error getting all members: ${error}.`); + } + return []; + }; + this.getUserFromToken = async (token) => { + const octokit = github.getOctokit(token); + const { data: user } = await octokit.rest.users.getAuthenticated(); + return user.login; + }; + this.findTag = async (owner, repo, tag, token) => { + const octokit = github.getOctokit(token); + try { + const { data: foundTag } = await octokit.rest.git.getRef({ + owner, + repo, + ref: `tags/${tag}`, + }); + return foundTag; + } + catch (err) { + return undefined; + } + }; + this.getTagSHA = async (owner, repo, tag, token) => { + const foundTag = await this.findTag(owner, repo, tag, token); + if (!foundTag) { + (0, logger_1.logError)(`The '${tag}' tag does not exist in the remote repository`); + return undefined; + } + return foundTag.object.sha; + }; + this.updateTag = async (owner, repo, sourceTag, targetTag, token) => { + const sourceTagSHA = await this.getTagSHA(owner, repo, sourceTag, token); + if (!sourceTagSHA) { + (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); + return; + } + const foundTargetTag = await this.findTag(owner, repo, targetTag, token); + const refName = `tags/${targetTag}`; + const octokit = github.getOctokit(token); + if (foundTargetTag) { + (0, logger_1.logDebugInfo)(`Updating the '${targetTag}' tag to point to the '${sourceTag}' tag`); + await octokit.rest.git.updateRef({ + owner, + repo, + ref: refName, + sha: sourceTagSHA, + force: true, + }); + } + else { + (0, logger_1.logDebugInfo)(`Creating the '${targetTag}' tag from the '${sourceTag}' tag`); + await octokit.rest.git.createRef({ + owner, + repo, + ref: `refs/${refName}`, + sha: sourceTagSHA, + }); + } + }; + this.updateRelease = async (owner, repo, sourceTag, targetTag, token) => { + // Get the release associated with sourceTag + const octokit = github.getOctokit(token); + const { data: sourceRelease } = await octokit.rest.repos.getReleaseByTag({ + owner, + repo, + tag: sourceTag, + }); + if (!sourceRelease.name || !sourceRelease.body) { + (0, logger_1.logError)(`The '${sourceTag}' tag does not exist in the remote repository`); + return undefined; + } + (0, logger_1.logDebugInfo)(`Found release for sourceTag '${sourceTag}': ${sourceRelease.name}`); + // Check if there is a release for targetTag + const { data: releases } = await octokit.rest.repos.listReleases({ + owner, + repo, + }); + const targetRelease = releases.find(r => r.tag_name === targetTag); + let targetReleaseId; + if (targetRelease) { + (0, logger_1.logDebugInfo)(`Updating release for targetTag '${targetTag}'`); + // Update the target release with the content from the source release + await octokit.rest.repos.updateRelease({ + owner, + repo, + release_id: targetRelease.id, + name: sourceRelease.name, + body: sourceRelease.body, + draft: sourceRelease.draft, + prerelease: sourceRelease.prerelease, + }); + targetReleaseId = targetRelease.id; + } + else { + console.log(`Creating new release for targetTag '${targetTag}'`); + // Create a new release for targetTag if it doesn't exist + const { data: newRelease } = await octokit.rest.repos.createRelease({ + owner, + repo, + tag_name: targetTag, + name: sourceRelease.name, + body: sourceRelease.body, + draft: sourceRelease.draft, + prerelease: sourceRelease.prerelease, + }); + targetReleaseId = newRelease.id; + } + (0, logger_1.logInfo)(`Updated release for targetTag '${targetTag}'`); + return targetReleaseId.toString(); + }; + this.createRelease = async (owner, repo, version, title, changelog, token) => { + try { + const octokit = github.getOctokit(token); + const { data: release } = await octokit.rest.repos.createRelease({ + owner, + repo, + tag_name: `v${version}`, + name: `v${version} - ${title}`, + body: changelog, + draft: false, + prerelease: false, + }); + return release.html_url; + } + catch (error) { + (0, logger_1.logError)(`Error creating release: ${error}`); + return undefined; + } + }; + this.createTag = async (owner, repo, branch, tag, token) => { + const octokit = github.getOctokit(token); + try { + // Check if tag already exists + const existingTag = await this.findTag(owner, repo, tag, token); + if (existingTag) { + (0, logger_1.logInfo)(`Tag '${tag}' already exists in repository ${owner}/${repo}`); + return existingTag.object.sha; + } + // Get the latest commit SHA from the specified branch + const { data: ref } = await octokit.rest.git.getRef({ + owner, + repo, + ref: `heads/${branch}`, + }); + // Create the tag + await octokit.rest.git.createRef({ + owner, + repo, + ref: `refs/tags/${tag}`, + sha: ref.object.sha, + }); + (0, logger_1.logInfo)(`Created tag '${tag}' in repository ${owner}/${repo} from branch '${branch}'`); + return ref.object.sha; + } + catch (error) { + (0, logger_1.logError)(`Error creating tag '${tag}': ${JSON.stringify(error, null, 2)}`); + return undefined; + } + }; } - const r = this._hparser.push(data) - if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } - } - - // allows for "easier" testing - if (this._firstWrite) { - this._bparser.push(B_CRLF) - this._firstWrite = false - } - - this._bparser.push(data) - - if (this._pause) { this._cb = cb } else { cb() } -} - -Dicer.prototype.reset = function () { - this._part = undefined - this._bparser = undefined - this._hparser = undefined -} - -Dicer.prototype.setBoundary = function (boundary) { - const self = this - this._bparser = new StreamSearch('\r\n--' + boundary) - this._bparser.on('info', function (isMatch, data, start, end) { - self._oninfo(isMatch, data, start, end) - }) } +exports.ProjectRepository = ProjectRepository; -Dicer.prototype._ignore = function () { - if (this._part && !this._ignoreData) { - this._ignoreData = true - this._part.on('error', EMPTY_FN) - // we must perform some kind of read on the stream even though we are - // ignoring the data, otherwise node's Readable stream will not emit 'end' - // after pushing null to the stream - this._part.resume() - } -} -Dicer.prototype._oninfo = function (isMatch, data, start, end) { - let buf; const self = this; let i = 0; let r; let shouldWriteMore = true +/***/ }), - if (!this._part && this._justMatched && data) { - while (this._dashes < 2 && (start + i) < end) { - if (data[start + i] === DASH) { - ++i - ++this._dashes - } else { - if (this._dashes) { buf = B_ONEDASH } - this._dashes = 0 - break - } - } - if (this._dashes === 2) { - if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } - this.reset() - this._finished = true - // no more parts will be added - if (self._parts === 0) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } - } - if (this._dashes) { return } - } - if (this._justMatched) { this._justMatched = false } - if (!this._part) { - this._part = new PartStream(this._partOpts) - this._part._read = function (n) { - self._unpause() - } - if (this._isPreamble && this.listenerCount('preamble') !== 0) { - this.emit('preamble', this._part) - } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { - this.emit('part', this._part) - } else { - this._ignore() - } - if (!this._isPreamble) { this._inHeader = true } - } - if (data && start < end && !this._ignoreData) { - if (this._isPreamble || !this._inHeader) { - if (buf) { shouldWriteMore = this._part.push(buf) } - shouldWriteMore = this._part.push(data.slice(start, end)) - if (!shouldWriteMore) { this._pause = true } - } else if (!this._isPreamble && this._inHeader) { - if (buf) { this._hparser.push(buf) } - r = this._hparser.push(data.slice(start, end)) - if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } +/***/ 634: +/***/ (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]; } }; } - } - if (isMatch) { - this._hparser.reset() - if (this._isPreamble) { this._isPreamble = false } else { - if (start !== end) { - ++this._parts - this._part.on('end', function () { - if (--self._parts === 0) { - if (self._finished) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } else { - self._unpause() + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullRequestRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const logger_1 = __nccwpck_require__(8836); +class PullRequestRepository { + constructor() { + this.isLinked = async (pullRequestUrl) => { + const htmlContent = await fetch(pullRequestUrl).then(res => res.text()); + return !htmlContent.includes('has_github_issues=false'); + }; + this.updateBaseBranch = async (owner, repository, pullRequestNumber, branch, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.pulls.update({ + owner: owner, + repo: repository, + pull_number: pullRequestNumber, + base: branch, + }); + (0, logger_1.logDebugInfo)(`Changed base branch to ${branch}`); + }; + this.updateDescription = async (owner, repository, pullRequestNumber, description, token) => { + const octokit = github.getOctokit(token); + await octokit.rest.pulls.update({ + owner: owner, + repo: repository, + pull_number: pullRequestNumber, + body: description, + }); + (0, logger_1.logDebugInfo)(`Updated PR #${pullRequestNumber} description with: ${description}`); + }; + this.getCurrentReviewers = async (owner, repository, pullNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data } = await octokit.rest.pulls.listRequestedReviewers({ + owner, + repo: repository, + pull_number: pullNumber, + }); + return data.users.map((user) => user.login); } - } - }) - } + catch (error) { + (0, logger_1.logError)(`Error getting reviewers of PR: ${error}.`); + return []; + } + }; + this.addReviewersToPullRequest = async (owner, repository, pullNumber, reviewers, token) => { + const octokit = github.getOctokit(token); + try { + if (reviewers.length === 0) { + (0, logger_1.logDebugInfo)(`No reviewers provided for addition. Skipping operation.`); + return []; + } + const { data } = await octokit.rest.pulls.requestReviewers({ + owner, + repo: repository, + pull_number: pullNumber, + reviewers: reviewers, + }); + const addedReviewers = data.requested_reviewers || []; + return addedReviewers.map((reviewer) => reviewer.login); + } + catch (error) { + (0, logger_1.logError)(`Error adding reviewers to pull request: ${error}.`); + return []; + } + }; + this.getChangedFiles = async (owner, repository, pullNumber, token) => { + const octokit = github.getOctokit(token); + try { + const { data } = await octokit.rest.pulls.listFiles({ + owner, + repo: repository, + pull_number: pullNumber, + }); + return data.map((file) => ({ + filename: file.filename, + status: file.status + })); + } + catch (error) { + (0, logger_1.logError)(`Error getting changed files from pull request: ${error}.`); + return []; + } + }; + this.getPullRequestChanges = async (owner, repository, pullNumber, token) => { + const octokit = github.getOctokit(token); + const allFiles = []; + try { + for await (const response of octokit.paginate.iterator(octokit.rest.pulls.listFiles, { + owner, + repo: repository, + pull_number: pullNumber, + per_page: 100 + })) { + const filesData = response.data; + allFiles.push(...filesData.map((file) => ({ + filename: file.filename, + status: file.status, + additions: file.additions, + deletions: file.deletions, + patch: file.patch || '' + }))); + } + return allFiles; + } + catch (error) { + (0, logger_1.logError)(`Error getting pull request changes: ${error}.`); + return []; + } + }; } - this._part.push(null) - this._part = undefined - this._ignoreData = false - this._justMatched = true - this._dashes = 0 - } -} - -Dicer.prototype._unpause = function () { - if (!this._pause) { return } - - this._pause = false - if (this._cb) { - const cb = this._cb - this._cb = undefined - cb() - } } - -module.exports = Dicer +exports.PullRequestRepository = PullRequestRepository; /***/ }), -/***/ 92032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9829: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SupabaseRepository = void 0; +const supabase_js_1 = __nccwpck_require__(1206); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class SupabaseRepository { + constructor(config) { + this.AI_FILE_CACHE_TABLE = 'ai_file_cache'; + this.MAX_BATCH_SIZE = 500; + this.DEFAULT_TIMEOUT = 30000; // 30 seconds + /** + * Set or update AI file cache entry + * If SHA hasn't changed, this will update the entry + */ + this.setAIFileCache = async (owner, repository, branch, fileInfo) => { + try { + const { error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .upsert({ + owner, + repository, + branch, + file_name: fileInfo.file_name, + path: fileInfo.path, + sha: fileInfo.sha, + description: fileInfo.description, + consumes: fileInfo.consumes, + consumed_by: fileInfo.consumed_by, + last_updated: new Date().toISOString() + }, { + onConflict: 'owner,repository,branch,path' + }); + if (error) { + (0, logger_1.logError)(`Error setting AI file cache for ${fileInfo.path}: ${JSON.stringify(error, null, 2)}`); + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error setting AI file cache ${fileInfo.path}: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Get AI file cache entry by path + */ + this.getAIFileCache = async (owner, repository, branch, filePath) => { + try { + const { data, error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .select('*') + .eq('owner', owner) + .eq('repository', repository) + .eq('branch', branch) + .eq('path', filePath) + .single(); + if (error) { + if (error.code === 'PGRST116') { + // No rows returned + return null; + } + (0, logger_1.logError)(`Error getting AI file cache: ${JSON.stringify(error, null, 2)}`); + return null; + } + return data; + } + catch (error) { + (0, logger_1.logError)(`Error getting AI file cache: ${JSON.stringify(error, null, 2)}`); + return null; + } + }; + /** + * Get all AI file cache entries for a branch + */ + this.getAIFileCachesByBranch = async (owner, repository, branch) => { + try { + const { data, error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .select('*') + .eq('owner', owner) + .eq('repository', repository) + .eq('branch', branch) + .order('path'); + if (error) { + (0, logger_1.logError)(`Error getting AI file caches by branch: ${JSON.stringify(error, null, 2)}`); + return []; + } + if (!data) { + return []; + } + return data; + } + catch (error) { + (0, logger_1.logError)(`Error getting AI file caches by branch: ${JSON.stringify(error, null, 2)}`); + return []; + } + }; + /** + * Remove AI file cache entry by path + */ + this.removeAIFileCacheByPath = async (owner, repository, branch, filePath) => { + try { + const { error } = await this.supabase + .from(this.AI_FILE_CACHE_TABLE) + .delete() + .eq('owner', owner) + .eq('repository', repository) + .eq('branch', branch) + .eq('path', filePath); + if (error) { + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error removing AI file cache by path: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Duplicate AI file cache entries from one branch to another + */ + this.duplicateAIFileCacheByBranch = async (owner, repository, sourceBranch, targetBranch) => { + try { + const { error } = await this.supabase + .rpc('duplicate_ai_file_cache_by_branch', { + owner_param: owner, + repository_param: repository, + source_branch_param: sourceBranch, + target_branch_param: targetBranch + }); + if (error) { + (0, logger_1.logError)(`Error duplicating AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error duplicating AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Remove all AI file cache entries for a branch + */ + this.removeAIFileCacheByBranch = async (owner, repository, branch) => { + try { + const { error } = await this.supabase + .rpc('delete_ai_file_cache_by_branch', { + owner_param: owner, + repository_param: repository, + branch_param: branch + }); + if (error) { + (0, logger_1.logError)(`Error removing AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + } + catch (error) { + (0, logger_1.logError)(`Error removing AI file cache by branch: ${JSON.stringify(error, null, 2)}`); + throw error; + } + }; + /** + * Get SHA by path (for checking if file is cached) + */ + this.getShasumByPath = async (owner, repository, branch, path) => { + try { + const cached = await this.getAIFileCache(owner, repository, branch, path); + return cached?.sha; + } + catch (error) { + (0, logger_1.logError)(`Error getting SHA by path: ${JSON.stringify(error, null, 2)}`); + return undefined; + } + }; + /** + * Get distinct paths for a branch + */ + this.getDistinctPaths = async (owner, repository, branch) => { + try { + const cachedFiles = await this.getAIFileCachesByBranch(owner, repository, branch); + return cachedFiles.map(file => file.path); + } + catch (error) { + (0, logger_1.logError)(`Error getting distinct paths: ${JSON.stringify(error, null, 2)}`); + return []; + } + }; + const customFetch = async (input, init) => { + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), this.DEFAULT_TIMEOUT); + try { + const response = await fetch(input, { + ...init, + signal: controller.signal + }); + return response; + } + finally { + clearTimeout(timeoutId); + } + }; + this.supabase = (0, supabase_js_1.createClient)(config.getUrl(), config.getKey(), { + global: { + headers: { + 'X-Client-Info': constants_1.COMMAND + }, + fetch: customFetch + }, + db: { + schema: 'public' + }, + auth: { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true + } + }); + } +} +exports.SupabaseRepository = SupabaseRepository; -const EventEmitter = (__nccwpck_require__(15673).EventEmitter) -const inherits = (__nccwpck_require__(47261).inherits) -const getLimit = __nccwpck_require__(21467) - -const StreamSearch = __nccwpck_require__(51142) -const B_DCRLF = Buffer.from('\r\n\r\n') -const RE_CRLF = /\r\n/g -const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex +/***/ }), -function HeaderParser (cfg) { - EventEmitter.call(this) +/***/ 779: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - cfg = cfg || {} - const self = this - this.nread = 0 - this.maxed = false - this.npairs = 0 - this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) - this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) - this.buffer = '' - this.header = {} - this.finished = false - this.ss = new StreamSearch(B_DCRLF) - this.ss.on('info', function (isMatch, data, start, end) { - if (data && !self.maxed) { - if (self.nread + end - start >= self.maxHeaderSize) { - end = self.maxHeaderSize - self.nread + start - self.nread = self.maxHeaderSize - self.maxed = true - } else { self.nread += (end - start) } +"use strict"; - self.buffer += data.toString('binary', start, end) +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.WorkflowRepository = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const workflow_run_1 = __nccwpck_require__(6845); +const constants_1 = __nccwpck_require__(8593); +class WorkflowRepository { + constructor() { + this.getWorkflows = async (params) => { + const octokit = github.getOctokit(params.tokens.token); + const workflows = await octokit.rest.actions.listWorkflowRunsForRepo({ + owner: params.owner, + repo: params.repo, + }); + return workflows.data.workflow_runs.map(w => new workflow_run_1.WorkflowRun({ + id: w.id, + name: w.name ?? 'unknown', + head_branch: w.head_branch, + head_sha: w.head_sha, + run_number: w.run_number, + event: w.event, + status: w.status ?? 'unknown', + conclusion: w.conclusion ?? null, + created_at: w.created_at, + updated_at: w.updated_at, + url: w.url, + html_url: w.html_url, + })); + }; + this.getActivePreviousRuns = async (params) => { + const workflows = await this.getWorkflows(params); + const runId = parseInt(process.env.GITHUB_RUN_ID, 10); + const workflowName = process.env.GITHUB_WORKFLOW; + return workflows.filter((run) => { + const isSameWorkflow = run.name === workflowName; + const isPrevious = run.id < runId; + const isActive = constants_1.WORKFLOW_ACTIVE_STATUSES.includes(run.status); + return isSameWorkflow && isPrevious && isActive; + }); + }; } - if (isMatch) { self._finish() } - }) -} -inherits(HeaderParser, EventEmitter) - -HeaderParser.prototype.push = function (data) { - const r = this.ss.push(data) - if (this.finished) { return r } } +exports.WorkflowRepository = WorkflowRepository; -HeaderParser.prototype.reset = function () { - this.finished = false - this.buffer = '' - this.header = {} - this.ss.reset() -} -HeaderParser.prototype._finish = function () { - if (this.buffer) { this._parseHeader() } - this.ss.matches = this.ss.maxMatches - const header = this.header - this.header = {} - this.buffer = '' - this.finished = true - this.nread = this.npairs = 0 - this.maxed = false - this.emit('header', header) -} +/***/ }), -HeaderParser.prototype._parseHeader = function () { - if (this.npairs === this.maxHeaderPairs) { return } +/***/ 6365: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const lines = this.buffer.split(RE_CRLF) - const len = lines.length - let m, h +"use strict"; - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (lines[i].length === 0) { continue } - if (lines[i][0] === '\t' || lines[i][0] === ' ') { - // folded header content - // RFC2822 says to just remove the CRLF and not the whitespace following - // it, so we follow the RFC and include the leading whitespace ... - if (h) { - this.header[h][this.header[h].length - 1] += lines[i] - continue - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ContentInterface = void 0; +const logger_1 = __nccwpck_require__(8836); +class ContentInterface { + constructor() { + this.getContent = (description) => { + try { + if (description === undefined) { + return undefined; + } + if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { + return undefined; + } + return description.split(this.startPattern)[1].split(this.endPattern)[0]; + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; + this._addContent = (description, content) => { + if (description.indexOf(this.startPattern) === -1 && description.indexOf(this.endPattern) === -1) { + const newContent = `${this.startPattern}\n${content}\n${this.endPattern}`; + return `${description}\n\n${newContent}`; + } + else { + return undefined; + } + }; + this._updateContent = (description, content) => { + if (description.indexOf(this.startPattern) === -1 || description.indexOf(this.endPattern) === -1) { + (0, logger_1.logError)(`The content has a problem with open-close tags: ${this.startPattern} / ${this.endPattern}`); + return undefined; + } + const start = description.split(this.startPattern)[0]; + const mid = `${this.startPattern}\n${content}\n${this.endPattern}`; + const end = description.split(this.endPattern)[1]; + return `${start}${mid}${end}`; + }; + this.updateContent = (description, content) => { + try { + if (description === undefined || content === undefined) { + return undefined; + } + const addedContent = this._addContent(description, content); + if (addedContent !== undefined) { + return addedContent; + } + return this._updateContent(description, content); + } + catch (error) { + (0, logger_1.logError)(`Error updating issue description: ${error}`); + return undefined; + } + }; } - - const posColon = lines[i].indexOf(':') - if ( - posColon === -1 || - posColon === 0 - ) { - return + get _id() { + return `git-board-flow-${this.id}`; + } + get startPattern() { + if (this.visibleContent) { + return ``; + } + return ``; + } + return `${this._id}-end -->`; } - m = RE_HDR.exec(lines[i]) - h = m[1].toLowerCase() - this.header[h] = this.header[h] || [] - this.header[h].push((m[2] || '')) - if (++this.npairs === this.maxHeaderPairs) { break } - } } - -module.exports = HeaderParser +exports.ContentInterface = ContentInterface; /***/ }), -/***/ 81620: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9913: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const inherits = (__nccwpck_require__(47261).inherits) -const ReadableStream = (__nccwpck_require__(84492).Readable) - -function PartStream (opts) { - ReadableStream.call(this, opts) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueContentInterface = void 0; +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +const content_interface_1 = __nccwpck_require__(6365); +class IssueContentInterface extends content_interface_1.ContentInterface { + constructor() { + super(...arguments); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.internalGetter = async (execution) => { + try { + let number = -1; + if (execution.isSingleAction) { + number = execution.issueNumber; + } + else if (execution.isIssue) { + number = execution.issue.number; + } + else if (execution.isPullRequest) { + number = execution.pullRequest.number; + } + else if (execution.isPush) { + number = execution.issueNumber; + } + else { + return undefined; + } + const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); + return this.getContent(description); + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; + this.internalUpdate = async (execution, content) => { + try { + let number = -1; + if (execution.isSingleAction) { + if (execution.isIssue) { + number = execution.issue.number; + } + else if (execution.isPullRequest) { + number = execution.pullRequest.number; + } + else if (execution.isPush) { + number = execution.issueNumber; + } + else { + number = execution.singleAction.issue; + } + } + else if (execution.isIssue) { + number = execution.issue.number; + } + else if (execution.isPullRequest) { + number = execution.pullRequest.number; + } + else if (execution.isPush) { + number = execution.issueNumber; + } + else { + return undefined; + } + const description = await this.issueRepository.getDescription(execution.owner, execution.repo, number, execution.tokens.token); + const updated = this.updateContent(description, content); + if (updated === undefined) { + return undefined; + } + await this.issueRepository.updateDescription(execution.owner, execution.repo, number, updated, execution.tokens.token); + return updated; + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; + } } -inherits(PartStream, ReadableStream) - -PartStream.prototype._read = function (n) {} - -module.exports = PartStream +exports.IssueContentInterface = IssueContentInterface; /***/ }), -/***/ 51142: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 4509: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -/** - * Copyright Brian White. All rights reserved. - * - * @see https://github.com/mscdex/streamsearch - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - * - * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation - * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool - */ -const EventEmitter = (__nccwpck_require__(15673).EventEmitter) -const inherits = (__nccwpck_require__(47261).inherits) - -function SBMH (needle) { - if (typeof needle === 'string') { - needle = Buffer.from(needle) - } - - if (!Buffer.isBuffer(needle)) { - throw new TypeError('The needle has to be a String or a Buffer.') - } - - const needleLength = needle.length - - if (needleLength === 0) { - throw new Error('The needle cannot be an empty String/Buffer.') - } - - if (needleLength > 256) { - throw new Error('The needle cannot have a length bigger than 256.') - } - - this.maxMatches = Infinity - this.matches = 0 - - this._occ = new Array(256) - .fill(needleLength) // Initialize occurrence table. - this._lookbehind_size = 0 - this._needle = needle - this._bufpos = 0 - - this._lookbehind = Buffer.alloc(needleLength) - - // Populate occurrence table with analysis of the needle, - // ignoring last letter. - for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var - this._occ[needle[i]] = needleLength - 1 - i - } -} -inherits(SBMH, EventEmitter) - -SBMH.prototype.reset = function () { - this._lookbehind_size = 0 - this.matches = 0 - this._bufpos = 0 -} - -SBMH.prototype.push = function (chunk, pos) { - if (!Buffer.isBuffer(chunk)) { - chunk = Buffer.from(chunk, 'binary') - } - const chlen = chunk.length - this._bufpos = pos || 0 - let r - while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } - return r -} - -SBMH.prototype._sbmh_feed = function (data) { - const len = data.length - const needle = this._needle - const needleLength = needle.length - const lastNeedleChar = needle[needleLength - 1] - - // Positive: points to a position in `data` - // pos == 3 points to data[3] - // Negative: points to a position in the lookbehind buffer - // pos == -2 points to lookbehind[lookbehind_size - 2] - let pos = -this._lookbehind_size - let ch - - if (pos < 0) { - // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool - // search with character lookup code that considers both the - // lookbehind buffer and the current round's haystack data. - // - // Loop until - // there is a match. - // or until - // we've moved past the position that requires the - // lookbehind buffer. In this case we switch to the - // optimized loop. - // or until - // the character to look at lies outside the haystack. - while (pos < 0 && pos <= len - needleLength) { - ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - - if ( - ch === lastNeedleChar && - this._sbmh_memcmp(data, pos, needleLength - 1) - ) { - this._lookbehind_size = 0 - ++this.matches - this.emit('info', true) - - return (this._bufpos = pos + needleLength) - } - pos += this._occ[ch] +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ConfigurationHandler = void 0; +const config_1 = __nccwpck_require__(1106); +const logger_1 = __nccwpck_require__(8836); +const issue_content_interface_1 = __nccwpck_require__(9913); +class ConfigurationHandler extends issue_content_interface_1.IssueContentInterface { + constructor() { + super(...arguments); + this.update = async (execution) => { + try { + return await this.internalUpdate(execution, JSON.stringify(execution.currentConfiguration, null, 4)); + } + catch (error) { + (0, logger_1.logError)(`Error updating issue description: ${error}`); + return undefined; + } + }; + this.get = async (execution) => { + try { + const config = await this.internalGetter(execution); + if (config === undefined) { + return undefined; + } + const branchConfig = JSON.parse(config); + return new config_1.Config(branchConfig); + } + catch (error) { + (0, logger_1.logError)(`Error reading issue configuration: ${error}`); + throw error; + } + }; } - - // No match. - - if (pos < 0) { - // There's too few data for Boyer-Moore-Horspool to run, - // so let's use a different algorithm to skip as much as - // we can. - // Forward pos until - // the trailing part of lookbehind + data - // looks like the beginning of the needle - // or until - // pos == 0 - while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + get id() { + return 'configuration'; } - - if (pos >= 0) { - // Discard lookbehind buffer. - this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) - this._lookbehind_size = 0 - } else { - // Cut off part of the lookbehind buffer that has - // been processed and append the entire haystack - // into it. - const bytesToCutOff = this._lookbehind_size + pos - if (bytesToCutOff > 0) { - // The cut off data is guaranteed not to contain the needle. - this.emit('info', false, this._lookbehind, 0, bytesToCutOff) - } - - this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, - this._lookbehind_size - bytesToCutOff) - this._lookbehind_size -= bytesToCutOff - - data.copy(this._lookbehind, this._lookbehind_size) - this._lookbehind_size += len - - this._bufpos = len - return len + get visibleContent() { + return false; } - } - - pos += (pos >= 0) * this._bufpos - - // Lookbehind buffer is now empty. We only need to check if the - // needle is in the haystack. - if (data.indexOf(needle, pos) !== -1) { - pos = data.indexOf(needle, pos) - ++this.matches - if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - - return (this._bufpos = pos + needleLength) - } else { - pos = len - needleLength - } +} +exports.ConfigurationHandler = ConfigurationHandler; - // There was no match. If there's trailing haystack data that we cannot - // match yet using the Boyer-Moore-Horspool algorithm (because the trailing - // data is less than the needle size) then match using a modified - // algorithm that starts matching from the beginning instead of the end. - // Whatever trailing data is left after running this algorithm is added to - // the lookbehind buffer. - while ( - pos < len && - ( - data[pos] !== needle[0] || - ( - (Buffer.compare( - data.subarray(pos, pos + len - pos), - needle.subarray(0, len - pos) - ) !== 0) - ) - ) - ) { - ++pos - } - if (pos < len) { - data.copy(this._lookbehind, 0, pos, pos + (len - pos)) - this._lookbehind_size = len - pos - } - // Everything until pos is guaranteed not to contain needle data. - if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } +/***/ }), - this._bufpos = len - return len -} +/***/ 2430: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -SBMH.prototype._sbmh_lookup_char = function (data, pos) { - return (pos < 0) - ? this._lookbehind[this._lookbehind_size + pos] - : data[pos] -} +"use strict"; -SBMH.prototype._sbmh_memcmp = function (data, pos, len) { - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } - } - return true +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CreateReleaseUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class CreateReleaseUseCase { + constructor() { + this.taskId = 'CreateReleaseUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + if (param.singleAction.version.length === 0) { + (0, logger_1.logError)(`Version is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` + ], + })); + return result; + } + else if (param.singleAction.title.length === 0) { + (0, logger_1.logError)(`Title is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_TITLE} is not set.` + ], + })); + } + else if (param.singleAction.changelog.length === 0) { + (0, logger_1.logError)(`Changelog is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_CHANGELOG} is not set.` + ], + })); + } + try { + const releaseUrl = await this.projectRepository.createRelease(param.owner, param.repo, param.singleAction.version, param.singleAction.title, param.singleAction.changelog, param.tokens.token); + if (releaseUrl) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`Created release \`${releaseUrl}\`.`], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Failed to create release.` + ], + })); + } + } + catch (error) { + (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Failed to create release.`], + errors: [ + JSON.stringify(error) + ], + })); + } + return result; + } } - -module.exports = SBMH +exports.CreateReleaseUseCase = CreateReleaseUseCase; /***/ }), -/***/ 50727: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5279: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const WritableStream = (__nccwpck_require__(84492).Writable) -const { inherits } = __nccwpck_require__(47261) -const Dicer = __nccwpck_require__(92960) - -const MultipartParser = __nccwpck_require__(32183) -const UrlencodedParser = __nccwpck_require__(78306) -const parseParams = __nccwpck_require__(31854) - -function Busboy (opts) { - if (!(this instanceof Busboy)) { return new Busboy(opts) } - - if (typeof opts !== 'object') { - throw new TypeError('Busboy expected an options-Object.') - } - if (typeof opts.headers !== 'object') { - throw new TypeError('Busboy expected an options-Object with headers-attribute.') - } - if (typeof opts.headers['content-type'] !== 'string') { - throw new TypeError('Missing Content-Type-header.') - } - - const { - headers, - ...streamOptions - } = opts - - this.opts = { - autoDestroy: false, - ...streamOptions - } - WritableStream.call(this, this.opts) - - this._done = false - this._parser = this.getParserByHeaders(headers) - this._finished = false -} -inherits(Busboy, WritableStream) - -Busboy.prototype.emit = function (ev) { - if (ev === 'finish') { - if (!this._done) { - this._parser?.end() - return - } else if (this._finished) { - return +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CreateTagUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class CreateTagUseCase { + constructor() { + this.taskId = 'CreateTagUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + if (param.singleAction.version.length === 0) { + (0, logger_1.logError)(`Version is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` + ], + })); + return result; + } + else if (param.currentConfiguration.releaseBranch === undefined) { + (0, logger_1.logError)(`Working branch not found in configuration.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Release branch not found in issue configuration.` + ], + })); + return result; + } + try { + const sha1Tag = await this.projectRepository.createTag(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.singleAction.version, param.tokens.token); + if (sha1Tag) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`Tag ${param.singleAction.version} is ready: ${sha1Tag}`], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Failed to create tag ${param.singleAction.version}.` + ], + })); + } + } + catch (error) { + (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Failed to create tag ${param.singleAction.version}.`], + errors: [ + JSON.stringify(error) + ], + })); + } + return result; } - this._finished = true - } - WritableStream.prototype.emit.apply(this, arguments) } +exports.CreateTagUseCase = CreateTagUseCase; -Busboy.prototype.getParserByHeaders = function (headers) { - const parsed = parseParams(headers['content-type']) - - const cfg = { - defCharset: this.opts.defCharset, - fileHwm: this.opts.fileHwm, - headers, - highWaterMark: this.opts.highWaterMark, - isPartAFile: this.opts.isPartAFile, - limits: this.opts.limits, - parsedConType: parsed, - preservePath: this.opts.preservePath - } - if (MultipartParser.detect.test(parsed[0])) { - return new MultipartParser(this, cfg) - } - if (UrlencodedParser.detect.test(parsed[0])) { - return new UrlencodedParser(this, cfg) - } - throw new Error('Unsupported Content-Type.') -} +/***/ }), -Busboy.prototype._write = function (chunk, encoding, cb) { - this._parser.write(chunk, cb) -} +/***/ 8293: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = Busboy -module.exports["default"] = Busboy -module.exports.Busboy = Busboy +"use strict"; -module.exports.Dicer = Dicer +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DeployedActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class DeployedActionUseCase { + constructor() { + this.taskId = 'DeployedActionUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.branchRepository = new branch_repository_1.BranchRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (!param.labels.isDeploy) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to set label \`${param.labels.deployed}\` but there was no \`${param.labels.deploy}\` label.`, + ], + })); + return result; + } + if (param.labels.isDeployed) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to set label \`${param.labels.deployed}\` but it was already set.`, + ], + })); + return result; + } + const labelNames = param.labels.currentIssueLabels.filter(name => name !== param.labels.deploy); + labelNames.push(param.labels.deployed); + await this.issueRepository.setLabels(param.owner, param.repo, param.singleAction.issue, labelNames, param.tokens.token); + (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.singleAction.issue}:`); + (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Label \`${param.labels.deployed}\` added after a success deploy.`, + ], + })); + if (param.currentConfiguration.releaseBranch) { + const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDefaultResult); + const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.releaseBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDevelopResult); + } + else if (param.currentConfiguration.hotfixBranch) { + const mergeToDefaultResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.currentConfiguration.hotfixBranch, param.branches.defaultBranch, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDefaultResult); + const mergeToDevelopResult = await this.branchRepository.mergeBranch(param.owner, param.repo, param.branches.defaultBranch, param.branches.development, param.pullRequest.mergeTimeout, param.tokens.token); + result.push(...mergeToDevelopResult); + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to assign members to issue.`], + error: error, + })); + } + return result; + } +} +exports.DeployedActionUseCase = DeployedActionUseCase; /***/ }), -/***/ 32183: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 9029: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PublishGithubActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const constants_1 = __nccwpck_require__(8593); +const logger_1 = __nccwpck_require__(8836); +class PublishGithubActionUseCase { + constructor() { + this.taskId = 'PublishGithubActionUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + if (param.singleAction.version.length === 0) { + (0, logger_1.logError)(`Version is not set.`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `${constants_1.INPUT_KEYS.SINGLE_ACTION_VERSION} is not set.` + ], + })); + return result; + } + const sourceTag = `v${param.singleAction.version}`; + const targetTag = sourceTag.split('.')[0]; + try { + await this.projectRepository.updateTag(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); + const releaseId = await this.projectRepository.updateRelease(param.owner, param.repo, sourceTag, targetTag, param.tokens.token); + if (releaseId) { + (0, logger_1.logInfo)(`Updated release \`${targetTag}\` from \`${sourceTag}\`: ${releaseId}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`Updated release \`${targetTag}\` from \`${sourceTag}\`.`], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Failed to update release \`${targetTag}\` from \`${sourceTag}\`.` + ], + })); + } + } + catch (error) { + (0, logger_1.logError)(`Error executing ${this.taskId}: ${error}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Failed to update release \`${targetTag}\` from \`${sourceTag}\`.`], + errors: [ + JSON.stringify(error) + ], + })); + } + return result; + } +} +exports.PublishGithubActionUseCase = PublishGithubActionUseCase; -// TODO: -// * support 1 nested multipart level -// (see second multipart example here: -// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) -// * support limits.fieldNameSize -// -- this will require modifications to utils.parseParams -const { Readable } = __nccwpck_require__(84492) -const { inherits } = __nccwpck_require__(47261) +/***/ }), -const Dicer = __nccwpck_require__(92960) +/***/ 7757: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const parseParams = __nccwpck_require__(31854) -const decodeText = __nccwpck_require__(84619) -const basename = __nccwpck_require__(48647) -const getLimit = __nccwpck_require__(21467) +"use strict"; -const RE_BOUNDARY = /^boundary$/i -const RE_FIELD = /^form-data$/i -const RE_CHARSET = /^charset$/i -const RE_FILENAME = /^filename$/i -const RE_NAME = /^name$/i +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.VectorActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const file_repository_1 = __nccwpck_require__(1503); +const supabase_repository_1 = __nccwpck_require__(9829); +const ai_repository_1 = __nccwpck_require__(8307); +const logger_1 = __nccwpck_require__(8836); +const file_import_analyzer_1 = __nccwpck_require__(5310); +const file_cache_manager_1 = __nccwpck_require__(1855); +const codebase_analyzer_1 = __nccwpck_require__(678); +const constants_1 = __nccwpck_require__(8593); +class VectorActionUseCase { + constructor() { + this.taskId = 'VectorActionUseCase'; + this.fileRepository = new file_repository_1.FileRepository(); + this.aiRepository = new ai_repository_1.AiRepository(); + this.fileImportAnalyzer = new file_import_analyzer_1.FileImportAnalyzer(); + this.fileCacheManager = new file_cache_manager_1.FileCacheManager(); + this.checkAICacheInSupabase = async (param, branch, repositoryFiles) => { + const results = []; + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + const remotePaths = await supabaseRepository.getDistinctPaths(param.owner, param.repo, branch); + // Get all local paths from repository files + const localPaths = new Set(Array.from(repositoryFiles.keys())); + // Find paths that exist in Supabase but not in the current branch + const pathsToRemove = remotePaths.filter(path => !localPaths.has(path)); + if (pathsToRemove.length > 0 && remotePaths.length > 0) { + (0, logger_1.logInfo)(`šŸ“¦ Found ${pathsToRemove.length} paths to remove from AI index as they no longer exist in the branch ${branch}.`); + for (const path of pathsToRemove) { + try { + await supabaseRepository.removeAIFileCacheByPath(param.owner, param.repo, branch, path); + (0, logger_1.logInfo)(`šŸ“¦ āœ… Removed AI cache for path: ${path}`); + } + catch (error) { + (0, logger_1.logError)(`šŸ“¦ āŒ Error removing AI cache for path ${path}: ${JSON.stringify(error, null, 2)}`); + } + } + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Removed ${pathsToRemove.length} paths from AI index as they no longer exist in \`${branch}\`.`, + ], + })); + } + else { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + return results; + }; + this.uploadAICacheToSupabase = async (param, branch, repositoryFiles) => { + const results = []; + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + const startTime = Date.now(); + const filePaths = Array.from(repositoryFiles.keys()); + // Step 1: Build relationship map once for all files + (0, logger_1.logInfo)(`šŸ“¦ Building relationship map from repository files...`); + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumesMap = relationshipMaps.consumes; + const consumedByMap = relationshipMaps.consumedBy; + (0, logger_1.logInfo)(`āœ… Relationship map built for ${repositoryFiles.size} files`); + for (let i = 0; i < filePaths.length; i++) { + const filePath = filePaths[i]; + const fileContent = repositoryFiles.get(filePath) || ''; + const progress = ((i + 1) / filePaths.length) * 100; + const currentTime = Date.now(); + const elapsedTime = (currentTime - startTime) / 1000; // in seconds + const estimatedTotalTime = (elapsedTime / (i + 1)) * filePaths.length; + const remainingTime = estimatedTotalTime - elapsedTime; + (0, logger_1.logSingleLine)(`šŸ”˜ ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Checking [${filePath}]`); + // Normalize path for consistent comparison + const normalizedPath = filePath.replace(/^\.\//, '').replace(/\\/g, '/').trim(); + // Calculate SHA for comparison + const currentSHA = this.fileCacheManager.calculateFileSHA(fileContent); + const remoteShasum = await supabaseRepository.getShasumByPath(param.owner, param.repo, branch, normalizedPath); + if (remoteShasum) { + if (remoteShasum === currentSHA) { + (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File indexed [${normalizedPath}]`); + continue; + } + else if (remoteShasum !== currentSHA) { + (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File has changes and must be reindexed [${normalizedPath}]`); + await supabaseRepository.removeAIFileCacheByPath(param.owner, param.repo, branch, normalizedPath); + } + } + else { + // File not in cache - will be processed below + (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File not in cache, will index [${normalizedPath}]`); + } + // Generate AI cache for this file + if (fileContent) { + try { + (0, logger_1.logSingleLine)(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Generating AI cache [${filePath}]`); + // Step 2: Extract imports for this file (from pre-built map) + const consumes = consumesMap.get(filePath) || []; + const consumedBy = consumedByMap.get(filePath) || []; + // Step 3: Generate description using AI (with fallback) + let description = this.codebaseAnalyzer.generateBasicDescription(filePath); + try { + // Create schema for single file description + const FILE_DESCRIPTION_SCHEMA = { + "type": "object", + "description": "File description", + "properties": { + "description": { + "type": "string", + "description": "Description of what the file does." + } + }, + "required": ["description"], + "additionalProperties": false + }; + const descriptionPrompt = `${constants_1.PROMPTS.CODE_BASE_ANALYSIS}: -Multipart.detect = /^multipart\/form-data/i -function Multipart (boy, cfg) { - let i - let len - const self = this - let boundary - const limits = cfg.limits - const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) - const parsedConType = cfg.parsedConType || [] - const defCharset = cfg.defCharset || 'utf8' - const preservePath = cfg.preservePath - const fileOpts = { highWaterMark: cfg.fileHwm } +\`\`\` +${fileContent} +\`\`\` - for (i = 0, len = parsedConType.length; i < len; ++i) { - if (Array.isArray(parsedConType[i]) && - RE_BOUNDARY.test(parsedConType[i][0])) { - boundary = parsedConType[i][1] - break +`; + const aiResponse = await this.aiRepository.askJson(param.ai, descriptionPrompt, FILE_DESCRIPTION_SCHEMA, "file_description"); + if (aiResponse && typeof aiResponse === 'object' && aiResponse.description) { + description = aiResponse.description.trim(); + } + } + catch (error) { + (0, logger_1.logError)(`Error generating AI description for ${filePath}, using fallback: ${error}`); + } + // Step 4: Save to Supabase (normalize path before saving) + const fileName = filePath.split('/').pop() || filePath; + const normalizedFilePath = filePath.replace(/^\.\//, '').replace(/\\/g, '/').trim(); + const normalizedConsumes = consumes.map(p => p.replace(/^\.\//, '').replace(/\\/g, '/').trim()); + const normalizedConsumedBy = consumedBy.map(p => p.replace(/^\.\//, '').replace(/\\/g, '/').trim()); + await supabaseRepository.setAIFileCache(param.owner, param.repo, branch, { + file_name: fileName, + path: normalizedFilePath, + sha: currentSHA, + description: description, + consumes: normalizedConsumes, + consumed_by: normalizedConsumedBy + }); + (0, logger_1.logSingleLine)(`🟢 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | AI cache saved [${filePath}]`); + } + catch (error) { + (0, logger_1.logError)(`Error generating AI cache for ${filePath}: ${JSON.stringify(error, null, 2)}`); + } + } + } + const totalDurationSeconds = (Date.now() - startTime) / 1000; + (0, logger_1.logInfo)(`šŸ“¦ šŸš€ All files stored in AI cache ${param.owner}/${param.repo}/${branch}. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, true); + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `All files up to date in AI cache for \`${branch}\`. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, + ], + })); + return results; + }; + this.duplicateAICacheToBranch = async (param, sourceBranch, targetBranch) => { + const results = []; + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + const supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + try { + (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Clearing possible existing AI cache from ${targetBranch} for ${param.owner}/${param.repo}.`); + await supabaseRepository.removeAIFileCacheByBranch(param.owner, param.repo, targetBranch); + (0, logger_1.logInfo)(`šŸ“¦ -> šŸ“¦ Duplicating AI cache from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`); + await supabaseRepository.duplicateAIFileCacheByBranch(param.owner, param.repo, sourceBranch, targetBranch); + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Duplicated AI cache from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`, + ], + })); + } + catch (error) { + (0, logger_1.logError)(`šŸ“¦ -> šŸ“¦ āŒ Error duplicating AI cache from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Error duplicating AI cache from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`, + ], + })); + } + return results; + }; + // Initialize CodebaseAnalyzer with dependencies + this.codebaseAnalyzer = new codebase_analyzer_1.CodebaseAnalyzer(this.aiRepository, this.fileImportAnalyzer, this.fileCacheManager); } - } - - function checkFinished () { - if (nends === 0 && finished && !boy._done) { - finished = false - self.end() + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + if (!param.supabaseConfig) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Supabase config not found.`, + ], + })); + return results; + } + // Check if AI configuration is available + if (!param.ai || !param.ai.getOpenRouterModel() || !param.ai.getOpenRouterApiKey()) { + (0, logger_1.logError)(`Missing required AI configuration. Please provide OPENROUTER_API_KEY and OPENROUTER_MODEL. ${JSON.stringify(param.ai, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Missing required AI configuration. Please provide OPENROUTER_API_KEY and OPENROUTER_MODEL.`, + ], + })); + return results; + } + const branch = param.commit.branch || param.branches.main; + let duplicationBranch = undefined; + if (branch === param.branches.main && param.singleAction.isAiCacheLocalAction) { + (0, logger_1.logInfo)(`šŸ“¦ AI cache from [${param.branches.main}] will be duplicated to [${param.branches.development}] for ${param.owner}/${param.repo}.`); + duplicationBranch = param.branches.development; + } + (0, logger_1.logInfo)(`šŸ“¦ Getting repository files on ${param.owner}/${param.repo}/${branch}`); + const repositoryFiles = await this.fileRepository.getRepositoryContent(param.owner, param.repo, param.tokens.token, branch, param.ai.getAiIgnoreFiles(), (fileName) => { + (0, logger_1.logSingleLine)(`Checking file ${fileName}`); + }, (fileName) => { + (0, logger_1.logSingleLine)(`Ignoring file ${fileName}`); + }); + (0, logger_1.logInfo)(`šŸ“¦ āœ… Files to index: ${repositoryFiles.size}`, true); + results.push(...await this.checkAICacheInSupabase(param, branch, repositoryFiles)); + results.push(...await this.uploadAICacheToSupabase(param, branch, repositoryFiles)); + if (duplicationBranch) { + results.push(...await this.duplicateAICacheToBranch(param, branch, duplicationBranch)); + } + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Vector action executed successfully.`, + ], + })); + } + catch (error) { + (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`, + ], + })); + } + return results; } - } - - if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - - const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) - const filesLimit = getLimit(limits, 'files', Infinity) - const fieldsLimit = getLimit(limits, 'fields', Infinity) - const partsLimit = getLimit(limits, 'parts', Infinity) - const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) - const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) +} +exports.VectorActionUseCase = VectorActionUseCase; - let nfiles = 0 - let nfields = 0 - let nends = 0 - let curFile - let curField - let finished = false - this._needDrain = false - this._pause = false - this._cb = undefined - this._nparts = 0 - this._boy = boy +/***/ }), - const parserCfg = { - boundary, - maxHeaderPairs: headerPairsLimit, - maxHeaderSize: headerSizeLimit, - partHwm: fileOpts.highWaterMark, - highWaterMark: cfg.highWaterMark - } +/***/ 5016: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.parser = new Dicer(parserCfg) - this.parser.on('drain', function () { - self._needDrain = false - if (self._cb && !self._pause) { - const cb = self._cb - self._cb = undefined - cb() - } - }).on('part', function onPart (part) { - if (++self._nparts > partsLimit) { - self.parser.removeListener('part', onPart) - self.parser.on('part', skipPart) - boy.hitPartsLimit = true - boy.emit('partsLimit') - return skipPart(part) - } +"use strict"; - // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let - // us emit 'end' early since we know the part has ended if we are already - // seeing the next part - if (curField) { - const field = curField - field.emit('end') - field.removeAllListeners('end') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommitUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +const notify_new_commit_on_issue_use_case_1 = __nccwpck_require__(8020); +const check_changes_issue_size_use_case_1 = __nccwpck_require__(5863); +class CommitUseCase { + constructor() { + this.taskId = 'CommitUseCase'; } - - part.on('header', function (header) { - let contype - let fieldname - let parsed - let charset - let encoding - let filename - let nsize = 0 - - if (header['content-type']) { - parsed = parseParams(header['content-type'][0]) - if (parsed[0]) { - contype = parsed[0].toLowerCase() - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_CHARSET.test(parsed[i][0])) { - charset = parsed[i][1].toLowerCase() - break + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + if (param.commit.commits.length === 0) { + (0, logger_1.logDebugInfo)('No commits found in this push.'); + return results; } - } + (0, logger_1.logDebugInfo)(`Branch: ${param.commit.branch}`); + (0, logger_1.logDebugInfo)(`Commits detected: ${param.commit.commits.length}`); + (0, logger_1.logDebugInfo)(`Issue number: ${param.issueNumber}`); + results.push(...(await new notify_new_commit_on_issue_use_case_1.NotifyNewCommitOnIssueUseCase().invoke(param))); + results.push(...(await new check_changes_issue_size_use_case_1.CheckChangesIssueSizeUseCase().invoke(param))); } - } - - if (contype === undefined) { contype = 'text/plain' } - if (charset === undefined) { charset = defCharset } - - if (header['content-disposition']) { - parsed = parseParams(header['content-disposition'][0]) - if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_NAME.test(parsed[i][0])) { - fieldname = parsed[i][1] - } else if (RE_FILENAME.test(parsed[i][0])) { - filename = parsed[i][1] - if (!preservePath) { filename = basename(filename) } - } + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error processing the commits.`, + ], + error: error, + })); } - } else { return skipPart(part) } + return results; + } +} +exports.CommitUseCase = CommitUseCase; - if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - let onData, - onEnd +/***/ }), - if (isPartAFile(fieldname, contype, filename)) { - // file/binary field - if (nfiles === filesLimit) { - if (!boy.hitFilesLimit) { - boy.hitFilesLimit = true - boy.emit('filesLimit') - } - return skipPart(part) - } +/***/ 854: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ++nfiles +"use strict"; - if (boy.listenerCount('file') === 0) { - self.parser._ignore() - return - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueCommentUseCase = void 0; +const logger_1 = __nccwpck_require__(8836); +const think_use_case_1 = __nccwpck_require__(3841); +const check_issue_comment_language_use_case_1 = __nccwpck_require__(465); +class IssueCommentUseCase { + constructor() { + this.taskId = 'IssueCommentUseCase'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + results.push(...await new check_issue_comment_language_use_case_1.CheckIssueCommentLanguageUseCase().invoke(param)); + results.push(...await new think_use_case_1.ThinkUseCase().invoke(param)); + return results; + } +} +exports.IssueCommentUseCase = IssueCommentUseCase; - ++nends - const file = new FileStream(fileOpts) - curFile = file - file.on('end', function () { - --nends - self._pause = false - checkFinished() - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - }) - file._read = function (n) { - if (!self._pause) { return } - self._pause = false - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - } - boy.emit('file', fieldname, file, filename, encoding, contype) - onData = function (data) { - if ((nsize += data.length) > fileSizeLimit) { - const extralen = fileSizeLimit - nsize + data.length - if (extralen > 0) { file.push(data.slice(0, extralen)) } - file.truncated = true - file.bytesRead = fileSizeLimit - part.removeAllListeners('data') - file.emit('limit') - return - } else if (!file.push(data)) { self._pause = true } +/***/ }), - file.bytesRead = nsize - } +/***/ 8675: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - onEnd = function () { - curFile = undefined - file.push(null) +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.IssueUseCase = void 0; +const logger_1 = __nccwpck_require__(8836); +const check_permissions_use_case_1 = __nccwpck_require__(8749); +const update_title_use_case_1 = __nccwpck_require__(5107); +const assign_members_to_issue_use_case_1 = __nccwpck_require__(3115); +const check_priority_issue_size_use_case_1 = __nccwpck_require__(151); +const close_not_allowed_issue_use_case_1 = __nccwpck_require__(7826); +const label_deploy_added_use_case_1 = __nccwpck_require__(5678); +const label_deployed_added_use_case_1 = __nccwpck_require__(8388); +const link_issue_project_use_case_1 = __nccwpck_require__(7528); +const prepare_branches_use_case_1 = __nccwpck_require__(4423); +const remove_issue_branches_use_case_1 = __nccwpck_require__(2354); +const remove_not_needed_branches_use_case_1 = __nccwpck_require__(773); +const update_issue_type_use_case_1 = __nccwpck_require__(1652); +class IssueUseCase { + constructor() { + this.taskId = 'IssueUseCase'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + const permissionResult = await new check_permissions_use_case_1.CheckPermissionsUseCase().invoke(param); + const lastAction = permissionResult[permissionResult.length - 1]; + if (!lastAction.success && lastAction.executed) { + results.push(...permissionResult); + results.push(...await new close_not_allowed_issue_use_case_1.CloseNotAllowedIssueUseCase().invoke(param)); + return results; } - } else { - // non-file field - if (nfields === fieldsLimit) { - if (!boy.hitFieldsLimit) { - boy.hitFieldsLimit = true - boy.emit('fieldsLimit') - } - return skipPart(part) + if (param.cleanIssueBranches) { + results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); } - - ++nfields - ++nends - let buffer = '' - let truncated = false - curField = part - - onData = function (data) { - if ((nsize += data.length) > fieldSizeLimit) { - const extralen = (fieldSizeLimit - (nsize - data.length)) - buffer += data.toString('binary', 0, extralen) - truncated = true - part.removeAllListeners('data') - } else { buffer += data.toString('binary') } + /** + * Assignees + */ + results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); + /** + * Update title + */ + results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); + /** + * Update issue type + */ + results.push(...await new update_issue_type_use_case_1.UpdateIssueTypeUseCase().invoke(param)); + /** + * Link issue to project + */ + results.push(...await new link_issue_project_use_case_1.LinkIssueProjectUseCase().invoke(param)); + /** + * Check priority issue size + */ + results.push(...await new check_priority_issue_size_use_case_1.CheckPriorityIssueSizeUseCase().invoke(param)); + /** + * Prepare branches + */ + if (param.isBranched) { + results.push(...await new prepare_branches_use_case_1.PrepareBranchesUseCase().invoke(param)); } - - onEnd = function () { - curField = undefined - if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } - boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) - --nends - checkFinished() + else { + results.push(...await new remove_issue_branches_use_case_1.RemoveIssueBranchesUseCase().invoke(param)); } - } - - /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become - broken. Streams2/streams3 is a huge black box of confusion, but - somehow overriding the sync state seems to fix things again (and still - seems to work for previous node versions). - */ - part._readableState.sync = false - - part.on('data', onData) - part.on('end', onEnd) - }).on('error', function (err) { - if (curFile) { curFile.emit('error', err) } - }) - }).on('error', function (err) { - boy.emit('error', err) - }).on('finish', function () { - finished = true - checkFinished() - }) -} - -Multipart.prototype.write = function (chunk, cb) { - const r = this.parser.write(chunk) - if (r && !this._pause) { - cb() - } else { - this._needDrain = !r - this._cb = cb - } + /** + * Remove unnecessary branches + */ + results.push(...await new remove_not_needed_branches_use_case_1.RemoveNotNeededBranchesUseCase().invoke(param)); + /** + * Check if deploy label was added + */ + results.push(...await new label_deploy_added_use_case_1.DeployAddedUseCase().invoke(param)); + /** + * Check if deployed label was added + */ + results.push(...await new label_deployed_added_use_case_1.DeployedAddedUseCase().invoke(param)); + return results; + } } +exports.IssueUseCase = IssueUseCase; -Multipart.prototype.end = function () { - const self = this - - if (self.parser.writable) { - self.parser.end() - } else if (!self._boy._done) { - process.nextTick(function () { - self._boy._done = true - self._boy.emit('finish') - }) - } -} -function skipPart (part) { - part.resume() -} +/***/ }), -function FileStream (opts) { - Readable.call(this, opts) +/***/ 7883: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.bytesRead = 0 +"use strict"; - this.truncated = false +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullRequestReviewCommentUseCase = void 0; +const logger_1 = __nccwpck_require__(8836); +const check_pull_request_comment_language_use_case_1 = __nccwpck_require__(7112); +class PullRequestReviewCommentUseCase { + constructor() { + this.taskId = 'PullRequestReviewCommentUseCase'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + results.push(...await new check_pull_request_comment_language_use_case_1.CheckPullRequestCommentLanguageUseCase().invoke(param)); + return results; + } } - -inherits(FileStream, Readable) - -FileStream.prototype._read = function (n) {} - -module.exports = Multipart +exports.PullRequestReviewCommentUseCase = PullRequestReviewCommentUseCase; /***/ }), -/***/ 78306: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5041: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -const Decoder = __nccwpck_require__(27100) -const decodeText = __nccwpck_require__(84619) -const getLimit = __nccwpck_require__(21467) - -const RE_CHARSET = /^charset$/i - -UrlEncoded.detect = /^application\/x-www-form-urlencoded/i -function UrlEncoded (boy, cfg) { - const limits = cfg.limits - const parsedConType = cfg.parsedConType - this.boy = boy - - this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) - this.fieldsLimit = getLimit(limits, 'fields', Infinity) - - let charset - for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var - if (Array.isArray(parsedConType[i]) && - RE_CHARSET.test(parsedConType[i][0])) { - charset = parsedConType[i][1].toLowerCase() - break - } - } - - if (charset === undefined) { charset = cfg.defCharset || 'utf8' } - - this.decoder = new Decoder() - this.charset = charset - this._fields = 0 - this._state = 'key' - this._checkingBytes = true - this._bytesKey = 0 - this._bytesVal = 0 - this._key = '' - this._val = '' - this._keyTrunc = false - this._valTrunc = false - this._hitLimit = false -} - -UrlEncoded.prototype.write = function (data, cb) { - if (this._fields === this.fieldsLimit) { - if (!this.boy.hitFieldsLimit) { - this.boy.hitFieldsLimit = true - this.boy.emit('fieldsLimit') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PullRequestUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +const update_title_use_case_1 = __nccwpck_require__(5107); +const assign_members_to_issue_use_case_1 = __nccwpck_require__(3115); +const assign_reviewers_to_issue_use_case_1 = __nccwpck_require__(6275); +const close_issue_after_merging_use_case_1 = __nccwpck_require__(5137); +const check_changes_pull_request_size_use_case_1 = __nccwpck_require__(8129); +const check_priority_pull_request_size_use_case_1 = __nccwpck_require__(7383); +const link_pull_request_issue_use_case_1 = __nccwpck_require__(2175); +const link_pull_request_project_use_case_1 = __nccwpck_require__(4311); +const update_pull_request_description_use_case_1 = __nccwpck_require__(158); +class PullRequestUseCase { + constructor() { + this.taskId = 'PullRequestUseCase'; } - return cb() - } - - let idxeq; let idxamp; let i; let p = 0; const len = data.length - - while (p < len) { - if (this._state === 'key') { - idxeq = idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x3D/* = */) { - idxeq = i - break - } else if (data[i] === 0x26/* & */) { - idxamp = i - break + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + (0, logger_1.logDebugInfo)(`PR action ${param.pullRequest.action}`); + (0, logger_1.logDebugInfo)(`PR isOpened ${param.pullRequest.isOpened}`); + (0, logger_1.logDebugInfo)(`PR isMerged ${param.pullRequest.isMerged}`); + (0, logger_1.logDebugInfo)(`PR isClosed ${param.pullRequest.isClosed}`); + if (param.pullRequest.isOpened) { + /** + * Update title + */ + results.push(...await new update_title_use_case_1.UpdateTitleUseCase().invoke(param)); + /** + * Assignees + */ + results.push(...await new assign_members_to_issue_use_case_1.AssignMemberToIssueUseCase().invoke(param)); + /** + * Reviewers + */ + results.push(...await new assign_reviewers_to_issue_use_case_1.AssignReviewersToIssueUseCase().invoke(param)); + /** + * Link Pull Request to projects + */ + results.push(...await new link_pull_request_project_use_case_1.LinkPullRequestProjectUseCase().invoke(param)); + /** + * Link Pull Request to issue + */ + results.push(...await new link_pull_request_issue_use_case_1.LinkPullRequestIssueUseCase().invoke(param)); + /** + * Check priority pull request size + */ + results.push(...await new check_priority_pull_request_size_use_case_1.CheckPriorityPullRequestSizeUseCase().invoke(param)); + /** + * Check changes size + */ + results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); + if (param.ai.getAiPullRequestDescription()) { + /** + * Update pull request description + */ + results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); + } + } + else if (param.pullRequest.isSynchronize) { + /** + * Check changes size + */ + results.push(...await new check_changes_pull_request_size_use_case_1.CheckChangesPullRequestSizeUseCase().invoke(param)); + /** + * Pushed changes to the pull request + */ + if (param.ai.getAiPullRequestDescription()) { + /** + * Update pull request description + */ + results.push(...await new update_pull_request_description_use_case_1.UpdatePullRequestDescriptionUseCase().invoke(param)); + } + } + else if (param.pullRequest.isClosed && param.pullRequest.isMerged) { + /** + * Close issue if needed + */ + results.push(...await new close_issue_after_merging_use_case_1.CloseIssueAfterMergingUseCase().invoke(param)); + } } - if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesKey } - } - - if (idxeq !== undefined) { - // key with assignment - if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } - this._state = 'val' + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error linking projects/issues with pull request.`, + ], + error: error, + })); + } + return results; + } +} +exports.PullRequestUseCase = PullRequestUseCase; - this._hitLimit = false - this._checkingBytes = true - this._val = '' - this._bytesVal = 0 - this._valTrunc = false - this.decoder.reset() - p = idxeq + 1 - } else if (idxamp !== undefined) { - // key with no assignment - ++this._fields - let key; const keyTrunc = this._keyTrunc - if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } +/***/ }), - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() +/***/ 6479: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (key.length) { - this.boy.emit('field', decodeText(key, 'binary', this.charset), - '', - keyTrunc, - false) - } +"use strict"; - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._keyTrunc = true +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SingleActionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +const deployed_action_use_case_1 = __nccwpck_require__(8293); +const vector_action_use_case_1 = __nccwpck_require__(7757); +const publish_github_action_use_case_1 = __nccwpck_require__(9029); +const create_release_use_case_1 = __nccwpck_require__(2430); +const create_tag_use_case_1 = __nccwpck_require__(5279); +const think_use_case_1 = __nccwpck_require__(3841); +class SingleActionUseCase { + constructor() { + this.taskId = 'SingleActionUseCase'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + if (!param.singleAction.validSingleAction) { + (0, logger_1.logDebugInfo)(`Not a valid single action: ${param.singleAction.currentSingleAction}`); + return results; + } + if (param.singleAction.isAiCacheAction) { + results.push(...await new vector_action_use_case_1.VectorActionUseCase().invoke(param)); + } + else if (param.singleAction.isDeployedAction) { + results.push(...await new deployed_action_use_case_1.DeployedActionUseCase().invoke(param)); + } + else if (param.singleAction.isPublishGithubAction) { + results.push(...await new publish_github_action_use_case_1.PublishGithubActionUseCase().invoke(param)); + } + else if (param.singleAction.isCreateReleaseAction) { + results.push(...await new create_release_use_case_1.CreateReleaseUseCase().invoke(param)); + } + else if (param.singleAction.isCreateTagAction) { + results.push(...await new create_tag_use_case_1.CreateTagUseCase().invoke(param)); + } + else if (param.singleAction.isThinkAction) { + results.push(...await new think_use_case_1.ThinkUseCase().invoke(param)); + } } - } else { - if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } - p = len - } - } else { - idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x26/* & */) { - idxamp = i - break + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error executing single action: ${param.singleAction.currentSingleAction}.`, + ], + error: error, + })); } - if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesVal } - } + return results; + } +} +exports.SingleActionUseCase = SingleActionUseCase; - if (idxamp !== undefined) { - ++this._fields - if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - this._state = 'key' - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() +/***/ }), - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._val === '' && this.fieldSizeLimit === 0) || - (this._bytesVal = this._val.length) === this.fieldSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._valTrunc = true +/***/ 5863: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckChangesIssueSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckChangesIssueSizeUseCase { + constructor() { + this.taskId = 'CheckChangesIssueSizeUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.currentConfiguration.parentBranch === undefined) { + (0, logger_1.logDebugInfo)(`Parent branch is undefined.`); + return result; + } + const headBranch = param.commit.branch; + const baseBranch = param.currentConfiguration.parentBranch; + const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, headBranch, baseBranch, param.sizeThresholds, param.labels, param.tokens.token); + (0, logger_1.logDebugInfo)(`Size: ${size}`); + (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); + (0, logger_1.logDebugInfo)(`Reason: ${reason}`); + (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnIssue}`); + if (param.labels.sizedLabelOnIssue !== size) { + const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); + labelNames.push(size); + await this.issueRepository.setLabels(param.owner, param.repo, param.issueNumber, labelNames, param.tokens.token); + for (const project of param.project.getProjects()) { + await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.issueNumber, githubSize, param.tokens.token); + } + (0, logger_1.logDebugInfo)(`Updated labels on issue #${param.issueNumber}:`); + (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `${reason}, so the issue was resized to ${size}.`, + ], + })); + } + else { + (0, logger_1.logDebugInfo)(`The issue is already at the correct size.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } } - } else { - if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } - p = len - } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the size of the changes, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } - } - cb() } +exports.CheckChangesIssueSizeUseCase = CheckChangesIssueSizeUseCase; -UrlEncoded.prototype.end = function () { - if (this.boy._done) { return } - if (this._state === 'key' && this._key.length > 0) { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - '', - this._keyTrunc, - false) - } else if (this._state === 'val') { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - } - this.boy._done = true - this.boy.emit('finish') -} +/***/ }), -module.exports = UrlEncoded +/***/ 8020: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; -/***/ }), +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.NotifyNewCommitOnIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const list_utils_1 = __nccwpck_require__(4990); +const logger_1 = __nccwpck_require__(8836); +const execute_script_use_case_1 = __nccwpck_require__(155); +class NotifyNewCommitOnIssueUseCase { + constructor() { + this.taskId = 'NotifyNewCommitOnIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.mergeBranchPattern = 'Merge branch '; + this.ghAction = 'gh-action: '; + this.separator = '------------------------------------------------------'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const branchName = param.commit.branch; + let commitPrefix = ''; + if (param.commitPrefixBuilder.length > 0) { + param.commitPrefixBuilderParams = { + branchName: branchName, + }; + const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); + const prefixResult = await executor.invoke(param); + commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; + (0, logger_1.logDebugInfo)(`Commit prefix: ${commitPrefix}`); + } + let title = ''; + let image = ''; + if (param.release.active) { + title = 'šŸš€ Release News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitReleaseGifs); + } + else if (param.hotfix.active) { + title = 'šŸ”„šŸ› Hotfix News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitHotfixGifs); + } + else if (param.isBugfix) { + title = 'šŸ› Bugfix News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitBugfixGifs); + } + else if (param.isFeature) { + title = '✨ Feature News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitFeatureGifs); + } + else if (param.isDocs) { + title = 'šŸ“ Documentation News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitDocsGifs); + } + else if (param.isChore) { + title = 'šŸ”§ Chore News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitChoreGifs); + } + else { + title = 'šŸŖ„ Automatic News'; + image = (0, list_utils_1.getRandomElement)(param.images.commitAutomaticActions); + } + let commentBody = ` +# ${title} -/***/ 27100: -/***/ ((module) => { +**Changes on branch \`${param.commit.branch}\`:** -"use strict"; +`; + let shouldWarn = false; + for (const commit of param.commit.commits) { + commentBody += ` +${this.separator} +- ${commit.id} by **${commit.author.name}** (@${commit.author.username}) +\`\`\` +${commit.message.replaceAll(`${commitPrefix}: `, '')} +\`\`\` -const RE_PLUS = /\+/g +`; + if ((commit.message.indexOf(commitPrefix) !== 0 && commitPrefix.length > 0) + && commit.message.indexOf(this.mergeBranchPattern) !== 0 + && commit.message.indexOf(this.ghAction) !== 0) { + shouldWarn = true; + } + } + if (shouldWarn && commitPrefix.length > 0) { + commentBody += ` +${this.separator} +## āš ļø Attention -const HEX = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -] +One or more commits didn't start with the prefix **${commitPrefix}**. -function Decoder () { - this.buffer = undefined -} -Decoder.prototype.write = function (str) { - // Replace '+' with ' ' before decoding - str = str.replace(RE_PLUS, ' ') - let res = '' - let i = 0; let p = 0; const len = str.length - for (; i < len; ++i) { - if (this.buffer !== undefined) { - if (!HEX[str.charCodeAt(i)]) { - res += '%' + this.buffer - this.buffer = undefined - --i // retry character - } else { - this.buffer += str[i] - ++p - if (this.buffer.length === 2) { - res += String.fromCharCode(parseInt(this.buffer, 16)) - this.buffer = undefined +\`\`\` +${commitPrefix}: created hello-world app +\`\`\` +`; + } + if (image && param.images.imagesOnCommit) { + commentBody += ` +${this.separator} + +![image](${image}) +`; + } + if (param.issue.reopenOnPush) { + const opened = await this.issueRepository.openIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (opened) { + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was re-opened after pushing new commits to the branch \`${branchName}\`.`, param.tokens.token); + } + } + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, commentBody, param.tokens.token); } - } - } else if (str[i] === '%') { - if (i > p) { - res += str.substring(p, i) - p = i - } - this.buffer = '' - ++p + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to notify the new commit on the issue, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } - } - if (p < len && this.buffer === undefined) { res += str.substring(p) } - return res } -Decoder.prototype.reset = function () { - this.buffer = undefined -} - -module.exports = Decoder +exports.NotifyNewCommitOnIssueUseCase = NotifyNewCommitOnIssueUseCase; /***/ }), -/***/ 48647: -/***/ ((module) => { +/***/ 8749: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -module.exports = function basename (path) { - if (typeof path !== 'string') { return '' } - for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var - switch (path.charCodeAt(i)) { - case 0x2F: // '/' - case 0x5C: // '\' - path = path.slice(i + 1) - return (path === '..' || path === '.' ? '' : path) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPermissionsUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckPermissionsUseCase { + constructor() { + this.taskId = 'CheckPermissionsUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + /** + * If a release/hotfix issue was opened, check if author is a member of the project. + */ + if (param.isIssue && !param.issue.opened) { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue state is not 'opened'.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + else if (param.isPullRequest && !param.pullRequest.opened) { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Pull request state is not 'opened'.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + try { + const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); + const creator = param.isIssue ? param.issue.creator : param.pullRequest.creator; + const creatorIsTeamMember = creator.length > 0 + && currentProjectMembers.indexOf(creator) > -1; + if (param.labels.isMandatoryBranchedLabel) { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); + if (creatorIsTeamMember) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`@${param.issue.creator} was not authorized to create **[${param.labels.currentIssueLabels.join(',')}]** issues.`], + })); + } + } + else { + (0, logger_1.logDebugInfo)(`Ignoring permission checking. Issue doesn't require mandatory branch.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; } - } - return (path === '..' || path === '.' ? '' : path) } +exports.CheckPermissionsUseCase = CheckPermissionsUseCase; /***/ }), -/***/ 84619: -/***/ (function(module) { +/***/ 155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -// Node has always utf-8 -const utf8Decoder = new TextDecoder('utf-8') -const textDecoders = new Map([ - ['utf-8', utf8Decoder], - ['utf8', utf8Decoder] -]) - -function getDecoder (charset) { - let lc - while (true) { - switch (charset) { - case 'utf-8': - case 'utf8': - return decoders.utf8 - case 'latin1': - case 'ascii': // TODO: Make these a separate, strict decoder? - case 'us-ascii': - case 'iso-8859-1': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'windows-1252': - case 'iso_8859-1:1987': - case 'cp1252': - case 'x-cp1252': - return decoders.latin1 - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return decoders.utf16le - case 'base64': - return decoders.base64 - default: - if (lc === undefined) { - lc = true - charset = charset.toLowerCase() - continue - } - return decoders.other.bind(charset) - } - } -} - -const decoders = { - utf8: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.utf8Slice(0, data.length) - }, - - latin1: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - return data - } - return data.latin1Slice(0, data.length) - }, - - utf16le: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.ucs2Slice(0, data.length) - }, - - base64: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommitPrefixBuilderUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +class CommitPrefixBuilderUseCase { + constructor() { + this.taskId = 'CommitPrefixBuilderUseCase'; } - return data.base64Slice(0, data.length) - }, - - other: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const branchName = param.commitPrefixBuilderParams.branchName; + const transforms = param.commitPrefixBuilder; // Now it's a list of transforms + const commitPrefix = this.applyTransforms(branchName, transforms); + (0, logger_1.logDebugInfo)(`Commit prefix generated: ${commitPrefix}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [], + payload: { + scriptResult: commitPrefix + } + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [], + error: error, + })); + } + return result; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + applyTransforms(branchName, transforms) { + // Parse the list of transformations + const transformList = transforms.split(',').map(t => t.trim()); + let result = branchName; + // Apply each transformation sequentially + for (const transform of transformList) { + result = this.applyTransform(result, transform); + } + return result; } - - if (textDecoders.has(this.toString())) { - try { - return textDecoders.get(this).decode(data) - } catch {} + applyTransform(input, transform) { + switch (transform) { + case "replace-slash": + return input.replace("/", "-"); + case "replace-all": + return input.replace(/[^a-zA-Z0-9-]/g, "-"); + case "lowercase": + return input.toLowerCase(); + case "uppercase": + return input.toUpperCase(); + case "kebab-case": + return input + .replace(/[^a-zA-Z0-9-]/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, "") + .toLowerCase(); + case "snake-case": + return input + .replace(/[^a-zA-Z0-9-]/g, "_") + .replace(/_+/g, "_") + .replace(/^_|_$/g, "") + .toLowerCase(); + case "camel-case": + return input + .replace(/[^a-zA-Z0-9-]/g, "-") + .split("-") + .map((word, index) => index === 0 ? word.toLowerCase() : + word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) + .join(""); + case "trim": + return input.trim(); + case "remove-numbers": + return input.replace(/\d+/g, ""); + case "remove-special": + return input.replace(/[^a-zA-Z0-9]/g, ""); + case "remove-spaces": + return input.replace(/\s+/g, ""); + case "remove-dashes": + return input.replace(/-+/g, ""); + case "remove-underscores": + return input.replace(/_+/g, ""); + case "clean-dashes": + return input.replace(/-+/g, "-").replace(/^-|-$/g, ""); + case "clean-underscores": + return input.replace(/_+/g, "_").replace(/^_|_$/g, ""); + case "prefix": + return `prefix-${input}`; + case "suffix": + return `${input}-suffix`; + default: + // If not recognized, return without changes + (0, logger_1.logDebugInfo)(`Unknown transform: ${transform}, skipping...`); + return input; + } } - return typeof data === 'string' - ? data - : data.toString() - } -} - -function decodeText (text, sourceEncoding, destEncoding) { - if (text) { - return getDecoder(destEncoding)(text, sourceEncoding) - } - return text } - -module.exports = decodeText +exports.CommitPrefixBuilderUseCase = CommitPrefixBuilderUseCase; /***/ }), -/***/ 21467: -/***/ ((module) => { +/***/ 8243: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -module.exports = function getLimit (limits, name, defaultLimit) { - if ( - !limits || - limits[name] === undefined || - limits[name] === null - ) { return defaultLimit } - - if ( - typeof limits[name] !== 'number' || - isNaN(limits[name]) - ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - - return limits[name] +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetHotfixVersionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class GetHotfixVersionUseCase { + constructor() { + this.taskId = 'GetHotfixVersionUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + let number = -1; + if (param.isSingleAction) { + number = param.singleAction.issue; + } + else if (param.isIssue) { + number = param.issue.number; + } + else if (param.isPullRequest) { + number = param.pullRequest.number; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem identifying the issue.`], + })); + return result; + } + const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); + if (description === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem getting the description.`], + })); + return result; + } + const baseVersion = (0, content_utils_1.extractVersion)('Base Version', description); + const hotfixVersion = (0, content_utils_1.extractVersion)('Hotfix Version', description); + if (baseVersion === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the base version but there was a problem identifying the version.`], + })); + return result; + } + else if (hotfixVersion === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the hotfix version but there was a problem identifying the version.`], + })); + return result; + } + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + payload: { + baseVersion: baseVersion, + hotfixVersion: hotfixVersion, + } + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; + } } +exports.GetHotfixVersionUseCase = GetHotfixVersionUseCase; /***/ }), -/***/ 31854: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5966: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -/* eslint-disable object-property-newline */ - - -const decodeText = __nccwpck_require__(84619) - -const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - -const EncodedLookup = { - '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', - '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', - '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', - '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', - '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', - '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', - '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', - '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', - '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', - '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', - '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', - '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', - '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', - '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', - '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', - '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', - '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', - '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', - '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', - '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', - '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', - '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', - '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', - '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', - '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', - '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', - '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', - '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', - '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', - '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', - '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', - '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', - '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', - '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', - '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', - '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', - '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', - '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', - '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', - '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', - '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', - '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', - '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', - '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', - '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', - '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', - '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', - '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', - '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', - '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', - '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', - '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', - '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', - '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', - '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', - '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', - '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', - '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', - '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', - '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', - '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', - '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', - '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', - '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', - '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', - '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', - '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', - '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', - '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', - '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', - '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', - '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', - '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', - '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', - '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', - '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', - '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', - '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', - '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', - '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', - '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', - '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', - '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', - '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', - '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', - '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', - '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', - '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', - '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', - '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', - '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', - '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', - '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', - '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', - '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', - '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', - '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' -} - -function encodedReplacer (match) { - return EncodedLookup[match] -} - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - const char = str[i] - if (char === '\\' && inquote) { - if (escaping) { escaping = false } else { - escaping = true - continue - } - } else if (char === '"') { - if (!escaping) { - if (inquote) { - inquote = false - state = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = STATE_KEY - if (charset) { - if (tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } - charset = '' - } else if (tmp.length) { - tmp = decodeText(tmp, 'binary', 'utf8') +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetReleaseTypeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class GetReleaseTypeUseCase { + constructor() { + this.taskId = 'GetReleaseTypeUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + let number = -1; + if (param.isSingleAction) { + number = param.singleAction.issue; + } + else if (param.isIssue) { + number = param.issue.number; + } + else if (param.isPullRequest) { + number = param.pullRequest.number; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the release type but there was a problem identifying the issue.`], + })); + return result; + } + const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); + if (description === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the release type but there was a problem getting the description.`], + })); + return result; + } + const releaseType = (0, content_utils_1.extractReleaseType)('Release Type', description); + if (releaseType === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the release type but there was a problem identifying the type.`], + })); + return result; + } + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + payload: { + releaseType: releaseType, + } + })); } - if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } - tmp = '' - ++p - continue - } else if (!inquote && (char === ' ' || char === '\t')) { continue } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; } - tmp += char - } - if (charset && tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } else if (tmp) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - - if (res[p] === undefined) { - if (tmp) { res[p] = tmp } - } else { res[p][1] = tmp } - - return res } - -module.exports = parseParams +exports.GetReleaseTypeUseCase = GetReleaseTypeUseCase; /***/ }), -/***/ 52694: -/***/ (function(module, exports) { - -// GENERATED FILE. DO NOT EDIT. -(function (global, factory) { - function preferDefault(exports) { - return exports.default || exports; - } - if (typeof define === "function" && define.amd) { - define([], function () { - var exports = {}; - factory(exports); - return preferDefault(exports); - }); - } else if (true) { - factory(exports); - if (true) module.exports = preferDefault(exports); - } else {} -})( - typeof globalThis !== "undefined" - ? globalThis - : typeof self !== "undefined" - ? self - : this, - function (_exports) { - "use strict"; - - Object.defineProperty(_exports, "__esModule", { - value: true, - }); - _exports.default = void 0; - /** - * @license - * Copyright 2009 The Closure Library Authors - * Copyright 2020 Daniel Wirtz / The long.js 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 - * - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - - // WebAssembly optimizations to do native i64 multiplication and divide - var wasm = null; - try { - wasm = new WebAssembly.Instance( - new WebAssembly.Module( - new Uint8Array([ - // \0asm - 0, 97, 115, 109, - // version 1 - 1, 0, 0, 0, - // section "type" - 1, 13, 2, - // 0, () => i32 - 96, 0, 1, 127, - // 1, (i32, i32, i32, i32) => i32 - 96, 4, 127, 127, 127, 127, 1, 127, - // section "function" - 3, 7, 6, - // 0, type 0 - 0, - // 1, type 1 - 1, - // 2, type 1 - 1, - // 3, type 1 - 1, - // 4, type 1 - 1, - // 5, type 1 - 1, - // section "global" - 6, 6, 1, - // 0, "high", mutable i32 - 127, 1, 65, 0, 11, - // section "export" - 7, 50, 6, - // 0, "mul" - 3, 109, 117, 108, 0, 1, - // 1, "div_s" - 5, 100, 105, 118, 95, 115, 0, 2, - // 2, "div_u" - 5, 100, 105, 118, 95, 117, 0, 3, - // 3, "rem_s" - 5, 114, 101, 109, 95, 115, 0, 4, - // 4, "rem_u" - 5, 114, 101, 109, 95, 117, 0, 5, - // 5, "get_high" - 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, - // section "code" - 10, 191, 1, 6, - // 0, "get_high" - 4, 0, 35, 0, 11, - // 1, "mul" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 2, "div_s" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 3, "div_u" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 4, "rem_s" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 5, "rem_u" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - ]), - ), - {}, - ).exports; - } catch { - // no wasm support :( - } - - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * @exports Long - * @class A Long class for representing a 64 bit two's-complement integer value. - * @param {number} low The low (signed) 32 bits of the long - * @param {number} high The high (signed) 32 bits of the long - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @constructor - */ - function Long(low, high, unsigned) { - /** - * The low 32 bits as a signed value. - * @type {number} - */ - this.low = low | 0; - - /** - * The high 32 bits as a signed value. - * @type {number} - */ - this.high = high | 0; - - /** - * Whether unsigned or not. - * @type {boolean} - */ - this.unsigned = !!unsigned; - } - - // The internal representation of a long is the two given signed, 32-bit values. - // We use 32-bit pieces because these are the size of integers on which - // Javascript performs bit-operations. For operations like addition and - // multiplication, we split each number into 16 bit pieces, which can easily be - // multiplied within Javascript's floating-point representation without overflow - // or change in sign. - // - // In the algorithms below, we frequently reduce the negative case to the - // positive case by negating the input(s) and then post-processing the result. - // Note that we must ALWAYS check specially whether those values are MIN_VALUE - // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - // a positive number, it overflows back into a negative). Not handling this - // case would often result in infinite recursion. - // - // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* - // methods on which they depend. +/***/ 3827: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * An indicator used to reliably determine if an object is a Long or not. - * @type {boolean} - * @const - * @private - */ - Long.prototype.__isLong__; - Object.defineProperty(Long.prototype, "__isLong__", { - value: true, - }); +"use strict"; - /** - * @function - * @param {*} obj Object - * @returns {boolean} - * @inner - */ - function isLong(obj) { - return (obj && obj["__isLong__"]) === true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.GetReleaseVersionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class GetReleaseVersionUseCase { + constructor() { + this.taskId = 'GetReleaseVersionUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); } - - /** - * @function - * @param {*} value number - * @returns {number} - * @inner - */ - function ctz32(value) { - var c = Math.clz32(value & -value); - return value ? 31 - c : c; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + let number = -1; + if (param.isSingleAction) { + number = param.singleAction.issue; + } + else if (param.isIssue) { + number = param.issue.number; + } + else if (param.isPullRequest) { + number = param.pullRequest.number; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem identifying the issue.`], + })); + return result; + } + const description = await this.issueRepository.getDescription(param.owner, param.repo, number, param.tokens.token); + if (description === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to get the version but there was a problem getting the description.`], + })); + return result; + } + const releaseVersion = (0, content_utils_1.extractVersion)('Release Version', description); + if (releaseVersion === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + })); + return result; + } + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + payload: { + releaseVersion: releaseVersion, + } + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to check action permissions.`], + error: error, + })); + } + return result; } +} +exports.GetReleaseVersionUseCase = GetReleaseVersionUseCase; - /** - * Tests if the specified object is a Long. - * @function - * @param {*} obj Object - * @returns {boolean} - */ - Long.isLong = isLong; - - /** - * A cache of the Long representations of small integer values. - * @type {!Object} - * @inner - */ - var INT_CACHE = {}; - /** - * A cache of the Long representations of small unsigned integer values. - * @type {!Object} - * @inner - */ - var UINT_CACHE = {}; +/***/ }), - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromInt(value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, 0, true); - if (cache) UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache) INT_CACHE[value] = obj; - return obj; - } - } +/***/ 9813: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Returns a Long representing the given 32 bit integer value. - * @function - * @param {number} value The 32 bit integer in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromInt = fromInt; +"use strict"; - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromNumber(value, unsigned) { - if (isNaN(value)) return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) return UZERO; - if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; - } - if (value < 0) return fromNumber(-value, unsigned).neg(); - return fromBits( - value % TWO_PWR_32_DBL | 0, - (value / TWO_PWR_32_DBL) | 0, - unsigned, - ); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PublishResultUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const list_utils_1 = __nccwpck_require__(4990); +const logger_1 = __nccwpck_require__(8836); +/** + * Publish the resume of actions + */ +class PublishResultUseCase { + constructor() { + this.taskId = 'PublishResultUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + try { + /** + * Comment resume of actions + */ + let title = 'šŸŖ„ Automatic Actions'; + let content = ''; + let stupidGif = ''; + let image; + let errors = ''; + let footer = ''; + if (param.isIssue) { + if (param.issueNotBranched) { + title = 'šŸŖ„ Automatic Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.issueAutomaticActions); + } + else if (param.release.active) { + title = 'šŸš€ Release Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.issueReleaseGifs); + } + else if (param.hotfix.active) { + title = 'šŸ”„šŸ› Hotfix Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.issueHotfixGifs); + } + else if (param.isBugfix) { + title = 'šŸ› Bugfix Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.issueBugfixGifs); + } + else if (param.isFeature) { + title = '✨ Feature Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.issueFeatureGifs); + } + else if (param.isDocs) { + title = 'šŸ“ Documentation Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.issueDocsGifs); + } + else if (param.isChore) { + title = 'šŸ”§ Chore Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.issueChoreGifs); + } + } + else if (param.isPullRequest) { + if (param.release.active) { + title = 'šŸš€ Release Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.pullRequestReleaseGifs); + } + else if (param.hotfix.active) { + title = 'šŸ”„šŸ› Hotfix Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.pullRequestHotfixGifs); + } + else if (param.isBugfix) { + title = 'šŸ› Bugfix Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.pullRequestBugfixGifs); + } + else if (param.isFeature) { + title = '✨ Feature Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.pullRequestFeatureGifs); + } + else if (param.isDocs) { + title = 'šŸ“ Documentation Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.pullRequestDocsGifs); + } + else if (param.isChore) { + title = 'šŸ”§ Chore Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.pullRequestChoreGifs); + } + else { + title = 'šŸŖ„ Automatic Actions'; + image = (0, list_utils_1.getRandomElement)(param.images.pullRequestAutomaticActions); + } + } + if (image) { + if (param.isIssue && param.images.imagesOnIssue) { + stupidGif = `![image](${image})`; + } + else if (param.isPullRequest && param.images.imagesOnPullRequest) { + stupidGif = `![image](${image})`; + } + } + let indexStep = 0; + param.currentConfiguration.results.forEach(r => { + for (const step of r.steps) { + content += `${indexStep + 1}. ${step}\n`; + indexStep++; + } + }); + let indexReminder = 0; + param.currentConfiguration.results.forEach(r => { + for (const reminder of r.reminders) { + footer += `${indexReminder + 1}. ${reminder}\n`; + indexReminder++; + } + }); + let indexError = 0; + param.currentConfiguration.results.forEach(r => { + for (const error of r.errors) { + errors += `${indexError + 1}. +\`\`\` +${error} +\`\`\` +`; + indexError++; + } + }); + if (footer.length > 0) { + footer = ` +## Reminder - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @function - * @param {number} value The number in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromNumber = fromNumber; +${footer} +`; + } + if (errors.length > 0) { + errors = ` +## Errors Found - /** - * @param {number} lowBits - * @param {number} highBits - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } +${errors} - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is - * assumed to use 32 bits. - * @function - * @param {number} lowBits The low 32 bits - * @param {number} highBits The high 32 bits - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromBits = fromBits; +Check your project configuration, if everything is okay consider [opening an issue](https://github.com/landamessenger/git-board-flow/issues/new/choose). +`; + } + const commentBody = `# ${title} +${content} +${errors.length > 0 ? errors : ''} - /** - * @function - * @param {number} base - * @param {number} exponent - * @returns {number} - * @inner - */ - var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) +${stupidGif} - /** - * @param {string} str - * @param {(boolean|number)=} unsigned - * @param {number=} radix - * @returns {!Long} - * @inner - */ - function fromString(str, unsigned, radix) { - if (str.length === 0) throw Error("empty string"); - if (typeof unsigned === "number") { - // For goog.math.long compatibility - radix = unsigned; - unsigned = false; - } else { - unsigned = !!unsigned; - } - if ( - str === "NaN" || - str === "Infinity" || - str === "+Infinity" || - str === "-Infinity" - ) - return unsigned ? UZERO : ZERO; - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - var p; - if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen"); - else if (p === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); - } +${footer} - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 8)); - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), - value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = fromNumber(pow_dbl(radix, size)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); +šŸš€ Happy coding! + `; + if (content.length === 0) { + return; + } + if (param.isSingleAction) { + await this.issueRepository.addComment(param.owner, param.repo, param.singleAction.issue, commentBody, param.tokens.token); + } + else if (param.isIssue) { + await this.issueRepository.addComment(param.owner, param.repo, param.issue.number, commentBody, param.tokens.token); + } + else if (param.isPullRequest) { + await this.issueRepository.addComment(param.owner, param.repo, param.pullRequest.number, commentBody, param.tokens.token); + } + } + catch (error) { + (0, logger_1.logError)(error); + param.currentConfiguration.results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to publish the resume, but there was a problem.`, + ], + error: error, + })); } - } - result.unsigned = unsigned; - return result; } +} +exports.PublishResultUseCase = PublishResultUseCase; - /** - * Returns a Long representation of the given string, written using the specified radix. - * @function - * @param {string} str The textual representation of the Long - * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed - * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 - * @returns {!Long} The corresponding Long value - */ - Long.fromString = fromString; - /** - * @function - * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromValue(val, unsigned) { - if (typeof val === "number") return fromNumber(val, unsigned); - if (typeof val === "string") return fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return fromBits( - val.low, - val.high, - typeof unsigned === "boolean" ? unsigned : val.unsigned, - ); - } +/***/ }), - /** - * Converts the specified value to a Long using the appropriate from* function for its type. - * @function - * @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} - */ - Long.fromValue = fromValue; +/***/ 678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be - // no runtime penalty for these. +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CodebaseAnalyzer = void 0; +const logger_1 = __nccwpck_require__(8836); +const constants_1 = __nccwpck_require__(8593); +/** + * Service for analyzing codebase structure and generating file descriptions + */ +class CodebaseAnalyzer { + constructor(aiRepository, fileImportAnalyzer, fileCacheManager) { + this.aiRepository = aiRepository; + this.fileImportAnalyzer = fileImportAnalyzer; + this.fileCacheManager = fileCacheManager; + } /** - * @type {number} - * @const - * @inner + * Generate codebase analysis with file descriptions and relationships + * This runs before the main reasoning loop to provide context + * Uses relationship map built from imports + AI descriptions in batches */ - var TWO_PWR_16_DBL = 1 << 16; + async generateCodebaseAnalysis(param, repositoryFiles, question) { + try { + // Filter relevant files (code files, not config/docs) + const codeExtensions = ['.ts', '.tsx', '.js', '.jsx', '.py', '.java', '.kt', '.go', '.rs', '.rb', '.php', '.swift', '.dart']; + const relevantFiles = Array.from(repositoryFiles.entries()) + .filter(([path]) => { + const ext = path.split('.').pop()?.toLowerCase() || ''; + return codeExtensions.includes(`.${ext}`) || + path.includes('/src/') || + path.includes('/lib/') || + path.includes('/usecase/') || + path.includes('/repository/'); + }); + if (relevantFiles.length === 0) { + (0, logger_1.logInfo)(`āš ļø No relevant code files found for analysis`); + return []; + } + (0, logger_1.logInfo)(`šŸ” Analyzing ${relevantFiles.length} relevant files for structure and relationships...`); + // STEP 0: Load cache from Supabase + const cache = await this.fileCacheManager.loadAICache(param); + // STEP 1: Build relationship map from imports (in memory, no AI needed) + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumesMap = relationshipMaps.consumes; + const consumedByMap = relationshipMaps.consumedBy; + // STEP 2: Identify files that need AI analysis (not in cache or SHA changed) + const filesNeedingAnalysis = []; + const cachedAnalyses = []; + let cacheMissReasons = { + notInCache: 0, + shaMismatch: 0 + }; + // Track files that should be in cache but aren't + const missingFromCache = []; + for (const [filePath, content] of relevantFiles) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const cached = this.fileCacheManager.getCachedFile(cache, filePath); + if (!cached) { + cacheMissReasons.notInCache++; + missingFromCache.push(filePath); + (0, logger_1.logDebugInfo)(`āŒ Cache miss for ${filePath} (not in cache)`); + filesNeedingAnalysis.push([filePath, content]); + } + else if (cached.sha !== currentSHA) { + cacheMissReasons.shaMismatch++; + (0, logger_1.logDebugInfo)(`šŸ”„ SHA mismatch for ${filePath}: cached=${cached.sha.substring(0, 8)}..., current=${currentSHA.substring(0, 8)}...`); + filesNeedingAnalysis.push([filePath, content]); + } + else { + // Use cached data + const consumes = consumesMap.get(filePath) || []; + const consumedBy = consumedByMap.get(filePath) || []; + cachedAnalyses.push({ + path: filePath, + description: cached.description, + consumes: consumes, + consumed_by: consumedBy + }); + } + } + (0, logger_1.logInfo)(`šŸ“Š Cache hit: ${cachedAnalyses.length} files, Need analysis: ${filesNeedingAnalysis.length} files (not in cache: ${cacheMissReasons.notInCache}, SHA mismatch: ${cacheMissReasons.shaMismatch})`); + // Debug: Show detailed cache comparison + if (cacheMissReasons.notInCache > 0) { + if (cache.size > 0) { + const sampleCachePaths = Array.from(cache.keys()).slice(0, 10); + const sampleMissingPaths = missingFromCache.slice(0, 10); + (0, logger_1.logDebugInfo)(`šŸ” Cache contains ${cache.size} files. Sample cached paths: ${sampleCachePaths.join(', ')}`); + (0, logger_1.logDebugInfo)(`šŸ” Sample missing paths (${missingFromCache.length} total): ${sampleMissingPaths.join(', ')}`); + // Check if any missing paths are similar to cached paths (normalization issue) + for (const missingPath of sampleMissingPaths.slice(0, 3)) { + const normalizedMissing = missingPath.replace(/^\.\//, '').replace(/\\/g, '/'); + const foundSimilar = sampleCachePaths.find(cached => cached.includes(normalizedMissing) || normalizedMissing.includes(cached)); + if (foundSimilar) { + (0, logger_1.logDebugInfo)(`āš ļø Potential path mismatch: missing="${missingPath}" vs cached="${foundSimilar}"`); + } + } + } + else { + (0, logger_1.logDebugInfo)(`āš ļø Cache is empty! All ${relevantFiles.length} files need analysis.`); + } + } + // STEP 3: Process files needing analysis in batches with AI (only for descriptions) + // Relationships come from the map we built + const BATCH_SIZE = 20; // Process 20 files at a time + const allAnalyses = [...cachedAnalyses]; + // Create simplified schema for AI (only needs description, relationships come from map) + const FILE_DESCRIPTION_SCHEMA = { + "type": "array", + "description": "Array of file descriptions", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File path relative to repository root" + }, + "description": { + "type": "string", + "description": "Complete description of what the file does" + } + }, + "required": ["path", "description"], + "additionalProperties": false + } + }; + for (let i = 0; i < filesNeedingAnalysis.length; i += BATCH_SIZE) { + const batch = filesNeedingAnalysis.slice(i, i + BATCH_SIZE); + const batchNumber = Math.floor(i / BATCH_SIZE) + 1; + const totalBatches = Math.ceil(relevantFiles.length / BATCH_SIZE); + (0, logger_1.logInfo)(`šŸ“ Processing batch ${batchNumber}/${totalBatches} (${batch.length} files)...`); + // Prepare batch content + const batchFilesList = batch.map(([path]) => path).join('\n'); + const batchContent = batch.map(([path, content]) => `\n## ${path}\n\`\`\`\n${content}\n\`\`\``).join('\n'); + const batchPrompt = `# Codebase Structure Analysis - Batch ${batchNumber}/${totalBatches} - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_24_DBL = 1 << 24; +You are analyzing a codebase to understand what each file does. - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +## User's Question: +${question} - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +## Files to Analyze in this batch (${batch.length} files): +${batchFilesList} - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +## File Contents: +${batchContent} - /** - * @type {!Long} - * @const - * @inner - */ - var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); +## Task: +For EACH of the ${batch.length} files listed above, - /** - * @type {!Long} - * @inner - */ - var ZERO = fromInt(0); +${constants_1.PROMPTS.CODE_BASE_ANALYSIS} - /** - * Signed zero. - * @type {!Long} - */ - Long.ZERO = ZERO; +Return a JSON array with this structure: +[ + { + "path": "src/path/to/file.ts", + "description": "description_here" + }, + ... +] +**REQUIREMENTS**: +- You MUST return a description for ALL ${batch.length} files in this batch`; + try { + const batchResponse = await this.aiRepository.askJson(param.ai, batchPrompt, FILE_DESCRIPTION_SCHEMA, "file_descriptions"); + if (batchResponse && Array.isArray(batchResponse)) { + // Merge AI descriptions with relationship map and update cache + for (const item of batchResponse) { + if (item && typeof item.path === 'string' && typeof item.description === 'string') { + const [filePath, content] = batch.find(([p]) => p === item.path) || [item.path, '']; + const currentSHA = filePath && content ? this.fileCacheManager.calculateFileSHA(content) : ''; + const consumes = consumesMap.get(item.path) || []; + const consumedBy = consumedByMap.get(item.path) || []; + allAnalyses.push({ + path: item.path, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }); + // Update cache + if (filePath && currentSHA) { + const cachedInfo = { + path: item.path, + sha: currentSHA, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(item.path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, item.path, cachedInfo, consumes, consumedBy); + } + } + } + (0, logger_1.logInfo)(`āœ… Processed batch ${batchNumber}/${totalBatches}: ${batchResponse.length} files`); + } + else { + (0, logger_1.logError)(`āš ļø Batch ${batchNumber} failed, using fallback descriptions`); + // Fallback for this batch + for (const [path, content] of batch) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const consumes = consumesMap.get(path) || []; + const consumedBy = consumedByMap.get(path) || []; + const fallbackDesc = this.generateBasicDescription(path); + allAnalyses.push({ + path, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }); + // Update cache with fallback + const cachedInfo = { + path, + sha: currentSHA, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, path, cachedInfo, consumes, consumedBy); + } + } + } + catch (error) { + (0, logger_1.logError)(`Error processing batch ${batchNumber}: ${error}`); + // Fallback for this batch + for (const [path, content] of batch) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const consumes = consumesMap.get(path) || []; + const consumedBy = consumedByMap.get(path) || []; + const fallbackDesc = this.generateBasicDescription(path); + allAnalyses.push({ + path, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }); + // Update cache with fallback + const cachedInfo = { + path, + sha: currentSHA, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, path, cachedInfo, consumes, consumedBy); + } + } + } + // STEP 4: Cache is saved incrementally during processing + // No need to save all at once since we're using Supabase + if (allAnalyses.length > 0) { + (0, logger_1.logInfo)(`āœ… Generated analysis for ${allAnalyses.length} files (${cachedAnalyses.length} from cache, ${filesNeedingAnalysis.length} from AI)`); + return allAnalyses; + } + // Fallback: Generate simple descriptions based on file paths and basic content + (0, logger_1.logInfo)(`āš ļø AI analysis failed, generating fallback descriptions...`); + const fallbackDescriptions = this.generateFallbackFileDescriptions(relevantFiles); + // Merge with relationship maps and update cache + const fallbackResults = await Promise.all(fallbackDescriptions.map(async (item) => { + const consumes = consumesMap.get(item.path) || []; + const consumedBy = consumedByMap.get(item.path) || []; + const content = repositoryFiles.get(item.path) || ''; + const currentSHA = content ? this.fileCacheManager.calculateFileSHA(content) : ''; + // Update cache + if (content && currentSHA) { + const cachedInfo = { + path: item.path, + sha: currentSHA, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(item.path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, item.path, cachedInfo, consumes, consumedBy); + } + return { + ...item, + consumes: consumes, + consumed_by: consumedBy + }; + })); + return fallbackResults; + } + catch (error) { + (0, logger_1.logError)(`Error generating codebase analysis: ${error}`); + // Fallback to simple path-based analysis + const relevantFiles = Array.from(repositoryFiles.entries()) + .filter(([path]) => path.includes('/src/') || path.includes('/lib/')); + const fallbackDescriptions = this.generateFallbackFileDescriptions(relevantFiles); + // Try to build relationship map even in fallback + try { + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumes = relationshipMaps.consumes; + const consumedBy = relationshipMaps.consumedBy; + return fallbackDescriptions.map(item => ({ + ...item, + consumes: consumes.get(item.path) || [], + consumed_by: consumedBy.get(item.path) || [] + })); + } + catch { + return fallbackDescriptions; + } + } + } /** - * @type {!Long} - * @inner + * Generate basic description from file path (fallback) */ - var UZERO = fromInt(0, true); - + generateBasicDescription(path) { + const pathParts = path.split('/'); + const fileName = pathParts[pathParts.length - 1]; + const dir = pathParts.slice(0, -1).join('/'); + if (path.includes('/usecase/')) { + return `Use case for ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles business logic and orchestrates operations.`; + } + else if (path.includes('/repository/')) { + return `Repository for ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles data access and external service interactions.`; + } + else if (path.includes('/model/')) { + return `Data model: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Defines data structures and interfaces.`; + } + else if (path.includes('/utils/')) { + return `Utility functions: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Provides helper functions and utilities.`; + } + else if (path.includes('/actions/')) { + return `Action handler: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles action execution and workflows.`; + } + else { + return `File: ${fileName}. Located in ${dir || 'root'}.`; + } + } /** - * Unsigned zero. - * @type {!Long} + * Generate fallback file descriptions when AI analysis fails */ - Long.UZERO = UZERO; - + generateFallbackFileDescriptions(files) { + const descriptions = []; + for (const [path] of files) { + const description = this.generateBasicDescription(path); + descriptions.push({ + path, + description, + consumes: [], // Will be filled by relationship map + consumed_by: [] // Will be filled by relationship map + }); + } + return descriptions; + } /** - * @type {!Long} - * @inner + * Format codebase analysis for inclusion in AI context */ - var ONE = fromInt(1); + formatCodebaseAnalysisForContext(analysis) { + if (analysis.length === 0) { + return ''; + } + const formatted = []; + formatted.push(`## šŸ“‹ Codebase Analysis & File Relationships\n\n`); + formatted.push(`This analysis provides context about the codebase structure to help you make informed decisions about which files to examine.\n\n`); + formatted.push(`**Relationship Types:**\n`); + formatted.push(`- **Consumes**: Files that this file imports/depends on\n`); + formatted.push(`- **Consumed By**: Files that import/depend on this file\n\n`); + // Group by directory for better organization + const byDirectory = new Map(); + analysis.forEach(item => { + const dir = item.path.split('/').slice(0, -1).join('/') || 'root'; + if (!byDirectory.has(dir)) { + byDirectory.set(dir, []); + } + byDirectory.get(dir).push(item); + }); + // Sort directories for consistent output + const sortedDirs = Array.from(byDirectory.keys()).sort(); + for (const dir of sortedDirs) { + const files = byDirectory.get(dir); + formatted.push(`### ${dir || 'Root'}\n\n`); + for (const file of files) { + formatted.push(`- **\`${file.path}\`**: ${file.description}`); + if (file.consumes && file.consumes.length > 0) { + formatted.push(`\n - *Consumes*: ${file.consumes.slice(0, 5).map(r => `\`${r}\``).join(', ')}${file.consumes.length > 5 ? '...' : ''}`); + } + if (file.consumed_by && file.consumed_by.length > 0) { + formatted.push(`\n - *Consumed By*: ${file.consumed_by.slice(0, 5).map(r => `\`${r}\``).join(', ')}${file.consumed_by.length > 5 ? '...' : ''}`); + } + formatted.push(`\n`); + } + formatted.push(`\n`); + } + formatted.push(`\n**Use this analysis to understand the codebase structure and identify relevant files for the task.**\n\n`); + return formatted.join(''); + } +} +exports.CodebaseAnalyzer = CodebaseAnalyzer; - /** - * Signed one. - * @type {!Long} - */ - Long.ONE = ONE; - /** - * @type {!Long} - * @inner - */ - var UONE = fromInt(1, true); +/***/ }), - /** - * Unsigned one. - * @type {!Long} - */ - Long.UONE = UONE; +/***/ 5788: +/***/ ((__unused_webpack_module, exports) => { - /** - * @type {!Long} - * @inner - */ - var NEG_ONE = fromInt(-1); +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CommentFormatter = void 0; +/** + * Service for formatting GitHub comments and code changes + */ +class CommentFormatter { + constructor() { + this.GITHUB_COMMENT_MAX_LENGTH = 65500; // Leave some margin below 65536 + } + /** + * Format the complete reasoning comment for GitHub + */ + formatReasoningComment(question, description, steps, analyzedFiles, proposedChanges, finalAnalysis, totalIterations, todoManager) { + let comment = ''; + // Header + comment += `# šŸ¤” AI Reasoning Analysis\n\n`; + if (question) { + comment += `## šŸ“ Question\n\n${question}\n\n`; + } + comment += `---\n\n`; + // MAIN CONTENT: Summary and conclusions + comment += `## šŸ“Š Analysis Summary\n\n`; + comment += `- **Total Iterations**: ${totalIterations}\n`; + comment += `- **Files Analyzed**: ${analyzedFiles.size}\n`; + comment += `- **Changes Proposed**: ${proposedChanges.length}\n`; + // TODO List Summary + const todoStats = todoManager.getStats(); + if (todoStats.total > 0) { + comment += `- **TODO Tasks**: ${todoStats.total} (${todoStats.completed} completed, ${todoStats.in_progress} in progress, ${todoStats.pending} pending)\n`; + } + comment += `\n---\n\n`; + // Final Analysis & Conclusions (main content) + if (finalAnalysis) { + comment += `## šŸŽÆ Final Analysis & Conclusions\n\n`; + comment += `${finalAnalysis}\n\n`; + comment += `---\n\n`; + } + else { + // Fallback summary if no final analysis + comment += `## šŸŽÆ Summary\n\n`; + comment += `Analysis completed after ${totalIterations} iterations. `; + comment += `Analyzed ${analyzedFiles.size} file${analyzedFiles.size !== 1 ? 's' : ''} and `; + comment += `proposed ${proposedChanges.length} change${proposedChanges.length !== 1 ? 's' : ''}.\n\n`; + comment += `---\n\n`; + } + // Proposed Changes (main content) + if (proposedChanges.length > 0) { + comment += `## šŸ’” Proposed Changes\n\n`; + proposedChanges.forEach((change, idx) => { + comment += this.formatProposedChange(change, idx + 1); + }); + comment += `\n---\n\n`; + } + else { + comment += `## šŸ’” Proposed Changes\n\n`; + comment += `No specific code changes were proposed. The analysis focused on understanding the codebase structure and requirements.\n\n`; + comment += `---\n\n`; + } + // Analyzed Files Summary (if relevant) + if (analyzedFiles.size > 0 && analyzedFiles.size <= 10) { + comment += `## šŸ“„ Analyzed Files\n\n`; + Array.from(analyzedFiles.values()).forEach(file => { + comment += `- **\`${file.path}\`** (${file.relevance} relevance): ${file.key_findings.substring(0, 200)}${file.key_findings.length > 200 ? '...' : ''}\n`; + }); + comment += `\n---\n\n`; + } + // TODO List Summary (if relevant) + if (todoStats.total > 0) { + comment += `## šŸ“‹ TODO List Summary\n\n`; + const completedTodos = todoManager.getTodosByStatus('completed'); + const activeTodos = todoManager.getActiveTodos(); + if (completedTodos.length > 0) { + comment += `### āœ… Completed Tasks\n\n`; + completedTodos.forEach(todo => { + comment += `- ${todo.content}\n`; + }); + comment += `\n`; + } + if (activeTodos.length > 0) { + comment += `### šŸ”„ Active/Pending Tasks\n\n`; + activeTodos.forEach(todo => { + comment += `- ${todo.status === 'in_progress' ? 'šŸ”„' : 'ā³'} ${todo.content}\n`; + }); + comment += `\n`; + } + comment += `---\n\n`; + } + // COLLAPSED SECTION: Detailed Reasoning Steps + comment += `
\nšŸ”„ Detailed Reasoning Steps (${steps.length} steps) - Click to expand\n\n`; + comment += `\n\n*This section contains the detailed step-by-step reasoning process. It's collapsed by default to keep the main analysis focused.*\n\n`; + comment += `---\n\n`; + let proposalIndex = 0; + const proposalShownFlags = new Set(); + for (const step of steps) { + comment += `### Step ${step.step_number}: ${this.getActionEmoji(step.action)} ${this.formatActionName(step.action)}\n\n`; + // Show reasoning (truncated for collapsed section) + if (step.reasoning) { + const reasoningText = step.reasoning.length > 500 + ? `${step.reasoning.substring(0, 500)}...` + : step.reasoning; + comment += `${reasoningText}\n\n`; + } + // Show files involved (simplified) + if (step.files_involved && step.files_involved.length > 0) { + const uniqueFiles = [...new Set(step.files_involved)]; + comment += `**Files**: ${uniqueFiles.map(f => `\`${f}\``).join(', ')}\n\n`; + } + // Show file analysis (simplified) + if (step.action === 'analyze_code' || step.action === 'read_file') { + const relevantFiles = Array.from(analyzedFiles.values()).filter(f => step.files_involved?.includes(f.path)); + const stepAnalysis = step.file_analysis_in_step; + const filesToShow = stepAnalysis || relevantFiles; + if (filesToShow.length > 0) { + comment += `**Analysis**: `; + filesToShow.forEach((file, idx) => { + if (idx > 0) + comment += ` | `; + comment += `\`${file.path}\` (${file.relevance}): ${file.key_findings.substring(0, 100)}${file.key_findings.length > 100 ? '...' : ''}`; + }); + comment += `\n\n`; + } + } + // Show proposals (simplified reference) + const stepProposals = step.proposals_in_step; + if (stepProposals && stepProposals.length > 0) { + comment += `**Proposed Changes**: ${stepProposals.map(c => `${c.change_type} \`${c.file_path}\``).join(', ')}\n\n`; + // Mark as shown + stepProposals.forEach((change) => { + const globalIndex = proposedChanges.indexOf(change); + if (globalIndex >= 0) { + proposalShownFlags.add(globalIndex); + } + }); + } + comment += `---\n\n`; + } + comment += `\n
\n\n`; + comment += `---\n\n`; + // Footer + comment += `*Analysis completed in ${totalIterations} iterations. Analyzed ${analyzedFiles.size} files and proposed ${proposedChanges.length} changes.*\n`; + // Truncate if too long + if (comment.length > this.GITHUB_COMMENT_MAX_LENGTH) { + // Try to keep main content, truncate collapsed section + const mainContent = comment.substring(0, comment.indexOf('
')); + const truncated = mainContent + `\n\n
\nšŸ”„ Detailed Reasoning Steps - Truncated due to length\n\n*Steps section was truncated due to comment length limits.*\n\n
\n\n`; + if (truncated.length > this.GITHUB_COMMENT_MAX_LENGTH) { + // If still too long, truncate main content + const finalTruncated = truncated.substring(0, this.GITHUB_COMMENT_MAX_LENGTH - 200); + return finalTruncated + `\n\n*[Comment truncated due to length limit]*\n`; + } + return truncated; + } + return comment; + } + /** + * Format a single proposed change + */ + formatProposedChange(change, index) { + let formatted = `### ${index}. ${this.getChangeTypeEmoji(change.change_type)} ${change.change_type.toUpperCase()}: \`${change.file_path}\`\n\n`; + formatted += `**Description**: ${change.description}\n\n`; + if (change.reasoning) { + formatted += `**Reasoning**: ${change.reasoning}\n\n`; + } + if (change.suggested_code) { + const language = this.detectLanguageFromPath(change.file_path); + formatted += `**Suggested Code**:\n\n`; + formatted += `\`\`\`${language}\n${change.suggested_code}\n\`\`\`\n\n`; + } + formatted += `---\n\n`; + return formatted; + } + /** + * Detect programming language from file path/extension + */ + detectLanguageFromPath(filePath) { + const extension = filePath.split('.').pop()?.toLowerCase() || ''; + const languageMap = { + // TypeScript/JavaScript + 'ts': 'typescript', + 'tsx': 'tsx', + 'js': 'javascript', + 'jsx': 'jsx', + 'mjs': 'javascript', + 'cjs': 'javascript', + // Python + 'py': 'python', + 'pyw': 'python', + 'pyi': 'python', + // Java/Kotlin + 'java': 'java', + 'kt': 'kotlin', + 'kts': 'kotlin', + // Go + 'go': 'go', + // Rust + 'rs': 'rust', + // C/C++ + 'c': 'c', + 'cpp': 'cpp', + 'cc': 'cpp', + 'cxx': 'cpp', + 'h': 'c', + 'hpp': 'cpp', + 'hxx': 'cpp', + // C# + 'cs': 'csharp', + // Ruby + 'rb': 'ruby', + // PHP + 'php': 'php', + // Swift + 'swift': 'swift', + // Dart + 'dart': 'dart', + // Shell + 'sh': 'bash', + 'bash': 'bash', + 'zsh': 'bash', + 'fish': 'fish', + // Configuration + 'json': 'json', + 'yaml': 'yaml', + 'yml': 'yaml', + 'toml': 'toml', + 'xml': 'xml', + 'ini': 'ini', + 'conf': 'conf', + 'config': 'conf', + // Markup + 'html': 'html', + 'htm': 'html', + 'css': 'css', + 'scss': 'scss', + 'sass': 'sass', + 'less': 'less', + 'md': 'markdown', + 'markdown': 'markdown', + // SQL + 'sql': 'sql', + // Docker + 'dockerfile': 'dockerfile', + 'docker': 'dockerfile', + // Other + 'txt': 'text', + 'log': 'text', + }; + // Check for exact match + if (languageMap[extension]) { + return languageMap[extension]; + } + // Check for Dockerfile (no extension) + if (filePath.toLowerCase().includes('dockerfile')) { + return 'dockerfile'; + } + // Default to empty string if unknown + return ''; + } /** - * Signed negative one. - * @type {!Long} + * Get emoji for action type */ - Long.NEG_ONE = NEG_ONE; - + getActionEmoji(action) { + const emojiMap = { + 'search_files': 'šŸ”', + 'read_file': 'šŸ“–', + 'analyze_code': 'šŸ”¬', + 'propose_changes': 'šŸ’”', + 'complete': 'āœ…' + }; + return emojiMap[action] || 'šŸ“'; + } /** - * @type {!Long} - * @inner + * Format action name for display */ - var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - + formatActionName(action) { + const nameMap = { + 'search_files': 'Search Files', + 'read_file': 'Read Files', + 'analyze_code': 'Analyze Code', + 'propose_changes': 'Propose Changes', + 'complete': 'Complete' + }; + return nameMap[action] || action; + } /** - * Maximum signed value. - * @type {!Long} + * Get emoji for change type */ - Long.MAX_VALUE = MAX_VALUE; + getChangeTypeEmoji(changeType) { + const emojiMap = { + 'create': '✨', + 'modify': 'šŸ“', + 'delete': 'šŸ—‘ļø', + 'refactor': 'ā™»ļø' + }; + return emojiMap[changeType] || 'šŸ“'; + } +} +exports.CommentFormatter = CommentFormatter; - /** - * @type {!Long} - * @inner - */ - var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true); - /** - * Maximum unsigned value. - * @type {!Long} - */ - Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; +/***/ }), - /** - * @type {!Long} - * @inner - */ - var MIN_VALUE = fromBits(0, 0x80000000 | 0, false); +/***/ 1855: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Minimum signed value. - * @type {!Long} - */ - Long.MIN_VALUE = MIN_VALUE; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileCacheManager = void 0; +const supabase_repository_1 = __nccwpck_require__(9829); +const logger_1 = __nccwpck_require__(8836); +const crypto_1 = __nccwpck_require__(6113); +/** + * Service for managing AI file cache in Supabase + */ +class FileCacheManager { + constructor() { + this.supabaseRepository = null; + } /** - * @alias Long.prototype - * @inner + * Normalize file path for consistent comparison + * Removes leading ./ and normalizes path separators */ - var LongPrototype = Long.prototype; - + normalizePath(path) { + return path + .replace(/^\.\//, '') // Remove leading ./ + .replace(/\\/g, '/') // Normalize separators + .trim(); + } /** - * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. - * @this {!Long} - * @returns {number} + * Calculate SHA256 hash of file content */ - LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - }; - + calculateFileSHA(content) { + return (0, crypto_1.createHash)('sha256').update(content).digest('hex'); + } /** - * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). - * @this {!Long} - * @returns {number} + * Initialize Supabase repository if config is available */ - LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - + initSupabaseRepository(param) { + if (!this.supabaseRepository && param.supabaseConfig) { + this.supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + } + return this.supabaseRepository; + } /** - * Converts the Long to a string written in the specified radix. - * @this {!Long} - * @param {number=} radix Radix (2-36), defaults to 10 - * @returns {string} - * @override - * @throws {RangeError} If `radix` is out of range + * Load cache from Supabase (or return empty map if Supabase not available) + * Uses normalized paths for consistent lookup */ - LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - if (this.isZero()) return "0"; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = fromNumber(radix), - div = this.div(radixLong), - rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else return "-" + this.neg().toString(radix); - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), - rem = this; - var result = ""; - while (true) { - var remDiv = rem.div(radixToPower), - intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, - digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) return digits + result; - else { - while (digits.length < 6) digits = "0" + digits; - result = "" + digits + result; + async loadAICache(param) { + this.initSupabaseRepository(param); + const cache = new Map(); + if (!this.supabaseRepository) { + (0, logger_1.logInfo)(`šŸ“‚ Supabase not configured, starting with empty cache`); + return cache; } - } - }; - + try { + const branch = param.commit.branch || param.branches.main; + const cachedFiles = await this.supabaseRepository.getAIFileCachesByBranch(param.owner, param.repo, branch); + for (const file of cachedFiles) { + const normalizedPath = this.normalizePath(file.path); + cache.set(normalizedPath, { + path: normalizedPath, + sha: file.sha, + description: file.description, + consumes: (file.consumes || []).map(p => this.normalizePath(p)), + consumed_by: (file.consumed_by || []).map(p => this.normalizePath(p)) + }); + } + (0, logger_1.logInfo)(`šŸ“‚ Loaded ${cache.size} files from Supabase cache`); + if (cachedFiles.length > 0) { + (0, logger_1.logDebugInfo)(`šŸ“‚ Sample cached paths: ${Array.from(cache.keys()).slice(0, 5).join(', ')}`); + } + } + catch (error) { + (0, logger_1.logError)(`Error loading AI cache from Supabase: ${error}`); + } + return cache; + } /** - * Gets the high 32 bits as a signed integer. - * @this {!Long} - * @returns {number} Signed high bits + * Get cached file info by path (with path normalization) */ - LongPrototype.getHighBits = function getHighBits() { - return this.high; - }; - + getCachedFile(cache, filePath) { + const normalizedPath = this.normalizePath(filePath); + return cache.get(normalizedPath); + } /** - * Gets the high 32 bits as an unsigned integer. - * @this {!Long} - * @returns {number} Unsigned high bits + * Save cache entry to Supabase + * Normalizes paths before saving */ - LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; - }; + async saveAICacheEntry(param, filePath, fileInfo, consumes, consumedBy) { + this.initSupabaseRepository(param); + if (!this.supabaseRepository) { + return; // Silently skip if Supabase not available + } + try { + const branch = param.commit.branch || param.branches.main; + const fileName = filePath.split('/').pop() || filePath; + const normalizedPath = this.normalizePath(filePath); + const normalizedConsumes = consumes.map(p => this.normalizePath(p)); + const normalizedConsumedBy = consumedBy.map(p => this.normalizePath(p)); + await this.supabaseRepository.setAIFileCache(param.owner, param.repo, branch, { + file_name: fileName, + path: normalizedPath, + sha: fileInfo.sha, + description: fileInfo.description, + consumes: normalizedConsumes, + consumed_by: normalizedConsumedBy + }); + (0, logger_1.logDebugInfo)(`šŸ’¾ Saved cache entry for ${normalizedPath}`); + } + catch (error) { + (0, logger_1.logError)(`Error saving AI cache entry to Supabase for ${filePath}: ${error}`); + } + } +} +exports.FileCacheManager = FileCacheManager; - /** - * Gets the low 32 bits as a signed integer. - * @this {!Long} - * @returns {number} Signed low bits - */ - LongPrototype.getLowBits = function getLowBits() { - return this.low; - }; - /** - * Gets the low 32 bits as an unsigned integer. - * @this {!Long} - * @returns {number} Unsigned low bits - */ - LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; - }; +/***/ }), - /** - * Gets the number of bits needed to represent the absolute value of this Long. - * @this {!Long} - * @returns {number} - */ - LongPrototype.getNumBitsAbs = function getNumBitsAbs() { - if (this.isNegative()) - // Unsigned Longs are never negative - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break; - return this.high != 0 ? bit + 33 : bit + 1; - }; +/***/ 5310: +/***/ ((__unused_webpack_module, exports) => { - /** - * Tests if this Long can be safely represented as a JavaScript number. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isSafeInteger = function isSafeInteger() { - // 2^53-1 is the maximum safe value - var top11Bits = this.high >> 21; - // [0, 2^53-1] - if (!top11Bits) return true; - // > 2^53-1 - if (this.unsigned) return false; - // [-2^53, -1] except -2^53 - return top11Bits === -1 && !(this.low === 0 && this.high === -0x200000); - }; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileImportAnalyzer = void 0; +/** + * Service for extracting imports and building file relationship maps + * Supports multiple programming languages + */ +class FileImportAnalyzer { + /** + * Extract imports from a file regardless of programming language + */ + extractImportsFromFile(filePath, content) { + const imports = []; + const ext = filePath.split('.').pop()?.toLowerCase() || ''; + const dir = filePath.split('/').slice(0, -1).join('/') || ''; + // TypeScript/JavaScript + if (['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs'].includes(ext)) { + // import ... from '...' + const es6Imports = content.match(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g) || []; + es6Imports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + // require('...') + const requireImports = content.match(/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g) || []; + requireImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // Python + if (['py', 'pyw', 'pyi'].includes(ext)) { + // import ... / from ... import ... + const pyImports = content.match(/(?:^|\n)\s*(?:import\s+\w+|from\s+[\w.]+)\s+import/gm) || []; + pyImports.forEach(match => { + const fromMatch = match.match(/from\s+([\w.]+)/); + if (fromMatch) { + imports.push(fromMatch[1]); + } + else { + const importMatch = match.match(/import\s+(\w+)/); + if (importMatch) + imports.push(importMatch[1]); + } + }); + } + // Java + if (ext === 'java') { + const javaImports = content.match(/import\s+(?:static\s+)?[\w.]+\s*;/g) || []; + javaImports.forEach(match => { + const path = match.replace(/import\s+(?:static\s+)?/, '').replace(/\s*;/, ''); + imports.push(path); + }); + } + // Kotlin + if (['kt', 'kts'].includes(ext)) { + const ktImports = content.match(/import\s+[\w.]+\s*/g) || []; + ktImports.forEach(match => { + const path = match.replace(/import\s+/, '').trim(); + imports.push(path); + }); + } + // Go + if (ext === 'go') { + const goImports = content.match(/import\s*(?:\([^)]+\)|['"]([^'"]+)['"])/gs) || []; + goImports.forEach(match => { + const quoted = match.match(/['"]([^'"]+)['"]/); + if (quoted) { + imports.push(quoted[1]); + } + else { + // Multi-line import block + const multiLine = match.match(/import\s*\(([^)]+)\)/s); + if (multiLine) { + const paths = multiLine[1].match(/['"]([^'"]+)['"]/g) || []; + paths.forEach(p => { + const path = p.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + } + }); + } + // Rust + if (ext === 'rs') { + const rustImports = content.match(/use\s+[\w:]+(?:::\*)?\s*;/g) || []; + rustImports.forEach(match => { + const path = match.replace(/use\s+/, '').replace(/\s*;/, '').split('::')[0]; + imports.push(path); + }); + } + // Ruby + if (ext === 'rb') { + const rubyImports = content.match(/(?:require|require_relative)\s+['"]([^'"]+)['"]/g) || []; + rubyImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // PHP + if (ext === 'php') { + const phpImports = content.match(/(?:use|require|include)(?:_once)?\s+['"]([^'"]+)['"]/g) || []; + phpImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // Swift + if (ext === 'swift') { + const swiftImports = content.match(/import\s+\w+/g) || []; + swiftImports.forEach(match => { + const path = match.replace(/import\s+/, ''); + imports.push(path); + }); + } + // Dart + if (ext === 'dart') { + const dartImports = content.match(/import\s+['"]([^'"]+)['"]/g) || []; + dartImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) + imports.push(path); + }); + } + // Resolve relative imports to absolute paths + return imports.map(imp => { + // Skip external packages (node_modules, stdlib, etc.) + if (!imp.startsWith('.') && !imp.startsWith('/')) { + // Try to resolve relative to current file + if (dir) { + // Check if it's a relative path that needs resolution + const possiblePath = `${dir}/${imp}`.replace(/\/+/g, '/'); + return possiblePath; + } + return imp; + } + // Resolve relative paths + if (imp.startsWith('.')) { + const resolved = this.resolveRelativePath(dir, imp); + return resolved; + } + return imp; + }).filter(imp => imp && !imp.includes('node_modules') && !imp.startsWith('http')); + } /** - * Tests if this Long's value equals zero. - * @this {!Long} - * @returns {boolean} + * Resolve relative import path to absolute path */ - LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; - }; + resolveRelativePath(baseDir, relativePath) { + if (!relativePath.startsWith('.')) { + return relativePath; + } + let path = baseDir || ''; + const parts = relativePath.split('/'); + for (const part of parts) { + if (part === '..') { + path = path.split('/').slice(0, -1).join('/'); + } + else if (part === '.' || part === '') { + // Current directory, do nothing + } + else { + path = path ? `${path}/${part}` : part; + } + } + // Remove file extension if present and add common extensions + const withoutExt = path.replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, ''); + return withoutExt; + } + /** + * Build relationship map from all files by extracting imports + * Also builds reverse map (consumed_by) + */ + buildRelationshipMap(repositoryFiles) { + const consumesMap = new Map(); + const consumedByMap = new Map(); + // Initialize consumedBy map for all files + for (const filePath of repositoryFiles.keys()) { + consumedByMap.set(filePath, []); + } + for (const [filePath, content] of repositoryFiles.entries()) { + const imports = this.extractImportsFromFile(filePath, content); + // Resolve imports to actual file paths in the repository + const resolvedImports = []; + for (const imp of imports) { + // Try to find matching file in repository + const possiblePaths = [ + imp, + `${imp}.ts`, + `${imp}.tsx`, + `${imp}.js`, + `${imp}.jsx`, + `${imp}/index.ts`, + `${imp}/index.tsx`, + `${imp}/index.js`, + `${imp}/index.jsx`, + ]; + for (const possiblePath of possiblePaths) { + // Check exact match + if (repositoryFiles.has(possiblePath)) { + if (!resolvedImports.includes(possiblePath)) { + resolvedImports.push(possiblePath); + } + // Update reverse map + const currentConsumers = consumedByMap.get(possiblePath) || []; + if (!currentConsumers.includes(filePath)) { + currentConsumers.push(filePath); + consumedByMap.set(possiblePath, currentConsumers); + } + break; + } + // Check if any file path contains this import + for (const [repoPath] of repositoryFiles.entries()) { + if (repoPath.includes(possiblePath) || possiblePath.includes(repoPath)) { + if (!resolvedImports.includes(repoPath)) { + resolvedImports.push(repoPath); + } + // Update reverse map + const currentConsumers = consumedByMap.get(repoPath) || []; + if (!currentConsumers.includes(filePath)) { + currentConsumers.push(filePath); + consumedByMap.set(repoPath, currentConsumers); + } + } + } + } + } + consumesMap.set(filePath, resolvedImports); + } + return { consumes: consumesMap, consumedBy: consumedByMap }; + } +} +exports.FileImportAnalyzer = FileImportAnalyzer; - /** - * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. - * @returns {boolean} - */ - LongPrototype.eqz = LongPrototype.isZero; - /** - * Tests if this Long's value is negative. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; - }; +/***/ }), - /** - * Tests if this Long's value is positive or zero. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; - }; +/***/ 9810: +/***/ ((__unused_webpack_module, exports) => { - /** - * Tests if this Long's value is odd. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; - }; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.FileSearchService = void 0; +/** + * Service for building file indexes and searching files + */ +class FileSearchService { /** - * Tests if this Long's value is even. - * @this {!Long} - * @returns {boolean} + * Build file index for quick lookup by filename or directory */ - LongPrototype.isEven = function isEven() { - return (this.low & 1) === 0; - }; - + buildFileIndex(files) { + const index = new Map(); + for (const [path, content] of files.entries()) { + const pathParts = path.split('/'); + const fileName = pathParts[pathParts.length - 1]; + // Index by filename + if (!index.has(fileName)) { + index.set(fileName, []); + } + index.get(fileName).push(path); + // Index by directory + if (pathParts.length > 1) { + const dir = pathParts.slice(0, -1).join('/'); + if (!index.has(dir)) { + index.set(dir, []); + } + index.get(dir).push(path); + } + } + return index; + } /** - * Tests if this Long's value equals the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} + * Search files by search terms (filename, directory, or pattern) */ - LongPrototype.equals = function equals(other) { - if (!isLong(other)) other = fromValue(other); - if ( - this.unsigned !== other.unsigned && - this.high >>> 31 === 1 && - other.high >>> 31 === 1 - ) - return false; - return this.high === other.high && this.low === other.low; - }; + searchFiles(searchTerms, fileIndex) { + const foundFiles = new Set(); + for (const term of searchTerms) { + // Exact filename match + if (fileIndex.has(term)) { + fileIndex.get(term).forEach(f => foundFiles.add(f)); + } + // Directory match + if (fileIndex.has(term)) { + fileIndex.get(term).forEach(f => foundFiles.add(f)); + } + // Pattern match (simple contains) + for (const [key, paths] of fileIndex.entries()) { + if (key.toLowerCase().includes(term.toLowerCase())) { + paths.forEach(p => foundFiles.add(p)); + } + // Also check paths + paths.forEach(path => { + if (path.toLowerCase().includes(term.toLowerCase())) { + foundFiles.add(path); + } + }); + } + } + return Array.from(foundFiles); + } +} +exports.FileSearchService = FileSearchService; - /** - * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.eq = LongPrototype.equals; - /** - * Tests if this Long's value differs from the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.notEquals = function notEquals(other) { - return !this.eq(/* validates */ other); - }; +/***/ }), - /** - * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.neq = LongPrototype.notEquals; +/***/ 9714: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.ne = LongPrototype.notEquals; +"use strict"; - /** - * Tests if this Long's value is less than the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThan = function lessThan(other) { - return this.comp(/* validates */ other) < 0; - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.StoreConfigurationUseCase = void 0; +const configuration_handler_1 = __nccwpck_require__(4509); +const logger_1 = __nccwpck_require__(8836); +/** + * Store las configuration in the description + */ +class StoreConfigurationUseCase { + constructor() { + this.taskId = 'StoreConfigurationUseCase'; + this.handler = new configuration_handler_1.ConfigurationHandler(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + try { + await this.handler.update(param); + } + catch (error) { + (0, logger_1.logError)(error); + } + } +} +exports.StoreConfigurationUseCase = StoreConfigurationUseCase; - /** - * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lt = LongPrototype.lessThan; - /** - * Tests if this Long's value is less than or equal the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp(/* validates */ other) <= 0; - }; +/***/ }), - /** - * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lte = LongPrototype.lessThanOrEqual; +/***/ 8785: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.le = LongPrototype.lessThanOrEqual; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ThinkCodeManager = void 0; +const logger_1 = __nccwpck_require__(8836); +/** + * Manages virtual code state - keeps files in memory and applies proposed changes + * so subsequent reasoning steps can see the accumulated progress + */ +class ThinkCodeManager { + constructor() { + this.originalFiles = new Map(); + this.virtualFiles = new Map(); + this.appliedChanges = new Map(); // file -> changes applied + this.allAppliedChanges = []; + } /** - * Tests if this Long's value is greater than the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} + * Initialize with original repository files */ - LongPrototype.greaterThan = function greaterThan(other) { - return this.comp(/* validates */ other) > 0; - }; - + initialize(originalFiles) { + this.originalFiles = new Map(originalFiles); + this.virtualFiles = new Map(originalFiles); + this.appliedChanges.clear(); + this.allAppliedChanges = []; + (0, logger_1.logInfo)(`šŸ“¦ Code manager initialized with ${originalFiles.size} files`); + } /** - * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} + * Get current state of a file (with applied changes) */ - LongPrototype.gt = LongPrototype.greaterThan; - + getFileContent(filePath) { + return this.virtualFiles.get(filePath); + } /** - * Tests if this Long's value is greater than or equal the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} + * Get all virtual files */ - LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp(/* validates */ other) >= 0; - }; - + getAllFiles() { + return new Map(this.virtualFiles); + } /** - * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} + * Check if a file has been modified */ - LongPrototype.gte = LongPrototype.greaterThanOrEqual; - + isFileModified(filePath) { + return this.appliedChanges.has(filePath); + } /** - * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} + * Get changes applied to a specific file */ - LongPrototype.ge = LongPrototype.greaterThanOrEqual; - + getFileChanges(filePath) { + return this.appliedChanges.get(filePath) || []; + } /** - * Compares this Long's value with the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater + * Apply a proposed change to the virtual codebase */ - LongPrototype.compare = function compare(other) { - if (!isLong(other)) other = fromValue(other); - if (this.eq(other)) return 0; - var thisNeg = this.isNegative(), - otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) return -1; - if (!thisNeg && otherNeg) return 1; - // At this point the sign bits are the same - if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; - + applyChange(change) { + try { + const filePath = change.file_path; + const currentContent = this.virtualFiles.get(filePath) || ''; + let newContent = currentContent; + switch (change.change_type) { + case 'create': + if (!currentContent) { + // File doesn't exist, create it with suggested code + newContent = change.suggested_code || ''; + (0, logger_1.logDebugInfo)(`āœ… Created virtual file: ${filePath}`); + } + else { + (0, logger_1.logDebugInfo)(`āš ļø File ${filePath} already exists, skipping create`); + return false; + } + break; + case 'modify': + if (currentContent) { + // Apply modification - for now, append suggested code + // In a more sophisticated implementation, we could parse and merge + if (change.suggested_code) { + // Simple strategy: append the suggested code with a marker + newContent = `${currentContent}\n\n// === AI Proposed Modification ===\n${change.suggested_code}`; + (0, logger_1.logDebugInfo)(`āœ… Modified virtual file: ${filePath}`); + } + else { + // Just note the modification + newContent = `${currentContent}\n\n// === AI Proposed Modification: ${change.description} ===`; + (0, logger_1.logDebugInfo)(`āœ… Noted modification in virtual file: ${filePath}`); + } + } + else { + (0, logger_1.logDebugInfo)(`āš ļø Cannot modify non-existent file: ${filePath}`); + return false; + } + break; + case 'delete': + // Mark as deleted but keep for reference + newContent = `// === FILE MARKED FOR DELETION ===\n// Original content:\n${currentContent}`; + (0, logger_1.logDebugInfo)(`āœ… Marked virtual file for deletion: ${filePath}`); + break; + case 'refactor': + if (currentContent && change.suggested_code) { + // Refactor: replace with new code + newContent = `${currentContent}\n\n// === AI Proposed Refactoring ===\n${change.suggested_code}`; + (0, logger_1.logDebugInfo)(`āœ… Refactored virtual file: ${filePath}`); + } + else { + (0, logger_1.logDebugInfo)(`āš ļø Cannot refactor file ${filePath}: ${currentContent ? 'no suggested code' : 'file does not exist'}`); + return false; + } + break; + default: + (0, logger_1.logDebugInfo)(`āš ļø Unknown change type: ${change.change_type}`); + return false; + } + this.virtualFiles.set(filePath, newContent); + // Track applied changes + if (!this.appliedChanges.has(filePath)) { + this.appliedChanges.set(filePath, []); + } + this.appliedChanges.get(filePath).push(change); + this.allAppliedChanges.push(change); + return true; + } + catch (error) { + (0, logger_1.logDebugInfo)(`āŒ Error applying change to ${change.file_path}: ${error}`); + return false; + } + } /** - * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater + * Check if a change has already been applied (to avoid duplicates) */ - LongPrototype.comp = LongPrototype.compare; - + hasChangeBeenApplied(change) { + // Check by file path and description similarity + const existingChanges = this.allAppliedChanges.filter(c => c.file_path === change.file_path && + c.change_type === change.change_type && + this.areSimilar(c.description, change.description)); + return existingChanges.length > 0; + } /** - * Negates this Long's value. - * @this {!Long} - * @returns {!Long} Negated Long + * Get summary of all applied changes */ - LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; - return this.not().add(ONE); - }; - + getChangesSummary() { + if (this.allAppliedChanges.length === 0) { + return 'No changes applied yet.'; + } + const summary = []; + summary.push(`\n## Applied Changes (${this.allAppliedChanges.length} total):\n`); + for (const [filePath, changes] of this.appliedChanges.entries()) { + summary.push(`\n### ${filePath} (${changes.length} change${changes.length > 1 ? 's' : ''}):`); + changes.forEach((change, idx) => { + summary.push(` ${idx + 1}. ${change.change_type.toUpperCase()}: ${change.description}`); + }); + } + return summary.join('\n'); + } /** - * Negates this Long's value. This is an alias of {@link Long#negate}. - * @function - * @returns {!Long} Negated Long + * Get context about what has changed for the AI */ - LongPrototype.neg = LongPrototype.negate; - + getContextForAI() { + const context = []; + if (this.allAppliedChanges.length > 0) { + context.push(`\n## Code State Changes Applied:`); + context.push(`Total changes applied: ${this.allAppliedChanges.length}`); + context.push(`Files modified: ${this.appliedChanges.size}`); + context.push(this.getChangesSummary()); + // Show modified file contents summary + context.push(`\n## Modified Files Preview:`); + for (const [filePath, changes] of this.appliedChanges.entries()) { + const currentContent = this.virtualFiles.get(filePath); + if (currentContent) { + const preview = currentContent.substring(0, 500); + context.push(`\n### ${filePath}:`); + context.push(`\`\`\`\n${preview}${currentContent.length > 500 ? '\n... (truncated)' : ''}\n\`\`\``); + } + } + } + else { + context.push(`\n## Code State: No changes applied yet.`); + } + return context.join('\n'); + } /** - * Returns the sum of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} addend Addend - * @returns {!Long} Sum + * Simple similarity check for change descriptions */ - LongPrototype.add = function add(addend) { - if (!isLong(addend)) addend = fromValue(addend); - - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - + areSimilar(desc1, desc2) { + const normalize = (s) => s.toLowerCase().trim().replace(/\s+/g, ' '); + const n1 = normalize(desc1); + const n2 = normalize(desc2); + // Exact match + if (n1 === n2) + return true; + // Check if one contains the other (for similar proposals) + if (n1.length > 20 && n2.length > 20) { + const words1 = n1.split(' ').filter(w => w.length > 3); + const words2 = n2.split(' ').filter(w => w.length > 3); + const commonWords = words1.filter(w => words2.includes(w)); + // If 70% of significant words match, consider similar + return commonWords.length / Math.max(words1.length, words2.length) > 0.7; + } + return false; + } /** - * Returns the difference of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} subtrahend Subtrahend - * @returns {!Long} Difference + * Get statistics */ - LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; + getStats() { + return { + totalFiles: this.virtualFiles.size, + modifiedFiles: this.appliedChanges.size, + totalChanges: this.allAppliedChanges.length + }; + } +} +exports.ThinkCodeManager = ThinkCodeManager; - /** - * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. - * @function - * @param {!Long|number|bigint|string} subtrahend Subtrahend - * @returns {!Long} Difference - */ - LongPrototype.sub = LongPrototype.subtract; - /** - * Returns the product of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.multiply = function multiply(multiplier) { - if (this.isZero()) return this; - if (!isLong(multiplier)) multiplier = fromValue(multiplier); - - // use wasm support if present - if (wasm) { - var low = wasm["mul"]( - this.low, - this.high, - multiplier.low, - multiplier.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO; - if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); - else return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - - // If both longs are small, use float multiplication - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber( - this.toNumber() * multiplier.toNumber(), - this.unsigned, - ); +/***/ }), - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; +/***/ 3618: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. - * @function - * @param {!Long|number|bigint|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.mul = LongPrototype.multiply; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ThinkTodoManager = void 0; +const logger_1 = __nccwpck_require__(8836); +/** + * Manages TODO list for the reasoning process + * Similar to how the assistant tracks high-level tasks vs iterative steps + */ +class ThinkTodoManager { + constructor() { + this.todos = new Map(); + this.nextId = 1; + } /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or - * unsigned if this Long is unsigned. - * @this {!Long} - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Quotient + * Initialize with optional initial todos */ - LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - if (divisor.isZero()) throw Error("division by zero"); - - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if ( - !this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1 - ) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( - this.low, - this.high, - divisor.low, - divisor.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (this.isZero()) return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(MIN_VALUE)) return ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; + initialize(initialTodos) { + this.todos.clear(); + this.nextId = 1; + if (initialTodos && initialTodos.length > 0) { + for (const todo of initialTodos) { + this.createTodo(todo.content, todo.status || 'pending'); } - } - } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) divisor = divisor.toUnsigned(); - if (divisor.gt(this)) return UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return UONE; - res = UZERO; - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2), - delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - approxRes = fromNumber(approx), - approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) approxRes = ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - + (0, logger_1.logInfo)(`šŸ“‹ TODO list initialized with ${initialTodos.length} tasks`); + } + else { + (0, logger_1.logInfo)(`šŸ“‹ TODO list initialized (empty)`); + } + } /** - * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Quotient + * Create a new TODO item */ - LongPrototype.div = LongPrototype.divide; - + createTodo(content, status = 'pending') { + const id = `todo_${this.nextId++}`; + const now = Date.now(); + const todo = { + id, + content, + status, + created_at: now, + updated_at: now + }; + this.todos.set(id, todo); + (0, logger_1.logDebugInfo)(`āœ… Created TODO: ${content} (${status})`); + return todo; + } /** - * Returns this Long modulo the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder + * Update an existing TODO item */ - LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( - this.low, - this.high, - divisor.low, - divisor.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - + updateTodo(id, updates) { + const todo = this.todos.get(id); + if (!todo) { + (0, logger_1.logDebugInfo)(`āš ļø TODO ${id} not found for update`); + return false; + } + const now = Date.now(); + const oldStatus = todo.status; + if (updates.status) { + todo.status = updates.status; + if (updates.status === 'completed' && !todo.completed_at) { + todo.completed_at = now; + } + } + if (updates.notes !== undefined) { + todo.notes = updates.notes; + } + if (updates.related_files) { + todo.related_files = updates.related_files; + } + if (updates.related_changes) { + todo.related_changes = updates.related_changes; + } + todo.updated_at = now; + if (oldStatus !== todo.status) { + (0, logger_1.logInfo)(`šŸ“ Updated TODO ${id}: ${oldStatus} → ${todo.status}`); + } + else { + (0, logger_1.logDebugInfo)(`šŸ“ Updated TODO ${id} (notes/metadata)`); + } + return true; + } /** - * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder + * Get all TODOs */ - LongPrototype.mod = LongPrototype.modulo; - + getAllTodos() { + return Array.from(this.todos.values()).sort((a, b) => a.created_at - b.created_at); + } /** - * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder + * Get TODOs by status */ - LongPrototype.rem = LongPrototype.modulo; - + getTodosByStatus(status) { + return this.getAllTodos().filter(todo => todo.status === status); + } /** - * Returns the bitwise NOT of this Long. - * @this {!Long} - * @returns {!Long} + * Get active TODOs (pending or in_progress) */ - LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); - }; - + getActiveTodos() { + return this.getAllTodos().filter(todo => todo.status === 'pending' || todo.status === 'in_progress'); + } /** - * Returns count leading zeros of this Long. - * @this {!Long} - * @returns {!number} + * Get completion statistics */ - LongPrototype.countLeadingZeros = function countLeadingZeros() { - return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; - }; - + getStats() { + const all = this.getAllTodos(); + const pending = all.filter(t => t.status === 'pending').length; + const in_progress = all.filter(t => t.status === 'in_progress').length; + const completed = all.filter(t => t.status === 'completed').length; + const cancelled = all.filter(t => t.status === 'cancelled').length; + const total = all.length; + const completion_rate = total > 0 ? (completed / total) * 100 : 0; + return { + total, + pending, + in_progress, + completed, + cancelled, + completion_rate + }; + } /** - * Returns count leading zeros. This is an alias of {@link Long#countLeadingZeros}. - * @function - * @param {!Long} - * @returns {!number} - */ - LongPrototype.clz = LongPrototype.countLeadingZeros; - + * Get formatted TODO list for AI context + */ + getContextForAI() { + const stats = this.getStats(); + const activeTodos = this.getActiveTodos(); + const completedTodos = this.getTodosByStatus('completed').slice(-5); // Last 5 completed + const allTodos = this.getAllTodos(); + const context = []; + context.push(`\n## šŸ“‹ TODO List Status`); + context.push(`- **Total Tasks**: ${stats.total}`); + context.push(`- **Pending**: ${stats.pending}`); + context.push(`- **In Progress**: ${stats.in_progress}`); + context.push(`- **Completed**: ${stats.completed} (${stats.completion_rate.toFixed(1)}%)`); + context.push(`- **Cancelled**: ${stats.cancelled}`); + if (allTodos.length > 0) { + context.push(`\n### šŸ“ All TODO Items (with IDs for reference):`); + allTodos.forEach((todo, idx) => { + const statusEmoji = todo.status === 'completed' ? 'āœ…' : + todo.status === 'in_progress' ? 'šŸ”„' : + todo.status === 'cancelled' ? 'āŒ' : 'ā³'; + context.push(`${idx + 1}. ${statusEmoji} **[ID: ${todo.id}]** ${todo.status.toUpperCase()}: ${todo.content}`); + if (todo.related_files && todo.related_files.length > 0) { + context.push(` šŸ“ Related files: ${todo.related_files.join(', ')}`); + } + if (todo.notes) { + context.push(` šŸ“ Notes: ${todo.notes}`); + } + }); + context.push(`\n**āš ļø IMPORTANT**: When updating TODOs, use the EXACT ID shown above (e.g., "${allTodos[0]?.id || 'todo_1'}"). Do NOT use numeric IDs like "1" or "2".`); + } + if (activeTodos.length > 0) { + context.push(`\n### šŸ”„ Active Tasks to Work On (${activeTodos.length}):`); + activeTodos.forEach((todo, idx) => { + const statusEmoji = todo.status === 'in_progress' ? 'šŸ”„' : 'ā³'; + context.push(`${idx + 1}. ${statusEmoji} **[ID: ${todo.id}]** ${todo.status.toUpperCase()}: ${todo.content}`); + if (todo.related_files && todo.related_files.length > 0) { + context.push(` šŸ“ Related files: ${todo.related_files.join(', ')}`); + } + if (todo.notes) { + context.push(` šŸ“ Notes: ${todo.notes}`); + } + }); + } + if (completedTodos.length > 0) { + context.push(`\n### āœ… Recently Completed (${completedTodos.length}):`); + completedTodos.forEach((todo, idx) => { + context.push(`${idx + 1}. āœ… **[ID: ${todo.id}]** ${todo.content}`); + }); + } + if (activeTodos.length === 0 && stats.total > 0) { + context.push(`\nšŸŽ‰ All tasks completed!`); + } + return context.join('\n'); + } /** - * Returns count trailing zeros of this Long. - * @this {!Long} - * @returns {!number} + * Link a TODO to proposed changes */ - LongPrototype.countTrailingZeros = function countTrailingZeros() { - return this.low ? ctz32(this.low) : ctz32(this.high) + 32; - }; - + linkTodoToChanges(todoId, changes) { + const todo = this.todos.get(todoId); + if (!todo) + return; + const changeDescriptions = changes.map(c => `${c.change_type}:${c.file_path}:${c.description.substring(0, 50)}`); + if (!todo.related_changes) { + todo.related_changes = []; + } + todo.related_changes.push(...changeDescriptions); + // Also update related files + const files = changes.map(c => c.file_path); + if (!todo.related_files) { + todo.related_files = []; + } + todo.related_files.push(...files); + todo.related_files = [...new Set(todo.related_files)]; // Remove duplicates + todo.updated_at = Date.now(); + } + /** + * Auto-update TODO status based on progress + * If changes are applied for a TODO, mark it as in_progress or completed + */ + autoUpdateFromChanges(changes) { + // Find active TODOs that might be related to these changes + const activeTodos = this.getActiveTodos(); + for (const todo of activeTodos) { + // Check if any of the changes are related to this TODO's files + if (todo.related_files) { + const relatedChanges = changes.filter(c => todo.related_files.includes(c.file_path)); + if (relatedChanges.length > 0) { + // Link changes to TODO + this.linkTodoToChanges(todo.id, relatedChanges); + // If TODO was pending, mark as in_progress + if (todo.status === 'pending') { + this.updateTodo(todo.id, { + status: 'in_progress', + notes: `Auto-updated: ${relatedChanges.length} change(s) applied` + }); + } + } + } + } + } /** - * Returns count trailing zeros. This is an alias of {@link Long#countTrailingZeros}. - * @function - * @param {!Long} - * @returns {!number} + * Get summary for final report */ - LongPrototype.ctz = LongPrototype.countTrailingZeros; + getSummary() { + const stats = this.getStats(); + const allTodos = this.getAllTodos(); + if (allTodos.length === 0) { + return 'No TODO list was created during this analysis.'; + } + const summary = []; + summary.push(`\n## TODO List Summary`); + summary.push(`- Total tasks: ${stats.total}`); + summary.push(`- Completed: ${stats.completed} (${stats.completion_rate.toFixed(1)}%)`); + summary.push(`- In Progress: ${stats.in_progress}`); + summary.push(`- Pending: ${stats.pending}`); + summary.push(`\n### All Tasks:`); + allTodos.forEach((todo, idx) => { + const statusIcon = todo.status === 'completed' ? 'āœ…' : + todo.status === 'in_progress' ? 'šŸ”„' : + todo.status === 'cancelled' ? 'āŒ' : 'ā³'; + summary.push(`${idx + 1}. ${statusIcon} **${todo.status.toUpperCase()}**: ${todo.content}`); + if (todo.notes) { + summary.push(` Notes: ${todo.notes}`); + } + }); + return summary.join('\n'); + } +} +exports.ThinkTodoManager = ThinkTodoManager; - /** - * Returns the bitwise AND of this Long and the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.and = function and(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low & other.low, - this.high & other.high, - this.unsigned, - ); - }; - /** - * Returns the bitwise OR of this Long and the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.or = function or(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low | other.low, - this.high | other.high, - this.unsigned, - ); - }; +/***/ }), + +/***/ 3841: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ThinkUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const file_repository_1 = __nccwpck_require__(1503); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +const think_code_manager_1 = __nccwpck_require__(8785); +const think_todo_manager_1 = __nccwpck_require__(3618); +const file_import_analyzer_1 = __nccwpck_require__(5310); +const file_cache_manager_1 = __nccwpck_require__(1855); +const codebase_analyzer_1 = __nccwpck_require__(678); +const file_search_service_1 = __nccwpck_require__(9810); +const comment_formatter_1 = __nccwpck_require__(5788); +class ThinkUseCase { + constructor() { + this.taskId = 'ThinkUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.fileRepository = new file_repository_1.FileRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + // Services + this.fileImportAnalyzer = new file_import_analyzer_1.FileImportAnalyzer(); + this.fileCacheManager = new file_cache_manager_1.FileCacheManager(); + this.fileSearchService = new file_search_service_1.FileSearchService(); + this.commentFormatter = new comment_formatter_1.CommentFormatter(); + this.MAX_ITERATIONS = 30; // Increased to allow deeper analysis + this.MAX_FILES_TO_ANALYZE = 50; // Increased file limit + this.MAX_CONSECUTIVE_SEARCHES = 3; // Max consecutive search_files without progress + // Initialize CodebaseAnalyzer with dependencies + this.codebaseAnalyzer = new codebase_analyzer_1.CodebaseAnalyzer(this.aiRepository, this.fileImportAnalyzer, this.fileCacheManager); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + // Extract the question/prompt from the issue, PR, or comment + let question = ''; + let description = ''; + if (param.issue.isIssueComment) { + question = param.issue.commentBody || ''; + description = await this.getIssueDescription(param) || ''; + } + else if (param.pullRequest.isPullRequestReviewComment) { + question = param.pullRequest.commentBody || ''; + description = await this.getIssueDescription(param) || ''; + } + else if (param.issue.isIssue) { + description = await this.getIssueDescription(param) || ''; + question = description; + } + else if (param.singleAction.isThinkAction) { + // For CLI usage, get question from comment body if available + // This handles the case when think is called as single-action + const commentBody = param.issue.commentBody || param.inputs?.comment?.body || ''; + if (commentBody) { + question = commentBody; + description = await this.getIssueDescription(param) || ''; + } + else { + description = await this.getIssueDescription(param) || ''; + question = description || ''; + } + } + if (!question || question.length === 0) { + if (!param.singleAction.isThinkAction) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + errors: ['No question or prompt provided.'], + })); + return results; + } + } + if (param.ai.getOpenRouterModel().length === 0 || param.ai.getOpenRouterApiKey().length === 0) { + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + errors: ['OpenRouter model or API key not found.'], + })); + return results; + } + (0, logger_1.logInfo)(`šŸ”Ž Question: ${question}`); + (0, logger_1.logInfo)(`šŸ”Ž Description: ${description}`); + if (question.length === 0 || !question.includes(`@${param.tokenUser}`)) { + (0, logger_1.logInfo)(`šŸ”Ž Comment body is empty or does not include @${param.tokenUser}`); + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return results; + } + else { + question = question.replace(`@${param.tokenUser}`, '').trim(); + } + // Get full repository content + (0, logger_1.logInfo)(`šŸ“š Loading repository content for ${param.owner}/${param.repo}/${param.commit.branch}`); + const repositoryFiles = await this.fileRepository.getRepositoryContent(param.owner, param.repo, param.tokens.token, param.commit.branch, param.ai.getAiIgnoreFiles(), (fileName) => (0, logger_1.logDebugInfo)(`Loading: ${fileName}`), (fileName) => (0, logger_1.logDebugInfo)(`Ignoring: ${fileName}`)); + (0, logger_1.logInfo)(`šŸ“š Loaded ${repositoryFiles.size} files from repository`); + // Initialize code manager with repository files + const codeManager = new think_code_manager_1.ThinkCodeManager(); + codeManager.initialize(repositoryFiles); + // Initialize TODO manager + const todoManager = new think_todo_manager_1.ThinkTodoManager(); + // AI will create initial TODOs in first iteration if needed + // Build file index for quick lookup + const fileIndex = this.fileSearchService.buildFileIndex(repositoryFiles); + // STEP 0: Generate codebase analysis and file relationships + (0, logger_1.logInfo)(`šŸ” Step 0: Analyzing codebase structure and file relationships...`); + const codebaseAnalysis = await this.codebaseAnalyzer.generateCodebaseAnalysis(param, repositoryFiles, question); + (0, logger_1.logInfo)(`āœ… Codebase analysis completed. Analyzed ${codebaseAnalysis.length} files.`); + // Format codebase analysis for context + const codebaseAnalysisText = this.codebaseAnalyzer.formatCodebaseAnalysisForContext(codebaseAnalysis); + // Reasoning process + const steps = []; + let iteration = 0; + let complete = false; + let analyzedFiles = new Map(); + let allProposedChanges = []; + let currentContext = codebaseAnalysisText; // Start with codebase analysis + let finalAnalysis = ''; + let consecutiveSearches = 0; // Track consecutive search_files without reading + let lastProgressIteration = 0; // Track last iteration with actual progress + let filesReadInIteration = 0; + let seenActions = new Map(); // Track action patterns to detect repetition + while (!complete && iteration < this.MAX_ITERATIONS) { + iteration++; + filesReadInIteration = 0; + (0, logger_1.logInfo)(`šŸ¤” Reasoning iteration ${iteration}/${this.MAX_ITERATIONS}`); + const thinkResponse = await this.performReasoningStep(param, question, description, codeManager, todoManager, fileIndex, analyzedFiles, currentContext, iteration, steps); + if (!thinkResponse) { + (0, logger_1.logError)('No response from AI reasoning step'); + break; + } + // Handle TODO updates (can be included with any action) + if (thinkResponse.todo_updates) { + // Create new TODOs + if (thinkResponse.todo_updates.create) { + for (const todo of thinkResponse.todo_updates.create) { + const createdTodo = todoManager.createTodo(todo.content, todo.status || 'pending'); + (0, logger_1.logInfo)(`āœ… Created TODO: [${createdTodo.id}] ${todo.content}`); + } + (0, logger_1.logInfo)(`šŸ“‹ Created ${thinkResponse.todo_updates.create.length} new TODO items`); + } + // Update existing TODOs + if (thinkResponse.todo_updates.update) { + let successCount = 0; + let failedIds = []; + for (const update of thinkResponse.todo_updates.update) { + const success = todoManager.updateTodo(update.id, { + status: update.status, + notes: update.notes + }); + if (success) { + successCount++; + } + else { + failedIds.push(update.id); + } + } + if (successCount > 0) { + (0, logger_1.logInfo)(`šŸ“‹ Successfully updated ${successCount} TODO items`); + } + if (failedIds.length > 0) { + // Show available TODO IDs to help the AI + const allTodos = todoManager.getAllTodos(); + const availableIds = allTodos.map(t => t.id).join(', '); + (0, logger_1.logInfo)(`āš ļø Failed to update ${failedIds.length} TODO items. Available IDs: ${availableIds}`); + currentContext += `\n\nāš ļø TODO Update Error: Could not find TODO(s) with ID(s): ${failedIds.join(', ')}. Available TODO IDs are: ${availableIds}. Please use the EXACT ID from the TODO list above.`; + } + } + } + // Record step with associated data for better comment formatting + const step = { + step_number: iteration, + action: thinkResponse.action, + reasoning: thinkResponse.reasoning, + files_involved: [ + ...(thinkResponse.files_to_read || []), + ...(thinkResponse.files_to_search || []), + ...(thinkResponse.analyzed_files?.map(f => f.path) || []) + ], + findings: thinkResponse.reasoning, + timestamp: Date.now() + }; + // Attach proposals to step if they were generated in this step + if (thinkResponse.action === 'propose_changes' && thinkResponse.proposed_changes) { + step.proposals_in_step = thinkResponse.proposed_changes; + } + // Attach file analysis to step if provided + if (thinkResponse.action === 'analyze_code' && thinkResponse.analyzed_files) { + step.file_analysis_in_step = thinkResponse.analyzed_files; + } + steps.push(step); + (0, logger_1.logInfo)(`šŸ¤” Step ${iteration}: ${thinkResponse.action} - ${thinkResponse.reasoning.substring(0, 100)}...`); + // Track action patterns to detect repetition + const actionKey = `${thinkResponse.action}_${thinkResponse.files_to_search?.join(',') || thinkResponse.files_to_read?.join(',') || 'general'}`; + const actionCount = seenActions.get(actionKey) || 0; + seenActions.set(actionKey, actionCount + 1); + // Execute action + switch (thinkResponse.action) { + case 'search_files': + consecutiveSearches++; + if (thinkResponse.files_to_search && thinkResponse.files_to_search.length > 0) { + const foundFiles = this.fileSearchService.searchFiles(thinkResponse.files_to_search, fileIndex); + (0, logger_1.logInfo)(`šŸ” Search results: Found ${foundFiles.length} files for terms: ${thinkResponse.files_to_search.join(', ')}`); + // Detect if we're repeating the same search + if (actionCount > 1) { + currentContext += `\n\nāš ļø WARNING: You've already searched for "${thinkResponse.files_to_search.join(', ')}" ${actionCount} times. `; + if (foundFiles.length > 0) { + currentContext += `These files were found previously. Consider READING them instead of searching again.`; + } + else { + currentContext += `No files found. Consider trying different search terms or reading files from the list above.`; + } + } + if (foundFiles.length > 0) { + currentContext += `\n\nFound ${foundFiles.length} files matching search criteria:\n${foundFiles.map(f => `- ${f}`).join('\n')}`; + // If found files after multiple searches, suggest reading them + if (consecutiveSearches >= this.MAX_CONSECUTIVE_SEARCHES && foundFiles.length > 0) { + currentContext += `\n\nšŸ’” IMPORTANT: You've searched ${consecutiveSearches} times. You MUST read some of the found files now to proceed with analysis. Suggested files: ${foundFiles.slice(0, 5).join(', ')}`; + } + } + else { + currentContext += `\n\nNo files found matching search criteria: ${thinkResponse.files_to_search.join(', ')}. Available files in repository: ${Array.from(repositoryFiles.keys()).slice(0, 30).join(', ')}...`; + // If too many searches without finding files, provide full file list + if (consecutiveSearches >= this.MAX_CONSECUTIVE_SEARCHES) { + currentContext += `\n\nšŸ“‹ Here are all available files in the repository to help you:\n${Array.from(repositoryFiles.keys()).map((f, i) => `${i + 1}. ${f}`).slice(0, 100).join('\n')}${repositoryFiles.size > 100 ? '\n... and more' : ''}`; + } + } + } + break; + case 'read_file': + consecutiveSearches = 0; // Reset counter when reading files + if (thinkResponse.files_to_read && thinkResponse.files_to_read.length > 0) { + const filesToAnalyze = thinkResponse.files_to_read.slice(0, this.MAX_FILES_TO_ANALYZE - analyzedFiles.size); + (0, logger_1.logInfo)(`šŸ“– Reading ${filesToAnalyze.length} files: ${filesToAnalyze.join(', ')}`); + for (const filePath of filesToAnalyze) { + if (analyzedFiles.has(filePath)) { + (0, logger_1.logDebugInfo)(`ā­ļø Skipping already analyzed file: ${filePath}`); + continue; // Already analyzed + } + // Get content from virtual files (includes applied changes) + const content = codeManager.getFileContent(filePath); + if (content !== undefined) { + filesReadInIteration++; + const isModified = codeManager.isFileModified(filePath); + const modificationNote = isModified ? ` [MODIFIED - ${codeManager.getFileChanges(filePath).length} change(s) applied]` : ''; + (0, logger_1.logDebugInfo)(`āœ… Reading file: ${filePath} (${content.length} chars)${modificationNote}`); + // Show current state with applied changes + currentContext += `\n\n=== File: ${filePath}${modificationNote} ===\n${content.substring(0, 8000)}${content.length > 8000 ? '\n... (truncated)' : ''}`; + // If file was modified, show what changed + if (isModified) { + const changes = codeManager.getFileChanges(filePath); + currentContext += `\n\nāš ļø This file has been modified in previous steps. Changes applied: ${changes.map(c => `${c.change_type}: ${c.description}`).join(', ')}`; + } + lastProgressIteration = iteration; + } + else { + (0, logger_1.logInfo)(`āŒ File not found in repository: ${filePath}`); + // Try to find similar file names + const fileName = filePath.split('/').pop() || ''; + const similarFiles = Array.from(repositoryFiles.keys()).filter(f => f.toLowerCase().includes(fileName.toLowerCase()) || + f.split('/').pop()?.toLowerCase().includes(fileName.toLowerCase())).slice(0, 5); + currentContext += `\n\nāš ļø File not found: ${filePath}. ${similarFiles.length > 0 ? `Similar files found: ${similarFiles.join(', ')}` : 'Please check the file path.'}`; + } + } + } + break; + case 'analyze_code': + consecutiveSearches = 0; // Reset counter when analyzing + if (thinkResponse.analyzed_files && thinkResponse.analyzed_files.length > 0) { + const beforeCount = analyzedFiles.size; + for (const analysis of thinkResponse.analyzed_files) { + if (!analyzedFiles.has(analysis.path)) { + analyzedFiles.set(analysis.path, analysis); + } + } + if (analyzedFiles.size > beforeCount) { + lastProgressIteration = iteration; + } + const findings = thinkResponse.analyzed_files + .map(f => `${f.path} (${f.relevance}): ${f.key_findings}`) + .join('\n'); + currentContext += `\n\nAnalysis findings:\n${findings}`; + } + break; + case 'propose_changes': + consecutiveSearches = 0; // Reset counter when proposing changes + if (thinkResponse.proposed_changes && thinkResponse.proposed_changes.length > 0) { + // Filter out changes that have already been applied + const newChanges = thinkResponse.proposed_changes.filter(change => !codeManager.hasChangeBeenApplied(change)); + if (newChanges.length === 0) { + (0, logger_1.logInfo)(`āš ļø All proposed changes have already been applied. Skipping duplicates.`); + currentContext += `\n\nāš ļø All proposed changes in this step have already been applied in previous iterations. Please propose NEW changes or move to the next step.`; + break; + } + // Apply changes to virtual codebase + let appliedCount = 0; + for (const change of newChanges) { + if (codeManager.applyChange(change)) { + appliedCount++; + allProposedChanges.push(change); + } + } + (0, logger_1.logInfo)(`āœ… Applied ${appliedCount} new changes to virtual codebase (${newChanges.length - appliedCount} skipped)`); + // Auto-update TODOs based on applied changes + todoManager.autoUpdateFromChanges(newChanges.slice(0, appliedCount)); + // Store the index where these proposals start for proper ordering + const startIndex = allProposedChanges.length - appliedCount; + const appliedChanges = newChanges.slice(0, appliedCount); + // Attach to step with start index for proper display order + const currentStep = steps[steps.length - 1]; + if (currentStep) { + currentStep.proposals_in_step = appliedChanges; + currentStep.proposals_start_index = startIndex; + } + const changesSummary = appliedChanges + .map(c => `${c.change_type} ${c.file_path}: ${c.description}`) + .join('\n'); + currentContext += `\n\nāœ… Applied ${appliedCount} new changes to codebase:\n${changesSummary}`; + // Add context about code state + currentContext += codeManager.getContextForAI(); + lastProgressIteration = iteration; + } + break; + case 'update_todos': + consecutiveSearches = 0; // Reset counter when updating TODOs + // Note: TODO updates are handled before the switch statement + // This case is mainly for when action is explicitly update_todos + if (thinkResponse.todo_updates && (!thinkResponse.files_to_search && + !thinkResponse.files_to_read && + !thinkResponse.analyzed_files && + !thinkResponse.proposed_changes)) { + // Pure TODO update action - warn if this happens too often + (0, logger_1.logInfo)(`šŸ“‹ Pure TODO update action (no other work done)`); + currentContext += `\n\nšŸ“‹ TODO list updated. Current status:\n${todoManager.getContextForAI()}`; + currentContext += `\n\nāš ļø **NOTE**: You updated TODOs but didn't do any actual work. In the next iteration, DO THE WORK: search for files, read files, analyze code, or propose changes related to the active TODOs.`; + lastProgressIteration = iteration; + } + break; + case 'complete': + complete = true; + finalAnalysis = thinkResponse.final_analysis || thinkResponse.reasoning; + lastProgressIteration = iteration; + break; + } + // Check for stagnation - if too many iterations without progress + const iterationsWithoutProgress = iteration - lastProgressIteration; + if (iterationsWithoutProgress > 5 && !complete && iteration > 5) { + (0, logger_1.logInfo)(`āš ļø No significant progress in last ${iterationsWithoutProgress} iterations (last progress at iteration ${lastProgressIteration}). Forcing completion.`); + complete = true; + if (!finalAnalysis) { + finalAnalysis = `Analysis completed after ${iteration} iterations. Analyzed ${analyzedFiles.size} files, proposed ${allProposedChanges.length} changes.`; + } + } + // Check if stuck in TODO update loop + const recentActions = steps.slice(-3).map(s => s.action); + const allUpdateTodos = recentActions.every(a => a === 'update_todos'); + if (allUpdateTodos && recentActions.length >= 3 && iteration > 3) { + (0, logger_1.logInfo)(`āš ļø Detected loop: ${recentActions.length} consecutive update_todos actions. Warning AI to do actual work.`); + const activeTodos = todoManager.getActiveTodos(); + const todoIds = activeTodos.map(t => t.id).join(', '); + currentContext += `\n\nāš ļø **STOP UPDATING TODOs AND DO ACTUAL WORK**: You've been updating TODOs repeatedly. Pick a TODO to work on (IDs: ${todoIds}) and DO THE WORK: search for files, read files, analyze code, or propose changes. Stop just updating TODO status!`; + } + // Prevent infinite loops - check file limit + if (analyzedFiles.size >= this.MAX_FILES_TO_ANALYZE) { + (0, logger_1.logInfo)(`Reached maximum files to analyze (${this.MAX_FILES_TO_ANALYZE})`); + if (!complete) { + complete = true; + finalAnalysis = finalAnalysis || `Reached maximum file limit. Analyzed ${analyzedFiles.size} files, proposed ${allProposedChanges.length} changes.`; + } + break; + } + } + // Generate final comprehensive response + if (!finalAnalysis && complete) { + finalAnalysis = await this.generateFinalAnalysis(param, question, analyzedFiles, allProposedChanges, steps, todoManager); + } + // Format and post comprehensive reasoning comment + const formattedComment = this.commentFormatter.formatReasoningComment(question, description, steps, analyzedFiles, allProposedChanges, finalAnalysis, iteration, todoManager); + // Determine issue number + let issueNumber = param.issueNumber; + if (param.singleAction.isThinkAction && issueNumber <= 0) { + // Try to get from issue if available + issueNumber = param.issue?.number || 1; + } + // Post comment if we have a valid issue number and token + if (issueNumber > 0 && param.tokens.token) { + try { + await this.issueRepository.addComment(param.owner, param.repo, issueNumber, formattedComment, param.tokens.token); + (0, logger_1.logInfo)(`āœ… Posted reasoning comment to issue #${issueNumber}`); + } + catch (error) { + (0, logger_1.logError)(`Failed to post comment to issue: ${error}`); + } + } + else { + (0, logger_1.logInfo)(`ā­ļø Skipping comment post: issueNumber=${issueNumber}, hasToken=${!!param.tokens.token}`); + } + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: steps.map(s => `Step ${s.step_number}: ${s.action} - ${s.reasoning.substring(0, 200)}`), + payload: { + steps: steps, + analyzed_files: Array.from(analyzedFiles.values()), + proposed_changes: allProposedChanges, + final_analysis: finalAnalysis, + total_iterations: iteration, + total_files_analyzed: analyzedFiles.size, + comment_posted: issueNumber > 0 + } + })); + } + catch (error) { + (0, logger_1.logError)(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`], + })); + } + return results; + } + async getIssueDescription(param) { + try { + const description = await this.issueRepository.getDescription(param.owner, param.repo, param.issueNumber, param.tokens.token); + return description ?? null; + } + catch (error) { + (0, logger_1.logError)(`Error getting issue description: ${error}`); + return null; + } + } + // All methods related to file imports, cache, codebase analysis, and comment formatting + // have been moved to dedicated services: + // - FileImportAnalyzer: extractImportsFromFile, resolveRelativePath, buildRelationshipMap + // - FileCacheManager: calculateFileSHA, loadAICache, saveAICacheEntry + // - CodebaseAnalyzer: generateCodebaseAnalysis, generateBasicDescription, generateFallbackFileDescriptions, formatCodebaseAnalysisForContext + // - FileSearchService: buildFileIndex, searchFiles + // - CommentFormatter: formatReasoningComment, formatProposedChange, detectLanguageFromPath, getActionEmoji, formatActionName, getChangeTypeEmoji + async performReasoningStep(param, question, description, codeManager, todoManager, fileIndex, analyzedFiles, currentContext, iteration, previousSteps) { + const analyzedFilesList = Array.from(analyzedFiles.values()); + const analyzedFilesSummary = analyzedFilesList.length > 0 + ? `\n\nPreviously analyzed files (${analyzedFilesList.length}):\n${analyzedFilesList.map(f => `- ${f.path} (${f.relevance}): ${f.key_findings.substring(0, 150)}...`).join('\n')}` + : ''; + const codeStats = codeManager.getStats(); + const codeStateInfo = codeManager.getContextForAI(); + const todoContext = todoManager.getContextForAI(); + const todoStats = todoManager.getStats(); + // Get codebase analysis from initial step (stored in currentContext at start) + const codebaseAnalysisMatch = currentContext.match(/## šŸ“‹ Codebase Analysis & File Relationships\n\n([\s\S]*?)(?=\n##|$)/); + const codebaseAnalysis = codebaseAnalysisMatch ? codebaseAnalysisMatch[1] : ''; + // Build summary of previous steps to avoid repetition + const stepsSummary = previousSteps.length > 0 + ? `\n\n## Previous Steps Taken (${previousSteps.length}):\n${previousSteps.slice(-5).map(s => `- Step ${s.step_number}: ${s.action} - ${s.reasoning.substring(0, 100)}...`).join('\n')}${previousSteps.length > 5 ? `\n... and ${previousSteps.length - 5} more steps` : ''}` + : ''; + const fileListSummary = `\n\nAvailable files in repository (${codeStats.totalFiles} files):\n${Array.from(codeManager.getAllFiles().keys()).slice(0, 50).join('\n')}${codeStats.totalFiles > 50 ? `\n... and ${codeStats.totalFiles - 50} more files` : ''}`; + const prompt = ` +# Code Analysis Assistant + +You are an advanced code analysis assistant similar to Cursor's Auto agent. Your role is to perform deep analysis of codebases and propose thoughtful changes. - /** - * Returns the bitwise XOR of this Long and the given one. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.xor = function xor(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low ^ other.low, - this.high ^ other.high, - this.unsigned, - ); - }; +**CRITICAL CONCEPTS**: - /** - * Returns this Long with bits shifted to the left by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - this.low << numBits, - (this.high << numBits) | (this.low >>> (32 - numBits)), - this.unsigned, - ); - else return fromBits(0, this.low << (numBits - 32), this.unsigned); - }; +1. **VIRTUAL CODEBASE**: You are working with a VIRTUAL CODEBASE. When you propose changes, they are automatically applied to the code in memory. Subsequent steps will see the MODIFIED code, not the original. This allows you to build upon previous changes incrementally. - /** - * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shl = LongPrototype.shiftLeft; +2. **TODO LIST SYSTEM**: You have a TODO list system to track high-level tasks. Each task in the TODO list may require multiple reasoning steps (search, read, analyze, propose). Use this to: + - Create TODOs in your first iteration to break down the problem + - Update TODO status as you make progress (pending → in_progress → completed) + - Link your actions to TODOs to show which task you're working on + - This helps you understand where you are in the overall process, even if you need many steps per task - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - (this.low >>> numBits) | (this.high << (32 - numBits)), - this.high >> numBits, - this.unsigned, - ); - else - return fromBits( - this.high >> (numBits - 32), - this.high >= 0 ? 0 : -1, - this.unsigned, - ); - }; +3. **TWO-LEVEL REASONING**: + - **High-level (TODO list)**: What major tasks need to be done? + - **Low-level (reasoning steps)**: How do I accomplish each task? (search, read, analyze, propose) - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shr = LongPrototype.shiftRight; +${codebaseAnalysis ? `\n\n## šŸ“‹ Codebase Analysis & File Relationships\n\n${codebaseAnalysis}\n\n**This analysis helps you understand the codebase structure and relationships between files. Use it to make informed decisions about which files to examine for the task.**\n\n` : ''} - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits < 32) - return fromBits( - (this.low >>> numBits) | (this.high << (32 - numBits)), - this.high >>> numBits, - this.unsigned, - ); - if (numBits === 32) return fromBits(this.high, 0, this.unsigned); - return fromBits(this.high >>> (numBits - 32), 0, this.unsigned); - }; +${todoStats.total > 0 ? `\n${todoContext}\n\n**CRITICAL**: To work on a TODO, use its EXACT ID (shown above) when updating. Don't just update status - DO THE ACTUAL WORK (search, read, analyze, propose) in the same response where you update the TODO.` : iteration === 1 ? `\n\n## šŸ“‹ TODO List\n\n**IMPORTANT**: In your first response, you should create a TODO list breaking down the problem into manageable tasks. Use the \`todo_updates.create\` field to create initial TODOs. Each TODO represents a high-level task that may require multiple reasoning steps to complete.` : ''} - /** - * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shru = LongPrototype.shiftRightUnsigned; +## Current Task - /** - * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; +${description ? `### Context/Issue Description:\n\`\`\`\n${description}\n\`\`\`` : ''} - /** - * Returns this Long with bits rotated to the left by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotateLeft = function rotateLeft(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - (this.low << numBits) | (this.high >>> b), - (this.high << numBits) | (this.low >>> b), - this.unsigned, - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - (this.high << numBits) | (this.low >>> b), - (this.low << numBits) | (this.high >>> b), - this.unsigned, - ); - }; - /** - * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotl = LongPrototype.rotateLeft; +### User's Question/Prompt: +\`\`\` +${question} +\`\`\` - /** - * Returns this Long with bits rotated to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotateRight = function rotateRight(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - (this.high << b) | (this.low >>> numBits), - (this.low << b) | (this.high >>> numBits), - this.unsigned, - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - (this.low << b) | (this.high >>> numBits), - (this.high << b) | (this.low >>> numBits), - this.unsigned, - ); - }; - /** - * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotr = LongPrototype.rotateRight; +## Reasoning Process (Iteration ${iteration}/${this.MAX_ITERATIONS}) - /** - * Converts this Long to signed. - * @this {!Long} - * @returns {!Long} Signed long - */ - LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) return this; - return fromBits(this.low, this.high, false); - }; +${iteration === 1 ? 'You are starting your analysis. Begin by understanding the question and identifying what files or areas of the codebase might be relevant.' : `You have been analyzing this problem through ${iteration - 1} previous iterations.`} - /** - * Converts this Long to unsigned. - * @this {!Long} - * @returns {!Long} Unsigned long - */ - LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) return this; - return fromBits(this.low, this.high, true); - }; +${stepsSummary} - /** - * Converts this Long to its byte representation. - * @param {boolean=} le Whether little or big endian, defaults to big endian - * @this {!Long} - * @returns {!Array.} Byte representation - */ - LongPrototype.toBytes = function toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; +${codeStats.totalChanges > 0 ? `\n\n## āš ļø CODE STATE: ${codeStats.totalChanges} changes have been applied to ${codeStats.modifiedFiles} files\n\n${codeStateInfo}\n\n**IMPORTANT**: When you read files, you will see the MODIFIED version with all previous changes applied. Build upon this modified code, don't repeat changes that have already been made.` : ''} - /** - * Converts this Long to its little endian byte representation. - * @this {!Long} - * @returns {!Array.} Little endian byte representation - */ - LongPrototype.toBytesLE = function toBytesLE() { - var hi = this.high, - lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24, - ]; - }; +${analyzedFilesSummary} - /** - * Converts this Long to its big endian byte representation. - * @this {!Long} - * @returns {!Array.} Big endian byte representation - */ - LongPrototype.toBytesBE = function toBytesBE() { - var hi = this.high, - lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff, - ]; - }; +${iteration > 1 ? `\n\n## Previous Iteration Context:\n${currentContext.substring(0, 4000)}${currentContext.length > 4000 ? '\n... (truncated for brevity)' : ''}` : ''} - /** - * Creates a Long from its byte representation. - * @param {!Array.} bytes Byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @param {boolean=} le Whether little or big endian, defaults to big endian - * @returns {Long} The corresponding Long value - */ - Long.fromBytes = function fromBytes(bytes, unsigned, le) { - return le - ? Long.fromBytesLE(bytes, unsigned) - : Long.fromBytesBE(bytes, unsigned); - }; +${fileListSummary} - /** - * Creates a Long from its little endian byte representation. - * @param {!Array.} bytes Little endian byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {Long} The corresponding Long value - */ - Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { - return new Long( - bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), - bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), - unsigned, - ); - }; +## Your Analysis Approach - /** - * Creates a Long from its big endian byte representation. - * @param {!Array.} bytes Big endian byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {Long} The corresponding Long value - */ - Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { - return new Long( - (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], - (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], - unsigned, - ); - }; +1. **search_files**: Use when you need to find files by name, pattern, or path. Be specific. AVOID searching for the same terms repeatedly. +2. **read_file**: Use when you need to examine specific files. The files you read will show the CURRENT STATE (with all applied changes from previous steps). +3. **analyze_code**: Use when you've read files and want to document findings. Focus on understanding relationships and dependencies. +4. **propose_changes**: Use when you have enough context. **CRITICAL**: Only propose NEW changes that build upon what's already been done. Don't repeat changes that were already applied. +5. **update_todos** (or include with other actions): + - Create TODOs ONLY in your first iteration to break down the problem + - Update TODO status when you START working on it (in_progress) or COMPLETE it (completed) + - **IMPORTANT**: Use the EXACT TODO ID from the list above (e.g., "todo_1"), NOT numeric IDs + - Include todo_updates in the SAME response where you do the actual work +6. **complete**: Use when your analysis is finished and you have a comprehensive understanding. All TODOs should be completed or cancelled. - // Support conversion to/from BigInt where available - if (typeof BigInt === "function") { - /** - * Returns a Long representing the given big integer. - * @function - * @param {number} value The big integer value - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromBigInt = function fromBigInt(value, unsigned) { - var lowBits = Number(BigInt.asIntN(32, value)); - var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); - return fromBits(lowBits, highBits, unsigned); - }; +## Critical Instructions - // Override - Long.fromValue = function fromValueWithBigInt(value, unsigned) { - if (typeof value === "bigint") return Long.fromBigInt(value, unsigned); - return fromValue(value, unsigned); - }; +- **USE TODO LIST CORRECTLY**: + - Create TODOs in iteration 1 to break down the problem into manageable tasks + - **IMPORTANT**: When updating TODOs, you MUST use the EXACT ID shown in the TODO list (e.g., "todo_1", "todo_2"). Do NOT use numeric IDs like "1" or "2" + - Each TODO represents a high-level task that may require multiple reasoning steps (search, read, analyze, propose) + +- **WORK ON TODOS, DON'T JUST UPDATE THEM**: + - When a TODO is "pending" or "in_progress", DO REAL WORK: search for files, read files, analyze code, propose changes + - Only update TODO status when you actually START working on it (mark "in_progress") or COMPLETE it (mark "completed") + - Don't waste iterations just updating TODO status - do the actual work! + +- **TRACK PROGRESS**: + - When you START working on a TODO: mark it "in_progress" AND then do the work (search, read, analyze, propose) + - When you COMPLETE work on a TODO: mark it "completed" + - Update TODOs in the same response where you do the work, don't create separate "update_todos" actions - /** - * Converts the Long to its big integer representation. - * @this {!Long} - * @returns {bigint} - */ - LongPrototype.toBigInt = function toBigInt() { - var lowBigInt = BigInt(this.low >>> 0); - var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); - return (highBigInt << BigInt(32)) | lowBigInt; - }; - } - var _default = (_exports.default = Long); - }, -); +- **AVOID REPETITION**: Don't search for the same files repeatedly. Don't propose changes that have already been applied. Don't try to update TODOs with wrong IDs. +- **BUILD INCREMENTALLY**: Each step should build upon the previous one. Read files that were modified in previous steps to see the current state. -/***/ }), +- **PROGRESS FORWARD**: If you've already analyzed files, move to proposing changes. Don't re-analyze the same code. -/***/ 88757: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +- **SEE THE MODIFIED CODE**: When you read files after changes have been applied, you'll see the modified version. Use this to understand the current state and propose the NEXT logical step. -"use strict"; -/*! Axios v1.13.1 Copyright (c) 2025 Matt Zabriskie and contributors */ - - -const FormData$1 = __nccwpck_require__(91403); -const crypto = __nccwpck_require__(6113); -const url = __nccwpck_require__(57310); -const http2 = __nccwpck_require__(85158); -const proxyFromEnv = __nccwpck_require__(63329); -const http = __nccwpck_require__(13685); -const https = __nccwpck_require__(95687); -const util = __nccwpck_require__(73837); -const followRedirects = __nccwpck_require__(67707); -const zlib = __nccwpck_require__(59796); -const stream = __nccwpck_require__(12781); -const events = __nccwpck_require__(82361); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -const FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData$1); -const crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto); -const url__default = /*#__PURE__*/_interopDefaultLegacy(url); -const proxyFromEnv__default = /*#__PURE__*/_interopDefaultLegacy(proxyFromEnv); -const http__default = /*#__PURE__*/_interopDefaultLegacy(http); -const https__default = /*#__PURE__*/_interopDefaultLegacy(https); -const util__default = /*#__PURE__*/_interopDefaultLegacy(util); -const followRedirects__default = /*#__PURE__*/_interopDefaultLegacy(followRedirects); -const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); -const stream__default = /*#__PURE__*/_interopDefaultLegacy(stream); +- **BE SPECIFIC**: When proposing changes, be very specific about what needs to change and provide suggested_code. -/** - * Create a bound version of a function with a specified `this` context - * - * @param {Function} fn - The function to bind - * @param {*} thisArg - The value to be passed as the `this` parameter - * @returns {Function} A new function that will call the original function with the specified `this` context - */ -function bind(fn, thisArg) { - return function wrap() { - return fn.apply(thisArg, arguments); - }; -} +- **THINK DEEPLY**: Don't just propose generic changes. Analyze the code structure, dependencies, and relationships before proposing changes. -// utils is a library of generic helper functions non-specific to axios +- **FOCUS ON ACTIVE TODOS**: Work on TODOs that are "pending" or "in_progress". Complete them by doing real work, not just updating status. -const {toString} = Object.prototype; -const {getPrototypeOf} = Object; -const {iterator, toStringTag} = Symbol; +## Important -const kindOf = (cache => thing => { - const str = toString.call(thing); - return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase()); -})(Object.create(null)); +- You must return a valid JSON object matching the schema +- Be thorough but efficient - don't request files you don't need +- Build understanding incrementally +- Connect insights across multiple files when relevant +- Each iteration should advance the analysis, not repeat previous steps +- You can include \`todo_updates\` alongside any action (not just when action is 'update_todos') +- When creating TODOs, make them specific and actionable (e.g., "Analyze authentication system" not "Do stuff") +`; + try { + const response = await this.aiRepository.askThinkJson(param.ai, prompt); + return response; + } + catch (error) { + (0, logger_1.logError)(`Error in reasoning step: ${error}`); + return undefined; + } + } + async generateFinalAnalysis(param, question, analyzedFiles, proposedChanges, steps, todoManager) { + const prompt = ` +# Final Analysis Summary -const kindOfTest = (type) => { - type = type.toLowerCase(); - return (thing) => kindOf(thing) === type -}; +Based on your analysis of the codebase, provide a comprehensive summary and recommendations. -const typeOfTest = type => thing => typeof thing === type; +## User's Question: +${question} -/** - * Determine if a value is an Array - * - * @param {Object} val The value to test - * - * @returns {boolean} True if value is an Array, otherwise false - */ -const {isArray} = Array; +## Analysis Summary: +- Total steps taken: ${steps.length} +- Files analyzed: ${analyzedFiles.size} +- Proposed changes: ${proposedChanges.length} +- TODO list: ${todoManager.getSummary()} -/** - * Determine if a value is undefined - * - * @param {*} val The value to test - * - * @returns {boolean} True if the value is undefined, otherwise false - */ -const isUndefined = typeOfTest('undefined'); +## Analyzed Files: +${Array.from(analyzedFiles.values()).map(f => `- ${f.path} (${f.relevance}): ${f.key_findings}`).join('\n')} -/** - * Determine if a value is a Buffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Buffer, otherwise false - */ -function isBuffer(val) { - return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) - && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val); -} +## Proposed Changes: +${proposedChanges.map(c => ` +### ${c.change_type.toUpperCase()}: ${c.file_path} +**Description:** ${c.description} +**Reasoning:** ${c.reasoning} +${c.suggested_code ? `**Suggested Code:**\n\`\`\`\n${c.suggested_code}\n\`\`\`` : ''} +`).join('\n')} -/** - * Determine if a value is an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is an ArrayBuffer, otherwise false - */ -const isArrayBuffer = kindOfTest('ArrayBuffer'); +## Steps Taken: +${steps.map(s => `${s.step_number}. ${s.action}: ${s.reasoning.substring(0, 150)}...`).join('\n')} +Provide a comprehensive final analysis that: +1. Summarizes what you discovered +2. Explains the key insights +3. Provides clear recommendations +4. Describes the proposed changes and their rationale +5. Notes any considerations or potential issues -/** - * Determine if a value is a view on an ArrayBuffer - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false - */ -function isArrayBufferView(val) { - let result; - if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { - result = ArrayBuffer.isView(val); - } else { - result = (val) && (val.buffer) && (isArrayBuffer(val.buffer)); - } - return result; +Be thorough, clear, and actionable. +`; + const response = await this.aiRepository.ask(param.ai, prompt); + return response || 'Analysis completed. Review the proposed changes and steps above.'; + } } +exports.ThinkUseCase = ThinkUseCase; -/** - * Determine if a value is a String - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a String, otherwise false - */ -const isString = typeOfTest('string'); - -/** - * Determine if a value is a Function - * - * @param {*} val The value to test - * @returns {boolean} True if value is a Function, otherwise false - */ -const isFunction$1 = typeOfTest('function'); - -/** - * Determine if a value is a Number - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Number, otherwise false - */ -const isNumber = typeOfTest('number'); - -/** - * Determine if a value is an Object - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an Object, otherwise false - */ -const isObject = (thing) => thing !== null && typeof thing === 'object'; - -/** - * Determine if a value is a Boolean - * - * @param {*} thing The value to test - * @returns {boolean} True if value is a Boolean, otherwise false - */ -const isBoolean = thing => thing === true || thing === false; - -/** - * Determine if a value is a plain Object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a plain Object, otherwise false - */ -const isPlainObject = (val) => { - if (kindOf(val) !== 'object') { - return false; - } - - const prototype = getPrototypeOf(val); - return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(toStringTag in val) && !(iterator in val); -}; - -/** - * Determine if a value is an empty object (safely handles Buffers) - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is an empty object, otherwise false - */ -const isEmptyObject = (val) => { - // Early return for non-objects or Buffers to prevent RangeError - if (!isObject(val) || isBuffer(val)) { - return false; - } - - try { - return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype; - } catch (e) { - // Fallback for any other objects that might cause RangeError with Object.keys() - return false; - } -}; - -/** - * Determine if a value is a Date - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Date, otherwise false - */ -const isDate = kindOfTest('Date'); - -/** - * Determine if a value is a File - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ -const isFile = kindOfTest('File'); - -/** - * Determine if a value is a Blob - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Blob, otherwise false - */ -const isBlob = kindOfTest('Blob'); - -/** - * Determine if a value is a FileList - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a File, otherwise false - */ -const isFileList = kindOfTest('FileList'); - -/** - * Determine if a value is a Stream - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a Stream, otherwise false - */ -const isStream = (val) => isObject(val) && isFunction$1(val.pipe); - -/** - * Determine if a value is a FormData - * - * @param {*} thing The value to test - * - * @returns {boolean} True if value is an FormData, otherwise false - */ -const isFormData = (thing) => { - let kind; - return thing && ( - (typeof FormData === 'function' && thing instanceof FormData) || ( - isFunction$1(thing.append) && ( - (kind = kindOf(thing)) === 'formdata' || - // detect form-data instance - (kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]') - ) - ) - ) -}; - -/** - * Determine if a value is a URLSearchParams object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a URLSearchParams object, otherwise false - */ -const isURLSearchParams = kindOfTest('URLSearchParams'); - -const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest); - -/** - * Trim excess whitespace off the beginning and end of a string - * - * @param {String} str The String to trim - * - * @returns {String} The String freed of excess whitespace - */ -const trim = (str) => str.trim ? - str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); - -/** - * Iterate over an Array or an Object invoking a function for each item. - * - * If `obj` is an Array callback will be called passing - * the value, index, and complete array for each item. - * - * If 'obj' is an Object callback will be called passing - * the value, key, and complete object for each property. - * - * @param {Object|Array} obj The object to iterate - * @param {Function} fn The callback to invoke for each item - * - * @param {Boolean} [allOwnKeys = false] - * @returns {any} - */ -function forEach(obj, fn, {allOwnKeys = false} = {}) { - // Don't bother if no value provided - if (obj === null || typeof obj === 'undefined') { - return; - } - - let i; - let l; - // Force an array if not already something iterable - if (typeof obj !== 'object') { - /*eslint no-param-reassign:0*/ - obj = [obj]; - } +/***/ }), - if (isArray(obj)) { - // Iterate over array values - for (i = 0, l = obj.length; i < l; i++) { - fn.call(null, obj[i], i, obj); - } - } else { - // Buffer check - if (isBuffer(obj)) { - return; - } +/***/ 5107: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Iterate over object keys - const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); - const len = keys.length; - let key; +"use strict"; - for (i = 0; i < len; i++) { - key = keys[i]; - fn.call(null, obj[key], key, obj); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UpdateTitleUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class UpdateTitleUseCase { + constructor() { + this.taskId = 'UpdateTitleUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); } - } -} - -function findKey(obj, key) { - if (isBuffer(obj)){ - return null; - } - - key = key.toLowerCase(); - const keys = Object.keys(obj); - let i = keys.length; - let _key; - while (i-- > 0) { - _key = keys[i]; - if (key === _key.toLowerCase()) { - return _key; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.isIssue) { + if (param.emoji.emojiLabeledTitle) { + let _title = await this.issueRepository.getTitle(param.owner, param.repo, param.issue.number, param.tokens.token) ?? param.issue.title; + let _version = ''; + if (param.release.active) { + _version = param.release.version ?? 'Unknown Version'; + } + else if (param.hotfix.active) { + _version = param.hotfix.version ?? 'Unknown Version'; + } + const title = await this.issueRepository.updateTitleIssueFormat(param.owner, param.repo, _version, _title, param.issue.number, param.issue.branchManagementAlways, param.emoji.branchManagementEmoji, param.labels, param.tokens.token); + if (title) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The issue's title was updated from \`${_title}\` to \`${title}\`.`, + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + else if (param.isPullRequest) { + if (param.emoji.emojiLabeledTitle) { + const issueTitle = await this.issueRepository.getTitle(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (issueTitle === undefined) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update title, but there was a problem.`, + ], + })); + return result; + } + const title = await this.issueRepository.updateTitlePullRequestFormat(param.owner, param.repo, param.pullRequest.title, issueTitle, param.issueNumber, param.pullRequest.number, false, '', param.labels, param.tokens.token); + if (title) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The pull request's title was updated from \`${param.pullRequest.title}\` to \`${title}\`.`, + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update title, but there was a problem.`, + ], + error: error, + })); + } + return result; } - } - return null; } +exports.UpdateTitleUseCase = UpdateTitleUseCase; -const _global = (() => { - /*eslint no-undef:0*/ - if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) -})(); -const isContextDefined = (context) => !isUndefined(context) && context !== _global; +/***/ }), -/** - * Accepts varargs expecting each argument to be an object, then - * immutably merges the properties of each object and returns result. - * - * When multiple objects contain the same key the later object in - * the arguments list will take precedence. - * - * Example: - * - * ```js - * var result = merge({foo: 123}, {foo: 456}); - * console.log(result.foo); // outputs 456 - * ``` - * - * @param {Object} obj1 Object to merge - * - * @returns {Object} Result of all merge properties - */ -function merge(/* obj1, obj2, obj3, ... */) { - const {caseless, skipUndefined} = isContextDefined(this) && this || {}; - const result = {}; - const assignValue = (val, key) => { - const targetKey = caseless && findKey(result, key) || key; - if (isPlainObject(result[targetKey]) && isPlainObject(val)) { - result[targetKey] = merge(result[targetKey], val); - } else if (isPlainObject(val)) { - result[targetKey] = merge({}, val); - } else if (isArray(val)) { - result[targetKey] = val.slice(); - } else if (!skipUndefined || !isUndefined(val)) { - result[targetKey] = val; - } - }; +/***/ 3115: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (let i = 0, l = arguments.length; i < l; i++) { - arguments[i] && forEach(arguments[i], assignValue); - } - return result; -} +"use strict"; -/** - * Extends object a by mutably adding to it the properties of object b. - * - * @param {Object} a The object to be extended - * @param {Object} b The object to copy properties from - * @param {Object} thisArg The object to bind function to - * - * @param {Boolean} [allOwnKeys] - * @returns {Object} The resulting value of object a - */ -const extend = (a, b, thisArg, {allOwnKeys}= {}) => { - forEach(b, (val, key) => { - if (thisArg && isFunction$1(val)) { - a[key] = bind(val, thisArg); - } else { - a[key] = val; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AssignMemberToIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class AssignMemberToIssueUseCase { + constructor() { + this.taskId = 'AssignMemberToIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); } - }, {allOwnKeys}); - return a; -}; - -/** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * - * @param {string} content with BOM - * - * @returns {string} content value without BOM - */ -const stripBOM = (content) => { - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -}; - -/** - * Inherit the prototype methods from one constructor into another - * @param {function} constructor - * @param {function} superConstructor - * @param {object} [props] - * @param {object} [descriptors] - * - * @returns {void} - */ -const inherits = (constructor, superConstructor, props, descriptors) => { - constructor.prototype = Object.create(superConstructor.prototype, descriptors); - constructor.prototype.constructor = constructor; - Object.defineProperty(constructor, 'super', { - value: superConstructor.prototype - }); - props && Object.assign(constructor.prototype, props); -}; - -/** - * Resolve object with deep prototype chain to a flat object - * @param {Object} sourceObj source object - * @param {Object} [destObj] - * @param {Function|Boolean} [filter] - * @param {Function} [propFilter] - * - * @returns {Object} - */ -const toFlatObject = (sourceObj, destObj, filter, propFilter) => { - let props; - let i; - let prop; - const merged = {}; - - destObj = destObj || {}; - // eslint-disable-next-line no-eq-null,eqeqeq - if (sourceObj == null) return destObj; - - do { - props = Object.getOwnPropertyNames(sourceObj); - i = props.length; - while (i-- > 0) { - prop = props[i]; - if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { - destObj[prop] = sourceObj[prop]; - merged[prop] = true; - } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const desiredAssigneesCount = param.isIssue ? + param.issue.desiredAssigneesCount : param.pullRequest.desiredAssigneesCount; + const number = param.isIssue ? param.issue.number : param.pullRequest.number; + const result = []; + try { + (0, logger_1.logDebugInfo)(`#${number} needs ${desiredAssigneesCount} assignees.`); + const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); + const currentMembers = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); + let remainingAssignees = desiredAssigneesCount - currentMembers.length; + const pullRequestCreatorIsTeamMember = param.isPullRequest + && param.pullRequest.creator.length > 0 + && currentProjectMembers.indexOf(param.pullRequest.creator) > -1 + && !currentMembers.includes(param.pullRequest.creator); + const issueCreatorIsTeamMember = param.isIssue + && param.issue.creator.length > 0 + && currentProjectMembers.indexOf(param.issue.creator) > -1 + && !currentMembers.includes(param.issue.creator); + /** + * Assign PR creator if applicable + */ + if (pullRequestCreatorIsTeamMember) { + const creator = param.pullRequest.creator; + await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); + (0, logger_1.logDebugInfo)(`Assigned PR creator @${creator} to #${number}.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`The pull request was assigned to @${creator} (creator).`], + })); + remainingAssignees--; // Reduce the count of required assignees + } + else if (issueCreatorIsTeamMember) { + const creator = param.issue.creator; + await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, [creator], param.tokens.token); + (0, logger_1.logDebugInfo)(`Assigned Issue creator @${creator} to #${number}.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [`The issue was assigned to @${creator} (creator).`], + })); + remainingAssignees--; // Reduce the count of required assignees + } + /** + * Exit if no more assignees are needed + */ + if (remainingAssignees <= 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return result; + } + /** + * Assign remaining members randomly + */ + const members = await this.projectRepository.getRandomMembers(param.owner, remainingAssignees, currentMembers, param.tokens.token); + if (members.length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to assign members to issue, but no one was found.`], + })); + return result; + } + const membersAdded = await this.issueRepository.assignMembersToIssue(param.owner, param.repo, number, members, param.tokens.token); + for (const member of membersAdded) { + if (members.includes(member)) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + param.isIssue ? `The issue was assigned to @${member}.` : `The pull request was assigned to @${member}.`, + ], + })); + } + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Tried to assign members to issue.`], + error: error, + })); + } + return result; } - sourceObj = filter !== false && getPrototypeOf(sourceObj); - } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); - - return destObj; -}; - -/** - * Determines whether a string ends with the characters of a specified string - * - * @param {String} str - * @param {String} searchString - * @param {Number} [position= 0] - * - * @returns {boolean} - */ -const endsWith = (str, searchString, position) => { - str = String(str); - if (position === undefined || position > str.length) { - position = str.length; - } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; -}; - - -/** - * Returns new array from array like object or null if failed - * - * @param {*} [thing] - * - * @returns {?Array} - */ -const toArray = (thing) => { - if (!thing) return null; - if (isArray(thing)) return thing; - let i = thing.length; - if (!isNumber(i)) return null; - const arr = new Array(i); - while (i-- > 0) { - arr[i] = thing[i]; - } - return arr; -}; - -/** - * Checking if the Uint8Array exists and if it does, it returns a function that checks if the - * thing passed in is an instance of Uint8Array - * - * @param {TypedArray} - * - * @returns {Array} - */ -// eslint-disable-next-line func-names -const isTypedArray = (TypedArray => { - // eslint-disable-next-line func-names - return thing => { - return TypedArray && thing instanceof TypedArray; - }; -})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array)); - -/** - * For each entry in the object, call the function with the key and value. - * - * @param {Object} obj - The object to iterate over. - * @param {Function} fn - The function to call for each entry. - * - * @returns {void} - */ -const forEachEntry = (obj, fn) => { - const generator = obj && obj[iterator]; - - const _iterator = generator.call(obj); - - let result; - - while ((result = _iterator.next()) && !result.done) { - const pair = result.value; - fn.call(obj, pair[0], pair[1]); - } -}; +} +exports.AssignMemberToIssueUseCase = AssignMemberToIssueUseCase; -/** - * It takes a regular expression and a string, and returns an array of all the matches - * - * @param {string} regExp - The regular expression to match against. - * @param {string} str - The string to search. - * - * @returns {Array} - */ -const matchAll = (regExp, str) => { - let matches; - const arr = []; - while ((matches = regExp.exec(str)) !== null) { - arr.push(matches); - } +/***/ }), - return arr; -}; +/***/ 6275: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */ -const isHTMLForm = kindOfTest('HTMLFormElement'); +"use strict"; -const toCamelCase = str => { - return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, - function replacer(m, p1, p2) { - return p1.toUpperCase() + p2; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.AssignReviewersToIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const pull_request_repository_1 = __nccwpck_require__(634); +const logger_1 = __nccwpck_require__(8836); +class AssignReviewersToIssueUseCase { + constructor() { + this.taskId = 'AssignReviewersToIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); } - ); -}; - -/* Creating a function that will check if an object has a property. */ -const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype); - -/** - * Determine if a value is a RegExp object - * - * @param {*} val The value to test - * - * @returns {boolean} True if value is a RegExp object, otherwise false - */ -const isRegExp = kindOfTest('RegExp'); - -const reduceDescriptors = (obj, reducer) => { - const descriptors = Object.getOwnPropertyDescriptors(obj); - const reducedDescriptors = {}; - - forEach(descriptors, (descriptor, name) => { - let ret; - if ((ret = reducer(descriptor, name, obj)) !== false) { - reducedDescriptors[name] = ret || descriptor; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const desiredReviewersCount = param.pullRequest.desiredReviewersCount; + const number = param.pullRequest.number; + const result = []; + try { + (0, logger_1.logDebugInfo)(`#${number} needs ${desiredReviewersCount} reviewers.`); + const currentReviewers = await this.pullRequestRepository.getCurrentReviewers(param.owner, param.repo, number, param.tokens.token); + const currentAssignees = await this.issueRepository.getCurrentAssignees(param.owner, param.repo, number, param.tokens.token); + if (currentReviewers.length >= desiredReviewersCount) { + /** + * No more assignees needed + */ + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return result; + } + const missingReviewers = desiredReviewersCount - currentReviewers.length; + (0, logger_1.logDebugInfo)(`#${number} needs ${missingReviewers} more reviewers.`); + const excludeForReview = []; + excludeForReview.push(param.pullRequest.creator); + excludeForReview.push(...currentReviewers); + excludeForReview.push(...currentAssignees); + const members = await this.projectRepository.getRandomMembers(param.owner, missingReviewers, excludeForReview, param.tokens.token); + if (members.length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to assign members as reviewers to pull request, but no one was found.`, + ], + })); + return result; + } + const reviewersAdded = await this.pullRequestRepository.addReviewersToPullRequest(param.owner, param.repo, number, members, param.tokens.token); + for (const member of reviewersAdded) { + if (members.indexOf(member) > -1) + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `@${member} was requested to review the pull request.`, + ], + })); + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to assign members to issue.`, + ], + error: error, + })); + } + return result; } - }); - - Object.defineProperties(obj, reducedDescriptors); -}; - -/** - * Makes all methods read-only - * @param {Object} obj - */ +} +exports.AssignReviewersToIssueUseCase = AssignReviewersToIssueUseCase; -const freezeMethods = (obj) => { - reduceDescriptors(obj, (descriptor, name) => { - // skip restricted props in strict mode - if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) { - return false; - } - const value = obj[name]; +/***/ }), - if (!isFunction$1(value)) return; +/***/ 151: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - descriptor.enumerable = false; +"use strict"; - if ('writable' in descriptor) { - descriptor.writable = false; - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPriorityIssueSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckPriorityIssueSizeUseCase { + constructor() { + this.taskId = 'CheckPriorityIssueSizeUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); } - - if (!descriptor.set) { - descriptor.set = () => { - throw Error('Can not rewrite read-only method \'' + name + '\''); - }; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const priority = param.labels.priorityLabelOnIssue; + if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + let priorityLabel = ``; + if (priority === param.labels.priorityHigh) { + priorityLabel = `P0`; + } + else if (priority === param.labels.priorityMedium) { + priorityLabel = `P1`; + } + else if (priority === param.labels.priorityLow) { + priorityLabel = `P2`; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + (0, logger_1.logDebugInfo)(`Priority: ${priority}`); + (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); + for (const project of param.project.getProjects()) { + const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.issueNumber, priorityLabel, param.tokens.token); + if (success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, + ], + })); + } + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the priority of the issue, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } - }); -}; - -const toObjectSet = (arrayOrString, delimiter) => { - const obj = {}; - - const define = (arr) => { - arr.forEach(value => { - obj[value] = true; - }); - }; - - isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter)); - - return obj; -}; - -const noop = () => {}; - -const toFiniteNumber = (value, defaultValue) => { - return value != null && Number.isFinite(value = +value) ? value : defaultValue; -}; - - - -/** - * If the thing is a FormData object, return true, otherwise return false. - * - * @param {unknown} thing - The thing to check. - * - * @returns {boolean} - */ -function isSpecCompliantForm(thing) { - return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]); } +exports.CheckPriorityIssueSizeUseCase = CheckPriorityIssueSizeUseCase; -const toJSONObject = (obj) => { - const stack = new Array(10); - - const visit = (source, i) => { - - if (isObject(source)) { - if (stack.indexOf(source) >= 0) { - return; - } - - //Buffer check - if (isBuffer(source)) { - return source; - } - if(!('toJSON' in source)) { - stack[i] = source; - const target = isArray(source) ? [] : {}; +/***/ }), - forEach(source, (value, key) => { - const reducedValue = visit(value, i + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); - }); +/***/ 5137: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - stack[i] = undefined; +"use strict"; - return target; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloseIssueAfterMergingUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const supabase_repository_1 = __nccwpck_require__(9829); +const logger_1 = __nccwpck_require__(8836); +class CloseIssueAfterMergingUseCase { + constructor() { + this.taskId = 'CloseIssueAfterMergingUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.removeBranches = async (supabaseRepository, param, branch) => { + const result = []; + if (!supabaseRepository) { + return result; + } + try { + await supabaseRepository.removeAIFileCacheByBranch(param.owner, param.repo, branch); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `AI index was removed from \`${branch}\`.`, + ] + })); + } + catch (error) { + (0, logger_1.logError)(`Error removing AI cache: ${JSON.stringify(error, null, 2)}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `There was an error removing the AI index from \`${branch}\`.`, + ], + errors: [ + JSON.stringify(error, null, 2), + ], + })); + } + return result; + }; } - - return source; - }; - - return visit(obj, 0); -}; - -const isAsyncFn = kindOfTest('AsyncFunction'); - -const isThenable = (thing) => - thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch); - -// original code -// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34 - -const _setImmediate = ((setImmediateSupported, postMessageSupported) => { - if (setImmediateSupported) { - return setImmediate; - } - - return postMessageSupported ? ((token, callbacks) => { - _global.addEventListener("message", ({source, data}) => { - if (source === _global && data === token) { - callbacks.length && callbacks.shift()(); - } - }, false); - - return (cb) => { - callbacks.push(cb); - _global.postMessage(token, "*"); + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + let supabaseRepository = undefined; + if (param.supabaseConfig) { + supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + } + const result = []; + try { + const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (closed) { + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue was closed after merging #${param.pullRequest.number}.`, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `#${param.issueNumber} was automatically closed after merging this pull request.` + ] + })); + result.push(...await this.removeBranches(supabaseRepository, param, param.pullRequest.head.replace('refs/heads/', ''))); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to close issue #${param.issueNumber}, but there was a problem.`, + ], + error: error, + })); + } + return result; } - })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb); -})( - typeof setImmediate === 'function', - isFunction$1(_global.postMessage) -); - -const asap = typeof queueMicrotask !== 'undefined' ? - queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate); - -// ********************* - - -const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]); - - -const utils$1 = { - isArray, - isArrayBuffer, - isBuffer, - isFormData, - isArrayBufferView, - isString, - isNumber, - isBoolean, - isObject, - isPlainObject, - isEmptyObject, - isReadableStream, - isRequest, - isResponse, - isHeaders, - isUndefined, - isDate, - isFile, - isBlob, - isRegExp, - isFunction: isFunction$1, - isStream, - isURLSearchParams, - isTypedArray, - isFileList, - forEach, - merge, - extend, - trim, - stripBOM, - inherits, - toFlatObject, - kindOf, - kindOfTest, - endsWith, - toArray, - forEachEntry, - matchAll, - isHTMLForm, - hasOwnProperty, - hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection - reduceDescriptors, - freezeMethods, - toObjectSet, - toCamelCase, - noop, - toFiniteNumber, - findKey, - global: _global, - isContextDefined, - isSpecCompliantForm, - toJSONObject, - isAsyncFn, - isThenable, - setImmediate: _setImmediate, - asap, - isIterable -}; - -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [config] The config. - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * - * @returns {Error} The created error. - */ -function AxiosError(message, code, config, request, response) { - Error.call(this); - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = (new Error()).stack; - } - - this.message = message; - this.name = 'AxiosError'; - code && (this.code = code); - config && (this.config = config); - request && (this.request = request); - if (response) { - this.response = response; - this.status = response.status ? response.status : null; - } } +exports.CloseIssueAfterMergingUseCase = CloseIssueAfterMergingUseCase; -utils$1.inherits(AxiosError, Error, { - toJSON: function toJSON() { - return { - // Standard - message: this.message, - name: this.name, - // Microsoft - description: this.description, - number: this.number, - // Mozilla - fileName: this.fileName, - lineNumber: this.lineNumber, - columnNumber: this.columnNumber, - stack: this.stack, - // Axios - config: utils$1.toJSONObject(this.config), - code: this.code, - status: this.status - }; - } -}); - -const prototype$1 = AxiosError.prototype; -const descriptors = {}; -[ - 'ERR_BAD_OPTION_VALUE', - 'ERR_BAD_OPTION', - 'ECONNABORTED', - 'ETIMEDOUT', - 'ERR_NETWORK', - 'ERR_FR_TOO_MANY_REDIRECTS', - 'ERR_DEPRECATED', - 'ERR_BAD_RESPONSE', - 'ERR_BAD_REQUEST', - 'ERR_CANCELED', - 'ERR_NOT_SUPPORT', - 'ERR_INVALID_URL' -// eslint-disable-next-line func-names -].forEach(code => { - descriptors[code] = {value: code}; -}); +/***/ }), -Object.defineProperties(AxiosError, descriptors); -Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); +/***/ 7826: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// eslint-disable-next-line func-names -AxiosError.from = (error, code, config, request, response, customProps) => { - const axiosError = Object.create(prototype$1); +"use strict"; - utils$1.toFlatObject(error, axiosError, function filter(obj) { - return obj !== Error.prototype; - }, prop => { - return prop !== 'isAxiosError'; - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CloseNotAllowedIssueUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class CloseNotAllowedIssueUseCase { + constructor() { + this.taskId = 'CloseNotAllowedIssueUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const closed = await this.issueRepository.closeIssue(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (closed) { + await this.issueRepository.addComment(param.owner, param.repo, param.issueNumber, `This issue has been closed because the author is not a member of the project. The user may be banned if the fact is repeated.`, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `#${param.issueNumber} was automatically closed because the author is not a member of the project.` + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to close issue #${param.issueNumber}, but there was a problem.`, + ], + error: error, + })); + } + return result; + } +} +exports.CloseNotAllowedIssueUseCase = CloseNotAllowedIssueUseCase; - const msg = error && error.message ? error.message : 'Error'; - // Prefer explicit code; otherwise copy the low-level error's code (e.g. ECONNREFUSED) - const errCode = code == null && error ? error.code : code; - AxiosError.call(axiosError, msg, errCode, config, request, response); +/***/ }), - // Chain the original error on the standard field; non-enumerable to avoid JSON noise - if (error && axiosError.cause == null) { - Object.defineProperty(axiosError, 'cause', { value: error, configurable: true }); - } +/***/ 5678: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - axiosError.name = (error && error.name) || 'Error'; +"use strict"; - customProps && Object.assign(axiosError, customProps); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DeployAddedUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const content_utils_1 = __nccwpck_require__(7873); +const logger_1 = __nccwpck_require__(8836); +class DeployAddedUseCase { + constructor() { + this.taskId = 'DeployAddedUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.issue.labeled && param.issue.labelAdded === param.labels.deploy) { + (0, logger_1.logDebugInfo)(`Deploying requested.`); + if (param.release.active && param.release.branch !== undefined) { + const sanitizedTitle = param.issue.title + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + const description = param.issue.body?.match(/### Changelog\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; + const escapedDescription = description.replace(/\n/g, '\\n'); + const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; + const parameters = { + version: param.release.version, + title: sanitizedTitle, + changelog: escapedDescription, + issue: `${param.issue.number}`, + }; + await this.branchRepository.executeWorkflow(param.owner, param.repo, param.release.branch, param.workflows.release, parameters, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Executed release workflow [**${param.workflows.release}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.release}) on [**${param.release.branch}**](${releaseUrl}). - return axiosError; -}; +${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}` + ] + })); + } + else if (param.hotfix.active && param.hotfix.branch !== undefined) { + const sanitizedTitle = param.issue.title + .replace(/\b\d+(\.\d+){2,}\b/g, '') + .replace(/[^\p{L}\p{N}\p{P}\p{Z}^$\n]/gu, '') + .replace(/\u200D/g, '') + .replace(/[^\S\r\n]+/g, ' ') + .replace(/[^a-zA-Z0-9 .]/g, '') + .replace(/^-+|-+$/g, '') + .replace(/- -/g, '-').trim() + .replace(/-+/g, '-') + .trim(); + const description = param.issue.body?.match(/### Hotfix Solution\n\n([\s\S]*?)(?=\n\n|$)/)?.[1]?.trim() ?? 'No changelog provided'; + const escapedDescription = description.replace(/\n/g, '\\n'); + const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; + const parameters = { + version: param.hotfix.version, + title: sanitizedTitle, + changelog: escapedDescription, + issue: param.issue.number, + }; + await this.branchRepository.executeWorkflow(param.owner, param.repo, param.hotfix.branch, param.workflows.release, parameters, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Executed hotfix workflow [**${param.workflows.hotfix}**](https://github.com/${param.owner}/${param.repo}/actions/workflows/${param.workflows.hotfix}) on [**${param.hotfix.branch}**](${hotfixUrl}). -/** - * Determines if the given thing is a array or js object. - * - * @param {string} thing - The object or array to be visited. - * - * @returns {boolean} - */ -function isVisitable(thing) { - return utils$1.isPlainObject(thing) || utils$1.isArray(thing); +${(0, content_utils_1.injectJsonAsMarkdownBlock)('Workflow Parameters', parameters)}\`` + ] + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to work with workflows, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; + } } +exports.DeployAddedUseCase = DeployAddedUseCase; -/** - * It removes the brackets from the end of a string - * - * @param {string} key - The key of the parameter. - * - * @returns {string} the key without the brackets. - */ -function removeBrackets(key) { - return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; -} -/** - * It takes a path, a key, and a boolean, and returns a string - * - * @param {string} path - The path to the current key. - * @param {string} key - The key of the current object being iterated over. - * @param {string} dots - If true, the key will be rendered with dots instead of brackets. - * - * @returns {string} The path to the current key. - */ -function renderKey(path, key, dots) { - if (!path) return key; - return path.concat(key).map(function each(token, i) { - // eslint-disable-next-line no-param-reassign - token = removeBrackets(token); - return !dots && i ? '[' + token + ']' : token; - }).join(dots ? '.' : ''); -} +/***/ }), -/** - * If the array is an array and none of its elements are visitable, then it's a flat array. - * - * @param {Array} arr - The array to check - * - * @returns {boolean} - */ -function isFlatArray(arr) { - return utils$1.isArray(arr) && !arr.some(isVisitable); -} +/***/ 8388: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { - return /^is[A-Z]/.test(prop); -}); +"use strict"; -/** - * Convert a data object to FormData - * - * @param {Object} obj - * @param {?Object} [formData] - * @param {?Object} [options] - * @param {Function} [options.visitor] - * @param {Boolean} [options.metaTokens = true] - * @param {Boolean} [options.dots = false] - * @param {?Boolean} [options.indexes = false] - * - * @returns {Object} - **/ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DeployedAddedUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const logger_1 = __nccwpck_require__(8836); +class DeployedAddedUseCase { + constructor() { + this.taskId = 'DeployedAddedUseCase'; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + if (param.issue.labeled && param.issue.labelAdded === param.labels.deployed) { + (0, logger_1.logDebugInfo)(`Deploy complete.`); + if (param.release.active && param.release.branch !== undefined) { + const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Deploy complete from [${param.release.branch}](${releaseUrl})` + ] + })); + } + else if (param.hotfix.active && param.hotfix.branch !== undefined) { + const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Deploy complete from [${param.hotfix.branch}](${hotfixUrl})` + ] + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to complete the deployment, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; + } +} +exports.DeployedAddedUseCase = DeployedAddedUseCase; -/** - * It converts an object into a FormData object - * - * @param {Object} obj - The object to convert to form data. - * @param {string} formData - The FormData object to append to. - * @param {Object} options - * - * @returns - */ -function toFormData(obj, formData, options) { - if (!utils$1.isObject(obj)) { - throw new TypeError('target must be an object'); - } - - // eslint-disable-next-line no-param-reassign - formData = formData || new (FormData__default["default"] || FormData)(); - - // eslint-disable-next-line no-param-reassign - options = utils$1.toFlatObject(options, { - metaTokens: true, - dots: false, - indexes: false - }, false, function defined(option, source) { - // eslint-disable-next-line no-eq-null,eqeqeq - return !utils$1.isUndefined(source[option]); - }); - const metaTokens = options.metaTokens; - // eslint-disable-next-line no-use-before-define - const visitor = options.visitor || defaultVisitor; - const dots = options.dots; - const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; - const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); +/***/ }), - if (!utils$1.isFunction(visitor)) { - throw new TypeError('visitor must be a function'); - } +/***/ 7528: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function convertValue(value) { - if (value === null) return ''; +"use strict"; - if (utils$1.isDate(value)) { - return value.toISOString(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LinkIssueProjectUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class LinkIssueProjectUseCase { + constructor() { + this.taskId = 'LinkIssueProjectUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); } - - if (utils$1.isBoolean(value)) { - return value.toString(); + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + const columnName = param.project.getProjectColumnIssueCreated(); + try { + for (const project of param.project.getProjects()) { + const issueId = await this.issueRepository.getId(param.owner, param.repo, param.issue.number, param.tokens.token); + let actionDone = await this.projectRepository.linkContentId(project, issueId, param.tokens.token); + if (actionDone) { + /** + * Wait for 10 seconds to ensure the issue is linked to the project + */ + await new Promise(resolve => setTimeout(resolve, 10000)); + actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issue.number, columnName, param.tokens.token); + if (actionDone) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The issue was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, + ] + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + steps: [] + })); + } + } + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to link issue to project, but there was a problem.`, + ], + error: error, + })); + } + return result; } +} +exports.LinkIssueProjectUseCase = LinkIssueProjectUseCase; - if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError('Blob is not supported. Use a Buffer instead.'); - } - if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); - } +/***/ }), - return value; - } +/***/ 8203: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /** - * Default visitor. - * - * @param {*} value - * @param {String|Number} key - * @param {Array} path - * @this {FormData} - * - * @returns {boolean} return true to visit the each prop of the value recursively - */ - function defaultVisitor(value, key, path) { - let arr = value; - - if (value && !path && typeof value === 'object') { - if (utils$1.endsWith(key, '{}')) { - // eslint-disable-next-line no-param-reassign - key = metaTokens ? key : key.slice(0, -2); - // eslint-disable-next-line no-param-reassign - value = JSON.stringify(value); - } else if ( - (utils$1.isArray(value) && isFlatArray(value)) || - ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) - )) { - // eslint-disable-next-line no-param-reassign - key = removeBrackets(key); - - arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append( - // eslint-disable-next-line no-nested-ternary - indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), - convertValue(el) - ); - }); - return false; - } - } +"use strict"; - if (isVisitable(value)) { - return true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.MoveIssueToInProgressUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class MoveIssueToInProgressUseCase { + constructor() { + this.taskId = 'MoveIssueToInProgressUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + const columnName = param.project.getProjectColumnIssueInProgress(); + try { + for (const project of param.project.getProjects()) { + const success = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.issueNumber, columnName, param.tokens.token); + if (success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Moved issue to \`${columnName}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, + ], + })); + } + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to move the issue to \`${columnName}\`, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; + } +} +exports.MoveIssueToInProgressUseCase = MoveIssueToInProgressUseCase; - formData.append(renderKey(path, key, dots), convertValue(value)); - - return false; - } - const stack = []; +/***/ }), - const exposedHelpers = Object.assign(predicates, { - defaultVisitor, - convertValue, - isVisitable - }); +/***/ 4423: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - function build(value, path) { - if (utils$1.isUndefined(value)) return; +"use strict"; - if (stack.indexOf(value) !== -1) { - throw Error('Circular reference detected in ' + path.join('.')); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PrepareBranchesUseCase = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const supabase_repository_1 = __nccwpck_require__(9829); +const logger_1 = __nccwpck_require__(8836); +const execute_script_use_case_1 = __nccwpck_require__(155); +const move_issue_to_in_progress_1 = __nccwpck_require__(8203); +class PrepareBranchesUseCase { + constructor() { + this.taskId = 'PrepareBranchesUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + this.duplicateAICacheByBranch = async (supabaseRepository, param, sourceBranch, targetBranch) => { + const result = []; + if (!supabaseRepository) { + return result; + } + try { + await supabaseRepository.duplicateAIFileCacheByBranch(param.owner, param.repo, sourceBranch, targetBranch); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `AI index was duplicated from \`${sourceBranch}\` to \`${targetBranch}\`.`, + ] + })); + } + catch (error) { + (0, logger_1.logError)(`Error duplicating AI cache: ${JSON.stringify(error, null, 2)}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `There was an error duplicating the AI index from \`${sourceBranch}\` to \`${targetBranch}\`.`, + ], + errors: [ + JSON.stringify(error, null, 2), + ], + })); + } + return result; + }; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + let supabaseRepository = undefined; + if (param.supabaseConfig) { + supabaseRepository = new supabase_repository_1.SupabaseRepository(param.supabaseConfig); + } + const result = []; + try { + const issueTitle = param.issue.title; + if (!param.labels.isMandatoryBranchedLabel && issueTitle.length === 0) { + core.setFailed('Issue title not available.'); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + reminders: [ + `Tried to check the title but no one was found.` + ] + })); + return result; + } + /** + * Fetch all branches/tags + */ + await this.branchRepository.fetchRemoteBranches(); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `Take a coffee break while you work ā˜•.` + ] + })); + const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); + (0, logger_1.logDebugInfo)('Available branches:'); + branches.forEach(branch => { + (0, logger_1.logDebugInfo)(`- ${branch}`); + }); + if (param.hotfix.active) { + if (param.hotfix.baseVersion !== undefined && param.hotfix.version !== undefined && param.hotfix.branch !== undefined && param.hotfix.baseBranch !== undefined) { + const branchOid = await this.branchRepository.getCommitTag(param.hotfix.baseVersion); + const tagUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.baseBranch}`; + const hotfixUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.hotfix.branch}`; + (0, logger_1.logDebugInfo)(`Tag branch: ${param.hotfix.baseBranch}`); + (0, logger_1.logDebugInfo)(`Hotfix branch: ${param.hotfix.branch}`); + param.currentConfiguration.parentBranch = param.hotfix.baseBranch; + param.currentConfiguration.hotfixBranch = param.hotfix.branch; + param.currentConfiguration.workingBranch = param.hotfix.branch; + if (branches.indexOf(param.hotfix.branch) === -1) { + const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.hotfix.baseBranch, param.hotfix.branch, param.issueNumber, branchOid, param.tokens.token); + if (linkResult[linkResult.length - 1].success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The tag [**${param.hotfix.baseBranch}**](${tagUrl}) was used to create the branch [**${param.hotfix.branch}**](${hotfixUrl})`, + ], + })); + (0, logger_1.logDebugInfo)(`Hotfix branch successfully linked to issue: ${JSON.stringify(linkResult)}`); + result.push(...await this.duplicateAICacheByBranch(supabaseRepository, param, param.branches.main, param.hotfix.branch)); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch [**${param.hotfix.branch}**](${hotfixUrl}) already exists and will not be created from the tag [**${param.hotfix.baseBranch}**](${tagUrl}).`, + ], + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to create a hotfix but no tag was found.`, + ] + })); + return result; + } + } + else if (param.release.active) { + if (param.release.version !== undefined && param.release.branch !== undefined) { + param.currentConfiguration.releaseBranch = param.release.branch; + param.currentConfiguration.workingBranch = param.release.branch; + (0, logger_1.logDebugInfo)(`Release branch: ${param.release.branch}`); + param.currentConfiguration.parentBranch = param.branches.development; + const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; + const releaseUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.release.branch}`; + const mainUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.defaultBranch}`; + if (branches.indexOf(param.release.branch) === -1) { + const linkResult = await this.branchRepository.createLinkedBranch(param.owner, param.repo, param.branches.development, param.release.branch, param.issueNumber, undefined, param.tokens.token); + const lastAction = linkResult[linkResult.length - 1]; + const reminders = []; + if (lastAction.success) { + const branchName = lastAction.payload.newBranchName; + let commitPrefix = ''; + if (param.commitPrefixBuilder.length > 0) { + param.commitPrefixBuilderParams = { + branchName: branchName, + }; + const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); + const prefixResult = await executor.invoke(param); + commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; + } + reminders.push(`Before deploying, apply any change needed in [**${param.release.branch}**](${releaseUrl}): +> \`\`\`bash +> git fetch -v && git checkout ${param.release.branch} +> \`\`\` +> +> Version files, changelogs..`); + if (commitPrefix.length > 0) { + reminders.push(`Commit the needed changes with this prefix: +> \`\`\` +>${commitPrefix} +> \`\`\``); + } + reminders.push(...[ + `Create the tag version in [**${param.release.branch}**](${releaseUrl}). +> Avoid using \`git merge --squash\`, otherwise the created tag will be lost.`, + `Add the **${param.labels.deploy}** label to run the \`${param.workflows.release}\` workflow.`, + `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). +> **Quick actions:** +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, + ]); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch [**${param.branches.development}**](${developmentUrl}) was used to create the branch [**${param.release.branch}**](${releaseUrl})`, + ], + reminders: reminders, + })); + (0, logger_1.logDebugInfo)(`Release branch successfully linked to issue: ${JSON.stringify(linkResult)}`); + result.push(...await this.duplicateAICacheByBranch(supabaseRepository, param, param.branches.development, param.release.branch)); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `After deploying, the new changes on [\`${param.release.branch}\`](${releaseUrl}) must end on [\`${param.branches.development}\`](${developmentUrl}) and [\`${param.branches.main}\`](${mainUrl}). +> **Quick actions:** +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.development}\`](${developmentUrl}). +> [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${param.release.branch}?expand=1) from [\`${param.release.branch}\`](${releaseUrl}) to [\`${param.branches.main}\`](${mainUrl}).`, + ], + })); + } + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to create a release but no release version was found.`, + ] + })); + } + return result; + } + (0, logger_1.logDebugInfo)(`Branch type: ${param.managementBranch}`); + const branchesResult = await this.branchRepository.manageBranches(param, param.owner, param.repo, param.issueNumber, issueTitle, param.managementBranch, param.branches.development, param.hotfix?.branch, param.hotfix.active, param.tokens.token); + result.push(...branchesResult); + const lastAction = branchesResult[branchesResult.length - 1]; + if (lastAction.success && lastAction.executed) { + const branchName = lastAction.payload.newBranchName; + param.currentConfiguration.workingBranch = branchName; + let commitPrefix = ''; + if (param.commitPrefixBuilder.length > 0) { + param.commitPrefixBuilderParams = { + branchName: branchName, + }; + const executor = new execute_script_use_case_1.CommitPrefixBuilderUseCase(); + const prefixResult = await executor.invoke(param); + commitPrefix = prefixResult[prefixResult.length - 1].payload['scriptResult'].toString() ?? ''; + } + const rename = lastAction.payload.baseBranchName.indexOf(`${param.branches.featureTree}/`) > -1 + || lastAction.payload.baseBranchName.indexOf(`${param.branches.bugfixTree}/`) > -1; + let step; + let reminder; + if (rename) { + const developmentUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.development}`; + step = `The branch **${lastAction.payload.baseBranchName}** was renamed to [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; + reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${param.branches.development}\`](${developmentUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.development}...${lastAction.payload.newBranchName}?expand=1)`; + } + else { + step = `The branch [**${lastAction.payload.baseBranchName}**](${lastAction.payload.baseBranchUrl}) was used to create [**${lastAction.payload.newBranchName}**](${lastAction.payload.newBranchUrl}).`; + reminder = `Open a Pull Request from [\`${lastAction.payload.newBranchName}\`](${lastAction.payload.newBranchUrl}) to [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${lastAction.payload.baseBranchName}...${lastAction.payload.newBranchName}?expand=1)`; + } + const reminders = []; + reminders.push(`Check out the branch: +> \`\`\`bash +> git fetch -v && git checkout ${lastAction.payload.newBranchName} +> \`\`\``); + if (commitPrefix.length > 0) { + reminders.push(`Commit the needed changes with this prefix: +> \`\`\` +>${commitPrefix} +> \`\`\``); + } + reminders.push(reminder); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + step, + ], + reminders: reminders, + })); + if (param.hotfix.active) { + const mainBranchUrl = `https://github.com/${param.owner}/${param.repo}/tree/${param.branches.main}`; + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `After merging into [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}), open a Pull Request from [\`${lastAction.payload.baseBranchName}\`](${lastAction.payload.baseBranchUrl}) to [\`${param.branches.main}\`](${mainBranchUrl}). [New PR](https://github.com/${param.owner}/${param.repo}/compare/${param.branches.main}...${lastAction.payload.baseBranchName}?expand=1)`, + `After merging into [\`${param.branches.main}\`](${mainBranchUrl}), create the tag \`${param.hotfix.version}\`.`, + ] + })); + } + result.push(...await this.duplicateAICacheByBranch(supabaseRepository, param, param.branches.development, lastAction.payload.newBranchName)); + await new Promise(resolve => setTimeout(resolve, 10000)); + result.push(...await new move_issue_to_in_progress_1.MoveIssueToInProgressUseCase().invoke(param)); + } + return result; + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to prepare the hotfix branch to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; } - - stack.push(value); - - utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( - formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers - ); - - if (result === true) { - build(el, path ? path.concat(key) : [key]); - } - }); - - stack.pop(); - } - - if (!utils$1.isObject(obj)) { - throw new TypeError('data must be an object'); - } - - build(obj); - - return formData; -} - -/** - * It encodes a string by replacing all characters that are not in the unreserved set with - * their percent-encoded equivalents - * - * @param {string} str - The string to encode. - * - * @returns {string} The encoded string. - */ -function encode$1(str) { - const charMap = { - '!': '%21', - "'": '%27', - '(': '%28', - ')': '%29', - '~': '%7E', - '%20': '+', - '%00': '\x00' - }; - return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) { - return charMap[match]; - }); -} - -/** - * It takes a params object and converts it to a FormData object - * - * @param {Object} params - The parameters to be converted to a FormData object. - * @param {Object} options - The options object passed to the Axios constructor. - * - * @returns {void} - */ -function AxiosURLSearchParams(params, options) { - this._pairs = []; - - params && toFormData(params, this, options); } +exports.PrepareBranchesUseCase = PrepareBranchesUseCase; -const prototype = AxiosURLSearchParams.prototype; -prototype.append = function append(name, value) { - this._pairs.push([name, value]); -}; +/***/ }), -prototype.toString = function toString(encoder) { - const _encode = encoder ? function(value) { - return encoder.call(this, value, encode$1); - } : encode$1; +/***/ 2354: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return this._pairs.map(function each(pair) { - return _encode(pair[0]) + '=' + _encode(pair[1]); - }, '').join('&'); -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RemoveIssueBranchesUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const logger_1 = __nccwpck_require__(8836); /** - * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their - * URI encoded counterparts - * - * @param {string} val The value to be encoded. - * - * @returns {string} The encoded value. + * Remove any branch created for this issue */ -function encode(val) { - return encodeURIComponent(val). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'); +class RemoveIssueBranchesUseCase { + constructor() { + this.taskId = 'RemoveIssueBranchesUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + try { + const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; + const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); + for (const type of branchTypes) { + (0, logger_1.logDebugInfo)(`Checking branch type ${type}`); + let branchName = ''; + const prefix = `${type}/${param.issueNumber}-`; + (0, logger_1.logDebugInfo)(`Checking prefix ${prefix}`); + const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); + if (!matchingBranch) + continue; + branchName = matchingBranch; + const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); + if (removed) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch \`${branchName}\` was removed.`, + ], + })); + if (param.previousConfiguration?.branchType === param.branches.hotfixTree) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + reminders: [ + `Determine if the \`${param.branches.hotfixTree}\` branch is no longer required and can be removed.`, + ], + })); + } + } + } + } + catch (error) { + (0, logger_1.logError)(error); + results.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update issue's title, but there was a problem.`, + ], + error: error, + })); + } + return results; + } } +exports.RemoveIssueBranchesUseCase = RemoveIssueBranchesUseCase; -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @param {?(object|Function)} options - * - * @returns {string} The formatted url - */ -function buildURL(url, params, options) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - - const _encode = options && options.encode || encode; - - if (utils$1.isFunction(options)) { - options = { - serialize: options - }; - } - - const serializeFn = options && options.serialize; - let serializedParams; +/***/ }), - if (serializeFn) { - serializedParams = serializeFn(params, options); - } else { - serializedParams = utils$1.isURLSearchParams(params) ? - params.toString() : - new AxiosURLSearchParams(params, options).toString(_encode); - } +/***/ 773: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (serializedParams) { - const hashmarkIndex = url.indexOf("#"); +"use strict"; - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); +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]; } }; } - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } - - return url; -} - -class InterceptorManager { - constructor() { - this.handlers = []; - } - - /** - * Add a new interceptor to the stack - * - * @param {Function} fulfilled The function to handle `then` for a `Promise` - * @param {Function} rejected The function to handle `reject` for a `Promise` - * - * @return {Number} An ID used to remove interceptor later - */ - use(fulfilled, rejected, options) { - this.handlers.push({ - fulfilled, - rejected, - synchronous: options ? options.synchronous : false, - runWhen: options ? options.runWhen : null - }); - return this.handlers.length - 1; - } - - /** - * Remove an interceptor from the stack - * - * @param {Number} id The ID that was returned by `use` - * - * @returns {void} - */ - eject(id) { - if (this.handlers[id]) { - this.handlers[id] = null; + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.RemoveNotNeededBranchesUseCase = void 0; +const core = __importStar(__nccwpck_require__(2186)); +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const logger_1 = __nccwpck_require__(8836); +class RemoveNotNeededBranchesUseCase { + constructor() { + this.taskId = 'RemoveNotNeededBranchesUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); } - } - - /** - * Clear all interceptors from the stack - * - * @returns {void} - */ - clear() { - if (this.handlers) { - this.handlers = []; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const issueTitle = param.issue.title; + if (issueTitle.length === 0) { + core.setFailed('Issue title not available.'); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Tried to remove not needed branches related to the issue, but the issue title was not found.`, + ], + })); + return result; + } + const sanitizedTitle = this.branchRepository.formatBranchName(issueTitle, param.issueNumber); + const branches = await this.branchRepository.getListOfBranches(param.owner, param.repo, param.tokens.token); + const finalBranch = `${param.managementBranch}/${param.issueNumber}-${sanitizedTitle}`; + const branchTypes = [param.branches.featureTree, param.branches.bugfixTree]; + for (const type of branchTypes) { + let branchName = `${type}/${param.issueNumber}-${sanitizedTitle}`; + const prefix = `${type}/${param.issueNumber}-`; + if (type !== param.managementBranch) { + const matchingBranch = branches.find(branch => branch.indexOf(prefix) > -1); + if (!matchingBranch) { + continue; + } + branchName = matchingBranch; + const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branchName, param.tokens.token); + if (removed) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch \`${branchName}\` was removed.`, + ], + })); + } + else { + (0, logger_1.logError)(`Error deleting ${branchName}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to remove not needed branch \`${branchName}\`, but there was a problem.`, + ], + })); + } + } + else { + for (const branch of branches) { + if (branch.indexOf(prefix) > -1 && branch !== finalBranch) { + const removed = await this.branchRepository.removeBranch(param.owner, param.repo, branch, param.tokens.token); + if (removed) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The branch \`${branch}\` was removed.`, + ], + })); + } + else { + (0, logger_1.logError)(`Error deleting ${branch}`); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to remove not needed branch \`${branch}\`, but there was a problem.`, + ], + })); + } + } + } + } + } + } + catch (error) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to remove not needed branches related to the issue, but there was a problem.`, + ], + error: error, + })); + } + return result; } - } - - /** - * Iterate over all the registered interceptors - * - * This method is particularly useful for skipping over any - * interceptors that may have become `null` calling `eject`. - * - * @param {Function} fn The function to call for each interceptor - * - * @returns {void} - */ - forEach(fn) { - utils$1.forEach(this.handlers, function forEachHandler(h) { - if (h !== null) { - fn(h); - } - }); - } } +exports.RemoveNotNeededBranchesUseCase = RemoveNotNeededBranchesUseCase; -const InterceptorManager$1 = InterceptorManager; - -const transitionalDefaults = { - silentJSONParsing: true, - forcedJSONParsing: true, - clarifyTimeoutError: false -}; - -const URLSearchParams = url__default["default"].URLSearchParams; - -const ALPHA = 'abcdefghijklmnopqrstuvwxyz'; - -const DIGIT = '0123456789'; -const ALPHABET = { - DIGIT, - ALPHA, - ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT -}; +/***/ }), -const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { - let str = ''; - const {length} = alphabet; - const randomValues = new Uint32Array(size); - crypto__default["default"].randomFillSync(randomValues); - for (let i = 0; i < size; i++) { - str += alphabet[randomValues[i] % length]; - } +/***/ 1652: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return str; -}; +"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UpdateIssueTypeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class UpdateIssueTypeUseCase { + constructor() { + this.taskId = 'UpdateIssueTypeUseCase'; + this.issueRepository = new issue_repository_1.IssueRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + await this.issueRepository.setIssueType(param.owner, param.repo, param.issueNumber, param.labels, param.issueTypes, param.tokens.token); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to update issue type, but there was a problem.`, + ], + error: error, + })); + } + return result; + } +} +exports.UpdateIssueTypeUseCase = UpdateIssueTypeUseCase; -const platform$1 = { - isNode: true, - classes: { - URLSearchParams, - FormData: FormData__default["default"], - Blob: typeof Blob !== 'undefined' && Blob || null - }, - ALPHABET, - generateString, - protocols: [ 'http', 'https', 'file', 'data' ] -}; -const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined'; +/***/ }), -const _navigator = typeof navigator === 'object' && navigator || undefined; +/***/ 465: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Determine if we're running in a standard browser environment - * - * This allows axios to run in a web worker, and react-native. - * Both environments support XMLHttpRequest, but not fully standard globals. - * - * web workers: - * typeof window -> undefined - * typeof document -> undefined - * - * react-native: - * navigator.product -> 'ReactNative' - * nativescript - * navigator.product -> 'NativeScript' or 'NS' - * - * @returns {boolean} - */ -const hasStandardBrowserEnv = hasBrowserEnv && - (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0); +"use strict"; -/** - * Determine if we're running in a standard browser webWorker environment - * - * Although the `isStandardBrowserEnv` method indicates that - * `allows axios to run in a web worker`, the WebWorker will still be - * filtered out due to its judgment standard - * `typeof window !== 'undefined' && typeof document !== 'undefined'`. - * This leads to a problem when axios post `FormData` in webWorker - */ -const hasStandardBrowserWebWorkerEnv = (() => { - return ( - typeof WorkerGlobalScope !== 'undefined' && - // eslint-disable-next-line no-undef - self instanceof WorkerGlobalScope && - typeof self.importScripts === 'function' - ); -})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckIssueCommentLanguageUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class CheckIssueCommentLanguageUseCase { + constructor() { + this.taskId = 'CheckIssueCommentLanguageUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.translatedKey = ``; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + const commentBody = param.issue.commentBody; + if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return results; + } + const locale = param.locale.issue; + let prompt = ` + You are a helpful assistant that checks if the text is written in ${locale}. + + Instructions: + 1. Analyze the provided text + 2. If the text is written in ${locale}, respond with exactly "done" + 3. If the text is written in any other language, respond with exactly "must_translate" + 4. Do not provide any explanation or additional text + + The text is: ${commentBody} + `; + let result = await this.aiRepository.ask(param.ai, prompt); + if (result === "done") { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return results; + } + prompt = ` +You are a helpful assistant that translates the text to ${locale}. -const origin = hasBrowserEnv && window.location.href || 'http://localhost'; +Instructions: +1. Translate the text to ${locale} +2. Do not provide any explanation or additional text +3. Return the translated text only -const utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv, - navigator: _navigator, - origin: origin -}); +The text is: ${commentBody} + `; + result = await this.aiRepository.ask(param.ai, prompt); + const translatedCommentBody = `${result} +> ${commentBody} +${this.translatedKey} +`; + (0, logger_1.logInfo)(`šŸ”Ž Issue number: ${param.issue.number}`); + await this.issueRepository.updateComment(param.owner, param.repo, param.issue.number, param.issue.commentId, translatedCommentBody, param.tokens.token); + return results; + } +} +exports.CheckIssueCommentLanguageUseCase = CheckIssueCommentLanguageUseCase; -const platform = { - ...utils, - ...platform$1 -}; -function toURLEncodedForm(data, options) { - return toFormData(data, new platform.classes.URLSearchParams(), { - visitor: function(value, key, path, helpers) { - if (platform.isNode && utils$1.isBuffer(value)) { - this.append(key, value.toString('base64')); - return false; - } +/***/ }), - return helpers.defaultVisitor.apply(this, arguments); - }, - ...options - }); -} +/***/ 8129: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z'] - * - * @param {string} name - The name of the property to get. - * - * @returns An array of strings. - */ -function parsePropPath(name) { - // foo[x][y][z] - // foo.x.y.z - // foo-x-y-z - // foo x y z - return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => { - return match[0] === '[]' ? '' : match[1] || match[0]; - }); -} +"use strict"; -/** - * Convert an array to an object. - * - * @param {Array} arr - The array to convert to an object. - * - * @returns An object with the same keys and values as the array. - */ -function arrayToObject(arr) { - const obj = {}; - const keys = Object.keys(arr); - let i; - const len = keys.length; - let key; - for (i = 0; i < len; i++) { - key = keys[i]; - obj[key] = arr[key]; - } - return obj; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckChangesPullRequestSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const branch_repository_1 = __nccwpck_require__(7701); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckChangesPullRequestSizeUseCase { + constructor() { + this.taskId = 'CheckChangesPullRequestSizeUseCase'; + this.branchRepository = new branch_repository_1.BranchRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const { size, githubSize, reason } = await this.branchRepository.getSizeCategoryAndReason(param.owner, param.repo, param.pullRequest.head, param.pullRequest.base, param.sizeThresholds, param.labels, param.tokens.token); + (0, logger_1.logDebugInfo)(`Size: ${size}`); + (0, logger_1.logDebugInfo)(`Github Size: ${githubSize}`); + (0, logger_1.logDebugInfo)(`Reason: ${reason}`); + (0, logger_1.logDebugInfo)(`Labels: ${param.labels.sizedLabelOnPullRequest}`); + if (param.labels.sizedLabelOnPullRequest !== size) { + /** + * Even if this is for pull reuqets, we are getting the issue labels for having a mirror of the issue labels on the pull request. + */ + const labelNames = param.labels.currentIssueLabels.filter(name => param.labels.sizeLabels.indexOf(name) === -1); + labelNames.push(size); + await this.issueRepository.setLabels(param.owner, param.repo, param.pullRequest.number, labelNames, param.tokens.token); + for (const project of param.project.getProjects()) { + await this.projectRepository.setTaskSize(project, param.owner, param.repo, param.pullRequest.number, githubSize, param.tokens.token); + } + (0, logger_1.logDebugInfo)(`Updated labels on pull request #${param.pullRequest.number}:`); + (0, logger_1.logDebugInfo)(`Labels: ${labelNames}`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `${reason}, so the pull request was resized to ${size}.`, + ], + })); + } + else { + (0, logger_1.logDebugInfo)(`The pull request is already at the correct size.`); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the size of the changes, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; + } } +exports.CheckChangesPullRequestSizeUseCase = CheckChangesPullRequestSizeUseCase; -/** - * It takes a FormData object and returns a JavaScript object - * - * @param {string} formData The FormData object to convert to JSON. - * - * @returns {Object | null} The converted object. - */ -function formDataToJSON(formData) { - function buildPath(path, value, target, index) { - let name = path[index++]; - - if (name === '__proto__') return true; - - const isNumericKey = Number.isFinite(+name); - const isLast = index >= path.length; - name = !name && utils$1.isArray(target) ? target.length : name; - - if (isLast) { - if (utils$1.hasOwnProp(target, name)) { - target[name] = [target[name], value]; - } else { - target[name] = value; - } - return !isNumericKey; - } +/***/ }), - if (!target[name] || !utils$1.isObject(target[name])) { - target[name] = []; - } +/***/ 7383: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const result = buildPath(path, value, target[name], index); +"use strict"; - if (result && utils$1.isArray(target[name])) { - target[name] = arrayToObject(target[name]); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPriorityPullRequestSizeUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class CheckPriorityPullRequestSizeUseCase { + constructor() { + this.taskId = 'CheckPriorityPullRequestSizeUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); } - - return !isNumericKey; - } - - if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) { - const obj = {}; - - utils$1.forEachEntry(formData, (name, value) => { - buildPath(parsePropPath(name), value, obj, 0); - }); - - return obj; - } - - return null; -} - -/** - * It takes a string, tries to parse it, and if it fails, it returns the stringified version - * of the input - * - * @param {any} rawValue - The value to be stringified. - * @param {Function} parser - A function that parses a string into a JavaScript object. - * @param {Function} encoder - A function that takes a value and returns a string. - * - * @returns {string} A stringified version of the rawValue. - */ -function stringifySafely(rawValue, parser, encoder) { - if (utils$1.isString(rawValue)) { - try { - (parser || JSON.parse)(rawValue); - return utils$1.trim(rawValue); - } catch (e) { - if (e.name !== 'SyntaxError') { - throw e; - } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const priority = param.labels.priorityLabelOnIssue; + if (!param.labels.priorityLabelOnIssueProcessable || param.project.getProjects().length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + let priorityLabel = ``; + if (priority === param.labels.priorityHigh) { + priorityLabel = `P0`; + } + else if (priority === param.labels.priorityMedium) { + priorityLabel = `P1`; + } + else if (priority === param.labels.priorityLow) { + priorityLabel = `P2`; + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return result; + } + (0, logger_1.logDebugInfo)(`Priority: ${priority}`); + (0, logger_1.logDebugInfo)(`Github Priority Label: ${priorityLabel}`); + for (const project of param.project.getProjects()) { + const success = await this.projectRepository.setTaskPriority(project, param.owner, param.repo, param.pullRequest.number, priorityLabel, param.tokens.token); + if (success) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `Priority set to \`${priorityLabel}\` in [${project.title}](https://github.com/${param.owner}/${param.repo}/projects/${project.id}).`, + ], + })); + } + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to check the priority of the issue, but there was a problem.`, + ], + errors: [ + error?.toString() ?? 'Unknown error', + ], + })); + } + return result; } - } - - return (encoder || JSON.stringify)(rawValue); } +exports.CheckPriorityPullRequestSizeUseCase = CheckPriorityPullRequestSizeUseCase; -const defaults = { - - transitional: transitionalDefaults, - - adapter: ['xhr', 'http', 'fetch'], - - transformRequest: [function transformRequest(data, headers) { - const contentType = headers.getContentType() || ''; - const hasJSONContentType = contentType.indexOf('application/json') > -1; - const isObjectPayload = utils$1.isObject(data); - if (isObjectPayload && utils$1.isHTMLForm(data)) { - data = new FormData(data); - } +/***/ }), - const isFormData = utils$1.isFormData(data); +/***/ 2175: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if (isFormData) { - return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data; - } +"use strict"; - if (utils$1.isArrayBuffer(data) || - utils$1.isBuffer(data) || - utils$1.isStream(data) || - utils$1.isFile(data) || - utils$1.isBlob(data) || - utils$1.isReadableStream(data) - ) { - return data; +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]; } }; } - if (utils$1.isArrayBufferView(data)) { - return data.buffer; + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LinkPullRequestIssueUseCase = void 0; +const github = __importStar(__nccwpck_require__(5438)); +const result_1 = __nccwpck_require__(7305); +const pull_request_repository_1 = __nccwpck_require__(634); +const logger_1 = __nccwpck_require__(8836); +class LinkPullRequestIssueUseCase { + constructor() { + this.taskId = 'LinkPullRequestIssueUseCase'; + this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); } - if (utils$1.isURLSearchParams(data)) { - headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false); - return data.toString(); + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const isLinked = await this.pullRequestRepository.isLinked(github.context.payload.pull_request?.html_url ?? ''); + if (!isLinked) { + /** + * Set the primary/default branch + */ + await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.branches.defaultBranch, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The base branch was temporarily updated to \`${param.branches.defaultBranch}\`.`, + ], + })); + /** + * Update PR's description. + */ + let prBody = param.pullRequest.body; + let updatedBody = `${prBody}\n\nResolves #${param.issueNumber}`; + await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The description was temporarily modified to include a reference to issue **#${param.issueNumber}**.`, + ], + })); + /** + * Await 20 seconds + */ + await new Promise(resolve => setTimeout(resolve, 20 * 1000)); + /** + * Restore the original branch + */ + await this.pullRequestRepository.updateBaseBranch(param.owner, param.repo, param.pullRequest.number, param.pullRequest.base, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The base branch was reverted to its original value: \`${param.pullRequest.base}\`.`, + ], + })); + /** + * Restore comment on description + */ + prBody = param.pullRequest.body; + updatedBody = prBody.replace(`\n\nResolves #${param.issueNumber}`, ""); + await this.pullRequestRepository.updateDescription(param.owner, param.repo, param.pullRequest.number, updatedBody, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The temporary issue reference **#${param.issueNumber}** was removed from the description.`, + ], + })); + return result; + } + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to link pull request to project, but there was a problem.`, + ], + error: error, + })); + } + return result; } +} +exports.LinkPullRequestIssueUseCase = LinkPullRequestIssueUseCase; - let isFileList; - - if (isObjectPayload) { - if (contentType.indexOf('application/x-www-form-urlencoded') > -1) { - return toURLEncodedForm(data, this.formSerializer).toString(); - } - - if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { - const _FormData = this.env && this.env.FormData; - - return toFormData( - isFileList ? {'files[]': data} : data, - _FormData && new _FormData(), - this.formSerializer - ); - } - } - if (isObjectPayload || hasJSONContentType ) { - headers.setContentType('application/json', false); - return stringifySafely(data); - } +/***/ }), - return data; - }], +/***/ 4311: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - transformResponse: [function transformResponse(data) { - const transitional = this.transitional || defaults.transitional; - const forcedJSONParsing = transitional && transitional.forcedJSONParsing; - const JSONRequested = this.responseType === 'json'; +"use strict"; - if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) { - return data; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.LinkPullRequestProjectUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const project_repository_1 = __nccwpck_require__(7917); +const logger_1 = __nccwpck_require__(8836); +class LinkPullRequestProjectUseCase { + constructor() { + this.taskId = 'LinkPullRequestProjectUseCase'; + this.projectRepository = new project_repository_1.ProjectRepository(); } - - if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) { - const silentJSONParsing = transitional && transitional.silentJSONParsing; - const strictJSONParsing = !silentJSONParsing && JSONRequested; - - try { - return JSON.parse(data, this.parseReviver); - } catch (e) { - if (strictJSONParsing) { - if (e.name === 'SyntaxError') { - throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); - } - throw e; + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const result = []; + const columnName = param.project.getProjectColumnPullRequestCreated(); + try { + for (const project of param.project.getProjects()) { + let actionDone = await this.projectRepository.linkContentId(project, param.pullRequest.id, param.tokens.token); + if (actionDone) { + /** + * Wait for 10 seconds to ensure the pull request is linked to the project + */ + await new Promise(resolve => setTimeout(resolve, 10000)); + actionDone = await this.projectRepository.moveIssueToColumn(project, param.owner, param.repo, param.pullRequest.number, columnName, param.tokens.token); + if (actionDone) { + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The pull request was linked to [**${project?.title}**](${project?.url}) and moved to the column \`${columnName}\`.`, + ], + })); + } + else { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `The pull request was linked to [**${project?.title}**](${project?.url}) but there was an error moving it to the column \`${columnName}\`.`, + ], + })); + } + } + } + return result; } - } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Tried to link pull request to project, but there was a problem.`, + ], + error: error, + })); + } + return result; } +} +exports.LinkPullRequestProjectUseCase = LinkPullRequestProjectUseCase; - return data; - }], - - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, - - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - maxContentLength: -1, - maxBodyLength: -1, +/***/ }), - env: { - FormData: platform.classes.FormData, - Blob: platform.classes.Blob - }, +/***/ 158: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - }, +"use strict"; - headers: { - common: { - 'Accept': 'application/json, text/plain, */*', - 'Content-Type': undefined +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.UpdatePullRequestDescriptionUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const file_repository_1 = __nccwpck_require__(1503); +const issue_repository_1 = __nccwpck_require__(57); +const project_repository_1 = __nccwpck_require__(7917); +const pull_request_repository_1 = __nccwpck_require__(634); +const logger_1 = __nccwpck_require__(8836); +class UpdatePullRequestDescriptionUseCase { + constructor() { + this.taskId = 'UpdatePullRequestDescriptionUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.pullRequestRepository = new pull_request_repository_1.PullRequestRepository(); + this.fileRepository = new file_repository_1.FileRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.projectRepository = new project_repository_1.ProjectRepository(); } - } -}; - -utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => { - defaults.headers[method] = {}; -}); + async invoke(param) { + (0, logger_1.logDebugInfo)(`Executing ${this.taskId}.`); + const result = []; + try { + const prNumber = param.pullRequest.number; + const issueDescription = await this.issueRepository.getIssueDescription(param.owner, param.repo, param.issueNumber, param.tokens.token); + if (issueDescription.length === 0) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + steps: [ + `No issue description found. Skipping update pull request description.` + ] + })); + return result; + } + const currentProjectMembers = await this.projectRepository.getAllMembers(param.owner, param.tokens.token); + const pullRequestCreatorIsTeamMember = param.pullRequest.creator.length > 0 + && currentProjectMembers.indexOf(param.pullRequest.creator) > -1; + if (!pullRequestCreatorIsTeamMember && param.ai.getAiMembersOnly()) { + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: false, + steps: [ + `The pull request creator @${param.pullRequest.creator} is not a team member and \`AI members only\` is enabled. Skipping update pull request description.` + ] + })); + return result; + } + const changes = await this.pullRequestRepository.getPullRequestChanges(param.owner, param.repo, prNumber, param.tokens.token); + const changesDescription = await this.processChanges(changes, param.ai, param.owner, param.repo, param.tokens.token, param.pullRequest.base); + const descriptionPrompt = `this an issue descrition. +define a description for the pull request which closes the issue and avoid the use of titles (#, ##, ###). +just a text description:\n\n +${issueDescription}`; + const currentDescription = await this.aiRepository.ask(param.ai, descriptionPrompt); + // Update pull request description + await this.pullRequestRepository.updateDescription(param.owner, param.repo, prNumber, ` +#${param.issueNumber} -const defaults$1 = defaults; +## What does this PR do? -// RawAxiosHeaders whose duplicates are ignored by node -// c.f. https://nodejs.org/api/http.html#http_message_headers -const ignoreDuplicateOf = utils$1.toObjectSet([ - 'age', 'authorization', 'content-length', 'content-type', 'etag', - 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', - 'last-modified', 'location', 'max-forwards', 'proxy-authorization', - 'referer', 'retry-after', 'user-agent' -]); +${currentDescription} -/** - * Parse headers into an object - * - * ``` - * Date: Wed, 27 Aug 2014 08:58:49 GMT - * Content-Type: application/json - * Connection: keep-alive - * Transfer-Encoding: chunked - * ``` - * - * @param {String} rawHeaders Headers needing to be parsed - * - * @returns {Object} Headers parsed into an object - */ -const parseHeaders = rawHeaders => { - const parsed = {}; - let key; - let val; - let i; - - rawHeaders && rawHeaders.split('\n').forEach(function parser(line) { - i = line.indexOf(':'); - key = line.substring(0, i).trim().toLowerCase(); - val = line.substring(i + 1).trim(); - - if (!key || (parsed[key] && ignoreDuplicateOf[key])) { - return; +${changesDescription} +`, param.tokens.token); + result.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + steps: [ + `The description has been updated with AI-generated content.` + ] + })); + } + catch (error) { + (0, logger_1.logError)(error); + result.push(new result_1.Result({ + id: this.taskId, + success: false, + executed: true, + steps: [ + `Error updating pull request description: ${error}` + ] + })); + } + return result; } - - if (key === 'set-cookie') { - if (parsed[key]) { - parsed[key].push(val); - } else { - parsed[key] = [val]; - } - } else { - parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + shouldIgnoreFile(filename, ignorePatterns) { + return ignorePatterns.some(pattern => { + // Convert glob pattern to regex + const regexPattern = pattern + .replace(/[.+?^${}()|[\]\\]/g, '\\$&') // Escape special regex characters (sin afectar *) + .replace(/\*/g, '.*') // Convert * to match anything + .replace(/\//g, '\\/'); // Escape forward slashes + // Allow pattern ending on /* to ignore also subdirectories and files inside + if (pattern.endsWith("/*")) { + return new RegExp(`^${regexPattern.replace(/\\\/\.\*$/, "(\\/.*)?")}$`).test(filename); + } + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(filename); + }); } - }); - - return parsed; -}; - -const $internals = Symbol('internals'); - -function normalizeHeader(header) { - return header && String(header).trim().toLowerCase(); -} - -function normalizeValue(value) { - if (value === false || value == null) { - return value; - } - - return utils$1.isArray(value) ? value.map(normalizeValue) : String(value); -} - -function parseTokens(str) { - const tokens = Object.create(null); - const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; - let match; - - while ((match = tokensRE.exec(str))) { - tokens[match[1]] = match[2]; - } - - return tokens; -} - -const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim()); - -function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) { - if (utils$1.isFunction(filter)) { - return filter.call(this, value, header); - } - - if (isHeaderNameFilter) { - value = header; - } - - if (!utils$1.isString(value)) return; + mergePatchSummaries(summaries) { + const mergedMap = new Map(); + for (const summary of summaries) { + const existing = mergedMap.get(summary.filePath); + if (existing) { + // Merge with existing summary + existing.summary = `${existing.summary}\n${summary.summary}`; + existing.changes = [...new Set([...existing.changes, ...summary.changes])]; + } + else { + // Create new entry + mergedMap.set(summary.filePath, { + filePath: summary.filePath, + summary: summary.summary, + changes: [...summary.changes] + }); + } + } + return Array.from(mergedMap.values()); + } + groupFilesByDirectory(files) { + const groups = { + root: [] + }; + files.forEach(file => { + const pathParts = file.filePath.split('/'); + if (pathParts.length > 1) { + const directory = pathParts.slice(0, -1).join('/'); + if (!groups[directory]) { + groups[directory] = []; + } + groups[directory].push(file); + } + else { + groups.root.push(file); + } + }); + return groups; + } + formatFileChanges(file) { + let output = `#### \`${file.filePath}\`\n\n`; + output += `${file.summary}\n\n`; + if (file.changes.length > 0) { + output += '**Changes:**\n'; + output += file.changes.map(change => `- ${change}`).join('\n'); + } + output += `\n\n--- \n\n`; + return output; + } + async processFile(change, ai, owner, repo, token, baseBranch) { + if (!change.patch) { + return []; + } + // Get the original file content + const originalContent = await this.fileRepository.getFileContent(owner, repo, change.filename, token, baseBranch); + const filePrompt = `Analyze the following code changes and provide a summary in JSON format. - if (utils$1.isString(filter)) { - return value.indexOf(filter) !== -1; - } +### **Guidelines**: +- Output must be a **valid JSON** object. +- Provide a high-level summary of the changes. +- List the key changes in detail. +- Pay attention to the file names, don't make mistakes with uppercase, lowercase, or underscores. +- Be careful when composing the response JSON, don't make mistakes with unnecessary commas. - if (utils$1.isRegExp(filter)) { - return filter.test(value); - } +### **Output Format Example**: +\`\`\`json +{ + "filePath": "src/utils/logger.ts", + "summary": "Refactored logging system for better error handling.", + "changes": [ + "Replaced \`console.error\` with \`logError\`.", + "Added support for async logging.", + "Removed unused function \`debugLog\`." + ] } +\`\`\` -function formatHeader(header) { - return header.trim() - .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => { - return char.toUpperCase() + str; - }); -} +### **Metadata**: +- **Filename:** ${change.filename} +- **Status:** ${change.status} +- **Changes:** +${change.additions} / -${change.deletions} -function buildAccessors(obj, header) { - const accessorName = utils$1.toCamelCase(' ' + header); +### **Original File Content**: +\`\`\` +${originalContent} +\`\`\` - ['get', 'set', 'has'].forEach(methodName => { - Object.defineProperty(obj, methodName + accessorName, { - value: function(arg1, arg2, arg3) { - return this[methodName].call(this, header, arg1, arg2, arg3); - }, - configurable: true - }); - }); +### **Patch**: +${change.patch}`; + const response = await this.aiRepository.ask(ai, filePrompt); + if (!response) { + return []; + } + try { + const cleanResponse = response.replace(/^```json\n?/, '').replace(/\n?```$/, '').trim(); + const patchSummary = JSON.parse(cleanResponse); + return [patchSummary]; + } + catch (error) { + (0, logger_1.logDebugError)(`Response: ${response}`); + (0, logger_1.logError)(`Error parsing JSON response: ${error}`); + return []; + } + } + async processChanges(changes, ai, owner, repo, token, baseBranch) { + (0, logger_1.logDebugInfo)(`Processing ${changes.length} changes`); + const processFilePromises = changes.map(async (change) => { + try { + (0, logger_1.logDebugInfo)(`Processing changes for file ${change.filename}`); + const shouldIgnoreFile = this.shouldIgnoreFile(change.filename, ai.getAiIgnoreFiles()); + if (shouldIgnoreFile) { + (0, logger_1.logDebugInfo)(`File ${change.filename} should be ignored`); + return []; + } + return await this.processFile(change, ai, owner, repo, token, baseBranch); + } + catch (error) { + (0, logger_1.logError)(error); + throw new Error(`Error processing file ${change.filename}: ${error}`); + } + }); + const fileDescriptions = (await Promise.all(processFilePromises)).flat(); + // Merge PatchSummary objects for the same file + const mergedFileDescriptions = this.mergePatchSummaries(fileDescriptions); + // Group files by directory + const groupedFiles = this.groupFilesByDirectory(mergedFileDescriptions); + // Generate a structured description + let description = ''; + // Add summary section if there are files + if (mergedFileDescriptions.length > 0) { + description += '## Summary of Changes\n\n'; + description += mergedFileDescriptions.map(file => `- **${file.filePath}**: ${file.summary}`).join('\n'); + description += '\n\n'; + } + // Add detailed changes section + description += '## Detailed Changes\n\n'; + // Process each directory group + for (const [directory, files] of Object.entries(groupedFiles)) { + if (directory === 'root') { + // Files in root directory + description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; + } + else { + // Files in subdirectories + description += `### ${directory}\n\n`; + description += files.map(file => this.formatFileChanges(file)).join('\n\n') + `\n\n`; + } + } + return description; + } } +exports.UpdatePullRequestDescriptionUseCase = UpdatePullRequestDescriptionUseCase; -class AxiosHeaders { - constructor(headers) { - headers && this.set(headers); - } - set(header, valueOrRewrite, rewrite) { - const self = this; +/***/ }), + +/***/ 7112: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - function setHeader(_value, _header, _rewrite) { - const lHeader = normalizeHeader(_header); +"use strict"; - if (!lHeader) { - throw new Error('header name must be a non-empty string'); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.CheckPullRequestCommentLanguageUseCase = void 0; +const result_1 = __nccwpck_require__(7305); +const ai_repository_1 = __nccwpck_require__(8307); +const issue_repository_1 = __nccwpck_require__(57); +const logger_1 = __nccwpck_require__(8836); +class CheckPullRequestCommentLanguageUseCase { + constructor() { + this.taskId = 'CheckPullRequestCommentLanguageUseCase'; + this.aiRepository = new ai_repository_1.AiRepository(); + this.issueRepository = new issue_repository_1.IssueRepository(); + this.translatedKey = ``; + } + async invoke(param) { + (0, logger_1.logInfo)(`Executing ${this.taskId}.`); + const results = []; + const commentBody = param.pullRequest.commentBody; + if (commentBody.length === 0 || commentBody.includes(this.translatedKey)) { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: false, + })); + return results; + } + const locale = param.locale.pullRequest; + let prompt = ` + You are a helpful assistant that checks if the text is written in ${locale}. + + Instructions: + 1. Analyze the provided text + 2. If the text is written in ${locale}, respond with exactly "done" + 3. If the text is written in any other language, respond with exactly "must_translate" + 4. Do not provide any explanation or additional text + + The text is: ${commentBody} + `; + let result = await this.aiRepository.ask(param.ai, prompt); + if (result === "done") { + results.push(new result_1.Result({ + id: this.taskId, + success: true, + executed: true, + })); + return results; + } + prompt = ` +You are a helpful assistant that translates the text to ${locale}. - const key = utils$1.findKey(self, lHeader); +Instructions: +1. Translate the text to ${locale} +2. Do not provide any explanation or additional text +3. Return the translated text only - if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) { - self[key || _header] = normalizeValue(_value); - } +The text is: ${commentBody} + `; + result = await this.aiRepository.ask(param.ai, prompt); + const translatedCommentBody = `${result} +> ${commentBody} +${this.translatedKey} +`; + await this.issueRepository.updateComment(param.owner, param.repo, param.pullRequest.number, param.pullRequest.commentId, translatedCommentBody, param.tokens.token); + return results; } +} +exports.CheckPullRequestCommentLanguageUseCase = CheckPullRequestCommentLanguageUseCase; - const setHeaders = (headers, _rewrite) => - utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); - if (utils$1.isPlainObject(header) || header instanceof this.constructor) { - setHeaders(header, valueOrRewrite); - } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { - setHeaders(parseHeaders(header), valueOrRewrite); - } else if (utils$1.isObject(header) && utils$1.isIterable(header)) { - let obj = {}, dest, key; - for (const entry of header) { - if (!utils$1.isArray(entry)) { - throw TypeError('Object iterator must return a key-value pair'); - } +/***/ }), - obj[key = entry[0]] = (dest = obj[key]) ? - (utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]]) : entry[1]; - } +/***/ 8593: +/***/ ((__unused_webpack_module, exports) => { - setHeaders(obj, valueOrRewrite); - } else { - header != null && setHeader(valueOrRewrite, header, rewrite); +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PROMPTS = exports.ACTIONS = exports.ERRORS = exports.INPUT_KEYS = exports.WORKFLOW_ACTIVE_STATUSES = exports.WORKFLOW_STATUS = exports.DEFAULT_IMAGE_CONFIG = exports.REPO_URL = exports.TITLE = exports.COMMAND = void 0; +exports.COMMAND = 'giik'; +exports.TITLE = 'Giik'; +exports.REPO_URL = 'https://github.com/landamessenger/git-board-flow'; +exports.DEFAULT_IMAGE_CONFIG = { + issue: { + automatic: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp" + ], + feature: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", + ], + bugfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" + ], + hotfix: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp" + ], + release: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", + ], + docs: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", + ], + chore: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", + ], + }, + pullRequest: { + automatic: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExYzRsNGFicndqMXgzMTVwdnhpeXNyZGsydXVxamV4eGxndWhna291OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/ktcUyw6mBlMVa/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjkyeWVubngzM28xODFrbXZ4Nng3Y2hubmM4cXJqNGpic3Bheml0NSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/M11UVCRrc0LUk/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenQwNDJmZnZraDBzNXBoNjUwZjEzMzFlanMxcHVodmF4b3l3bDl2biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/zrdUjl6N99nLq/200.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + ], + feature: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMm5iZHJydTJ4NGticXdxd3ZxYnZqNXdvaDQwOHdtb3o5NTRhdnRhOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LSX49vHf7JHGyGjrC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYmc4YWplZWs0Y2c3ZXNtbGpwZnQzdWpncmNjNXpodjg3MHdtbnJ5NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OMK7LRBedcnhm/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHBrYXpmd2poeGU5cWswbjRqNmJlZ2U2dWc0ejVpY3RpcXVuYTY3dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/llKJGxQ1ESmac/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMnFleXV0MXZteGN6c2s2b3R3ZGc2cWY1aXB0Y3ZzNmpvZHhyNDVmNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10FwycrnAkpshW/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExcHo0MjIzaGIycTRmeWFwZmp6bGExczJicXcyZTQxemsxaTY1b3V1NiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/QKkV58ufpV4ksJ1Okh/giphy.gif", + ], + bugfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExazc3OWszenA5c2FlemE3a25oNnlmZDBra3liMWRqMW82NzM2b2FveCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xPGkOAdiIO3Is/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExY3liaGF2NzI3bzM1YjRmdHFsaGdyenp4b3o3M3dqM3F0bGN5MHZtNSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/npUpB306c3EStRK6qP/200.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExZWh6d3Nld3E0MTF1eTk2YXFibnI3MTBhbGtpamJiemRwejl3YmkzMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gU25raLP4pUu4/giphy.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", + ], + hotfix: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmozN3plMWNiYjZoemh6N2RmeTB1MG9ieHlqYTJsb3BrZmNoY3h0dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/stv1Dliu5TrMs/giphy.webp", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExd2R0cjNxbXBjZjRjNmg4NmN3MGlhazVkNHJsaDkxMHZkY2hweGRtZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/pCU4bC7kC6sxy/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExenkyZTc3aDlweWl0MnI0cXJsZGptY3g0bzE2NTY1aWMyaHd4Y201ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dbtDDSvWErdf2/giphy.webp", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExM25ndGd2d3Uya3g3dnlnenJ1bjh0Y2NtNHdwZHY3Mjh2NnBmZDJpbyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2xF8gHUf085aNyyAQR/200.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExdjU3bHdsc3FtamlyazBlbWppNHc3MTV3MW4xdHd2cWo4b2tzbTkwcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/1EghTrigJJhq8/200.webp", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExdmM1OWR0cnk5eXI0dXpoNWRzbmVseTVyd2l3MzdrOHZueHJ6bjhjMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/12yjKJaLB7DuG4/giphy.webp", + ], + release: [ + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2NxcHEzam92enRtd29xc21pMHhmbHozMWljamF1cmt4cjhwZTI0ayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/PApUm1HPVYlDNLoMmr/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNXU4dnhwOWVqZzc4NXVsdTY3c2I4Mm9lOHF1c253MDJya25zNXU0ZyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dxn6fRlTIShoeBr69N/giphy.webp", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXN2bjJob3pxazE2NDJhbGE3ZWY5d2dzbDM4czgwZnA4ejlxY3ZqeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/9D37RaHngWP7ZmmsEt/giphy.webp", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExZnI0YTM2N2hwamd2dXYwNmN2MjRpYXIyN203cnNpbW13YjNhZGRhdyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/LYWPXVUNz30ze/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdW1jZ3F4ZGRwMWkyc3ZocHJ3aXhyb2FuZGppcnMyMWtsYXpjbDY2ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tXLpxypfSXvUc/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHRianpoOW51MzZ4Yjk3MmNpbmdseTJlb3o3dWVpYzJpazc5ZHNoayZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/b85mPT4Usz7fq/giphy.gif", + ], + docs: [ + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExaGRpZHJqYzRvZ25xcjR3ZXcwbzVudXF2Z2hsaHoyc2g1ZjZuam81YiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/eDArHBLT4aATKEKtCd/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExa2NubXR1b2M1dDQ2Z2UxYmk5bzltbHdudWI1emVzOGFlbDNsOGU1bSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/wpgYasZ0tBrP4lCgS3/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExMmEyNzc3M2V0anp4d2JtOTJuMTZ2dXNnMmEyN3A4MmE0ZGpiaDhnNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orifaQEOagjYJ1EXe/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZjUyenc2eG5pZ3NjYzcyZXg2dDFndm5qZHRqMHk5amNoYjhhNnNvZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/7E8lI6TkLrvvAcPXso/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExaWFxcXZ3MTMxM3Bjd2IwNG43ZDJjdndreXNmdTVvZ2g3Z2Q4NjczMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3tJdi9wQQ10BD2H47g/giphy.gif", + "https://media1.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFrejZmaHQ2Z2o1Y3B2MDl6cmU5bzNybG84eXFrYjBjZjV0dGFpeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fsXOS3oBboiYf6fSsY/giphy.gif", + "https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHdhOHRianU1YmtrNHE0c2R2M2I2MTBzNnZhdnBrMW5ueG02eHF6OSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieOEBYMAwTClHqM/giphy.gif", + ], + chore: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjFtNXY0ZXdmdGxkdno2Nm5odGk3Nzd3aTRuYnJtbDA4MXIxdHFhdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/10zsjaH4g0GgmY/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExZG1sNXB6eTZvdDNtNzJwNXVxenNjendwaGgxb2xzNWI1dGNpdTVmZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NHHYRm7mAUQ6Y/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHd4bDJrc216YWpicDQ5emczdWF3bTk0dXYzeGQ4ajg2a3IyYjV6diZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/FHEjBpiqMwSuA/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExM3d5b2U1Z3Jic3AxY2llYjQwNW5wODFpNWp5NHY0dGV5Z2cxdThkdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/kLZNLNqUZ6bC0/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbTNpZ2w0c3NrMmc0cmZobTd2eTM3YTRlM2lnbWpoZDUzNnRjdnNmZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/NV4cSrRYXXwfUcYnua/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExbmFzZHNuODg0dDRheGt0aGU2bjVvd2xiNDI1bWFmYTVsbHJ2eHI2dyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XaAbmtzzz35IgW3Ntn/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWM2OHkzYmNkajZxa204Njg0bmQzaWp1M3NobnJjbWxyYWJrbDNnciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/OiwOPq0fFqqyainyMu/giphy.gif", + ], + }, + commit: { + automatic: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + feature: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + bugfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + hotfix: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + release: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + docs: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ], + chore: [ + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExdWp2OGJ5ZmczaGhiMmVxdjRxMWZnYnRrNW5uemlmd2Ewam1nNGd0aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2XflxzEtr4EPIEzioLu/giphy.gif", + "https://media0.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTkzeTFveHd6N3Fubm8yZDlpYTVuMnp0bm1rODQyZDdpbTF4YzAxaiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/n2IPMYMthV0m4/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZ3BmNXV1YzZod2NkYjZ3aTE1Z3BwMWJ0ZG9uMXN0bm5pbDQ4ajBvaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3WxRbhsvQjYw8/giphy.gif", + "https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWs5YXEyajhoNWI1aHdxeHNwcmt2czY2NW1mNjZrbnViYm9reXJsZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/loLqo6AzjUcMdjS1Jj/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExdHh5MndyMzBmY3c3bDRxeGhpanF2ZjIycGpmbzlkMDV5cDJkeXhjMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3orieQDBZVlki2mJLW/giphy.gif", + "https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExNGdkaHFsMTlzM2ZuY3R5ZXJpZmo3cHRqZWJieXVlOHQwc2F3eGVrdSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/tELuxgGsoL62ihEtQs/giphy.gif", + ] } +}; +exports.WORKFLOW_STATUS = { + IN_PROGRESS: 'in_progress', + QUEUED: 'queued', + COMPLETED: 'completed', + FAILED: 'failed', + CANCELLED: 'cancelled', + SKIPPED: 'skipped', + TIMED_OUT: 'timed_out', +}; +exports.WORKFLOW_ACTIVE_STATUSES = [exports.WORKFLOW_STATUS.IN_PROGRESS, exports.WORKFLOW_STATUS.QUEUED]; +exports.INPUT_KEYS = { + // Debug + DEBUG: 'debug', + // Welcome + WELCOME_TITLE: 'welcome-title', + WELCOME_MESSAGES: 'welcome-messages', + // Single action + SINGLE_ACTION: 'single-action', + SINGLE_ACTION_ISSUE: 'single-action-issue', + SINGLE_ACTION_VERSION: 'single-action-version', + SINGLE_ACTION_TITLE: 'single-action-title', + SINGLE_ACTION_CHANGELOG: 'single-action-changelog', + // Tokens + TOKEN: 'token', + // AI + OPENROUTER_API_KEY: 'openrouter-api-key', + OPENROUTER_MODEL: 'openrouter-model', + AI_PULL_REQUEST_DESCRIPTION: 'ai-pull-request-description', + AI_MEMBERS_ONLY: 'ai-members-only', + AI_IGNORE_FILES: 'ai-ignore-files', + AI_INCLUDE_REASONING: 'ai-include-reasoning', + OPENROUTER_PROVIDER_ORDER: 'openrouter-provider-order', + OPENROUTER_PROVIDER_ALLOW_FALLBACKS: 'openrouter-provider-allow-fallbacks', + OPENROUTER_PROVIDER_REQUIRE_PARAMETERS: 'openrouter-provider-require-parameters', + OPENROUTER_PROVIDER_DATA_COLLECTION: 'openrouter-provider-data-collection', + OPENROUTER_PROVIDER_IGNORE: 'openrouter-provider-ignore', + OPENROUTER_PROVIDER_QUANTIZATIONS: 'openrouter-provider-quantizations', + OPENROUTER_PROVIDER_SORT: 'openrouter-provider-sort', + // Projects + PROJECT_IDS: 'project-ids', + PROJECT_COLUMN_ISSUE_CREATED: 'project-column-issue-created', + PROJECT_COLUMN_PULL_REQUEST_CREATED: 'project-column-pull-request-created', + PROJECT_COLUMN_ISSUE_IN_PROGRESS: 'project-column-issue-in-progress', + PROJECT_COLUMN_PULL_REQUEST_IN_PROGRESS: 'project-column-pull-request-in-progress', + // Images + IMAGES_ON_ISSUE: 'images-on-issue', + IMAGES_ON_PULL_REQUEST: 'images-on-pull-request', + IMAGES_ON_COMMIT: 'images-on-commit', + IMAGES_ISSUE_AUTOMATIC: 'images-issue-automatic', + IMAGES_ISSUE_FEATURE: 'images-issue-feature', + IMAGES_ISSUE_BUGFIX: 'images-issue-bugfix', + IMAGES_ISSUE_DOCS: 'images-issue-docs', + IMAGES_ISSUE_CHORE: 'images-issue-chore', + IMAGES_ISSUE_RELEASE: 'images-issue-release', + IMAGES_ISSUE_HOTFIX: 'images-issue-hotfix', + IMAGES_PULL_REQUEST_AUTOMATIC: 'images-pull-request-automatic', + IMAGES_PULL_REQUEST_FEATURE: 'images-pull-request-feature', + IMAGES_PULL_REQUEST_BUGFIX: 'images-pull-request-bugfix', + IMAGES_PULL_REQUEST_RELEASE: 'images-pull-request-release', + IMAGES_PULL_REQUEST_HOTFIX: 'images-pull-request-hotfix', + IMAGES_PULL_REQUEST_DOCS: 'images-pull-request-docs', + IMAGES_PULL_REQUEST_CHORE: 'images-pull-request-chore', + IMAGES_COMMIT_AUTOMATIC: 'images-commit-automatic', + IMAGES_COMMIT_FEATURE: 'images-commit-feature', + IMAGES_COMMIT_BUGFIX: 'images-commit-bugfix', + IMAGES_COMMIT_RELEASE: 'images-commit-release', + IMAGES_COMMIT_HOTFIX: 'images-commit-hotfix', + IMAGES_COMMIT_DOCS: 'images-commit-docs', + IMAGES_COMMIT_CHORE: 'images-commit-chore', + // Workflows + RELEASE_WORKFLOW: 'release-workflow', + HOTFIX_WORKFLOW: 'hotfix-workflow', + // Emoji + EMOJI_LABELED_TITLE: 'emoji-labeled-title', + BRANCH_MANAGEMENT_EMOJI: 'branch-management-emoji', + // Labels + BRANCH_MANAGEMENT_LAUNCHER_LABEL: 'branch-management-launcher-label', + BUGFIX_LABEL: 'bugfix-label', + BUG_LABEL: 'bug-label', + HOTFIX_LABEL: 'hotfix-label', + ENHANCEMENT_LABEL: 'enhancement-label', + FEATURE_LABEL: 'feature-label', + RELEASE_LABEL: 'release-label', + QUESTION_LABEL: 'question-label', + HELP_LABEL: 'help-label', + DEPLOY_LABEL: 'deploy-label', + DEPLOYED_LABEL: 'deployed-label', + DOCS_LABEL: 'docs-label', + DOCUMENTATION_LABEL: 'documentation-label', + CHORE_LABEL: 'chore-label', + MAINTENANCE_LABEL: 'maintenance-label', + PRIORITY_HIGH_LABEL: 'priority-high-label', + PRIORITY_MEDIUM_LABEL: 'priority-medium-label', + PRIORITY_LOW_LABEL: 'priority-low-label', + PRIORITY_NONE_LABEL: 'priority-none-label', + SIZE_XXL_LABEL: 'size-xxl-label', + SIZE_XL_LABEL: 'size-xl-label', + SIZE_L_LABEL: 'size-l-label', + SIZE_M_LABEL: 'size-m-label', + SIZE_S_LABEL: 'size-s-label', + SIZE_XS_LABEL: 'size-xs-label', + // Issue Types + ISSUE_TYPE_BUG: 'issue-type-bug', + ISSUE_TYPE_BUG_DESCRIPTION: 'issue-type-bug-description', + ISSUE_TYPE_BUG_COLOR: 'issue-type-bug-color', + ISSUE_TYPE_HOTFIX: 'issue-type-hotfix', + ISSUE_TYPE_HOTFIX_DESCRIPTION: 'issue-type-hotfix-description', + ISSUE_TYPE_HOTFIX_COLOR: 'issue-type-hotfix-color', + ISSUE_TYPE_FEATURE: 'issue-type-feature', + ISSUE_TYPE_FEATURE_DESCRIPTION: 'issue-type-feature-description', + ISSUE_TYPE_FEATURE_COLOR: 'issue-type-feature-color', + ISSUE_TYPE_DOCUMENTATION: 'issue-type-documentation', + ISSUE_TYPE_DOCUMENTATION_DESCRIPTION: 'issue-type-documentation-description', + ISSUE_TYPE_DOCUMENTATION_COLOR: 'issue-type-documentation-color', + ISSUE_TYPE_MAINTENANCE: 'issue-type-maintenance', + ISSUE_TYPE_MAINTENANCE_DESCRIPTION: 'issue-type-maintenance-description', + ISSUE_TYPE_MAINTENANCE_COLOR: 'issue-type-maintenance-color', + ISSUE_TYPE_RELEASE: 'issue-type-release', + ISSUE_TYPE_RELEASE_DESCRIPTION: 'issue-type-release-description', + ISSUE_TYPE_RELEASE_COLOR: 'issue-type-release-color', + ISSUE_TYPE_QUESTION: 'issue-type-question', + ISSUE_TYPE_QUESTION_DESCRIPTION: 'issue-type-question-description', + ISSUE_TYPE_QUESTION_COLOR: 'issue-type-question-color', + ISSUE_TYPE_HELP: 'issue-type-help', + ISSUE_TYPE_HELP_DESCRIPTION: 'issue-type-help-description', + ISSUE_TYPE_HELP_COLOR: 'issue-type-help-color', + ISSUE_TYPE_TASK: 'issue-type-task', + ISSUE_TYPE_TASK_DESCRIPTION: 'issue-type-task-description', + ISSUE_TYPE_TASK_COLOR: 'issue-type-task-color', + // Locale + ISSUES_LOCALE: 'issues-locale', + PULL_REQUESTS_LOCALE: 'pull-requests-locale', + // Size Thresholds + SIZE_XXL_THRESHOLD_LINES: 'size-xxl-threshold-lines', + SIZE_XXL_THRESHOLD_FILES: 'size-xxl-threshold-files', + SIZE_XXL_THRESHOLD_COMMITS: 'size-xxl-threshold-commits', + SIZE_XL_THRESHOLD_LINES: 'size-xl-threshold-lines', + SIZE_XL_THRESHOLD_FILES: 'size-xl-threshold-files', + SIZE_XL_THRESHOLD_COMMITS: 'size-xl-threshold-commits', + SIZE_L_THRESHOLD_LINES: 'size-l-threshold-lines', + SIZE_L_THRESHOLD_FILES: 'size-l-threshold-files', + SIZE_L_THRESHOLD_COMMITS: 'size-l-threshold-commits', + SIZE_M_THRESHOLD_LINES: 'size-m-threshold-lines', + SIZE_M_THRESHOLD_FILES: 'size-m-threshold-files', + SIZE_M_THRESHOLD_COMMITS: 'size-m-threshold-commits', + SIZE_S_THRESHOLD_LINES: 'size-s-threshold-lines', + SIZE_S_THRESHOLD_FILES: 'size-s-threshold-files', + SIZE_S_THRESHOLD_COMMITS: 'size-s-threshold-commits', + SIZE_XS_THRESHOLD_LINES: 'size-xs-threshold-lines', + SIZE_XS_THRESHOLD_FILES: 'size-xs-threshold-files', + SIZE_XS_THRESHOLD_COMMITS: 'size-xs-threshold-commits', + // Branches + MAIN_BRANCH: 'main-branch', + DEVELOPMENT_BRANCH: 'development-branch', + FEATURE_TREE: 'feature-tree', + BUGFIX_TREE: 'bugfix-tree', + HOTFIX_TREE: 'hotfix-tree', + RELEASE_TREE: 'release-tree', + DOCS_TREE: 'docs-tree', + CHORE_TREE: 'chore-tree', + // Commit + COMMIT_PREFIX_TRANSFORMS: 'commit-prefix-transforms', + // Issue + BRANCH_MANAGEMENT_ALWAYS: 'branch-management-always', + REOPEN_ISSUE_ON_PUSH: 'reopen-issue-on-push', + DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', + // Pull Request + PULL_REQUEST_DESIRED_ASSIGNEES_COUNT: 'desired-assignees-count', + PULL_REQUEST_DESIRED_REVIEWERS_COUNT: 'desired-reviewers-count', + PULL_REQUEST_MERGE_TIMEOUT: 'merge-timeout', + // Supabase + SUPABASE_URL: 'supabase-url', + SUPABASE_KEY: 'supabase-key' +}; +exports.ERRORS = { + GIT_REPOSITORY_NOT_FOUND: 'āŒ Git repository not found' +}; +exports.ACTIONS = { + DEPLOYED: 'deployed_action', + AI_CACHE: 'ai_cache_action', + AI_CACHE_LOCAL: 'ai_cache_local_action', + PUBLISH_GITHUB_ACTION: 'publish_github_action', + CREATE_RELEASE: 'create_release', + CREATE_TAG: 'create_tag', + THINK: 'think_action', +}; +exports.PROMPTS = { + CODE_BASE_ANALYSIS: ` +You are a technical code analysis assistant. - return this; - } +Your task is to analyze the content of the following source code file in depth. - get(header, parser) { - header = normalizeHeader(header); +Provide a precise and highly technical explanation of what the code does, including: +- Its main purpose and functionality. +- A breakdown of the logic and flow (step by step or module by module). +- How each class, function, or major block interacts with the rest. +- The technologies, frameworks, or libraries it uses and how. +- Any relevant algorithms, patterns, or data structures implemented. +- Potential edge cases, performance considerations, or hidden behaviors. +- Dependencies and external integrations (APIs, services, databases, etc.). +- Any implicit assumptions or limitations found in the implementation. - if (header) { - const key = utils$1.findKey(this, header); +Focus exclusively on *accurate technical analysis and understanding*, not on summarizing in simple language. - if (key) { - const value = this[key]; +Do not propose improvements, changes, or fixes in this stage — your only goal is to explain exactly what the code does and how it works. + `, +}; - if (!parser) { - return value; - } - if (parser === true) { - return parseTokens(value); - } +/***/ }), - if (utils$1.isFunction(parser)) { - return parser.call(this, value, key); - } +/***/ 7873: +/***/ ((__unused_webpack_module, exports) => { - if (utils$1.isRegExp(parser)) { - return parser.exec(value); - } +"use strict"; - throw new TypeError('parser must be boolean|regexp|function'); - } - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.injectJsonAsMarkdownBlock = exports.extractReleaseType = exports.extractVersion = void 0; +const extractVersion = (pattern, text) => { + const versionPattern = new RegExp(`###\\s*${pattern}\\s+(\\d+\\.\\d+\\.\\d+)`, 'i'); + const match = text.match(versionPattern); + return match ? match[1] : undefined; +}; +exports.extractVersion = extractVersion; +const extractReleaseType = (pattern, text) => { + const releaseTypePattern = new RegExp(`###\\s*${pattern}\\s+(Patch|Minor|Major)`, 'i'); + const match = text.match(releaseTypePattern); + return match ? match[1] : undefined; +}; +exports.extractReleaseType = extractReleaseType; +const injectJsonAsMarkdownBlock = (title, json) => { + const formattedJson = JSON.stringify(json, null, 4) // Pretty-print the JSON with 4 spaces. + .split('\n') // Split into lines. + .map(line => `> ${line}`) // Prefix each line with '> '. + .join('\n'); // Join lines back into a string. + return `> **${title}**\n>\n> \`\`\`json\n${formattedJson}\n> \`\`\``; +}; +exports.injectJsonAsMarkdownBlock = injectJsonAsMarkdownBlock; - has(header, matcher) { - header = normalizeHeader(header); - if (header) { - const key = utils$1.findKey(this, header); +/***/ }), - return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher))); - } +/***/ 1479: +/***/ ((__unused_webpack_module, exports) => { - return false; - } +"use strict"; - delete(header, matcher) { - const self = this; - let deleted = false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.typesForIssue = exports.branchesForManagement = void 0; +const branchesForManagement = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { + if (labels.includes(hotfixLabel)) + return params.branches.bugfixTree; + if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) + return params.branches.bugfixTree; + if (labels.includes(releaseLabel)) + return params.branches.releaseTree; + if (labels.includes(docsLabel) || labels.includes(documentationLabel)) + return params.branches.docsTree; + if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) + return params.branches.choreTree; + if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) + return params.branches.featureTree; + return params.branches.featureTree; +}; +exports.branchesForManagement = branchesForManagement; +const typesForIssue = (params, labels, featureLabel, enhancementLabel, bugfixLabel, bugLabel, hotfixLabel, releaseLabel, docsLabel, documentationLabel, choreLabel, maintenanceLabel) => { + if (labels.includes(hotfixLabel)) + return params.branches.hotfixTree; + if (labels.includes(bugfixLabel) || labels.includes(bugLabel)) + return params.branches.bugfixTree; + if (labels.includes(releaseLabel)) + return params.branches.releaseTree; + if (labels.includes(docsLabel) || labels.includes(documentationLabel)) + return params.branches.docsTree; + if (labels.includes(choreLabel) || labels.includes(maintenanceLabel)) + return params.branches.choreTree; + if (labels.includes(featureLabel) || labels.includes(enhancementLabel)) + return params.branches.featureTree; + return params.branches.featureTree; +}; +exports.typesForIssue = typesForIssue; - function deleteHeader(_header) { - _header = normalizeHeader(_header); - if (_header) { - const key = utils$1.findKey(self, _header); +/***/ }), - if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) { - delete self[key]; +/***/ 4990: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - deleted = true; - } - } - } +"use strict"; - if (utils$1.isArray(header)) { - header.forEach(deleteHeader); - } else { - deleteHeader(header); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getRandomElement = void 0; +const chance_1 = __importDefault(__nccwpck_require__(2983)); +const chance = new chance_1.default(); +const getRandomElement = (list) => { + // Return undefined for empty lists + if (!list?.length) { + return undefined; } - - return deleted; - } - - clear(matcher) { - const keys = Object.keys(this); - let i = keys.length; - let deleted = false; - - while (i--) { - const key = keys[i]; - if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { - delete this[key]; - deleted = true; - } + // Return first element for single item lists + if (list.length === 1) { + return list[0]; } + // Use chance to get a random index + const randomIndex = chance.integer({ min: 0, max: list.length - 1 }); + return list[randomIndex]; +}; +exports.getRandomElement = getRandomElement; - return deleted; - } - - normalize(format) { - const self = this; - const headers = {}; - - utils$1.forEach(this, (value, header) => { - const key = utils$1.findKey(headers, header); - - if (key) { - self[key] = normalizeValue(value); - delete self[header]; - return; - } - - const normalized = format ? formatHeader(header) : String(header).trim(); - - if (normalized !== header) { - delete self[header]; - } - - self[normalized] = normalizeValue(value); - - headers[normalized] = true; - }); - - return this; - } - - concat(...targets) { - return this.constructor.concat(this, ...targets); - } - - toJSON(asStrings) { - const obj = Object.create(null); - - utils$1.forEach(this, (value, header) => { - value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value); - }); - - return obj; - } - - [Symbol.iterator]() { - return Object.entries(this.toJSON())[Symbol.iterator](); - } - - toString() { - return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n'); - } - - getSetCookie() { - return this.get("set-cookie") || []; - } - - get [Symbol.toStringTag]() { - return 'AxiosHeaders'; - } - - static from(thing) { - return thing instanceof this ? thing : new this(thing); - } - - static concat(first, ...targets) { - const computed = new this(first); - - targets.forEach((target) => computed.set(target)); - - return computed; - } - - static accessor(header) { - const internals = this[$internals] = (this[$internals] = { - accessors: {} - }); - - const accessors = internals.accessors; - const prototype = this.prototype; - function defineAccessor(_header) { - const lHeader = normalizeHeader(_header); +/***/ }), - if (!accessors[lHeader]) { - buildAccessors(prototype, _header); - accessors[lHeader] = true; - } - } +/***/ 8836: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); +"use strict"; - return this; - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.setGlobalLoggerDebug = setGlobalLoggerDebug; +exports.logInfo = logInfo; +exports.logWarning = logWarning; +exports.logError = logError; +exports.logDebugInfo = logDebugInfo; +exports.logDebugWarning = logDebugWarning; +exports.logDebugError = logDebugError; +exports.logSingleLine = logSingleLine; +const readline_1 = __importDefault(__nccwpck_require__(4521)); +let loggerDebug = false; +let loggerRemote = false; +function setGlobalLoggerDebug(debug, isRemote = false) { + loggerDebug = debug; + loggerRemote = isRemote; } - -AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); - -// reserved names hotfix -utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { - let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` - return { - get: () => value, - set(headerValue) { - this[mapped] = headerValue; +function logInfo(message, previousWasSingleLine = false) { + if (previousWasSingleLine && !loggerRemote) { + console.log(); } - } -}); - -utils$1.freezeMethods(AxiosHeaders); - -const AxiosHeaders$1 = AxiosHeaders; - -/** - * Transform the data for a request or a response - * - * @param {Array|Function} fns A single function or Array of functions - * @param {?Object} response The response object - * - * @returns {*} The resulting transformed data - */ -function transformData(fns, response) { - const config = this || defaults$1; - const context = response || config; - const headers = AxiosHeaders$1.from(context.headers); - let data = context.data; - - utils$1.forEach(fns, function transform(fn) { - data = fn.call(config, data, headers.normalize(), response ? response.status : undefined); - }); - - headers.normalize(); - - return data; -} - -function isCancel(value) { - return !!(value && value.__CANCEL__); -} - -/** - * A `CanceledError` is an object that is thrown when an operation is canceled. - * - * @param {string=} message The message. - * @param {Object=} config The config. - * @param {Object=} request The request. - * - * @returns {CanceledError} The created error. - */ -function CanceledError(message, config, request) { - // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); - this.name = 'CanceledError'; -} - -utils$1.inherits(CanceledError, AxiosError, { - __CANCEL__: true -}); - -/** - * Resolve or reject a Promise based on response status. - * - * @param {Function} resolve A function that resolves the promise. - * @param {Function} reject A function that rejects the promise. - * @param {object} response The response. - * - * @returns {object} The response. - */ -function settle(resolve, reject, response) { - const validateStatus = response.config.validateStatus; - if (!response.status || !validateStatus || validateStatus(response.status)) { - resolve(response); - } else { - reject(new AxiosError( - 'Request failed with status code ' + response.status, - [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], - response.config, - response.request, - response - )); - } -} - -/** - * Determines whether the specified URL is absolute - * - * @param {string} url The URL to test - * - * @returns {boolean} True if the specified URL is absolute, otherwise false - */ -function isAbsoluteURL(url) { - // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). - // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed - // by any combination of letters, digits, plus, period, or hyphen. - return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); -} - -/** - * Creates a new URL by combining the specified URLs - * - * @param {string} baseURL The base URL - * @param {string} relativeURL The relative URL - * - * @returns {string} The combined URL - */ -function combineURLs(baseURL, relativeURL) { - return relativeURL - ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') - : baseURL; + console.log(message); } - -/** - * Creates a new URL by combining the baseURL with the requestedURL, - * only when the requestedURL is not already an absolute URL. - * If the requestURL is absolute, this function returns the requestedURL untouched. - * - * @param {string} baseURL The base URL - * @param {string} requestedURL Absolute or relative URL to combine - * - * @returns {string} The combined full path - */ -function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) { - let isRelativeUrl = !isAbsoluteURL(requestedURL); - if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) { - return combineURLs(baseURL, requestedURL); - } - return requestedURL; +function logWarning(message) { + console.warn(message); } - -const VERSION = "1.13.1"; - -function parseProtocol(url) { - const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); - return match && match[1] || ''; +function logError(message) { + console.error(message.toString()); } - -const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/; - -/** - * Parse data uri to a Buffer or Blob - * - * @param {String} uri - * @param {?Boolean} asBlob - * @param {?Object} options - * @param {?Function} options.Blob - * - * @returns {Buffer|Blob} - */ -function fromDataURI(uri, asBlob, options) { - const _Blob = options && options.Blob || platform.classes.Blob; - const protocol = parseProtocol(uri); - - if (asBlob === undefined && _Blob) { - asBlob = true; - } - - if (protocol === 'data') { - uri = protocol.length ? uri.slice(protocol.length + 1) : uri; - - const match = DATA_URL_PATTERN.exec(uri); - - if (!match) { - throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL); - } - - const mime = match[1]; - const isBase64 = match[2]; - const body = match[3]; - const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8'); - - if (asBlob) { - if (!_Blob) { - throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT); - } - - return new _Blob([buffer], {type: mime}); +function logDebugInfo(message, previousWasSingleLine = false) { + if (loggerDebug) { + logInfo(message, previousWasSingleLine); } - - return buffer; - } - - throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT); } - -const kInternals = Symbol('internals'); - -class AxiosTransformStream extends stream__default["default"].Transform{ - constructor(options) { - options = utils$1.toFlatObject(options, { - maxRate: 0, - chunkSize: 64 * 1024, - minChunkSize: 100, - timeWindow: 500, - ticksRate: 2, - samplesCount: 15 - }, null, (prop, source) => { - return !utils$1.isUndefined(source[prop]); - }); - - super({ - readableHighWaterMark: options.chunkSize - }); - - const internals = this[kInternals] = { - timeWindow: options.timeWindow, - chunkSize: options.chunkSize, - maxRate: options.maxRate, - minChunkSize: options.minChunkSize, - bytesSeen: 0, - isCaptured: false, - notifiedBytesLoaded: 0, - ts: Date.now(), - bytes: 0, - onReadCallback: null - }; - - this.on('newListener', event => { - if (event === 'progress') { - if (!internals.isCaptured) { - internals.isCaptured = true; - } - } - }); - } - - _read(size) { - const internals = this[kInternals]; - - if (internals.onReadCallback) { - internals.onReadCallback(); +function logDebugWarning(message) { + if (loggerDebug) { + logWarning(message); } - - return super._read(size); - } - - _transform(chunk, encoding, callback) { - const internals = this[kInternals]; - const maxRate = internals.maxRate; - - const readableHighWaterMark = this.readableHighWaterMark; - - const timeWindow = internals.timeWindow; - - const divider = 1000 / timeWindow; - const bytesThreshold = (maxRate / divider); - const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0; - - const pushChunk = (_chunk, _callback) => { - const bytes = Buffer.byteLength(_chunk); - internals.bytesSeen += bytes; - internals.bytes += bytes; - - internals.isCaptured && this.emit('progress', internals.bytesSeen); - - if (this.push(_chunk)) { - process.nextTick(_callback); - } else { - internals.onReadCallback = () => { - internals.onReadCallback = null; - process.nextTick(_callback); - }; - } - }; - - const transformChunk = (_chunk, _callback) => { - const chunkSize = Buffer.byteLength(_chunk); - let chunkRemainder = null; - let maxChunkSize = readableHighWaterMark; - let bytesLeft; - let passed = 0; - - if (maxRate) { - const now = Date.now(); - - if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) { - internals.ts = now; - bytesLeft = bytesThreshold - internals.bytes; - internals.bytes = bytesLeft < 0 ? -bytesLeft : 0; - passed = 0; - } - - bytesLeft = bytesThreshold - internals.bytes; - } - - if (maxRate) { - if (bytesLeft <= 0) { - // next time window - return setTimeout(() => { - _callback(null, _chunk); - }, timeWindow - passed); - } - - if (bytesLeft < maxChunkSize) { - maxChunkSize = bytesLeft; - } - } - - if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) { - chunkRemainder = _chunk.subarray(maxChunkSize); - _chunk = _chunk.subarray(0, maxChunkSize); - } - - pushChunk(_chunk, chunkRemainder ? () => { - process.nextTick(_callback, null, chunkRemainder); - } : _callback); - }; - - transformChunk(chunk, function transformNextChunk(err, _chunk) { - if (err) { - return callback(err); - } - - if (_chunk) { - transformChunk(_chunk, transformNextChunk); - } else { - callback(null); - } - }); - } } - -const AxiosTransformStream$1 = AxiosTransformStream; - -const {asyncIterator} = Symbol; - -const readBlob = async function* (blob) { - if (blob.stream) { - yield* blob.stream(); - } else if (blob.arrayBuffer) { - yield await blob.arrayBuffer(); - } else if (blob[asyncIterator]) { - yield* blob[asyncIterator](); - } else { - yield blob; - } -}; - -const readBlob$1 = readBlob; - -const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_'; - -const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util__default["default"].TextEncoder(); - -const CRLF = '\r\n'; -const CRLF_BYTES = textEncoder.encode(CRLF); -const CRLF_BYTES_COUNT = 2; - -class FormDataPart { - constructor(name, value) { - const {escapeName} = this.constructor; - const isStringValue = utils$1.isString(value); - - let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${ - !isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : '' - }${CRLF}`; - - if (isStringValue) { - value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); - } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; - } - - this.headers = textEncoder.encode(headers + CRLF); - - this.contentLength = isStringValue ? value.byteLength : value.size; - - this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; - - this.name = name; - this.value = value; - } - - async *encode(){ - yield this.headers; - - const {value} = this; - - if(utils$1.isTypedArray(value)) { - yield value; - } else { - yield* readBlob$1(value); +function logDebugError(message) { + if (loggerDebug) { + logError(message.toString()); } - - yield CRLF_BYTES; - } - - static escapeName(name) { - return String(name).replace(/[\r\n"]/g, (match) => ({ - '\r' : '%0D', - '\n' : '%0A', - '"' : '%22', - }[match])); - } } - -const formDataToStream = (form, headersHandler, options) => { - const { - tag = 'form-data-boundary', - size = 25, - boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET) - } = options || {}; - - if(!utils$1.isFormData(form)) { - throw TypeError('FormData instance required'); - } - - if (boundary.length < 1 || boundary.length > 70) { - throw Error('boundary must be 10-70 characters long') - } - - const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); - const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF); - let contentLength = footerBytes.byteLength; - - const parts = Array.from(form.entries()).map(([name, value]) => { - const part = new FormDataPart(name, value); - contentLength += part.size; - return part; - }); - - contentLength += boundaryBytes.byteLength * parts.length; - - contentLength = utils$1.toFiniteNumber(contentLength); - - const computedHeaders = { - 'Content-Type': `multipart/form-data; boundary=${boundary}` - }; - - if (Number.isFinite(contentLength)) { - computedHeaders['Content-Length'] = contentLength; - } - - headersHandler && headersHandler(computedHeaders); - - return stream.Readable.from((async function *() { - for(const part of parts) { - yield boundaryBytes; - yield* part.encode(); - } - - yield footerBytes; - })()); -}; - -const formDataToStream$1 = formDataToStream; - -class ZlibHeaderTransformStream extends stream__default["default"].Transform { - __transform(chunk, encoding, callback) { - this.push(chunk); - callback(); - } - - _transform(chunk, encoding, callback) { - if (chunk.length !== 0) { - this._transform = this.__transform; - - // Add Default Compression headers if no zlib headers are present - if (chunk[0] !== 120) { // Hex: 78 - const header = Buffer.alloc(2); - header[0] = 120; // Hex: 78 - header[1] = 156; // Hex: 9C - this.push(header, encoding); - } +function logSingleLine(message) { + if (loggerRemote) { + console.log(message); + return; } - - this.__transform(chunk, encoding, callback); - } + readline_1.default.clearLine(process.stdout, 0); + readline_1.default.cursorTo(process.stdout, 0); + process.stdout.write(message); } -const ZlibHeaderTransformStream$1 = ZlibHeaderTransformStream; - -const callbackify = (fn, reducer) => { - return utils$1.isAsyncFn(fn) ? function (...args) { - const cb = args.pop(); - fn.apply(this, args).then((value) => { - try { - reducer ? cb(null, ...reducer(value)) : cb(null, value); - } catch (err) { - cb(err); - } - }, cb); - } : fn; -}; - -const callbackify$1 = callbackify; - -/** - * Calculate data maxRate - * @param {Number} [samplesCount= 10] - * @param {Number} [min= 1000] - * @returns {Function} - */ -function speedometer(samplesCount, min) { - samplesCount = samplesCount || 10; - const bytes = new Array(samplesCount); - const timestamps = new Array(samplesCount); - let head = 0; - let tail = 0; - let firstSampleTS; - min = min !== undefined ? min : 1000; +/***/ }), - return function push(chunkLength) { - const now = Date.now(); +/***/ 9800: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const startedAt = timestamps[tail]; +"use strict"; - if (!firstSampleTS) { - firstSampleTS = now; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.waitForPreviousRuns = void 0; +const workflow_repository_1 = __nccwpck_require__(779); +const logger_1 = __nccwpck_require__(8836); +const waitForPreviousRuns = async (params) => { + let attempts = 0; + while (attempts < 2000) { + const workflowRepository = new workflow_repository_1.WorkflowRepository(); + const activeRuns = await workflowRepository.getActivePreviousRuns(params); + if (activeRuns.length === 0) { + (0, logger_1.logDebugInfo)("āœ… No previous runs active. Continuing..."); + return; + } + (0, logger_1.logDebugInfo)(`ā³ Found ${activeRuns.length} previous run(s) still active. Waiting 2s...`); + await new Promise((res) => setTimeout(res, 2000)); + attempts++; } + throw new Error("Timeout waiting for previous runs to finish."); +}; +exports.waitForPreviousRuns = waitForPreviousRuns; - bytes[head] = chunkLength; - timestamps[head] = now; - - let i = tail; - let bytesCount = 0; - while (i !== head) { - bytesCount += bytes[i++]; - i = i % samplesCount; - } +/***/ }), - head = (head + 1) % samplesCount; +/***/ 6676: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (head === tail) { - tail = (tail + 1) % samplesCount; - } +"use strict"; - if (now - firstSampleTS < min) { - return; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.extractVersionFromBranch = exports.extractIssueNumberFromPush = exports.extractIssueNumberFromBranch = void 0; +const logger_1 = __nccwpck_require__(8836); +const extractIssueNumberFromBranch = (branchName) => { + const match = branchName?.match(/[a-zA-Z]+\/([0-9]+)-.*/); + if (match) { + return parseInt(match[1]); } - - const passed = startedAt && now - startedAt; - - return passed ? Math.round(bytesCount * 1000 / passed) : undefined; - }; -} - -/** - * Throttle decorator - * @param {Function} fn - * @param {Number} freq - * @return {Function} - */ -function throttle(fn, freq) { - let timestamp = 0; - let threshold = 1000 / freq; - let lastArgs; - let timer; - - const invoke = (args, now = Date.now()) => { - timestamp = now; - lastArgs = null; - if (timer) { - clearTimeout(timer); - timer = null; - } - fn(...args); - }; - - const throttled = (...args) => { - const now = Date.now(); - const passed = now - timestamp; - if ( passed >= threshold) { - invoke(args, now); - } else { - lastArgs = args; - if (!timer) { - timer = setTimeout(() => { - timer = null; - invoke(lastArgs); - }, threshold - passed); - } + else { + (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); + return -1; } - }; - - const flush = () => lastArgs && invoke(lastArgs); - - return [throttled, flush]; -} - -const progressEventReducer = (listener, isDownloadStream, freq = 3) => { - let bytesNotified = 0; - const _speedometer = speedometer(50, 250); - - return throttle(e => { - const loaded = e.loaded; - const total = e.lengthComputable ? e.total : undefined; - const progressBytes = loaded - bytesNotified; - const rate = _speedometer(progressBytes); - const inRange = loaded <= total; - - bytesNotified = loaded; - - const data = { - loaded, - total, - progress: total ? (loaded / total) : undefined, - bytes: progressBytes, - rate: rate ? rate : undefined, - estimated: rate && total && inRange ? (total - loaded) / rate : undefined, - event: e, - lengthComputable: total != null, - [isDownloadStream ? 'download' : 'upload']: true - }; - - listener(data); - }, freq); -}; - -const progressEventDecorator = (total, throttled) => { - const lengthComputable = total != null; - - return [(loaded) => throttled[0]({ - lengthComputable, - total, - loaded - }), throttled[1]]; }; - -const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args)); - -/** - * Estimate decoded byte length of a data:// URL *without* allocating large buffers. - * - For base64: compute exact decoded size using length and padding; - * handle %XX at the character-count level (no string allocation). - * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound. - * - * @param {string} url - * @returns {number} - */ -function estimateDataURLDecodedBytes(url) { - if (!url || typeof url !== 'string') return 0; - if (!url.startsWith('data:')) return 0; - - const comma = url.indexOf(','); - if (comma < 0) return 0; - - const meta = url.slice(5, comma); - const body = url.slice(comma + 1); - const isBase64 = /;base64/i.test(meta); - - if (isBase64) { - let effectiveLen = body.length; - const len = body.length; // cache length - - for (let i = 0; i < len; i++) { - if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) { - const a = body.charCodeAt(i + 1); - const b = body.charCodeAt(i + 2); - const isHex = - ((a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)) && - ((b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102)); - - if (isHex) { - effectiveLen -= 2; - i += 2; - } - } +exports.extractIssueNumberFromBranch = extractIssueNumberFromBranch; +const extractIssueNumberFromPush = (branchName) => { + const issueNumberMatch = branchName.match(/^[^/]+\/(\d+)-/); + if (!issueNumberMatch) { + (0, logger_1.logDebugInfo)('No issue number found in the branch name.'); + return -1; } - - let pad = 0; - let idx = len - 1; - - const tailIsPct3D = (j) => - j >= 2 && - body.charCodeAt(j - 2) === 37 && // '%' - body.charCodeAt(j - 1) === 51 && // '3' - (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd' - - if (idx >= 0) { - if (body.charCodeAt(idx) === 61 /* '=' */) { - pad++; - idx--; - } else if (tailIsPct3D(idx)) { - pad++; - idx -= 3; - } + const issueNumber = parseInt(issueNumberMatch[1], 10); + (0, logger_1.logDebugInfo)(`Linked Issue: #${issueNumber}`); + return issueNumber; +}; +exports.extractIssueNumberFromPush = extractIssueNumberFromPush; +const extractVersionFromBranch = (branchName) => { + const match = branchName?.match(/^[^\/]+\/(\d+\.\d+\.\d+)$/); + if (match) { + return match[1]; } - - if (pad === 1 && idx >= 0) { - if (body.charCodeAt(idx) === 61 /* '=' */) { - pad++; - } else if (tailIsPct3D(idx)) { - pad++; - } + else { + (0, logger_1.logDebugInfo)('No version found in the branch name.'); + return undefined; } - - const groups = Math.floor(effectiveLen / 4); - const bytes = groups * 3 - (pad || 0); - return bytes > 0 ? bytes : 0; - } - - return Buffer.byteLength(body, 'utf8'); -} - -const zlibOptions = { - flush: zlib__default["default"].constants.Z_SYNC_FLUSH, - finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH -}; - -const brotliOptions = { - flush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH, - finishFlush: zlib__default["default"].constants.BROTLI_OPERATION_FLUSH -}; - -const { - HTTP2_HEADER_SCHEME, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_HEADER_STATUS -} = http2.constants; - -const isBrotliSupported = utils$1.isFunction(zlib__default["default"].createBrotliDecompress); - -const {http: httpFollow, https: httpsFollow} = followRedirects__default["default"]; - -const isHttps = /https:?/; - -const supportedProtocols = platform.protocols.map(protocol => { - return protocol + ':'; -}); - - -const flushOnFinish = (stream, [throttled, flush]) => { - stream - .on('end', flush) - .on('error', flush); - - return throttled; }; +exports.extractVersionFromBranch = extractVersionFromBranch; -class Http2Sessions { - constructor() { - this.sessions = Object.create(null); - } - getSession(authority, options) { - options = Object.assign({ - sessionTimeout: 1000 - }, options); +/***/ }), - let authoritySessions; +/***/ 9887: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if ((authoritySessions = this.sessions[authority])) { - let len = authoritySessions.length; +"use strict"; - for (let i = 0; i < len; i++) { - const [sessionHandle, sessionOptions] = authoritySessions[i]; - if (!sessionHandle.destroyed && !sessionHandle.closed && util__default["default"].isDeepStrictEqual(sessionOptions, options)) { - return sessionHandle; - } - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getLatestVersion = exports.incrementVersion = void 0; +const logger_1 = __nccwpck_require__(8836); +const incrementVersion = (version, releaseType) => { + (0, logger_1.logDebugInfo)(`Incrementing version ${version}.`); + const versionParts = version.split('.').map(Number); + if (versionParts.length !== 3) { + throw new Error('Invalid version format'); } + const [major, minor, patch] = versionParts; + switch (releaseType) { + case 'Major': + // Increment the major version and reset minor and patch + return `${major + 1}.0.0`; + case 'Minor': + // Increment the minor version and reset patch + return `${major}.${minor + 1}.0`; + case 'Patch': + // Increment the patch version + return `${major}.${minor}.${patch + 1}`; + default: + throw new Error('Unknown release type'); + } +}; +exports.incrementVersion = incrementVersion; +const getLatestVersion = (versions) => { + return versions + .map(version => version.split('.').map(num => parseInt(num, 10))) + .sort((a, b) => { + for (let i = 0; i < 3; i++) { + if (a[i] > b[i]) + return 1; + if (a[i] < b[i]) + return -1; + } + return 0; + }) + .map(version => version.join('.')) + .pop(); +}; +exports.getLatestVersion = getLatestVersion; - const session = http2.connect(authority, options); - let removed; +/***/ }), - const removeSession = () => { - if (removed) { - return; - } +/***/ 9491: +/***/ ((module) => { - removed = true; +"use strict"; +module.exports = require("assert"); - let entries = authoritySessions, len = entries.length, i = len; +/***/ }), - while (i--) { - if (entries[i][0] === session) { - entries.splice(i, 1); - if (len === 1) { - delete this.sessions[authority]; - return; - } - } - } - }; +/***/ 852: +/***/ ((module) => { - const originalRequestFn = session.request; +"use strict"; +module.exports = require("async_hooks"); - const {sessionTimeout} = options; +/***/ }), - if(sessionTimeout != null) { +/***/ 4300: +/***/ ((module) => { - let timer; - let streamsCount = 0; +"use strict"; +module.exports = require("buffer"); - session.request = function () { - const stream = originalRequestFn.apply(this, arguments); +/***/ }), - streamsCount++; +/***/ 2081: +/***/ ((module) => { - if (timer) { - clearTimeout(timer); - timer = null; - } +"use strict"; +module.exports = require("child_process"); - stream.once('close', () => { - if (!--streamsCount) { - timer = setTimeout(() => { - timer = null; - removeSession(); - }, sessionTimeout); - } - }); +/***/ }), - return stream; - }; - } +/***/ 6206: +/***/ ((module) => { - session.once('close', removeSession); +"use strict"; +module.exports = require("console"); - let entries = this.sessions[authority], entry = [ - session, - options - ]; +/***/ }), - entries ? this.sessions[authority].push(entry) : authoritySessions = this.sessions[authority] = [entry]; +/***/ 6113: +/***/ ((module) => { - return session; - } -} +"use strict"; +module.exports = require("crypto"); -const http2Sessions = new Http2Sessions(); +/***/ }), +/***/ 7643: +/***/ ((module) => { -/** - * If the proxy or config beforeRedirects functions are defined, call them with the options - * object. - * - * @param {Object} options - The options object that was passed to the request. - * - * @returns {Object} - */ -function dispatchBeforeRedirect(options, responseDetails) { - if (options.beforeRedirects.proxy) { - options.beforeRedirects.proxy(options); - } - if (options.beforeRedirects.config) { - options.beforeRedirects.config(options, responseDetails); - } -} +"use strict"; +module.exports = require("diagnostics_channel"); -/** - * If the proxy or config afterRedirects functions are defined, call them with the options - * - * @param {http.ClientRequestArgs} options - * @param {AxiosProxyConfig} configProxy configuration from Axios options object - * @param {string} location - * - * @returns {http.ClientRequestArgs} - */ -function setProxy(options, configProxy, location) { - let proxy = configProxy; - if (!proxy && proxy !== false) { - const proxyUrl = proxyFromEnv__default["default"].getProxyForUrl(location); - if (proxyUrl) { - proxy = new URL(proxyUrl); - } - } - if (proxy) { - // Basic proxy authorization - if (proxy.username) { - proxy.auth = (proxy.username || '') + ':' + (proxy.password || ''); - } +/***/ }), - if (proxy.auth) { - // Support proxy auth object form - if (proxy.auth.username || proxy.auth.password) { - proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || ''); - } - const base64 = Buffer - .from(proxy.auth, 'utf8') - .toString('base64'); - options.headers['Proxy-Authorization'] = 'Basic ' + base64; - } +/***/ 2361: +/***/ ((module) => { - options.headers.host = options.hostname + (options.port ? ':' + options.port : ''); - const proxyHost = proxy.hostname || proxy.host; - options.hostname = proxyHost; - // Replace 'host' since options is not a URL object - options.host = proxyHost; - options.port = proxy.port; - options.path = location; - if (proxy.protocol) { - options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`; - } - } +"use strict"; +module.exports = require("events"); - options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) { - // Configure proxy for redirected request, passing the original config proxy to apply - // the exact same logic as if the redirected request was performed by axios directly. - setProxy(redirectOptions, configProxy, redirectOptions.href); - }; -} +/***/ }), -const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process'; +/***/ 7147: +/***/ ((module) => { -// temporary hotfix +"use strict"; +module.exports = require("fs"); -const wrapAsync = (asyncExecutor) => { - return new Promise((resolve, reject) => { - let onDone; - let isDone; +/***/ }), - const done = (value, isRejected) => { - if (isDone) return; - isDone = true; - onDone && onDone(value, isRejected); - }; +/***/ 3685: +/***/ ((module) => { - const _resolve = (value) => { - done(value); - resolve(value); - }; +"use strict"; +module.exports = require("http"); - const _reject = (reason) => { - done(reason, true); - reject(reason); - }; +/***/ }), - asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject); - }) -}; +/***/ 5158: +/***/ ((module) => { -const resolveFamily = ({address, family}) => { - if (!utils$1.isString(address)) { - throw TypeError('address must be a string'); - } - return ({ - address, - family: family || (address.indexOf('.') < 0 ? 6 : 4) - }); -}; +"use strict"; +module.exports = require("http2"); -const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {address, family}); +/***/ }), -const http2Transport = { - request(options, cb) { - const authority = options.protocol + '//' + options.hostname + ':' + (options.port || 80); +/***/ 5687: +/***/ ((module) => { - const {http2Options, headers} = options; +"use strict"; +module.exports = require("https"); - const session = http2Sessions.getSession(authority, http2Options); +/***/ }), - const http2Headers = { - [HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''), - [HTTP2_HEADER_METHOD]: options.method, - [HTTP2_HEADER_PATH]: options.path, - }; +/***/ 1808: +/***/ ((module) => { - utils$1.forEach(headers, (header, name) => { - name.charAt(0) !== ':' && (http2Headers[name] = header); - }); +"use strict"; +module.exports = require("net"); - const req = session.request(http2Headers); +/***/ }), - req.once('response', (responseHeaders) => { - const response = req; //duplex +/***/ 6005: +/***/ ((module) => { - responseHeaders = Object.assign({}, responseHeaders); +"use strict"; +module.exports = require("node:crypto"); - const status = responseHeaders[HTTP2_HEADER_STATUS]; +/***/ }), - delete responseHeaders[HTTP2_HEADER_STATUS]; +/***/ 5673: +/***/ ((module) => { - response.headers = responseHeaders; +"use strict"; +module.exports = require("node:events"); - response.statusCode = +status; +/***/ }), - cb(response); - }); +/***/ 7742: +/***/ ((module) => { - return req; - } -}; +"use strict"; +module.exports = require("node:process"); -/*eslint consistent-return:0*/ -const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) { - return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) { - let {data, lookup, family, httpVersion = 1, http2Options} = config; - const {responseType, responseEncoding} = config; - const method = config.method.toUpperCase(); - let isDone; - let rejected = false; - let req; +/***/ }), - httpVersion = +httpVersion; +/***/ 4492: +/***/ ((module) => { - if (Number.isNaN(httpVersion)) { - throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`); - } +"use strict"; +module.exports = require("node:stream"); - if (httpVersion !== 1 && httpVersion !== 2) { - throw TypeError(`Unsupported protocol version '${httpVersion}'`); - } +/***/ }), - const isHttp2 = httpVersion === 2; +/***/ 7261: +/***/ ((module) => { - if (lookup) { - const _lookup = callbackify$1(lookup, (value) => utils$1.isArray(value) ? value : [value]); - // hotfix to support opt.all option which is required for node 20.x - lookup = (hostname, opt, cb) => { - _lookup(hostname, opt, (err, arg0, arg1) => { - if (err) { - return cb(err); - } +"use strict"; +module.exports = require("node:util"); - const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)]; +/***/ }), - opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family); - }); - }; - } +/***/ 2037: +/***/ ((module) => { - const abortEmitter = new events.EventEmitter(); +"use strict"; +module.exports = require("os"); - function abort(reason) { - try { - abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason); - } catch(err) { - console.warn('emit error', err); - } - } +/***/ }), - abortEmitter.once('abort', reject); +/***/ 1017: +/***/ ((module) => { - const onFinished = () => { - if (config.cancelToken) { - config.cancelToken.unsubscribe(abort); - } +"use strict"; +module.exports = require("path"); - if (config.signal) { - config.signal.removeEventListener('abort', abort); - } +/***/ }), - abortEmitter.removeAllListeners(); - }; +/***/ 4074: +/***/ ((module) => { - if (config.cancelToken || config.signal) { - config.cancelToken && config.cancelToken.subscribe(abort); - if (config.signal) { - config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort); - } - } +"use strict"; +module.exports = require("perf_hooks"); - onDone((response, isRejected) => { - isDone = true; +/***/ }), - if (isRejected) { - rejected = true; - onFinished(); - return; - } +/***/ 3477: +/***/ ((module) => { - const {data} = response; +"use strict"; +module.exports = require("querystring"); - if (data instanceof stream__default["default"].Readable || data instanceof stream__default["default"].Duplex) { - const offListeners = stream__default["default"].finished(data, () => { - offListeners(); - onFinished(); - }); - } else { - onFinished(); - } - }); +/***/ }), +/***/ 4521: +/***/ ((module) => { +"use strict"; +module.exports = require("readline"); +/***/ }), +/***/ 2781: +/***/ ((module) => { - // Parse url - const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); - const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined); - const protocol = parsed.protocol || supportedProtocols[0]; +"use strict"; +module.exports = require("stream"); - if (protocol === 'data:') { - // Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set. - if (config.maxContentLength > -1) { - // Use the exact string passed to fromDataURI (config.url); fall back to fullPath if needed. - const dataUrl = String(config.url || fullPath || ''); - const estimated = estimateDataURLDecodedBytes(dataUrl); +/***/ }), - if (estimated > config.maxContentLength) { - return reject(new AxiosError( - 'maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, - config - )); - } - } +/***/ 5356: +/***/ ((module) => { - let convertedData; +"use strict"; +module.exports = require("stream/web"); - if (method !== 'GET') { - return settle(resolve, reject, { - status: 405, - statusText: 'method not allowed', - headers: {}, - config - }); - } +/***/ }), - try { - convertedData = fromDataURI(config.url, responseType === 'blob', { - Blob: config.env && config.env.Blob - }); - } catch (err) { - throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config); - } +/***/ 1576: +/***/ ((module) => { - if (responseType === 'text') { - convertedData = convertedData.toString(responseEncoding); +"use strict"; +module.exports = require("string_decoder"); - if (!responseEncoding || responseEncoding === 'utf8') { - convertedData = utils$1.stripBOM(convertedData); - } - } else if (responseType === 'stream') { - convertedData = stream__default["default"].Readable.from(convertedData); - } +/***/ }), - return settle(resolve, reject, { - data: convertedData, - status: 200, - statusText: 'OK', - headers: new AxiosHeaders$1(), - config - }); - } +/***/ 9512: +/***/ ((module) => { - if (supportedProtocols.indexOf(protocol) === -1) { - return reject(new AxiosError( - 'Unsupported protocol ' + protocol, - AxiosError.ERR_BAD_REQUEST, - config - )); - } +"use strict"; +module.exports = require("timers"); - const headers = AxiosHeaders$1.from(config.headers).normalize(); +/***/ }), - // Set User-Agent (required by some servers) - // See https://github.com/axios/axios/issues/69 - // User-Agent is specified; handle case where no UA header is desired - // Only set header if it hasn't been set in config - headers.set('User-Agent', 'axios/' + VERSION, false); +/***/ 4404: +/***/ ((module) => { - const {onUploadProgress, onDownloadProgress} = config; - const maxRate = config.maxRate; - let maxUploadRate = undefined; - let maxDownloadRate = undefined; +"use strict"; +module.exports = require("tls"); - // support for spec compliant FormData objects - if (utils$1.isSpecCompliantForm(data)) { - const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i); +/***/ }), - data = formDataToStream$1(data, (formHeaders) => { - headers.set(formHeaders); - }, { - tag: `axios-${VERSION}-boundary`, - boundary: userBoundary && userBoundary[1] || undefined - }); - // support for https://www.npmjs.com/package/form-data api - } else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders)) { - headers.set(data.getHeaders()); +/***/ 7310: +/***/ ((module) => { - if (!headers.hasContentLength()) { - try { - const knownLength = await util__default["default"].promisify(data.getLength).call(data); - Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength); - /*eslint no-empty:0*/ - } catch (e) { - } - } - } else if (utils$1.isBlob(data) || utils$1.isFile(data)) { - data.size && headers.setContentType(data.type || 'application/octet-stream'); - headers.setContentLength(data.size || 0); - data = stream__default["default"].Readable.from(readBlob$1(data)); - } else if (data && !utils$1.isStream(data)) { - if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) { - data = Buffer.from(new Uint8Array(data)); - } else if (utils$1.isString(data)) { - data = Buffer.from(data, 'utf-8'); - } else { - return reject(new AxiosError( - 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', - AxiosError.ERR_BAD_REQUEST, - config - )); - } +"use strict"; +module.exports = require("url"); - // Add Content-Length header if data exists - headers.setContentLength(data.length, false); +/***/ }), - if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) { - return reject(new AxiosError( - 'Request body larger than maxBodyLength limit', - AxiosError.ERR_BAD_REQUEST, - config - )); - } - } +/***/ 3837: +/***/ ((module) => { - const contentLength = utils$1.toFiniteNumber(headers.getContentLength()); +"use strict"; +module.exports = require("util"); - if (utils$1.isArray(maxRate)) { - maxUploadRate = maxRate[0]; - maxDownloadRate = maxRate[1]; - } else { - maxUploadRate = maxDownloadRate = maxRate; - } +/***/ }), - if (data && (onUploadProgress || maxUploadRate)) { - if (!utils$1.isStream(data)) { - data = stream__default["default"].Readable.from(data, {objectMode: false}); - } +/***/ 9830: +/***/ ((module) => { - data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxUploadRate) - })], utils$1.noop); +"use strict"; +module.exports = require("util/types"); - onUploadProgress && data.on('progress', flushOnFinish( - data, - progressEventDecorator( - contentLength, - progressEventReducer(asyncDecorator(onUploadProgress), false, 3) - ) - )); - } +/***/ }), - // HTTP basic authentication - let auth = undefined; - if (config.auth) { - const username = config.auth.username || ''; - const password = config.auth.password || ''; - auth = username + ':' + password; - } +/***/ 1267: +/***/ ((module) => { - if (!auth && parsed.username) { - const urlUsername = parsed.username; - const urlPassword = parsed.password; - auth = urlUsername + ':' + urlPassword; - } +"use strict"; +module.exports = require("worker_threads"); - auth && headers.delete('authorization'); +/***/ }), - let path; +/***/ 9796: +/***/ ((module) => { - try { - path = buildURL( - parsed.pathname + parsed.search, - config.params, - config.paramsSerializer - ).replace(/^\?/, ''); - } catch (err) { - const customErr = new Error(err.message); - customErr.config = config; - customErr.url = config.url; - customErr.exists = true; - return reject(customErr); - } +"use strict"; +module.exports = require("zlib"); - headers.set( - 'Accept-Encoding', - 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false - ); +/***/ }), - const options = { - path, - method: method, - headers: headers.toJSON(), - agents: { http: config.httpAgent, https: config.httpsAgent }, - auth, - protocol, - family, - beforeRedirect: dispatchBeforeRedirect, - beforeRedirects: {}, - http2Options - }; +/***/ 2960: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // cacheable-lookup integration hotfix - !utils$1.isUndefined(lookup) && (options.lookup = lookup); +"use strict"; - if (config.socketPath) { - options.socketPath = config.socketPath; - } else { - options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname; - options.port = parsed.port; - setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); - } - let transport; - const isHttpsRequest = isHttps.test(options.protocol); - options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; +const WritableStream = (__nccwpck_require__(4492).Writable) +const inherits = (__nccwpck_require__(7261).inherits) - if (isHttp2) { - transport = http2Transport; - } else { - if (config.transport) { - transport = config.transport; - } else if (config.maxRedirects === 0) { - transport = isHttpsRequest ? https__default["default"] : http__default["default"]; - } else { - if (config.maxRedirects) { - options.maxRedirects = config.maxRedirects; - } - if (config.beforeRedirect) { - options.beforeRedirects.config = config.beforeRedirect; - } - transport = isHttpsRequest ? httpsFollow : httpFollow; - } - } +const StreamSearch = __nccwpck_require__(1142) - if (config.maxBodyLength > -1) { - options.maxBodyLength = config.maxBodyLength; - } else { - // follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited - options.maxBodyLength = Infinity; - } +const PartStream = __nccwpck_require__(1620) +const HeaderParser = __nccwpck_require__(2032) - if (config.insecureHTTPParser) { - options.insecureHTTPParser = config.insecureHTTPParser; - } +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} - // Create the request - req = transport.request(options, function handleResponse(res) { - if (req.destroyed) return; +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) - const streams = [res]; + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - const responseLength = utils$1.toFiniteNumber(res.headers['content-length']); + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - if (onDownloadProgress || maxDownloadRate) { - const transformStream = new AxiosTransformStream$1({ - maxRate: utils$1.toFiniteNumber(maxDownloadRate) - }); + this._headerFirst = cfg.headerFirst - onDownloadProgress && transformStream.on('progress', flushOnFinish( - transformStream, - progressEventDecorator( - responseLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true, 3) - ) - )); + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false - streams.push(transformStream); - } + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) - // decompress the response body transparently if required - let responseStream = res; - - // return the last request in case of redirects - const lastRequest = res.req || req; - - // if decompress disabled we should not decompress - if (config.decompress !== false && res.headers['content-encoding']) { - // if no content, but headers still say that it is encoded, - // remove the header not confuse downstream operations - if (method === 'HEAD' || res.statusCode === 204) { - delete res.headers['content-encoding']; - } - - switch ((res.headers['content-encoding'] || '').toLowerCase()) { - /*eslint default-case:0*/ - case 'gzip': - case 'x-gzip': - case 'compress': - case 'x-compress': - // add the unzipper to the body stream processing pipeline - streams.push(zlib__default["default"].createUnzip(zlibOptions)); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - case 'deflate': - streams.push(new ZlibHeaderTransformStream$1()); - - // add the unzipper to the body stream processing pipeline - streams.push(zlib__default["default"].createUnzip(zlibOptions)); - - // remove the content-encoding in order to not confuse downstream operations - delete res.headers['content-encoding']; - break; - case 'br': - if (isBrotliSupported) { - streams.push(zlib__default["default"].createBrotliDecompress(brotliOptions)); - delete res.headers['content-encoding']; - } +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return } - } - - responseStream = streams.length > 1 ? stream__default["default"].pipeline(streams, utils$1.noop) : streams[0]; + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } +} +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } - const response = { - status: res.statusCode, - statusText: res.statusMessage, - headers: new AxiosHeaders$1(res.headers), - config, - request: lastRequest - }; + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } - if (responseType === 'stream') { - response.data = responseStream; - settle(resolve, reject, response); - } else { - const responseBuffer = []; - let totalResponseBytes = 0; - - responseStream.on('data', function handleStreamData(chunk) { - responseBuffer.push(chunk); - totalResponseBytes += chunk.length; - - // make sure the content length is not over the maxContentLength if specified - if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { - // stream.destroy() emit aborted event before calling reject() on Node.js v16 - rejected = true; - responseStream.destroy(); - abort(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded', - AxiosError.ERR_BAD_RESPONSE, config, lastRequest)); - } - }); + this._bparser.push(data) - responseStream.on('aborted', function handlerStreamAborted() { - if (rejected) { - return; - } + if (this._pause) { this._cb = cb } else { cb() } +} - const err = new AxiosError( - 'stream has been aborted', - AxiosError.ERR_BAD_RESPONSE, - config, - lastRequest - ); - responseStream.destroy(err); - reject(err); - }); +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} - responseStream.on('error', function handleStreamError(err) { - if (req.destroyed) return; - reject(AxiosError.from(err, null, config, lastRequest)); - }); +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} - responseStream.on('end', function handleStreamEnd() { - try { - let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer); - if (responseType !== 'arraybuffer') { - responseData = responseData.toString(responseEncoding); - if (!responseEncoding || responseEncoding === 'utf8') { - responseData = utils$1.stripBOM(responseData); - } - } - response.data = responseData; - } catch (err) { - return reject(AxiosError.from(err, null, config, response.request, response)); - } - settle(resolve, reject, response); - }); - } +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} - abortEmitter.once('abort', err => { - if (!responseStream.destroyed) { - responseStream.emit('error', err); - responseStream.destroy(); - } - }); - }); +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true - abortEmitter.once('abort', err => { - if (req.close) { - req.close(); + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes } else { - req.destroy(err); + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break } - }); - - // Handle errors - req.on('error', function handleRequestError(err) { - // @todo remove - // if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return; - reject(AxiosError.from(err, null, config, req)); - }); - - // set tcp keep alive to prevent drop connection by peer - req.on('socket', function handleRequestSocket(socket) { - // default interval of sending ack packet is 1 minute - socket.setKeepAlive(true, 1000 * 60); - }); - - // Handle request timeout - if (config.timeout) { - // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. - const timeout = parseInt(config.timeout, 10); - - if (Number.isNaN(timeout)) { - abort(new AxiosError( - 'error trying to parse `config.timeout` to int', - AxiosError.ERR_BAD_OPTION_VALUE, - config, - req - )); - - return; + } + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false } - - // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. - // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. - // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. - // And then these socket which be hang up will devouring CPU little by little. - // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. - req.setTimeout(timeout, function handleRequestTimeout() { - if (isDone) return; - let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = config.transitional || transitionalDefaults; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; - } - abort(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - req - )); - }); } - - - // Send the request - if (utils$1.isStream(data)) { - let ended = false; - let errored = false; - - data.on('end', () => { - ended = true; - }); - - data.once('error', err => { - errored = true; - req.destroy(err); - }); - - data.on('close', () => { - if (!ended && !errored) { - abort(new CanceledError('Request stream has been aborted', config, req)); - } - }); - - data.pipe(req); + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) } else { - data && req.write(data); - req.end(); + this._ignore() } - }); -}; - -const isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => { - url = new URL(url, platform.origin); - - return ( - origin.protocol === url.protocol && - origin.host === url.host && - (isMSIE || origin.port === url.port) - ); -})( - new URL(platform.origin), - platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent) -) : () => true; - -const cookies = platform.hasStandardBrowserEnv ? - - // Standard browser envs support document.cookie - { - write(name, value, expires, path, domain, secure, sameSite) { - if (typeof document === 'undefined') return; - - const cookie = [`${name}=${encodeURIComponent(value)}`]; - - if (utils$1.isNumber(expires)) { - cookie.push(`expires=${new Date(expires).toUTCString()}`); - } - if (utils$1.isString(path)) { - cookie.push(`path=${path}`); - } - if (utils$1.isString(domain)) { - cookie.push(`domain=${domain}`); - } - if (secure === true) { - cookie.push('secure'); - } - if (utils$1.isString(sameSite)) { - cookie.push(`SameSite=${sameSite}`); + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) } - - document.cookie = cookie.join('; '); - }, - - read(name) { - if (typeof document === 'undefined') return null; - const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)')); - return match ? decodeURIComponent(match[1]) : null; - }, - - remove(name) { - this.write(name, '', Date.now() - 86400000, '/'); } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 } - - : - - // Non-standard browser env (web workers, react-native) lack needed support. - { - write() {}, - read() { - return null; - }, - remove() {} - }; - -const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing; - -/** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * - * @returns {Object} New object resulting from merging config2 to config1 - */ -function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - const config = {}; - - function getMergedValue(target, source, prop, caseless) { - if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) { - return utils$1.merge.call({caseless}, target, source); - } else if (utils$1.isPlainObject(source)) { - return utils$1.merge({}, source); - } else if (utils$1.isArray(source)) { - return source.slice(); - } - return source; - } - - // eslint-disable-next-line consistent-return - function mergeDeepProperties(a, b, prop, caseless) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(a, b, prop, caseless); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a, prop, caseless); - } - } - - // eslint-disable-next-line consistent-return - function valueFromConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } - } - - // eslint-disable-next-line consistent-return - function defaultToConfig2(a, b) { - if (!utils$1.isUndefined(b)) { - return getMergedValue(undefined, b); - } else if (!utils$1.isUndefined(a)) { - return getMergedValue(undefined, a); - } - } - - // eslint-disable-next-line consistent-return - function mergeDirectKeys(a, b, prop) { - if (prop in config2) { - return getMergedValue(a, b); - } else if (prop in config1) { - return getMergedValue(undefined, a); - } - } - - const mergeMap = { - url: valueFromConfig2, - method: valueFromConfig2, - data: valueFromConfig2, - baseURL: defaultToConfig2, - transformRequest: defaultToConfig2, - transformResponse: defaultToConfig2, - paramsSerializer: defaultToConfig2, - timeout: defaultToConfig2, - timeoutMessage: defaultToConfig2, - withCredentials: defaultToConfig2, - withXSRFToken: defaultToConfig2, - adapter: defaultToConfig2, - responseType: defaultToConfig2, - xsrfCookieName: defaultToConfig2, - xsrfHeaderName: defaultToConfig2, - onUploadProgress: defaultToConfig2, - onDownloadProgress: defaultToConfig2, - decompress: defaultToConfig2, - maxContentLength: defaultToConfig2, - maxBodyLength: defaultToConfig2, - beforeRedirect: defaultToConfig2, - transport: defaultToConfig2, - httpAgent: defaultToConfig2, - httpsAgent: defaultToConfig2, - cancelToken: defaultToConfig2, - socketPath: defaultToConfig2, - responseEncoding: defaultToConfig2, - validateStatus: mergeDirectKeys, - headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true) - }; - - utils$1.forEach(Object.keys({...config1, ...config2}), function computeConfigValue(prop) { - const merge = mergeMap[prop] || mergeDeepProperties; - const configValue = merge(config1[prop], config2[prop], prop); - (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue); - }); - - return config; } -const resolveConfig = (config) => { - const newConfig = mergeConfig({}, config); - - let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig; - - newConfig.headers = headers = AxiosHeaders$1.from(headers); - - newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer); - - // HTTP basic authentication - if (auth) { - headers.set('Authorization', 'Basic ' + - btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : '')) - ); - } - - if (utils$1.isFormData(data)) { - if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) { - headers.setContentType(undefined); // browser handles it - } else if (utils$1.isFunction(data.getHeaders)) { - // Node.js FormData (like form-data package) - const formHeaders = data.getHeaders(); - // Only set safe headers to avoid overwriting security headers - const allowedHeaders = ['content-type', 'content-length']; - Object.entries(formHeaders).forEach(([key, val]) => { - if (allowedHeaders.includes(key.toLowerCase())) { - headers.set(key, val); - } - }); - } - } - - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - - if (platform.hasStandardBrowserEnv) { - withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig)); - - if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) { - // Add xsrf header - const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName); +Dicer.prototype._unpause = function () { + if (!this._pause) { return } - if (xsrfValue) { - headers.set(xsrfHeaderName, xsrfValue); - } - } + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() } +} - return newConfig; -}; +module.exports = Dicer -const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined'; -const xhrAdapter = isXHRAdapterSupported && function (config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - const _config = resolveConfig(config); - let requestData = _config.data; - const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize(); - let {responseType, onUploadProgress, onDownloadProgress} = _config; - let onCanceled; - let uploadThrottled, downloadThrottled; - let flushUpload, flushDownload; +/***/ }), - function done() { - flushUpload && flushUpload(); // flush events - flushDownload && flushDownload(); // flush events +/***/ 2032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled); +"use strict"; - _config.signal && _config.signal.removeEventListener('abort', onCanceled); - } - let request = new XMLHttpRequest(); +const EventEmitter = (__nccwpck_require__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) +const getLimit = __nccwpck_require__(1467) - request.open(_config.method.toUpperCase(), _config.url, true); +const StreamSearch = __nccwpck_require__(1142) - // Set the request timeout in MS - request.timeout = _config.timeout; +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex - function onloadend() { - if (!request) { - return; - } - // Prepare the response - const responseHeaders = AxiosHeaders$1.from( - 'getAllResponseHeaders' in request && request.getAllResponseHeaders() - ); - const responseData = !responseType || responseType === 'text' || responseType === 'json' ? - request.responseText : request.response; - const response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config, - request - }; +function HeaderParser (cfg) { + EventEmitter.call(this) - settle(function _resolve(value) { - resolve(value); - done(); - }, function _reject(err) { - reject(err); - done(); - }, response); + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } - // Clean up request - request = null; + self.buffer += data.toString('binary', start, end) } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) - if ('onloadend' in request) { - // Use onloadend if available - request.onloadend = onloadend; - } else { - // Listen for ready state to emulate onloadend - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; - } - // readystate handler is calling before onerror or ontimeout handlers, - // so we should call onloadend on the next 'tick' - setTimeout(onloadend); - }; - } +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} - reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } - // Clean up request - request = null; - }; + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h - // Handle low level network errors - request.onerror = function handleError(event) { - // Browsers deliver a ProgressEvent in XHR onerror - // (message may be empty; when present, surface it) - // See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event - const msg = event && event.message ? event.message : 'Network Error'; - const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request); - // attach the underlying event for consumers who want details - err.event = event || null; - reject(err); - request = null; - }; - - // Handle timeout - request.ontimeout = function handleTimeout() { - let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded'; - const transitional = _config.transitional || transitionalDefaults; - if (_config.timeoutErrorMessage) { - timeoutErrorMessage = _config.timeoutErrorMessage; + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue } - reject(new AxiosError( - timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, - config, - request)); - - // Clean up request - request = null; - }; - - // Remove Content-Type if data is undefined - requestData === undefined && requestHeaders.setContentType(null); - - // Add headers to the request - if ('setRequestHeader' in request) { - utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { - request.setRequestHeader(key, val); - }); - } - - // Add withCredentials to request if needed - if (!utils$1.isUndefined(_config.withCredentials)) { - request.withCredentials = !!_config.withCredentials; - } - - // Add responseType to request if needed - if (responseType && responseType !== 'json') { - request.responseType = _config.responseType; } - // Handle progress if needed - if (onDownloadProgress) { - ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true)); - request.addEventListener('progress', downloadThrottled); + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } +} - // Not all browsers support upload events - if (onUploadProgress && request.upload) { - ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress)); +module.exports = HeaderParser - request.upload.addEventListener('progress', uploadThrottled); - request.upload.addEventListener('loadend', flushUpload); - } +/***/ }), - if (_config.cancelToken || _config.signal) { - // Handle cancellation - // eslint-disable-next-line func-names - onCanceled = cancel => { - if (!request) { - return; - } - reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); - request.abort(); - request = null; - }; +/***/ 1620: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _config.cancelToken && _config.cancelToken.subscribe(onCanceled); - if (_config.signal) { - _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled); - } - } +"use strict"; - const protocol = parseProtocol(_config.url); - if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); - return; - } +const inherits = (__nccwpck_require__(7261).inherits) +const ReadableStream = (__nccwpck_require__(4492).Readable) +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) - // Send the request - request.send(requestData || null); - }); -}; +PartStream.prototype._read = function (n) {} -const composeSignals = (signals, timeout) => { - const {length} = (signals = signals ? signals.filter(Boolean) : []); +module.exports = PartStream - if (timeout || length) { - let controller = new AbortController(); - let aborted; +/***/ }), - const onabort = function (reason) { - if (!aborted) { - aborted = true; - unsubscribe(); - const err = reason instanceof Error ? reason : this.reason; - controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err)); - } - }; +/***/ 1142: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - let timer = timeout && setTimeout(() => { - timer = null; - onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT)); - }, timeout); - - const unsubscribe = () => { - if (signals) { - timer && clearTimeout(timer); - timer = null; - signals.forEach(signal => { - signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort); - }); - signals = null; - } - }; +"use strict"; - signals.forEach((signal) => signal.addEventListener('abort', onabort)); - const {signal} = controller; +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = (__nccwpck_require__(5673).EventEmitter) +const inherits = (__nccwpck_require__(7261).inherits) - signal.unsubscribe = () => utils$1.asap(unsubscribe); +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } - return signal; + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') } -}; -const composeSignals$1 = composeSignals; + const needleLength = needle.length -const streamChunk = function* (chunk, chunkSize) { - let len = chunk.byteLength; + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } - if (!chunkSize || len < chunkSize) { - yield chunk; - return; + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') } - let pos = 0; - let end; + this.maxMatches = Infinity + this.matches = 0 - while (pos < len) { - end = pos + chunkSize; - yield chunk.slice(pos, end); - pos = end; - } -}; + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 -const readBytes = async function* (iterable, chunkSize) { - for await (const chunk of readStream(iterable)) { - yield* streamChunk(chunk, chunkSize); - } -}; + this._lookbehind = Buffer.alloc(needleLength) -const readStream = async function* (stream) { - if (stream[Symbol.asyncIterator]) { - yield* stream; - return; + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i } +} +inherits(SBMH, EventEmitter) - const reader = stream.getReader(); - try { - for (;;) { - const {done, value} = await reader.read(); - if (done) { - break; - } - yield value; - } - } finally { - await reader.cancel(); +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') } -}; + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} -const trackStream = (stream, chunkSize, onProgress, onFinish) => { - const iterator = readBytes(stream, chunkSize); +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] - let bytes = 0; - let done; - let _onFinish = (e) => { - if (!done) { - done = true; - onFinish && onFinish(e); - } - }; + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch - return new ReadableStream({ - async pull(controller) { - try { - const {done, value} = await iterator.next(); + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - if (done) { - _onFinish(); - controller.close(); - return; - } + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) - let len = value.byteLength; - if (onProgress) { - let loadedBytes = bytes += len; - onProgress(loadedBytes); - } - controller.enqueue(new Uint8Array(value)); - } catch (err) { - _onFinish(err); - throw err; + return (this._bufpos = pos + needleLength) } - }, - cancel(reason) { - _onFinish(reason); - return iterator.return(); + pos += this._occ[ch] } - }, { - highWaterMark: 2 - }) -}; -const DEFAULT_CHUNK_SIZE = 64 * 1024; + // No match. -const {isFunction} = utils$1; + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + } -const globalFetchAPI = (({Request, Response}) => ({ - Request, Response -}))(utils$1.global); + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } -const { - ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1 -} = utils$1.global; + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len -const test = (fn, ...args) => { - try { - return !!fn(...args); - } catch (e) { - return false + this._bufpos = len + return len + } } -}; -const factory = (env) => { - env = utils$1.merge.call({ - skipUndefined: true - }, globalFetchAPI, env); + pos += (pos >= 0) * this._bufpos - const {fetch: envFetch, Request, Response} = env; - const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function'; - const isRequestSupported = isFunction(Request); - const isResponseSupported = isFunction(Response); + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - if (!isFetchSupported) { - return false; + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength } - const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1); - - const encodeText = isFetchSupported && (typeof TextEncoder$1 === 'function' ? - ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : - async (str) => new Uint8Array(await new Request(str).arrayBuffer()) - ); - - const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => { - let duplexAccessed = false; - - const hasContentType = new Request(platform.origin, { - body: new ReadableStream$1(), - method: 'POST', - get duplex() { - duplexAccessed = true; - return 'half'; - }, - }).headers.has('Content-Type'); - - return duplexAccessed && !hasContentType; - }); - - const supportsResponseStream = isResponseSupported && isReadableStreamSupported && - test(() => utils$1.isReadableStream(new Response('').body)); - - const resolvers = { - stream: supportsResponseStream && ((res) => res.body) - }; - - isFetchSupported && ((() => { - ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => { - !resolvers[type] && (resolvers[type] = (res, config) => { - let method = res && res[type]; - - if (method) { - return method.call(res); - } - - throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config); - }); - }); - })()); + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } - const getBodyLength = async (body) => { - if (body == null) { - return 0; - } + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } - if (utils$1.isBlob(body)) { - return body.size; - } + this._bufpos = len + return len +} - if (utils$1.isSpecCompliantForm(body)) { - const _request = new Request(platform.origin, { - method: 'POST', - body, - }); - return (await _request.arrayBuffer()).byteLength; - } +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} - if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) { - return body.byteLength; - } +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} - if (utils$1.isURLSearchParams(body)) { - body = body + ''; - } +module.exports = SBMH - if (utils$1.isString(body)) { - return (await encodeText(body)).byteLength; - } - }; - const resolveBodyLength = async (headers, body) => { - const length = utils$1.toFiniteNumber(headers.getContentLength()); +/***/ }), - return length == null ? getBodyLength(body) : length; - }; +/***/ 727: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return async (config) => { - let { - url, - method, - data, - signal, - cancelToken, - timeout, - onDownloadProgress, - onUploadProgress, - responseType, - headers, - withCredentials = 'same-origin', - fetchOptions - } = resolveConfig(config); +"use strict"; - let _fetch = envFetch || fetch; - responseType = responseType ? (responseType + '').toLowerCase() : 'text'; +const WritableStream = (__nccwpck_require__(4492).Writable) +const { inherits } = __nccwpck_require__(7261) +const Dicer = __nccwpck_require__(2960) - let composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout); +const MultipartParser = __nccwpck_require__(2183) +const UrlencodedParser = __nccwpck_require__(8306) +const parseParams = __nccwpck_require__(1854) - let request = null; +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } - const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => { - composedSignal.unsubscribe(); - }); + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } - let requestContentLength; + const { + headers, + ...streamOptions + } = opts - try { - if ( - onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' && - (requestContentLength = await resolveBodyLength(headers, data)) !== 0 - ) { - let _request = new Request(url, { - method: 'POST', - body: data, - duplex: "half" - }); + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) - let contentTypeHeader; + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) - if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) { - headers.setContentType(contentTypeHeader); - } +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return + } + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} - if (_request.body) { - const [onProgress, flush] = progressEventDecorator( - requestContentLength, - progressEventReducer(asyncDecorator(onUploadProgress)) - ); +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) - data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush); - } - } + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } - if (!utils$1.isString(withCredentials)) { - withCredentials = withCredentials ? 'include' : 'omit'; - } + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} - // Cloudflare Workers throws when credentials are defined - // see https://github.com/cloudflare/workerd/issues/902 - const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype; - - const resolvedOptions = { - ...fetchOptions, - signal: composedSignal, - method: method.toUpperCase(), - headers: headers.normalize().toJSON(), - body: data, - duplex: "half", - credentials: isCredentialsSupported ? withCredentials : undefined - }; +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} - request = isRequestSupported && new Request(url, resolvedOptions); +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy - let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions)); +module.exports.Dicer = Dicer - const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response'); - if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) { - const options = {}; +/***/ }), - ['status', 'statusText', 'headers'].forEach(prop => { - options[prop] = response[prop]; - }); +/***/ 2183: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length')); +"use strict"; - const [onProgress, flush] = onDownloadProgress && progressEventDecorator( - responseContentLength, - progressEventReducer(asyncDecorator(onDownloadProgress), true) - ) || []; - response = new Response( - trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => { - flush && flush(); - unsubscribe && unsubscribe(); - }), - options - ); - } +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams - responseType = responseType || 'text'; +const { Readable } = __nccwpck_require__(4492) +const { inherits } = __nccwpck_require__(7261) - let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config); +const Dicer = __nccwpck_require__(2960) - !isStreamResponse && unsubscribe && unsubscribe(); +const parseParams = __nccwpck_require__(1854) +const decodeText = __nccwpck_require__(4619) +const basename = __nccwpck_require__(8647) +const getLimit = __nccwpck_require__(1467) - return await new Promise((resolve, reject) => { - settle(resolve, reject, { - data: responseData, - headers: AxiosHeaders$1.from(response.headers), - status: response.status, - statusText: response.statusText, - config, - request - }); - }) - } catch (err) { - unsubscribe && unsubscribe(); +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i - if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) { - throw Object.assign( - new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), - { - cause: err.cause || err - } - ) - } +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } - throw AxiosError.from(err, err && err.code, config, request); + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break } } -}; -const seedCache = new Map(); + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } -const getFetch = (config) => { - let env = (config && config.env) || {}; - const {fetch, Request, Response} = env; - const seeds = [ - Request, Response, fetch - ]; + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - let len = seeds.length, i = len, - seed, target, map = seedCache; + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) - while (i--) { - seed = seeds[i]; - target = map.get(seed); + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false - target === undefined && map.set(seed, target = (i ? new Map() : factory(env))); + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy - map = target; + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark } - return target; -}; - -getFetch(); - -/** - * Known adapters mapping. - * Provides environment-specific adapters for Axios: - * - `http` for Node.js - * - `xhr` for browsers - * - `fetch` for fetch API-based requests - * - * @type {Object} - */ -const knownAdapters = { - http: httpAdapter, - xhr: xhrAdapter, - fetch: { - get: getFetch, - } -}; + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } -// Assign adapter names for easier debugging and identification -utils$1.forEach(knownAdapters, (fn, value) => { - if (fn) { - try { - Object.defineProperty(fn, 'name', { value }); - } catch (e) { - // eslint-disable-next-line no-empty + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') } - Object.defineProperty(fn, 'adapterName', { value }); - } -}); -/** - * Render a rejection reason string for unknown or unsupported adapters - * - * @param {string} reason - * @returns {string} - */ -const renderReason = (reason) => `- ${reason}`; + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 -/** - * Check if the adapter is resolved (function, null, or false) - * - * @param {Function|null|false} adapter - * @returns {boolean} - */ -const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false; + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } -/** - * Get the first suitable adapter from the provided list. - * Tries each adapter in order until a supported one is found. - * Throws an AxiosError if no adapter is suitable. - * - * @param {Array|string|Function} adapters - Adapter(s) by name or function. - * @param {Object} config - Axios request configuration - * @throws {AxiosError} If no suitable adapter is available - * @returns {Function} The resolved adapter function - */ -function getAdapter(adapters, config) { - adapters = utils$1.isArray(adapters) ? adapters : [adapters]; + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } - const { length } = adapters; - let nameOrAdapter; - let adapter; + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } - const rejectedReasons = {}; + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - for (let i = 0; i < length; i++) { - nameOrAdapter = adapters[i]; - let id; + let onData, + onEnd - adapter = nameOrAdapter; + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } - if (!isResolvedHandle(nameOrAdapter)) { - adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; + ++nfiles - if (adapter === undefined) { - throw new AxiosError(`Unknown adapter '${id}'`); - } - } + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } - if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) { - break; - } + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) - rejectedReasons[id || '#' + i] = adapter; - } + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } - if (!adapter) { - const reasons = Object.entries(rejectedReasons) - .map(([id, state]) => `adapter ${id} ` + - (state === false ? 'is not supported by the environment' : 'is not available in the build') - ); + file.bytesRead = nsize + } - let s = length ? - (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : - 'as no adapter specified'; + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } - throw new AxiosError( - `There is no suitable adapter to dispatch the request ` + s, - 'ERR_NOT_SUPPORT' - ); - } + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part - return adapter; -} + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } -/** - * Exports Axios adapters and utility to resolve an adapter - */ -const adapters = { - /** - * Resolve an adapter from a list of adapter names or functions. - * @type {Function} - */ - getAdapter, + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } - /** - * Exposes all known adapters - * @type {Object} - */ - adapters: knownAdapters -}; + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false -/** - * Throws a `CanceledError` if cancellation has been requested. - * - * @param {Object} config The config that is to be used for the request - * - * @returns {void} - */ -function throwIfCancellationRequested(config) { - if (config.cancelToken) { - config.cancelToken.throwIfRequested(); - } + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} - if (config.signal && config.signal.aborted) { - throw new CanceledError(null, config); +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb } } -/** - * Dispatch a request to the server using the configured adapter. - * - * @param {object} config The config that is to be used for the request - * - * @returns {Promise} The Promise to be fulfilled - */ -function dispatchRequest(config) { - throwIfCancellationRequested(config); - - config.headers = AxiosHeaders$1.from(config.headers); - - // Transform request data - config.data = transformData.call( - config, - config.transformRequest - ); +Multipart.prototype.end = function () { + const self = this - if (['post', 'put', 'patch'].indexOf(config.method) !== -1) { - config.headers.setContentType('application/x-www-form-urlencoded', false); + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) } +} + +function skipPart (part) { + part.resume() +} - const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter, config); +function FileStream (opts) { + Readable.call(this, opts) - return adapter(config).then(function onAdapterResolution(response) { - throwIfCancellationRequested(config); + this.bytesRead = 0 - // Transform response data - response.data = transformData.call( - config, - config.transformResponse, - response - ); + this.truncated = false +} - response.headers = AxiosHeaders$1.from(response.headers); +inherits(FileStream, Readable) - return response; - }, function onAdapterRejection(reason) { - if (!isCancel(reason)) { - throwIfCancellationRequested(config); - - // Transform response data - if (reason && reason.response) { - reason.response.data = transformData.call( - config, - config.transformResponse, - reason.response - ); - reason.response.headers = AxiosHeaders$1.from(reason.response.headers); - } - } +FileStream.prototype._read = function (n) {} - return Promise.reject(reason); - }); -} +module.exports = Multipart -const validators$1 = {}; -// eslint-disable-next-line func-names -['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => { - validators$1[type] = function validator(thing) { - return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; - }; -}); +/***/ }), -const deprecatedWarnings = {}; +/***/ 8306: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Transitional option validator - * - * @param {function|boolean?} validator - set to false if the transitional option has been removed - * @param {string?} version - deprecated version / removed since version - * @param {string?} message - some message with additional info - * - * @returns {function} - */ -validators$1.transitional = function transitional(validator, version, message) { - function formatMessage(opt, desc) { - return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); - } +"use strict"; - // eslint-disable-next-line func-names - return (value, opt, opts) => { - if (validator === false) { - throw new AxiosError( - formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError.ERR_DEPRECATED - ); - } - if (version && !deprecatedWarnings[opt]) { - deprecatedWarnings[opt] = true; - // eslint-disable-next-line no-console - console.warn( - formatMessage( - opt, - ' has been deprecated since v' + version + ' and will be removed in the near future' - ) - ); - } +const Decoder = __nccwpck_require__(7100) +const decodeText = __nccwpck_require__(4619) +const getLimit = __nccwpck_require__(1467) - return validator ? validator(value, opt, opts) : true; - }; -}; +const RE_CHARSET = /^charset$/i -validators$1.spelling = function spelling(correctSpelling) { - return (value, opt) => { - // eslint-disable-next-line no-console - console.warn(`${opt} is likely a misspelling of ${correctSpelling}`); - return true; - } -}; +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy -/** - * Assert object's properties type - * - * @param {object} options - * @param {object} schema - * @param {boolean?} allowUnknown - * - * @returns {object} - */ + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) -function assertOptions(options, schema, allowUnknown) { - if (typeof options !== 'object') { - throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); - } - const keys = Object.keys(options); - let i = keys.length; - while (i-- > 0) { - const opt = keys[i]; - const validator = schema[opt]; - if (validator) { - const value = options[opt]; - const result = value === undefined || validator(value, opt, options); - if (result !== true) { - throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); - } - continue; - } - if (allowUnknown !== true) { - throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break } } -} -const validator = { - assertOptions, - validators: validators$1 -}; + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } -const validators = validator.validators; + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false +} -/** - * Create a new instance of Axios - * - * @param {Object} instanceConfig The default config for the instance - * - * @return {Axios} A new instance of Axios - */ -class Axios { - constructor(instanceConfig) { - this.defaults = instanceConfig || {}; - this.interceptors = { - request: new InterceptorManager$1(), - response: new InterceptorManager$1() - }; +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() } - /** - * Dispatch a request - * - * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) - * @param {?Object} config - * - * @returns {Promise} The Promise to be fulfilled - */ - async request(configOrUrl, config) { - try { - return await this._request(configOrUrl, config); - } catch (err) { - if (err instanceof Error) { - let dummy = {}; - - Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error()); + let idxeq; let idxamp; let i; let p = 0; const len = data.length - // slice off the Error: ... line - const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : ''; - try { - if (!err.stack) { - err.stack = stack; - // match without the 2 top stack lines - } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) { - err.stack += '\n' + stack; - } - } catch (e) { - // ignore the case where "stack" is an un-writable property + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } } - throw err; - } - } + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' - _request(configOrUrl, config) { - /*eslint no-param-reassign:0*/ - // Allow for axios('example/url'[, config]) a la fetch API - if (typeof configOrUrl === 'string') { - config = config || {}; - config.url = configOrUrl; - } else { - config = configOrUrl || {}; - } + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() - config = mergeConfig(this.defaults, config); + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } - const {transitional, paramsSerializer, headers} = config; + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() - if (transitional !== undefined) { - validator.assertOptions(transitional, { - silentJSONParsing: validators.transitional(validators.boolean), - forcedJSONParsing: validators.transitional(validators.boolean), - clarifyTimeoutError: validators.transitional(validators.boolean) - }, false); - } + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } - if (paramsSerializer != null) { - if (utils$1.isFunction(paramsSerializer)) { - config.paramsSerializer = { - serialize: paramsSerializer - }; + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } } else { - validator.assertOptions(paramsSerializer, { - encode: validators.function, - serialize: validators.function - }, true); + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len } - } - - // Set config.allowAbsoluteUrls - if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) { - config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls; } else { - config.allowAbsoluteUrls = true; - } - - validator.assertOptions(config, { - baseUrl: validators.spelling('baseURL'), - withXsrfToken: validators.spelling('withXSRFToken') - }, true); - - // Set config.method - config.method = (config.method || this.defaults.method || 'get').toLowerCase(); - - // Flatten headers - let contextHeaders = headers && utils$1.merge( - headers.common, - headers[config.method] - ); - - headers && utils$1.forEach( - ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], - (method) => { - delete headers[method]; + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } } - ); - config.headers = AxiosHeaders$1.concat(contextHeaders, headers); + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() - // filter out skipped interceptors - const requestInterceptorChain = []; - let synchronousRequestInterceptors = true; - this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { - if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { - return; + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len } + } + } + cb() +} - synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } - requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); - }); + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} - const responseInterceptorChain = []; - this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { - responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); - }); +module.exports = UrlEncoded - let promise; - let i = 0; - let len; - if (!synchronousRequestInterceptors) { - const chain = [dispatchRequest.bind(this), undefined]; - chain.unshift(...requestInterceptorChain); - chain.push(...responseInterceptorChain); - len = chain.length; +/***/ }), - promise = Promise.resolve(config); +/***/ 7100: +/***/ ((module) => { - while (i < len) { - promise = promise.then(chain[i++], chain[i++]); - } +"use strict"; - return promise; - } - len = requestInterceptorChain.length; +const RE_PLUS = /\+/g - let newConfig = config; +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] - while (i < len) { - const onFulfilled = requestInterceptorChain[i++]; - const onRejected = requestInterceptorChain[i++]; - try { - newConfig = onFulfilled(newConfig); - } catch (error) { - onRejected.call(this, error); - break; +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p } - - try { - promise = dispatchRequest.call(this, newConfig); - } catch (error) { - return Promise.reject(error); - } - - i = 0; - len = responseInterceptorChain.length; - - while (i < len) { - promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); - } - - return promise; - } - - getUri(config) { - config = mergeConfig(this.defaults, config); - const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls); - return buildURL(fullPath, config.params, config.paramsSerializer); } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined } -// Provide aliases for supported request methods -utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { - /*eslint func-names:0*/ - Axios.prototype[method] = function(url, config) { - return this.request(mergeConfig(config || {}, { - method, - url, - data: (config || {}).data - })); - }; -}); +module.exports = Decoder -utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - /*eslint func-names:0*/ - function generateHTTPMethod(isForm) { - return function httpMethod(url, data, config) { - return this.request(mergeConfig(config || {}, { - method, - headers: isForm ? { - 'Content-Type': 'multipart/form-data' - } : {}, - url, - data - })); - }; - } +/***/ }), - Axios.prototype[method] = generateHTTPMethod(); +/***/ 8647: +/***/ ((module) => { - Axios.prototype[method + 'Form'] = generateHTTPMethod(true); -}); +"use strict"; -const Axios$1 = Axios; -/** - * A `CancelToken` is an object that can be used to request cancellation of an operation. - * - * @param {Function} executor The executor function. - * - * @returns {CancelToken} - */ -class CancelToken { - constructor(executor) { - if (typeof executor !== 'function') { - throw new TypeError('executor must be a function.'); +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) } + } + return (path === '..' || path === '.' ? '' : path) +} - let resolvePromise; - - this.promise = new Promise(function promiseExecutor(resolve) { - resolvePromise = resolve; - }); - - const token = this; - - // eslint-disable-next-line func-names - this.promise.then(cancel => { - if (!token._listeners) return; - - let i = token._listeners.length; - while (i-- > 0) { - token._listeners[i](cancel); - } - token._listeners = null; - }); +/***/ }), - // eslint-disable-next-line func-names - this.promise.then = onfulfilled => { - let _resolve; - // eslint-disable-next-line func-names - const promise = new Promise(resolve => { - token.subscribe(resolve); - _resolve = resolve; - }).then(onfulfilled); - - promise.cancel = function reject() { - token.unsubscribe(_resolve); - }; +/***/ 4619: +/***/ (function(module) { - return promise; - }; +"use strict"; - executor(function cancel(message, config, request) { - if (token.reason) { - // Cancellation has already been requested - return; - } - token.reason = new CanceledError(message, config, request); - resolvePromise(token.reason); - }); - } +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) - /** - * Throws a `CanceledError` if cancellation has been requested. - */ - throwIfRequested() { - if (this.reason) { - throw this.reason; +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) } } +} - /** - * Subscribe to the cancel signal - */ - - subscribe(listener) { - if (this.reason) { - listener(this.reason); - return; +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - - if (this._listeners) { - this._listeners.push(listener); - } else { - this._listeners = [listener]; + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } - } - - /** - * Unsubscribe from the cancel signal - */ + return data.utf8Slice(0, data.length) + }, - unsubscribe(listener) { - if (!this._listeners) { - return; + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - const index = this._listeners.indexOf(listener); - if (index !== -1) { - this._listeners.splice(index, 1); + if (typeof data === 'string') { + return data } - } - - toAbortSignal() { - const controller = new AbortController(); + return data.latin1Slice(0, data.length) + }, - const abort = (err) => { - controller.abort(err); - }; + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, - this.subscribe(abort); + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, - controller.signal.unsubscribe = () => this.unsubscribe(abort); + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } - return controller.signal; + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() } +} - /** - * Returns an object that contains a new `CancelToken` and a function that, when called, - * cancels the `CancelToken`. - */ - static source() { - let cancel; - const token = new CancelToken(function executor(c) { - cancel = c; - }); - return { - token, - cancel - }; +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) } + return text } -const CancelToken$1 = CancelToken; - -/** - * Syntactic sugar for invoking a function and expanding an array for arguments. - * - * Common use case would be to use `Function.prototype.apply`. - * - * ```js - * function f(x, y, z) {} - * var args = [1, 2, 3]; - * f.apply(null, args); - * ``` - * - * With `spread` this example can be re-written. - * - * ```js - * spread(function(x, y, z) {})([1, 2, 3]); - * ``` - * - * @param {Function} callback - * - * @returns {Function} - */ -function spread(callback) { - return function wrap(arr) { - return callback.apply(null, arr); - }; -} +module.exports = decodeText -/** - * Determines whether the payload is an error thrown by Axios - * - * @param {*} payload The value to test - * - * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false - */ -function isAxiosError(payload) { - return utils$1.isObject(payload) && (payload.isAxiosError === true); -} - -const HttpStatusCode = { - Continue: 100, - SwitchingProtocols: 101, - Processing: 102, - EarlyHints: 103, - Ok: 200, - Created: 201, - Accepted: 202, - NonAuthoritativeInformation: 203, - NoContent: 204, - ResetContent: 205, - PartialContent: 206, - MultiStatus: 207, - AlreadyReported: 208, - ImUsed: 226, - MultipleChoices: 300, - MovedPermanently: 301, - Found: 302, - SeeOther: 303, - NotModified: 304, - UseProxy: 305, - Unused: 306, - TemporaryRedirect: 307, - PermanentRedirect: 308, - BadRequest: 400, - Unauthorized: 401, - PaymentRequired: 402, - Forbidden: 403, - NotFound: 404, - MethodNotAllowed: 405, - NotAcceptable: 406, - ProxyAuthenticationRequired: 407, - RequestTimeout: 408, - Conflict: 409, - Gone: 410, - LengthRequired: 411, - PreconditionFailed: 412, - PayloadTooLarge: 413, - UriTooLong: 414, - UnsupportedMediaType: 415, - RangeNotSatisfiable: 416, - ExpectationFailed: 417, - ImATeapot: 418, - MisdirectedRequest: 421, - UnprocessableEntity: 422, - Locked: 423, - FailedDependency: 424, - TooEarly: 425, - UpgradeRequired: 426, - PreconditionRequired: 428, - TooManyRequests: 429, - RequestHeaderFieldsTooLarge: 431, - UnavailableForLegalReasons: 451, - InternalServerError: 500, - NotImplemented: 501, - BadGateway: 502, - ServiceUnavailable: 503, - GatewayTimeout: 504, - HttpVersionNotSupported: 505, - VariantAlsoNegotiates: 506, - InsufficientStorage: 507, - LoopDetected: 508, - NotExtended: 510, - NetworkAuthenticationRequired: 511, - WebServerIsDown: 521, - ConnectionTimedOut: 522, - OriginIsUnreachable: 523, - TimeoutOccurred: 524, - SslHandshakeFailed: 525, - InvalidSslCertificate: 526, -}; -Object.entries(HttpStatusCode).forEach(([key, value]) => { - HttpStatusCode[value] = key; -}); +/***/ }), -const HttpStatusCode$1 = HttpStatusCode; +/***/ 1467: +/***/ ((module) => { -/** - * Create an instance of Axios - * - * @param {Object} defaultConfig The default config for the instance - * - * @returns {Axios} A new instance of Axios - */ -function createInstance(defaultConfig) { - const context = new Axios$1(defaultConfig); - const instance = bind(Axios$1.prototype.request, context); +"use strict"; - // Copy axios.prototype to instance - utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); - // Copy context to instance - utils$1.extend(instance, context, null, {allOwnKeys: true}); +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } - // Factory for creating new instances - instance.create = function create(instanceConfig) { - return createInstance(mergeConfig(defaultConfig, instanceConfig)); - }; + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - return instance; + return limits[name] } -// Create the default instance to be exported -const axios = createInstance(defaults$1); -// Expose Axios class to allow class inheritance -axios.Axios = Axios$1; +/***/ }), -// Expose Cancel & CancelToken -axios.CanceledError = CanceledError; -axios.CancelToken = CancelToken$1; -axios.isCancel = isCancel; -axios.VERSION = VERSION; -axios.toFormData = toFormData; +/***/ 1854: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Expose AxiosError class -axios.AxiosError = AxiosError; +"use strict"; +/* eslint-disable object-property-newline */ -// alias for CanceledError for backward compatibility -axios.Cancel = axios.CanceledError; -// Expose all/spread -axios.all = function all(promises) { - return Promise.all(promises); -}; +const decodeText = __nccwpck_require__(4619) -axios.spread = spread; +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g -// Expose isAxiosError -axios.isAxiosError = isAxiosError; +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} -// Expose mergeConfig -axios.mergeConfig = mergeConfig; +function encodedReplacer (match) { + return EncodedLookup[match] +} -axios.AxiosHeaders = AxiosHeaders$1; +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 -axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length -axios.getAdapter = adapters.getAdapter; + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } -axios.HttpStatusCode = HttpStatusCode$1; + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } -axios.default = axios; + return res +} -module.exports = axios; -//# sourceMappingURL=axios.cjs.map +module.exports = parseParams /***/ }), -/***/ 46192: +/***/ 6192: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { "use strict"; @@ -149470,7 +69408,7 @@ __nccwpck_require__.d(__webpack_exports__, { }); // EXTERNAL MODULE: external "node:process" -var external_node_process_ = __nccwpck_require__(97742); +var external_node_process_ = __nccwpck_require__(7742); ;// CONCATENATED MODULE: ./node_modules/ansi-regex/index.js function ansiRegex({onlyFirst = false} = {}) { // Valid string terminator sequences are BEL, ESC\, and 0x9c @@ -149941,7 +69879,7 @@ function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) { // EXTERNAL MODULE: ./node_modules/emoji-regex/index.js -var emoji_regex = __nccwpck_require__(18212); +var emoji_regex = __nccwpck_require__(8212); ;// CONCATENATED MODULE: ./node_modules/string-width/index.js @@ -150027,7 +69965,7 @@ function stringWidth(string, options = {}) { } // EXTERNAL MODULE: ./node_modules/chalk/source/index.js + 5 modules -var source = __nccwpck_require__(77037); +var source = __nccwpck_require__(7037); ;// CONCATENATED MODULE: ./node_modules/widest-line/index.js @@ -150042,7 +69980,7 @@ function widestLine(string) { } // EXTERNAL MODULE: ./node_modules/cli-boxes/index.js -var cli_boxes = __nccwpck_require__(83733); +var cli_boxes = __nccwpck_require__(3733); ;// CONCATENATED MODULE: ./node_modules/camelcase/index.js const UPPERCASE = /[\p{Lu}]/u; const LOWERCASE = /[\p{Ll}]/u; @@ -150156,7 +70094,7 @@ function camelCase(input, options) { } // EXTERNAL MODULE: ./node_modules/ansi-align/index.js -var ansi_align = __nccwpck_require__(22225); +var ansi_align = __nccwpck_require__(2225); ;// CONCATENATED MODULE: ./node_modules/ansi-styles/index.js const ANSI_BACKGROUND_OFFSET = 10; @@ -150987,7 +70925,7 @@ function boxen(text, options) { /***/ }), -/***/ 77037: +/***/ 7037: /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { "use strict"; @@ -151237,7 +71175,7 @@ const ansiStyles = assembleStyles(); /* harmony default export */ const ansi_styles = (ansiStyles); // EXTERNAL MODULE: external "node:process" -var external_node_process_ = __nccwpck_require__(97742); +var external_node_process_ = __nccwpck_require__(7742); ;// CONCATENATED MODULE: external "node:os" const external_node_os_namespaceObject = require("node:os"); ;// CONCATENATED MODULE: external "node:tty" @@ -151682,76 +71620,12 @@ const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); /***/ }), -/***/ 56569: -/***/ ((module) => { - -"use strict"; -module.exports = {"i8":"1.14.0"}; - -/***/ }), - -/***/ 70094: +/***/ 94: /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"single":{"topLeft":"ā”Œ","top":"─","topRight":"┐","right":"│","bottomRight":"ā”˜","bottom":"─","bottomLeft":"ā””","left":"│"},"double":{"topLeft":"ā•”","top":"═","topRight":"ā•—","right":"ā•‘","bottomRight":"ā•","bottom":"═","bottomLeft":"ā•š","left":"ā•‘"},"round":{"topLeft":"ā•­","top":"─","topRight":"ā•®","right":"│","bottomRight":"╯","bottom":"─","bottomLeft":"ā•°","left":"│"},"bold":{"topLeft":"ā”","top":"━","topRight":"┓","right":"ā”ƒ","bottomRight":"ā”›","bottom":"━","bottomLeft":"ā”—","left":"ā”ƒ"},"singleDouble":{"topLeft":"ā•“","top":"─","topRight":"ā•–","right":"ā•‘","bottomRight":"ā•œ","bottom":"─","bottomLeft":"ā•™","left":"ā•‘"},"doubleSingle":{"topLeft":"ā•’","top":"═","topRight":"ā••","right":"│","bottomRight":"ā•›","bottom":"═","bottomLeft":"ā•˜","left":"│"},"classic":{"topLeft":"+","top":"-","topRight":"+","right":"|","bottomRight":"+","bottom":"-","bottomLeft":"+","left":"|"},"arrow":{"topLeft":"ā†˜","top":"↓","topRight":"↙","right":"←","bottomRight":"↖","bottom":"↑","bottomLeft":"↗","left":"→"}}'); -/***/ }), - -/***/ 53765: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"application/1d-interleaved-parityfec":{"source":"iana"},"application/3gpdash-qoe-report+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/3gpp-ims+xml":{"source":"iana","compressible":true},"application/3gpphal+json":{"source":"iana","compressible":true},"application/3gpphalforms+json":{"source":"iana","compressible":true},"application/a2l":{"source":"iana"},"application/ace+cbor":{"source":"iana"},"application/activemessage":{"source":"iana"},"application/activity+json":{"source":"iana","compressible":true},"application/alto-costmap+json":{"source":"iana","compressible":true},"application/alto-costmapfilter+json":{"source":"iana","compressible":true},"application/alto-directory+json":{"source":"iana","compressible":true},"application/alto-endpointcost+json":{"source":"iana","compressible":true},"application/alto-endpointcostparams+json":{"source":"iana","compressible":true},"application/alto-endpointprop+json":{"source":"iana","compressible":true},"application/alto-endpointpropparams+json":{"source":"iana","compressible":true},"application/alto-error+json":{"source":"iana","compressible":true},"application/alto-networkmap+json":{"source":"iana","compressible":true},"application/alto-networkmapfilter+json":{"source":"iana","compressible":true},"application/alto-updatestreamcontrol+json":{"source":"iana","compressible":true},"application/alto-updatestreamparams+json":{"source":"iana","compressible":true},"application/aml":{"source":"iana"},"application/andrew-inset":{"source":"iana","extensions":["ez"]},"application/applefile":{"source":"iana"},"application/applixware":{"source":"apache","extensions":["aw"]},"application/at+jwt":{"source":"iana"},"application/atf":{"source":"iana"},"application/atfx":{"source":"iana"},"application/atom+xml":{"source":"iana","compressible":true,"extensions":["atom"]},"application/atomcat+xml":{"source":"iana","compressible":true,"extensions":["atomcat"]},"application/atomdeleted+xml":{"source":"iana","compressible":true,"extensions":["atomdeleted"]},"application/atomicmail":{"source":"iana"},"application/atomsvc+xml":{"source":"iana","compressible":true,"extensions":["atomsvc"]},"application/atsc-dwd+xml":{"source":"iana","compressible":true,"extensions":["dwd"]},"application/atsc-dynamic-event-message":{"source":"iana"},"application/atsc-held+xml":{"source":"iana","compressible":true,"extensions":["held"]},"application/atsc-rdt+json":{"source":"iana","compressible":true},"application/atsc-rsat+xml":{"source":"iana","compressible":true,"extensions":["rsat"]},"application/atxml":{"source":"iana"},"application/auth-policy+xml":{"source":"iana","compressible":true},"application/bacnet-xdd+zip":{"source":"iana","compressible":false},"application/batch-smtp":{"source":"iana"},"application/bdoc":{"compressible":false,"extensions":["bdoc"]},"application/beep+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/calendar+json":{"source":"iana","compressible":true},"application/calendar+xml":{"source":"iana","compressible":true,"extensions":["xcs"]},"application/call-completion":{"source":"iana"},"application/cals-1840":{"source":"iana"},"application/captive+json":{"source":"iana","compressible":true},"application/cbor":{"source":"iana"},"application/cbor-seq":{"source":"iana"},"application/cccex":{"source":"iana"},"application/ccmp+xml":{"source":"iana","compressible":true},"application/ccxml+xml":{"source":"iana","compressible":true,"extensions":["ccxml"]},"application/cdfx+xml":{"source":"iana","compressible":true,"extensions":["cdfx"]},"application/cdmi-capability":{"source":"iana","extensions":["cdmia"]},"application/cdmi-container":{"source":"iana","extensions":["cdmic"]},"application/cdmi-domain":{"source":"iana","extensions":["cdmid"]},"application/cdmi-object":{"source":"iana","extensions":["cdmio"]},"application/cdmi-queue":{"source":"iana","extensions":["cdmiq"]},"application/cdni":{"source":"iana"},"application/cea":{"source":"iana"},"application/cea-2018+xml":{"source":"iana","compressible":true},"application/cellml+xml":{"source":"iana","compressible":true},"application/cfw":{"source":"iana"},"application/city+json":{"source":"iana","compressible":true},"application/clr":{"source":"iana"},"application/clue+xml":{"source":"iana","compressible":true},"application/clue_info+xml":{"source":"iana","compressible":true},"application/cms":{"source":"iana"},"application/cnrp+xml":{"source":"iana","compressible":true},"application/coap-group+json":{"source":"iana","compressible":true},"application/coap-payload":{"source":"iana"},"application/commonground":{"source":"iana"},"application/conference-info+xml":{"source":"iana","compressible":true},"application/cose":{"source":"iana"},"application/cose-key":{"source":"iana"},"application/cose-key-set":{"source":"iana"},"application/cpl+xml":{"source":"iana","compressible":true,"extensions":["cpl"]},"application/csrattrs":{"source":"iana"},"application/csta+xml":{"source":"iana","compressible":true},"application/cstadata+xml":{"source":"iana","compressible":true},"application/csvm+json":{"source":"iana","compressible":true},"application/cu-seeme":{"source":"apache","extensions":["cu"]},"application/cwt":{"source":"iana"},"application/cybercash":{"source":"iana"},"application/dart":{"compressible":true},"application/dash+xml":{"source":"iana","compressible":true,"extensions":["mpd"]},"application/dash-patch+xml":{"source":"iana","compressible":true,"extensions":["mpp"]},"application/dashdelta":{"source":"iana"},"application/davmount+xml":{"source":"iana","compressible":true,"extensions":["davmount"]},"application/dca-rft":{"source":"iana"},"application/dcd":{"source":"iana"},"application/dec-dx":{"source":"iana"},"application/dialog-info+xml":{"source":"iana","compressible":true},"application/dicom":{"source":"iana"},"application/dicom+json":{"source":"iana","compressible":true},"application/dicom+xml":{"source":"iana","compressible":true},"application/dii":{"source":"iana"},"application/dit":{"source":"iana"},"application/dns":{"source":"iana"},"application/dns+json":{"source":"iana","compressible":true},"application/dns-message":{"source":"iana"},"application/docbook+xml":{"source":"apache","compressible":true,"extensions":["dbk"]},"application/dots+cbor":{"source":"iana"},"application/dskpp+xml":{"source":"iana","compressible":true},"application/dssc+der":{"source":"iana","extensions":["dssc"]},"application/dssc+xml":{"source":"iana","compressible":true,"extensions":["xdssc"]},"application/dvcs":{"source":"iana"},"application/ecmascript":{"source":"iana","compressible":true,"extensions":["es","ecma"]},"application/edi-consent":{"source":"iana"},"application/edi-x12":{"source":"iana","compressible":false},"application/edifact":{"source":"iana","compressible":false},"application/efi":{"source":"iana"},"application/elm+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/elm+xml":{"source":"iana","compressible":true},"application/emergencycalldata.cap+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/emergencycalldata.comment+xml":{"source":"iana","compressible":true},"application/emergencycalldata.control+xml":{"source":"iana","compressible":true},"application/emergencycalldata.deviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.ecall.msd":{"source":"iana"},"application/emergencycalldata.providerinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.serviceinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.subscriberinfo+xml":{"source":"iana","compressible":true},"application/emergencycalldata.veds+xml":{"source":"iana","compressible":true},"application/emma+xml":{"source":"iana","compressible":true,"extensions":["emma"]},"application/emotionml+xml":{"source":"iana","compressible":true,"extensions":["emotionml"]},"application/encaprtp":{"source":"iana"},"application/epp+xml":{"source":"iana","compressible":true},"application/epub+zip":{"source":"iana","compressible":false,"extensions":["epub"]},"application/eshop":{"source":"iana"},"application/exi":{"source":"iana","extensions":["exi"]},"application/expect-ct-report+json":{"source":"iana","compressible":true},"application/express":{"source":"iana","extensions":["exp"]},"application/fastinfoset":{"source":"iana"},"application/fastsoap":{"source":"iana"},"application/fdt+xml":{"source":"iana","compressible":true,"extensions":["fdt"]},"application/fhir+json":{"source":"iana","charset":"UTF-8","compressible":true},"application/fhir+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/fido.trusted-apps+json":{"compressible":true},"application/fits":{"source":"iana"},"application/flexfec":{"source":"iana"},"application/font-sfnt":{"source":"iana"},"application/font-tdpfr":{"source":"iana","extensions":["pfr"]},"application/font-woff":{"source":"iana","compressible":false},"application/framework-attributes+xml":{"source":"iana","compressible":true},"application/geo+json":{"source":"iana","compressible":true,"extensions":["geojson"]},"application/geo+json-seq":{"source":"iana"},"application/geopackage+sqlite3":{"source":"iana"},"application/geoxacml+xml":{"source":"iana","compressible":true},"application/gltf-buffer":{"source":"iana"},"application/gml+xml":{"source":"iana","compressible":true,"extensions":["gml"]},"application/gpx+xml":{"source":"apache","compressible":true,"extensions":["gpx"]},"application/gxf":{"source":"apache","extensions":["gxf"]},"application/gzip":{"source":"iana","compressible":false,"extensions":["gz"]},"application/h224":{"source":"iana"},"application/held+xml":{"source":"iana","compressible":true},"application/hjson":{"extensions":["hjson"]},"application/http":{"source":"iana"},"application/hyperstudio":{"source":"iana","extensions":["stk"]},"application/ibe-key-request+xml":{"source":"iana","compressible":true},"application/ibe-pkg-reply+xml":{"source":"iana","compressible":true},"application/ibe-pp-data":{"source":"iana"},"application/iges":{"source":"iana"},"application/im-iscomposing+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/index":{"source":"iana"},"application/index.cmd":{"source":"iana"},"application/index.obj":{"source":"iana"},"application/index.response":{"source":"iana"},"application/index.vnd":{"source":"iana"},"application/inkml+xml":{"source":"iana","compressible":true,"extensions":["ink","inkml"]},"application/iotp":{"source":"iana"},"application/ipfix":{"source":"iana","extensions":["ipfix"]},"application/ipp":{"source":"iana"},"application/isup":{"source":"iana"},"application/its+xml":{"source":"iana","compressible":true,"extensions":["its"]},"application/java-archive":{"source":"apache","compressible":false,"extensions":["jar","war","ear"]},"application/java-serialized-object":{"source":"apache","compressible":false,"extensions":["ser"]},"application/java-vm":{"source":"apache","compressible":false,"extensions":["class"]},"application/javascript":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["js","mjs"]},"application/jf2feed+json":{"source":"iana","compressible":true},"application/jose":{"source":"iana"},"application/jose+json":{"source":"iana","compressible":true},"application/jrd+json":{"source":"iana","compressible":true},"application/jscalendar+json":{"source":"iana","compressible":true},"application/json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["json","map"]},"application/json-patch+json":{"source":"iana","compressible":true},"application/json-seq":{"source":"iana"},"application/json5":{"extensions":["json5"]},"application/jsonml+json":{"source":"apache","compressible":true,"extensions":["jsonml"]},"application/jwk+json":{"source":"iana","compressible":true},"application/jwk-set+json":{"source":"iana","compressible":true},"application/jwt":{"source":"iana"},"application/kpml-request+xml":{"source":"iana","compressible":true},"application/kpml-response+xml":{"source":"iana","compressible":true},"application/ld+json":{"source":"iana","compressible":true,"extensions":["jsonld"]},"application/lgr+xml":{"source":"iana","compressible":true,"extensions":["lgr"]},"application/link-format":{"source":"iana"},"application/load-control+xml":{"source":"iana","compressible":true},"application/lost+xml":{"source":"iana","compressible":true,"extensions":["lostxml"]},"application/lostsync+xml":{"source":"iana","compressible":true},"application/lpf+zip":{"source":"iana","compressible":false},"application/lxf":{"source":"iana"},"application/mac-binhex40":{"source":"iana","extensions":["hqx"]},"application/mac-compactpro":{"source":"apache","extensions":["cpt"]},"application/macwriteii":{"source":"iana"},"application/mads+xml":{"source":"iana","compressible":true,"extensions":["mads"]},"application/manifest+json":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["webmanifest"]},"application/marc":{"source":"iana","extensions":["mrc"]},"application/marcxml+xml":{"source":"iana","compressible":true,"extensions":["mrcx"]},"application/mathematica":{"source":"iana","extensions":["ma","nb","mb"]},"application/mathml+xml":{"source":"iana","compressible":true,"extensions":["mathml"]},"application/mathml-content+xml":{"source":"iana","compressible":true},"application/mathml-presentation+xml":{"source":"iana","compressible":true},"application/mbms-associated-procedure-description+xml":{"source":"iana","compressible":true},"application/mbms-deregister+xml":{"source":"iana","compressible":true},"application/mbms-envelope+xml":{"source":"iana","compressible":true},"application/mbms-msk+xml":{"source":"iana","compressible":true},"application/mbms-msk-response+xml":{"source":"iana","compressible":true},"application/mbms-protection-description+xml":{"source":"iana","compressible":true},"application/mbms-reception-report+xml":{"source":"iana","compressible":true},"application/mbms-register+xml":{"source":"iana","compressible":true},"application/mbms-register-response+xml":{"source":"iana","compressible":true},"application/mbms-schedule+xml":{"source":"iana","compressible":true},"application/mbms-user-service-description+xml":{"source":"iana","compressible":true},"application/mbox":{"source":"iana","extensions":["mbox"]},"application/media-policy-dataset+xml":{"source":"iana","compressible":true,"extensions":["mpf"]},"application/media_control+xml":{"source":"iana","compressible":true},"application/mediaservercontrol+xml":{"source":"iana","compressible":true,"extensions":["mscml"]},"application/merge-patch+json":{"source":"iana","compressible":true},"application/metalink+xml":{"source":"apache","compressible":true,"extensions":["metalink"]},"application/metalink4+xml":{"source":"iana","compressible":true,"extensions":["meta4"]},"application/mets+xml":{"source":"iana","compressible":true,"extensions":["mets"]},"application/mf4":{"source":"iana"},"application/mikey":{"source":"iana"},"application/mipc":{"source":"iana"},"application/missing-blocks+cbor-seq":{"source":"iana"},"application/mmt-aei+xml":{"source":"iana","compressible":true,"extensions":["maei"]},"application/mmt-usd+xml":{"source":"iana","compressible":true,"extensions":["musd"]},"application/mods+xml":{"source":"iana","compressible":true,"extensions":["mods"]},"application/moss-keys":{"source":"iana"},"application/moss-signature":{"source":"iana"},"application/mosskey-data":{"source":"iana"},"application/mosskey-request":{"source":"iana"},"application/mp21":{"source":"iana","extensions":["m21","mp21"]},"application/mp4":{"source":"iana","extensions":["mp4s","m4p"]},"application/mpeg4-generic":{"source":"iana"},"application/mpeg4-iod":{"source":"iana"},"application/mpeg4-iod-xmt":{"source":"iana"},"application/mrb-consumer+xml":{"source":"iana","compressible":true},"application/mrb-publish+xml":{"source":"iana","compressible":true},"application/msc-ivr+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msc-mixer+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/msword":{"source":"iana","compressible":false,"extensions":["doc","dot"]},"application/mud+json":{"source":"iana","compressible":true},"application/multipart-core":{"source":"iana"},"application/mxf":{"source":"iana","extensions":["mxf"]},"application/n-quads":{"source":"iana","extensions":["nq"]},"application/n-triples":{"source":"iana","extensions":["nt"]},"application/nasdata":{"source":"iana"},"application/news-checkgroups":{"source":"iana","charset":"US-ASCII"},"application/news-groupinfo":{"source":"iana","charset":"US-ASCII"},"application/news-transmission":{"source":"iana"},"application/nlsml+xml":{"source":"iana","compressible":true},"application/node":{"source":"iana","extensions":["cjs"]},"application/nss":{"source":"iana"},"application/oauth-authz-req+jwt":{"source":"iana"},"application/oblivious-dns-message":{"source":"iana"},"application/ocsp-request":{"source":"iana"},"application/ocsp-response":{"source":"iana"},"application/octet-stream":{"source":"iana","compressible":false,"extensions":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{"source":"iana","extensions":["oda"]},"application/odm+xml":{"source":"iana","compressible":true},"application/odx":{"source":"iana"},"application/oebps-package+xml":{"source":"iana","compressible":true,"extensions":["opf"]},"application/ogg":{"source":"iana","compressible":false,"extensions":["ogx"]},"application/omdoc+xml":{"source":"apache","compressible":true,"extensions":["omdoc"]},"application/onenote":{"source":"apache","extensions":["onetoc","onetoc2","onetmp","onepkg"]},"application/opc-nodeset+xml":{"source":"iana","compressible":true},"application/oscore":{"source":"iana"},"application/oxps":{"source":"iana","extensions":["oxps"]},"application/p21":{"source":"iana"},"application/p21+zip":{"source":"iana","compressible":false},"application/p2p-overlay+xml":{"source":"iana","compressible":true,"extensions":["relo"]},"application/parityfec":{"source":"iana"},"application/passport":{"source":"iana"},"application/patch-ops-error+xml":{"source":"iana","compressible":true,"extensions":["xer"]},"application/pdf":{"source":"iana","compressible":false,"extensions":["pdf"]},"application/pdx":{"source":"iana"},"application/pem-certificate-chain":{"source":"iana"},"application/pgp-encrypted":{"source":"iana","compressible":false,"extensions":["pgp"]},"application/pgp-keys":{"source":"iana","extensions":["asc"]},"application/pgp-signature":{"source":"iana","extensions":["asc","sig"]},"application/pics-rules":{"source":"apache","extensions":["prf"]},"application/pidf+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pidf-diff+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/pkcs10":{"source":"iana","extensions":["p10"]},"application/pkcs12":{"source":"iana"},"application/pkcs7-mime":{"source":"iana","extensions":["p7m","p7c"]},"application/pkcs7-signature":{"source":"iana","extensions":["p7s"]},"application/pkcs8":{"source":"iana","extensions":["p8"]},"application/pkcs8-encrypted":{"source":"iana"},"application/pkix-attr-cert":{"source":"iana","extensions":["ac"]},"application/pkix-cert":{"source":"iana","extensions":["cer"]},"application/pkix-crl":{"source":"iana","extensions":["crl"]},"application/pkix-pkipath":{"source":"iana","extensions":["pkipath"]},"application/pkixcmp":{"source":"iana","extensions":["pki"]},"application/pls+xml":{"source":"iana","compressible":true,"extensions":["pls"]},"application/poc-settings+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/postscript":{"source":"iana","compressible":true,"extensions":["ai","eps","ps"]},"application/ppsp-tracker+json":{"source":"iana","compressible":true},"application/problem+json":{"source":"iana","compressible":true},"application/problem+xml":{"source":"iana","compressible":true},"application/provenance+xml":{"source":"iana","compressible":true,"extensions":["provx"]},"application/prs.alvestrand.titrax-sheet":{"source":"iana"},"application/prs.cww":{"source":"iana","extensions":["cww"]},"application/prs.cyn":{"source":"iana","charset":"7-BIT"},"application/prs.hpub+zip":{"source":"iana","compressible":false},"application/prs.nprend":{"source":"iana"},"application/prs.plucker":{"source":"iana"},"application/prs.rdf-xml-crypt":{"source":"iana"},"application/prs.xsf+xml":{"source":"iana","compressible":true},"application/pskc+xml":{"source":"iana","compressible":true,"extensions":["pskcxml"]},"application/pvd+json":{"source":"iana","compressible":true},"application/qsig":{"source":"iana"},"application/raml+yaml":{"compressible":true,"extensions":["raml"]},"application/raptorfec":{"source":"iana"},"application/rdap+json":{"source":"iana","compressible":true},"application/rdf+xml":{"source":"iana","compressible":true,"extensions":["rdf","owl"]},"application/reginfo+xml":{"source":"iana","compressible":true,"extensions":["rif"]},"application/relax-ng-compact-syntax":{"source":"iana","extensions":["rnc"]},"application/remote-printing":{"source":"iana"},"application/reputon+json":{"source":"iana","compressible":true},"application/resource-lists+xml":{"source":"iana","compressible":true,"extensions":["rl"]},"application/resource-lists-diff+xml":{"source":"iana","compressible":true,"extensions":["rld"]},"application/rfc+xml":{"source":"iana","compressible":true},"application/riscos":{"source":"iana"},"application/rlmi+xml":{"source":"iana","compressible":true},"application/rls-services+xml":{"source":"iana","compressible":true,"extensions":["rs"]},"application/route-apd+xml":{"source":"iana","compressible":true,"extensions":["rapd"]},"application/route-s-tsid+xml":{"source":"iana","compressible":true,"extensions":["sls"]},"application/route-usd+xml":{"source":"iana","compressible":true,"extensions":["rusd"]},"application/rpki-ghostbusters":{"source":"iana","extensions":["gbr"]},"application/rpki-manifest":{"source":"iana","extensions":["mft"]},"application/rpki-publication":{"source":"iana"},"application/rpki-roa":{"source":"iana","extensions":["roa"]},"application/rpki-updown":{"source":"iana"},"application/rsd+xml":{"source":"apache","compressible":true,"extensions":["rsd"]},"application/rss+xml":{"source":"apache","compressible":true,"extensions":["rss"]},"application/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"application/rtploopback":{"source":"iana"},"application/rtx":{"source":"iana"},"application/samlassertion+xml":{"source":"iana","compressible":true},"application/samlmetadata+xml":{"source":"iana","compressible":true},"application/sarif+json":{"source":"iana","compressible":true},"application/sarif-external-properties+json":{"source":"iana","compressible":true},"application/sbe":{"source":"iana"},"application/sbml+xml":{"source":"iana","compressible":true,"extensions":["sbml"]},"application/scaip+xml":{"source":"iana","compressible":true},"application/scim+json":{"source":"iana","compressible":true},"application/scvp-cv-request":{"source":"iana","extensions":["scq"]},"application/scvp-cv-response":{"source":"iana","extensions":["scs"]},"application/scvp-vp-request":{"source":"iana","extensions":["spq"]},"application/scvp-vp-response":{"source":"iana","extensions":["spp"]},"application/sdp":{"source":"iana","extensions":["sdp"]},"application/secevent+jwt":{"source":"iana"},"application/senml+cbor":{"source":"iana"},"application/senml+json":{"source":"iana","compressible":true},"application/senml+xml":{"source":"iana","compressible":true,"extensions":["senmlx"]},"application/senml-etch+cbor":{"source":"iana"},"application/senml-etch+json":{"source":"iana","compressible":true},"application/senml-exi":{"source":"iana"},"application/sensml+cbor":{"source":"iana"},"application/sensml+json":{"source":"iana","compressible":true},"application/sensml+xml":{"source":"iana","compressible":true,"extensions":["sensmlx"]},"application/sensml-exi":{"source":"iana"},"application/sep+xml":{"source":"iana","compressible":true},"application/sep-exi":{"source":"iana"},"application/session-info":{"source":"iana"},"application/set-payment":{"source":"iana"},"application/set-payment-initiation":{"source":"iana","extensions":["setpay"]},"application/set-registration":{"source":"iana"},"application/set-registration-initiation":{"source":"iana","extensions":["setreg"]},"application/sgml":{"source":"iana"},"application/sgml-open-catalog":{"source":"iana"},"application/shf+xml":{"source":"iana","compressible":true,"extensions":["shf"]},"application/sieve":{"source":"iana","extensions":["siv","sieve"]},"application/simple-filter+xml":{"source":"iana","compressible":true},"application/simple-message-summary":{"source":"iana"},"application/simplesymbolcontainer":{"source":"iana"},"application/sipc":{"source":"iana"},"application/slate":{"source":"iana"},"application/smil":{"source":"iana"},"application/smil+xml":{"source":"iana","compressible":true,"extensions":["smi","smil"]},"application/smpte336m":{"source":"iana"},"application/soap+fastinfoset":{"source":"iana"},"application/soap+xml":{"source":"iana","compressible":true},"application/sparql-query":{"source":"iana","extensions":["rq"]},"application/sparql-results+xml":{"source":"iana","compressible":true,"extensions":["srx"]},"application/spdx+json":{"source":"iana","compressible":true},"application/spirits-event+xml":{"source":"iana","compressible":true},"application/sql":{"source":"iana"},"application/srgs":{"source":"iana","extensions":["gram"]},"application/srgs+xml":{"source":"iana","compressible":true,"extensions":["grxml"]},"application/sru+xml":{"source":"iana","compressible":true,"extensions":["sru"]},"application/ssdl+xml":{"source":"apache","compressible":true,"extensions":["ssdl"]},"application/ssml+xml":{"source":"iana","compressible":true,"extensions":["ssml"]},"application/stix+json":{"source":"iana","compressible":true},"application/swid+xml":{"source":"iana","compressible":true,"extensions":["swidtag"]},"application/tamp-apex-update":{"source":"iana"},"application/tamp-apex-update-confirm":{"source":"iana"},"application/tamp-community-update":{"source":"iana"},"application/tamp-community-update-confirm":{"source":"iana"},"application/tamp-error":{"source":"iana"},"application/tamp-sequence-adjust":{"source":"iana"},"application/tamp-sequence-adjust-confirm":{"source":"iana"},"application/tamp-status-query":{"source":"iana"},"application/tamp-status-response":{"source":"iana"},"application/tamp-update":{"source":"iana"},"application/tamp-update-confirm":{"source":"iana"},"application/tar":{"compressible":true},"application/taxii+json":{"source":"iana","compressible":true},"application/td+json":{"source":"iana","compressible":true},"application/tei+xml":{"source":"iana","compressible":true,"extensions":["tei","teicorpus"]},"application/tetra_isi":{"source":"iana"},"application/thraud+xml":{"source":"iana","compressible":true,"extensions":["tfi"]},"application/timestamp-query":{"source":"iana"},"application/timestamp-reply":{"source":"iana"},"application/timestamped-data":{"source":"iana","extensions":["tsd"]},"application/tlsrpt+gzip":{"source":"iana"},"application/tlsrpt+json":{"source":"iana","compressible":true},"application/tnauthlist":{"source":"iana"},"application/token-introspection+jwt":{"source":"iana"},"application/toml":{"compressible":true,"extensions":["toml"]},"application/trickle-ice-sdpfrag":{"source":"iana"},"application/trig":{"source":"iana","extensions":["trig"]},"application/ttml+xml":{"source":"iana","compressible":true,"extensions":["ttml"]},"application/tve-trigger":{"source":"iana"},"application/tzif":{"source":"iana"},"application/tzif-leap":{"source":"iana"},"application/ubjson":{"compressible":false,"extensions":["ubj"]},"application/ulpfec":{"source":"iana"},"application/urc-grpsheet+xml":{"source":"iana","compressible":true},"application/urc-ressheet+xml":{"source":"iana","compressible":true,"extensions":["rsheet"]},"application/urc-targetdesc+xml":{"source":"iana","compressible":true,"extensions":["td"]},"application/urc-uisocketdesc+xml":{"source":"iana","compressible":true},"application/vcard+json":{"source":"iana","compressible":true},"application/vcard+xml":{"source":"iana","compressible":true},"application/vemmi":{"source":"iana"},"application/vividence.scriptfile":{"source":"apache"},"application/vnd.1000minds.decision-model+xml":{"source":"iana","compressible":true,"extensions":["1km"]},"application/vnd.3gpp-prose+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-prose-pc3ch+xml":{"source":"iana","compressible":true},"application/vnd.3gpp-v2x-local-service-information":{"source":"iana"},"application/vnd.3gpp.5gnas":{"source":"iana"},"application/vnd.3gpp.access-transfer-events+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.bsf+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gmop+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.gtpc":{"source":"iana"},"application/vnd.3gpp.interworking-data":{"source":"iana"},"application/vnd.3gpp.lpp":{"source":"iana"},"application/vnd.3gpp.mc-signalling-ear":{"source":"iana"},"application/vnd.3gpp.mcdata-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-payload":{"source":"iana"},"application/vnd.3gpp.mcdata-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-signalling":{"source":"iana"},"application/vnd.3gpp.mcdata-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcdata-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-floor-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-signed+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-ue-init-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcptt-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-command+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-affiliation-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-location-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-mbms-usage-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-service-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-transmission-request+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-ue-config+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mcvideo-user-profile+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.mid-call+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ngap":{"source":"iana"},"application/vnd.3gpp.pfcp":{"source":"iana"},"application/vnd.3gpp.pic-bw-large":{"source":"iana","extensions":["plb"]},"application/vnd.3gpp.pic-bw-small":{"source":"iana","extensions":["psb"]},"application/vnd.3gpp.pic-bw-var":{"source":"iana","extensions":["pvb"]},"application/vnd.3gpp.s1ap":{"source":"iana"},"application/vnd.3gpp.sms":{"source":"iana"},"application/vnd.3gpp.sms+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-ext+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.srvcc-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.state-and-event-info+xml":{"source":"iana","compressible":true},"application/vnd.3gpp.ussd+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.bcmcsinfo+xml":{"source":"iana","compressible":true},"application/vnd.3gpp2.sms":{"source":"iana"},"application/vnd.3gpp2.tcap":{"source":"iana","extensions":["tcap"]},"application/vnd.3lightssoftware.imagescal":{"source":"iana"},"application/vnd.3m.post-it-notes":{"source":"iana","extensions":["pwn"]},"application/vnd.accpac.simply.aso":{"source":"iana","extensions":["aso"]},"application/vnd.accpac.simply.imp":{"source":"iana","extensions":["imp"]},"application/vnd.acucobol":{"source":"iana","extensions":["acu"]},"application/vnd.acucorp":{"source":"iana","extensions":["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{"source":"apache","compressible":false,"extensions":["air"]},"application/vnd.adobe.flash.movie":{"source":"iana"},"application/vnd.adobe.formscentral.fcdt":{"source":"iana","extensions":["fcdt"]},"application/vnd.adobe.fxp":{"source":"iana","extensions":["fxp","fxpl"]},"application/vnd.adobe.partial-upload":{"source":"iana"},"application/vnd.adobe.xdp+xml":{"source":"iana","compressible":true,"extensions":["xdp"]},"application/vnd.adobe.xfdf":{"source":"iana","extensions":["xfdf"]},"application/vnd.aether.imp":{"source":"iana"},"application/vnd.afpc.afplinedata":{"source":"iana"},"application/vnd.afpc.afplinedata-pagedef":{"source":"iana"},"application/vnd.afpc.cmoca-cmresource":{"source":"iana"},"application/vnd.afpc.foca-charset":{"source":"iana"},"application/vnd.afpc.foca-codedfont":{"source":"iana"},"application/vnd.afpc.foca-codepage":{"source":"iana"},"application/vnd.afpc.modca":{"source":"iana"},"application/vnd.afpc.modca-cmtable":{"source":"iana"},"application/vnd.afpc.modca-formdef":{"source":"iana"},"application/vnd.afpc.modca-mediummap":{"source":"iana"},"application/vnd.afpc.modca-objectcontainer":{"source":"iana"},"application/vnd.afpc.modca-overlay":{"source":"iana"},"application/vnd.afpc.modca-pagesegment":{"source":"iana"},"application/vnd.age":{"source":"iana","extensions":["age"]},"application/vnd.ah-barcode":{"source":"iana"},"application/vnd.ahead.space":{"source":"iana","extensions":["ahead"]},"application/vnd.airzip.filesecure.azf":{"source":"iana","extensions":["azf"]},"application/vnd.airzip.filesecure.azs":{"source":"iana","extensions":["azs"]},"application/vnd.amadeus+json":{"source":"iana","compressible":true},"application/vnd.amazon.ebook":{"source":"apache","extensions":["azw"]},"application/vnd.amazon.mobi8-ebook":{"source":"iana"},"application/vnd.americandynamics.acc":{"source":"iana","extensions":["acc"]},"application/vnd.amiga.ami":{"source":"iana","extensions":["ami"]},"application/vnd.amundsen.maze+xml":{"source":"iana","compressible":true},"application/vnd.android.ota":{"source":"iana"},"application/vnd.android.package-archive":{"source":"apache","compressible":false,"extensions":["apk"]},"application/vnd.anki":{"source":"iana"},"application/vnd.anser-web-certificate-issue-initiation":{"source":"iana","extensions":["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{"source":"apache","extensions":["fti"]},"application/vnd.antix.game-component":{"source":"iana","extensions":["atx"]},"application/vnd.apache.arrow.file":{"source":"iana"},"application/vnd.apache.arrow.stream":{"source":"iana"},"application/vnd.apache.thrift.binary":{"source":"iana"},"application/vnd.apache.thrift.compact":{"source":"iana"},"application/vnd.apache.thrift.json":{"source":"iana"},"application/vnd.api+json":{"source":"iana","compressible":true},"application/vnd.aplextor.warrp+json":{"source":"iana","compressible":true},"application/vnd.apothekende.reservation+json":{"source":"iana","compressible":true},"application/vnd.apple.installer+xml":{"source":"iana","compressible":true,"extensions":["mpkg"]},"application/vnd.apple.keynote":{"source":"iana","extensions":["key"]},"application/vnd.apple.mpegurl":{"source":"iana","extensions":["m3u8"]},"application/vnd.apple.numbers":{"source":"iana","extensions":["numbers"]},"application/vnd.apple.pages":{"source":"iana","extensions":["pages"]},"application/vnd.apple.pkpass":{"compressible":false,"extensions":["pkpass"]},"application/vnd.arastra.swi":{"source":"iana"},"application/vnd.aristanetworks.swi":{"source":"iana","extensions":["swi"]},"application/vnd.artisan+json":{"source":"iana","compressible":true},"application/vnd.artsquare":{"source":"iana"},"application/vnd.astraea-software.iota":{"source":"iana","extensions":["iota"]},"application/vnd.audiograph":{"source":"iana","extensions":["aep"]},"application/vnd.autopackage":{"source":"iana"},"application/vnd.avalon+json":{"source":"iana","compressible":true},"application/vnd.avistar+xml":{"source":"iana","compressible":true},"application/vnd.balsamiq.bmml+xml":{"source":"iana","compressible":true,"extensions":["bmml"]},"application/vnd.balsamiq.bmpr":{"source":"iana"},"application/vnd.banana-accounting":{"source":"iana"},"application/vnd.bbf.usp.error":{"source":"iana"},"application/vnd.bbf.usp.msg":{"source":"iana"},"application/vnd.bbf.usp.msg+json":{"source":"iana","compressible":true},"application/vnd.bekitzur-stech+json":{"source":"iana","compressible":true},"application/vnd.bint.med-content":{"source":"iana"},"application/vnd.biopax.rdf+xml":{"source":"iana","compressible":true},"application/vnd.blink-idb-value-wrapper":{"source":"iana"},"application/vnd.blueice.multipass":{"source":"iana","extensions":["mpm"]},"application/vnd.bluetooth.ep.oob":{"source":"iana"},"application/vnd.bluetooth.le.oob":{"source":"iana"},"application/vnd.bmi":{"source":"iana","extensions":["bmi"]},"application/vnd.bpf":{"source":"iana"},"application/vnd.bpf3":{"source":"iana"},"application/vnd.businessobjects":{"source":"iana","extensions":["rep"]},"application/vnd.byu.uapi+json":{"source":"iana","compressible":true},"application/vnd.cab-jscript":{"source":"iana"},"application/vnd.canon-cpdl":{"source":"iana"},"application/vnd.canon-lips":{"source":"iana"},"application/vnd.capasystems-pg+json":{"source":"iana","compressible":true},"application/vnd.cendio.thinlinc.clientconf":{"source":"iana"},"application/vnd.century-systems.tcp_stream":{"source":"iana"},"application/vnd.chemdraw+xml":{"source":"iana","compressible":true,"extensions":["cdxml"]},"application/vnd.chess-pgn":{"source":"iana"},"application/vnd.chipnuts.karaoke-mmd":{"source":"iana","extensions":["mmd"]},"application/vnd.ciedi":{"source":"iana"},"application/vnd.cinderella":{"source":"iana","extensions":["cdy"]},"application/vnd.cirpack.isdn-ext":{"source":"iana"},"application/vnd.citationstyles.style+xml":{"source":"iana","compressible":true,"extensions":["csl"]},"application/vnd.claymore":{"source":"iana","extensions":["cla"]},"application/vnd.cloanto.rp9":{"source":"iana","extensions":["rp9"]},"application/vnd.clonk.c4group":{"source":"iana","extensions":["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{"source":"iana","extensions":["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{"source":"iana","extensions":["c11amz"]},"application/vnd.coffeescript":{"source":"iana"},"application/vnd.collabio.xodocuments.document":{"source":"iana"},"application/vnd.collabio.xodocuments.document-template":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation":{"source":"iana"},"application/vnd.collabio.xodocuments.presentation-template":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet":{"source":"iana"},"application/vnd.collabio.xodocuments.spreadsheet-template":{"source":"iana"},"application/vnd.collection+json":{"source":"iana","compressible":true},"application/vnd.collection.doc+json":{"source":"iana","compressible":true},"application/vnd.collection.next+json":{"source":"iana","compressible":true},"application/vnd.comicbook+zip":{"source":"iana","compressible":false},"application/vnd.comicbook-rar":{"source":"iana"},"application/vnd.commerce-battelle":{"source":"iana"},"application/vnd.commonspace":{"source":"iana","extensions":["csp"]},"application/vnd.contact.cmsg":{"source":"iana","extensions":["cdbcmsg"]},"application/vnd.coreos.ignition+json":{"source":"iana","compressible":true},"application/vnd.cosmocaller":{"source":"iana","extensions":["cmc"]},"application/vnd.crick.clicker":{"source":"iana","extensions":["clkx"]},"application/vnd.crick.clicker.keyboard":{"source":"iana","extensions":["clkk"]},"application/vnd.crick.clicker.palette":{"source":"iana","extensions":["clkp"]},"application/vnd.crick.clicker.template":{"source":"iana","extensions":["clkt"]},"application/vnd.crick.clicker.wordbank":{"source":"iana","extensions":["clkw"]},"application/vnd.criticaltools.wbs+xml":{"source":"iana","compressible":true,"extensions":["wbs"]},"application/vnd.cryptii.pipe+json":{"source":"iana","compressible":true},"application/vnd.crypto-shade-file":{"source":"iana"},"application/vnd.cryptomator.encrypted":{"source":"iana"},"application/vnd.cryptomator.vault":{"source":"iana"},"application/vnd.ctc-posml":{"source":"iana","extensions":["pml"]},"application/vnd.ctct.ws+xml":{"source":"iana","compressible":true},"application/vnd.cups-pdf":{"source":"iana"},"application/vnd.cups-postscript":{"source":"iana"},"application/vnd.cups-ppd":{"source":"iana","extensions":["ppd"]},"application/vnd.cups-raster":{"source":"iana"},"application/vnd.cups-raw":{"source":"iana"},"application/vnd.curl":{"source":"iana"},"application/vnd.curl.car":{"source":"apache","extensions":["car"]},"application/vnd.curl.pcurl":{"source":"apache","extensions":["pcurl"]},"application/vnd.cyan.dean.root+xml":{"source":"iana","compressible":true},"application/vnd.cybank":{"source":"iana"},"application/vnd.cyclonedx+json":{"source":"iana","compressible":true},"application/vnd.cyclonedx+xml":{"source":"iana","compressible":true},"application/vnd.d2l.coursepackage1p0+zip":{"source":"iana","compressible":false},"application/vnd.d3m-dataset":{"source":"iana"},"application/vnd.d3m-problem":{"source":"iana"},"application/vnd.dart":{"source":"iana","compressible":true,"extensions":["dart"]},"application/vnd.data-vision.rdz":{"source":"iana","extensions":["rdz"]},"application/vnd.datapackage+json":{"source":"iana","compressible":true},"application/vnd.dataresource+json":{"source":"iana","compressible":true},"application/vnd.dbf":{"source":"iana","extensions":["dbf"]},"application/vnd.debian.binary-package":{"source":"iana"},"application/vnd.dece.data":{"source":"iana","extensions":["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{"source":"iana","compressible":true,"extensions":["uvt","uvvt"]},"application/vnd.dece.unspecified":{"source":"iana","extensions":["uvx","uvvx"]},"application/vnd.dece.zip":{"source":"iana","extensions":["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{"source":"iana","extensions":["fe_launch"]},"application/vnd.desmume.movie":{"source":"iana"},"application/vnd.dir-bi.plate-dl-nosuffix":{"source":"iana"},"application/vnd.dm.delegation+xml":{"source":"iana","compressible":true},"application/vnd.dna":{"source":"iana","extensions":["dna"]},"application/vnd.document+json":{"source":"iana","compressible":true},"application/vnd.dolby.mlp":{"source":"apache","extensions":["mlp"]},"application/vnd.dolby.mobile.1":{"source":"iana"},"application/vnd.dolby.mobile.2":{"source":"iana"},"application/vnd.doremir.scorecloud-binary-document":{"source":"iana"},"application/vnd.dpgraph":{"source":"iana","extensions":["dpg"]},"application/vnd.dreamfactory":{"source":"iana","extensions":["dfac"]},"application/vnd.drive+json":{"source":"iana","compressible":true},"application/vnd.ds-keypoint":{"source":"apache","extensions":["kpxx"]},"application/vnd.dtg.local":{"source":"iana"},"application/vnd.dtg.local.flash":{"source":"iana"},"application/vnd.dtg.local.html":{"source":"iana"},"application/vnd.dvb.ait":{"source":"iana","extensions":["ait"]},"application/vnd.dvb.dvbisl+xml":{"source":"iana","compressible":true},"application/vnd.dvb.dvbj":{"source":"iana"},"application/vnd.dvb.esgcontainer":{"source":"iana"},"application/vnd.dvb.ipdcdftnotifaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess":{"source":"iana"},"application/vnd.dvb.ipdcesgaccess2":{"source":"iana"},"application/vnd.dvb.ipdcesgpdd":{"source":"iana"},"application/vnd.dvb.ipdcroaming":{"source":"iana"},"application/vnd.dvb.iptv.alfec-base":{"source":"iana"},"application/vnd.dvb.iptv.alfec-enhancement":{"source":"iana"},"application/vnd.dvb.notif-aggregate-root+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-container+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-generic+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-msglist+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-request+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-ia-registration-response+xml":{"source":"iana","compressible":true},"application/vnd.dvb.notif-init+xml":{"source":"iana","compressible":true},"application/vnd.dvb.pfr":{"source":"iana"},"application/vnd.dvb.service":{"source":"iana","extensions":["svc"]},"application/vnd.dxr":{"source":"iana"},"application/vnd.dynageo":{"source":"iana","extensions":["geo"]},"application/vnd.dzr":{"source":"iana"},"application/vnd.easykaraoke.cdgdownload":{"source":"iana"},"application/vnd.ecdis-update":{"source":"iana"},"application/vnd.ecip.rlp":{"source":"iana"},"application/vnd.eclipse.ditto+json":{"source":"iana","compressible":true},"application/vnd.ecowin.chart":{"source":"iana","extensions":["mag"]},"application/vnd.ecowin.filerequest":{"source":"iana"},"application/vnd.ecowin.fileupdate":{"source":"iana"},"application/vnd.ecowin.series":{"source":"iana"},"application/vnd.ecowin.seriesrequest":{"source":"iana"},"application/vnd.ecowin.seriesupdate":{"source":"iana"},"application/vnd.efi.img":{"source":"iana"},"application/vnd.efi.iso":{"source":"iana"},"application/vnd.emclient.accessrequest+xml":{"source":"iana","compressible":true},"application/vnd.enliven":{"source":"iana","extensions":["nml"]},"application/vnd.enphase.envoy":{"source":"iana"},"application/vnd.eprints.data+xml":{"source":"iana","compressible":true},"application/vnd.epson.esf":{"source":"iana","extensions":["esf"]},"application/vnd.epson.msf":{"source":"iana","extensions":["msf"]},"application/vnd.epson.quickanime":{"source":"iana","extensions":["qam"]},"application/vnd.epson.salt":{"source":"iana","extensions":["slt"]},"application/vnd.epson.ssf":{"source":"iana","extensions":["ssf"]},"application/vnd.ericsson.quickcall":{"source":"iana"},"application/vnd.espass-espass+zip":{"source":"iana","compressible":false},"application/vnd.eszigno3+xml":{"source":"iana","compressible":true,"extensions":["es3","et3"]},"application/vnd.etsi.aoc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.asic-e+zip":{"source":"iana","compressible":false},"application/vnd.etsi.asic-s+zip":{"source":"iana","compressible":false},"application/vnd.etsi.cug+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvcommand+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-bc+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-cod+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsad-npvr+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvservice+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvsync+xml":{"source":"iana","compressible":true},"application/vnd.etsi.iptvueprofile+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mcid+xml":{"source":"iana","compressible":true},"application/vnd.etsi.mheg5":{"source":"iana"},"application/vnd.etsi.overload-control-policy-dataset+xml":{"source":"iana","compressible":true},"application/vnd.etsi.pstn+xml":{"source":"iana","compressible":true},"application/vnd.etsi.sci+xml":{"source":"iana","compressible":true},"application/vnd.etsi.simservs+xml":{"source":"iana","compressible":true},"application/vnd.etsi.timestamp-token":{"source":"iana"},"application/vnd.etsi.tsl+xml":{"source":"iana","compressible":true},"application/vnd.etsi.tsl.der":{"source":"iana"},"application/vnd.eu.kasparian.car+json":{"source":"iana","compressible":true},"application/vnd.eudora.data":{"source":"iana"},"application/vnd.evolv.ecig.profile":{"source":"iana"},"application/vnd.evolv.ecig.settings":{"source":"iana"},"application/vnd.evolv.ecig.theme":{"source":"iana"},"application/vnd.exstream-empower+zip":{"source":"iana","compressible":false},"application/vnd.exstream-package":{"source":"iana"},"application/vnd.ezpix-album":{"source":"iana","extensions":["ez2"]},"application/vnd.ezpix-package":{"source":"iana","extensions":["ez3"]},"application/vnd.f-secure.mobile":{"source":"iana"},"application/vnd.familysearch.gedcom+zip":{"source":"iana","compressible":false},"application/vnd.fastcopy-disk-image":{"source":"iana"},"application/vnd.fdf":{"source":"iana","extensions":["fdf"]},"application/vnd.fdsn.mseed":{"source":"iana","extensions":["mseed"]},"application/vnd.fdsn.seed":{"source":"iana","extensions":["seed","dataless"]},"application/vnd.ffsns":{"source":"iana"},"application/vnd.ficlab.flb+zip":{"source":"iana","compressible":false},"application/vnd.filmit.zfc":{"source":"iana"},"application/vnd.fints":{"source":"iana"},"application/vnd.firemonkeys.cloudcell":{"source":"iana"},"application/vnd.flographit":{"source":"iana","extensions":["gph"]},"application/vnd.fluxtime.clip":{"source":"iana","extensions":["ftc"]},"application/vnd.font-fontforge-sfd":{"source":"iana"},"application/vnd.framemaker":{"source":"iana","extensions":["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{"source":"iana","extensions":["fnc"]},"application/vnd.frogans.ltf":{"source":"iana","extensions":["ltf"]},"application/vnd.fsc.weblaunch":{"source":"iana","extensions":["fsc"]},"application/vnd.fujifilm.fb.docuworks":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.binder":{"source":"iana"},"application/vnd.fujifilm.fb.docuworks.container":{"source":"iana"},"application/vnd.fujifilm.fb.jfi+xml":{"source":"iana","compressible":true},"application/vnd.fujitsu.oasys":{"source":"iana","extensions":["oas"]},"application/vnd.fujitsu.oasys2":{"source":"iana","extensions":["oa2"]},"application/vnd.fujitsu.oasys3":{"source":"iana","extensions":["oa3"]},"application/vnd.fujitsu.oasysgp":{"source":"iana","extensions":["fg5"]},"application/vnd.fujitsu.oasysprs":{"source":"iana","extensions":["bh2"]},"application/vnd.fujixerox.art-ex":{"source":"iana"},"application/vnd.fujixerox.art4":{"source":"iana"},"application/vnd.fujixerox.ddd":{"source":"iana","extensions":["ddd"]},"application/vnd.fujixerox.docuworks":{"source":"iana","extensions":["xdw"]},"application/vnd.fujixerox.docuworks.binder":{"source":"iana","extensions":["xbd"]},"application/vnd.fujixerox.docuworks.container":{"source":"iana"},"application/vnd.fujixerox.hbpl":{"source":"iana"},"application/vnd.fut-misnet":{"source":"iana"},"application/vnd.futoin+cbor":{"source":"iana"},"application/vnd.futoin+json":{"source":"iana","compressible":true},"application/vnd.fuzzysheet":{"source":"iana","extensions":["fzs"]},"application/vnd.genomatix.tuxedo":{"source":"iana","extensions":["txd"]},"application/vnd.gentics.grd+json":{"source":"iana","compressible":true},"application/vnd.geo+json":{"source":"iana","compressible":true},"application/vnd.geocube+xml":{"source":"iana","compressible":true},"application/vnd.geogebra.file":{"source":"iana","extensions":["ggb"]},"application/vnd.geogebra.slides":{"source":"iana"},"application/vnd.geogebra.tool":{"source":"iana","extensions":["ggt"]},"application/vnd.geometry-explorer":{"source":"iana","extensions":["gex","gre"]},"application/vnd.geonext":{"source":"iana","extensions":["gxt"]},"application/vnd.geoplan":{"source":"iana","extensions":["g2w"]},"application/vnd.geospace":{"source":"iana","extensions":["g3w"]},"application/vnd.gerber":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt":{"source":"iana"},"application/vnd.globalplatform.card-content-mgt-response":{"source":"iana"},"application/vnd.gmx":{"source":"iana","extensions":["gmx"]},"application/vnd.google-apps.document":{"compressible":false,"extensions":["gdoc"]},"application/vnd.google-apps.presentation":{"compressible":false,"extensions":["gslides"]},"application/vnd.google-apps.spreadsheet":{"compressible":false,"extensions":["gsheet"]},"application/vnd.google-earth.kml+xml":{"source":"iana","compressible":true,"extensions":["kml"]},"application/vnd.google-earth.kmz":{"source":"iana","compressible":false,"extensions":["kmz"]},"application/vnd.gov.sk.e-form+xml":{"source":"iana","compressible":true},"application/vnd.gov.sk.e-form+zip":{"source":"iana","compressible":false},"application/vnd.gov.sk.xmldatacontainer+xml":{"source":"iana","compressible":true},"application/vnd.grafeq":{"source":"iana","extensions":["gqf","gqs"]},"application/vnd.gridmp":{"source":"iana"},"application/vnd.groove-account":{"source":"iana","extensions":["gac"]},"application/vnd.groove-help":{"source":"iana","extensions":["ghf"]},"application/vnd.groove-identity-message":{"source":"iana","extensions":["gim"]},"application/vnd.groove-injector":{"source":"iana","extensions":["grv"]},"application/vnd.groove-tool-message":{"source":"iana","extensions":["gtm"]},"application/vnd.groove-tool-template":{"source":"iana","extensions":["tpl"]},"application/vnd.groove-vcard":{"source":"iana","extensions":["vcg"]},"application/vnd.hal+json":{"source":"iana","compressible":true},"application/vnd.hal+xml":{"source":"iana","compressible":true,"extensions":["hal"]},"application/vnd.handheld-entertainment+xml":{"source":"iana","compressible":true,"extensions":["zmm"]},"application/vnd.hbci":{"source":"iana","extensions":["hbci"]},"application/vnd.hc+json":{"source":"iana","compressible":true},"application/vnd.hcl-bireports":{"source":"iana"},"application/vnd.hdt":{"source":"iana"},"application/vnd.heroku+json":{"source":"iana","compressible":true},"application/vnd.hhe.lesson-player":{"source":"iana","extensions":["les"]},"application/vnd.hl7cda+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hl7v2+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.hp-hpgl":{"source":"iana","extensions":["hpgl"]},"application/vnd.hp-hpid":{"source":"iana","extensions":["hpid"]},"application/vnd.hp-hps":{"source":"iana","extensions":["hps"]},"application/vnd.hp-jlyt":{"source":"iana","extensions":["jlt"]},"application/vnd.hp-pcl":{"source":"iana","extensions":["pcl"]},"application/vnd.hp-pclxl":{"source":"iana","extensions":["pclxl"]},"application/vnd.httphone":{"source":"iana"},"application/vnd.hydrostatix.sof-data":{"source":"iana","extensions":["sfd-hdstx"]},"application/vnd.hyper+json":{"source":"iana","compressible":true},"application/vnd.hyper-item+json":{"source":"iana","compressible":true},"application/vnd.hyperdrive+json":{"source":"iana","compressible":true},"application/vnd.hzn-3d-crossword":{"source":"iana"},"application/vnd.ibm.afplinedata":{"source":"iana"},"application/vnd.ibm.electronic-media":{"source":"iana"},"application/vnd.ibm.minipay":{"source":"iana","extensions":["mpy"]},"application/vnd.ibm.modcap":{"source":"iana","extensions":["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{"source":"iana","extensions":["irm"]},"application/vnd.ibm.secure-container":{"source":"iana","extensions":["sc"]},"application/vnd.iccprofile":{"source":"iana","extensions":["icc","icm"]},"application/vnd.ieee.1905":{"source":"iana"},"application/vnd.igloader":{"source":"iana","extensions":["igl"]},"application/vnd.imagemeter.folder+zip":{"source":"iana","compressible":false},"application/vnd.imagemeter.image+zip":{"source":"iana","compressible":false},"application/vnd.immervision-ivp":{"source":"iana","extensions":["ivp"]},"application/vnd.immervision-ivu":{"source":"iana","extensions":["ivu"]},"application/vnd.ims.imsccv1p1":{"source":"iana"},"application/vnd.ims.imsccv1p2":{"source":"iana"},"application/vnd.ims.imsccv1p3":{"source":"iana"},"application/vnd.ims.lis.v2.result+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolconsumerprofile+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolproxy.id+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings+json":{"source":"iana","compressible":true},"application/vnd.ims.lti.v2.toolsettings.simple+json":{"source":"iana","compressible":true},"application/vnd.informedcontrol.rms+xml":{"source":"iana","compressible":true},"application/vnd.informix-visionary":{"source":"iana"},"application/vnd.infotech.project":{"source":"iana"},"application/vnd.infotech.project+xml":{"source":"iana","compressible":true},"application/vnd.innopath.wamp.notification":{"source":"iana"},"application/vnd.insors.igm":{"source":"iana","extensions":["igm"]},"application/vnd.intercon.formnet":{"source":"iana","extensions":["xpw","xpx"]},"application/vnd.intergeo":{"source":"iana","extensions":["i2g"]},"application/vnd.intertrust.digibox":{"source":"iana"},"application/vnd.intertrust.nncp":{"source":"iana"},"application/vnd.intu.qbo":{"source":"iana","extensions":["qbo"]},"application/vnd.intu.qfx":{"source":"iana","extensions":["qfx"]},"application/vnd.iptc.g2.catalogitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.conceptitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.knowledgeitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.newsmessage+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.packageitem+xml":{"source":"iana","compressible":true},"application/vnd.iptc.g2.planningitem+xml":{"source":"iana","compressible":true},"application/vnd.ipunplugged.rcprofile":{"source":"iana","extensions":["rcprofile"]},"application/vnd.irepository.package+xml":{"source":"iana","compressible":true,"extensions":["irp"]},"application/vnd.is-xpr":{"source":"iana","extensions":["xpr"]},"application/vnd.isac.fcs":{"source":"iana","extensions":["fcs"]},"application/vnd.iso11783-10+zip":{"source":"iana","compressible":false},"application/vnd.jam":{"source":"iana","extensions":["jam"]},"application/vnd.japannet-directory-service":{"source":"iana"},"application/vnd.japannet-jpnstore-wakeup":{"source":"iana"},"application/vnd.japannet-payment-wakeup":{"source":"iana"},"application/vnd.japannet-registration":{"source":"iana"},"application/vnd.japannet-registration-wakeup":{"source":"iana"},"application/vnd.japannet-setstore-wakeup":{"source":"iana"},"application/vnd.japannet-verification":{"source":"iana"},"application/vnd.japannet-verification-wakeup":{"source":"iana"},"application/vnd.jcp.javame.midlet-rms":{"source":"iana","extensions":["rms"]},"application/vnd.jisp":{"source":"iana","extensions":["jisp"]},"application/vnd.joost.joda-archive":{"source":"iana","extensions":["joda"]},"application/vnd.jsk.isdn-ngn":{"source":"iana"},"application/vnd.kahootz":{"source":"iana","extensions":["ktz","ktr"]},"application/vnd.kde.karbon":{"source":"iana","extensions":["karbon"]},"application/vnd.kde.kchart":{"source":"iana","extensions":["chrt"]},"application/vnd.kde.kformula":{"source":"iana","extensions":["kfo"]},"application/vnd.kde.kivio":{"source":"iana","extensions":["flw"]},"application/vnd.kde.kontour":{"source":"iana","extensions":["kon"]},"application/vnd.kde.kpresenter":{"source":"iana","extensions":["kpr","kpt"]},"application/vnd.kde.kspread":{"source":"iana","extensions":["ksp"]},"application/vnd.kde.kword":{"source":"iana","extensions":["kwd","kwt"]},"application/vnd.kenameaapp":{"source":"iana","extensions":["htke"]},"application/vnd.kidspiration":{"source":"iana","extensions":["kia"]},"application/vnd.kinar":{"source":"iana","extensions":["kne","knp"]},"application/vnd.koan":{"source":"iana","extensions":["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{"source":"iana","extensions":["sse"]},"application/vnd.las":{"source":"iana"},"application/vnd.las.las+json":{"source":"iana","compressible":true},"application/vnd.las.las+xml":{"source":"iana","compressible":true,"extensions":["lasxml"]},"application/vnd.laszip":{"source":"iana"},"application/vnd.leap+json":{"source":"iana","compressible":true},"application/vnd.liberty-request+xml":{"source":"iana","compressible":true},"application/vnd.llamagraphics.life-balance.desktop":{"source":"iana","extensions":["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{"source":"iana","compressible":true,"extensions":["lbe"]},"application/vnd.logipipe.circuit+zip":{"source":"iana","compressible":false},"application/vnd.loom":{"source":"iana"},"application/vnd.lotus-1-2-3":{"source":"iana","extensions":["123"]},"application/vnd.lotus-approach":{"source":"iana","extensions":["apr"]},"application/vnd.lotus-freelance":{"source":"iana","extensions":["pre"]},"application/vnd.lotus-notes":{"source":"iana","extensions":["nsf"]},"application/vnd.lotus-organizer":{"source":"iana","extensions":["org"]},"application/vnd.lotus-screencam":{"source":"iana","extensions":["scm"]},"application/vnd.lotus-wordpro":{"source":"iana","extensions":["lwp"]},"application/vnd.macports.portpkg":{"source":"iana","extensions":["portpkg"]},"application/vnd.mapbox-vector-tile":{"source":"iana","extensions":["mvt"]},"application/vnd.marlin.drm.actiontoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.conftoken+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.license+xml":{"source":"iana","compressible":true},"application/vnd.marlin.drm.mdcf":{"source":"iana"},"application/vnd.mason+json":{"source":"iana","compressible":true},"application/vnd.maxar.archive.3tz+zip":{"source":"iana","compressible":false},"application/vnd.maxmind.maxmind-db":{"source":"iana"},"application/vnd.mcd":{"source":"iana","extensions":["mcd"]},"application/vnd.medcalcdata":{"source":"iana","extensions":["mc1"]},"application/vnd.mediastation.cdkey":{"source":"iana","extensions":["cdkey"]},"application/vnd.meridian-slingshot":{"source":"iana"},"application/vnd.mfer":{"source":"iana","extensions":["mwf"]},"application/vnd.mfmp":{"source":"iana","extensions":["mfm"]},"application/vnd.micro+json":{"source":"iana","compressible":true},"application/vnd.micrografx.flo":{"source":"iana","extensions":["flo"]},"application/vnd.micrografx.igx":{"source":"iana","extensions":["igx"]},"application/vnd.microsoft.portable-executable":{"source":"iana"},"application/vnd.microsoft.windows.thumbnail-cache":{"source":"iana"},"application/vnd.miele+json":{"source":"iana","compressible":true},"application/vnd.mif":{"source":"iana","extensions":["mif"]},"application/vnd.minisoft-hp3000-save":{"source":"iana"},"application/vnd.mitsubishi.misty-guard.trustweb":{"source":"iana"},"application/vnd.mobius.daf":{"source":"iana","extensions":["daf"]},"application/vnd.mobius.dis":{"source":"iana","extensions":["dis"]},"application/vnd.mobius.mbk":{"source":"iana","extensions":["mbk"]},"application/vnd.mobius.mqy":{"source":"iana","extensions":["mqy"]},"application/vnd.mobius.msl":{"source":"iana","extensions":["msl"]},"application/vnd.mobius.plc":{"source":"iana","extensions":["plc"]},"application/vnd.mobius.txf":{"source":"iana","extensions":["txf"]},"application/vnd.mophun.application":{"source":"iana","extensions":["mpn"]},"application/vnd.mophun.certificate":{"source":"iana","extensions":["mpc"]},"application/vnd.motorola.flexsuite":{"source":"iana"},"application/vnd.motorola.flexsuite.adsi":{"source":"iana"},"application/vnd.motorola.flexsuite.fis":{"source":"iana"},"application/vnd.motorola.flexsuite.gotap":{"source":"iana"},"application/vnd.motorola.flexsuite.kmr":{"source":"iana"},"application/vnd.motorola.flexsuite.ttc":{"source":"iana"},"application/vnd.motorola.flexsuite.wem":{"source":"iana"},"application/vnd.motorola.iprm":{"source":"iana"},"application/vnd.mozilla.xul+xml":{"source":"iana","compressible":true,"extensions":["xul"]},"application/vnd.ms-3mfdocument":{"source":"iana"},"application/vnd.ms-artgalry":{"source":"iana","extensions":["cil"]},"application/vnd.ms-asf":{"source":"iana"},"application/vnd.ms-cab-compressed":{"source":"iana","extensions":["cab"]},"application/vnd.ms-color.iccprofile":{"source":"apache"},"application/vnd.ms-excel":{"source":"iana","compressible":false,"extensions":["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{"source":"iana","extensions":["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{"source":"iana","extensions":["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{"source":"iana","extensions":["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{"source":"iana","extensions":["xltm"]},"application/vnd.ms-fontobject":{"source":"iana","compressible":true,"extensions":["eot"]},"application/vnd.ms-htmlhelp":{"source":"iana","extensions":["chm"]},"application/vnd.ms-ims":{"source":"iana","extensions":["ims"]},"application/vnd.ms-lrm":{"source":"iana","extensions":["lrm"]},"application/vnd.ms-office.activex+xml":{"source":"iana","compressible":true},"application/vnd.ms-officetheme":{"source":"iana","extensions":["thmx"]},"application/vnd.ms-opentype":{"source":"apache","compressible":true},"application/vnd.ms-outlook":{"compressible":false,"extensions":["msg"]},"application/vnd.ms-package.obfuscated-opentype":{"source":"apache"},"application/vnd.ms-pki.seccat":{"source":"apache","extensions":["cat"]},"application/vnd.ms-pki.stl":{"source":"apache","extensions":["stl"]},"application/vnd.ms-playready.initiator+xml":{"source":"iana","compressible":true},"application/vnd.ms-powerpoint":{"source":"iana","compressible":false,"extensions":["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{"source":"iana","extensions":["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{"source":"iana","extensions":["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{"source":"iana","extensions":["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{"source":"iana","extensions":["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{"source":"iana","extensions":["potm"]},"application/vnd.ms-printdevicecapabilities+xml":{"source":"iana","compressible":true},"application/vnd.ms-printing.printticket+xml":{"source":"apache","compressible":true},"application/vnd.ms-printschematicket+xml":{"source":"iana","compressible":true},"application/vnd.ms-project":{"source":"iana","extensions":["mpp","mpt"]},"application/vnd.ms-tnef":{"source":"iana"},"application/vnd.ms-windows.devicepairing":{"source":"iana"},"application/vnd.ms-windows.nwprinting.oob":{"source":"iana"},"application/vnd.ms-windows.printerpairing":{"source":"iana"},"application/vnd.ms-windows.wsd.oob":{"source":"iana"},"application/vnd.ms-wmdrm.lic-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.lic-resp":{"source":"iana"},"application/vnd.ms-wmdrm.meter-chlg-req":{"source":"iana"},"application/vnd.ms-wmdrm.meter-resp":{"source":"iana"},"application/vnd.ms-word.document.macroenabled.12":{"source":"iana","extensions":["docm"]},"application/vnd.ms-word.template.macroenabled.12":{"source":"iana","extensions":["dotm"]},"application/vnd.ms-works":{"source":"iana","extensions":["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{"source":"iana","extensions":["wpl"]},"application/vnd.ms-xpsdocument":{"source":"iana","compressible":false,"extensions":["xps"]},"application/vnd.msa-disk-image":{"source":"iana"},"application/vnd.mseq":{"source":"iana","extensions":["mseq"]},"application/vnd.msign":{"source":"iana"},"application/vnd.multiad.creator":{"source":"iana"},"application/vnd.multiad.creator.cif":{"source":"iana"},"application/vnd.music-niff":{"source":"iana"},"application/vnd.musician":{"source":"iana","extensions":["mus"]},"application/vnd.muvee.style":{"source":"iana","extensions":["msty"]},"application/vnd.mynfc":{"source":"iana","extensions":["taglet"]},"application/vnd.nacamar.ybrid+json":{"source":"iana","compressible":true},"application/vnd.ncd.control":{"source":"iana"},"application/vnd.ncd.reference":{"source":"iana"},"application/vnd.nearst.inv+json":{"source":"iana","compressible":true},"application/vnd.nebumind.line":{"source":"iana"},"application/vnd.nervana":{"source":"iana"},"application/vnd.netfpx":{"source":"iana"},"application/vnd.neurolanguage.nlu":{"source":"iana","extensions":["nlu"]},"application/vnd.nimn":{"source":"iana"},"application/vnd.nintendo.nitro.rom":{"source":"iana"},"application/vnd.nintendo.snes.rom":{"source":"iana"},"application/vnd.nitf":{"source":"iana","extensions":["ntf","nitf"]},"application/vnd.noblenet-directory":{"source":"iana","extensions":["nnd"]},"application/vnd.noblenet-sealer":{"source":"iana","extensions":["nns"]},"application/vnd.noblenet-web":{"source":"iana","extensions":["nnw"]},"application/vnd.nokia.catalogs":{"source":"iana"},"application/vnd.nokia.conml+wbxml":{"source":"iana"},"application/vnd.nokia.conml+xml":{"source":"iana","compressible":true},"application/vnd.nokia.iptv.config+xml":{"source":"iana","compressible":true},"application/vnd.nokia.isds-radio-presets":{"source":"iana"},"application/vnd.nokia.landmark+wbxml":{"source":"iana"},"application/vnd.nokia.landmark+xml":{"source":"iana","compressible":true},"application/vnd.nokia.landmarkcollection+xml":{"source":"iana","compressible":true},"application/vnd.nokia.n-gage.ac+xml":{"source":"iana","compressible":true,"extensions":["ac"]},"application/vnd.nokia.n-gage.data":{"source":"iana","extensions":["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{"source":"iana","extensions":["n-gage"]},"application/vnd.nokia.ncd":{"source":"iana"},"application/vnd.nokia.pcd+wbxml":{"source":"iana"},"application/vnd.nokia.pcd+xml":{"source":"iana","compressible":true},"application/vnd.nokia.radio-preset":{"source":"iana","extensions":["rpst"]},"application/vnd.nokia.radio-presets":{"source":"iana","extensions":["rpss"]},"application/vnd.novadigm.edm":{"source":"iana","extensions":["edm"]},"application/vnd.novadigm.edx":{"source":"iana","extensions":["edx"]},"application/vnd.novadigm.ext":{"source":"iana","extensions":["ext"]},"application/vnd.ntt-local.content-share":{"source":"iana"},"application/vnd.ntt-local.file-transfer":{"source":"iana"},"application/vnd.ntt-local.ogw_remote-access":{"source":"iana"},"application/vnd.ntt-local.sip-ta_remote":{"source":"iana"},"application/vnd.ntt-local.sip-ta_tcp_stream":{"source":"iana"},"application/vnd.oasis.opendocument.chart":{"source":"iana","extensions":["odc"]},"application/vnd.oasis.opendocument.chart-template":{"source":"iana","extensions":["otc"]},"application/vnd.oasis.opendocument.database":{"source":"iana","extensions":["odb"]},"application/vnd.oasis.opendocument.formula":{"source":"iana","extensions":["odf"]},"application/vnd.oasis.opendocument.formula-template":{"source":"iana","extensions":["odft"]},"application/vnd.oasis.opendocument.graphics":{"source":"iana","compressible":false,"extensions":["odg"]},"application/vnd.oasis.opendocument.graphics-template":{"source":"iana","extensions":["otg"]},"application/vnd.oasis.opendocument.image":{"source":"iana","extensions":["odi"]},"application/vnd.oasis.opendocument.image-template":{"source":"iana","extensions":["oti"]},"application/vnd.oasis.opendocument.presentation":{"source":"iana","compressible":false,"extensions":["odp"]},"application/vnd.oasis.opendocument.presentation-template":{"source":"iana","extensions":["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{"source":"iana","compressible":false,"extensions":["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{"source":"iana","extensions":["ots"]},"application/vnd.oasis.opendocument.text":{"source":"iana","compressible":false,"extensions":["odt"]},"application/vnd.oasis.opendocument.text-master":{"source":"iana","extensions":["odm"]},"application/vnd.oasis.opendocument.text-template":{"source":"iana","extensions":["ott"]},"application/vnd.oasis.opendocument.text-web":{"source":"iana","extensions":["oth"]},"application/vnd.obn":{"source":"iana"},"application/vnd.ocf+cbor":{"source":"iana"},"application/vnd.oci.image.manifest.v1+json":{"source":"iana","compressible":true},"application/vnd.oftn.l10n+json":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessdownload+xml":{"source":"iana","compressible":true},"application/vnd.oipf.contentaccessstreaming+xml":{"source":"iana","compressible":true},"application/vnd.oipf.cspg-hexbinary":{"source":"iana"},"application/vnd.oipf.dae.svg+xml":{"source":"iana","compressible":true},"application/vnd.oipf.dae.xhtml+xml":{"source":"iana","compressible":true},"application/vnd.oipf.mippvcontrolmessage+xml":{"source":"iana","compressible":true},"application/vnd.oipf.pae.gem":{"source":"iana"},"application/vnd.oipf.spdiscovery+xml":{"source":"iana","compressible":true},"application/vnd.oipf.spdlist+xml":{"source":"iana","compressible":true},"application/vnd.oipf.ueprofile+xml":{"source":"iana","compressible":true},"application/vnd.oipf.userprofile+xml":{"source":"iana","compressible":true},"application/vnd.olpc-sugar":{"source":"iana","extensions":["xo"]},"application/vnd.oma-scws-config":{"source":"iana"},"application/vnd.oma-scws-http-request":{"source":"iana"},"application/vnd.oma-scws-http-response":{"source":"iana"},"application/vnd.oma.bcast.associated-procedure-parameter+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.drm-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.imd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.ltkm":{"source":"iana"},"application/vnd.oma.bcast.notification+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.provisioningtrigger":{"source":"iana"},"application/vnd.oma.bcast.sgboot":{"source":"iana"},"application/vnd.oma.bcast.sgdd+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sgdu":{"source":"iana"},"application/vnd.oma.bcast.simple-symbol-container":{"source":"iana"},"application/vnd.oma.bcast.smartcard-trigger+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.sprov+xml":{"source":"iana","compressible":true},"application/vnd.oma.bcast.stkm":{"source":"iana"},"application/vnd.oma.cab-address-book+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-feature-handler+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-pcc+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-subs-invite+xml":{"source":"iana","compressible":true},"application/vnd.oma.cab-user-prefs+xml":{"source":"iana","compressible":true},"application/vnd.oma.dcd":{"source":"iana"},"application/vnd.oma.dcdc":{"source":"iana"},"application/vnd.oma.dd2+xml":{"source":"iana","compressible":true,"extensions":["dd2"]},"application/vnd.oma.drm.risd+xml":{"source":"iana","compressible":true},"application/vnd.oma.group-usage-list+xml":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+cbor":{"source":"iana"},"application/vnd.oma.lwm2m+json":{"source":"iana","compressible":true},"application/vnd.oma.lwm2m+tlv":{"source":"iana"},"application/vnd.oma.pal+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.detailed-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.final-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.groups+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.invocation-descriptor+xml":{"source":"iana","compressible":true},"application/vnd.oma.poc.optimized-progress-report+xml":{"source":"iana","compressible":true},"application/vnd.oma.push":{"source":"iana"},"application/vnd.oma.scidm.messages+xml":{"source":"iana","compressible":true},"application/vnd.oma.xcap-directory+xml":{"source":"iana","compressible":true},"application/vnd.omads-email+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-file+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omads-folder+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.omaloc-supl-init":{"source":"iana"},"application/vnd.onepager":{"source":"iana"},"application/vnd.onepagertamp":{"source":"iana"},"application/vnd.onepagertamx":{"source":"iana"},"application/vnd.onepagertat":{"source":"iana"},"application/vnd.onepagertatp":{"source":"iana"},"application/vnd.onepagertatx":{"source":"iana"},"application/vnd.openblox.game+xml":{"source":"iana","compressible":true,"extensions":["obgx"]},"application/vnd.openblox.game-binary":{"source":"iana"},"application/vnd.openeye.oeb":{"source":"iana"},"application/vnd.openofficeorg.extension":{"source":"apache","extensions":["oxt"]},"application/vnd.openstreetmap.data+xml":{"source":"iana","compressible":true,"extensions":["osm"]},"application/vnd.opentimestamps.ots":{"source":"iana"},"application/vnd.openxmlformats-officedocument.custom-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.customxmlproperties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawing+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chart+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.extended-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{"source":"iana","compressible":false,"extensions":["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slide":{"source":"iana","extensions":["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{"source":"iana","extensions":["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.tags+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.template":{"source":"iana","extensions":["potx"]},"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{"source":"iana","compressible":false,"extensions":["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{"source":"iana","extensions":["xltx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.theme+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.themeoverride+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.vmldrawing":{"source":"iana"},"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{"source":"iana","compressible":false,"extensions":["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{"source":"iana","extensions":["dotx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.core-properties+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml":{"source":"iana","compressible":true},"application/vnd.openxmlformats-package.relationships+xml":{"source":"iana","compressible":true},"application/vnd.oracle.resource+json":{"source":"iana","compressible":true},"application/vnd.orange.indata":{"source":"iana"},"application/vnd.osa.netdeploy":{"source":"iana"},"application/vnd.osgeo.mapguide.package":{"source":"iana","extensions":["mgp"]},"application/vnd.osgi.bundle":{"source":"iana"},"application/vnd.osgi.dp":{"source":"iana","extensions":["dp"]},"application/vnd.osgi.subsystem":{"source":"iana","extensions":["esa"]},"application/vnd.otps.ct-kip+xml":{"source":"iana","compressible":true},"application/vnd.oxli.countgraph":{"source":"iana"},"application/vnd.pagerduty+json":{"source":"iana","compressible":true},"application/vnd.palm":{"source":"iana","extensions":["pdb","pqa","oprc"]},"application/vnd.panoply":{"source":"iana"},"application/vnd.paos.xml":{"source":"iana"},"application/vnd.patentdive":{"source":"iana"},"application/vnd.patientecommsdoc":{"source":"iana"},"application/vnd.pawaafile":{"source":"iana","extensions":["paw"]},"application/vnd.pcos":{"source":"iana"},"application/vnd.pg.format":{"source":"iana","extensions":["str"]},"application/vnd.pg.osasli":{"source":"iana","extensions":["ei6"]},"application/vnd.piaccess.application-licence":{"source":"iana"},"application/vnd.picsel":{"source":"iana","extensions":["efif"]},"application/vnd.pmi.widget":{"source":"iana","extensions":["wg"]},"application/vnd.poc.group-advertisement+xml":{"source":"iana","compressible":true},"application/vnd.pocketlearn":{"source":"iana","extensions":["plf"]},"application/vnd.powerbuilder6":{"source":"iana","extensions":["pbd"]},"application/vnd.powerbuilder6-s":{"source":"iana"},"application/vnd.powerbuilder7":{"source":"iana"},"application/vnd.powerbuilder7-s":{"source":"iana"},"application/vnd.powerbuilder75":{"source":"iana"},"application/vnd.powerbuilder75-s":{"source":"iana"},"application/vnd.preminet":{"source":"iana"},"application/vnd.previewsystems.box":{"source":"iana","extensions":["box"]},"application/vnd.proteus.magazine":{"source":"iana","extensions":["mgz"]},"application/vnd.psfs":{"source":"iana"},"application/vnd.publishare-delta-tree":{"source":"iana","extensions":["qps"]},"application/vnd.pvi.ptid1":{"source":"iana","extensions":["ptid"]},"application/vnd.pwg-multiplexed":{"source":"iana"},"application/vnd.pwg-xhtml-print+xml":{"source":"iana","compressible":true},"application/vnd.qualcomm.brew-app-res":{"source":"iana"},"application/vnd.quarantainenet":{"source":"iana"},"application/vnd.quark.quarkxpress":{"source":"iana","extensions":["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.quobject-quoxdocument":{"source":"iana"},"application/vnd.radisys.moml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-conn+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-audit-stream+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-conf+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-base+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-detect+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-fax-sendrecv+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-group+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-speech+xml":{"source":"iana","compressible":true},"application/vnd.radisys.msml-dialog-transform+xml":{"source":"iana","compressible":true},"application/vnd.rainstor.data":{"source":"iana"},"application/vnd.rapid":{"source":"iana"},"application/vnd.rar":{"source":"iana","extensions":["rar"]},"application/vnd.realvnc.bed":{"source":"iana","extensions":["bed"]},"application/vnd.recordare.musicxml":{"source":"iana","extensions":["mxl"]},"application/vnd.recordare.musicxml+xml":{"source":"iana","compressible":true,"extensions":["musicxml"]},"application/vnd.renlearn.rlprint":{"source":"iana"},"application/vnd.resilient.logic":{"source":"iana"},"application/vnd.restful+json":{"source":"iana","compressible":true},"application/vnd.rig.cryptonote":{"source":"iana","extensions":["cryptonote"]},"application/vnd.rim.cod":{"source":"apache","extensions":["cod"]},"application/vnd.rn-realmedia":{"source":"apache","extensions":["rm"]},"application/vnd.rn-realmedia-vbr":{"source":"apache","extensions":["rmvb"]},"application/vnd.route66.link66+xml":{"source":"iana","compressible":true,"extensions":["link66"]},"application/vnd.rs-274x":{"source":"iana"},"application/vnd.ruckus.download":{"source":"iana"},"application/vnd.s3sms":{"source":"iana"},"application/vnd.sailingtracker.track":{"source":"iana","extensions":["st"]},"application/vnd.sar":{"source":"iana"},"application/vnd.sbm.cid":{"source":"iana"},"application/vnd.sbm.mid2":{"source":"iana"},"application/vnd.scribus":{"source":"iana"},"application/vnd.sealed.3df":{"source":"iana"},"application/vnd.sealed.csf":{"source":"iana"},"application/vnd.sealed.doc":{"source":"iana"},"application/vnd.sealed.eml":{"source":"iana"},"application/vnd.sealed.mht":{"source":"iana"},"application/vnd.sealed.net":{"source":"iana"},"application/vnd.sealed.ppt":{"source":"iana"},"application/vnd.sealed.tiff":{"source":"iana"},"application/vnd.sealed.xls":{"source":"iana"},"application/vnd.sealedmedia.softseal.html":{"source":"iana"},"application/vnd.sealedmedia.softseal.pdf":{"source":"iana"},"application/vnd.seemail":{"source":"iana","extensions":["see"]},"application/vnd.seis+json":{"source":"iana","compressible":true},"application/vnd.sema":{"source":"iana","extensions":["sema"]},"application/vnd.semd":{"source":"iana","extensions":["semd"]},"application/vnd.semf":{"source":"iana","extensions":["semf"]},"application/vnd.shade-save-file":{"source":"iana"},"application/vnd.shana.informed.formdata":{"source":"iana","extensions":["ifm"]},"application/vnd.shana.informed.formtemplate":{"source":"iana","extensions":["itp"]},"application/vnd.shana.informed.interchange":{"source":"iana","extensions":["iif"]},"application/vnd.shana.informed.package":{"source":"iana","extensions":["ipk"]},"application/vnd.shootproof+json":{"source":"iana","compressible":true},"application/vnd.shopkick+json":{"source":"iana","compressible":true},"application/vnd.shp":{"source":"iana"},"application/vnd.shx":{"source":"iana"},"application/vnd.sigrok.session":{"source":"iana"},"application/vnd.simtech-mindmapper":{"source":"iana","extensions":["twd","twds"]},"application/vnd.siren+json":{"source":"iana","compressible":true},"application/vnd.smaf":{"source":"iana","extensions":["mmf"]},"application/vnd.smart.notebook":{"source":"iana"},"application/vnd.smart.teacher":{"source":"iana","extensions":["teacher"]},"application/vnd.snesdev-page-table":{"source":"iana"},"application/vnd.software602.filler.form+xml":{"source":"iana","compressible":true,"extensions":["fo"]},"application/vnd.software602.filler.form-xml-zip":{"source":"iana"},"application/vnd.solent.sdkm+xml":{"source":"iana","compressible":true,"extensions":["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{"source":"iana","extensions":["dxp"]},"application/vnd.spotfire.sfs":{"source":"iana","extensions":["sfs"]},"application/vnd.sqlite3":{"source":"iana"},"application/vnd.sss-cod":{"source":"iana"},"application/vnd.sss-dtf":{"source":"iana"},"application/vnd.sss-ntf":{"source":"iana"},"application/vnd.stardivision.calc":{"source":"apache","extensions":["sdc"]},"application/vnd.stardivision.draw":{"source":"apache","extensions":["sda"]},"application/vnd.stardivision.impress":{"source":"apache","extensions":["sdd"]},"application/vnd.stardivision.math":{"source":"apache","extensions":["smf"]},"application/vnd.stardivision.writer":{"source":"apache","extensions":["sdw","vor"]},"application/vnd.stardivision.writer-global":{"source":"apache","extensions":["sgl"]},"application/vnd.stepmania.package":{"source":"iana","extensions":["smzip"]},"application/vnd.stepmania.stepchart":{"source":"iana","extensions":["sm"]},"application/vnd.street-stream":{"source":"iana"},"application/vnd.sun.wadl+xml":{"source":"iana","compressible":true,"extensions":["wadl"]},"application/vnd.sun.xml.calc":{"source":"apache","extensions":["sxc"]},"application/vnd.sun.xml.calc.template":{"source":"apache","extensions":["stc"]},"application/vnd.sun.xml.draw":{"source":"apache","extensions":["sxd"]},"application/vnd.sun.xml.draw.template":{"source":"apache","extensions":["std"]},"application/vnd.sun.xml.impress":{"source":"apache","extensions":["sxi"]},"application/vnd.sun.xml.impress.template":{"source":"apache","extensions":["sti"]},"application/vnd.sun.xml.math":{"source":"apache","extensions":["sxm"]},"application/vnd.sun.xml.writer":{"source":"apache","extensions":["sxw"]},"application/vnd.sun.xml.writer.global":{"source":"apache","extensions":["sxg"]},"application/vnd.sun.xml.writer.template":{"source":"apache","extensions":["stw"]},"application/vnd.sus-calendar":{"source":"iana","extensions":["sus","susp"]},"application/vnd.svd":{"source":"iana","extensions":["svd"]},"application/vnd.swiftview-ics":{"source":"iana"},"application/vnd.sycle+xml":{"source":"iana","compressible":true},"application/vnd.syft+json":{"source":"iana","compressible":true},"application/vnd.symbian.install":{"source":"apache","extensions":["sis","sisx"]},"application/vnd.syncml+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xsm"]},"application/vnd.syncml.dm+wbxml":{"source":"iana","charset":"UTF-8","extensions":["bdm"]},"application/vnd.syncml.dm+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["xdm"]},"application/vnd.syncml.dm.notification":{"source":"iana"},"application/vnd.syncml.dmddf+wbxml":{"source":"iana"},"application/vnd.syncml.dmddf+xml":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["ddf"]},"application/vnd.syncml.dmtnds+wbxml":{"source":"iana"},"application/vnd.syncml.dmtnds+xml":{"source":"iana","charset":"UTF-8","compressible":true},"application/vnd.syncml.ds.notification":{"source":"iana"},"application/vnd.tableschema+json":{"source":"iana","compressible":true},"application/vnd.tao.intent-module-archive":{"source":"iana","extensions":["tao"]},"application/vnd.tcpdump.pcap":{"source":"iana","extensions":["pcap","cap","dmp"]},"application/vnd.think-cell.ppttc+json":{"source":"iana","compressible":true},"application/vnd.tmd.mediaflex.api+xml":{"source":"iana","compressible":true},"application/vnd.tml":{"source":"iana"},"application/vnd.tmobile-livetv":{"source":"iana","extensions":["tmo"]},"application/vnd.tri.onesource":{"source":"iana"},"application/vnd.trid.tpt":{"source":"iana","extensions":["tpt"]},"application/vnd.triscape.mxs":{"source":"iana","extensions":["mxs"]},"application/vnd.trueapp":{"source":"iana","extensions":["tra"]},"application/vnd.truedoc":{"source":"iana"},"application/vnd.ubisoft.webplayer":{"source":"iana"},"application/vnd.ufdl":{"source":"iana","extensions":["ufd","ufdl"]},"application/vnd.uiq.theme":{"source":"iana","extensions":["utz"]},"application/vnd.umajin":{"source":"iana","extensions":["umj"]},"application/vnd.unity":{"source":"iana","extensions":["unityweb"]},"application/vnd.uoml+xml":{"source":"iana","compressible":true,"extensions":["uoml"]},"application/vnd.uplanet.alert":{"source":"iana"},"application/vnd.uplanet.alert-wbxml":{"source":"iana"},"application/vnd.uplanet.bearer-choice":{"source":"iana"},"application/vnd.uplanet.bearer-choice-wbxml":{"source":"iana"},"application/vnd.uplanet.cacheop":{"source":"iana"},"application/vnd.uplanet.cacheop-wbxml":{"source":"iana"},"application/vnd.uplanet.channel":{"source":"iana"},"application/vnd.uplanet.channel-wbxml":{"source":"iana"},"application/vnd.uplanet.list":{"source":"iana"},"application/vnd.uplanet.list-wbxml":{"source":"iana"},"application/vnd.uplanet.listcmd":{"source":"iana"},"application/vnd.uplanet.listcmd-wbxml":{"source":"iana"},"application/vnd.uplanet.signal":{"source":"iana"},"application/vnd.uri-map":{"source":"iana"},"application/vnd.valve.source.material":{"source":"iana"},"application/vnd.vcx":{"source":"iana","extensions":["vcx"]},"application/vnd.vd-study":{"source":"iana"},"application/vnd.vectorworks":{"source":"iana"},"application/vnd.vel+json":{"source":"iana","compressible":true},"application/vnd.verimatrix.vcas":{"source":"iana"},"application/vnd.veritone.aion+json":{"source":"iana","compressible":true},"application/vnd.veryant.thin":{"source":"iana"},"application/vnd.ves.encrypted":{"source":"iana"},"application/vnd.vidsoft.vidconference":{"source":"iana"},"application/vnd.visio":{"source":"iana","extensions":["vsd","vst","vss","vsw"]},"application/vnd.visionary":{"source":"iana","extensions":["vis"]},"application/vnd.vividence.scriptfile":{"source":"iana"},"application/vnd.vsf":{"source":"iana","extensions":["vsf"]},"application/vnd.wap.sic":{"source":"iana"},"application/vnd.wap.slc":{"source":"iana"},"application/vnd.wap.wbxml":{"source":"iana","charset":"UTF-8","extensions":["wbxml"]},"application/vnd.wap.wmlc":{"source":"iana","extensions":["wmlc"]},"application/vnd.wap.wmlscriptc":{"source":"iana","extensions":["wmlsc"]},"application/vnd.webturbo":{"source":"iana","extensions":["wtb"]},"application/vnd.wfa.dpp":{"source":"iana"},"application/vnd.wfa.p2p":{"source":"iana"},"application/vnd.wfa.wsc":{"source":"iana"},"application/vnd.windows.devicepairing":{"source":"iana"},"application/vnd.wmc":{"source":"iana"},"application/vnd.wmf.bootstrap":{"source":"iana"},"application/vnd.wolfram.mathematica":{"source":"iana"},"application/vnd.wolfram.mathematica.package":{"source":"iana"},"application/vnd.wolfram.player":{"source":"iana","extensions":["nbp"]},"application/vnd.wordperfect":{"source":"iana","extensions":["wpd"]},"application/vnd.wqd":{"source":"iana","extensions":["wqd"]},"application/vnd.wrq-hp3000-labelled":{"source":"iana"},"application/vnd.wt.stf":{"source":"iana","extensions":["stf"]},"application/vnd.wv.csp+wbxml":{"source":"iana"},"application/vnd.wv.csp+xml":{"source":"iana","compressible":true},"application/vnd.wv.ssp+xml":{"source":"iana","compressible":true},"application/vnd.xacml+json":{"source":"iana","compressible":true},"application/vnd.xara":{"source":"iana","extensions":["xar"]},"application/vnd.xfdl":{"source":"iana","extensions":["xfdl"]},"application/vnd.xfdl.webform":{"source":"iana"},"application/vnd.xmi+xml":{"source":"iana","compressible":true},"application/vnd.xmpie.cpkg":{"source":"iana"},"application/vnd.xmpie.dpkg":{"source":"iana"},"application/vnd.xmpie.plan":{"source":"iana"},"application/vnd.xmpie.ppkg":{"source":"iana"},"application/vnd.xmpie.xlim":{"source":"iana"},"application/vnd.yamaha.hv-dic":{"source":"iana","extensions":["hvd"]},"application/vnd.yamaha.hv-script":{"source":"iana","extensions":["hvs"]},"application/vnd.yamaha.hv-voice":{"source":"iana","extensions":["hvp"]},"application/vnd.yamaha.openscoreformat":{"source":"iana","extensions":["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{"source":"iana","compressible":true,"extensions":["osfpvg"]},"application/vnd.yamaha.remote-setup":{"source":"iana"},"application/vnd.yamaha.smaf-audio":{"source":"iana","extensions":["saf"]},"application/vnd.yamaha.smaf-phrase":{"source":"iana","extensions":["spf"]},"application/vnd.yamaha.through-ngn":{"source":"iana"},"application/vnd.yamaha.tunnel-udpencap":{"source":"iana"},"application/vnd.yaoweme":{"source":"iana"},"application/vnd.yellowriver-custom-menu":{"source":"iana","extensions":["cmp"]},"application/vnd.youtube.yt":{"source":"iana"},"application/vnd.zul":{"source":"iana","extensions":["zir","zirz"]},"application/vnd.zzazz.deck+xml":{"source":"iana","compressible":true,"extensions":["zaz"]},"application/voicexml+xml":{"source":"iana","compressible":true,"extensions":["vxml"]},"application/voucher-cms+json":{"source":"iana","compressible":true},"application/vq-rtcpxr":{"source":"iana"},"application/wasm":{"source":"iana","compressible":true,"extensions":["wasm"]},"application/watcherinfo+xml":{"source":"iana","compressible":true,"extensions":["wif"]},"application/webpush-options+json":{"source":"iana","compressible":true},"application/whoispp-query":{"source":"iana"},"application/whoispp-response":{"source":"iana"},"application/widget":{"source":"iana","extensions":["wgt"]},"application/winhlp":{"source":"apache","extensions":["hlp"]},"application/wita":{"source":"iana"},"application/wordperfect5.1":{"source":"iana"},"application/wsdl+xml":{"source":"iana","compressible":true,"extensions":["wsdl"]},"application/wspolicy+xml":{"source":"iana","compressible":true,"extensions":["wspolicy"]},"application/x-7z-compressed":{"source":"apache","compressible":false,"extensions":["7z"]},"application/x-abiword":{"source":"apache","extensions":["abw"]},"application/x-ace-compressed":{"source":"apache","extensions":["ace"]},"application/x-amf":{"source":"apache"},"application/x-apple-diskimage":{"source":"apache","extensions":["dmg"]},"application/x-arj":{"compressible":false,"extensions":["arj"]},"application/x-authorware-bin":{"source":"apache","extensions":["aab","x32","u32","vox"]},"application/x-authorware-map":{"source":"apache","extensions":["aam"]},"application/x-authorware-seg":{"source":"apache","extensions":["aas"]},"application/x-bcpio":{"source":"apache","extensions":["bcpio"]},"application/x-bdoc":{"compressible":false,"extensions":["bdoc"]},"application/x-bittorrent":{"source":"apache","extensions":["torrent"]},"application/x-blorb":{"source":"apache","extensions":["blb","blorb"]},"application/x-bzip":{"source":"apache","compressible":false,"extensions":["bz"]},"application/x-bzip2":{"source":"apache","compressible":false,"extensions":["bz2","boz"]},"application/x-cbr":{"source":"apache","extensions":["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{"source":"apache","extensions":["vcd"]},"application/x-cfs-compressed":{"source":"apache","extensions":["cfs"]},"application/x-chat":{"source":"apache","extensions":["chat"]},"application/x-chess-pgn":{"source":"apache","extensions":["pgn"]},"application/x-chrome-extension":{"extensions":["crx"]},"application/x-cocoa":{"source":"nginx","extensions":["cco"]},"application/x-compress":{"source":"apache"},"application/x-conference":{"source":"apache","extensions":["nsc"]},"application/x-cpio":{"source":"apache","extensions":["cpio"]},"application/x-csh":{"source":"apache","extensions":["csh"]},"application/x-deb":{"compressible":false},"application/x-debian-package":{"source":"apache","extensions":["deb","udeb"]},"application/x-dgc-compressed":{"source":"apache","extensions":["dgc"]},"application/x-director":{"source":"apache","extensions":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{"source":"apache","extensions":["wad"]},"application/x-dtbncx+xml":{"source":"apache","compressible":true,"extensions":["ncx"]},"application/x-dtbook+xml":{"source":"apache","compressible":true,"extensions":["dtb"]},"application/x-dtbresource+xml":{"source":"apache","compressible":true,"extensions":["res"]},"application/x-dvi":{"source":"apache","compressible":false,"extensions":["dvi"]},"application/x-envoy":{"source":"apache","extensions":["evy"]},"application/x-eva":{"source":"apache","extensions":["eva"]},"application/x-font-bdf":{"source":"apache","extensions":["bdf"]},"application/x-font-dos":{"source":"apache"},"application/x-font-framemaker":{"source":"apache"},"application/x-font-ghostscript":{"source":"apache","extensions":["gsf"]},"application/x-font-libgrx":{"source":"apache"},"application/x-font-linux-psf":{"source":"apache","extensions":["psf"]},"application/x-font-pcf":{"source":"apache","extensions":["pcf"]},"application/x-font-snf":{"source":"apache","extensions":["snf"]},"application/x-font-speedo":{"source":"apache"},"application/x-font-sunos-news":{"source":"apache"},"application/x-font-type1":{"source":"apache","extensions":["pfa","pfb","pfm","afm"]},"application/x-font-vfont":{"source":"apache"},"application/x-freearc":{"source":"apache","extensions":["arc"]},"application/x-futuresplash":{"source":"apache","extensions":["spl"]},"application/x-gca-compressed":{"source":"apache","extensions":["gca"]},"application/x-glulx":{"source":"apache","extensions":["ulx"]},"application/x-gnumeric":{"source":"apache","extensions":["gnumeric"]},"application/x-gramps-xml":{"source":"apache","extensions":["gramps"]},"application/x-gtar":{"source":"apache","extensions":["gtar"]},"application/x-gzip":{"source":"apache"},"application/x-hdf":{"source":"apache","extensions":["hdf"]},"application/x-httpd-php":{"compressible":true,"extensions":["php"]},"application/x-install-instructions":{"source":"apache","extensions":["install"]},"application/x-iso9660-image":{"source":"apache","extensions":["iso"]},"application/x-iwork-keynote-sffkey":{"extensions":["key"]},"application/x-iwork-numbers-sffnumbers":{"extensions":["numbers"]},"application/x-iwork-pages-sffpages":{"extensions":["pages"]},"application/x-java-archive-diff":{"source":"nginx","extensions":["jardiff"]},"application/x-java-jnlp-file":{"source":"apache","compressible":false,"extensions":["jnlp"]},"application/x-javascript":{"compressible":true},"application/x-keepass2":{"extensions":["kdbx"]},"application/x-latex":{"source":"apache","compressible":false,"extensions":["latex"]},"application/x-lua-bytecode":{"extensions":["luac"]},"application/x-lzh-compressed":{"source":"apache","extensions":["lzh","lha"]},"application/x-makeself":{"source":"nginx","extensions":["run"]},"application/x-mie":{"source":"apache","extensions":["mie"]},"application/x-mobipocket-ebook":{"source":"apache","extensions":["prc","mobi"]},"application/x-mpegurl":{"compressible":false},"application/x-ms-application":{"source":"apache","extensions":["application"]},"application/x-ms-shortcut":{"source":"apache","extensions":["lnk"]},"application/x-ms-wmd":{"source":"apache","extensions":["wmd"]},"application/x-ms-wmz":{"source":"apache","extensions":["wmz"]},"application/x-ms-xbap":{"source":"apache","extensions":["xbap"]},"application/x-msaccess":{"source":"apache","extensions":["mdb"]},"application/x-msbinder":{"source":"apache","extensions":["obd"]},"application/x-mscardfile":{"source":"apache","extensions":["crd"]},"application/x-msclip":{"source":"apache","extensions":["clp"]},"application/x-msdos-program":{"extensions":["exe"]},"application/x-msdownload":{"source":"apache","extensions":["exe","dll","com","bat","msi"]},"application/x-msmediaview":{"source":"apache","extensions":["mvb","m13","m14"]},"application/x-msmetafile":{"source":"apache","extensions":["wmf","wmz","emf","emz"]},"application/x-msmoney":{"source":"apache","extensions":["mny"]},"application/x-mspublisher":{"source":"apache","extensions":["pub"]},"application/x-msschedule":{"source":"apache","extensions":["scd"]},"application/x-msterminal":{"source":"apache","extensions":["trm"]},"application/x-mswrite":{"source":"apache","extensions":["wri"]},"application/x-netcdf":{"source":"apache","extensions":["nc","cdf"]},"application/x-ns-proxy-autoconfig":{"compressible":true,"extensions":["pac"]},"application/x-nzb":{"source":"apache","extensions":["nzb"]},"application/x-perl":{"source":"nginx","extensions":["pl","pm"]},"application/x-pilot":{"source":"nginx","extensions":["prc","pdb"]},"application/x-pkcs12":{"source":"apache","compressible":false,"extensions":["p12","pfx"]},"application/x-pkcs7-certificates":{"source":"apache","extensions":["p7b","spc"]},"application/x-pkcs7-certreqresp":{"source":"apache","extensions":["p7r"]},"application/x-pki-message":{"source":"iana"},"application/x-rar-compressed":{"source":"apache","compressible":false,"extensions":["rar"]},"application/x-redhat-package-manager":{"source":"nginx","extensions":["rpm"]},"application/x-research-info-systems":{"source":"apache","extensions":["ris"]},"application/x-sea":{"source":"nginx","extensions":["sea"]},"application/x-sh":{"source":"apache","compressible":true,"extensions":["sh"]},"application/x-shar":{"source":"apache","extensions":["shar"]},"application/x-shockwave-flash":{"source":"apache","compressible":false,"extensions":["swf"]},"application/x-silverlight-app":{"source":"apache","extensions":["xap"]},"application/x-sql":{"source":"apache","extensions":["sql"]},"application/x-stuffit":{"source":"apache","compressible":false,"extensions":["sit"]},"application/x-stuffitx":{"source":"apache","extensions":["sitx"]},"application/x-subrip":{"source":"apache","extensions":["srt"]},"application/x-sv4cpio":{"source":"apache","extensions":["sv4cpio"]},"application/x-sv4crc":{"source":"apache","extensions":["sv4crc"]},"application/x-t3vm-image":{"source":"apache","extensions":["t3"]},"application/x-tads":{"source":"apache","extensions":["gam"]},"application/x-tar":{"source":"apache","compressible":true,"extensions":["tar"]},"application/x-tcl":{"source":"apache","extensions":["tcl","tk"]},"application/x-tex":{"source":"apache","extensions":["tex"]},"application/x-tex-tfm":{"source":"apache","extensions":["tfm"]},"application/x-texinfo":{"source":"apache","extensions":["texinfo","texi"]},"application/x-tgif":{"source":"apache","extensions":["obj"]},"application/x-ustar":{"source":"apache","extensions":["ustar"]},"application/x-virtualbox-hdd":{"compressible":true,"extensions":["hdd"]},"application/x-virtualbox-ova":{"compressible":true,"extensions":["ova"]},"application/x-virtualbox-ovf":{"compressible":true,"extensions":["ovf"]},"application/x-virtualbox-vbox":{"compressible":true,"extensions":["vbox"]},"application/x-virtualbox-vbox-extpack":{"compressible":false,"extensions":["vbox-extpack"]},"application/x-virtualbox-vdi":{"compressible":true,"extensions":["vdi"]},"application/x-virtualbox-vhd":{"compressible":true,"extensions":["vhd"]},"application/x-virtualbox-vmdk":{"compressible":true,"extensions":["vmdk"]},"application/x-wais-source":{"source":"apache","extensions":["src"]},"application/x-web-app-manifest+json":{"compressible":true,"extensions":["webapp"]},"application/x-www-form-urlencoded":{"source":"iana","compressible":true},"application/x-x509-ca-cert":{"source":"iana","extensions":["der","crt","pem"]},"application/x-x509-ca-ra-cert":{"source":"iana"},"application/x-x509-next-ca-cert":{"source":"iana"},"application/x-xfig":{"source":"apache","extensions":["fig"]},"application/x-xliff+xml":{"source":"apache","compressible":true,"extensions":["xlf"]},"application/x-xpinstall":{"source":"apache","compressible":false,"extensions":["xpi"]},"application/x-xz":{"source":"apache","extensions":["xz"]},"application/x-zmachine":{"source":"apache","extensions":["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/x400-bp":{"source":"iana"},"application/xacml+xml":{"source":"iana","compressible":true},"application/xaml+xml":{"source":"apache","compressible":true,"extensions":["xaml"]},"application/xcap-att+xml":{"source":"iana","compressible":true,"extensions":["xav"]},"application/xcap-caps+xml":{"source":"iana","compressible":true,"extensions":["xca"]},"application/xcap-diff+xml":{"source":"iana","compressible":true,"extensions":["xdf"]},"application/xcap-el+xml":{"source":"iana","compressible":true,"extensions":["xel"]},"application/xcap-error+xml":{"source":"iana","compressible":true},"application/xcap-ns+xml":{"source":"iana","compressible":true,"extensions":["xns"]},"application/xcon-conference-info+xml":{"source":"iana","compressible":true},"application/xcon-conference-info-diff+xml":{"source":"iana","compressible":true},"application/xenc+xml":{"source":"iana","compressible":true,"extensions":["xenc"]},"application/xhtml+xml":{"source":"iana","compressible":true,"extensions":["xhtml","xht"]},"application/xhtml-voice+xml":{"source":"apache","compressible":true},"application/xliff+xml":{"source":"iana","compressible":true,"extensions":["xlf"]},"application/xml":{"source":"iana","compressible":true,"extensions":["xml","xsl","xsd","rng"]},"application/xml-dtd":{"source":"iana","compressible":true,"extensions":["dtd"]},"application/xml-external-parsed-entity":{"source":"iana"},"application/xml-patch+xml":{"source":"iana","compressible":true},"application/xmpp+xml":{"source":"iana","compressible":true},"application/xop+xml":{"source":"iana","compressible":true,"extensions":["xop"]},"application/xproc+xml":{"source":"apache","compressible":true,"extensions":["xpl"]},"application/xslt+xml":{"source":"iana","compressible":true,"extensions":["xsl","xslt"]},"application/xspf+xml":{"source":"apache","compressible":true,"extensions":["xspf"]},"application/xv+xml":{"source":"iana","compressible":true,"extensions":["mxml","xhvml","xvml","xvm"]},"application/yang":{"source":"iana","extensions":["yang"]},"application/yang-data+json":{"source":"iana","compressible":true},"application/yang-data+xml":{"source":"iana","compressible":true},"application/yang-patch+json":{"source":"iana","compressible":true},"application/yang-patch+xml":{"source":"iana","compressible":true},"application/yin+xml":{"source":"iana","compressible":true,"extensions":["yin"]},"application/zip":{"source":"iana","compressible":false,"extensions":["zip"]},"application/zlib":{"source":"iana"},"application/zstd":{"source":"iana"},"audio/1d-interleaved-parityfec":{"source":"iana"},"audio/32kadpcm":{"source":"iana"},"audio/3gpp":{"source":"iana","compressible":false,"extensions":["3gpp"]},"audio/3gpp2":{"source":"iana"},"audio/aac":{"source":"iana"},"audio/ac3":{"source":"iana"},"audio/adpcm":{"source":"apache","extensions":["adp"]},"audio/amr":{"source":"iana","extensions":["amr"]},"audio/amr-wb":{"source":"iana"},"audio/amr-wb+":{"source":"iana"},"audio/aptx":{"source":"iana"},"audio/asc":{"source":"iana"},"audio/atrac-advanced-lossless":{"source":"iana"},"audio/atrac-x":{"source":"iana"},"audio/atrac3":{"source":"iana"},"audio/basic":{"source":"iana","compressible":false,"extensions":["au","snd"]},"audio/bv16":{"source":"iana"},"audio/bv32":{"source":"iana"},"audio/clearmode":{"source":"iana"},"audio/cn":{"source":"iana"},"audio/dat12":{"source":"iana"},"audio/dls":{"source":"iana"},"audio/dsr-es201108":{"source":"iana"},"audio/dsr-es202050":{"source":"iana"},"audio/dsr-es202211":{"source":"iana"},"audio/dsr-es202212":{"source":"iana"},"audio/dv":{"source":"iana"},"audio/dvi4":{"source":"iana"},"audio/eac3":{"source":"iana"},"audio/encaprtp":{"source":"iana"},"audio/evrc":{"source":"iana"},"audio/evrc-qcp":{"source":"iana"},"audio/evrc0":{"source":"iana"},"audio/evrc1":{"source":"iana"},"audio/evrcb":{"source":"iana"},"audio/evrcb0":{"source":"iana"},"audio/evrcb1":{"source":"iana"},"audio/evrcnw":{"source":"iana"},"audio/evrcnw0":{"source":"iana"},"audio/evrcnw1":{"source":"iana"},"audio/evrcwb":{"source":"iana"},"audio/evrcwb0":{"source":"iana"},"audio/evrcwb1":{"source":"iana"},"audio/evs":{"source":"iana"},"audio/flexfec":{"source":"iana"},"audio/fwdred":{"source":"iana"},"audio/g711-0":{"source":"iana"},"audio/g719":{"source":"iana"},"audio/g722":{"source":"iana"},"audio/g7221":{"source":"iana"},"audio/g723":{"source":"iana"},"audio/g726-16":{"source":"iana"},"audio/g726-24":{"source":"iana"},"audio/g726-32":{"source":"iana"},"audio/g726-40":{"source":"iana"},"audio/g728":{"source":"iana"},"audio/g729":{"source":"iana"},"audio/g7291":{"source":"iana"},"audio/g729d":{"source":"iana"},"audio/g729e":{"source":"iana"},"audio/gsm":{"source":"iana"},"audio/gsm-efr":{"source":"iana"},"audio/gsm-hr-08":{"source":"iana"},"audio/ilbc":{"source":"iana"},"audio/ip-mr_v2.5":{"source":"iana"},"audio/isac":{"source":"apache"},"audio/l16":{"source":"iana"},"audio/l20":{"source":"iana"},"audio/l24":{"source":"iana","compressible":false},"audio/l8":{"source":"iana"},"audio/lpc":{"source":"iana"},"audio/melp":{"source":"iana"},"audio/melp1200":{"source":"iana"},"audio/melp2400":{"source":"iana"},"audio/melp600":{"source":"iana"},"audio/mhas":{"source":"iana"},"audio/midi":{"source":"apache","extensions":["mid","midi","kar","rmi"]},"audio/mobile-xmf":{"source":"iana","extensions":["mxmf"]},"audio/mp3":{"compressible":false,"extensions":["mp3"]},"audio/mp4":{"source":"iana","compressible":false,"extensions":["m4a","mp4a"]},"audio/mp4a-latm":{"source":"iana"},"audio/mpa":{"source":"iana"},"audio/mpa-robust":{"source":"iana"},"audio/mpeg":{"source":"iana","compressible":false,"extensions":["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/mpeg4-generic":{"source":"iana"},"audio/musepack":{"source":"apache"},"audio/ogg":{"source":"iana","compressible":false,"extensions":["oga","ogg","spx","opus"]},"audio/opus":{"source":"iana"},"audio/parityfec":{"source":"iana"},"audio/pcma":{"source":"iana"},"audio/pcma-wb":{"source":"iana"},"audio/pcmu":{"source":"iana"},"audio/pcmu-wb":{"source":"iana"},"audio/prs.sid":{"source":"iana"},"audio/qcelp":{"source":"iana"},"audio/raptorfec":{"source":"iana"},"audio/red":{"source":"iana"},"audio/rtp-enc-aescm128":{"source":"iana"},"audio/rtp-midi":{"source":"iana"},"audio/rtploopback":{"source":"iana"},"audio/rtx":{"source":"iana"},"audio/s3m":{"source":"apache","extensions":["s3m"]},"audio/scip":{"source":"iana"},"audio/silk":{"source":"apache","extensions":["sil"]},"audio/smv":{"source":"iana"},"audio/smv-qcp":{"source":"iana"},"audio/smv0":{"source":"iana"},"audio/sofa":{"source":"iana"},"audio/sp-midi":{"source":"iana"},"audio/speex":{"source":"iana"},"audio/t140c":{"source":"iana"},"audio/t38":{"source":"iana"},"audio/telephone-event":{"source":"iana"},"audio/tetra_acelp":{"source":"iana"},"audio/tetra_acelp_bb":{"source":"iana"},"audio/tone":{"source":"iana"},"audio/tsvcis":{"source":"iana"},"audio/uemclip":{"source":"iana"},"audio/ulpfec":{"source":"iana"},"audio/usac":{"source":"iana"},"audio/vdvi":{"source":"iana"},"audio/vmr-wb":{"source":"iana"},"audio/vnd.3gpp.iufp":{"source":"iana"},"audio/vnd.4sb":{"source":"iana"},"audio/vnd.audiokoz":{"source":"iana"},"audio/vnd.celp":{"source":"iana"},"audio/vnd.cisco.nse":{"source":"iana"},"audio/vnd.cmles.radio-events":{"source":"iana"},"audio/vnd.cns.anp1":{"source":"iana"},"audio/vnd.cns.inf1":{"source":"iana"},"audio/vnd.dece.audio":{"source":"iana","extensions":["uva","uvva"]},"audio/vnd.digital-winds":{"source":"iana","extensions":["eol"]},"audio/vnd.dlna.adts":{"source":"iana"},"audio/vnd.dolby.heaac.1":{"source":"iana"},"audio/vnd.dolby.heaac.2":{"source":"iana"},"audio/vnd.dolby.mlp":{"source":"iana"},"audio/vnd.dolby.mps":{"source":"iana"},"audio/vnd.dolby.pl2":{"source":"iana"},"audio/vnd.dolby.pl2x":{"source":"iana"},"audio/vnd.dolby.pl2z":{"source":"iana"},"audio/vnd.dolby.pulse.1":{"source":"iana"},"audio/vnd.dra":{"source":"iana","extensions":["dra"]},"audio/vnd.dts":{"source":"iana","extensions":["dts"]},"audio/vnd.dts.hd":{"source":"iana","extensions":["dtshd"]},"audio/vnd.dts.uhd":{"source":"iana"},"audio/vnd.dvb.file":{"source":"iana"},"audio/vnd.everad.plj":{"source":"iana"},"audio/vnd.hns.audio":{"source":"iana"},"audio/vnd.lucent.voice":{"source":"iana","extensions":["lvp"]},"audio/vnd.ms-playready.media.pya":{"source":"iana","extensions":["pya"]},"audio/vnd.nokia.mobile-xmf":{"source":"iana"},"audio/vnd.nortel.vbk":{"source":"iana"},"audio/vnd.nuera.ecelp4800":{"source":"iana","extensions":["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{"source":"iana","extensions":["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{"source":"iana","extensions":["ecelp9600"]},"audio/vnd.octel.sbc":{"source":"iana"},"audio/vnd.presonus.multitrack":{"source":"iana"},"audio/vnd.qcelp":{"source":"iana"},"audio/vnd.rhetorex.32kadpcm":{"source":"iana"},"audio/vnd.rip":{"source":"iana","extensions":["rip"]},"audio/vnd.rn-realaudio":{"compressible":false},"audio/vnd.sealedmedia.softseal.mpeg":{"source":"iana"},"audio/vnd.vmx.cvsd":{"source":"iana"},"audio/vnd.wave":{"compressible":false},"audio/vorbis":{"source":"iana","compressible":false},"audio/vorbis-config":{"source":"iana"},"audio/wav":{"compressible":false,"extensions":["wav"]},"audio/wave":{"compressible":false,"extensions":["wav"]},"audio/webm":{"source":"apache","compressible":false,"extensions":["weba"]},"audio/x-aac":{"source":"apache","compressible":false,"extensions":["aac"]},"audio/x-aiff":{"source":"apache","extensions":["aif","aiff","aifc"]},"audio/x-caf":{"source":"apache","compressible":false,"extensions":["caf"]},"audio/x-flac":{"source":"apache","extensions":["flac"]},"audio/x-m4a":{"source":"nginx","extensions":["m4a"]},"audio/x-matroska":{"source":"apache","extensions":["mka"]},"audio/x-mpegurl":{"source":"apache","extensions":["m3u"]},"audio/x-ms-wax":{"source":"apache","extensions":["wax"]},"audio/x-ms-wma":{"source":"apache","extensions":["wma"]},"audio/x-pn-realaudio":{"source":"apache","extensions":["ram","ra"]},"audio/x-pn-realaudio-plugin":{"source":"apache","extensions":["rmp"]},"audio/x-realaudio":{"source":"nginx","extensions":["ra"]},"audio/x-tta":{"source":"apache"},"audio/x-wav":{"source":"apache","extensions":["wav"]},"audio/xm":{"source":"apache","extensions":["xm"]},"chemical/x-cdx":{"source":"apache","extensions":["cdx"]},"chemical/x-cif":{"source":"apache","extensions":["cif"]},"chemical/x-cmdf":{"source":"apache","extensions":["cmdf"]},"chemical/x-cml":{"source":"apache","extensions":["cml"]},"chemical/x-csml":{"source":"apache","extensions":["csml"]},"chemical/x-pdb":{"source":"apache"},"chemical/x-xyz":{"source":"apache","extensions":["xyz"]},"font/collection":{"source":"iana","extensions":["ttc"]},"font/otf":{"source":"iana","compressible":true,"extensions":["otf"]},"font/sfnt":{"source":"iana"},"font/ttf":{"source":"iana","compressible":true,"extensions":["ttf"]},"font/woff":{"source":"iana","extensions":["woff"]},"font/woff2":{"source":"iana","extensions":["woff2"]},"image/aces":{"source":"iana","extensions":["exr"]},"image/apng":{"compressible":false,"extensions":["apng"]},"image/avci":{"source":"iana","extensions":["avci"]},"image/avcs":{"source":"iana","extensions":["avcs"]},"image/avif":{"source":"iana","compressible":false,"extensions":["avif"]},"image/bmp":{"source":"iana","compressible":true,"extensions":["bmp"]},"image/cgm":{"source":"iana","extensions":["cgm"]},"image/dicom-rle":{"source":"iana","extensions":["drle"]},"image/emf":{"source":"iana","extensions":["emf"]},"image/fits":{"source":"iana","extensions":["fits"]},"image/g3fax":{"source":"iana","extensions":["g3"]},"image/gif":{"source":"iana","compressible":false,"extensions":["gif"]},"image/heic":{"source":"iana","extensions":["heic"]},"image/heic-sequence":{"source":"iana","extensions":["heics"]},"image/heif":{"source":"iana","extensions":["heif"]},"image/heif-sequence":{"source":"iana","extensions":["heifs"]},"image/hej2k":{"source":"iana","extensions":["hej2"]},"image/hsj2":{"source":"iana","extensions":["hsj2"]},"image/ief":{"source":"iana","extensions":["ief"]},"image/jls":{"source":"iana","extensions":["jls"]},"image/jp2":{"source":"iana","compressible":false,"extensions":["jp2","jpg2"]},"image/jpeg":{"source":"iana","compressible":false,"extensions":["jpeg","jpg","jpe"]},"image/jph":{"source":"iana","extensions":["jph"]},"image/jphc":{"source":"iana","extensions":["jhc"]},"image/jpm":{"source":"iana","compressible":false,"extensions":["jpm"]},"image/jpx":{"source":"iana","compressible":false,"extensions":["jpx","jpf"]},"image/jxr":{"source":"iana","extensions":["jxr"]},"image/jxra":{"source":"iana","extensions":["jxra"]},"image/jxrs":{"source":"iana","extensions":["jxrs"]},"image/jxs":{"source":"iana","extensions":["jxs"]},"image/jxsc":{"source":"iana","extensions":["jxsc"]},"image/jxsi":{"source":"iana","extensions":["jxsi"]},"image/jxss":{"source":"iana","extensions":["jxss"]},"image/ktx":{"source":"iana","extensions":["ktx"]},"image/ktx2":{"source":"iana","extensions":["ktx2"]},"image/naplps":{"source":"iana"},"image/pjpeg":{"compressible":false},"image/png":{"source":"iana","compressible":false,"extensions":["png"]},"image/prs.btif":{"source":"iana","extensions":["btif"]},"image/prs.pti":{"source":"iana","extensions":["pti"]},"image/pwg-raster":{"source":"iana"},"image/sgi":{"source":"apache","extensions":["sgi"]},"image/svg+xml":{"source":"iana","compressible":true,"extensions":["svg","svgz"]},"image/t38":{"source":"iana","extensions":["t38"]},"image/tiff":{"source":"iana","compressible":false,"extensions":["tif","tiff"]},"image/tiff-fx":{"source":"iana","extensions":["tfx"]},"image/vnd.adobe.photoshop":{"source":"iana","compressible":true,"extensions":["psd"]},"image/vnd.airzip.accelerator.azv":{"source":"iana","extensions":["azv"]},"image/vnd.cns.inf2":{"source":"iana"},"image/vnd.dece.graphic":{"source":"iana","extensions":["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{"source":"iana","extensions":["djvu","djv"]},"image/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"image/vnd.dwg":{"source":"iana","extensions":["dwg"]},"image/vnd.dxf":{"source":"iana","extensions":["dxf"]},"image/vnd.fastbidsheet":{"source":"iana","extensions":["fbs"]},"image/vnd.fpx":{"source":"iana","extensions":["fpx"]},"image/vnd.fst":{"source":"iana","extensions":["fst"]},"image/vnd.fujixerox.edmics-mmr":{"source":"iana","extensions":["mmr"]},"image/vnd.fujixerox.edmics-rlc":{"source":"iana","extensions":["rlc"]},"image/vnd.globalgraphics.pgb":{"source":"iana"},"image/vnd.microsoft.icon":{"source":"iana","compressible":true,"extensions":["ico"]},"image/vnd.mix":{"source":"iana"},"image/vnd.mozilla.apng":{"source":"iana"},"image/vnd.ms-dds":{"compressible":true,"extensions":["dds"]},"image/vnd.ms-modi":{"source":"iana","extensions":["mdi"]},"image/vnd.ms-photo":{"source":"apache","extensions":["wdp"]},"image/vnd.net-fpx":{"source":"iana","extensions":["npx"]},"image/vnd.pco.b16":{"source":"iana","extensions":["b16"]},"image/vnd.radiance":{"source":"iana"},"image/vnd.sealed.png":{"source":"iana"},"image/vnd.sealedmedia.softseal.gif":{"source":"iana"},"image/vnd.sealedmedia.softseal.jpg":{"source":"iana"},"image/vnd.svf":{"source":"iana"},"image/vnd.tencent.tap":{"source":"iana","extensions":["tap"]},"image/vnd.valve.source.texture":{"source":"iana","extensions":["vtf"]},"image/vnd.wap.wbmp":{"source":"iana","extensions":["wbmp"]},"image/vnd.xiff":{"source":"iana","extensions":["xif"]},"image/vnd.zbrush.pcx":{"source":"iana","extensions":["pcx"]},"image/webp":{"source":"apache","extensions":["webp"]},"image/wmf":{"source":"iana","extensions":["wmf"]},"image/x-3ds":{"source":"apache","extensions":["3ds"]},"image/x-cmu-raster":{"source":"apache","extensions":["ras"]},"image/x-cmx":{"source":"apache","extensions":["cmx"]},"image/x-freehand":{"source":"apache","extensions":["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{"source":"apache","compressible":true,"extensions":["ico"]},"image/x-jng":{"source":"nginx","extensions":["jng"]},"image/x-mrsid-image":{"source":"apache","extensions":["sid"]},"image/x-ms-bmp":{"source":"nginx","compressible":true,"extensions":["bmp"]},"image/x-pcx":{"source":"apache","extensions":["pcx"]},"image/x-pict":{"source":"apache","extensions":["pic","pct"]},"image/x-portable-anymap":{"source":"apache","extensions":["pnm"]},"image/x-portable-bitmap":{"source":"apache","extensions":["pbm"]},"image/x-portable-graymap":{"source":"apache","extensions":["pgm"]},"image/x-portable-pixmap":{"source":"apache","extensions":["ppm"]},"image/x-rgb":{"source":"apache","extensions":["rgb"]},"image/x-tga":{"source":"apache","extensions":["tga"]},"image/x-xbitmap":{"source":"apache","extensions":["xbm"]},"image/x-xcf":{"compressible":false},"image/x-xpixmap":{"source":"apache","extensions":["xpm"]},"image/x-xwindowdump":{"source":"apache","extensions":["xwd"]},"message/cpim":{"source":"iana"},"message/delivery-status":{"source":"iana"},"message/disposition-notification":{"source":"iana","extensions":["disposition-notification"]},"message/external-body":{"source":"iana"},"message/feedback-report":{"source":"iana"},"message/global":{"source":"iana","extensions":["u8msg"]},"message/global-delivery-status":{"source":"iana","extensions":["u8dsn"]},"message/global-disposition-notification":{"source":"iana","extensions":["u8mdn"]},"message/global-headers":{"source":"iana","extensions":["u8hdr"]},"message/http":{"source":"iana","compressible":false},"message/imdn+xml":{"source":"iana","compressible":true},"message/news":{"source":"iana"},"message/partial":{"source":"iana","compressible":false},"message/rfc822":{"source":"iana","compressible":true,"extensions":["eml","mime"]},"message/s-http":{"source":"iana"},"message/sip":{"source":"iana"},"message/sipfrag":{"source":"iana"},"message/tracking-status":{"source":"iana"},"message/vnd.si.simp":{"source":"iana"},"message/vnd.wfa.wsc":{"source":"iana","extensions":["wsc"]},"model/3mf":{"source":"iana","extensions":["3mf"]},"model/e57":{"source":"iana"},"model/gltf+json":{"source":"iana","compressible":true,"extensions":["gltf"]},"model/gltf-binary":{"source":"iana","compressible":true,"extensions":["glb"]},"model/iges":{"source":"iana","compressible":false,"extensions":["igs","iges"]},"model/mesh":{"source":"iana","compressible":false,"extensions":["msh","mesh","silo"]},"model/mtl":{"source":"iana","extensions":["mtl"]},"model/obj":{"source":"iana","extensions":["obj"]},"model/step":{"source":"iana"},"model/step+xml":{"source":"iana","compressible":true,"extensions":["stpx"]},"model/step+zip":{"source":"iana","compressible":false,"extensions":["stpz"]},"model/step-xml+zip":{"source":"iana","compressible":false,"extensions":["stpxz"]},"model/stl":{"source":"iana","extensions":["stl"]},"model/vnd.collada+xml":{"source":"iana","compressible":true,"extensions":["dae"]},"model/vnd.dwf":{"source":"iana","extensions":["dwf"]},"model/vnd.flatland.3dml":{"source":"iana"},"model/vnd.gdl":{"source":"iana","extensions":["gdl"]},"model/vnd.gs-gdl":{"source":"apache"},"model/vnd.gs.gdl":{"source":"iana"},"model/vnd.gtw":{"source":"iana","extensions":["gtw"]},"model/vnd.moml+xml":{"source":"iana","compressible":true},"model/vnd.mts":{"source":"iana","extensions":["mts"]},"model/vnd.opengex":{"source":"iana","extensions":["ogex"]},"model/vnd.parasolid.transmit.binary":{"source":"iana","extensions":["x_b"]},"model/vnd.parasolid.transmit.text":{"source":"iana","extensions":["x_t"]},"model/vnd.pytha.pyox":{"source":"iana"},"model/vnd.rosette.annotated-data-model":{"source":"iana"},"model/vnd.sap.vds":{"source":"iana","extensions":["vds"]},"model/vnd.usdz+zip":{"source":"iana","compressible":false,"extensions":["usdz"]},"model/vnd.valve.source.compiled-map":{"source":"iana","extensions":["bsp"]},"model/vnd.vtu":{"source":"iana","extensions":["vtu"]},"model/vrml":{"source":"iana","compressible":false,"extensions":["wrl","vrml"]},"model/x3d+binary":{"source":"apache","compressible":false,"extensions":["x3db","x3dbz"]},"model/x3d+fastinfoset":{"source":"iana","extensions":["x3db"]},"model/x3d+vrml":{"source":"apache","compressible":false,"extensions":["x3dv","x3dvz"]},"model/x3d+xml":{"source":"iana","compressible":true,"extensions":["x3d","x3dz"]},"model/x3d-vrml":{"source":"iana","extensions":["x3dv"]},"multipart/alternative":{"source":"iana","compressible":false},"multipart/appledouble":{"source":"iana"},"multipart/byteranges":{"source":"iana"},"multipart/digest":{"source":"iana"},"multipart/encrypted":{"source":"iana","compressible":false},"multipart/form-data":{"source":"iana","compressible":false},"multipart/header-set":{"source":"iana"},"multipart/mixed":{"source":"iana"},"multipart/multilingual":{"source":"iana"},"multipart/parallel":{"source":"iana"},"multipart/related":{"source":"iana","compressible":false},"multipart/report":{"source":"iana"},"multipart/signed":{"source":"iana","compressible":false},"multipart/vnd.bint.med-plus":{"source":"iana"},"multipart/voice-message":{"source":"iana"},"multipart/x-mixed-replace":{"source":"iana"},"text/1d-interleaved-parityfec":{"source":"iana"},"text/cache-manifest":{"source":"iana","compressible":true,"extensions":["appcache","manifest"]},"text/calendar":{"source":"iana","extensions":["ics","ifb"]},"text/calender":{"compressible":true},"text/cmd":{"compressible":true},"text/coffeescript":{"extensions":["coffee","litcoffee"]},"text/cql":{"source":"iana"},"text/cql-expression":{"source":"iana"},"text/cql-identifier":{"source":"iana"},"text/css":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["css"]},"text/csv":{"source":"iana","compressible":true,"extensions":["csv"]},"text/csv-schema":{"source":"iana"},"text/directory":{"source":"iana"},"text/dns":{"source":"iana"},"text/ecmascript":{"source":"iana"},"text/encaprtp":{"source":"iana"},"text/enriched":{"source":"iana"},"text/fhirpath":{"source":"iana"},"text/flexfec":{"source":"iana"},"text/fwdred":{"source":"iana"},"text/gff3":{"source":"iana"},"text/grammar-ref-list":{"source":"iana"},"text/html":{"source":"iana","compressible":true,"extensions":["html","htm","shtml"]},"text/jade":{"extensions":["jade"]},"text/javascript":{"source":"iana","compressible":true},"text/jcr-cnd":{"source":"iana"},"text/jsx":{"compressible":true,"extensions":["jsx"]},"text/less":{"compressible":true,"extensions":["less"]},"text/markdown":{"source":"iana","compressible":true,"extensions":["markdown","md"]},"text/mathml":{"source":"nginx","extensions":["mml"]},"text/mdx":{"compressible":true,"extensions":["mdx"]},"text/mizar":{"source":"iana"},"text/n3":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["n3"]},"text/parameters":{"source":"iana","charset":"UTF-8"},"text/parityfec":{"source":"iana"},"text/plain":{"source":"iana","compressible":true,"extensions":["txt","text","conf","def","list","log","in","ini"]},"text/provenance-notation":{"source":"iana","charset":"UTF-8"},"text/prs.fallenstein.rst":{"source":"iana"},"text/prs.lines.tag":{"source":"iana","extensions":["dsc"]},"text/prs.prop.logic":{"source":"iana"},"text/raptorfec":{"source":"iana"},"text/red":{"source":"iana"},"text/rfc822-headers":{"source":"iana"},"text/richtext":{"source":"iana","compressible":true,"extensions":["rtx"]},"text/rtf":{"source":"iana","compressible":true,"extensions":["rtf"]},"text/rtp-enc-aescm128":{"source":"iana"},"text/rtploopback":{"source":"iana"},"text/rtx":{"source":"iana"},"text/sgml":{"source":"iana","extensions":["sgml","sgm"]},"text/shaclc":{"source":"iana"},"text/shex":{"source":"iana","extensions":["shex"]},"text/slim":{"extensions":["slim","slm"]},"text/spdx":{"source":"iana","extensions":["spdx"]},"text/strings":{"source":"iana"},"text/stylus":{"extensions":["stylus","styl"]},"text/t140":{"source":"iana"},"text/tab-separated-values":{"source":"iana","compressible":true,"extensions":["tsv"]},"text/troff":{"source":"iana","extensions":["t","tr","roff","man","me","ms"]},"text/turtle":{"source":"iana","charset":"UTF-8","extensions":["ttl"]},"text/ulpfec":{"source":"iana"},"text/uri-list":{"source":"iana","compressible":true,"extensions":["uri","uris","urls"]},"text/vcard":{"source":"iana","compressible":true,"extensions":["vcard"]},"text/vnd.a":{"source":"iana"},"text/vnd.abc":{"source":"iana"},"text/vnd.ascii-art":{"source":"iana"},"text/vnd.curl":{"source":"iana","extensions":["curl"]},"text/vnd.curl.dcurl":{"source":"apache","extensions":["dcurl"]},"text/vnd.curl.mcurl":{"source":"apache","extensions":["mcurl"]},"text/vnd.curl.scurl":{"source":"apache","extensions":["scurl"]},"text/vnd.debian.copyright":{"source":"iana","charset":"UTF-8"},"text/vnd.dmclientscript":{"source":"iana"},"text/vnd.dvb.subtitle":{"source":"iana","extensions":["sub"]},"text/vnd.esmertec.theme-descriptor":{"source":"iana","charset":"UTF-8"},"text/vnd.familysearch.gedcom":{"source":"iana","extensions":["ged"]},"text/vnd.ficlab.flt":{"source":"iana"},"text/vnd.fly":{"source":"iana","extensions":["fly"]},"text/vnd.fmi.flexstor":{"source":"iana","extensions":["flx"]},"text/vnd.gml":{"source":"iana"},"text/vnd.graphviz":{"source":"iana","extensions":["gv"]},"text/vnd.hans":{"source":"iana"},"text/vnd.hgl":{"source":"iana"},"text/vnd.in3d.3dml":{"source":"iana","extensions":["3dml"]},"text/vnd.in3d.spot":{"source":"iana","extensions":["spot"]},"text/vnd.iptc.newsml":{"source":"iana"},"text/vnd.iptc.nitf":{"source":"iana"},"text/vnd.latex-z":{"source":"iana"},"text/vnd.motorola.reflex":{"source":"iana"},"text/vnd.ms-mediapackage":{"source":"iana"},"text/vnd.net2phone.commcenter.command":{"source":"iana"},"text/vnd.radisys.msml-basic-layout":{"source":"iana"},"text/vnd.senx.warpscript":{"source":"iana"},"text/vnd.si.uricatalogue":{"source":"iana"},"text/vnd.sosi":{"source":"iana"},"text/vnd.sun.j2me.app-descriptor":{"source":"iana","charset":"UTF-8","extensions":["jad"]},"text/vnd.trolltech.linguist":{"source":"iana","charset":"UTF-8"},"text/vnd.wap.si":{"source":"iana"},"text/vnd.wap.sl":{"source":"iana"},"text/vnd.wap.wml":{"source":"iana","extensions":["wml"]},"text/vnd.wap.wmlscript":{"source":"iana","extensions":["wmls"]},"text/vtt":{"source":"iana","charset":"UTF-8","compressible":true,"extensions":["vtt"]},"text/x-asm":{"source":"apache","extensions":["s","asm"]},"text/x-c":{"source":"apache","extensions":["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{"source":"nginx","extensions":["htc"]},"text/x-fortran":{"source":"apache","extensions":["f","for","f77","f90"]},"text/x-gwt-rpc":{"compressible":true},"text/x-handlebars-template":{"extensions":["hbs"]},"text/x-java-source":{"source":"apache","extensions":["java"]},"text/x-jquery-tmpl":{"compressible":true},"text/x-lua":{"extensions":["lua"]},"text/x-markdown":{"compressible":true,"extensions":["mkd"]},"text/x-nfo":{"source":"apache","extensions":["nfo"]},"text/x-opml":{"source":"apache","extensions":["opml"]},"text/x-org":{"compressible":true,"extensions":["org"]},"text/x-pascal":{"source":"apache","extensions":["p","pas"]},"text/x-processing":{"compressible":true,"extensions":["pde"]},"text/x-sass":{"extensions":["sass"]},"text/x-scss":{"extensions":["scss"]},"text/x-setext":{"source":"apache","extensions":["etx"]},"text/x-sfv":{"source":"apache","extensions":["sfv"]},"text/x-suse-ymp":{"compressible":true,"extensions":["ymp"]},"text/x-uuencode":{"source":"apache","extensions":["uu"]},"text/x-vcalendar":{"source":"apache","extensions":["vcs"]},"text/x-vcard":{"source":"apache","extensions":["vcf"]},"text/xml":{"source":"iana","compressible":true,"extensions":["xml"]},"text/xml-external-parsed-entity":{"source":"iana"},"text/yaml":{"compressible":true,"extensions":["yaml","yml"]},"video/1d-interleaved-parityfec":{"source":"iana"},"video/3gpp":{"source":"iana","extensions":["3gp","3gpp"]},"video/3gpp-tt":{"source":"iana"},"video/3gpp2":{"source":"iana","extensions":["3g2"]},"video/av1":{"source":"iana"},"video/bmpeg":{"source":"iana"},"video/bt656":{"source":"iana"},"video/celb":{"source":"iana"},"video/dv":{"source":"iana"},"video/encaprtp":{"source":"iana"},"video/ffv1":{"source":"iana"},"video/flexfec":{"source":"iana"},"video/h261":{"source":"iana","extensions":["h261"]},"video/h263":{"source":"iana","extensions":["h263"]},"video/h263-1998":{"source":"iana"},"video/h263-2000":{"source":"iana"},"video/h264":{"source":"iana","extensions":["h264"]},"video/h264-rcdo":{"source":"iana"},"video/h264-svc":{"source":"iana"},"video/h265":{"source":"iana"},"video/iso.segment":{"source":"iana","extensions":["m4s"]},"video/jpeg":{"source":"iana","extensions":["jpgv"]},"video/jpeg2000":{"source":"iana"},"video/jpm":{"source":"apache","extensions":["jpm","jpgm"]},"video/jxsv":{"source":"iana"},"video/mj2":{"source":"iana","extensions":["mj2","mjp2"]},"video/mp1s":{"source":"iana"},"video/mp2p":{"source":"iana"},"video/mp2t":{"source":"iana","extensions":["ts"]},"video/mp4":{"source":"iana","compressible":false,"extensions":["mp4","mp4v","mpg4"]},"video/mp4v-es":{"source":"iana"},"video/mpeg":{"source":"iana","compressible":false,"extensions":["mpeg","mpg","mpe","m1v","m2v"]},"video/mpeg4-generic":{"source":"iana"},"video/mpv":{"source":"iana"},"video/nv":{"source":"iana"},"video/ogg":{"source":"iana","compressible":false,"extensions":["ogv"]},"video/parityfec":{"source":"iana"},"video/pointer":{"source":"iana"},"video/quicktime":{"source":"iana","compressible":false,"extensions":["qt","mov"]},"video/raptorfec":{"source":"iana"},"video/raw":{"source":"iana"},"video/rtp-enc-aescm128":{"source":"iana"},"video/rtploopback":{"source":"iana"},"video/rtx":{"source":"iana"},"video/scip":{"source":"iana"},"video/smpte291":{"source":"iana"},"video/smpte292m":{"source":"iana"},"video/ulpfec":{"source":"iana"},"video/vc1":{"source":"iana"},"video/vc2":{"source":"iana"},"video/vnd.cctv":{"source":"iana"},"video/vnd.dece.hd":{"source":"iana","extensions":["uvh","uvvh"]},"video/vnd.dece.mobile":{"source":"iana","extensions":["uvm","uvvm"]},"video/vnd.dece.mp4":{"source":"iana"},"video/vnd.dece.pd":{"source":"iana","extensions":["uvp","uvvp"]},"video/vnd.dece.sd":{"source":"iana","extensions":["uvs","uvvs"]},"video/vnd.dece.video":{"source":"iana","extensions":["uvv","uvvv"]},"video/vnd.directv.mpeg":{"source":"iana"},"video/vnd.directv.mpeg-tts":{"source":"iana"},"video/vnd.dlna.mpeg-tts":{"source":"iana"},"video/vnd.dvb.file":{"source":"iana","extensions":["dvb"]},"video/vnd.fvt":{"source":"iana","extensions":["fvt"]},"video/vnd.hns.video":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.1dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-1010":{"source":"iana"},"video/vnd.iptvforum.2dparityfec-2005":{"source":"iana"},"video/vnd.iptvforum.ttsavc":{"source":"iana"},"video/vnd.iptvforum.ttsmpeg2":{"source":"iana"},"video/vnd.motorola.video":{"source":"iana"},"video/vnd.motorola.videop":{"source":"iana"},"video/vnd.mpegurl":{"source":"iana","extensions":["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{"source":"iana","extensions":["pyv"]},"video/vnd.nokia.interleaved-multimedia":{"source":"iana"},"video/vnd.nokia.mp4vr":{"source":"iana"},"video/vnd.nokia.videovoip":{"source":"iana"},"video/vnd.objectvideo":{"source":"iana"},"video/vnd.radgamettools.bink":{"source":"iana"},"video/vnd.radgamettools.smacker":{"source":"iana"},"video/vnd.sealed.mpeg1":{"source":"iana"},"video/vnd.sealed.mpeg4":{"source":"iana"},"video/vnd.sealed.swf":{"source":"iana"},"video/vnd.sealedmedia.softseal.mov":{"source":"iana"},"video/vnd.uvvu.mp4":{"source":"iana","extensions":["uvu","uvvu"]},"video/vnd.vivo":{"source":"iana","extensions":["viv"]},"video/vnd.youtube.yt":{"source":"iana"},"video/vp8":{"source":"iana"},"video/vp9":{"source":"iana"},"video/webm":{"source":"apache","compressible":false,"extensions":["webm"]},"video/x-f4v":{"source":"apache","extensions":["f4v"]},"video/x-fli":{"source":"apache","extensions":["fli"]},"video/x-flv":{"source":"apache","compressible":false,"extensions":["flv"]},"video/x-m4v":{"source":"apache","extensions":["m4v"]},"video/x-matroska":{"source":"apache","compressible":false,"extensions":["mkv","mk3d","mks"]},"video/x-mng":{"source":"apache","extensions":["mng"]},"video/x-ms-asf":{"source":"apache","extensions":["asf","asx"]},"video/x-ms-vob":{"source":"apache","extensions":["vob"]},"video/x-ms-wm":{"source":"apache","extensions":["wm"]},"video/x-ms-wmv":{"source":"apache","compressible":false,"extensions":["wmv"]},"video/x-ms-wmx":{"source":"apache","extensions":["wmx"]},"video/x-ms-wvx":{"source":"apache","extensions":["wvx"]},"video/x-msvideo":{"source":"apache","extensions":["avi"]},"video/x-sgi-movie":{"source":"apache","extensions":["movie"]},"video/x-smv":{"source":"apache","extensions":["smv"]},"x-conference/x-cooltalk":{"source":"apache","extensions":["ice"]},"x-shader/x-fragment":{"compressible":true},"x-shader/x-vertex":{"compressible":true}}'); - -/***/ }), - -/***/ 44784: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"nested":{"Api":{"fields":{"name":{"type":"string","id":1},"methods":{"rule":"repeated","type":"Method","id":2},"options":{"rule":"repeated","type":"Option","id":3},"version":{"type":"string","id":4},"sourceContext":{"type":"SourceContext","id":5},"mixins":{"rule":"repeated","type":"Mixin","id":6},"syntax":{"type":"Syntax","id":7}}},"Method":{"fields":{"name":{"type":"string","id":1},"requestTypeUrl":{"type":"string","id":2},"requestStreaming":{"type":"bool","id":3},"responseTypeUrl":{"type":"string","id":4},"responseStreaming":{"type":"bool","id":5},"options":{"rule":"repeated","type":"Option","id":6},"syntax":{"type":"Syntax","id":7}}},"Mixin":{"fields":{"name":{"type":"string","id":1},"root":{"type":"string","id":2}}},"SourceContext":{"fields":{"fileName":{"type":"string","id":1}}},"Option":{"fields":{"name":{"type":"string","id":1},"value":{"type":"Any","id":2}}},"Syntax":{"values":{"SYNTAX_PROTO2":0,"SYNTAX_PROTO3":1}}}}}}}}'); - -/***/ }), - -/***/ 43571: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"options":{"go_package":"google.golang.org/protobuf/types/descriptorpb","java_package":"com.google.protobuf","java_outer_classname":"DescriptorProtos","csharp_namespace":"Google.Protobuf.Reflection","objc_class_prefix":"GPB","cc_enable_arenas":true,"optimize_for":"SPEED"},"nested":{"FileDescriptorSet":{"edition":"proto2","fields":{"file":{"rule":"repeated","type":"FileDescriptorProto","id":1}},"extensions":[[536000000,536000000]]},"Edition":{"edition":"proto2","values":{"EDITION_UNKNOWN":0,"EDITION_LEGACY":900,"EDITION_PROTO2":998,"EDITION_PROTO3":999,"EDITION_2023":1000,"EDITION_2024":1001,"EDITION_1_TEST_ONLY":1,"EDITION_2_TEST_ONLY":2,"EDITION_99997_TEST_ONLY":99997,"EDITION_99998_TEST_ONLY":99998,"EDITION_99999_TEST_ONLY":99999,"EDITION_MAX":2147483647}},"FileDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"package":{"type":"string","id":2},"dependency":{"rule":"repeated","type":"string","id":3},"publicDependency":{"rule":"repeated","type":"int32","id":10},"weakDependency":{"rule":"repeated","type":"int32","id":11},"optionDependency":{"rule":"repeated","type":"string","id":15},"messageType":{"rule":"repeated","type":"DescriptorProto","id":4},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":5},"service":{"rule":"repeated","type":"ServiceDescriptorProto","id":6},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":7},"options":{"type":"FileOptions","id":8},"sourceCodeInfo":{"type":"SourceCodeInfo","id":9},"syntax":{"type":"string","id":12},"edition":{"type":"Edition","id":14}}},"DescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"field":{"rule":"repeated","type":"FieldDescriptorProto","id":2},"extension":{"rule":"repeated","type":"FieldDescriptorProto","id":6},"nestedType":{"rule":"repeated","type":"DescriptorProto","id":3},"enumType":{"rule":"repeated","type":"EnumDescriptorProto","id":4},"extensionRange":{"rule":"repeated","type":"ExtensionRange","id":5},"oneofDecl":{"rule":"repeated","type":"OneofDescriptorProto","id":8},"options":{"type":"MessageOptions","id":7},"reservedRange":{"rule":"repeated","type":"ReservedRange","id":9},"reservedName":{"rule":"repeated","type":"string","id":10},"visibility":{"type":"SymbolVisibility","id":11}},"nested":{"ExtensionRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2},"options":{"type":"ExtensionRangeOptions","id":3}}},"ReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"ExtensionRangeOptions":{"edition":"proto2","fields":{"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999},"declaration":{"rule":"repeated","type":"Declaration","id":2,"options":{"retention":"RETENTION_SOURCE"}},"features":{"type":"FeatureSet","id":50},"verification":{"type":"VerificationState","id":3,"options":{"default":"UNVERIFIED","retention":"RETENTION_SOURCE"}}},"extensions":[[1000,536870911]],"nested":{"Declaration":{"fields":{"number":{"type":"int32","id":1},"fullName":{"type":"string","id":2},"type":{"type":"string","id":3},"reserved":{"type":"bool","id":5},"repeated":{"type":"bool","id":6}},"reserved":[[4,4]]},"VerificationState":{"values":{"DECLARATION":0,"UNVERIFIED":1}}}},"FieldDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":3},"label":{"type":"Label","id":4},"type":{"type":"Type","id":5},"typeName":{"type":"string","id":6},"extendee":{"type":"string","id":2},"defaultValue":{"type":"string","id":7},"oneofIndex":{"type":"int32","id":9},"jsonName":{"type":"string","id":10},"options":{"type":"FieldOptions","id":8},"proto3Optional":{"type":"bool","id":17}},"nested":{"Type":{"values":{"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Label":{"values":{"LABEL_OPTIONAL":1,"LABEL_REPEATED":3,"LABEL_REQUIRED":2}}}},"OneofDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"options":{"type":"OneofOptions","id":2}}},"EnumDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"value":{"rule":"repeated","type":"EnumValueDescriptorProto","id":2},"options":{"type":"EnumOptions","id":3},"reservedRange":{"rule":"repeated","type":"EnumReservedRange","id":4},"reservedName":{"rule":"repeated","type":"string","id":5},"visibility":{"type":"SymbolVisibility","id":6}},"nested":{"EnumReservedRange":{"fields":{"start":{"type":"int32","id":1},"end":{"type":"int32","id":2}}}}},"EnumValueDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"type":"EnumValueOptions","id":3}}},"ServiceDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"method":{"rule":"repeated","type":"MethodDescriptorProto","id":2},"options":{"type":"ServiceOptions","id":3}}},"MethodDescriptorProto":{"edition":"proto2","fields":{"name":{"type":"string","id":1},"inputType":{"type":"string","id":2},"outputType":{"type":"string","id":3},"options":{"type":"MethodOptions","id":4},"clientStreaming":{"type":"bool","id":5},"serverStreaming":{"type":"bool","id":6}}},"FileOptions":{"edition":"proto2","fields":{"javaPackage":{"type":"string","id":1},"javaOuterClassname":{"type":"string","id":8},"javaMultipleFiles":{"type":"bool","id":10},"javaGenerateEqualsAndHash":{"type":"bool","id":20,"options":{"deprecated":true}},"javaStringCheckUtf8":{"type":"bool","id":27},"optimizeFor":{"type":"OptimizeMode","id":9,"options":{"default":"SPEED"}},"goPackage":{"type":"string","id":11},"ccGenericServices":{"type":"bool","id":16},"javaGenericServices":{"type":"bool","id":17},"pyGenericServices":{"type":"bool","id":18},"deprecated":{"type":"bool","id":23},"ccEnableArenas":{"type":"bool","id":31,"options":{"default":true}},"objcClassPrefix":{"type":"string","id":36},"csharpNamespace":{"type":"string","id":37},"swiftPrefix":{"type":"string","id":39},"phpClassPrefix":{"type":"string","id":40},"phpNamespace":{"type":"string","id":41},"phpMetadataNamespace":{"type":"string","id":44},"rubyPackage":{"type":"string","id":45},"features":{"type":"FeatureSet","id":50},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[42,42],[38,38],"php_generic_services"],"nested":{"OptimizeMode":{"values":{"SPEED":1,"CODE_SIZE":2,"LITE_RUNTIME":3}}}},"MessageOptions":{"edition":"proto2","fields":{"messageSetWireFormat":{"type":"bool","id":1},"noStandardDescriptorAccessor":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3},"mapEntry":{"type":"bool","id":7},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":11,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":12},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[4,4],[5,5],[6,6],[8,8],[9,9]]},"FieldOptions":{"edition":"proto2","fields":{"ctype":{"type":"CType","id":1,"options":{"default":"STRING"}},"packed":{"type":"bool","id":2},"jstype":{"type":"JSType","id":6,"options":{"default":"JS_NORMAL"}},"lazy":{"type":"bool","id":5},"unverifiedLazy":{"type":"bool","id":15},"deprecated":{"type":"bool","id":3},"weak":{"type":"bool","id":10,"options":{"deprecated":true}},"debugRedact":{"type":"bool","id":16},"retention":{"type":"OptionRetention","id":17},"targets":{"rule":"repeated","type":"OptionTargetType","id":19},"editionDefaults":{"rule":"repeated","type":"EditionDefault","id":20},"features":{"type":"FeatureSet","id":21},"featureSupport":{"type":"FeatureSupport","id":22},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[4,4],[18,18]],"nested":{"CType":{"values":{"STRING":0,"CORD":1,"STRING_PIECE":2}},"JSType":{"values":{"JS_NORMAL":0,"JS_STRING":1,"JS_NUMBER":2}},"OptionRetention":{"values":{"RETENTION_UNKNOWN":0,"RETENTION_RUNTIME":1,"RETENTION_SOURCE":2}},"OptionTargetType":{"values":{"TARGET_TYPE_UNKNOWN":0,"TARGET_TYPE_FILE":1,"TARGET_TYPE_EXTENSION_RANGE":2,"TARGET_TYPE_MESSAGE":3,"TARGET_TYPE_FIELD":4,"TARGET_TYPE_ONEOF":5,"TARGET_TYPE_ENUM":6,"TARGET_TYPE_ENUM_ENTRY":7,"TARGET_TYPE_SERVICE":8,"TARGET_TYPE_METHOD":9}},"EditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"value":{"type":"string","id":2}}},"FeatureSupport":{"fields":{"editionIntroduced":{"type":"Edition","id":1},"editionDeprecated":{"type":"Edition","id":2},"deprecationWarning":{"type":"string","id":3},"editionRemoved":{"type":"Edition","id":4}}}}},"OneofOptions":{"edition":"proto2","fields":{"features":{"type":"FeatureSet","id":1},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]]},"EnumOptions":{"edition":"proto2","fields":{"allowAlias":{"type":"bool","id":2},"deprecated":{"type":"bool","id":3},"deprecatedLegacyJsonFieldConflicts":{"type":"bool","id":6,"options":{"deprecated":true}},"features":{"type":"FeatureSet","id":7},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"reserved":[[5,5]]},"EnumValueOptions":{"edition":"proto2","fields":{"deprecated":{"type":"bool","id":1},"features":{"type":"FeatureSet","id":2},"debugRedact":{"type":"bool","id":3},"featureSupport":{"type":"FieldOptions.FeatureSupport","id":4},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]]},"ServiceOptions":{"edition":"proto2","fields":{"features":{"type":"FeatureSet","id":34},"deprecated":{"type":"bool","id":33},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]]},"MethodOptions":{"edition":"proto2","fields":{"deprecated":{"type":"bool","id":33},"idempotencyLevel":{"type":"IdempotencyLevel","id":34,"options":{"default":"IDEMPOTENCY_UNKNOWN"}},"features":{"type":"FeatureSet","id":35},"uninterpretedOption":{"rule":"repeated","type":"UninterpretedOption","id":999}},"extensions":[[1000,536870911]],"nested":{"IdempotencyLevel":{"values":{"IDEMPOTENCY_UNKNOWN":0,"NO_SIDE_EFFECTS":1,"IDEMPOTENT":2}}}},"UninterpretedOption":{"edition":"proto2","fields":{"name":{"rule":"repeated","type":"NamePart","id":2},"identifierValue":{"type":"string","id":3},"positiveIntValue":{"type":"uint64","id":4},"negativeIntValue":{"type":"int64","id":5},"doubleValue":{"type":"double","id":6},"stringValue":{"type":"bytes","id":7},"aggregateValue":{"type":"string","id":8}},"nested":{"NamePart":{"fields":{"namePart":{"rule":"required","type":"string","id":1},"isExtension":{"rule":"required","type":"bool","id":2}}}}},"FeatureSet":{"edition":"proto2","fields":{"fieldPresence":{"type":"FieldPresence","id":1,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_2023","edition_defaults.value":"EXPLICIT"}},"enumType":{"type":"EnumType","id":2,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"OPEN"}},"repeatedFieldEncoding":{"type":"RepeatedFieldEncoding","id":3,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"PACKED"}},"utf8Validation":{"type":"Utf8Validation","id":4,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"VERIFY"}},"messageEncoding":{"type":"MessageEncoding","id":5,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_LEGACY","edition_defaults.value":"LENGTH_PREFIXED"}},"jsonFormat":{"type":"JsonFormat","id":6,"options":{"retention":"RETENTION_RUNTIME","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2023","edition_defaults.edition":"EDITION_PROTO3","edition_defaults.value":"ALLOW"}},"enforceNamingStyle":{"type":"EnforceNamingStyle","id":7,"options":{"retention":"RETENTION_SOURCE","targets":"TARGET_TYPE_METHOD","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"STYLE2024"}},"defaultSymbolVisibility":{"type":"VisibilityFeature.DefaultSymbolVisibility","id":8,"options":{"retention":"RETENTION_SOURCE","targets":"TARGET_TYPE_FILE","feature_support.edition_introduced":"EDITION_2024","edition_defaults.edition":"EDITION_2024","edition_defaults.value":"EXPORT_TOP_LEVEL"}}},"extensions":[[1000,9994],[9995,9999],[10000,10000]],"reserved":[[999,999]],"nested":{"FieldPresence":{"values":{"FIELD_PRESENCE_UNKNOWN":0,"EXPLICIT":1,"IMPLICIT":2,"LEGACY_REQUIRED":3}},"EnumType":{"values":{"ENUM_TYPE_UNKNOWN":0,"OPEN":1,"CLOSED":2}},"RepeatedFieldEncoding":{"values":{"REPEATED_FIELD_ENCODING_UNKNOWN":0,"PACKED":1,"EXPANDED":2}},"Utf8Validation":{"values":{"UTF8_VALIDATION_UNKNOWN":0,"VERIFY":2,"NONE":3}},"MessageEncoding":{"values":{"MESSAGE_ENCODING_UNKNOWN":0,"LENGTH_PREFIXED":1,"DELIMITED":2}},"JsonFormat":{"values":{"JSON_FORMAT_UNKNOWN":0,"ALLOW":1,"LEGACY_BEST_EFFORT":2}},"EnforceNamingStyle":{"values":{"ENFORCE_NAMING_STYLE_UNKNOWN":0,"STYLE2024":1,"STYLE_LEGACY":2}},"VisibilityFeature":{"fields":{},"reserved":[[1,536870911]],"nested":{"DefaultSymbolVisibility":{"values":{"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN":0,"EXPORT_ALL":1,"EXPORT_TOP_LEVEL":2,"LOCAL_ALL":3,"STRICT":4}}}}}},"FeatureSetDefaults":{"edition":"proto2","fields":{"defaults":{"rule":"repeated","type":"FeatureSetEditionDefault","id":1},"minimumEdition":{"type":"Edition","id":4},"maximumEdition":{"type":"Edition","id":5}},"nested":{"FeatureSetEditionDefault":{"fields":{"edition":{"type":"Edition","id":3},"overridableFeatures":{"type":"FeatureSet","id":4},"fixedFeatures":{"type":"FeatureSet","id":5}},"reserved":[[1,1],[2,2],"features"]}}},"SourceCodeInfo":{"edition":"proto2","fields":{"location":{"rule":"repeated","type":"Location","id":1}},"extensions":[[536000000,536000000]],"nested":{"Location":{"fields":{"path":{"rule":"repeated","type":"int32","id":1,"options":{"packed":true}},"span":{"rule":"repeated","type":"int32","id":2,"options":{"packed":true}},"leadingComments":{"type":"string","id":3},"trailingComments":{"type":"string","id":4},"leadingDetachedComments":{"rule":"repeated","type":"string","id":6}}}}},"GeneratedCodeInfo":{"edition":"proto2","fields":{"annotation":{"rule":"repeated","type":"Annotation","id":1}},"nested":{"Annotation":{"fields":{"path":{"rule":"repeated","type":"int32","id":1,"options":{"packed":true}},"sourceFile":{"type":"string","id":2},"begin":{"type":"int32","id":3},"end":{"type":"int32","id":4},"semantic":{"type":"Semantic","id":5}},"nested":{"Semantic":{"values":{"NONE":0,"SET":1,"ALIAS":2}}}}}},"SymbolVisibility":{"edition":"proto2","values":{"VISIBILITY_UNSET":0,"VISIBILITY_LOCAL":1,"VISIBILITY_EXPORT":2}}}}}}}}'); - -/***/ }), - -/***/ 73342: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"nested":{"SourceContext":{"fields":{"fileName":{"type":"string","id":1}}}}}}}}}'); - -/***/ }), - -/***/ 58783: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('{"nested":{"google":{"nested":{"protobuf":{"nested":{"Type":{"fields":{"name":{"type":"string","id":1},"fields":{"rule":"repeated","type":"Field","id":2},"oneofs":{"rule":"repeated","type":"string","id":3},"options":{"rule":"repeated","type":"Option","id":4},"sourceContext":{"type":"SourceContext","id":5},"syntax":{"type":"Syntax","id":6}}},"Field":{"fields":{"kind":{"type":"Kind","id":1},"cardinality":{"type":"Cardinality","id":2},"number":{"type":"int32","id":3},"name":{"type":"string","id":4},"typeUrl":{"type":"string","id":6},"oneofIndex":{"type":"int32","id":7},"packed":{"type":"bool","id":8},"options":{"rule":"repeated","type":"Option","id":9},"jsonName":{"type":"string","id":10},"defaultValue":{"type":"string","id":11}},"nested":{"Kind":{"values":{"TYPE_UNKNOWN":0,"TYPE_DOUBLE":1,"TYPE_FLOAT":2,"TYPE_INT64":3,"TYPE_UINT64":4,"TYPE_INT32":5,"TYPE_FIXED64":6,"TYPE_FIXED32":7,"TYPE_BOOL":8,"TYPE_STRING":9,"TYPE_GROUP":10,"TYPE_MESSAGE":11,"TYPE_BYTES":12,"TYPE_UINT32":13,"TYPE_ENUM":14,"TYPE_SFIXED32":15,"TYPE_SFIXED64":16,"TYPE_SINT32":17,"TYPE_SINT64":18}},"Cardinality":{"values":{"CARDINALITY_UNKNOWN":0,"CARDINALITY_OPTIONAL":1,"CARDINALITY_REQUIRED":2,"CARDINALITY_REPEATED":3}}}},"Enum":{"fields":{"name":{"type":"string","id":1},"enumvalue":{"rule":"repeated","type":"EnumValue","id":2},"options":{"rule":"repeated","type":"Option","id":3},"sourceContext":{"type":"SourceContext","id":4},"syntax":{"type":"Syntax","id":5}}},"EnumValue":{"fields":{"name":{"type":"string","id":1},"number":{"type":"int32","id":2},"options":{"rule":"repeated","type":"Option","id":3}}},"Option":{"fields":{"name":{"type":"string","id":1},"value":{"type":"Any","id":2}}},"Syntax":{"values":{"SYNTAX_PROTO2":0,"SYNTAX_PROTO3":1}},"Any":{"fields":{"type_url":{"type":"string","id":1},"value":{"type":"bytes","id":2}}},"SourceContext":{"fields":{"fileName":{"type":"string","id":1}}}}}}}}}'); - -/***/ }), - -/***/ 66674: -/***/ ((module) => { - -"use strict"; -module.exports = {"i8":"1.17.0"}; - -/***/ }), - -/***/ 72020: -/***/ ((module) => { - -"use strict"; -module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]]'); - /***/ }) /******/ }); @@ -151824,7 +71698,7 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"] /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(86925); +/******/ var __webpack_exports__ = __nccwpck_require__(6925); /******/ module.exports = __webpack_exports__; /******/ /******/ })() diff --git a/build/github_action/lib/protocol/crypto/build/Release/sshcrypto.node b/build/github_action/lib/protocol/crypto/build/Release/sshcrypto.node index 320bf0fd..86cad96c 100755 Binary files a/build/github_action/lib/protocol/crypto/build/Release/sshcrypto.node and b/build/github_action/lib/protocol/crypto/build/Release/sshcrypto.node differ diff --git a/build/github_action/runner/cli.d.ts b/build/github_action/runner/cli.d.ts deleted file mode 100644 index e0c8ad7a..00000000 --- a/build/github_action/runner/cli.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env node -/** - * CLI Entry Point - * - * This script serves as the main entry point for the CLI application. - * It executes the common compiled binary with the provided command line arguments. - */ -export {}; diff --git a/build/github_action/runner/github_action.d.ts b/build/github_action/runner/github_action.d.ts deleted file mode 100644 index 799fa864..00000000 --- a/build/github_action/runner/github_action.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * This script serves as a runner for GitHub Actions, executing the common - * compiled binary with the necessary environment variables. - * - * It sets up environment variables for the GitHub Action, - * including passing through all INPUT_* variables from the parent process. - */ -export {}; diff --git a/build/github_action/src/data/model/ai_response_schema.d.ts b/build/github_action/src/data/model/ai_response_schema.d.ts new file mode 100644 index 00000000..54adfc1c --- /dev/null +++ b/build/github_action/src/data/model/ai_response_schema.d.ts @@ -0,0 +1,31 @@ +/** + * JSON Schema for AiResponse interface + * This schema is used to enforce structured JSON responses from the AI + */ +export declare const AI_RESPONSE_JSON_SCHEMA: { + type: string; + properties: { + text_response: { + type: string; + description: string; + }; + action: { + type: string; + enum: string[]; + description: string; + }; + related_files: { + type: string; + items: { + type: string; + }; + description: string; + }; + complete: { + type: string; + description: string; + }; + }; + required: string[]; + additionalProperties: boolean; +}; diff --git a/build/github_action/src/data/model/codebase_analysis_schema.d.ts b/build/github_action/src/data/model/codebase_analysis_schema.d.ts new file mode 100644 index 00000000..b2bb7f82 --- /dev/null +++ b/build/github_action/src/data/model/codebase_analysis_schema.d.ts @@ -0,0 +1,30 @@ +/** + * JSON Schema for codebase analysis responses + * Used in Step 0 of the thinking process to analyze codebase structure + */ +export declare const CODEBASE_ANALYSIS_JSON_SCHEMA: { + type: string; + description: string; + items: { + type: string; + properties: { + path: { + type: string; + description: string; + }; + description: { + type: string; + description: string; + }; + relationships: { + type: string; + description: string; + items: { + type: string; + }; + }; + }; + required: string[]; + additionalProperties: boolean; + }; +}; diff --git a/build/github_action/src/data/model/execution.d.ts b/build/github_action/src/data/model/execution.d.ts index 6e382aac..187bf263 100644 --- a/build/github_action/src/data/model/execution.d.ts +++ b/build/github_action/src/data/model/execution.d.ts @@ -2,7 +2,6 @@ import { Ai } from "./ai"; import { Branches } from "./branches"; import { Commit } from "./commit"; import { Config } from "./config"; -import { DockerConfig } from "./docker_config"; import { Emoji } from "./emoji"; import { Hotfix } from "./hotfix"; import { Images } from "./images"; @@ -50,7 +49,6 @@ export declare class Execution { previousConfiguration: Config | undefined; currentConfiguration: Config; tokenUser: string | undefined; - dockerConfig: DockerConfig; supabaseConfig: SupabaseConfig | undefined; inputs: any | undefined; get eventName(): string; @@ -72,6 +70,6 @@ export declare class Execution { get cleanIssueBranches(): boolean; get commit(): Commit; get runnedByToken(): boolean; - constructor(debug: boolean, dockerConfig: DockerConfig, singleAction: SingleAction, commitPrefixBuilder: string, issue: Issue, pullRequest: PullRequest, emoji: Emoji, giphy: Images, tokens: Tokens, ai: Ai, labels: Labels, issueTypes: IssueTypes, locale: Locale, sizeThresholds: SizeThresholds, branches: Branches, release: Release, hotfix: Hotfix, workflows: Workflows, project: Projects, supabaseConfig: SupabaseConfig | undefined, welcome: Welcome | undefined, inputs: any | undefined); + constructor(debug: boolean, singleAction: SingleAction, commitPrefixBuilder: string, issue: Issue, pullRequest: PullRequest, emoji: Emoji, giphy: Images, tokens: Tokens, ai: Ai, labels: Labels, issueTypes: IssueTypes, locale: Locale, sizeThresholds: SizeThresholds, branches: Branches, release: Release, hotfix: Hotfix, workflows: Workflows, project: Projects, supabaseConfig: SupabaseConfig | undefined, welcome: Welcome | undefined, inputs: any | undefined); setup: () => Promise; } diff --git a/build/github_action/src/data/model/single_action.d.ts b/build/github_action/src/data/model/single_action.d.ts index 5bffd29a..f58a9c9f 100644 --- a/build/github_action/src/data/model/single_action.d.ts +++ b/build/github_action/src/data/model/single_action.d.ts @@ -20,13 +20,12 @@ export declare class SingleAction { title: string; changelog: string; get isDeployedAction(): boolean; - get isCompileVectorServerAction(): boolean; - get isVectorAction(): boolean; - get isVectorLocalAction(): boolean; - get isVectorRemovalAction(): boolean; + get isAiCacheAction(): boolean; + get isAiCacheLocalAction(): boolean; get isPublishGithubAction(): boolean; get isCreateReleaseAction(): boolean; get isCreateTagAction(): boolean; + get isThinkAction(): boolean; get enabledSingleAction(): boolean; get validSingleAction(): boolean; get isSingleActionWithoutIssue(): boolean; diff --git a/build/github_action/src/data/model/think_response.d.ts b/build/github_action/src/data/model/think_response.d.ts new file mode 100644 index 00000000..38b58e15 --- /dev/null +++ b/build/github_action/src/data/model/think_response.d.ts @@ -0,0 +1,56 @@ +export interface FileAnalysis { + path: string; + key_findings: string; + relevance: 'high' | 'medium' | 'low'; +} +export interface ProposedChange { + file_path: string; + change_type: 'create' | 'modify' | 'delete' | 'refactor'; + description: string; + suggested_code?: string; + reasoning: string; +} +export interface ThinkResponse { + reasoning: string; + action: 'search_files' | 'read_file' | 'analyze_code' | 'propose_changes' | 'complete' | 'update_todos'; + files_to_search?: string[]; + files_to_read?: string[]; + analyzed_files?: FileAnalysis[]; + proposed_changes?: ProposedChange[]; + todo_updates?: { + create?: Array<{ + content: string; + status?: 'pending' | 'in_progress'; + }>; + update?: Array<{ + id: string; + status?: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + notes?: string; + }>; + }; + complete: boolean; + final_analysis?: string; +} +export interface ThinkStep { + step_number: number; + action: string; + reasoning: string; + files_involved?: string[]; + findings?: string; + timestamp: number; +} +export interface ThinkTodoItem { + id: string; + content: string; + status: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + created_at: number; + updated_at: number; + completed_at?: number; + related_files?: string[]; + related_changes?: string[]; + notes?: string; +} +export interface ThinkTodoList { + items: ThinkTodoItem[]; + last_updated: number; +} diff --git a/build/github_action/src/data/model/think_response_schema.d.ts b/build/github_action/src/data/model/think_response_schema.d.ts new file mode 100644 index 00000000..d178403d --- /dev/null +++ b/build/github_action/src/data/model/think_response_schema.d.ts @@ -0,0 +1,131 @@ +/** + * JSON Schema for ThinkResponse interface + * This schema is used for structured AI reasoning and analysis responses + */ +export declare const THINK_RESPONSE_JSON_SCHEMA: { + type: string; + properties: { + reasoning: { + type: string; + description: string; + }; + action: { + type: string; + enum: string[]; + description: string; + }; + files_to_search: { + type: string; + items: { + type: string; + }; + description: string; + }; + files_to_read: { + type: string; + items: { + type: string; + }; + description: string; + }; + analyzed_files: { + type: string; + items: { + type: string; + properties: { + path: { + type: string; + }; + key_findings: { + type: string; + }; + relevance: { + type: string; + enum: string[]; + }; + }; + required: string[]; + }; + description: string; + }; + proposed_changes: { + type: string; + items: { + type: string; + properties: { + file_path: { + type: string; + }; + change_type: { + type: string; + enum: string[]; + }; + description: { + type: string; + }; + suggested_code: { + type: string; + }; + reasoning: { + type: string; + }; + }; + required: string[]; + }; + description: string; + }; + complete: { + type: string; + description: string; + }; + final_analysis: { + type: string; + description: string; + }; + todo_updates: { + type: string; + description: string; + properties: { + create: { + type: string; + items: { + type: string; + properties: { + content: { + type: string; + }; + status: { + type: string; + enum: string[]; + }; + }; + required: string[]; + }; + description: string; + }; + update: { + type: string; + items: { + type: string; + properties: { + id: { + type: string; + }; + status: { + type: string; + enum: string[]; + }; + notes: { + type: string; + }; + }; + required: string[]; + }; + description: string; + }; + }; + }; + }; + required: string[]; + additionalProperties: boolean; +}; diff --git a/build/github_action/src/data/model/tokens.d.ts b/build/github_action/src/data/model/tokens.d.ts index f6247503..2e473be2 100644 --- a/build/github_action/src/data/model/tokens.d.ts +++ b/build/github_action/src/data/model/tokens.d.ts @@ -1,5 +1,4 @@ export declare class Tokens { token: string; - classicToken: string; - constructor(token: string, classicToken: string); + constructor(token: string); } diff --git a/build/github_action/src/data/repository/ai_repository.d.ts b/build/github_action/src/data/repository/ai_repository.d.ts index e5766b62..16d3a60c 100644 --- a/build/github_action/src/data/repository/ai_repository.d.ts +++ b/build/github_action/src/data/repository/ai_repository.d.ts @@ -1,5 +1,6 @@ import { Ai } from '../model/ai'; export declare class AiRepository { ask: (ai: Ai, prompt: string) => Promise; - askJson: (ai: Ai, prompt: string) => Promise; + askJson: (ai: Ai, prompt: string, schema?: any, schemaName?: string) => Promise; + askThinkJson: (ai: Ai, prompt: string) => Promise; } diff --git a/build/github_action/src/data/repository/cache_repository.d.ts b/build/github_action/src/data/repository/cache_repository.d.ts deleted file mode 100644 index 53c64153..00000000 --- a/build/github_action/src/data/repository/cache_repository.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -export declare class CacheRepository { - private isGitHubActions; - private ensureCacheDirectory; - /** - * Saves data to the GitHub Actions cache - * @param key The unique key for the cache entry - * @param paths List of file paths to cache - * @returns Promise True if cache was saved successfully - */ - saveCache(key: string, paths: string[]): Promise; - /** - * Retrieves data from the GitHub Actions cache - * @param key The unique key for the cache entry - * @param paths List of file paths to restore - * @returns Promise True if cache was restored successfully - */ - restoreCache(key: string, paths: string[]): Promise; -} diff --git a/build/github_action/src/data/repository/file_repository.d.ts b/build/github_action/src/data/repository/file_repository.d.ts index ac551a2f..e1698a15 100644 --- a/build/github_action/src/data/repository/file_repository.d.ts +++ b/build/github_action/src/data/repository/file_repository.d.ts @@ -1,4 +1,3 @@ -import { ChunkedFile } from "../model/chunked_file"; export interface FileTreeNodeWithNoContent { name: string; type: 'file' | 'directory'; @@ -17,9 +16,6 @@ export declare class FileRepository { private isMediaOrPdfFile; getFileContent: (owner: string, repository: string, path: string, token: string, branch: string) => Promise; getRepositoryContent: (owner: string, repository: string, token: string, branch: string, ignoreFiles: string[], progress: (fileName: string) => void, ignoredFiles: (fileName: string) => void) => Promise>; - getChunkedRepositoryContent: (owner: string, repository: string, branch: string, chunkSize: number, token: string, ignoreFiles: string[], progress: (fileName: string) => void, ignoredFiles: (fileName: string) => void) => Promise>; - getChunksByLines: (path: string, content: string, shasum: string, chunkSize: number) => ChunkedFile[]; - getChunksByBlocks: (path: string, content: string, shasum: string, chunkSize: number) => ChunkedFile[]; private shouldIgnoreFile; private extractCodeBlocks; private shouldIgnoreLine; diff --git a/build/github_action/src/data/repository/supabase_repository.d.ts b/build/github_action/src/data/repository/supabase_repository.d.ts index fdf01749..a9e56edd 100644 --- a/build/github_action/src/data/repository/supabase_repository.d.ts +++ b/build/github_action/src/data/repository/supabase_repository.d.ts @@ -1,27 +1,61 @@ -import { ChunkedFile } from '../model/chunked_file'; -import { ChunkedFileChunk } from '../model/chunked_file_chunk'; import { SupabaseConfig } from '../model/supabase_config'; +export interface AICachedFileInfo { + owner: string; + repository: string; + branch: string; + file_name: string; + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; + created_at?: string; + last_updated?: string; +} export declare class SupabaseRepository { - private readonly CHUNKS_TABLE; + private readonly AI_FILE_CACHE_TABLE; private readonly MAX_BATCH_SIZE; private readonly DEFAULT_TIMEOUT; private supabase; constructor(config: SupabaseConfig); - setChunkedFile: (owner: string, repository: string, branch: string, chunkedFile: ChunkedFile) => Promise; - removeChunksByShasum: (owner: string, repository: string, branch: string, shasum: string) => Promise; - getChunkedFileByShasum: (owner: string, repository: string, branch: string, type: string, shasum: string) => Promise; - getChunks: (owner: string, repository: string, branch: string, path: string, type: string, index: number) => Promise; - getChunksByShasum: (owner: string, repository: string, branch: string, shasum: string) => Promise; - updateVector: (owner: string, repository: string, branch: string, path: string, index: number, chunkIndex: number, vector: number[]) => Promise; - matchChunks: (owner: string, repository: string, branch: string, type: string, queryEmbedding: number[], matchCount?: number) => Promise; - duplicateChunksByBranch: (owner: string, repository: string, sourceBranch: string, targetBranch: string) => Promise; - removeChunksByBranch: (owner: string, repository: string, branch: string) => Promise; - getDistinctPaths: (owner: string, repository: string, branch: string) => Promise; - removeChunksByPath: (owner: string, repository: string, branch: string, path: string) => Promise; + /** + * Set or update AI file cache entry + * If SHA hasn't changed, this will update the entry + */ + setAIFileCache: (owner: string, repository: string, branch: string, fileInfo: { + file_name: string; + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; + }) => Promise; + /** + * Get AI file cache entry by path + */ + getAIFileCache: (owner: string, repository: string, branch: string, filePath: string) => Promise; + /** + * Get all AI file cache entries for a branch + */ + getAIFileCachesByBranch: (owner: string, repository: string, branch: string) => Promise; + /** + * Remove AI file cache entry by path + */ + removeAIFileCacheByPath: (owner: string, repository: string, branch: string, filePath: string) => Promise; + /** + * Duplicate AI file cache entries from one branch to another + */ + duplicateAIFileCacheByBranch: (owner: string, repository: string, sourceBranch: string, targetBranch: string) => Promise; + /** + * Remove all AI file cache entries for a branch + */ + removeAIFileCacheByBranch: (owner: string, repository: string, branch: string) => Promise; + /** + * Get SHA by path (for checking if file is cached) + */ getShasumByPath: (owner: string, repository: string, branch: string, path: string) => Promise; - private countBranchEntries; - private duplicateFileEntries; - private duplicateBranchEntries; - private deleteBranchEntries; - getVectorOfChunkContent: (owner: string, repository: string, content: string) => Promise; + /** + * Get distinct paths for a branch + */ + getDistinctPaths: (owner: string, repository: string, branch: string) => Promise; } diff --git a/build/github_action/src/usecase/actions/prepare_local_vector_server_use_case.d.ts b/build/github_action/src/usecase/actions/prepare_local_vector_server_use_case.d.ts deleted file mode 100644 index 9087aec2..00000000 --- a/build/github_action/src/usecase/actions/prepare_local_vector_server_use_case.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Execution } from '../../data/model/execution'; -import { Result } from '../../data/model/result'; -import { ParamUseCase } from '../base/param_usecase'; -export declare class PrepareLocalVectorServerUseCase implements ParamUseCase { - taskId: string; - private dockerRepository; - invoke(param: Execution): Promise; -} diff --git a/build/github_action/src/usecase/actions/vector_action_removal_use_case.d.ts b/build/github_action/src/usecase/actions/vector_action_removal_use_case.d.ts index 5ffdf184..38e75fbe 100644 --- a/build/github_action/src/usecase/actions/vector_action_removal_use_case.d.ts +++ b/build/github_action/src/usecase/actions/vector_action_removal_use_case.d.ts @@ -4,5 +4,5 @@ import { ParamUseCase } from '../base/param_usecase'; export declare class VectorActionRemovalUseCase implements ParamUseCase { taskId: string; invoke(param: Execution): Promise; - private removeChunksByBranch; + private removeAICacheByBranch; } diff --git a/build/github_action/src/usecase/actions/vector_action_use_case.d.ts b/build/github_action/src/usecase/actions/vector_action_use_case.d.ts index 5ef0b741..862ba6a4 100644 --- a/build/github_action/src/usecase/actions/vector_action_use_case.d.ts +++ b/build/github_action/src/usecase/actions/vector_action_use_case.d.ts @@ -3,12 +3,14 @@ import { Result } from '../../data/model/result'; import { ParamUseCase } from '../base/param_usecase'; export declare class VectorActionUseCase implements ParamUseCase { taskId: string; - private dockerRepository; private fileRepository; - private readonly CODE_INSTRUCTION_BLOCK; - private readonly CODE_INSTRUCTION_LINE; + private aiRepository; + private fileImportAnalyzer; + private fileCacheManager; + private codebaseAnalyzer; + constructor(); invoke(param: Execution): Promise; - private checkChunksInSupabase; - private uploadChunksToSupabase; - private duplicateChunksToBranch; + private checkAICacheInSupabase; + private uploadAICacheToSupabase; + private duplicateAICacheToBranch; } diff --git a/build/github_action/src/usecase/steps/common/services/codebase_analyzer.d.ts b/build/github_action/src/usecase/steps/common/services/codebase_analyzer.d.ts new file mode 100644 index 00000000..5a63f75d --- /dev/null +++ b/build/github_action/src/usecase/steps/common/services/codebase_analyzer.d.ts @@ -0,0 +1,37 @@ +import { Execution } from '../../../../data/model/execution'; +import { AiRepository } from '../../../../data/repository/ai_repository'; +import { FileImportAnalyzer } from './file_import_analyzer'; +import { FileCacheManager } from './file_cache_manager'; +export interface FileAnalysisResult { + path: string; + description: string; + consumes: string[]; + consumed_by: string[]; +} +/** + * Service for analyzing codebase structure and generating file descriptions + */ +export declare class CodebaseAnalyzer { + private aiRepository; + private fileImportAnalyzer; + private fileCacheManager; + constructor(aiRepository: AiRepository, fileImportAnalyzer: FileImportAnalyzer, fileCacheManager: FileCacheManager); + /** + * Generate codebase analysis with file descriptions and relationships + * This runs before the main reasoning loop to provide context + * Uses relationship map built from imports + AI descriptions in batches + */ + generateCodebaseAnalysis(param: Execution, repositoryFiles: Map, question: string): Promise; + /** + * Generate basic description from file path (fallback) + */ + generateBasicDescription(path: string): string; + /** + * Generate fallback file descriptions when AI analysis fails + */ + generateFallbackFileDescriptions(files: Array<[string, string]>): FileAnalysisResult[]; + /** + * Format codebase analysis for inclusion in AI context + */ + formatCodebaseAnalysisForContext(analysis: FileAnalysisResult[]): string; +} diff --git a/build/github_action/src/usecase/steps/common/services/comment_formatter.d.ts b/build/github_action/src/usecase/steps/common/services/comment_formatter.d.ts new file mode 100644 index 00000000..c0013f16 --- /dev/null +++ b/build/github_action/src/usecase/steps/common/services/comment_formatter.d.ts @@ -0,0 +1,32 @@ +import { ThinkStep, ProposedChange, FileAnalysis } from '../../../../data/model/think_response'; +import { ThinkTodoManager } from '../think_todo_manager'; +/** + * Service for formatting GitHub comments and code changes + */ +export declare class CommentFormatter { + private readonly GITHUB_COMMENT_MAX_LENGTH; + /** + * Format the complete reasoning comment for GitHub + */ + formatReasoningComment(question: string, description: string, steps: ThinkStep[], analyzedFiles: Map, proposedChanges: ProposedChange[], finalAnalysis: string, totalIterations: number, todoManager: ThinkTodoManager): string; + /** + * Format a single proposed change + */ + formatProposedChange(change: ProposedChange, index: number): string; + /** + * Detect programming language from file path/extension + */ + detectLanguageFromPath(filePath: string): string; + /** + * Get emoji for action type + */ + getActionEmoji(action: string): string; + /** + * Format action name for display + */ + formatActionName(action: string): string; + /** + * Get emoji for change type + */ + getChangeTypeEmoji(changeType: string): string; +} diff --git a/build/github_action/src/usecase/steps/common/services/file_cache_manager.d.ts b/build/github_action/src/usecase/steps/common/services/file_cache_manager.d.ts new file mode 100644 index 00000000..3ae0e95f --- /dev/null +++ b/build/github_action/src/usecase/steps/common/services/file_cache_manager.d.ts @@ -0,0 +1,36 @@ +import { Execution } from '../../../../data/model/execution'; +import { SupabaseRepository } from '../../../../data/repository/supabase_repository'; +import { CachedFileInfo } from './types'; +/** + * Service for managing AI file cache in Supabase + */ +export declare class FileCacheManager { + private supabaseRepository; + /** + * Normalize file path for consistent comparison + * Removes leading ./ and normalizes path separators + */ + private normalizePath; + /** + * Calculate SHA256 hash of file content + */ + calculateFileSHA(content: string): string; + /** + * Initialize Supabase repository if config is available + */ + initSupabaseRepository(param: Execution): SupabaseRepository | null; + /** + * Load cache from Supabase (or return empty map if Supabase not available) + * Uses normalized paths for consistent lookup + */ + loadAICache(param: Execution): Promise>; + /** + * Get cached file info by path (with path normalization) + */ + getCachedFile(cache: Map, filePath: string): CachedFileInfo | undefined; + /** + * Save cache entry to Supabase + * Normalizes paths before saving + */ + saveAICacheEntry(param: Execution, filePath: string, fileInfo: CachedFileInfo, consumes: string[], consumedBy: string[]): Promise; +} diff --git a/build/github_action/src/usecase/steps/common/services/file_import_analyzer.d.ts b/build/github_action/src/usecase/steps/common/services/file_import_analyzer.d.ts new file mode 100644 index 00000000..f2b5da10 --- /dev/null +++ b/build/github_action/src/usecase/steps/common/services/file_import_analyzer.d.ts @@ -0,0 +1,22 @@ +/** + * Service for extracting imports and building file relationship maps + * Supports multiple programming languages + */ +export declare class FileImportAnalyzer { + /** + * Extract imports from a file regardless of programming language + */ + extractImportsFromFile(filePath: string, content: string): string[]; + /** + * Resolve relative import path to absolute path + */ + resolveRelativePath(baseDir: string, relativePath: string): string; + /** + * Build relationship map from all files by extracting imports + * Also builds reverse map (consumed_by) + */ + buildRelationshipMap(repositoryFiles: Map): { + consumes: Map; + consumedBy: Map; + }; +} diff --git a/build/github_action/src/usecase/steps/common/services/file_search_service.d.ts b/build/github_action/src/usecase/steps/common/services/file_search_service.d.ts new file mode 100644 index 00000000..1a601ce8 --- /dev/null +++ b/build/github_action/src/usecase/steps/common/services/file_search_service.d.ts @@ -0,0 +1,13 @@ +/** + * Service for building file indexes and searching files + */ +export declare class FileSearchService { + /** + * Build file index for quick lookup by filename or directory + */ + buildFileIndex(files: Map): Map; + /** + * Search files by search terms (filename, directory, or pattern) + */ + searchFiles(searchTerms: string[], fileIndex: Map): string[]; +} diff --git a/build/github_action/src/usecase/steps/common/services/types.d.ts b/build/github_action/src/usecase/steps/common/services/types.d.ts new file mode 100644 index 00000000..84a081ba --- /dev/null +++ b/build/github_action/src/usecase/steps/common/services/types.d.ts @@ -0,0 +1,14 @@ +/** + * Shared types for codebase analysis services + */ +export interface CachedFileInfo { + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; +} +export interface FileRelationshipMap { + consumes: Map; + consumedBy: Map; +} diff --git a/build/github_action/src/usecase/steps/common/think_code_manager.d.ts b/build/github_action/src/usecase/steps/common/think_code_manager.d.ts new file mode 100644 index 00000000..465bde74 --- /dev/null +++ b/build/github_action/src/usecase/steps/common/think_code_manager.d.ts @@ -0,0 +1,59 @@ +import { ProposedChange } from '../../../data/model/think_response'; +/** + * Manages virtual code state - keeps files in memory and applies proposed changes + * so subsequent reasoning steps can see the accumulated progress + */ +export declare class ThinkCodeManager { + private originalFiles; + private virtualFiles; + private appliedChanges; + private allAppliedChanges; + /** + * Initialize with original repository files + */ + initialize(originalFiles: Map): void; + /** + * Get current state of a file (with applied changes) + */ + getFileContent(filePath: string): string | undefined; + /** + * Get all virtual files + */ + getAllFiles(): Map; + /** + * Check if a file has been modified + */ + isFileModified(filePath: string): boolean; + /** + * Get changes applied to a specific file + */ + getFileChanges(filePath: string): ProposedChange[]; + /** + * Apply a proposed change to the virtual codebase + */ + applyChange(change: ProposedChange): boolean; + /** + * Check if a change has already been applied (to avoid duplicates) + */ + hasChangeBeenApplied(change: ProposedChange): boolean; + /** + * Get summary of all applied changes + */ + getChangesSummary(): string; + /** + * Get context about what has changed for the AI + */ + getContextForAI(): string; + /** + * Simple similarity check for change descriptions + */ + private areSimilar; + /** + * Get statistics + */ + getStats(): { + totalFiles: number; + modifiedFiles: number; + totalChanges: number; + }; +} diff --git a/build/github_action/src/usecase/steps/common/think_todo_manager.d.ts b/build/github_action/src/usecase/steps/common/think_todo_manager.d.ts new file mode 100644 index 00000000..03857149 --- /dev/null +++ b/build/github_action/src/usecase/steps/common/think_todo_manager.d.ts @@ -0,0 +1,70 @@ +import { ThinkTodoItem } from '../../../data/model/think_response'; +import { ProposedChange } from '../../../data/model/think_response'; +/** + * Manages TODO list for the reasoning process + * Similar to how the assistant tracks high-level tasks vs iterative steps + */ +export declare class ThinkTodoManager { + private todos; + private nextId; + /** + * Initialize with optional initial todos + */ + initialize(initialTodos?: Array<{ + content: string; + status?: 'pending' | 'in_progress'; + }>): void; + /** + * Create a new TODO item + */ + createTodo(content: string, status?: 'pending' | 'in_progress'): ThinkTodoItem; + /** + * Update an existing TODO item + */ + updateTodo(id: string, updates: { + status?: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + notes?: string; + related_files?: string[]; + related_changes?: string[]; + }): boolean; + /** + * Get all TODOs + */ + getAllTodos(): ThinkTodoItem[]; + /** + * Get TODOs by status + */ + getTodosByStatus(status: ThinkTodoItem['status']): ThinkTodoItem[]; + /** + * Get active TODOs (pending or in_progress) + */ + getActiveTodos(): ThinkTodoItem[]; + /** + * Get completion statistics + */ + getStats(): { + total: number; + pending: number; + in_progress: number; + completed: number; + cancelled: number; + completion_rate: number; + }; + /** + * Get formatted TODO list for AI context + */ + getContextForAI(): string; + /** + * Link a TODO to proposed changes + */ + linkTodoToChanges(todoId: string, changes: ProposedChange[]): void; + /** + * Auto-update TODO status based on progress + * If changes are applied for a TODO, mark it as in_progress or completed + */ + autoUpdateFromChanges(changes: ProposedChange[]): void; + /** + * Get summary for final report + */ + getSummary(): string; +} diff --git a/build/github_action/src/usecase/steps/common/think_use_case.d.ts b/build/github_action/src/usecase/steps/common/think_use_case.d.ts new file mode 100644 index 00000000..ead15fe7 --- /dev/null +++ b/build/github_action/src/usecase/steps/common/think_use_case.d.ts @@ -0,0 +1,22 @@ +import { Execution } from '../../../data/model/execution'; +import { Result } from '../../../data/model/result'; +import { ParamUseCase } from '../../base/param_usecase'; +export declare class ThinkUseCase implements ParamUseCase { + taskId: string; + private aiRepository; + private fileRepository; + private issueRepository; + private fileImportAnalyzer; + private fileCacheManager; + private codebaseAnalyzer; + private fileSearchService; + private commentFormatter; + private readonly MAX_ITERATIONS; + private readonly MAX_FILES_TO_ANALYZE; + private readonly MAX_CONSECUTIVE_SEARCHES; + constructor(); + invoke(param: Execution): Promise; + private getIssueDescription; + private performReasoningStep; + private generateFinalAnalysis; +} diff --git a/build/github_action/src/usecase/steps/issue/prepare_branches_use_case.d.ts b/build/github_action/src/usecase/steps/issue/prepare_branches_use_case.d.ts index 1d6abab2..4c0c63ea 100644 --- a/build/github_action/src/usecase/steps/issue/prepare_branches_use_case.d.ts +++ b/build/github_action/src/usecase/steps/issue/prepare_branches_use_case.d.ts @@ -5,5 +5,5 @@ export declare class PrepareBranchesUseCase implements ParamUseCase; - private duplicateChunksByBranch; + private duplicateAICacheByBranch; } diff --git a/build/github_action/src/utils/constants.d.ts b/build/github_action/src/utils/constants.d.ts index 3bb23aef..992fd05f 100644 --- a/build/github_action/src/utils/constants.d.ts +++ b/build/github_action/src/utils/constants.d.ts @@ -1,5 +1,5 @@ -export declare const COMMAND = "git-board-flow"; -export declare const TITLE = "Git Board Flow"; +export declare const COMMAND = "giik"; +export declare const TITLE = "Giik"; export declare const REPO_URL = "https://github.com/landamessenger/git-board-flow"; export declare const DEFAULT_IMAGE_CONFIG: { issue: { @@ -44,18 +44,12 @@ export declare const INPUT_KEYS: { readonly DEBUG: "debug"; readonly WELCOME_TITLE: "welcome-title"; readonly WELCOME_MESSAGES: "welcome-messages"; - readonly DOCKER_CONTAINER_NAME: "docker-container-name"; - readonly DOCKER_DOMAIN: "docker-domain"; - readonly DOCKER_PORT: "docker-port"; - readonly DOCKER_CACHE_OS: "docker-cache-os"; - readonly DOCKER_CACHE_ARCH: "docker-cache-arch"; readonly SINGLE_ACTION: "single-action"; readonly SINGLE_ACTION_ISSUE: "single-action-issue"; readonly SINGLE_ACTION_VERSION: "single-action-version"; readonly SINGLE_ACTION_TITLE: "single-action-title"; readonly SINGLE_ACTION_CHANGELOG: "single-action-changelog"; readonly TOKEN: "token"; - readonly CLASSIC_TOKEN: "classic-token"; readonly OPENROUTER_API_KEY: "openrouter-api-key"; readonly OPENROUTER_MODEL: "openrouter-model"; readonly AI_PULL_REQUEST_DESCRIPTION: "ai-pull-request-description"; @@ -197,11 +191,13 @@ export declare const ERRORS: { }; export declare const ACTIONS: { readonly DEPLOYED: "deployed_action"; - readonly COMPILE_VECTOR_SERVER: "compile_vector_server"; - readonly VECTOR: "vector_action"; - readonly VECTOR_LOCAL: "vector_local"; - readonly VECTOR_REMOVAL: "vector_removal"; + readonly AI_CACHE: "ai_cache_action"; + readonly AI_CACHE_LOCAL: "ai_cache_local_action"; readonly PUBLISH_GITHUB_ACTION: "publish_github_action"; readonly CREATE_RELEASE: "create_release"; readonly CREATE_TAG: "create_tag"; + readonly THINK: "think_action"; +}; +export declare const PROMPTS: { + readonly CODE_BASE_ANALYSIS: "\nYou are a technical code analysis assistant.\n\nYour task is to analyze the content of the following source code file in depth.\n\nProvide a precise and highly technical explanation of what the code does, including:\n- Its main purpose and functionality.\n- A breakdown of the logic and flow (step by step or module by module).\n- How each class, function, or major block interacts with the rest.\n- The technologies, frameworks, or libraries it uses and how.\n- Any relevant algorithms, patterns, or data structures implemented.\n- Potential edge cases, performance considerations, or hidden behaviors.\n- Dependencies and external integrations (APIs, services, databases, etc.).\n- Any implicit assumptions or limitations found in the implementation.\n\nFocus exclusively on *accurate technical analysis and understanding*, not on summarizing in simple language.\n\nDo not propose improvements, changes, or fixes in this stage — your only goal is to explain exactly what the code does and how it works.\n "; }; diff --git a/docs/ai-container-system.md b/docs/ai-container-system.md index 7514026d..4638f08f 100644 --- a/docs/ai-container-system.md +++ b/docs/ai-container-system.md @@ -38,7 +38,7 @@ jobs: - name: Update AI Knowledge uses: ./ with: - single-action: vector_action + single-action: ai_cache_action ``` ### 4. Use in CLI diff --git a/package.json b/package.json index 4471379b..74477a0b 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "Automates branch management, GitHub project linking, and issue/PR tracking with Git-Flow methodology.", "main": "build/github_action/index.js", "bin": { - "git-board-flow": "./build/cli/index.js" + "giik": "./build/cli/index.js" }, "scripts": { "build": "ncc build src/actions/github_action.ts -o build/github_action && ncc build src/cli.ts -o build/cli && chmod +x build/cli/index.js" diff --git a/src/actions/github_action.ts b/src/actions/github_action.ts index 806e7e99..0a3606e7 100644 --- a/src/actions/github_action.ts +++ b/src/actions/github_action.ts @@ -1,7 +1,6 @@ import * as core from '@actions/core'; import { Ai } from '../data/model/ai'; import { Branches } from '../data/model/branches'; -import { DockerConfig } from '../data/model/docker_config'; import { Emoji } from '../data/model/emoji'; import { Execution } from '../data/model/execution'; import { Hotfix } from '../data/model/hotfix'; @@ -36,15 +35,6 @@ export async function runGitHubAction(): Promise { */ const debug = getInput(INPUT_KEYS.DEBUG) == 'true' - /** - * Docker - */ - const dockerContainerName = getInput(INPUT_KEYS.DOCKER_CONTAINER_NAME); - const dockerDomain = getInput(INPUT_KEYS.DOCKER_DOMAIN); - const dockerPort = parseInt(getInput(INPUT_KEYS.DOCKER_PORT)); - const dockerCacheOs = getInput(INPUT_KEYS.DOCKER_CACHE_OS); - const dockerCacheArch = getInput(INPUT_KEYS.DOCKER_CACHE_ARCH); - /** * Single action */ @@ -58,7 +48,6 @@ export async function runGitHubAction(): Promise { * Tokens */ const token = getInput(INPUT_KEYS.TOKEN, {required: true}); - const classicToken = getInput(INPUT_KEYS.CLASSIC_TOKEN); /** * AI @@ -500,7 +489,6 @@ export async function runGitHubAction(): Promise { const execution = new Execution( debug, - new DockerConfig(dockerContainerName, dockerDomain, dockerPort, dockerCacheOs, dockerCacheArch), new SingleAction( singleAction, singleActionIssue, @@ -551,7 +539,6 @@ export async function runGitHubAction(): Promise { ), new Tokens( token, - classicToken, ), new Ai( openrouterApiKey, diff --git a/src/actions/local_action.ts b/src/actions/local_action.ts index 769b5d86..a78a1cce 100644 --- a/src/actions/local_action.ts +++ b/src/actions/local_action.ts @@ -1,7 +1,6 @@ import chalk from 'chalk'; import { Ai } from '../data/model/ai'; import { Branches } from '../data/model/branches'; -import { DockerConfig } from '../data/model/docker_config'; import { Emoji } from '../data/model/emoji'; import { Execution } from '../data/model/execution'; import { Hotfix } from '../data/model/hotfix'; @@ -44,15 +43,6 @@ export async function runLocalAction(additionalParams: any): Promise { const welcomeTitle = additionalParams[INPUT_KEYS.WELCOME_TITLE] ?? actionInputs[INPUT_KEYS.WELCOME_TITLE]; const welcomeMessages = additionalParams[INPUT_KEYS.WELCOME_MESSAGES] ?? actionInputs[INPUT_KEYS.WELCOME_MESSAGES]; - /** - * Docker - */ - const dockerContainerName = additionalParams[INPUT_KEYS.DOCKER_CONTAINER_NAME] ?? actionInputs[INPUT_KEYS.DOCKER_CONTAINER_NAME]; - const dockerDomain = additionalParams[INPUT_KEYS.DOCKER_DOMAIN] ?? actionInputs[INPUT_KEYS.DOCKER_DOMAIN]; - const dockerPort = parseInt(additionalParams[INPUT_KEYS.DOCKER_PORT] ?? actionInputs[INPUT_KEYS.DOCKER_PORT]); - const dockerCacheOs = additionalParams[INPUT_KEYS.DOCKER_CACHE_OS] ?? actionInputs[INPUT_KEYS.DOCKER_CACHE_OS]; - const dockerCacheArch = additionalParams[INPUT_KEYS.DOCKER_CACHE_ARCH] ?? actionInputs[INPUT_KEYS.DOCKER_CACHE_ARCH]; - /** * Single action */ @@ -66,7 +56,6 @@ export async function runLocalAction(additionalParams: any): Promise { * Tokens */ const token = additionalParams[INPUT_KEYS.TOKEN] ?? actionInputs[INPUT_KEYS.TOKEN]; - const classicToken = additionalParams[INPUT_KEYS.CLASSIC_TOKEN] ?? actionInputs[INPUT_KEYS.CLASSIC_TOKEN]; /** * AI @@ -508,13 +497,6 @@ export async function runLocalAction(additionalParams: any): Promise { const execution = new Execution( debug, - new DockerConfig( - dockerContainerName, - dockerDomain, - dockerPort, - dockerCacheOs, - dockerCacheArch, - ), new SingleAction( singleAction, singleActionIssue, @@ -567,7 +549,6 @@ export async function runLocalAction(additionalParams: any): Promise { ), new Tokens( token, - classicToken, ), new Ai( openrouterApiKey, diff --git a/src/cli.ts b/src/cli.ts index dce6f76e..174e87e5 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -30,59 +30,11 @@ function getGitInfo() { } } -program - .name(COMMAND) - .description(`CLI tool for ${TITLE}`) - .version('1.0.0'); - program - .command('compile-vector-server') - .description('Compile vector server container') - .option('-d, --debug', 'Debug mode', false) - .option('-p, --platforms ', 'Platforms', 'linux/amd64,linux/arm64,linux/arm/v7,linux/ppc64le,linux/s390x') - .option('-v, --version ', 'Version', 'latest') - .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) - .option('-c, --classic-token ', 'Classic personal access token', process.env.CLASSIC_TOKEN) - .action(async (options) => { - const gitInfo = getGitInfo(); - - if ('error' in gitInfo) { - console.log(gitInfo.error); - return; - } - - const params: any = { - [INPUT_KEYS.DEBUG]: options.debug.toString(), - [INPUT_KEYS.SINGLE_ACTION]: ACTIONS.COMPILE_VECTOR_SERVER, - [INPUT_KEYS.SINGLE_ACTION_VERSION]: options.version, - [INPUT_KEYS.SINGLE_ACTION_ISSUE]: 1, - [INPUT_KEYS.SUPABASE_URL]: process.env.SUPABASE_URL, - [INPUT_KEYS.SUPABASE_KEY]: process.env.SUPABASE_KEY, - [INPUT_KEYS.TOKEN]: options.token || process.env.PERSONAL_ACCESS_TOKEN, - [INPUT_KEYS.CLASSIC_TOKEN]: options.classictoken || process.env.CLASSIC_TOKEN, - [INPUT_KEYS.AI_IGNORE_FILES]: 'build/*', - repo: { - owner: gitInfo.owner, - repo: gitInfo.repo, - }, - issue: { - number: 1, - }, - }; - - params[INPUT_KEYS.WELCOME_TITLE] = 'šŸ‘·šŸ› ļø Vector Server Container Build'; - params[INPUT_KEYS.WELCOME_MESSAGES] = [ - `Building vector server container for ${gitInfo.owner}/${gitInfo.repo}...`, - ]; - - await runLocalAction(params); - }); - program .command('build-ai') - .description('Build AI container and execute vector indexing') + .description(`${TITLE} - Build AI container and execute AI cache indexing`) .option('-d, --debug', 'Debug mode', false) .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) - .option('-c, --classic-token ', 'Classic personal access token', process.env.CLASSIC_TOKEN) .action(async (options) => { const gitInfo = getGitInfo(); @@ -93,12 +45,13 @@ program const params: any = { [INPUT_KEYS.DEBUG]: options.debug.toString(), - [INPUT_KEYS.SINGLE_ACTION]: ACTIONS.VECTOR_LOCAL, + [INPUT_KEYS.SINGLE_ACTION]: ACTIONS.AI_CACHE_LOCAL, [INPUT_KEYS.SINGLE_ACTION_ISSUE]: 1, [INPUT_KEYS.SUPABASE_URL]: process.env.SUPABASE_URL, [INPUT_KEYS.SUPABASE_KEY]: process.env.SUPABASE_KEY, + [INPUT_KEYS.OPENROUTER_API_KEY]: process.env.OPENROUTER_API_KEY, + [INPUT_KEYS.OPENROUTER_MODEL]: process.env.OPENROUTER_MODEL, [INPUT_KEYS.TOKEN]: options.token || process.env.PERSONAL_ACCESS_TOKEN, - [INPUT_KEYS.CLASSIC_TOKEN]: options.classictoken || process.env.CLASSIC_TOKEN, [INPUT_KEYS.AI_IGNORE_FILES]: 'build/*', repo: { owner: gitInfo.owner, @@ -118,18 +71,16 @@ program }); /** - * Run the asking AI scenario on issues or pull requests. - * - * For the action of asking the AI to be executed, the bot user managing the repository must be mentioned. + * Run the thinking AI scenario for deep code analysis and proposals. */ program - .command('ask-ai') - .description('Ask AI') - .option('-i, --issue ', 'Issue number to process', '1') + .command('think') + .description(`${TITLE} - Deep code analysis and change proposals using AI reasoning`) + .option('-i, --issue ', 'Issue number to process (optional)', '1') .option('-b, --branch ', 'Branch name', 'master') .option('-d, --debug', 'Debug mode', false) .option('-t, --token ', 'Personal access token', process.env.PERSONAL_ACCESS_TOKEN) - .option('-q, --question ', 'Question', '') + .option('-q, --question ', 'Question or prompt for analysis', '') .option('--openrouter-api-key ', 'OpenRouter API key', '') .option('--openrouter-model ', 'OpenRouter model', '') .option('--openrouter-provider-order ', 'OpenRouter provider', '') @@ -149,10 +100,28 @@ program return; } - const commentBody = (options.question || []).join(' '); + // Helper function to clean CLI arguments that may have '=' prefix + const cleanArg = (value: any): string => { + if (!value) return ''; + const str = String(value); + return str.startsWith('=') ? str.substring(1) : str; + }; + + const questionParts = (options.question || []).map(cleanArg); + const question = questionParts.join(' '); + + if (!question || question.length === 0) { + console.log('āŒ Please provide a question or prompt using -q or --question'); + return; + } + + const branch = cleanArg(options.branch); + const issueNumber = cleanArg(options.issue); const params: any = { [INPUT_KEYS.DEBUG]: options.debug.toString(), + [INPUT_KEYS.SINGLE_ACTION]: ACTIONS.THINK, + [INPUT_KEYS.SINGLE_ACTION_ISSUE]: parseInt(issueNumber) || 1, [INPUT_KEYS.SUPABASE_URL]: options?.supabaseUrl?.length > 0 ? options.supabaseUrl : process.env.SUPABASE_URL, [INPUT_KEYS.SUPABASE_KEY]: options?.supabaseKey?.length > 0 ? options.supabaseKey : process.env.SUPABASE_KEY, [INPUT_KEYS.TOKEN]: options?.token?.length > 0 ? options.token : process.env.PERSONAL_ACCESS_TOKEN, @@ -172,46 +141,45 @@ program repo: gitInfo.repo, }, commits: { - ref: `refs/heads/${options.branch}`, + ref: `refs/heads/${branch}`, }, } - const issueRepository = new IssueRepository(); - const isIssue = await issueRepository.isIssue( - gitInfo.owner, - gitInfo.repo, - parseInt(options.issue), - params[INPUT_KEYS.TOKEN] ?? '' - ); - - const isPullRequest = await issueRepository.isPullRequest( - gitInfo.owner, - gitInfo.repo, - parseInt(options.issue), - params[INPUT_KEYS.TOKEN] ?? '' - ); - - if (isIssue) { - params.eventName = 'issue_comment'; + // Set up issue context if provided + const parsedIssueNumber = parseInt(issueNumber); + if (issueNumber && parsedIssueNumber > 0) { + const issueRepository = new IssueRepository(); + const isIssue = await issueRepository.isIssue( + gitInfo.owner, + gitInfo.repo, + parsedIssueNumber, + params[INPUT_KEYS.TOKEN] ?? '' + ); + + if (isIssue) { + params.eventName = 'issue'; + params.issue = { + number: parsedIssueNumber, + } + params.comment = { + body: question, + } + } + } else { + // If no issue provided, set up as issue with question as body + params.eventName = 'issue'; params.issue = { - number: parseInt(options.issue), + number: 1, } params.comment = { - body: commentBody, - } - } else if (isPullRequest) { - params.eventName = 'pull_request_review_comment'; - params.pull_request = { - number: parseInt(options.issue), - } - params.pull_request_review_comment = { - body: commentBody, + body: question, } } - params[INPUT_KEYS.WELCOME_TITLE] = 'šŸš€ Asking AI started'; + params[INPUT_KEYS.WELCOME_TITLE] = 'šŸ¤” AI Reasoning Analysis'; params[INPUT_KEYS.WELCOME_MESSAGES] = [ - `Asking AI on ${gitInfo.owner}/${gitInfo.repo}/${options.branch}...`, + `Starting deep code analysis for ${gitInfo.owner}/${gitInfo.repo}/${branch}...`, + `Question: ${question.substring(0, 100)}${question.length > 100 ? '...' : ''}`, ]; logInfo(JSON.stringify(params, null, 2)); diff --git a/src/data/model/ai_response_schema.ts b/src/data/model/ai_response_schema.ts new file mode 100644 index 00000000..2ee01b37 --- /dev/null +++ b/src/data/model/ai_response_schema.ts @@ -0,0 +1,32 @@ +/** + * JSON Schema for AiResponse interface + * This schema is used to enforce structured JSON responses from the AI + */ +export const AI_RESPONSE_JSON_SCHEMA = { + type: "object", + properties: { + text_response: { + type: "string", + description: "The detailed analysis or answer to the user's question" + }, + action: { + type: "string", + enum: ["none", "analyze_files"], + description: "The action to take: 'none' if no additional files are needed, 'analyze_files' if more files are required" + }, + related_files: { + type: "array", + items: { + type: "string" + }, + description: "List of file paths that need to be analyzed if action is 'analyze_files'" + }, + complete: { + type: "boolean", + description: "Whether the response is complete and no further analysis is needed" + } + }, + required: ["text_response", "action", "related_files", "complete"], + additionalProperties: false +}; + diff --git a/src/data/model/chunked_file.ts b/src/data/model/chunked_file.ts deleted file mode 100644 index e36f4add..00000000 --- a/src/data/model/chunked_file.ts +++ /dev/null @@ -1,19 +0,0 @@ - -export class ChunkedFile { - path: string; - index: number; - type: 'line' | 'block'; - content: string; - chunks: string[]; - shasum: string = ''; - vector: number[][] = []; - - constructor(path: string, index: number, type: 'line' | 'block', content: string, shasum: string, chunks: string[]) { - this.path = path; - this.index = index; - this.content = content; - this.chunks = chunks; - this.shasum = shasum; - this.type = type; - } -} diff --git a/src/data/model/chunked_file_chunk.ts b/src/data/model/chunked_file_chunk.ts deleted file mode 100644 index 20f51fe0..00000000 --- a/src/data/model/chunked_file_chunk.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { createHash } from 'crypto'; - -export class ChunkedFileChunk { - owner: string; - repository: string; - branch: string; - path: string; - type: 'line' | 'block'; - index: number; - chunkIndex: number; - chunk: string; - shasum: string = ''; - vector: number[] = []; - - constructor( - owner: string, - repository: string, - branch: string, - path: string, - type: 'line' | 'block', - index: number, - chunkIndex: number, - chunk: string, - shasum: string, - vector: number[] - ) { - this.owner = owner; - this.repository = repository; - this.branch = branch; - this.path = path; - this.type = type; - this.index = index; - this.chunkIndex = chunkIndex; - this.chunk = chunk; - this.shasum = shasum; - this.vector = vector; - } -} - diff --git a/src/data/model/codebase_analysis_schema.ts b/src/data/model/codebase_analysis_schema.ts new file mode 100644 index 00000000..adfb811f --- /dev/null +++ b/src/data/model/codebase_analysis_schema.ts @@ -0,0 +1,30 @@ +/** + * JSON Schema for codebase analysis responses + * Used in Step 0 of the thinking process to analyze codebase structure + */ +export const CODEBASE_ANALYSIS_JSON_SCHEMA = { + "type": "array", + "description": "Array of file analyses with descriptions and relationships", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File path relative to repository root" + }, + "description": { + "type": "string", + "description": "Brief description (1-2 sentences) of what the file does in English" + }, + "relationships": { + "type": "array", + "description": "Array of file paths that this file depends on or imports", + "items": { + "type": "string" + } + } + }, + "required": ["path", "description"], + "additionalProperties": false + } +}; diff --git a/src/data/model/docker_config.ts b/src/data/model/docker_config.ts deleted file mode 100644 index ac5b68c7..00000000 --- a/src/data/model/docker_config.ts +++ /dev/null @@ -1,36 +0,0 @@ -export class DockerConfig { - private containerName: string; - private domain: string; - private port: number; - private cacheOs: string; - private cacheArch: string; - - constructor(containerName: string, domain: string, port: number, cacheOs: string, cacheArch: string) { - this.containerName = containerName; - this.domain = domain; - this.port = port; - this.cacheOs = cacheOs; - this.cacheArch = cacheArch; - } - - public getContainerName(): string { - return this.containerName; - } - - public getDomain(): string { - return this.domain; - } - - public getPort(): number { - return this.port; - } - - public getCacheOs(): string { - return this.cacheOs; - } - - public getCacheArch(): string { - return this.cacheArch; - } -} - diff --git a/src/data/model/execution.ts b/src/data/model/execution.ts index f266e5bb..19404f8e 100644 --- a/src/data/model/execution.ts +++ b/src/data/model/execution.ts @@ -16,7 +16,6 @@ import { Ai } from "./ai"; import { Branches } from "./branches"; import { Commit } from "./commit"; import { Config } from "./config"; -import { DockerConfig } from "./docker_config"; import { Emoji } from "./emoji"; import { Hotfix } from "./hotfix"; import { Images } from "./images"; @@ -65,7 +64,6 @@ export class Execution { previousConfiguration: Config | undefined; currentConfiguration: Config; tokenUser: string | undefined; - dockerConfig: DockerConfig; supabaseConfig: SupabaseConfig | undefined; inputs: any | undefined; @@ -177,7 +175,6 @@ export class Execution { constructor( debug: boolean, - dockerConfig: DockerConfig, singleAction: SingleAction, commitPrefixBuilder: string, issue: Issue, @@ -200,7 +197,6 @@ export class Execution { inputs: any | undefined ) { this.debug = debug; - this.dockerConfig = dockerConfig; this.singleAction = singleAction; this.commitPrefixBuilder = commitPrefixBuilder; this.issue = issue; diff --git a/src/data/model/single_action.ts b/src/data/model/single_action.ts index 7ea703d8..58698d17 100644 --- a/src/data/model/single_action.ts +++ b/src/data/model/single_action.ts @@ -5,19 +5,18 @@ export class SingleAction { currentSingleAction: string; actions: string[] = [ ACTIONS.DEPLOYED, - ACTIONS.COMPILE_VECTOR_SERVER, - ACTIONS.VECTOR, - ACTIONS.VECTOR_LOCAL, - ACTIONS.VECTOR_REMOVAL, + ACTIONS.AI_CACHE, + ACTIONS.AI_CACHE_LOCAL, ACTIONS.PUBLISH_GITHUB_ACTION, ACTIONS.CREATE_TAG, ACTIONS.CREATE_RELEASE, + ACTIONS.THINK, ]; /** * Actions that throw an error if the last step failed */ actionsThrowError: string[] = [ - ACTIONS.VECTOR, + ACTIONS.AI_CACHE, ACTIONS.PUBLISH_GITHUB_ACTION, ACTIONS.CREATE_RELEASE, ACTIONS.DEPLOYED, @@ -28,9 +27,9 @@ export class SingleAction { * Actions that do not require an issue */ actionsWithoutIssue: string[] = [ - ACTIONS.VECTOR, - ACTIONS.VECTOR_LOCAL, - ACTIONS.COMPILE_VECTOR_SERVER, + ACTIONS.AI_CACHE, + ACTIONS.AI_CACHE_LOCAL, + ACTIONS.THINK, ]; isIssue: boolean = false; @@ -49,20 +48,12 @@ export class SingleAction { return this.currentSingleAction === ACTIONS.DEPLOYED; } - get isCompileVectorServerAction(): boolean { - return this.currentSingleAction === ACTIONS.COMPILE_VECTOR_SERVER; + get isAiCacheAction(): boolean { + return this.currentSingleAction === ACTIONS.AI_CACHE || this.currentSingleAction === ACTIONS.AI_CACHE_LOCAL; } - get isVectorAction(): boolean { - return this.currentSingleAction === ACTIONS.VECTOR || this.currentSingleAction === ACTIONS.VECTOR_LOCAL; - } - - get isVectorLocalAction(): boolean { - return this.currentSingleAction === ACTIONS.VECTOR_LOCAL; - } - - get isVectorRemovalAction(): boolean { - return this.currentSingleAction === ACTIONS.VECTOR_REMOVAL; + get isAiCacheLocalAction(): boolean { + return this.currentSingleAction === ACTIONS.AI_CACHE_LOCAL; } get isPublishGithubAction(): boolean { @@ -77,6 +68,10 @@ export class SingleAction { return this.currentSingleAction === ACTIONS.CREATE_TAG; } + get isThinkAction(): boolean { + return this.currentSingleAction === ACTIONS.THINK; + } + get enabledSingleAction(): boolean { return this.currentSingleAction.length > 0; } diff --git a/src/data/model/think_response.ts b/src/data/model/think_response.ts new file mode 100644 index 00000000..e6e5d0d7 --- /dev/null +++ b/src/data/model/think_response.ts @@ -0,0 +1,55 @@ +export interface FileAnalysis { + path: string; + key_findings: string; + relevance: 'high' | 'medium' | 'low'; +} + +export interface ProposedChange { + file_path: string; + change_type: 'create' | 'modify' | 'delete' | 'refactor'; + description: string; + suggested_code?: string; + reasoning: string; +} + +export interface ThinkResponse { + reasoning: string; + action: 'search_files' | 'read_file' | 'analyze_code' | 'propose_changes' | 'complete' | 'update_todos'; + files_to_search?: string[]; + files_to_read?: string[]; + analyzed_files?: FileAnalysis[]; + proposed_changes?: ProposedChange[]; + todo_updates?: { + create?: Array<{ content: string; status?: 'pending' | 'in_progress' }>; + update?: Array<{ id: string; status?: 'pending' | 'in_progress' | 'completed' | 'cancelled'; notes?: string }>; + }; + complete: boolean; + final_analysis?: string; +} + +export interface ThinkStep { + step_number: number; + action: string; + reasoning: string; + files_involved?: string[]; + findings?: string; + timestamp: number; +} + +export interface ThinkTodoItem { + id: string; + content: string; + status: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + created_at: number; + updated_at: number; + completed_at?: number; + related_files?: string[]; + related_changes?: string[]; // IDs or descriptions of changes related to this task + notes?: string; // Additional notes about progress or blockers +} + +export interface ThinkTodoList { + items: ThinkTodoItem[]; + last_updated: number; +} + diff --git a/src/data/model/think_response_schema.ts b/src/data/model/think_response_schema.ts new file mode 100644 index 00000000..3ca35760 --- /dev/null +++ b/src/data/model/think_response_schema.ts @@ -0,0 +1,102 @@ +/** + * JSON Schema for ThinkResponse interface + * This schema is used for structured AI reasoning and analysis responses + */ +export const THINK_RESPONSE_JSON_SCHEMA = { + type: "object", + properties: { + reasoning: { + type: "string", + description: "Current reasoning step or analysis of the problem" + }, + action: { + type: "string", + enum: ["search_files", "read_file", "analyze_code", "propose_changes", "complete", "update_todos"], + description: "Next action to take in the reasoning process" + }, + files_to_search: { + type: "array", + items: { + type: "string" + }, + description: "List of file paths or patterns to search for (when action is 'search_files')" + }, + files_to_read: { + type: "array", + items: { + type: "string" + }, + description: "List of specific file paths to read in full (when action is 'read_file')" + }, + analyzed_files: { + type: "array", + items: { + type: "object", + properties: { + path: { type: "string" }, + key_findings: { type: "string" }, + relevance: { type: "string", enum: ["high", "medium", "low"] } + }, + required: ["path", "key_findings", "relevance"] + }, + description: "Files that have been analyzed with their findings (when action is 'analyze_code')" + }, + proposed_changes: { + type: "array", + items: { + type: "object", + properties: { + file_path: { type: "string" }, + change_type: { type: "string", enum: ["create", "modify", "delete", "refactor"] }, + description: { type: "string" }, + suggested_code: { type: "string" }, + reasoning: { type: "string" } + }, + required: ["file_path", "change_type", "description", "reasoning"] + }, + description: "Proposed changes to the codebase (when action is 'propose_changes')" + }, + complete: { + type: "boolean", + description: "Whether the reasoning process is complete" + }, + final_analysis: { + type: "string", + description: "Final comprehensive analysis and recommendations (when complete is true)" + }, + todo_updates: { + type: "object", + description: "Updates to the TODO list (when action is 'update_todos' or alongside other actions)", + properties: { + create: { + type: "array", + items: { + type: "object", + properties: { + content: { type: "string" }, + status: { type: "string", enum: ["pending", "in_progress"] } + }, + required: ["content"] + }, + description: "New TODO items to create" + }, + update: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "string" }, + status: { type: "string", enum: ["pending", "in_progress", "completed", "cancelled"] }, + notes: { type: "string" } + }, + required: ["id"] + }, + description: "Updates to existing TODO items" + } + } + } + }, + required: ["reasoning", "action", "complete"], + additionalProperties: false +}; + diff --git a/src/data/model/tokens.ts b/src/data/model/tokens.ts index 8da3f75b..e440ba63 100644 --- a/src/data/model/tokens.ts +++ b/src/data/model/tokens.ts @@ -1,11 +1,8 @@ export class Tokens { token: string; - classicToken: string; constructor( token: string, - classicToken: string, ) { this.token = token; - this.classicToken = classicToken; } } \ No newline at end of file diff --git a/src/data/repository/ai_repository.ts b/src/data/repository/ai_repository.ts index 2498bd78..07a179fc 100644 --- a/src/data/repository/ai_repository.ts +++ b/src/data/repository/ai_repository.ts @@ -1,14 +1,8 @@ import { REPO_URL, TITLE } from '../../utils/constants'; import { logDebugInfo, logError } from '../../utils/logger'; import { Ai } from '../model/ai'; - -interface OpenRouterResponse { - choices: Array<{ - message: { - content: string; - }; - }>; -} +import { AI_RESPONSE_JSON_SCHEMA } from '../model/ai_response_schema'; +import { THINK_RESPONSE_JSON_SCHEMA } from '../model/think_response_schema'; export class AiRepository { ask = async (ai: Ai, prompt: string): Promise => { @@ -28,7 +22,7 @@ export class AiRepository { const url = `https://openrouter.ai/api/v1/chat/completions`; try { - // logDebugInfo(`Sending prompt to ${model}: ${prompt}`); + logDebugInfo(`Sending prompt to ${model}: ${prompt}`); const requestBody: any = { model: model, @@ -67,7 +61,7 @@ export class AiRepository { return undefined; } - logDebugInfo(`Successfully received response from ${model}`); + // logDebugInfo(`Successfully received response from ${model}`); return data.choices[0].message.content; } catch (error) { logError(`Error querying ${model}: ${error}`); @@ -75,16 +69,157 @@ export class AiRepository { } } - askJson = async (ai: Ai, prompt: string): Promise => { - const result = await this.ask(ai, prompt); - if (!result) { + askJson = async ( + ai: Ai, + prompt: string, + schema?: any, + schemaName: string = "ai_response" + ): Promise => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + + if (!model || !apiKey) { + logError('Missing required AI configuration'); + return undefined; + } + + // logDebugInfo(`šŸ”Ž Model: ${model}`); + // logDebugInfo(`šŸ”Ž API Key: ***`); + // logDebugInfo(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + + const url = `https://openrouter.ai/api/v1/chat/completions`; + + // Use provided schema or default to AI_RESPONSE_JSON_SCHEMA + const responseSchema = schema || AI_RESPONSE_JSON_SCHEMA; + + try { + const requestBody: any = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + response_format: { + type: "json_schema", + json_schema: { + name: schemaName, + schema: responseSchema, + strict: true + } + } + }; + + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': REPO_URL, + 'X-Title': TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + logError(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + + const data: any = await response.json(); + + if (!data.choices || data.choices.length === 0) { + logError('No response content received from API'); + return undefined; + } + + // logDebugInfo(`Successfully received response from ${model}`); + const content = data.choices[0].message.content; + + // logDebugInfo(`Response: ${content}`); + return JSON.parse(content); + } catch (error) { + logError(`Error querying ${model}: ${error}`); + return undefined; + } + } + + askThinkJson = async (ai: Ai, prompt: string): Promise => { + const model = ai.getOpenRouterModel(); + const apiKey = ai.getOpenRouterApiKey(); + const providerRouting = ai.getProviderRouting(); + + if (!model || !apiKey) { + logError('Missing required AI configuration'); + return undefined; + } + + logDebugInfo(`šŸ”Ž Model: ${model}`); + logDebugInfo(`šŸ”Ž API Key: ***`); + logDebugInfo(`šŸ”Ž Provider Routing: ${JSON.stringify(providerRouting, null, 2)}`); + + const url = `https://openrouter.ai/api/v1/chat/completions`; + + try { + const requestBody: any = { + model: model, + messages: [ + { role: 'user', content: prompt }, + ], + response_format: { + type: "json_schema", + json_schema: { + name: "think_response", + schema: THINK_RESPONSE_JSON_SCHEMA, + strict: true + } + } + }; + + // Add provider routing configuration if it exists and has properties + if (Object.keys(providerRouting).length > 0) { + requestBody.provider = providerRouting; + } + + const response = await fetch(url, { + method: 'POST', + headers: { + Authorization: `Bearer ${apiKey}`, + 'HTTP-Referer': REPO_URL, + 'X-Title': TITLE, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(requestBody), + }); + + if (!response.ok) { + const errorText = await response.text(); + console.error('API Response:', errorText); + logError(`Error from API: ${response.status} ${response.statusText}`); + return undefined; + } + + const data: any = await response.json(); + + if (!data.choices || data.choices.length === 0) { + logError('No response content received from API'); + return undefined; + } + + // logDebugInfo(`Successfully received response from ${model}`); + const content = data.choices[0].message.content; + + // logDebugInfo(`Response: ${content}`); + return JSON.parse(content); + } catch (error) { + logError(`Error querying ${model}: ${error}`); return undefined; } - // Clean the response by removing ```json markers if present - const cleanedResult = result - .replace(/^```json\n?/, '') // Remove ```json at the start - .replace(/\n?```$/, '') // Remove ``` at the end - .trim(); - return JSON.parse(cleanedResult); } } diff --git a/src/data/repository/docker_repository.ts b/src/data/repository/docker_repository.ts deleted file mode 100644 index 1a2d6114..00000000 --- a/src/data/repository/docker_repository.ts +++ /dev/null @@ -1,645 +0,0 @@ -import Docker, { Container } from 'dockerode'; -import path from 'path'; -import axios from 'axios'; -import { logDebugError, logDebugInfo, logError } from '../../utils/logger'; -import { Execution } from '../model/execution'; -import { execSync, spawn } from 'child_process'; - -interface EmbedRequest { - instructions: string[]; - texts: string[]; -} - -interface EmbedResponse { - embeddings: number[][]; -} - -interface HealthCheckResponse { - status: 'ready' | 'error' | string; - progress?: number; - message?: string; -} - -export class DockerRepository { - private docker: Docker; - private readonly dockerDir: string; - - constructor() { - this.docker = new Docker(); - this.dockerDir = path.join(process.cwd(), 'docker'); - } - - private isGitHubActions(): boolean { - return process.env.GITHUB_ACTIONS === 'true'; - } - - private isSelfHostedRunner(): boolean { - return process.env.RUNNER_TEMP?.includes('actions-runner') || - process.env.GITHUB_RUN_ID === undefined || - process.env.GITHUB_HOSTED === 'false'; - } - - private shouldUsePrebuiltImage(): boolean { - return this.isGitHubActions() && !this.isSelfHostedRunner(); - } - - private shouldUseLocalImage(): boolean { - return !this.isGitHubActions() || this.isSelfHostedRunner(); - } - - getArchitectureType(): string { - const platform = process.platform; - const arch = process.arch; - - if (platform === 'darwin' && arch === 'arm64') return 'arm64'; - if (platform === 'darwin' && arch === 'x64') return 'amd64'; - if (platform === 'linux' && arch === 'x64') return 'amd64'; - if (platform === 'linux' && arch === 'arm64') return 'arm64'; - if (platform === 'linux' && arch === 'arm') return 'armv7'; - if (platform === 'win32' && arch === 'x64') return 'amd64'; - - logDebugInfo(`🐳 🟔 Unknown architecture: ${platform}/${arch}, defaulting to amd64`); - return 'amd64'; - } - - // ============================== - // šŸ”§ Core Docker Lifecycle - // ============================== - - prepareLocalVectorServer = async (param: Execution): Promise => { - logDebugInfo('🐳 🟔 Preparing local vector server...'); - - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - - try { - // Authenticate with registry - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - - // Check if image already exists locally - const localImageExists = await this.imageExists(param); - if (localImageExists) { - logDebugInfo(`🐳 🟢 Local image ${imageName} already exists, skipping pull`); - return; - } - - // Check if multi-architecture image exists in registry - const registryImageExists = await this.checkMultiArchImageInRegistry(param); - if (!registryImageExists) { - throw new Error(`Multi-architecture image not found in registry: ${registryImageName}. Please build the image first using PrepareAIContainerUseCase.`); - } - - // Pull the multi-architecture image from registry - logDebugInfo(`🐳 🟔 Pulling multi-architecture image from registry: ${registryImageName}`); - - try { - execSync(`docker pull ${registryImageName}`, { - stdio: 'inherit', - env: { ...process.env, DOCKER_BUILDKIT: '1' } - }); - logDebugInfo(`🐳 🟢 Successfully pulled multi-architecture image: ${registryImageName}`); - } catch (error) { - logError(`🐳 šŸ”“ Failed to pull image: ${error}`); - throw error; - } - - // Tag the pulled image with local name for consistency - execSync(`docker tag ${registryImageName} ${imageName}`, { stdio: 'pipe' }); - - logDebugInfo(`🐳 🟢 Multi-architecture image pulled and tagged successfully: ${imageName}`); - } catch (error) { - logError(`🐳 šŸ”“ Failed to prepare local vector server: ${error}`); - throw error; - } - } - - private async checkMultiArchImageInRegistry(param: Execution): Promise { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - - try { - logDebugInfo(`🐳 🟔 Checking multi-architecture image in registry: ${registryImageName}`); - - // Try to inspect the manifest to check if multi-arch image exists - const output = execSync(`docker manifest inspect ${registryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - - logDebugInfo(`🐳 🟔 Manifest output: ${output.substring(0, 500)}...`); - - // Check if the manifest contains both architectures - const hasAmd64 = output.includes('"architecture": "amd64"'); - const hasArm64 = output.includes('"architecture": "arm64"'); - - logDebugInfo(`🐳 🟔 Registry image check - AMD64: ${hasAmd64}, ARM64: ${hasArm64}`); - return hasAmd64 && hasArm64; - } catch (error) { - logDebugInfo(`🐳 🟔 Multi-architecture image not found in registry: ${registryImageName} - ${error}`); - - // If specific version not found, try latest tag as fallback - if (!imageName.includes('latest')) { - logDebugInfo(`🐳 🟔 Trying latest tag as fallback...`); - const latestImageName = `${this.getImageName(param)}:latest`; - const latestRegistryImageName = `ghcr.io/${param.owner}/${latestImageName}`; - - try { - const latestOutput = execSync(`docker manifest inspect ${latestRegistryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - - const hasAmd64Latest = latestOutput.includes('"architecture": "amd64"'); - const hasArm64Latest = latestOutput.includes('"architecture": "arm64"'); - - if (hasAmd64Latest && hasArm64Latest) { - logDebugInfo(`🐳 🟢 Found latest multi-architecture image, will use that instead`); - return true; - } - } catch { - logDebugInfo(`🐳 🟔 Latest image also not found in registry`); - } - } - - return false; - } - } - - checkVersionExistsInRegistry = async (param: Execution): Promise => { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - - try { - logDebugInfo(`🐳 🟔 Checking if version already exists in registry: ${registryImageName}`); - - // Try to inspect the manifest to check if version exists - const output = execSync(`docker manifest inspect ${registryImageName}`, { - encoding: 'utf8', - stdio: 'pipe' - }); - - // Check if the manifest contains both architectures (multi-arch image) - const hasAmd64 = output.includes('"architecture": "amd64"'); - const hasArm64 = output.includes('"architecture": "arm64"'); - - const versionExists = hasAmd64 && hasArm64; - logDebugInfo(`🐳 🟔 Version ${imageName} exists in registry: ${versionExists}`); - - return versionExists; - } catch (error) { - logDebugInfo(`🐳 🟔 Version ${imageName} not found in registry: ${error}`); - return false; - } - } - - startContainer = async (param: Execution): Promise => { - logDebugInfo('🐳 🟔 Starting Docker container...'); - const isRunning = await this.isContainerRunning(param); - if (isRunning) { - logDebugInfo('🐳 🟢 Docker container is ready'); - return; - } - - try { - /* - if (this.shouldUsePrebuiltImage()) { - const imageExists = await this.imageExists(param); - if (!imageExists) { - const pulled = await this.pullPrebuiltImage(param); - if (!pulled) throw new Error('Prebuilt image not available'); - } - } else if (this.shouldUseLocalImage()) { - const imageExists = await this.imageExists(param); - if (!imageExists) await this.buildImage(param); - }*/ - - await this.runContainer(param); - logDebugInfo('🐳 🟢 Container started successfully'); - } catch (error) { - logError('Error starting container: ' + error); - throw error; - } - } - - private runContainer = async (param: Execution): Promise => { - const container = await this.getContainer(param); - const info = await container.inspect(); - if (info.State.Status !== 'running') await container.start(); - await this.waitForContainer(param); - } - - imageExists = async (param: Execution): Promise => { - const images = await this.docker.listImages(); - return images.some(img => - img.RepoTags && img.RepoTags.includes(this.getImageNameWithTag(param)) - ); - } - - getImageName(param: Execution): string { - return param.dockerConfig.getContainerName(); - } - - getImageNameWithTag(param: Execution): string { - const version = this.generateImageVersion(param); - return `${this.getImageName(param)}:${version}`; - } - - private generateImageVersion(param: Execution): string { - if (param.singleAction.version.length > 0) { - return `v${param.singleAction.version}`; - } - - // Fallback to latest - return 'latest'; - } - - private generateImageTags(param: Execution): string[] { - const baseImageName = this.getImageName(param); - const tags: string[] = []; - - // Always include the specific version - const version = this.generateImageVersion(param); - tags.push(`${baseImageName}:${version}`); - tags.push(`${baseImageName}:latest`); - - return tags; - } - - private pullPrebuiltImage = async (param: Execution): Promise => { - try { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - const stream = await this.docker.pull(registryImageName); - await new Promise((resolve, reject) => { - this.docker.modem.followProgress(stream, (err: any) => { - if (err) reject(err); else resolve(true); - }); - }); - return true; - } catch { - return false; - } - } - - // ============================== - // 🧱 Build Image - // ============================== - - buildImage = async (param: Execution): Promise => { - // const imageName = this.getImageNameWithTag(param); - // const archType = this.getArchitectureType(); - - // Check if Docker Buildx is available for multi-architecture builds - const buildxAvailable = await this.checkDockerBuildxAvailable(); - - if (buildxAvailable) { - await this.buildMultiArchImage(param); - } - - /* else { - logDebugInfo(`🐳 🟔 Building single-architecture Docker image: ${imageName} for architecture: ${archType}`); - await this.buildSingleArchImage(param, imageName, archType); - }*/ - - logDebugInfo('🐳 🟢 Docker image built successfully'); - } - - private async checkDockerBuildxAvailable(): Promise { - try { - // Check if Docker Buildx is installed - execSync('docker buildx version', { stdio: 'pipe' }); - - // Check if we can create a multi-platform builder - try { - const testBuilderName = 'test-multiarch-builder'; - execSync(`docker buildx create --name ${testBuilderName} --driver docker-container --platform linux/amd64,linux/arm64`, { stdio: 'pipe' }); - execSync(`docker buildx rm ${testBuilderName}`, { stdio: 'pipe' }); - logDebugInfo('🐳 🟢 Docker Buildx supports multi-platform builds'); - return true; - } catch { - logDebugInfo('🐳 🟔 Docker Buildx available but multi-platform not supported, will create custom builder'); - return true; // Still return true, we'll handle the builder creation in buildMultiArchImage - } - } catch { - logDebugInfo('🐳 🟔 Docker Buildx not available, falling back to single-architecture build'); - return false; - } - } - - private async buildMultiArchImage(param: Execution): Promise { - const imageTags = this.generateImageTags(param); - const registryImageTags = imageTags.map(tag => `ghcr.io/${param.owner}/${tag}`); - - logDebugInfo(`🐳 🟔 Building multi-architecture Docker image with tags: ${imageTags.join(', ')}`); - logDebugInfo(`🐳 🟔 Registry tags: ${registryImageTags.join(', ')}`); - - // Authenticate with registry before building - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - - // Create or use a multi-platform builder - const builderName = 'git-board-flow-multiarch'; - await this.ensureMultiPlatformBuilder(builderName); - - // Build and push multi-architecture image using Docker Buildx - const buildCommand = [ - 'docker', 'buildx', 'build', - '--builder', builderName, - '--platform', 'linux/amd64,linux/arm64', - ...registryImageTags.flatMap(tag => ['--tag', tag]), - '--push', - '--file', path.join(this.dockerDir, 'Dockerfile'), - this.dockerDir - ]; - - logDebugInfo(`🐳 🟔 Executing: ${buildCommand.join(' ')}`); - - try { - execSync(buildCommand.join(' '), { - stdio: 'inherit', - env: { ...process.env, DOCKER_BUILDKIT: '1' } - }); - logDebugInfo(`🐳 🟢 Multi-architecture image built and pushed successfully with tags: ${imageTags.join(', ')}`); - - await this.cleanupDanglingImages(); - await this.cleanupBuildxBuilder(); - } catch (error) { - logError(`🐳 šŸ”“ Multi-architecture build failed: ${error}`); - throw error; - } - } - - private async ensureMultiPlatformBuilder(builderName: string): Promise { - try { - // Check if builder already exists - const listCommand = ['docker', 'buildx', 'ls']; - const output = execSync(listCommand.join(' '), { encoding: 'utf8', stdio: 'pipe' }); - - if (output.includes(builderName)) { - logDebugInfo(`🐳 🟢 Multi-platform builder '${builderName}' already exists`); - return; - } - - // Create new multi-platform builder - logDebugInfo(`🐳 🟔 Creating multi-platform builder '${builderName}'...`); - const createCommand = [ - 'docker', 'buildx', 'create', - '--name', builderName, - '--driver', 'docker-container', - '--platform', 'linux/amd64,linux/arm64' - ]; - - execSync(createCommand.join(' '), { stdio: 'inherit' }); - - // Start the builder - const startCommand = ['docker', 'buildx', 'inspect', '--bootstrap', builderName]; - execSync(startCommand.join(' '), { stdio: 'inherit' }); - - logDebugInfo(`🐳 🟢 Multi-platform builder '${builderName}' created and started successfully`); - } catch (error) { - logError(`🐳 šŸ”“ Failed to create multi-platform builder: ${error}`); - throw error; - } - } - - /*private async buildSingleArchImage(param: Execution, imageName: string, archType: string): Promise { - const stream = await this.docker.buildImage({ - context: this.dockerDir, - src: ['Dockerfile', 'requirements.txt', 'main.py'], - }, { - t: imageName, - dockerfile: 'Dockerfile', - buildargs: {}, - nocache: false, - platform: `linux/${archType}`, - }); - - await new Promise((resolve, reject) => { - this.docker.modem.followProgress(stream, (err: any, res: any) => { - if (err) reject(err); - else resolve(res); - }, (event: any) => { - if (event.stream) logDebugInfo(`🐳 🟔 ${event.stream.trim()}`); - }); - }); - }*/ - - // ============================== - // 🧩 Manifest / Registry Handling - // ============================== - - /*checkImageInRegistry = async (param: Execution): Promise => { - const imageName = this.getImageNameWithTag(param); - const registryImageName = `ghcr.io/${param.owner}/${imageName}`; - const archType = this.getArchitectureType(); - const dockerPlatform = `linux/${archType}`; - - try { - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - const manifestProcess = spawn('docker', ['manifest', 'inspect', registryImageName]); - - const output = await new Promise((resolve) => { - let data = ''; - manifestProcess.stdout.on('data', (chunk) => data += chunk.toString()); - manifestProcess.on('close', () => resolve(data)); - }); - - logDebugInfo(`🐳 🟔 Manifest output: ${output}`); - - if (output.includes(`"${archType}"`)) { - logDebugInfo(`🐳 🟢 Image already has platform ${dockerPlatform}`); - return true; - } else if (output.includes('"architecture"')) { - logDebugInfo(`🐳 🟔 Image exists but missing ${dockerPlatform}`); - return false; - } - return false; - } catch { - logDebugInfo(`🐳 🟔 No manifest found for ${registryImageName}`); - return false; - } - }*/ - - /* - pushImageToRegistry = async (param: Execution, imageName: string): Promise => { - const buildxAvailable = await this.checkDockerBuildxAvailable(); - - if (buildxAvailable) { - // For multi-architecture builds, the image is already pushed during build - logDebugInfo('🐳 🟢 Multi-architecture image already pushed during build process'); - return; - } - - // Fallback to single-architecture push for systems without Buildx - const archType = this.getArchitectureType(); - const dockerPlatform = `linux/${archType}`; - const registryImageName = `ghcr.io/${param.owner}/${imageName}:latest`; - - await this.authenticateWithRegistry(param.owner, param.tokens.classicToken); - - // Tag + Push architecture-specific image - execSync(`docker tag ${imageName}:latest ${registryImageName}`, { stdio: 'inherit' }); - execSync(`docker push ${registryImageName}`, { stdio: 'inherit' }); - - // Merge with existing manifest if necessary - try { - const manifestExists = await this.checkImageInRegistry(param); - if (manifestExists) { - logDebugInfo(`🐳 🟔 Amending existing manifest with ${dockerPlatform}...`); - execSync(`docker manifest create ${registryImageName} --amend ${registryImageName}`, { stdio: 'inherit' }); - } else { - logDebugInfo(`🐳 🟔 Creating new manifest list for ${dockerPlatform}...`); - execSync(`docker manifest create ${registryImageName} ${registryImageName}`, { stdio: 'inherit' }); - } - - execSync(`docker manifest push ${registryImageName}`, { stdio: 'inherit' }); - logDebugInfo(`🐳 🟢 Multi-arch manifest updated successfully for ${dockerPlatform}`); - } catch (err) { - logError(`🐳 šŸ”“ Manifest merge failed: ${err}`); - } - }*/ - - private authenticateWithRegistry = async (organizationName: string, token: string): Promise => { - try { - logDebugInfo(`🐳 🟔 Authenticating with GitHub Container Registry as ${organizationName}`); - execSync(`echo ${token} | docker login ghcr.io -u ${organizationName} --password-stdin`, { stdio: 'pipe' }); - logDebugInfo(`🐳 🟢 Authenticated successfully`); - } catch (error: any) { - logError(`🐳 šŸ”“ Docker login error: ${error.message}`); - throw error; - } - } - - // ============================== - // 🧼 Misc Helpers - // ============================== - - private async getContainer(param: Execution): Promise { - const containerId = await this.getContainerIdByName(param); - const imageName = this.getImageNameWithTag(param); - if (containerId) return this.docker.getContainer(containerId); - return this.docker.createContainer({ - Image: imageName, - ExposedPorts: { [`${param.dockerConfig.getPort()}/tcp`]: {} }, - HostConfig: { - PortBindings: { [`${param.dockerConfig.getPort()}/tcp`]: [{ HostPort: param.dockerConfig.getPort().toString() }] }, - }, - name: this.getImageName(param), - }); - } - - private async waitForContainer(param: Execution): Promise { - const maxAttempts = 30; - const interval = 2000; - for (let i = 0; i < maxAttempts; i++) { - try { - const res = await axios.get(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/health`); - if (res.data.status === 'ready') return; - } catch {} - await new Promise(r => setTimeout(r, interval)); - } - throw new Error('Container did not become ready'); - } - - private async getContainerIdByName(param: Execution): Promise { - const containers = await this.docker.listContainers({ all: true }); - const found = containers.find(c => c.Names.includes(`/${this.getImageName(param)}`)); - return found?.Id || ''; - } - - async isContainerRunning(param: Execution): Promise { - const containers = await this.docker.listContainers({ all: true }); - const container = containers.find(c => c.Names.includes(`/${this.getImageName(param)}`)); - return container?.State === 'running'; - } - - getEmbedding = async (param: Execution, textInstructionsPairs: [string, string][]): Promise => { - try { - const request: EmbedRequest = { - instructions: textInstructionsPairs.map(pair => pair[0]), - texts: textInstructionsPairs.map(pair => pair[1]) - }; - - const response = await axios.post(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/embed`, request, { - headers: { - 'Content-Type': 'application/json', - }, - family: 4 - }); - - const data = response.data as EmbedResponse; - return data.embeddings; - } catch (error) { - logError(`🐳 šŸ”“ Error getting embedding: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - - getSystemInfo = async (param: Execution): Promise => { - const response = await axios.get(`http://${param.dockerConfig.getDomain()}:${param.dockerConfig.getPort()}/system-info`, { - family: 4 - }); - return response.data; - } - - stopContainer = async (param: Execution): Promise => { - logDebugInfo('🐳 🟠 Stopping Docker container...'); - if (!this.isContainerRunning(param)) return; - - const containerId = await this.getContainerIdByName(param); - if (!containerId) return; - - try { - const container = this.docker.getContainer(containerId); - await container.stop(); - await container.remove(); - logDebugInfo('🐳 ⚪ Docker container stopped'); - - // Clean up dangling images after stopping (only on self-hosted runners) - if (this.isSelfHostedRunner()) { - await this.cleanupDanglingImages(); - await this.cleanupBuildxBuilder(); - } - } catch (error) { - logError('🐳 šŸ”“ Error stopping container: ' + error); - } - } - - private cleanupDanglingImages = async (): Promise => { - try { - const images = await this.docker.listImages({ filters: { dangling: ['true'] } }); - if (images.length > 0) { - logDebugInfo(`🐳 🟔 Found ${images.length} dangling images, cleaning up...`); - let removedCount = 0; - for (const image of images) { - try { - // Force remove to handle different Docker managers (OrbStack, Colima, Docker Desktop) - await this.docker.getImage(image.Id).remove({ force: true }); - removedCount++; - logDebugInfo(`🐳 🟔 Removed dangling image: ${image.Id.substring(0, 12)}`); - } catch (error) { - logDebugError(`Error removing dangling image ${image.Id}: ${error}`); - } - } - logDebugInfo(`🐳 🟢 Dangling images cleanup completed: ${removedCount}/${images.length} removed`); - } - } catch (error) { - logDebugError('Error cleaning up dangling images: ' + error); - } - } - - private cleanupBuildxBuilder = async (): Promise => { - try { - const builderName = 'git-board-flow-multiarch'; - const listCommand = ['docker', 'buildx', 'ls']; - const output = execSync(listCommand.join(' '), { encoding: 'utf8', stdio: 'pipe' }); - - if (output.includes(builderName)) { - logDebugInfo(`🐳 🟔 Cleaning up Buildx builder '${builderName}'...`); - execSync(`docker buildx rm ${builderName}`, { stdio: 'pipe' }); - logDebugInfo(`🐳 🟢 Buildx builder '${builderName}' removed successfully`); - } - } catch (error) { - logDebugError(`Error cleaning up Buildx builder: ${error}`); - } - } -} diff --git a/src/data/repository/file_repository.ts b/src/data/repository/file_repository.ts index 26c30edd..37110e3b 100644 --- a/src/data/repository/file_repository.ts +++ b/src/data/repository/file_repository.ts @@ -1,6 +1,5 @@ import * as github from "@actions/github"; import { logError } from "../../utils/logger"; -import { ChunkedFile } from "../model/chunked_file"; import { createHash } from "crypto"; type Block = { @@ -123,107 +122,6 @@ export class FileRepository { } } - getChunkedRepositoryContent = async ( - owner: string, - repository: string, - branch: string, - chunkSize: number, - token: string, - ignoreFiles: string[], - progress: (fileName: string) => void, - ignoredFiles: (fileName: string) => void, - ): Promise> => { - const fileContents = await this.getRepositoryContent(owner, repository, token, branch, ignoreFiles, progress, ignoredFiles); - const chunkedFilesMap = new Map(); - - for (const [path, content] of fileContents.entries()) { - const shasum = this.calculateShasum(content); - chunkedFilesMap.set(path, [ - ...this.getChunksByLines(path, content, shasum, chunkSize), - ...this.getChunksByBlocks(path, content, shasum, chunkSize), - ]); - } - - return chunkedFilesMap; - } - - getChunksByLines = (path: string, content: string, shasum: string, chunkSize: number): ChunkedFile[] => { - const chunkedFiles: ChunkedFile[] = []; - const lines = content.split('\n'); - const chunks: string[][] = []; - let currentChunk: string[] = []; - - for (const line of lines) { - if (this.shouldIgnoreLine(line)) { - continue; - } - currentChunk.push(line.trim()); - if (currentChunk.length >= chunkSize) { - chunks.push([...currentChunk]); - currentChunk = []; - } - } - - // Add the last chunk if it's not empty - if (currentChunk.length > 0) { - chunks.push(currentChunk); - } - - // Create ChunkedFile objects for each chunk - chunks.forEach((chunkLines, index) => { - const chunkContent = chunkLines.join('\n'); - chunkedFiles.push( - new ChunkedFile( - path, - index, - 'line', - chunkContent, - shasum, - chunkLines - ) - ); - }); - - return chunkedFiles; - } - - getChunksByBlocks = (path: string, content: string, shasum: string, chunkSize: number): ChunkedFile[] => { - const chunkedFiles: ChunkedFile[] = []; - const blocks = this.extractCodeBlocks(content); - const chunks: string[][] = []; - let currentChunk: string[] = []; - - for (const block of blocks) { - currentChunk.push(block.content); - if (currentChunk.length >= chunkSize) { - chunks.push([...currentChunk]); - currentChunk = []; - } - } - - // Add the last chunk if it's not empty - if (currentChunk.length > 0) { - chunks.push(currentChunk); - } - - // Create ChunkedFile objects for each chunk - chunks.forEach((chunkLines, index) => { - const chunkContent = chunkLines.join('\n'); - chunkedFiles.push( - new ChunkedFile( - path, - index, - 'block', - chunkContent, - shasum, - chunkLines - ) - ); - }); - - return chunkedFiles; - } - private shouldIgnoreFile(filename: string, ignorePatterns: string[]): boolean { // First check for .DS_Store if (filename.endsWith('.DS_Store')) { diff --git a/src/data/repository/supabase_repository.ts b/src/data/repository/supabase_repository.ts index 135339c7..d5eed102 100644 --- a/src/data/repository/supabase_repository.ts +++ b/src/data/repository/supabase_repository.ts @@ -1,12 +1,24 @@ import { createClient } from '@supabase/supabase-js'; import { COMMAND } from '../../utils/constants'; import { logDebugInfo, logError, logInfo, logSingleLine } from '../../utils/logger'; -import { ChunkedFile } from '../model/chunked_file'; -import { ChunkedFileChunk } from '../model/chunked_file_chunk'; import { SupabaseConfig } from '../model/supabase_config'; +export interface AICachedFileInfo { + owner: string; + repository: string; + branch: string; + file_name: string; + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; + created_at?: string; + last_updated?: string; +} + export class SupabaseRepository { - private readonly CHUNKS_TABLE = 'chunks'; + private readonly AI_FILE_CACHE_TABLE = 'ai_file_cache'; private readonly MAX_BATCH_SIZE = 500; private readonly DEFAULT_TIMEOUT = 30000; // 30 seconds private supabase: any; @@ -45,137 +57,105 @@ export class SupabaseRepository { }); } - setChunkedFile = async ( + /** + * Set or update AI file cache entry + * If SHA hasn't changed, this will update the entry + */ + setAIFileCache = async ( owner: string, repository: string, branch: string, - chunkedFile: ChunkedFile, - ): Promise => { - try { - const insertPromises = chunkedFile.chunks.map(async (chunk, index) => { - const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .insert({ - owner, - repository, - branch, - path: chunkedFile.path, - type: chunkedFile.type, - index: chunkedFile.index, - chunk_index: index, - content: chunk, - shasum: chunkedFile.shasum, - vector: chunkedFile.vector[index], - updated_at: new Date().toISOString() - }); - - if (error) { - chunkedFile.vector = []; - logError(`Error inserting index ${chunkedFile.index} chunk ${index} for file ${chunkedFile.path}: ${JSON.stringify(chunkedFile, null, 2)}`); - logError(`Inserting error: ${JSON.stringify(error, null, 2)}`); - throw error; - } - }); - - await Promise.all(insertPromises); - } catch (error) { - logError(`Error setting chunked file ${chunkedFile.path}: ${JSON.stringify(error, null, 2)}`); - // throw error; + fileInfo: { + file_name: string; + path: string; + sha: string; + description: string; + consumes: string[]; + consumed_by: string[]; } - } - - removeChunksByShasum = async ( - owner: string, - repository: string, - branch: string, - shasum: string, ): Promise => { try { const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .delete() - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('shasum', shasum); + .from(this.AI_FILE_CACHE_TABLE) + .upsert({ + owner, + repository, + branch, + file_name: fileInfo.file_name, + path: fileInfo.path, + sha: fileInfo.sha, + description: fileInfo.description, + consumes: fileInfo.consumes, + consumed_by: fileInfo.consumed_by, + last_updated: new Date().toISOString() + }, { + onConflict: 'owner,repository,branch,path' + }); if (error) { + logError(`Error setting AI file cache for ${fileInfo.path}: ${JSON.stringify(error, null, 2)}`); throw error; } } catch (error) { - logError(`Error removing chunks by shasum: ${JSON.stringify(error, null, 2)}`); + logError(`Error setting AI file cache ${fileInfo.path}: ${JSON.stringify(error, null, 2)}`); throw error; } } - getChunkedFileByShasum = async ( + /** + * Get AI file cache entry by path + */ + getAIFileCache = async ( owner: string, repository: string, branch: string, - type: string, - shasum: string, - ): Promise => { + filePath: string, + ): Promise => { try { const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) + .from(this.AI_FILE_CACHE_TABLE) .select('*') .eq('owner', owner) .eq('repository', repository) .eq('branch', branch) - .eq('type', type) - .eq('shasum', shasum) - .order('chunk_index'); + .eq('path', filePath) + .single(); if (error) { - logError(`Supabase error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; - } - - if (!data) { - return []; + if (error.code === 'PGRST116') { + // No rows returned + return null; + } + logError(`Error getting AI file cache: ${JSON.stringify(error, null, 2)}`); + return null; } - return data.map((doc: any) => new ChunkedFileChunk( - doc.owner, - doc.repository, - doc.branch, - doc.path, - doc.type, - doc.index, - doc.chunk_index, - doc.content, - doc.shasum, - doc.vector - )); + return data as AICachedFileInfo; } catch (error) { - logError(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - return []; + logError(`Error getting AI file cache: ${JSON.stringify(error, null, 2)}`); + return null; } } - - getChunks = async ( + /** + * Get all AI file cache entries for a branch + */ + getAIFileCachesByBranch = async ( owner: string, repository: string, branch: string, - path: string, - type: string, - index: number, - ): Promise => { + ): Promise => { try { const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) + .from(this.AI_FILE_CACHE_TABLE) .select('*') .eq('owner', owner) .eq('repository', repository) .eq('branch', branch) - .eq('path', path) - .eq('type', type) - .eq('index', index) - .order('chunk_index'); + .order('path'); if (error) { - logError(`Supabase error getting chunked file: ${JSON.stringify(error, null, 2)}`); + logError(`Error getting AI file caches by branch: ${JSON.stringify(error, null, 2)}`); return []; } @@ -183,427 +163,128 @@ export class SupabaseRepository { return []; } - return data.map((doc: any) => new ChunkedFileChunk( - doc.owner, - doc.repository, - doc.branch, - doc.path, - doc.type, - doc.index, - doc.chunk_index, - doc.chunk, - doc.shasum, - doc.vector - )); + return data as AICachedFileInfo[]; } catch (error) { - logError(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); + logError(`Error getting AI file caches by branch: ${JSON.stringify(error, null, 2)}`); return []; } } - getChunksByShasum = async ( - owner: string, - repository: string, - branch: string, - shasum: string, - ): Promise => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('shasum', shasum) - .order('chunk_index'); - - if (error) { - throw error; - } - - if (!data) { - return []; - } - return data.map((doc: any) => new ChunkedFileChunk( - doc.owner, - doc.repository, - doc.branch, - doc.path, - doc.type, - doc.index, - doc.chunk_index, - doc.chunk, - doc.shasum, - doc.vector - )); - } catch (error) { - logError(`Error getting chunked file: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - - updateVector = async ( + /** + * Remove AI file cache entry by path + */ + removeAIFileCacheByPath = async ( owner: string, repository: string, branch: string, - path: string, - index: number, - chunkIndex: number, - vector: number[] + filePath: string, ): Promise => { try { const { error } = await this.supabase - .from(this.CHUNKS_TABLE) - .update({ vector }) + .from(this.AI_FILE_CACHE_TABLE) + .delete() .eq('owner', owner) .eq('repository', repository) .eq('branch', branch) - .eq('path', path) - .eq('index', index) - .eq('chunk_index', chunkIndex); - - if (error) { - throw error; - } - } catch (error) { - logError(`Error updating vector: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - - matchChunks = async ( - owner: string, - repository: string, - branch: string, - type: string, - queryEmbedding: number[], - matchCount: number = 5 - ): Promise => { - try { - const { data, error } = await this.supabase - .rpc('match_chunks', { - owner_param: owner, - repository_param: repository, - branch_param: branch, - type_param: type, - query_embedding: queryEmbedding, - match_count: matchCount - }); + .eq('path', filePath); if (error) { - logError(`Error matching chunks: ${JSON.stringify(error, null, 2)}`); throw error; } - - return data.map((doc: any) => new ChunkedFileChunk( - doc.owner, - doc.repository, - doc.branch, - doc.path, - doc.type, - doc.index, - doc.chunk_index, - doc.content, - doc.shasum, - doc.vector - )); } catch (error) { - logError(`Error matching chunks: ${JSON.stringify(error, null, 2)}`); + logError(`Error removing AI file cache by path: ${JSON.stringify(error, null, 2)}`); throw error; } } - duplicateChunksByBranch = async ( + /** + * Duplicate AI file cache entries from one branch to another + */ + duplicateAIFileCacheByBranch = async ( owner: string, repository: string, sourceBranch: string, targetBranch: string, ): Promise => { - const count = await this.countBranchEntries(owner, repository, sourceBranch); - logDebugInfo(`Counting chunks in branch ${sourceBranch}: ${count}`); - - if (count < 10000) { - await this.duplicateBranchEntries(owner, repository, sourceBranch, targetBranch); - } else { - const filePaths = await this.getDistinctPaths(owner, repository, sourceBranch); - logDebugInfo(`Counting files in branch ${sourceBranch}: ${filePaths.length}`); - for (const path of filePaths) { - await this.duplicateFileEntries(owner, repository, sourceBranch, path, targetBranch); - } - } - } - - removeChunksByBranch = async ( - owner: string, - repository: string, - branch: string, - ): Promise => { - const count = await this.countBranchEntries(owner, repository, branch); - logDebugInfo(`Counting chunks in branch ${branch}: ${count}`); - - if (count < 10000) { - await this.deleteBranchEntries(owner, repository, branch); - } else { - const filePaths = await this.getDistinctPaths(owner, repository, branch); - logDebugInfo(`Counting files in branch ${branch}: ${filePaths.length}`); - for (const path of filePaths) { - await this.removeChunksByPath(owner, repository, branch, path); - } - } - - logDebugInfo(`Checking if all chunks are deleted from branch ${branch}`); - - // Retry logic to ensure all chunks are deleted - const maxRetries = 5; - const retryDelay = 10000; // 1 second - let retryCount = 0; - - while (retryCount < maxRetries) { - const { data: chunks, error: chunksError } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - - if (chunksError) { - logError(`Error checking chunks by branch: ${JSON.stringify(chunksError, null, 2)}`); - throw chunksError; - } - - if (!chunks || chunks.length === 0) { - // No chunks found, deletion successful - logDebugInfo(`Removed all chunks from branch ${branch}`); - return; - } - - retryCount++; - if (retryCount < maxRetries) { - logDebugInfo(`Chunks still present for branch ${branch}, retrying in ${retryDelay}ms (attempt ${retryCount}/${maxRetries})`); - await new Promise(resolve => setTimeout(resolve, retryDelay)); - } - } - - // If we reach here, we've exhausted all retries and chunks still exist - logError(`There are still chunks left for this branch after ${maxRetries} attempts: ${branch}`); - throw new Error(`There are still chunks left for this branch after ${maxRetries} attempts: ${branch}`); - } - - getDistinctPaths = async ( - owner: string, - repository: string, - branch: string, - ): Promise => { - try { - const { data, error } = await this.supabase - .rpc('get_distinct_paths', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - - if (error) { - logError(`Error getting distinct paths for ${owner}/${repository}/${branch}: ${JSON.stringify(error, null, 2)}`); - return []; - } - - if (!data) { - logInfo(`No data found for ${owner}/${repository}/${branch}`); - return []; - } - - const paths = data.map((doc: { path: string }) => doc.path); - return paths; - } catch (error) { - logError(`Unexpected error getting distinct paths for ${owner}/${repository}/${branch}: ${JSON.stringify(error, null, 2)}`); - if (error instanceof Error) { - logError(`Error details: ${error.message}`); - logError(`Error stack: ${error.stack}`); - } - return []; - } - } - - removeChunksByPath = async ( - owner: string, - repository: string, - branch: string, - path: string, - ): Promise => { - const { error } = await this.supabase - .rpc('delete_branch_path_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch, - path_param: path - }); - logDebugInfo(`Removed chunks: ${path} [${branch}]`); - if (error) { - logError(`Error removing chunks by path: ${JSON.stringify(error, null, 2)}`); - throw error; - } - } - - getShasumByPath = async ( - owner: string, - repository: string, - branch: string, - path: string, - ): Promise => { - try { - const { data, error } = await this.supabase - .from(this.CHUNKS_TABLE) - .select('*') - .eq('owner', owner) - .eq('repository', repository) - .eq('branch', branch) - .eq('path', path) - .order('index') - .order('chunk_index') - .limit(1); - - if (error) { - logError(`Supabase error getting chunks by path: ${JSON.stringify(error, null, 2)}`); - return undefined; - } - - if (!data) { - return undefined; - } - - return data[0].shasum; - } catch (error) { - // logError(`Error getting shasum by path: ${JSON.stringify(error, null, 2)}`); - return undefined; - } - } - - private countBranchEntries = async ( - owner: string, - repository: string, - branch: string, - ): Promise => { try { - const { data, error } = await this.supabase - .rpc('count_branch_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - - if (error) { - logError(`Error counting branch entries: ${JSON.stringify(error, null, 2)}`); - return 0; - } - - return data || 0; - } catch (error) { - logError(`Error counting branch entries: ${JSON.stringify(error, null, 2)}`); - return 0; - } - } - - private duplicateFileEntries = async ( - owner: string, - repository: string, - sourceBranch: string, - path: string, - targetBranch: string, - ): Promise => { - try { - logDebugInfo(`Duplicating file entries: ${path} [${sourceBranch}] -> [${targetBranch}]`); - const { error } = await this.supabase - .rpc('duplicate_file_entries', { + .rpc('duplicate_ai_file_cache_by_branch', { owner_param: owner, repository_param: repository, source_branch_param: sourceBranch, - path_param: path, target_branch_param: targetBranch }); if (error) { - logError(`Error duplicating file entries: ${JSON.stringify(error, null, 2)}`); + logError(`Error duplicating AI file cache by branch: ${JSON.stringify(error, null, 2)}`); throw error; } } catch (error) { - logError(`Error duplicating file entries: ${JSON.stringify(error, null, 2)}`); + logError(`Error duplicating AI file cache by branch: ${JSON.stringify(error, null, 2)}`); throw error; } } - private duplicateBranchEntries = async ( + /** + * Remove all AI file cache entries for a branch + */ + removeAIFileCacheByBranch = async ( owner: string, repository: string, - sourceBranch: string, - targetBranch: string, + branch: string, ): Promise => { try { - logDebugInfo(`Duplicating branch entries for ${owner}/${repository}/${sourceBranch} to ${targetBranch}`); const { error } = await this.supabase - .rpc('duplicate_branch_entries', { + .rpc('delete_ai_file_cache_by_branch', { owner_param: owner, repository_param: repository, - source_branch_param: sourceBranch, - target_branch_param: targetBranch + branch_param: branch }); if (error) { - logError(`Error duplicating branch entries: ${JSON.stringify(error, null, 2)}`); + logError(`Error removing AI file cache by branch: ${JSON.stringify(error, null, 2)}`); throw error; } } catch (error) { - logError(`Error duplicating branch entries: ${JSON.stringify(error, null, 2)}`); + logError(`Error removing AI file cache by branch: ${JSON.stringify(error, null, 2)}`); throw error; } } - private deleteBranchEntries = async ( + /** + * Get SHA by path (for checking if file is cached) + */ + getShasumByPath = async ( owner: string, repository: string, branch: string, - ): Promise => { - const { error } = await this.supabase - .rpc('delete_branch_entries', { - owner_param: owner, - repository_param: repository, - branch_param: branch - }); - - if (error) { - logError(`Error removing chunks from branch: ${JSON.stringify(error, null, 2)}`); - throw error; + path: string, + ): Promise => { + try { + const cached = await this.getAIFileCache(owner, repository, branch, path); + return cached?.sha; + } catch (error) { + logError(`Error getting SHA by path: ${JSON.stringify(error, null, 2)}`); + return undefined; } } - getVectorOfChunkContent = async ( + /** + * Get distinct paths for a branch + */ + getDistinctPaths = async ( owner: string, repository: string, - content: string, - ): Promise => { + branch: string, + ): Promise => { try { - const { data, error } = await this.supabase - .rpc('get_vector_of_chunk_content', { - owner_param: owner, - repository_param: repository, - content_param: content - }); - - if (error) { - logError(`Error getting vector of chunk content: ${JSON.stringify(error, null, 2)}`); - throw error; - } - - // If no data is found, return empty array - if (!data) { - return []; - } - - return data; + const cachedFiles = await this.getAIFileCachesByBranch(owner, repository, branch); + return cachedFiles.map(file => file.path); } catch (error) { - logError(`Error getting vector of chunk content: ${JSON.stringify(error, null, 2)}`); + logError(`Error getting distinct paths: ${JSON.stringify(error, null, 2)}`); return []; } } + } \ No newline at end of file diff --git a/src/usecase/actions/prepare_ai_container_use_case.ts b/src/usecase/actions/prepare_ai_container_use_case.ts deleted file mode 100644 index 6fbc971b..00000000 --- a/src/usecase/actions/prepare_ai_container_use_case.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { Execution } from '../../data/model/execution'; -import { Result } from '../../data/model/result'; -import { DockerRepository } from '../../data/repository/docker_repository'; -import { logError, logInfo } from '../../utils/logger'; -import { ParamUseCase } from '../base/param_usecase'; - -export class PrepareAIContainerUseCase implements ParamUseCase { - taskId = 'PrepareAIContainerUseCase'; - private dockerRepository = new DockerRepository(); - - async invoke(param: Execution): Promise { - logInfo(`Executing ${this.taskId}.`); - const results: Result[] = []; - - try { - const version = param.singleAction.version; - if (version.length === 0) { - logError(`No version specified, skipping version check`); - results.push(new Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`No version specified, skipping build`], - })); - return results; - } - - const imageName = this.dockerRepository.getImageNameWithTag(param); - - logInfo(`🐳 🟔 Checking if v${version} already exists in registry...`); - logInfo(`🐳 🟔 Image: ${imageName}`); - - const versionExists = await this.dockerRepository.checkVersionExistsInRegistry(param); - - if (versionExists) { - logInfo(`🐳 🟢 v${version} already exists in registry, skipping build`); - results.push(new Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`v${version} already exists in registry: ${imageName}`], - })); - return results; - } else { - logInfo(`🐳 🟔 v${version} not found in registry, proceeding with build...`); - } - - logInfo('🐳 🟔 Building and pushing new image...'); - await this.dockerRepository.buildImage(param); - - results.push(new Result({ - id: this.taskId, - success: true, - executed: true, - steps: [`Image built and pushed successfully: ${this.dockerRepository.getImageName(param)}`], - })); - } catch (error) { - logError(`Error in ${this.taskId}: ${error}`); - results.push(new Result({ - id: this.taskId, - success: false, - executed: true, - steps: [`Error preparing AI container: ${error}`], - })); - } - - return results; - } - - /*private async buildAndPushImage(param: Execution): Promise { - const imageName = this.dockerRepository.getImageName(param); - - const localExists = await this.dockerRepository.imageExists(param); - if (!localExists) { - logDebugInfo('🐳 🟔 Local image not found, building...'); - await this.dockerRepository.buildImage(param); - } else { - logDebugInfo('🐳 🟢 Local image already exists, skipping build'); - } - - logInfo('🐳 🟔 Pushing image to registry...'); - // await this.dockerRepository.pushImageToRegistry(param, imageName); - }*/ -} \ No newline at end of file diff --git a/src/usecase/actions/vector_action_removal_use_case.ts b/src/usecase/actions/vector_action_removal_use_case.ts index f39caede..937c5b52 100644 --- a/src/usecase/actions/vector_action_removal_use_case.ts +++ b/src/usecase/actions/vector_action_removal_use_case.ts @@ -29,7 +29,7 @@ export class VectorActionRemovalUseCase implements ParamUseCase { + private removeAICacheByBranch = async (param: Execution, branch: string) => { const results: Result[] = []; if (!param.supabaseConfig) { @@ -77,7 +77,7 @@ export class VectorActionRemovalUseCase implements ParamUseCase { taskId: string = 'VectorActionUseCase'; - private dockerRepository: DockerRepository = new DockerRepository(); private fileRepository: FileRepository = new FileRepository(); - private readonly CODE_INSTRUCTION_BLOCK = "Represent the code for semantic search"; - private readonly CODE_INSTRUCTION_LINE = "Represent each line of code for retrieval"; + private aiRepository: AiRepository = new AiRepository(); + private fileImportAnalyzer: FileImportAnalyzer = new FileImportAnalyzer(); + private fileCacheManager: FileCacheManager = new FileCacheManager(); + private codebaseAnalyzer: CodebaseAnalyzer; + + constructor() { + // Initialize CodebaseAnalyzer with dependencies + this.codebaseAnalyzer = new CodebaseAnalyzer( + this.aiRepository, + this.fileImportAnalyzer, + this.fileCacheManager + ); + } async invoke(param: Execution): Promise { logInfo(`Executing ${this.taskId}.`) @@ -35,31 +47,36 @@ export class VectorActionUseCase implements ParamUseCase { return results; } - await this.dockerRepository.prepareLocalVectorServer(param); + // Check if AI configuration is available + if (!param.ai || !param.ai.getOpenRouterModel() || !param.ai.getOpenRouterApiKey()) { + logError(`Missing required AI configuration. Please provide OPENROUTER_API_KEY and OPENROUTER_MODEL. ${JSON.stringify(param.ai, null, 2)}`); + results.push( + new Result({ + id: this.taskId, + success: false, + executed: true, + errors: [ + `Missing required AI configuration. Please provide OPENROUTER_API_KEY and OPENROUTER_MODEL.`, + ], + }) + ) + return results; + } const branch = param.commit.branch || param.branches.main; let duplicationBranch: string | undefined = undefined; - if (branch === param.branches.main && param.singleAction.isVectorLocalAction) { - logInfo(`šŸ“¦ Chunks from [${param.branches.main}] will be duplicated to [${param.branches.development}] for ${param.owner}/${param.repo}.`); + if (branch === param.branches.main && param.singleAction.isAiCacheLocalAction) { + logInfo(`šŸ“¦ AI cache from [${param.branches.main}] will be duplicated to [${param.branches.development}] for ${param.owner}/${param.repo}.`); duplicationBranch = param.branches.development; } - await this.dockerRepository.startContainer(param); + logInfo(`šŸ“¦ Getting repository files on ${param.owner}/${param.repo}/${branch}`); - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const chunkSize = systemInfo.parameters.chunk_size as number; - const maxWorkers = systemInfo.parameters.max_workers as number; - - logInfo(`šŸ§‘ā€šŸ­ Max workers: ${maxWorkers}`); - logInfo(`🚚 Chunk size: ${chunkSize}`); - logInfo(`šŸ“¦ Getting chunks on ${param.owner}/${param.repo}/${branch}`); - - const chunkedFilesMap = await this.fileRepository.getChunkedRepositoryContent( + const repositoryFiles = await this.fileRepository.getRepositoryContent( param.owner, param.repo, - branch, - chunkSize, param.tokens.token, + branch, param.ai.getAiIgnoreFiles(), (fileName: string) => { logSingleLine(`Checking file ${fileName}`); @@ -69,13 +86,13 @@ export class VectorActionUseCase implements ParamUseCase { } ); - logInfo(`šŸ“¦ āœ… Files to index: ${chunkedFilesMap.size}`, true); + logInfo(`šŸ“¦ āœ… Files to index: ${repositoryFiles.size}`, true); - results.push(...await this.checkChunksInSupabase(param, branch, chunkedFilesMap)); - results.push(...await this.uploadChunksToSupabase(param, branch, chunkedFilesMap)); + results.push(...await this.checkAICacheInSupabase(param, branch, repositoryFiles)); + results.push(...await this.uploadAICacheToSupabase(param, branch, repositoryFiles)); if (duplicationBranch) { - results.push(...await this.duplicateChunksToBranch(param, branch, duplicationBranch)); + results.push(...await this.duplicateAICacheToBranch(param, branch, duplicationBranch)); } results.push( @@ -101,14 +118,12 @@ export class VectorActionUseCase implements ParamUseCase { ], }) ); - } finally { - await this.dockerRepository.stopContainer(param); } return results; } - private checkChunksInSupabase = async (param: Execution, branch: string, chunkedFilesMap: Map) => { + private checkAICacheInSupabase = async (param: Execution, branch: string, repositoryFiles: Map) => { const results: Result[] = []; if (!param.supabaseConfig) { @@ -133,8 +148,8 @@ export class VectorActionUseCase implements ParamUseCase { branch, ); - // Get all local paths from chunkedFiles - const localPaths = new Set(Array.from(chunkedFilesMap.keys())); + // Get all local paths from repository files + const localPaths = new Set(Array.from(repositoryFiles.keys())); // Find paths that exist in Supabase but not in the current branch const pathsToRemove = remotePaths.filter(path => !localPaths.has(path)); @@ -144,15 +159,15 @@ export class VectorActionUseCase implements ParamUseCase { for (const path of pathsToRemove) { try { - await supabaseRepository.removeChunksByPath( + await supabaseRepository.removeAIFileCacheByPath( param.owner, param.repo, branch, path ); - logInfo(`šŸ“¦ āœ… Removed chunks for path: ${path}`); + logInfo(`šŸ“¦ āœ… Removed AI cache for path: ${path}`); } catch (error) { - logError(`šŸ“¦ āŒ Error removing chunks for path ${path}: ${JSON.stringify(error, null, 2)}`); + logError(`šŸ“¦ āŒ Error removing AI cache for path ${path}: ${JSON.stringify(error, null, 2)}`); } } @@ -179,7 +194,7 @@ export class VectorActionUseCase implements ParamUseCase { return results; } - private uploadChunksToSupabase = async (param: Execution, branch: string, chunkedFilesMap: Map) => { + private uploadAICacheToSupabase = async (param: Execution, branch: string, repositoryFiles: Map) => { const results: Result[] = []; if (!param.supabaseConfig) { @@ -197,130 +212,137 @@ export class VectorActionUseCase implements ParamUseCase { } const supabaseRepository: SupabaseRepository = new SupabaseRepository(param.supabaseConfig); - const processedChunkedFiles: ChunkedFile[] = []; const startTime = Date.now(); - const chunkedPaths = Array.from(chunkedFilesMap.keys()); + const filePaths = Array.from(repositoryFiles.keys()); + + // Step 1: Build relationship map once for all files + logInfo(`šŸ“¦ Building relationship map from repository files...`); + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumesMap = relationshipMaps.consumes; + const consumedByMap = relationshipMaps.consumedBy; + logInfo(`āœ… Relationship map built for ${repositoryFiles.size} files`); - for (let i = 0; i < chunkedPaths.length; i++) { - const path = chunkedPaths[i]; - const chunkedFiles: ChunkedFile[] = chunkedFilesMap.get(path) || []; - const progress = ((i + 1) / chunkedPaths.length) * 100; + for (let i = 0; i < filePaths.length; i++) { + const filePath = filePaths[i]; + const fileContent = repositoryFiles.get(filePath) || ''; + const progress = ((i + 1) / filePaths.length) * 100; const currentTime = Date.now(); const elapsedTime = (currentTime - startTime) / 1000; // in seconds - const estimatedTotalTime = (elapsedTime / (i + 1)) * chunkedPaths.length; + const estimatedTotalTime = (elapsedTime / (i + 1)) * filePaths.length; const remainingTime = estimatedTotalTime - elapsedTime; - logSingleLine(`šŸ”˜ ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Checking [${path}]`); + logSingleLine(`šŸ”˜ ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Checking [${filePath}]`); + // Normalize path for consistent comparison + const normalizedPath = filePath.replace(/^\.\//, '').replace(/\\/g, '/').trim(); + + // Calculate SHA for comparison + const currentSHA = this.fileCacheManager.calculateFileSHA(fileContent); + const remoteShasum = await supabaseRepository.getShasumByPath( param.owner, param.repo, branch, - path + normalizedPath ); if (remoteShasum) { - if (remoteShasum === chunkedFiles[0].shasum) { - logSingleLine(`🟢 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File indexed [${path}]`); + if (remoteShasum === currentSHA) { + logSingleLine(`🟢 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File indexed [${normalizedPath}]`); continue; - } else if (remoteShasum !== chunkedFiles[0].shasum) { - logSingleLine(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File has changes and must be reindexed [${path}]`); - await supabaseRepository.removeChunksByPath( + } else if (remoteShasum !== currentSHA) { + logSingleLine(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File has changes and must be reindexed [${normalizedPath}]`); + await supabaseRepository.removeAIFileCacheByPath( param.owner, param.repo, branch, - path + normalizedPath ); } + } else { + // File not in cache - will be processed below + logSingleLine(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | File not in cache, will index [${normalizedPath}]`); } - // Process chunks in parallel with concurrency limit - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const maxWorkers = systemInfo.parameters.max_workers as number; - const chunkPromises: Promise[] = []; - let activeWorkers = 0; - - for (let j = 0; j < chunkedFiles.length; j++) { - const chunkedFile = chunkedFiles[j]; - const chunkProgress = ((j + 1) / chunkedFiles.length) * 100; - - // Wait if we have reached the limit of workers - while (activeWorkers >= maxWorkers) { - await Promise.race(chunkPromises); - activeWorkers = chunkPromises.filter(p => !p).length; - } - - const processChunk = async () => { + // Generate AI cache for this file + if (fileContent) { + + try { + logSingleLine(`🟔 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Generating AI cache [${filePath}]`); + + // Step 2: Extract imports for this file (from pre-built map) + const consumes = consumesMap.get(filePath) || []; + const consumedBy = consumedByMap.get(filePath) || []; + + // Step 3: Generate description using AI (with fallback) + let description = this.codebaseAnalyzer.generateBasicDescription(filePath); try { - logSingleLine(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Vectorizing [${chunkedFile.path}]`); - - const existingVectors: number[][] = []; - const existingChunks: string[] = []; + // Create schema for single file description + const FILE_DESCRIPTION_SCHEMA = { + "type": "object", + "description": "File description", + "properties": { + "description": { + "type": "string", + "description": "Description of what the file does." + } + }, + "required": ["description"], + "additionalProperties": false + }; - const chunksToProcess: string[] = []; - - for (const chunk of chunkedFile.chunks) { - const vector = await supabaseRepository.getVectorOfChunkContent( - param.owner, - param.repo, - chunk - ); - if (vector.length > 0) { - existingVectors.push(vector); - existingChunks.push(chunk); - } else { - chunksToProcess.push(chunk); - } - } + const descriptionPrompt = `${PROMPTS.CODE_BASE_ANALYSIS}: - const cachedPercentage = (existingChunks.length / chunkedFile.chunks.length) * 100; - logSingleLine(`🟔 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Vectorizing [${chunkedFile.path}] - ${cachedPercentage.toFixed(1)}% cached`); - - let embeddings: number[][] = []; - let chunks: string[] = []; - if (chunksToProcess.length > 0) { - const newEmbeddings = await this.dockerRepository.getEmbedding( - param, - chunksToProcess.map(chunk => [chunkedFile.type === 'block' ? this.CODE_INSTRUCTION_BLOCK : this.CODE_INSTRUCTION_LINE, chunk]) - ); - embeddings = [...existingVectors, ...newEmbeddings]; - chunks = [...existingChunks, ...chunksToProcess]; - } else { - embeddings = existingVectors; - chunks = existingChunks; - } - chunkedFile.vector = embeddings; - chunkedFile.chunks = chunks; - logSingleLine(`🟢 ${i + 1}/${chunkedPaths.length} (${progress.toFixed(1)}%) - Chunk ${j + 1}/${chunkedFiles.length} (${chunkProgress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | Storing [${chunkedFile.path}]`); +\`\`\` +${fileContent} +\`\`\` + +`; - await supabaseRepository.setChunkedFile( - param.owner, - param.repo, - branch, - chunkedFile + const aiResponse = await this.aiRepository.askJson( + param.ai, + descriptionPrompt, + FILE_DESCRIPTION_SCHEMA, + "file_description" ); - - processedChunkedFiles.push(chunkedFile); + + if (aiResponse && typeof aiResponse === 'object' && aiResponse.description) { + description = aiResponse.description.trim(); + } } catch (error) { - logError(`Error processing chunk ${j + 1} of file ${path}: ${JSON.stringify(error, null, 2)}`); + logError(`Error generating AI description for ${filePath}, using fallback: ${error}`); } - }; - - const chunkPromise = processChunk(); - chunkPromises.push(chunkPromise); - activeWorkers++; - - chunkPromise.finally(() => { - activeWorkers--; - }); + + // Step 4: Save to Supabase (normalize path before saving) + const fileName = filePath.split('/').pop() || filePath; + const normalizedFilePath = filePath.replace(/^\.\//, '').replace(/\\/g, '/').trim(); + const normalizedConsumes = consumes.map(p => p.replace(/^\.\//, '').replace(/\\/g, '/').trim()); + const normalizedConsumedBy = consumedBy.map(p => p.replace(/^\.\//, '').replace(/\\/g, '/').trim()); + + await supabaseRepository.setAIFileCache( + param.owner, + param.repo, + branch, + { + file_name: fileName, + path: normalizedFilePath, + sha: currentSHA, + description: description, + consumes: normalizedConsumes, + consumed_by: normalizedConsumedBy + } + ); + + logSingleLine(`🟢 ${i + 1}/${filePaths.length} (${progress.toFixed(1)}%) - Estimated time remaining: ${Math.ceil(remainingTime)} seconds | AI cache saved [${filePath}]`); + + } catch (error) { + logError(`Error generating AI cache for ${filePath}: ${JSON.stringify(error, null, 2)}`); + } } - - // Wait for all chunks of the current file to be processed - await Promise.all(chunkPromises); } const totalDurationSeconds = (Date.now() - startTime) / 1000; - logInfo(`šŸ“¦ šŸš€ All chunked files stored ${param.owner}/${param.repo}/${branch}. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, true); + logInfo(`šŸ“¦ šŸš€ All files stored in AI cache ${param.owner}/${param.repo}/${branch}. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, true); results.push( new Result({ @@ -328,14 +350,14 @@ export class VectorActionUseCase implements ParamUseCase { success: true, executed: true, steps: [ - `All chunked files up to date in AI index for \`${branch}\`. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, + `All files up to date in AI cache for \`${branch}\`. Total duration: ${Math.ceil(totalDurationSeconds)} seconds`, ], }) ); return results; } - private duplicateChunksToBranch = async (param: Execution, sourceBranch: string, targetBranch: string) => { + private duplicateAICacheToBranch = async (param: Execution, sourceBranch: string, targetBranch: string) => { const results: Result[] = []; if (!param.supabaseConfig) { @@ -355,15 +377,15 @@ export class VectorActionUseCase implements ParamUseCase { const supabaseRepository: SupabaseRepository = new SupabaseRepository(param.supabaseConfig); try { - logInfo(`šŸ“¦ -> šŸ“¦ Clearing possible existing chunks from ${targetBranch} for ${param.owner}/${param.repo}.`); - await supabaseRepository.removeChunksByBranch( + logInfo(`šŸ“¦ -> šŸ“¦ Clearing possible existing AI cache from ${targetBranch} for ${param.owner}/${param.repo}.`); + await supabaseRepository.removeAIFileCacheByBranch( param.owner, param.repo, targetBranch ); - logInfo(`šŸ“¦ -> šŸ“¦ Duplicating chunks from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`); - await supabaseRepository.duplicateChunksByBranch( + logInfo(`šŸ“¦ -> šŸ“¦ Duplicating AI cache from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`); + await supabaseRepository.duplicateAIFileCacheByBranch( param.owner, param.repo, sourceBranch, @@ -376,19 +398,19 @@ export class VectorActionUseCase implements ParamUseCase { success: true, executed: true, steps: [ - `Duplicated chunks from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`, + `Duplicated AI cache from ${sourceBranch} to ${targetBranch} for ${param.owner}/${param.repo}.`, ], }) ); } catch (error) { - logError(`šŸ“¦ -> šŸ“¦ āŒ Error duplicating chunks from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`); + logError(`šŸ“¦ -> šŸ“¦ āŒ Error duplicating AI cache from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`); results.push( new Result({ id: this.taskId, success: false, executed: true, errors: [ - `Error duplicating chunks from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`, + `Error duplicating AI cache from ${sourceBranch} to ${targetBranch}: ${JSON.stringify(error, null, 2)}`, ], }) ); @@ -396,4 +418,10 @@ export class VectorActionUseCase implements ParamUseCase { return results; } + + // All methods related to file imports, cache, and codebase analysis + // have been moved to dedicated services: + // - FileImportAnalyzer: extractImportsFromFile, resolveRelativePath, buildRelationshipMap + // - FileCacheManager: calculateFileSHA + // - CodebaseAnalyzer: generateBasicDescription } diff --git a/src/usecase/issue_comment_use_case.ts b/src/usecase/issue_comment_use_case.ts index 7533b6ae..5485def8 100644 --- a/src/usecase/issue_comment_use_case.ts +++ b/src/usecase/issue_comment_use_case.ts @@ -1,7 +1,7 @@ import { Execution } from "../data/model/execution"; import { Result } from "../data/model/result"; import { logInfo } from "../utils/logger"; -import { AskActionUseCase } from "./steps/common/ask_ai_use_case"; +import { ThinkUseCase } from "./steps/common/think_use_case"; import { ParamUseCase } from "./base/param_usecase"; import { CheckIssueCommentLanguageUseCase } from "./steps/issue_comment/check_issue_comment_language_use_case"; @@ -15,7 +15,7 @@ export class IssueCommentUseCase implements ParamUseCase { results.push(...await new CheckIssueCommentLanguageUseCase().invoke(param)); - results.push(...await new AskActionUseCase().invoke(param)); + results.push(...await new ThinkUseCase().invoke(param)); return results; diff --git a/src/usecase/single_action_use_case.ts b/src/usecase/single_action_use_case.ts index 5ecf15bc..3c482d34 100644 --- a/src/usecase/single_action_use_case.ts +++ b/src/usecase/single_action_use_case.ts @@ -1,14 +1,13 @@ import { Execution } from "../data/model/execution"; import { Result } from "../data/model/result"; import { logDebugInfo, logError, logInfo } from "../utils/logger"; -import { AskActionUseCase } from "./steps/common/ask_ai_use_case"; import { DeployedActionUseCase } from "./actions/deployed_action_use_case"; import { VectorActionUseCase } from "./actions/vector_action_use_case"; -import { PrepareAIContainerUseCase } from "./actions/prepare_ai_container_use_case"; import { ParamUseCase } from "./base/param_usecase"; import { PublishGithubActionUseCase } from "./actions/publish_github_action_use_case"; import { CreateReleaseUseCase } from "./actions/create_release_use_case"; import { CreateTagUseCase } from "./actions/create_tag_use_case"; +import { ThinkUseCase } from "./steps/common/think_use_case"; export class SingleActionUseCase implements ParamUseCase { taskId: string = 'SingleActionUseCase'; @@ -23,10 +22,7 @@ export class SingleActionUseCase implements ParamUseCase { return results; } - if (param.singleAction.isCompileVectorServerAction) { - results.push(...await new PrepareAIContainerUseCase().invoke(param)); - } else if (param.singleAction.isVectorAction) { - // results.push(...await new PrepareLocalVectorServerUseCase().invoke(param)); + if (param.singleAction.isAiCacheAction) { results.push(...await new VectorActionUseCase().invoke(param)); } else if (param.singleAction.isDeployedAction) { results.push(...await new DeployedActionUseCase().invoke(param)); @@ -36,6 +32,8 @@ export class SingleActionUseCase implements ParamUseCase { results.push(...await new CreateReleaseUseCase().invoke(param)); } else if (param.singleAction.isCreateTagAction) { results.push(...await new CreateTagUseCase().invoke(param)); + } else if (param.singleAction.isThinkAction) { + results.push(...await new ThinkUseCase().invoke(param)); } } catch (error) { logError(error); diff --git a/src/usecase/steps/common/ask_ai_use_case.ts b/src/usecase/steps/common/ask_ai_use_case.ts deleted file mode 100644 index 51e45968..00000000 --- a/src/usecase/steps/common/ask_ai_use_case.ts +++ /dev/null @@ -1,371 +0,0 @@ -import { AiResponse } from '../../../data/model/ai_response'; -import { ChunkedFileChunk } from '../../../data/model/chunked_file_chunk'; -import { Execution } from '../../../data/model/execution'; -import { Result } from '../../../data/model/result'; -import { AiRepository } from '../../../data/repository/ai_repository'; -import { DockerRepository } from '../../../data/repository/docker_repository'; -import { FileRepository, FileTreeNodeWithContent } from '../../../data/repository/file_repository'; -import { IssueRepository } from '../../../data/repository/issue_repository'; -import { SupabaseRepository } from '../../../data/repository/supabase_repository'; -import { logDebugInfo, logError, logInfo, logSingleLine } from '../../../utils/logger'; -import { ParamUseCase } from '../../base/param_usecase'; - -export class AskActionUseCase implements ParamUseCase { - taskId: string = 'AskActionUseCase'; - private dockerRepository: DockerRepository = new DockerRepository(); - private fileRepository: FileRepository = new FileRepository(); - private aiRepository: AiRepository = new AiRepository(); - private issueRepository: IssueRepository = new IssueRepository(); - - private readonly CODE_INSTRUCTION_ASK = "Represent the question for retrieving relevant code snippets"; - - async invoke(param: Execution): Promise { - logInfo(`Executing ${this.taskId}.`) - - const results: Result[] = []; - - try { - /** - * Check if the user from the token is found. - */ - if (!param.tokenUser) { - results.push( - new Result({ - id: this.taskId, - success: false, - executed: false, - errors: [ - `User from token not found.`, - ], - }) - ) - return results; - } - - let description = ''; - let commentBody = ''; - - /** - * Get the comment body. - */ - if (param.issue.isIssueComment) { - logInfo(`šŸ”Ž Issue comment body: ${param.issue.commentBody}`); - commentBody = param.issue.commentBody; - description = await this.issueRepository.getDescription( - param.owner, - param.repo, - param.issueNumber, - param.tokens.token - ) ?? ''; - } else if (param.pullRequest.isPullRequestReviewComment) { - logInfo(`šŸ”Ž Pull request review comment body: ${param.pullRequest.commentBody}`); - commentBody = param.pullRequest.commentBody; - description = await this.issueRepository.getDescription( - param.owner, - param.repo, - param.issueNumber, - param.tokens.token - ) ?? ''; - } else { - logError(`Not a valid comment body.`); - results.push( - new Result({ - id: this.taskId, - success: true, - executed: false, - }) - ) - return results; - } - - if (commentBody.length === 0 || !commentBody.includes(`@${param.tokenUser}`)) { - logInfo(`šŸ”Ž Comment body is empty or does not include @${param.tokenUser}`); - results.push( - new Result({ - id: this.taskId, - success: true, - executed: false, - }) - ); - return results; - } else { - commentBody = commentBody.replace(param.tokenUser, '').trim(); - } - - logInfo(`šŸ”Ž Comment body: ${commentBody}`); - - if (param.ai.getOpenRouterModel().length === 0 || param.ai.getOpenRouterApiKey().length === 0) { - results.push( - new Result({ - id: this.taskId, - success: false, - executed: false, - errors: [ - `OpenRouter model or API key not found.`, - ], - }) - ) - return results; - } - - /** - * Check if the supabase config is found. - */ - if (!param.supabaseConfig) { - results.push( - new Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Supabase config not found.`, - ], - }) - ) - return results; - } - - const supabaseRepository: SupabaseRepository = new SupabaseRepository(param.supabaseConfig); - - await this.dockerRepository.startContainer(param); - - const systemInfo = await this.dockerRepository.getSystemInfo(param); - const chunkSize = systemInfo.parameters.chunk_size as number; - const maxWorkers = systemInfo.parameters.max_workers as number; - - logInfo(`šŸ§‘ā€šŸ­ Max workers: ${maxWorkers}`); - logInfo(`🚚 Chunk size: ${chunkSize}`); - logInfo(`šŸ“¦ Getting chunked files for ${param.owner}/${param.repo}/${param.commit.branch}`); - - const startTime = Date.now(); - - const embeddings = await this.dockerRepository.getEmbedding( - param, - [ - [this.CODE_INSTRUCTION_ASK, commentBody] - ] - ); - - // logInfo(`šŸ”Ž Embeddings: ${JSON.stringify(embeddings, null, 2)}`); - - const types = [ - 'line', - 'block' - ]; - const chunks: ChunkedFileChunk[] = []; - for (const type of types) { - logInfo(`šŸ“¦ šŸ”Ž Matching chunks for ${param.owner}/${param.repo}/${param.commit.branch}`); - const foundChunks = await supabaseRepository.matchChunks( - param.owner, - param.repo, - param.commit.branch, - type, - embeddings[0], - 5 - ); - - for (const chunk of foundChunks) { - logDebugInfo(`šŸ“¦ šŸ”Ž Chunk type: ${type} - ${chunk.path}`); - } - - chunks.push(...foundChunks); - } - - const { withContent, withoutContent } = await this.fileRepository.getFileTree( - param.owner, - param.repo, - param.tokens.token, - param.commit.branch, - param.ai.getAiIgnoreFiles(), - (fileName: string) => { - logSingleLine(`Checking file ${fileName}`); - }, - (fileName: string) => { - logSingleLine(`Ignoring file ${fileName}`); - } - ); - - let workComplete = false; - let relatedFiles: Map = new Map(); - let finalResponse = ''; - - while (!workComplete) { - const prompt = ` - # Copilot - - You are a highly skilled code analysis assistant, currently working on a GitHub issue. Your role is to assist the developer by answering any related questions they may have. I will provide you with: - 1. The issue description - 2. A user's question about a codebase - 3. A file tree representing the structure of the project - 4. The most relevant code snippets from the codebase related to their query - - ## Your tasks - - - Analyze the code snippets in the context of the user's question. - - If the provided code snippets are not directly relevant to the question, analyze the file tree structure to identify potential relevant files and directories. - - Use the file tree to provide additional context if needed (e.g., to understand module relationships). - - Strive to find the most appropriate and complete solution to the user's question. - - When in doubt or if you need more context to provide a confident answer, request additional files. - - Provide your answer **only** in a JSON format, following this structure: - - { - "text_response": "Your detailed analysis or answer here.", - "action": "none" | "analyze_files", - "related_files": ["optional", "list", "of", "files"], - "complete": true | false - } - - ## Important guidelines for text_response - - - Start your response directly with the answer or analysis, without introductory phrases like "Based on the provided code snippets..." or "Based on the file tree..." - - Be concise and direct in your response - - Focus on providing the information requested without unnecessary context or explanations - - If you need more information, state it directly without prefacing phrases - - ## Explanation - - - If the provided code snippets and file tree are sufficient to confidently answer the question, set "complete": true and "action": "none". - - If you have any doubts or need more context to provide a complete and accurate answer, set "complete": false, "action": "analyze_files", and list the related file paths you need to investigate further in "related_files". - - If the current code snippets are not relevant to the question, analyze the file tree structure to identify potentially relevant files and request them. - - Do not invent file paths; only request files that logically relate to the question based on the information available. - - Always provide a "text_response" with your reasoning, even if requesting more files. - - When requesting additional files, explain in the text_response why you need those specific files to provide a better answer. - - ## Important - - - **Respond only with the JSON object**, without any extra commentary or text outside of the JSON. - - Prioritize accuracy and completeness over speed - it's better to request more files than to provide an incomplete or uncertain answer. - - If the current code snippets are not helpful, use the file tree structure to guide your search for relevant files. - - ## Information provided - - ### Issue description - - \`\`\` - ${description} - \`\`\` - - ### User's question - - \`\`\` - ${commentBody} - \`\`\` - - ### File tree - - \`\`\`json - ${JSON.stringify(withoutContent, null, 2)} - \`\`\` - - ### Relevant code snippets - - ${relatedFiles.size > 0 - ? Array.from(relatedFiles.entries()).map(([path, content]) => `\nFile: ${path}\nCode:\n${content}`).join('\n') - : chunks.map(chunk => `\nFile: ${chunk.path}\nCode:\n${chunk.chunk}`).join('\n')} - `; - - const jsonResponse = await this.aiRepository.askJson( - param.ai, - prompt, - ) as AiResponse; - - if (!jsonResponse) { - logError(`No result from AI.`); - results.push( - new Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error in ${this.taskId}: No result from AI.`, - ], - }) - ); - return results; - } - - logInfo(`šŸ”Ž Result: ${JSON.stringify(jsonResponse, null, 2)}`); - - workComplete = jsonResponse.complete; - - if (jsonResponse.action === 'analyze_files') { - relatedFiles = this.getRelatedFiles(jsonResponse.related_files, withContent); - } else if (jsonResponse.action === 'none') { - finalResponse = jsonResponse.text_response; - } - } - - const totalDurationSeconds = (Date.now() - startTime) / 1000; - logInfo(`šŸ“¦ šŸ”Ž Matched chunks for ${param.owner}/${param.repo}/${param.commit.branch}:\n Total duration: ${Math.ceil(totalDurationSeconds)} seconds`); - - let number = 0 - if (param.issue.isIssueComment) { - number = param.issueNumber; - } else if (param.pullRequest.isPullRequestReviewComment) { - number = param.pullRequest.number; - } - - await this.issueRepository.addComment( - param.owner, - param.repo, - number, - finalResponse, - param.tokens.token - ); - - results.push( - new Result({ - id: this.taskId, - success: true, - executed: true, - }) - ); - } catch (error) { - logError(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); - results.push( - new Result({ - id: this.taskId, - success: false, - executed: true, - steps: [ - `Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`, - ], - }) - ); - } finally { - await this.dockerRepository.stopContainer(param); - } - - return results; - } - - private getRelatedFiles(relatedFiles: string[], tree: FileTreeNodeWithContent): Map { - const result = new Map(); - - const findFile = (node: FileTreeNodeWithContent, targetPath: string): FileTreeNodeWithContent | null => { - if (node.path === targetPath) { - return node; - } - - if (node.children) { - for (const child of node.children) { - const found = findFile(child, targetPath); - if (found) { - return found; - } - } - } - - return null; - }; - - for (const filePath of relatedFiles) { - const fileNode = findFile(tree, filePath); - if (fileNode && fileNode.type === 'file' && fileNode.content) { - result.set(filePath, fileNode.content); - } - } - - return result; - } -} \ No newline at end of file diff --git a/src/usecase/steps/common/services/codebase_analyzer.ts b/src/usecase/steps/common/services/codebase_analyzer.ts new file mode 100644 index 00000000..b93f407a --- /dev/null +++ b/src/usecase/steps/common/services/codebase_analyzer.ts @@ -0,0 +1,458 @@ +import { Execution } from '../../../../data/model/execution'; +import { AiRepository } from '../../../../data/repository/ai_repository'; +import { logDebugInfo, logError, logInfo } from '../../../../utils/logger'; +import { PROMPTS } from '../../../../utils/constants'; +import { FileImportAnalyzer } from './file_import_analyzer'; +import { FileCacheManager } from './file_cache_manager'; +import { CachedFileInfo } from './types'; + +export interface FileAnalysisResult { + path: string; + description: string; + consumes: string[]; + consumed_by: string[]; +} + +/** + * Service for analyzing codebase structure and generating file descriptions + */ +export class CodebaseAnalyzer { + constructor( + private aiRepository: AiRepository, + private fileImportAnalyzer: FileImportAnalyzer, + private fileCacheManager: FileCacheManager + ) {} + + /** + * Generate codebase analysis with file descriptions and relationships + * This runs before the main reasoning loop to provide context + * Uses relationship map built from imports + AI descriptions in batches + */ + async generateCodebaseAnalysis( + param: Execution, + repositoryFiles: Map, + question: string + ): Promise { + try { + // Filter relevant files (code files, not config/docs) + const codeExtensions = ['.ts', '.tsx', '.js', '.jsx', '.py', '.java', '.kt', '.go', '.rs', '.rb', '.php', '.swift', '.dart']; + const relevantFiles = Array.from(repositoryFiles.entries()) + .filter(([path]) => { + const ext = path.split('.').pop()?.toLowerCase() || ''; + return codeExtensions.includes(`.${ext}`) || + path.includes('/src/') || + path.includes('/lib/') || + path.includes('/usecase/') || + path.includes('/repository/'); + }); + + if (relevantFiles.length === 0) { + logInfo(`āš ļø No relevant code files found for analysis`); + return []; + } + + logInfo(`šŸ” Analyzing ${relevantFiles.length} relevant files for structure and relationships...`); + + // STEP 0: Load cache from Supabase + const cache = await this.fileCacheManager.loadAICache(param); + + // STEP 1: Build relationship map from imports (in memory, no AI needed) + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumesMap = relationshipMaps.consumes; + const consumedByMap = relationshipMaps.consumedBy; + + // STEP 2: Identify files that need AI analysis (not in cache or SHA changed) + const filesNeedingAnalysis: Array<[string, string]> = []; + const cachedAnalyses: FileAnalysisResult[] = []; + + let cacheMissReasons = { + notInCache: 0, + shaMismatch: 0 + }; + + // Track files that should be in cache but aren't + const missingFromCache: string[] = []; + + for (const [filePath, content] of relevantFiles) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const cached = this.fileCacheManager.getCachedFile(cache, filePath); + + if (!cached) { + cacheMissReasons.notInCache++; + missingFromCache.push(filePath); + logDebugInfo(`āŒ Cache miss for ${filePath} (not in cache)`); + filesNeedingAnalysis.push([filePath, content]); + } else if (cached.sha !== currentSHA) { + cacheMissReasons.shaMismatch++; + logDebugInfo(`šŸ”„ SHA mismatch for ${filePath}: cached=${cached.sha.substring(0, 8)}..., current=${currentSHA.substring(0, 8)}...`); + filesNeedingAnalysis.push([filePath, content]); + } else { + // Use cached data + const consumes = consumesMap.get(filePath) || []; + const consumedBy = consumedByMap.get(filePath) || []; + cachedAnalyses.push({ + path: filePath, + description: cached.description, + consumes: consumes, + consumed_by: consumedBy + }); + } + } + + logInfo(`šŸ“Š Cache hit: ${cachedAnalyses.length} files, Need analysis: ${filesNeedingAnalysis.length} files (not in cache: ${cacheMissReasons.notInCache}, SHA mismatch: ${cacheMissReasons.shaMismatch})`); + + // Debug: Show detailed cache comparison + if (cacheMissReasons.notInCache > 0) { + if (cache.size > 0) { + const sampleCachePaths = Array.from(cache.keys()).slice(0, 10); + const sampleMissingPaths = missingFromCache.slice(0, 10); + logDebugInfo(`šŸ” Cache contains ${cache.size} files. Sample cached paths: ${sampleCachePaths.join(', ')}`); + logDebugInfo(`šŸ” Sample missing paths (${missingFromCache.length} total): ${sampleMissingPaths.join(', ')}`); + + // Check if any missing paths are similar to cached paths (normalization issue) + for (const missingPath of sampleMissingPaths.slice(0, 3)) { + const normalizedMissing = missingPath.replace(/^\.\//, '').replace(/\\/g, '/'); + const foundSimilar = sampleCachePaths.find(cached => + cached.includes(normalizedMissing) || normalizedMissing.includes(cached) + ); + if (foundSimilar) { + logDebugInfo(`āš ļø Potential path mismatch: missing="${missingPath}" vs cached="${foundSimilar}"`); + } + } + } else { + logDebugInfo(`āš ļø Cache is empty! All ${relevantFiles.length} files need analysis.`); + } + } + + // STEP 3: Process files needing analysis in batches with AI (only for descriptions) + // Relationships come from the map we built + const BATCH_SIZE = 20; // Process 20 files at a time + const allAnalyses: FileAnalysisResult[] = [...cachedAnalyses]; + + // Create simplified schema for AI (only needs description, relationships come from map) + const FILE_DESCRIPTION_SCHEMA = { + "type": "array", + "description": "Array of file descriptions", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File path relative to repository root" + }, + "description": { + "type": "string", + "description": "Complete description of what the file does" + } + }, + "required": ["path", "description"], + "additionalProperties": false + } + }; + + for (let i = 0; i < filesNeedingAnalysis.length; i += BATCH_SIZE) { + const batch = filesNeedingAnalysis.slice(i, i + BATCH_SIZE); + const batchNumber = Math.floor(i / BATCH_SIZE) + 1; + const totalBatches = Math.ceil(relevantFiles.length / BATCH_SIZE); + + logInfo(`šŸ“ Processing batch ${batchNumber}/${totalBatches} (${batch.length} files)...`); + + // Prepare batch content + const batchFilesList = batch.map(([path]) => path).join('\n'); + const batchContent = batch.map(([path, content]) => + `\n## ${path}\n\`\`\`\n${content}\n\`\`\`` + ).join('\n'); + + const batchPrompt = `# Codebase Structure Analysis - Batch ${batchNumber}/${totalBatches} + +You are analyzing a codebase to understand what each file does. + +## User's Question: +${question} + +## Files to Analyze in this batch (${batch.length} files): +${batchFilesList} + +## File Contents: +${batchContent} + +## Task: +For EACH of the ${batch.length} files listed above, + +${PROMPTS.CODE_BASE_ANALYSIS} + +Return a JSON array with this structure: +[ + { + "path": "src/path/to/file.ts", + "description": "description_here" + }, + ... +] + +**REQUIREMENTS**: +- You MUST return a description for ALL ${batch.length} files in this batch`; + + try { + const batchResponse = await this.aiRepository.askJson( + param.ai, + batchPrompt, + FILE_DESCRIPTION_SCHEMA, + "file_descriptions" + ); + + if (batchResponse && Array.isArray(batchResponse)) { + // Merge AI descriptions with relationship map and update cache + for (const item of batchResponse) { + if (item && typeof item.path === 'string' && typeof item.description === 'string') { + const [filePath, content] = batch.find(([p]) => p === item.path) || [item.path, '']; + const currentSHA = filePath && content ? this.fileCacheManager.calculateFileSHA(content) : ''; + const consumes = consumesMap.get(item.path) || []; + const consumedBy = consumedByMap.get(item.path) || []; + + allAnalyses.push({ + path: item.path, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }); + + // Update cache + if (filePath && currentSHA) { + const cachedInfo: CachedFileInfo = { + path: item.path, + sha: currentSHA, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(item.path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, item.path, cachedInfo, consumes, consumedBy); + } + } + } + logInfo(`āœ… Processed batch ${batchNumber}/${totalBatches}: ${batchResponse.length} files`); + } else { + logError(`āš ļø Batch ${batchNumber} failed, using fallback descriptions`); + // Fallback for this batch + for (const [path, content] of batch) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const consumes = consumesMap.get(path) || []; + const consumedBy = consumedByMap.get(path) || []; + const fallbackDesc = this.generateBasicDescription(path); + + allAnalyses.push({ + path, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }); + + // Update cache with fallback + const cachedInfo: CachedFileInfo = { + path, + sha: currentSHA, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, path, cachedInfo, consumes, consumedBy); + } + } + } catch (error) { + logError(`Error processing batch ${batchNumber}: ${error}`); + // Fallback for this batch + for (const [path, content] of batch) { + const currentSHA = this.fileCacheManager.calculateFileSHA(content); + const consumes = consumesMap.get(path) || []; + const consumedBy = consumedByMap.get(path) || []; + const fallbackDesc = this.generateBasicDescription(path); + + allAnalyses.push({ + path, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }); + + // Update cache with fallback + const cachedInfo: CachedFileInfo = { + path, + sha: currentSHA, + description: fallbackDesc, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, path, cachedInfo, consumes, consumedBy); + } + } + } + + // STEP 4: Cache is saved incrementally during processing + // No need to save all at once since we're using Supabase + + if (allAnalyses.length > 0) { + logInfo(`āœ… Generated analysis for ${allAnalyses.length} files (${cachedAnalyses.length} from cache, ${filesNeedingAnalysis.length} from AI)`); + return allAnalyses; + } + + // Fallback: Generate simple descriptions based on file paths and basic content + logInfo(`āš ļø AI analysis failed, generating fallback descriptions...`); + const fallbackDescriptions = this.generateFallbackFileDescriptions(relevantFiles); + // Merge with relationship maps and update cache + const fallbackResults = await Promise.all(fallbackDescriptions.map(async (item) => { + const consumes = consumesMap.get(item.path) || []; + const consumedBy = consumedByMap.get(item.path) || []; + const content = repositoryFiles.get(item.path) || ''; + const currentSHA = content ? this.fileCacheManager.calculateFileSHA(content) : ''; + + // Update cache + if (content && currentSHA) { + const cachedInfo: CachedFileInfo = { + path: item.path, + sha: currentSHA, + description: item.description, + consumes: consumes, + consumed_by: consumedBy + }; + cache.set(item.path, cachedInfo); + // Save to Supabase + await this.fileCacheManager.saveAICacheEntry(param, item.path, cachedInfo, consumes, consumedBy); + } + + return { + ...item, + consumes: consumes, + consumed_by: consumedBy + }; + })); + + return fallbackResults; + + } catch (error) { + logError(`Error generating codebase analysis: ${error}`); + // Fallback to simple path-based analysis + const relevantFiles = Array.from(repositoryFiles.entries()) + .filter(([path]) => path.includes('/src/') || path.includes('/lib/')); + const fallbackDescriptions = this.generateFallbackFileDescriptions(relevantFiles); + // Try to build relationship map even in fallback + try { + const relationshipMaps = this.fileImportAnalyzer.buildRelationshipMap(repositoryFiles); + const consumes = relationshipMaps.consumes; + const consumedBy = relationshipMaps.consumedBy; + return fallbackDescriptions.map(item => ({ + ...item, + consumes: consumes.get(item.path) || [], + consumed_by: consumedBy.get(item.path) || [] + })); + } catch { + return fallbackDescriptions; + } + } + } + + /** + * Generate basic description from file path (fallback) + */ + generateBasicDescription(path: string): string { + const pathParts = path.split('/'); + const fileName = pathParts[pathParts.length - 1]; + const dir = pathParts.slice(0, -1).join('/'); + + if (path.includes('/usecase/')) { + return `Use case for ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles business logic and orchestrates operations.`; + } else if (path.includes('/repository/')) { + return `Repository for ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles data access and external service interactions.`; + } else if (path.includes('/model/')) { + return `Data model: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Defines data structures and interfaces.`; + } else if (path.includes('/utils/')) { + return `Utility functions: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Provides helper functions and utilities.`; + } else if (path.includes('/actions/')) { + return `Action handler: ${fileName.replace(/_/g, ' ').replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, '')}. Handles action execution and workflows.`; + } else { + return `File: ${fileName}. Located in ${dir || 'root'}.`; + } + } + + /** + * Generate fallback file descriptions when AI analysis fails + */ + generateFallbackFileDescriptions( + files: Array<[string, string]> + ): FileAnalysisResult[] { + const descriptions: FileAnalysisResult[] = []; + + for (const [path] of files) { + const description = this.generateBasicDescription(path); + descriptions.push({ + path, + description, + consumes: [], // Will be filled by relationship map + consumed_by: [] // Will be filled by relationship map + }); + } + + return descriptions; + } + + /** + * Format codebase analysis for inclusion in AI context + */ + formatCodebaseAnalysisForContext( + analysis: FileAnalysisResult[] + ): string { + if (analysis.length === 0) { + return ''; + } + + const formatted: string[] = []; + formatted.push(`## šŸ“‹ Codebase Analysis & File Relationships\n\n`); + formatted.push(`This analysis provides context about the codebase structure to help you make informed decisions about which files to examine.\n\n`); + formatted.push(`**Relationship Types:**\n`); + formatted.push(`- **Consumes**: Files that this file imports/depends on\n`); + formatted.push(`- **Consumed By**: Files that import/depend on this file\n\n`); + + // Group by directory for better organization + const byDirectory = new Map(); + analysis.forEach(item => { + const dir = item.path.split('/').slice(0, -1).join('/') || 'root'; + if (!byDirectory.has(dir)) { + byDirectory.set(dir, []); + } + byDirectory.get(dir)!.push(item); + }); + + // Sort directories for consistent output + const sortedDirs = Array.from(byDirectory.keys()).sort(); + + for (const dir of sortedDirs) { + const files = byDirectory.get(dir)!; + formatted.push(`### ${dir || 'Root'}\n\n`); + + for (const file of files) { + formatted.push(`- **\`${file.path}\`**: ${file.description}`); + + if (file.consumes && file.consumes.length > 0) { + formatted.push(`\n - *Consumes*: ${file.consumes.slice(0, 5).map(r => `\`${r}\``).join(', ')}${file.consumes.length > 5 ? '...' : ''}`); + } + + if (file.consumed_by && file.consumed_by.length > 0) { + formatted.push(`\n - *Consumed By*: ${file.consumed_by.slice(0, 5).map(r => `\`${r}\``).join(', ')}${file.consumed_by.length > 5 ? '...' : ''}`); + } + + formatted.push(`\n`); + } + formatted.push(`\n`); + } + + formatted.push(`\n**Use this analysis to understand the codebase structure and identify relevant files for the task.**\n\n`); + + return formatted.join(''); + } +} + diff --git a/src/usecase/steps/common/services/comment_formatter.ts b/src/usecase/steps/common/services/comment_formatter.ts new file mode 100644 index 00000000..172bd4d2 --- /dev/null +++ b/src/usecase/steps/common/services/comment_formatter.ts @@ -0,0 +1,363 @@ +import { ThinkStep, ProposedChange, FileAnalysis } from '../../../../data/model/think_response'; +import { ThinkTodoManager } from '../think_todo_manager'; + +/** + * Service for formatting GitHub comments and code changes + */ +export class CommentFormatter { + private readonly GITHUB_COMMENT_MAX_LENGTH = 65500; // Leave some margin below 65536 + + /** + * Format the complete reasoning comment for GitHub + */ + formatReasoningComment( + question: string, + description: string, + steps: ThinkStep[], + analyzedFiles: Map, + proposedChanges: ProposedChange[], + finalAnalysis: string, + totalIterations: number, + todoManager: ThinkTodoManager + ): string { + let comment = ''; + + // Header + comment += `# šŸ¤” AI Reasoning Analysis\n\n`; + + if (question) { + comment += `## šŸ“ Question\n\n${question}\n\n`; + } + + comment += `---\n\n`; + + // MAIN CONTENT: Summary and conclusions + comment += `## šŸ“Š Analysis Summary\n\n`; + comment += `- **Total Iterations**: ${totalIterations}\n`; + comment += `- **Files Analyzed**: ${analyzedFiles.size}\n`; + comment += `- **Changes Proposed**: ${proposedChanges.length}\n`; + + // TODO List Summary + const todoStats = todoManager.getStats(); + if (todoStats.total > 0) { + comment += `- **TODO Tasks**: ${todoStats.total} (${todoStats.completed} completed, ${todoStats.in_progress} in progress, ${todoStats.pending} pending)\n`; + } + + comment += `\n---\n\n`; + + // Final Analysis & Conclusions (main content) + if (finalAnalysis) { + comment += `## šŸŽÆ Final Analysis & Conclusions\n\n`; + comment += `${finalAnalysis}\n\n`; + comment += `---\n\n`; + } else { + // Fallback summary if no final analysis + comment += `## šŸŽÆ Summary\n\n`; + comment += `Analysis completed after ${totalIterations} iterations. `; + comment += `Analyzed ${analyzedFiles.size} file${analyzedFiles.size !== 1 ? 's' : ''} and `; + comment += `proposed ${proposedChanges.length} change${proposedChanges.length !== 1 ? 's' : ''}.\n\n`; + comment += `---\n\n`; + } + + // Proposed Changes (main content) + if (proposedChanges.length > 0) { + comment += `## šŸ’” Proposed Changes\n\n`; + proposedChanges.forEach((change, idx) => { + comment += this.formatProposedChange(change, idx + 1); + }); + comment += `\n---\n\n`; + } else { + comment += `## šŸ’” Proposed Changes\n\n`; + comment += `No specific code changes were proposed. The analysis focused on understanding the codebase structure and requirements.\n\n`; + comment += `---\n\n`; + } + + // Analyzed Files Summary (if relevant) + if (analyzedFiles.size > 0 && analyzedFiles.size <= 10) { + comment += `## šŸ“„ Analyzed Files\n\n`; + Array.from(analyzedFiles.values()).forEach(file => { + comment += `- **\`${file.path}\`** (${file.relevance} relevance): ${file.key_findings.substring(0, 200)}${file.key_findings.length > 200 ? '...' : ''}\n`; + }); + comment += `\n---\n\n`; + } + + // TODO List Summary (if relevant) + if (todoStats.total > 0) { + comment += `## šŸ“‹ TODO List Summary\n\n`; + const completedTodos = todoManager.getTodosByStatus('completed'); + const activeTodos = todoManager.getActiveTodos(); + + if (completedTodos.length > 0) { + comment += `### āœ… Completed Tasks\n\n`; + completedTodos.forEach(todo => { + comment += `- ${todo.content}\n`; + }); + comment += `\n`; + } + + if (activeTodos.length > 0) { + comment += `### šŸ”„ Active/Pending Tasks\n\n`; + activeTodos.forEach(todo => { + comment += `- ${todo.status === 'in_progress' ? 'šŸ”„' : 'ā³'} ${todo.content}\n`; + }); + comment += `\n`; + } + + comment += `---\n\n`; + } + + // COLLAPSED SECTION: Detailed Reasoning Steps + comment += `
\nšŸ”„ Detailed Reasoning Steps (${steps.length} steps) - Click to expand\n\n`; + comment += `\n\n*This section contains the detailed step-by-step reasoning process. It's collapsed by default to keep the main analysis focused.*\n\n`; + comment += `---\n\n`; + + let proposalIndex = 0; + const proposalShownFlags = new Set(); + + for (const step of steps) { + comment += `### Step ${step.step_number}: ${this.getActionEmoji(step.action)} ${this.formatActionName(step.action)}\n\n`; + + // Show reasoning (truncated for collapsed section) + if (step.reasoning) { + const reasoningText = step.reasoning.length > 500 + ? `${step.reasoning.substring(0, 500)}...` + : step.reasoning; + comment += `${reasoningText}\n\n`; + } + + // Show files involved (simplified) + if (step.files_involved && step.files_involved.length > 0) { + const uniqueFiles = [...new Set(step.files_involved)]; + comment += `**Files**: ${uniqueFiles.map(f => `\`${f}\``).join(', ')}\n\n`; + } + + // Show file analysis (simplified) + if (step.action === 'analyze_code' || step.action === 'read_file') { + const relevantFiles = Array.from(analyzedFiles.values()).filter(f => + step.files_involved?.includes(f.path) + ); + + const stepAnalysis = (step as any).file_analysis_in_step as FileAnalysis[] | undefined; + const filesToShow = stepAnalysis || relevantFiles; + + if (filesToShow.length > 0) { + comment += `**Analysis**: `; + filesToShow.forEach((file, idx) => { + if (idx > 0) comment += ` | `; + comment += `\`${file.path}\` (${file.relevance}): ${file.key_findings.substring(0, 100)}${file.key_findings.length > 100 ? '...' : ''}`; + }); + comment += `\n\n`; + } + } + + // Show proposals (simplified reference) + const stepProposals = (step as any).proposals_in_step as ProposedChange[] | undefined; + if (stepProposals && stepProposals.length > 0) { + comment += `**Proposed Changes**: ${stepProposals.map(c => `${c.change_type} \`${c.file_path}\``).join(', ')}\n\n`; + + // Mark as shown + stepProposals.forEach((change) => { + const globalIndex = proposedChanges.indexOf(change); + if (globalIndex >= 0) { + proposalShownFlags.add(globalIndex); + } + }); + } + + comment += `---\n\n`; + } + + comment += `\n
\n\n`; + comment += `---\n\n`; + + // Footer + comment += `*Analysis completed in ${totalIterations} iterations. Analyzed ${analyzedFiles.size} files and proposed ${proposedChanges.length} changes.*\n`; + + // Truncate if too long + if (comment.length > this.GITHUB_COMMENT_MAX_LENGTH) { + // Try to keep main content, truncate collapsed section + const mainContent = comment.substring(0, comment.indexOf('
')); + const truncated = mainContent + `\n\n
\nšŸ”„ Detailed Reasoning Steps - Truncated due to length\n\n*Steps section was truncated due to comment length limits.*\n\n
\n\n`; + if (truncated.length > this.GITHUB_COMMENT_MAX_LENGTH) { + // If still too long, truncate main content + const finalTruncated = truncated.substring(0, this.GITHUB_COMMENT_MAX_LENGTH - 200); + return finalTruncated + `\n\n*[Comment truncated due to length limit]*\n`; + } + return truncated; + } + + return comment; + } + + /** + * Format a single proposed change + */ + formatProposedChange(change: ProposedChange, index: number): string { + let formatted = `### ${index}. ${this.getChangeTypeEmoji(change.change_type)} ${change.change_type.toUpperCase()}: \`${change.file_path}\`\n\n`; + + formatted += `**Description**: ${change.description}\n\n`; + + if (change.reasoning) { + formatted += `**Reasoning**: ${change.reasoning}\n\n`; + } + + if (change.suggested_code) { + const language = this.detectLanguageFromPath(change.file_path); + formatted += `**Suggested Code**:\n\n`; + formatted += `\`\`\`${language}\n${change.suggested_code}\n\`\`\`\n\n`; + } + + formatted += `---\n\n`; + + return formatted; + } + + /** + * Detect programming language from file path/extension + */ + detectLanguageFromPath(filePath: string): string { + const extension = filePath.split('.').pop()?.toLowerCase() || ''; + + const languageMap: { [key: string]: string } = { + // TypeScript/JavaScript + 'ts': 'typescript', + 'tsx': 'tsx', + 'js': 'javascript', + 'jsx': 'jsx', + 'mjs': 'javascript', + 'cjs': 'javascript', + + // Python + 'py': 'python', + 'pyw': 'python', + 'pyi': 'python', + + // Java/Kotlin + 'java': 'java', + 'kt': 'kotlin', + 'kts': 'kotlin', + + // Go + 'go': 'go', + + // Rust + 'rs': 'rust', + + // C/C++ + 'c': 'c', + 'cpp': 'cpp', + 'cc': 'cpp', + 'cxx': 'cpp', + 'h': 'c', + 'hpp': 'cpp', + 'hxx': 'cpp', + + // C# + 'cs': 'csharp', + + // Ruby + 'rb': 'ruby', + + // PHP + 'php': 'php', + + // Swift + 'swift': 'swift', + + // Dart + 'dart': 'dart', + + // Shell + 'sh': 'bash', + 'bash': 'bash', + 'zsh': 'bash', + 'fish': 'fish', + + // Configuration + 'json': 'json', + 'yaml': 'yaml', + 'yml': 'yaml', + 'toml': 'toml', + 'xml': 'xml', + 'ini': 'ini', + 'conf': 'conf', + 'config': 'conf', + + // Markup + 'html': 'html', + 'htm': 'html', + 'css': 'css', + 'scss': 'scss', + 'sass': 'sass', + 'less': 'less', + 'md': 'markdown', + 'markdown': 'markdown', + + // SQL + 'sql': 'sql', + + // Docker + 'dockerfile': 'dockerfile', + 'docker': 'dockerfile', + + // Other + 'txt': 'text', + 'log': 'text', + }; + + // Check for exact match + if (languageMap[extension]) { + return languageMap[extension]; + } + + // Check for Dockerfile (no extension) + if (filePath.toLowerCase().includes('dockerfile')) { + return 'dockerfile'; + } + + // Default to empty string if unknown + return ''; + } + + /** + * Get emoji for action type + */ + getActionEmoji(action: string): string { + const emojiMap: { [key: string]: string } = { + 'search_files': 'šŸ”', + 'read_file': 'šŸ“–', + 'analyze_code': 'šŸ”¬', + 'propose_changes': 'šŸ’”', + 'complete': 'āœ…' + }; + return emojiMap[action] || 'šŸ“'; + } + + /** + * Format action name for display + */ + formatActionName(action: string): string { + const nameMap: { [key: string]: string } = { + 'search_files': 'Search Files', + 'read_file': 'Read Files', + 'analyze_code': 'Analyze Code', + 'propose_changes': 'Propose Changes', + 'complete': 'Complete' + }; + return nameMap[action] || action; + } + + /** + * Get emoji for change type + */ + getChangeTypeEmoji(changeType: string): string { + const emojiMap: { [key: string]: string } = { + 'create': '✨', + 'modify': 'šŸ“', + 'delete': 'šŸ—‘ļø', + 'refactor': 'ā™»ļø' + }; + return emojiMap[changeType] || 'šŸ“'; + } +} + diff --git a/src/usecase/steps/common/services/file_cache_manager.ts b/src/usecase/steps/common/services/file_cache_manager.ts new file mode 100644 index 00000000..324d645c --- /dev/null +++ b/src/usecase/steps/common/services/file_cache_manager.ts @@ -0,0 +1,136 @@ +import { Execution } from '../../../../data/model/execution'; +import { SupabaseRepository, AICachedFileInfo } from '../../../../data/repository/supabase_repository'; +import { logError, logInfo, logDebugInfo } from '../../../../utils/logger'; +import { CachedFileInfo } from './types'; +import { createHash } from 'crypto'; + +/** + * Service for managing AI file cache in Supabase + */ +export class FileCacheManager { + private supabaseRepository: SupabaseRepository | null = null; + + /** + * Normalize file path for consistent comparison + * Removes leading ./ and normalizes path separators + */ + private normalizePath(path: string): string { + return path + .replace(/^\.\//, '') // Remove leading ./ + .replace(/\\/g, '/') // Normalize separators + .trim(); + } + + /** + * Calculate SHA256 hash of file content + */ + calculateFileSHA(content: string): string { + return createHash('sha256').update(content).digest('hex'); + } + + /** + * Initialize Supabase repository if config is available + */ + initSupabaseRepository(param: Execution): SupabaseRepository | null { + if (!this.supabaseRepository && param.supabaseConfig) { + this.supabaseRepository = new SupabaseRepository(param.supabaseConfig); + } + return this.supabaseRepository; + } + + /** + * Load cache from Supabase (or return empty map if Supabase not available) + * Uses normalized paths for consistent lookup + */ + async loadAICache(param: Execution): Promise> { + this.initSupabaseRepository(param); + const cache = new Map(); + + if (!this.supabaseRepository) { + logInfo(`šŸ“‚ Supabase not configured, starting with empty cache`); + return cache; + } + + try { + const branch = param.commit.branch || param.branches.main; + const cachedFiles = await this.supabaseRepository.getAIFileCachesByBranch( + param.owner, + param.repo, + branch + ); + + for (const file of cachedFiles) { + const normalizedPath = this.normalizePath(file.path); + cache.set(normalizedPath, { + path: normalizedPath, + sha: file.sha, + description: file.description, + consumes: (file.consumes || []).map(p => this.normalizePath(p)), + consumed_by: (file.consumed_by || []).map(p => this.normalizePath(p)) + }); + } + + logInfo(`šŸ“‚ Loaded ${cache.size} files from Supabase cache`); + if (cachedFiles.length > 0) { + logDebugInfo(`šŸ“‚ Sample cached paths: ${Array.from(cache.keys()).slice(0, 5).join(', ')}`); + } + } catch (error) { + logError(`Error loading AI cache from Supabase: ${error}`); + } + + return cache; + } + + /** + * Get cached file info by path (with path normalization) + */ + getCachedFile(cache: Map, filePath: string): CachedFileInfo | undefined { + const normalizedPath = this.normalizePath(filePath); + return cache.get(normalizedPath); + } + + /** + * Save cache entry to Supabase + * Normalizes paths before saving + */ + async saveAICacheEntry( + param: Execution, + filePath: string, + fileInfo: CachedFileInfo, + consumes: string[], + consumedBy: string[] + ): Promise { + this.initSupabaseRepository(param); + + if (!this.supabaseRepository) { + return; // Silently skip if Supabase not available + } + + try { + const branch = param.commit.branch || param.branches.main; + const fileName = filePath.split('/').pop() || filePath; + const normalizedPath = this.normalizePath(filePath); + const normalizedConsumes = consumes.map(p => this.normalizePath(p)); + const normalizedConsumedBy = consumedBy.map(p => this.normalizePath(p)); + + await this.supabaseRepository.setAIFileCache( + param.owner, + param.repo, + branch, + { + file_name: fileName, + path: normalizedPath, + sha: fileInfo.sha, + description: fileInfo.description, + consumes: normalizedConsumes, + consumed_by: normalizedConsumedBy + } + ); + + logDebugInfo(`šŸ’¾ Saved cache entry for ${normalizedPath}`); + } catch (error) { + logError(`Error saving AI cache entry to Supabase for ${filePath}: ${error}`); + } + } +} + diff --git a/src/usecase/steps/common/services/file_import_analyzer.ts b/src/usecase/steps/common/services/file_import_analyzer.ts new file mode 100644 index 00000000..9714509e --- /dev/null +++ b/src/usecase/steps/common/services/file_import_analyzer.ts @@ -0,0 +1,253 @@ +/** + * Service for extracting imports and building file relationship maps + * Supports multiple programming languages + */ +export class FileImportAnalyzer { + /** + * Extract imports from a file regardless of programming language + */ + extractImportsFromFile(filePath: string, content: string): string[] { + const imports: string[] = []; + const ext = filePath.split('.').pop()?.toLowerCase() || ''; + const dir = filePath.split('/').slice(0, -1).join('/') || ''; + + // TypeScript/JavaScript + if (['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs'].includes(ext)) { + // import ... from '...' + const es6Imports = content.match(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g) || []; + es6Imports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) imports.push(path); + }); + + // require('...') + const requireImports = content.match(/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g) || []; + requireImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) imports.push(path); + }); + } + + // Python + if (['py', 'pyw', 'pyi'].includes(ext)) { + // import ... / from ... import ... + const pyImports = content.match(/(?:^|\n)\s*(?:import\s+\w+|from\s+[\w.]+)\s+import/gm) || []; + pyImports.forEach(match => { + const fromMatch = match.match(/from\s+([\w.]+)/); + if (fromMatch) { + imports.push(fromMatch[1]); + } else { + const importMatch = match.match(/import\s+(\w+)/); + if (importMatch) imports.push(importMatch[1]); + } + }); + } + + // Java + if (ext === 'java') { + const javaImports = content.match(/import\s+(?:static\s+)?[\w.]+\s*;/g) || []; + javaImports.forEach(match => { + const path = match.replace(/import\s+(?:static\s+)?/, '').replace(/\s*;/, ''); + imports.push(path); + }); + } + + // Kotlin + if (['kt', 'kts'].includes(ext)) { + const ktImports = content.match(/import\s+[\w.]+\s*/g) || []; + ktImports.forEach(match => { + const path = match.replace(/import\s+/, '').trim(); + imports.push(path); + }); + } + + // Go + if (ext === 'go') { + const goImports = content.match(/import\s*(?:\([^)]+\)|['"]([^'"]+)['"])/gs) || []; + goImports.forEach(match => { + const quoted = match.match(/['"]([^'"]+)['"]/); + if (quoted) { + imports.push(quoted[1]); + } else { + // Multi-line import block + const multiLine = match.match(/import\s*\(([^)]+)\)/s); + if (multiLine) { + const paths = multiLine[1].match(/['"]([^'"]+)['"]/g) || []; + paths.forEach(p => { + const path = p.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) imports.push(path); + }); + } + } + }); + } + + // Rust + if (ext === 'rs') { + const rustImports = content.match(/use\s+[\w:]+(?:::\*)?\s*;/g) || []; + rustImports.forEach(match => { + const path = match.replace(/use\s+/, '').replace(/\s*;/, '').split('::')[0]; + imports.push(path); + }); + } + + // Ruby + if (ext === 'rb') { + const rubyImports = content.match(/(?:require|require_relative)\s+['"]([^'"]+)['"]/g) || []; + rubyImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) imports.push(path); + }); + } + + // PHP + if (ext === 'php') { + const phpImports = content.match(/(?:use|require|include)(?:_once)?\s+['"]([^'"]+)['"]/g) || []; + phpImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) imports.push(path); + }); + } + + // Swift + if (ext === 'swift') { + const swiftImports = content.match(/import\s+\w+/g) || []; + swiftImports.forEach(match => { + const path = match.replace(/import\s+/, ''); + imports.push(path); + }); + } + + // Dart + if (ext === 'dart') { + const dartImports = content.match(/import\s+['"]([^'"]+)['"]/g) || []; + dartImports.forEach(match => { + const path = match.match(/['"]([^'"]+)['"]/)?.[1]; + if (path) imports.push(path); + }); + } + + // Resolve relative imports to absolute paths + return imports.map(imp => { + // Skip external packages (node_modules, stdlib, etc.) + if (!imp.startsWith('.') && !imp.startsWith('/')) { + // Try to resolve relative to current file + if (dir) { + // Check if it's a relative path that needs resolution + const possiblePath = `${dir}/${imp}`.replace(/\/+/g, '/'); + return possiblePath; + } + return imp; + } + + // Resolve relative paths + if (imp.startsWith('.')) { + const resolved = this.resolveRelativePath(dir, imp); + return resolved; + } + + return imp; + }).filter(imp => imp && !imp.includes('node_modules') && !imp.startsWith('http')); + } + + /** + * Resolve relative import path to absolute path + */ + resolveRelativePath(baseDir: string, relativePath: string): string { + if (!relativePath.startsWith('.')) { + return relativePath; + } + + let path = baseDir || ''; + const parts = relativePath.split('/'); + + for (const part of parts) { + if (part === '..') { + path = path.split('/').slice(0, -1).join('/'); + } else if (part === '.' || part === '') { + // Current directory, do nothing + } else { + path = path ? `${path}/${part}` : part; + } + } + + // Remove file extension if present and add common extensions + const withoutExt = path.replace(/\.(ts|tsx|js|jsx|py|java|kt|go|rs|rb|php|swift|dart)$/, ''); + + return withoutExt; + } + + /** + * Build relationship map from all files by extracting imports + * Also builds reverse map (consumed_by) + */ + buildRelationshipMap( + repositoryFiles: Map + ): { consumes: Map, consumedBy: Map } { + const consumesMap = new Map(); + const consumedByMap = new Map(); + + // Initialize consumedBy map for all files + for (const filePath of repositoryFiles.keys()) { + consumedByMap.set(filePath, []); + } + + for (const [filePath, content] of repositoryFiles.entries()) { + const imports = this.extractImportsFromFile(filePath, content); + + // Resolve imports to actual file paths in the repository + const resolvedImports: string[] = []; + + for (const imp of imports) { + // Try to find matching file in repository + const possiblePaths = [ + imp, + `${imp}.ts`, + `${imp}.tsx`, + `${imp}.js`, + `${imp}.jsx`, + `${imp}/index.ts`, + `${imp}/index.tsx`, + `${imp}/index.js`, + `${imp}/index.jsx`, + ]; + + for (const possiblePath of possiblePaths) { + // Check exact match + if (repositoryFiles.has(possiblePath)) { + if (!resolvedImports.includes(possiblePath)) { + resolvedImports.push(possiblePath); + } + // Update reverse map + const currentConsumers = consumedByMap.get(possiblePath) || []; + if (!currentConsumers.includes(filePath)) { + currentConsumers.push(filePath); + consumedByMap.set(possiblePath, currentConsumers); + } + break; + } + + // Check if any file path contains this import + for (const [repoPath] of repositoryFiles.entries()) { + if (repoPath.includes(possiblePath) || possiblePath.includes(repoPath)) { + if (!resolvedImports.includes(repoPath)) { + resolvedImports.push(repoPath); + } + // Update reverse map + const currentConsumers = consumedByMap.get(repoPath) || []; + if (!currentConsumers.includes(filePath)) { + currentConsumers.push(filePath); + consumedByMap.set(repoPath, currentConsumers); + } + } + } + } + } + + consumesMap.set(filePath, resolvedImports); + } + + return { consumes: consumesMap, consumedBy: consumedByMap }; + } +} + diff --git a/src/usecase/steps/common/services/file_search_service.ts b/src/usecase/steps/common/services/file_search_service.ts new file mode 100644 index 00000000..8e298b67 --- /dev/null +++ b/src/usecase/steps/common/services/file_search_service.ts @@ -0,0 +1,68 @@ +/** + * Service for building file indexes and searching files + */ +export class FileSearchService { + /** + * Build file index for quick lookup by filename or directory + */ + buildFileIndex(files: Map): Map { + const index = new Map(); + + for (const [path, content] of files.entries()) { + const pathParts = path.split('/'); + const fileName = pathParts[pathParts.length - 1]; + + // Index by filename + if (!index.has(fileName)) { + index.set(fileName, []); + } + index.get(fileName)!.push(path); + + // Index by directory + if (pathParts.length > 1) { + const dir = pathParts.slice(0, -1).join('/'); + if (!index.has(dir)) { + index.set(dir, []); + } + index.get(dir)!.push(path); + } + } + + return index; + } + + /** + * Search files by search terms (filename, directory, or pattern) + */ + searchFiles(searchTerms: string[], fileIndex: Map): string[] { + const foundFiles = new Set(); + + for (const term of searchTerms) { + // Exact filename match + if (fileIndex.has(term)) { + fileIndex.get(term)!.forEach(f => foundFiles.add(f)); + } + + // Directory match + if (fileIndex.has(term)) { + fileIndex.get(term)!.forEach(f => foundFiles.add(f)); + } + + // Pattern match (simple contains) + for (const [key, paths] of fileIndex.entries()) { + if (key.toLowerCase().includes(term.toLowerCase())) { + paths.forEach(p => foundFiles.add(p)); + } + // Also check paths + paths.forEach(path => { + if (path.toLowerCase().includes(term.toLowerCase())) { + foundFiles.add(path); + } + }); + } + } + + return Array.from(foundFiles); + } +} + diff --git a/src/usecase/steps/common/services/types.ts b/src/usecase/steps/common/services/types.ts new file mode 100644 index 00000000..5f10e098 --- /dev/null +++ b/src/usecase/steps/common/services/types.ts @@ -0,0 +1,17 @@ +/** + * Shared types for codebase analysis services + */ + +export interface CachedFileInfo { + path: string; + sha: string; + description: string; + consumes: string[]; // Files this file imports + consumed_by: string[]; // Files that import this file +} + +export interface FileRelationshipMap { + consumes: Map; + consumedBy: Map; +} + diff --git a/src/usecase/steps/common/think_code_manager.ts b/src/usecase/steps/common/think_code_manager.ts new file mode 100644 index 00000000..e63eec33 --- /dev/null +++ b/src/usecase/steps/common/think_code_manager.ts @@ -0,0 +1,229 @@ +import { ProposedChange } from '../../../data/model/think_response'; +import { logDebugInfo, logInfo } from '../../../utils/logger'; + +/** + * Manages virtual code state - keeps files in memory and applies proposed changes + * so subsequent reasoning steps can see the accumulated progress + */ +export class ThinkCodeManager { + private originalFiles: Map = new Map(); + private virtualFiles: Map = new Map(); + private appliedChanges: Map = new Map(); // file -> changes applied + private allAppliedChanges: ProposedChange[] = []; + + /** + * Initialize with original repository files + */ + initialize(originalFiles: Map): void { + this.originalFiles = new Map(originalFiles); + this.virtualFiles = new Map(originalFiles); + this.appliedChanges.clear(); + this.allAppliedChanges = []; + logInfo(`šŸ“¦ Code manager initialized with ${originalFiles.size} files`); + } + + /** + * Get current state of a file (with applied changes) + */ + getFileContent(filePath: string): string | undefined { + return this.virtualFiles.get(filePath); + } + + /** + * Get all virtual files + */ + getAllFiles(): Map { + return new Map(this.virtualFiles); + } + + /** + * Check if a file has been modified + */ + isFileModified(filePath: string): boolean { + return this.appliedChanges.has(filePath); + } + + /** + * Get changes applied to a specific file + */ + getFileChanges(filePath: string): ProposedChange[] { + return this.appliedChanges.get(filePath) || []; + } + + /** + * Apply a proposed change to the virtual codebase + */ + applyChange(change: ProposedChange): boolean { + try { + const filePath = change.file_path; + const currentContent = this.virtualFiles.get(filePath) || ''; + + let newContent = currentContent; + + switch (change.change_type) { + case 'create': + if (!currentContent) { + // File doesn't exist, create it with suggested code + newContent = change.suggested_code || ''; + logDebugInfo(`āœ… Created virtual file: ${filePath}`); + } else { + logDebugInfo(`āš ļø File ${filePath} already exists, skipping create`); + return false; + } + break; + + case 'modify': + if (currentContent) { + // Apply modification - for now, append suggested code + // In a more sophisticated implementation, we could parse and merge + if (change.suggested_code) { + // Simple strategy: append the suggested code with a marker + newContent = `${currentContent}\n\n// === AI Proposed Modification ===\n${change.suggested_code}`; + logDebugInfo(`āœ… Modified virtual file: ${filePath}`); + } else { + // Just note the modification + newContent = `${currentContent}\n\n// === AI Proposed Modification: ${change.description} ===`; + logDebugInfo(`āœ… Noted modification in virtual file: ${filePath}`); + } + } else { + logDebugInfo(`āš ļø Cannot modify non-existent file: ${filePath}`); + return false; + } + break; + + case 'delete': + // Mark as deleted but keep for reference + newContent = `// === FILE MARKED FOR DELETION ===\n// Original content:\n${currentContent}`; + logDebugInfo(`āœ… Marked virtual file for deletion: ${filePath}`); + break; + + case 'refactor': + if (currentContent && change.suggested_code) { + // Refactor: replace with new code + newContent = `${currentContent}\n\n// === AI Proposed Refactoring ===\n${change.suggested_code}`; + logDebugInfo(`āœ… Refactored virtual file: ${filePath}`); + } else { + logDebugInfo(`āš ļø Cannot refactor file ${filePath}: ${currentContent ? 'no suggested code' : 'file does not exist'}`); + return false; + } + break; + + default: + logDebugInfo(`āš ļø Unknown change type: ${change.change_type}`); + return false; + } + + this.virtualFiles.set(filePath, newContent); + + // Track applied changes + if (!this.appliedChanges.has(filePath)) { + this.appliedChanges.set(filePath, []); + } + this.appliedChanges.get(filePath)!.push(change); + this.allAppliedChanges.push(change); + + return true; + } catch (error) { + logDebugInfo(`āŒ Error applying change to ${change.file_path}: ${error}`); + return false; + } + } + + /** + * Check if a change has already been applied (to avoid duplicates) + */ + hasChangeBeenApplied(change: ProposedChange): boolean { + // Check by file path and description similarity + const existingChanges = this.allAppliedChanges.filter(c => + c.file_path === change.file_path && + c.change_type === change.change_type && + this.areSimilar(c.description, change.description) + ); + return existingChanges.length > 0; + } + + /** + * Get summary of all applied changes + */ + getChangesSummary(): string { + if (this.allAppliedChanges.length === 0) { + return 'No changes applied yet.'; + } + + const summary: string[] = []; + summary.push(`\n## Applied Changes (${this.allAppliedChanges.length} total):\n`); + + for (const [filePath, changes] of this.appliedChanges.entries()) { + summary.push(`\n### ${filePath} (${changes.length} change${changes.length > 1 ? 's' : ''}):`); + changes.forEach((change, idx) => { + summary.push(` ${idx + 1}. ${change.change_type.toUpperCase()}: ${change.description}`); + }); + } + + return summary.join('\n'); + } + + /** + * Get context about what has changed for the AI + */ + getContextForAI(): string { + const context: string[] = []; + + if (this.allAppliedChanges.length > 0) { + context.push(`\n## Code State Changes Applied:`); + context.push(`Total changes applied: ${this.allAppliedChanges.length}`); + context.push(`Files modified: ${this.appliedChanges.size}`); + context.push(this.getChangesSummary()); + + // Show modified file contents summary + context.push(`\n## Modified Files Preview:`); + for (const [filePath, changes] of this.appliedChanges.entries()) { + const currentContent = this.virtualFiles.get(filePath); + if (currentContent) { + const preview = currentContent.substring(0, 500); + context.push(`\n### ${filePath}:`); + context.push(`\`\`\`\n${preview}${currentContent.length > 500 ? '\n... (truncated)' : ''}\n\`\`\``); + } + } + } else { + context.push(`\n## Code State: No changes applied yet.`); + } + + return context.join('\n'); + } + + /** + * Simple similarity check for change descriptions + */ + private areSimilar(desc1: string, desc2: string): boolean { + const normalize = (s: string) => s.toLowerCase().trim().replace(/\s+/g, ' '); + const n1 = normalize(desc1); + const n2 = normalize(desc2); + + // Exact match + if (n1 === n2) return true; + + // Check if one contains the other (for similar proposals) + if (n1.length > 20 && n2.length > 20) { + const words1 = n1.split(' ').filter(w => w.length > 3); + const words2 = n2.split(' ').filter(w => w.length > 3); + const commonWords = words1.filter(w => words2.includes(w)); + // If 70% of significant words match, consider similar + return commonWords.length / Math.max(words1.length, words2.length) > 0.7; + } + + return false; + } + + /** + * Get statistics + */ + getStats(): { totalFiles: number; modifiedFiles: number; totalChanges: number } { + return { + totalFiles: this.virtualFiles.size, + modifiedFiles: this.appliedChanges.size, + totalChanges: this.allAppliedChanges.length + }; + } +} + diff --git a/src/usecase/steps/common/think_todo_manager.ts b/src/usecase/steps/common/think_todo_manager.ts new file mode 100644 index 00000000..745b274f --- /dev/null +++ b/src/usecase/steps/common/think_todo_manager.ts @@ -0,0 +1,304 @@ +import { ThinkTodoItem, ThinkTodoList } from '../../../data/model/think_response'; +import { ProposedChange } from '../../../data/model/think_response'; +import { logDebugInfo, logInfo } from '../../../utils/logger'; + +/** + * Manages TODO list for the reasoning process + * Similar to how the assistant tracks high-level tasks vs iterative steps + */ +export class ThinkTodoManager { + private todos: Map = new Map(); + private nextId: number = 1; + + /** + * Initialize with optional initial todos + */ + initialize(initialTodos?: Array<{ content: string; status?: 'pending' | 'in_progress' }>): void { + this.todos.clear(); + this.nextId = 1; + + if (initialTodos && initialTodos.length > 0) { + for (const todo of initialTodos) { + this.createTodo(todo.content, todo.status || 'pending'); + } + logInfo(`šŸ“‹ TODO list initialized with ${initialTodos.length} tasks`); + } else { + logInfo(`šŸ“‹ TODO list initialized (empty)`); + } + } + + /** + * Create a new TODO item + */ + createTodo(content: string, status: 'pending' | 'in_progress' = 'pending'): ThinkTodoItem { + const id = `todo_${this.nextId++}`; + const now = Date.now(); + const todo: ThinkTodoItem = { + id, + content, + status, + created_at: now, + updated_at: now + }; + this.todos.set(id, todo); + logDebugInfo(`āœ… Created TODO: ${content} (${status})`); + return todo; + } + + /** + * Update an existing TODO item + */ + updateTodo(id: string, updates: { + status?: 'pending' | 'in_progress' | 'completed' | 'cancelled'; + notes?: string; + related_files?: string[]; + related_changes?: string[]; + }): boolean { + const todo = this.todos.get(id); + if (!todo) { + logDebugInfo(`āš ļø TODO ${id} not found for update`); + return false; + } + + const now = Date.now(); + const oldStatus = todo.status; + + if (updates.status) { + todo.status = updates.status; + if (updates.status === 'completed' && !todo.completed_at) { + todo.completed_at = now; + } + } + + if (updates.notes !== undefined) { + todo.notes = updates.notes; + } + + if (updates.related_files) { + todo.related_files = updates.related_files; + } + + if (updates.related_changes) { + todo.related_changes = updates.related_changes; + } + + todo.updated_at = now; + + if (oldStatus !== todo.status) { + logInfo(`šŸ“ Updated TODO ${id}: ${oldStatus} → ${todo.status}`); + } else { + logDebugInfo(`šŸ“ Updated TODO ${id} (notes/metadata)`); + } + + return true; + } + + /** + * Get all TODOs + */ + getAllTodos(): ThinkTodoItem[] { + return Array.from(this.todos.values()).sort((a, b) => a.created_at - b.created_at); + } + + /** + * Get TODOs by status + */ + getTodosByStatus(status: ThinkTodoItem['status']): ThinkTodoItem[] { + return this.getAllTodos().filter(todo => todo.status === status); + } + + /** + * Get active TODOs (pending or in_progress) + */ + getActiveTodos(): ThinkTodoItem[] { + return this.getAllTodos().filter(todo => + todo.status === 'pending' || todo.status === 'in_progress' + ); + } + + /** + * Get completion statistics + */ + getStats(): { + total: number; + pending: number; + in_progress: number; + completed: number; + cancelled: number; + completion_rate: number; + } { + const all = this.getAllTodos(); + const pending = all.filter(t => t.status === 'pending').length; + const in_progress = all.filter(t => t.status === 'in_progress').length; + const completed = all.filter(t => t.status === 'completed').length; + const cancelled = all.filter(t => t.status === 'cancelled').length; + const total = all.length; + const completion_rate = total > 0 ? (completed / total) * 100 : 0; + + return { + total, + pending, + in_progress, + completed, + cancelled, + completion_rate + }; + } + + /** + * Get formatted TODO list for AI context + */ + getContextForAI(): string { + const stats = this.getStats(); + const activeTodos = this.getActiveTodos(); + const completedTodos = this.getTodosByStatus('completed').slice(-5); // Last 5 completed + const allTodos = this.getAllTodos(); + + const context: string[] = []; + + context.push(`\n## šŸ“‹ TODO List Status`); + context.push(`- **Total Tasks**: ${stats.total}`); + context.push(`- **Pending**: ${stats.pending}`); + context.push(`- **In Progress**: ${stats.in_progress}`); + context.push(`- **Completed**: ${stats.completed} (${stats.completion_rate.toFixed(1)}%)`); + context.push(`- **Cancelled**: ${stats.cancelled}`); + + if (allTodos.length > 0) { + context.push(`\n### šŸ“ All TODO Items (with IDs for reference):`); + allTodos.forEach((todo, idx) => { + const statusEmoji = + todo.status === 'completed' ? 'āœ…' : + todo.status === 'in_progress' ? 'šŸ”„' : + todo.status === 'cancelled' ? 'āŒ' : 'ā³'; + context.push(`${idx + 1}. ${statusEmoji} **[ID: ${todo.id}]** ${todo.status.toUpperCase()}: ${todo.content}`); + if (todo.related_files && todo.related_files.length > 0) { + context.push(` šŸ“ Related files: ${todo.related_files.join(', ')}`); + } + if (todo.notes) { + context.push(` šŸ“ Notes: ${todo.notes}`); + } + }); + + context.push(`\n**āš ļø IMPORTANT**: When updating TODOs, use the EXACT ID shown above (e.g., "${allTodos[0]?.id || 'todo_1'}"). Do NOT use numeric IDs like "1" or "2".`); + } + + if (activeTodos.length > 0) { + context.push(`\n### šŸ”„ Active Tasks to Work On (${activeTodos.length}):`); + activeTodos.forEach((todo, idx) => { + const statusEmoji = todo.status === 'in_progress' ? 'šŸ”„' : 'ā³'; + context.push(`${idx + 1}. ${statusEmoji} **[ID: ${todo.id}]** ${todo.status.toUpperCase()}: ${todo.content}`); + if (todo.related_files && todo.related_files.length > 0) { + context.push(` šŸ“ Related files: ${todo.related_files.join(', ')}`); + } + if (todo.notes) { + context.push(` šŸ“ Notes: ${todo.notes}`); + } + }); + } + + if (completedTodos.length > 0) { + context.push(`\n### āœ… Recently Completed (${completedTodos.length}):`); + completedTodos.forEach((todo, idx) => { + context.push(`${idx + 1}. āœ… **[ID: ${todo.id}]** ${todo.content}`); + }); + } + + if (activeTodos.length === 0 && stats.total > 0) { + context.push(`\nšŸŽ‰ All tasks completed!`); + } + + return context.join('\n'); + } + + /** + * Link a TODO to proposed changes + */ + linkTodoToChanges(todoId: string, changes: ProposedChange[]): void { + const todo = this.todos.get(todoId); + if (!todo) return; + + const changeDescriptions = changes.map(c => + `${c.change_type}:${c.file_path}:${c.description.substring(0, 50)}` + ); + + if (!todo.related_changes) { + todo.related_changes = []; + } + todo.related_changes.push(...changeDescriptions); + + // Also update related files + const files = changes.map(c => c.file_path); + if (!todo.related_files) { + todo.related_files = []; + } + todo.related_files.push(...files); + todo.related_files = [...new Set(todo.related_files)]; // Remove duplicates + + todo.updated_at = Date.now(); + } + + /** + * Auto-update TODO status based on progress + * If changes are applied for a TODO, mark it as in_progress or completed + */ + autoUpdateFromChanges(changes: ProposedChange[]): void { + // Find active TODOs that might be related to these changes + const activeTodos = this.getActiveTodos(); + + for (const todo of activeTodos) { + // Check if any of the changes are related to this TODO's files + if (todo.related_files) { + const relatedChanges = changes.filter(c => + todo.related_files!.includes(c.file_path) + ); + + if (relatedChanges.length > 0) { + // Link changes to TODO + this.linkTodoToChanges(todo.id, relatedChanges); + + // If TODO was pending, mark as in_progress + if (todo.status === 'pending') { + this.updateTodo(todo.id, { + status: 'in_progress', + notes: `Auto-updated: ${relatedChanges.length} change(s) applied` + }); + } + } + } + } + } + + /** + * Get summary for final report + */ + getSummary(): string { + const stats = this.getStats(); + const allTodos = this.getAllTodos(); + + if (allTodos.length === 0) { + return 'No TODO list was created during this analysis.'; + } + + const summary: string[] = []; + summary.push(`\n## TODO List Summary`); + summary.push(`- Total tasks: ${stats.total}`); + summary.push(`- Completed: ${stats.completed} (${stats.completion_rate.toFixed(1)}%)`); + summary.push(`- In Progress: ${stats.in_progress}`); + summary.push(`- Pending: ${stats.pending}`); + + summary.push(`\n### All Tasks:`); + allTodos.forEach((todo, idx) => { + const statusIcon = + todo.status === 'completed' ? 'āœ…' : + todo.status === 'in_progress' ? 'šŸ”„' : + todo.status === 'cancelled' ? 'āŒ' : 'ā³'; + summary.push(`${idx + 1}. ${statusIcon} **${todo.status.toUpperCase()}**: ${todo.content}`); + if (todo.notes) { + summary.push(` Notes: ${todo.notes}`); + } + }); + + return summary.join('\n'); + } +} + diff --git a/src/usecase/steps/common/think_use_case.ts b/src/usecase/steps/common/think_use_case.ts new file mode 100644 index 00000000..1181e1c9 --- /dev/null +++ b/src/usecase/steps/common/think_use_case.ts @@ -0,0 +1,768 @@ +import { ThinkResponse, ThinkStep, ProposedChange, FileAnalysis } from '../../../data/model/think_response'; +import { Execution } from '../../../data/model/execution'; +import { Result } from '../../../data/model/result'; +import { AiRepository } from '../../../data/repository/ai_repository'; +import { FileRepository } from '../../../data/repository/file_repository'; +import { IssueRepository } from '../../../data/repository/issue_repository'; +import { logDebugInfo, logError, logInfo } from '../../../utils/logger'; +import { ParamUseCase } from '../../base/param_usecase'; +import { ThinkCodeManager } from './think_code_manager'; +import { ThinkTodoManager } from './think_todo_manager'; +import { FileImportAnalyzer } from './services/file_import_analyzer'; +import { FileCacheManager } from './services/file_cache_manager'; +import { CodebaseAnalyzer } from './services/codebase_analyzer'; +import { FileSearchService } from './services/file_search_service'; +import { CommentFormatter } from './services/comment_formatter'; + +export class ThinkUseCase implements ParamUseCase { + taskId: string = 'ThinkUseCase'; + private aiRepository: AiRepository = new AiRepository(); + private fileRepository: FileRepository = new FileRepository(); + private issueRepository: IssueRepository = new IssueRepository(); + + // Services + private fileImportAnalyzer: FileImportAnalyzer = new FileImportAnalyzer(); + private fileCacheManager: FileCacheManager = new FileCacheManager(); + private codebaseAnalyzer: CodebaseAnalyzer; + private fileSearchService: FileSearchService = new FileSearchService(); + private commentFormatter: CommentFormatter = new CommentFormatter(); + + private readonly MAX_ITERATIONS = 30; // Increased to allow deeper analysis + private readonly MAX_FILES_TO_ANALYZE = 50; // Increased file limit + private readonly MAX_CONSECUTIVE_SEARCHES = 3; // Max consecutive search_files without progress + + constructor() { + // Initialize CodebaseAnalyzer with dependencies + this.codebaseAnalyzer = new CodebaseAnalyzer( + this.aiRepository, + this.fileImportAnalyzer, + this.fileCacheManager + ); + } + + async invoke(param: Execution): Promise { + logInfo(`Executing ${this.taskId}.`); + + const results: Result[] = []; + + try { + // Extract the question/prompt from the issue, PR, or comment + let question = ''; + let description = ''; + + if (param.issue.isIssueComment) { + question = param.issue.commentBody || ''; + description = await this.getIssueDescription(param) || ''; + } else if (param.pullRequest.isPullRequestReviewComment) { + question = param.pullRequest.commentBody || ''; + description = await this.getIssueDescription(param) || ''; + } else if (param.issue.isIssue) { + description = await this.getIssueDescription(param) || ''; + question = description; + } else if (param.singleAction.isThinkAction) { + // For CLI usage, get question from comment body if available + // This handles the case when think is called as single-action + const commentBody = param.issue.commentBody || param.inputs?.comment?.body || ''; + if (commentBody) { + question = commentBody; + description = await this.getIssueDescription(param) || ''; + } else { + description = await this.getIssueDescription(param) || ''; + question = description || ''; + } + } + + if (!question || question.length === 0) { + if (!param.singleAction.isThinkAction) { + results.push( + new Result({ + id: this.taskId, + success: false, + executed: false, + errors: ['No question or prompt provided.'], + }) + ); + return results; + } + } + + if (param.ai.getOpenRouterModel().length === 0 || param.ai.getOpenRouterApiKey().length === 0) { + results.push( + new Result({ + id: this.taskId, + success: false, + executed: false, + errors: ['OpenRouter model or API key not found.'], + }) + ); + return results; + } + + logInfo(`šŸ”Ž Question: ${question}`); + logInfo(`šŸ”Ž Description: ${description}`); + + if (question.length === 0 || !question.includes(`@${param.tokenUser}`)) { + logInfo(`šŸ”Ž Comment body is empty or does not include @${param.tokenUser}`); + results.push( + new Result({ + id: this.taskId, + success: true, + executed: false, + }) + ); + return results; + } else { + question = question.replace(`@${param.tokenUser}`, '').trim(); + } + + // Get full repository content + logInfo(`šŸ“š Loading repository content for ${param.owner}/${param.repo}/${param.commit.branch}`); + const repositoryFiles = await this.fileRepository.getRepositoryContent( + param.owner, + param.repo, + param.tokens.token, + param.commit.branch, + param.ai.getAiIgnoreFiles(), + (fileName: string) => logDebugInfo(`Loading: ${fileName}`), + (fileName: string) => logDebugInfo(`Ignoring: ${fileName}`) + ); + + logInfo(`šŸ“š Loaded ${repositoryFiles.size} files from repository`); + + // Initialize code manager with repository files + const codeManager = new ThinkCodeManager(); + codeManager.initialize(repositoryFiles); + + // Initialize TODO manager + const todoManager = new ThinkTodoManager(); + // AI will create initial TODOs in first iteration if needed + + // Build file index for quick lookup + const fileIndex = this.fileSearchService.buildFileIndex(repositoryFiles); + + // STEP 0: Generate codebase analysis and file relationships + logInfo(`šŸ” Step 0: Analyzing codebase structure and file relationships...`); + const codebaseAnalysis = await this.codebaseAnalyzer.generateCodebaseAnalysis( + param, + repositoryFiles, + question + ); + logInfo(`āœ… Codebase analysis completed. Analyzed ${codebaseAnalysis.length} files.`); + + // Format codebase analysis for context + const codebaseAnalysisText = this.codebaseAnalyzer.formatCodebaseAnalysisForContext(codebaseAnalysis); + + // Reasoning process + const steps: ThinkStep[] = []; + let iteration = 0; + let complete = false; + let analyzedFiles: Map = new Map(); + let allProposedChanges: ProposedChange[] = []; + let currentContext = codebaseAnalysisText; // Start with codebase analysis + let finalAnalysis = ''; + let consecutiveSearches = 0; // Track consecutive search_files without reading + let lastProgressIteration = 0; // Track last iteration with actual progress + let filesReadInIteration = 0; + let seenActions: Map = new Map(); // Track action patterns to detect repetition + + while (!complete && iteration < this.MAX_ITERATIONS) { + iteration++; + filesReadInIteration = 0; + logInfo(`šŸ¤” Reasoning iteration ${iteration}/${this.MAX_ITERATIONS}`); + + const thinkResponse = await this.performReasoningStep( + param, + question, + description, + codeManager, + todoManager, + fileIndex, + analyzedFiles, + currentContext, + iteration, + steps + ) as ThinkResponse; + + if (!thinkResponse) { + logError('No response from AI reasoning step'); + break; + } + + // Handle TODO updates (can be included with any action) + if (thinkResponse.todo_updates) { + // Create new TODOs + if (thinkResponse.todo_updates.create) { + for (const todo of thinkResponse.todo_updates.create) { + const createdTodo = todoManager.createTodo(todo.content, todo.status || 'pending'); + logInfo(`āœ… Created TODO: [${createdTodo.id}] ${todo.content}`); + } + logInfo(`šŸ“‹ Created ${thinkResponse.todo_updates.create.length} new TODO items`); + } + + // Update existing TODOs + if (thinkResponse.todo_updates.update) { + let successCount = 0; + let failedIds: string[] = []; + + for (const update of thinkResponse.todo_updates.update) { + const success = todoManager.updateTodo(update.id, { + status: update.status, + notes: update.notes + }); + if (success) { + successCount++; + } else { + failedIds.push(update.id); + } + } + + if (successCount > 0) { + logInfo(`šŸ“‹ Successfully updated ${successCount} TODO items`); + } + + if (failedIds.length > 0) { + // Show available TODO IDs to help the AI + const allTodos = todoManager.getAllTodos(); + const availableIds = allTodos.map(t => t.id).join(', '); + logInfo(`āš ļø Failed to update ${failedIds.length} TODO items. Available IDs: ${availableIds}`); + currentContext += `\n\nāš ļø TODO Update Error: Could not find TODO(s) with ID(s): ${failedIds.join(', ')}. Available TODO IDs are: ${availableIds}. Please use the EXACT ID from the TODO list above.`; + } + } + } + + // Record step with associated data for better comment formatting + const step: ThinkStep = { + step_number: iteration, + action: thinkResponse.action, + reasoning: thinkResponse.reasoning, + files_involved: [ + ...(thinkResponse.files_to_read || []), + ...(thinkResponse.files_to_search || []), + ...(thinkResponse.analyzed_files?.map(f => f.path) || []) + ], + findings: thinkResponse.reasoning, + timestamp: Date.now() + }; + + // Attach proposals to step if they were generated in this step + if (thinkResponse.action === 'propose_changes' && thinkResponse.proposed_changes) { + (step as any).proposals_in_step = thinkResponse.proposed_changes; + } + + // Attach file analysis to step if provided + if (thinkResponse.action === 'analyze_code' && thinkResponse.analyzed_files) { + (step as any).file_analysis_in_step = thinkResponse.analyzed_files; + } + + steps.push(step); + + logInfo(`šŸ¤” Step ${iteration}: ${thinkResponse.action} - ${thinkResponse.reasoning.substring(0, 100)}...`); + + // Track action patterns to detect repetition + const actionKey = `${thinkResponse.action}_${thinkResponse.files_to_search?.join(',') || thinkResponse.files_to_read?.join(',') || 'general'}`; + const actionCount = seenActions.get(actionKey) || 0; + seenActions.set(actionKey, actionCount + 1); + + // Execute action + switch (thinkResponse.action) { + case 'search_files': + consecutiveSearches++; + if (thinkResponse.files_to_search && thinkResponse.files_to_search.length > 0) { + const foundFiles = this.fileSearchService.searchFiles(thinkResponse.files_to_search, fileIndex); + logInfo(`šŸ” Search results: Found ${foundFiles.length} files for terms: ${thinkResponse.files_to_search.join(', ')}`); + + // Detect if we're repeating the same search + if (actionCount > 1) { + currentContext += `\n\nāš ļø WARNING: You've already searched for "${thinkResponse.files_to_search.join(', ')}" ${actionCount} times. `; + if (foundFiles.length > 0) { + currentContext += `These files were found previously. Consider READING them instead of searching again.`; + } else { + currentContext += `No files found. Consider trying different search terms or reading files from the list above.`; + } + } + + if (foundFiles.length > 0) { + currentContext += `\n\nFound ${foundFiles.length} files matching search criteria:\n${foundFiles.map(f => `- ${f}`).join('\n')}`; + + // If found files after multiple searches, suggest reading them + if (consecutiveSearches >= this.MAX_CONSECUTIVE_SEARCHES && foundFiles.length > 0) { + currentContext += `\n\nšŸ’” IMPORTANT: You've searched ${consecutiveSearches} times. You MUST read some of the found files now to proceed with analysis. Suggested files: ${foundFiles.slice(0, 5).join(', ')}`; + } + } else { + currentContext += `\n\nNo files found matching search criteria: ${thinkResponse.files_to_search.join(', ')}. Available files in repository: ${Array.from(repositoryFiles.keys()).slice(0, 30).join(', ')}...`; + + // If too many searches without finding files, provide full file list + if (consecutiveSearches >= this.MAX_CONSECUTIVE_SEARCHES) { + currentContext += `\n\nšŸ“‹ Here are all available files in the repository to help you:\n${Array.from(repositoryFiles.keys()).map((f, i) => `${i + 1}. ${f}`).slice(0, 100).join('\n')}${repositoryFiles.size > 100 ? '\n... and more' : ''}`; + } + } + } + break; + + case 'read_file': + consecutiveSearches = 0; // Reset counter when reading files + if (thinkResponse.files_to_read && thinkResponse.files_to_read.length > 0) { + const filesToAnalyze = thinkResponse.files_to_read.slice(0, this.MAX_FILES_TO_ANALYZE - analyzedFiles.size); + logInfo(`šŸ“– Reading ${filesToAnalyze.length} files: ${filesToAnalyze.join(', ')}`); + + for (const filePath of filesToAnalyze) { + if (analyzedFiles.has(filePath)) { + logDebugInfo(`ā­ļø Skipping already analyzed file: ${filePath}`); + continue; // Already analyzed + } + + // Get content from virtual files (includes applied changes) + const content = codeManager.getFileContent(filePath); + if (content !== undefined) { + filesReadInIteration++; + const isModified = codeManager.isFileModified(filePath); + const modificationNote = isModified ? ` [MODIFIED - ${codeManager.getFileChanges(filePath).length} change(s) applied]` : ''; + logDebugInfo(`āœ… Reading file: ${filePath} (${content.length} chars)${modificationNote}`); + + // Show current state with applied changes + currentContext += `\n\n=== File: ${filePath}${modificationNote} ===\n${content.substring(0, 8000)}${content.length > 8000 ? '\n... (truncated)' : ''}`; + + // If file was modified, show what changed + if (isModified) { + const changes = codeManager.getFileChanges(filePath); + currentContext += `\n\nāš ļø This file has been modified in previous steps. Changes applied: ${changes.map(c => `${c.change_type}: ${c.description}`).join(', ')}`; + } + + lastProgressIteration = iteration; + } else { + logInfo(`āŒ File not found in repository: ${filePath}`); + // Try to find similar file names + const fileName = filePath.split('/').pop() || ''; + const similarFiles = Array.from(repositoryFiles.keys()).filter(f => + f.toLowerCase().includes(fileName.toLowerCase()) || + f.split('/').pop()?.toLowerCase().includes(fileName.toLowerCase()) + ).slice(0, 5); + currentContext += `\n\nāš ļø File not found: ${filePath}. ${similarFiles.length > 0 ? `Similar files found: ${similarFiles.join(', ')}` : 'Please check the file path.'}`; + } + } + } + break; + + case 'analyze_code': + consecutiveSearches = 0; // Reset counter when analyzing + if (thinkResponse.analyzed_files && thinkResponse.analyzed_files.length > 0) { + const beforeCount = analyzedFiles.size; + for (const analysis of thinkResponse.analyzed_files) { + if (!analyzedFiles.has(analysis.path)) { + analyzedFiles.set(analysis.path, analysis); + } + } + + if (analyzedFiles.size > beforeCount) { + lastProgressIteration = iteration; + } + + const findings = thinkResponse.analyzed_files + .map(f => `${f.path} (${f.relevance}): ${f.key_findings}`) + .join('\n'); + currentContext += `\n\nAnalysis findings:\n${findings}`; + } + break; + + case 'propose_changes': + consecutiveSearches = 0; // Reset counter when proposing changes + if (thinkResponse.proposed_changes && thinkResponse.proposed_changes.length > 0) { + // Filter out changes that have already been applied + const newChanges = thinkResponse.proposed_changes.filter(change => + !codeManager.hasChangeBeenApplied(change) + ); + + if (newChanges.length === 0) { + logInfo(`āš ļø All proposed changes have already been applied. Skipping duplicates.`); + currentContext += `\n\nāš ļø All proposed changes in this step have already been applied in previous iterations. Please propose NEW changes or move to the next step.`; + break; + } + + // Apply changes to virtual codebase + let appliedCount = 0; + for (const change of newChanges) { + if (codeManager.applyChange(change)) { + appliedCount++; + allProposedChanges.push(change); + } + } + + logInfo(`āœ… Applied ${appliedCount} new changes to virtual codebase (${newChanges.length - appliedCount} skipped)`); + + // Auto-update TODOs based on applied changes + todoManager.autoUpdateFromChanges(newChanges.slice(0, appliedCount)); + + // Store the index where these proposals start for proper ordering + const startIndex = allProposedChanges.length - appliedCount; + const appliedChanges = newChanges.slice(0, appliedCount); + + // Attach to step with start index for proper display order + const currentStep = steps[steps.length - 1]; + if (currentStep) { + (currentStep as any).proposals_in_step = appliedChanges; + (currentStep as any).proposals_start_index = startIndex; + } + + const changesSummary = appliedChanges + .map(c => `${c.change_type} ${c.file_path}: ${c.description}`) + .join('\n'); + currentContext += `\n\nāœ… Applied ${appliedCount} new changes to codebase:\n${changesSummary}`; + + // Add context about code state + currentContext += codeManager.getContextForAI(); + + lastProgressIteration = iteration; + } + break; + + case 'update_todos': + consecutiveSearches = 0; // Reset counter when updating TODOs + // Note: TODO updates are handled before the switch statement + // This case is mainly for when action is explicitly update_todos + if (thinkResponse.todo_updates && ( + !thinkResponse.files_to_search && + !thinkResponse.files_to_read && + !thinkResponse.analyzed_files && + !thinkResponse.proposed_changes + )) { + // Pure TODO update action - warn if this happens too often + logInfo(`šŸ“‹ Pure TODO update action (no other work done)`); + currentContext += `\n\nšŸ“‹ TODO list updated. Current status:\n${todoManager.getContextForAI()}`; + currentContext += `\n\nāš ļø **NOTE**: You updated TODOs but didn't do any actual work. In the next iteration, DO THE WORK: search for files, read files, analyze code, or propose changes related to the active TODOs.`; + lastProgressIteration = iteration; + } + break; + + case 'complete': + complete = true; + finalAnalysis = thinkResponse.final_analysis || thinkResponse.reasoning; + lastProgressIteration = iteration; + break; + } + + // Check for stagnation - if too many iterations without progress + const iterationsWithoutProgress = iteration - lastProgressIteration; + if (iterationsWithoutProgress > 5 && !complete && iteration > 5) { + logInfo(`āš ļø No significant progress in last ${iterationsWithoutProgress} iterations (last progress at iteration ${lastProgressIteration}). Forcing completion.`); + complete = true; + if (!finalAnalysis) { + finalAnalysis = `Analysis completed after ${iteration} iterations. Analyzed ${analyzedFiles.size} files, proposed ${allProposedChanges.length} changes.`; + } + } + + // Check if stuck in TODO update loop + const recentActions = steps.slice(-3).map(s => s.action); + const allUpdateTodos = recentActions.every(a => a === 'update_todos'); + if (allUpdateTodos && recentActions.length >= 3 && iteration > 3) { + logInfo(`āš ļø Detected loop: ${recentActions.length} consecutive update_todos actions. Warning AI to do actual work.`); + const activeTodos = todoManager.getActiveTodos(); + const todoIds = activeTodos.map(t => t.id).join(', '); + currentContext += `\n\nāš ļø **STOP UPDATING TODOs AND DO ACTUAL WORK**: You've been updating TODOs repeatedly. Pick a TODO to work on (IDs: ${todoIds}) and DO THE WORK: search for files, read files, analyze code, or propose changes. Stop just updating TODO status!`; + } + + // Prevent infinite loops - check file limit + if (analyzedFiles.size >= this.MAX_FILES_TO_ANALYZE) { + logInfo(`Reached maximum files to analyze (${this.MAX_FILES_TO_ANALYZE})`); + if (!complete) { + complete = true; + finalAnalysis = finalAnalysis || `Reached maximum file limit. Analyzed ${analyzedFiles.size} files, proposed ${allProposedChanges.length} changes.`; + } + break; + } + } + + // Generate final comprehensive response + if (!finalAnalysis && complete) { + finalAnalysis = await this.generateFinalAnalysis(param, question, analyzedFiles, allProposedChanges, steps, todoManager); + } + + // Format and post comprehensive reasoning comment + const formattedComment = this.commentFormatter.formatReasoningComment( + question, + description, + steps, + analyzedFiles, + allProposedChanges, + finalAnalysis, + iteration, + todoManager + ); + + // Determine issue number + let issueNumber = param.issueNumber; + if (param.singleAction.isThinkAction && issueNumber <= 0) { + // Try to get from issue if available + issueNumber = param.issue?.number || 1; + } + + // Post comment if we have a valid issue number and token + if (issueNumber > 0 && param.tokens.token) { + try { + await this.issueRepository.addComment( + param.owner, + param.repo, + issueNumber, + formattedComment, + param.tokens.token + ); + logInfo(`āœ… Posted reasoning comment to issue #${issueNumber}`); + } catch (error) { + logError(`Failed to post comment to issue: ${error}`); + } + } else { + logInfo(`ā­ļø Skipping comment post: issueNumber=${issueNumber}, hasToken=${!!param.tokens.token}`); + } + + results.push( + new Result({ + id: this.taskId, + success: true, + executed: true, + steps: steps.map(s => `Step ${s.step_number}: ${s.action} - ${s.reasoning.substring(0, 200)}`), + payload: { + steps: steps, + analyzed_files: Array.from(analyzedFiles.values()), + proposed_changes: allProposedChanges, + final_analysis: finalAnalysis, + total_iterations: iteration, + total_files_analyzed: analyzedFiles.size, + comment_posted: issueNumber > 0 + } + }) + ); + + } catch (error) { + logError(`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`); + results.push( + new Result({ + id: this.taskId, + success: false, + executed: true, + steps: [`Error in ${this.taskId}: ${JSON.stringify(error, null, 2)}`], + }) + ); + } + + return results; + } + + private async getIssueDescription(param: Execution): Promise { + try { + const description = await this.issueRepository.getDescription( + param.owner, + param.repo, + param.issueNumber, + param.tokens.token + ); + return description ?? null; + } catch (error) { + logError(`Error getting issue description: ${error}`); + return null; + } + } + + // All methods related to file imports, cache, codebase analysis, and comment formatting + // have been moved to dedicated services: + // - FileImportAnalyzer: extractImportsFromFile, resolveRelativePath, buildRelationshipMap + // - FileCacheManager: calculateFileSHA, loadAICache, saveAICacheEntry + // - CodebaseAnalyzer: generateCodebaseAnalysis, generateBasicDescription, generateFallbackFileDescriptions, formatCodebaseAnalysisForContext + // - FileSearchService: buildFileIndex, searchFiles + // - CommentFormatter: formatReasoningComment, formatProposedChange, detectLanguageFromPath, getActionEmoji, formatActionName, getChangeTypeEmoji + + private async performReasoningStep( + param: Execution, + question: string, + description: string, + codeManager: ThinkCodeManager, + todoManager: ThinkTodoManager, + fileIndex: Map, + analyzedFiles: Map, + currentContext: string, + iteration: number, + previousSteps: ThinkStep[] + ): Promise { + + const analyzedFilesList = Array.from(analyzedFiles.values()); + const analyzedFilesSummary = analyzedFilesList.length > 0 + ? `\n\nPreviously analyzed files (${analyzedFilesList.length}):\n${analyzedFilesList.map(f => `- ${f.path} (${f.relevance}): ${f.key_findings.substring(0, 150)}...`).join('\n')}` + : ''; + + const codeStats = codeManager.getStats(); + const codeStateInfo = codeManager.getContextForAI(); + const todoContext = todoManager.getContextForAI(); + const todoStats = todoManager.getStats(); + + // Get codebase analysis from initial step (stored in currentContext at start) + const codebaseAnalysisMatch = currentContext.match(/## šŸ“‹ Codebase Analysis & File Relationships\n\n([\s\S]*?)(?=\n##|$)/); + const codebaseAnalysis = codebaseAnalysisMatch ? codebaseAnalysisMatch[1] : ''; + + // Build summary of previous steps to avoid repetition + const stepsSummary = previousSteps.length > 0 + ? `\n\n## Previous Steps Taken (${previousSteps.length}):\n${previousSteps.slice(-5).map(s => + `- Step ${s.step_number}: ${s.action} - ${s.reasoning.substring(0, 100)}...` + ).join('\n')}${previousSteps.length > 5 ? `\n... and ${previousSteps.length - 5} more steps` : ''}` + : ''; + + const fileListSummary = `\n\nAvailable files in repository (${codeStats.totalFiles} files):\n${Array.from(codeManager.getAllFiles().keys()).slice(0, 50).join('\n')}${codeStats.totalFiles > 50 ? `\n... and ${codeStats.totalFiles - 50} more files` : ''}`; + + const prompt = ` +# Code Analysis Assistant + +You are an advanced code analysis assistant similar to Cursor's Auto agent. Your role is to perform deep analysis of codebases and propose thoughtful changes. + +**CRITICAL CONCEPTS**: + +1. **VIRTUAL CODEBASE**: You are working with a VIRTUAL CODEBASE. When you propose changes, they are automatically applied to the code in memory. Subsequent steps will see the MODIFIED code, not the original. This allows you to build upon previous changes incrementally. + +2. **TODO LIST SYSTEM**: You have a TODO list system to track high-level tasks. Each task in the TODO list may require multiple reasoning steps (search, read, analyze, propose). Use this to: + - Create TODOs in your first iteration to break down the problem + - Update TODO status as you make progress (pending → in_progress → completed) + - Link your actions to TODOs to show which task you're working on + - This helps you understand where you are in the overall process, even if you need many steps per task + +3. **TWO-LEVEL REASONING**: + - **High-level (TODO list)**: What major tasks need to be done? + - **Low-level (reasoning steps)**: How do I accomplish each task? (search, read, analyze, propose) + +${codebaseAnalysis ? `\n\n## šŸ“‹ Codebase Analysis & File Relationships\n\n${codebaseAnalysis}\n\n**This analysis helps you understand the codebase structure and relationships between files. Use it to make informed decisions about which files to examine for the task.**\n\n` : ''} + +${todoStats.total > 0 ? `\n${todoContext}\n\n**CRITICAL**: To work on a TODO, use its EXACT ID (shown above) when updating. Don't just update status - DO THE ACTUAL WORK (search, read, analyze, propose) in the same response where you update the TODO.` : iteration === 1 ? `\n\n## šŸ“‹ TODO List\n\n**IMPORTANT**: In your first response, you should create a TODO list breaking down the problem into manageable tasks. Use the \`todo_updates.create\` field to create initial TODOs. Each TODO represents a high-level task that may require multiple reasoning steps to complete.` : ''} + +## Current Task + +${description ? `### Context/Issue Description:\n\`\`\`\n${description}\n\`\`\`` : ''} + +### User's Question/Prompt: +\`\`\` +${question} +\`\`\` + +## Reasoning Process (Iteration ${iteration}/${this.MAX_ITERATIONS}) + +${iteration === 1 ? 'You are starting your analysis. Begin by understanding the question and identifying what files or areas of the codebase might be relevant.' : `You have been analyzing this problem through ${iteration - 1} previous iterations.`} + +${stepsSummary} + +${codeStats.totalChanges > 0 ? `\n\n## āš ļø CODE STATE: ${codeStats.totalChanges} changes have been applied to ${codeStats.modifiedFiles} files\n\n${codeStateInfo}\n\n**IMPORTANT**: When you read files, you will see the MODIFIED version with all previous changes applied. Build upon this modified code, don't repeat changes that have already been made.` : ''} + +${analyzedFilesSummary} + +${iteration > 1 ? `\n\n## Previous Iteration Context:\n${currentContext.substring(0, 4000)}${currentContext.length > 4000 ? '\n... (truncated for brevity)' : ''}` : ''} + +${fileListSummary} + +## Your Analysis Approach + +1. **search_files**: Use when you need to find files by name, pattern, or path. Be specific. AVOID searching for the same terms repeatedly. +2. **read_file**: Use when you need to examine specific files. The files you read will show the CURRENT STATE (with all applied changes from previous steps). +3. **analyze_code**: Use when you've read files and want to document findings. Focus on understanding relationships and dependencies. +4. **propose_changes**: Use when you have enough context. **CRITICAL**: Only propose NEW changes that build upon what's already been done. Don't repeat changes that were already applied. +5. **update_todos** (or include with other actions): + - Create TODOs ONLY in your first iteration to break down the problem + - Update TODO status when you START working on it (in_progress) or COMPLETE it (completed) + - **IMPORTANT**: Use the EXACT TODO ID from the list above (e.g., "todo_1"), NOT numeric IDs + - Include todo_updates in the SAME response where you do the actual work +6. **complete**: Use when your analysis is finished and you have a comprehensive understanding. All TODOs should be completed or cancelled. + +## Critical Instructions + +- **USE TODO LIST CORRECTLY**: + - Create TODOs in iteration 1 to break down the problem into manageable tasks + - **IMPORTANT**: When updating TODOs, you MUST use the EXACT ID shown in the TODO list (e.g., "todo_1", "todo_2"). Do NOT use numeric IDs like "1" or "2" + - Each TODO represents a high-level task that may require multiple reasoning steps (search, read, analyze, propose) + +- **WORK ON TODOS, DON'T JUST UPDATE THEM**: + - When a TODO is "pending" or "in_progress", DO REAL WORK: search for files, read files, analyze code, propose changes + - Only update TODO status when you actually START working on it (mark "in_progress") or COMPLETE it (mark "completed") + - Don't waste iterations just updating TODO status - do the actual work! + +- **TRACK PROGRESS**: + - When you START working on a TODO: mark it "in_progress" AND then do the work (search, read, analyze, propose) + - When you COMPLETE work on a TODO: mark it "completed" + - Update TODOs in the same response where you do the work, don't create separate "update_todos" actions + +- **AVOID REPETITION**: Don't search for the same files repeatedly. Don't propose changes that have already been applied. Don't try to update TODOs with wrong IDs. + +- **BUILD INCREMENTALLY**: Each step should build upon the previous one. Read files that were modified in previous steps to see the current state. + +- **PROGRESS FORWARD**: If you've already analyzed files, move to proposing changes. Don't re-analyze the same code. + +- **SEE THE MODIFIED CODE**: When you read files after changes have been applied, you'll see the modified version. Use this to understand the current state and propose the NEXT logical step. + +- **BE SPECIFIC**: When proposing changes, be very specific about what needs to change and provide suggested_code. + +- **THINK DEEPLY**: Don't just propose generic changes. Analyze the code structure, dependencies, and relationships before proposing changes. + +- **FOCUS ON ACTIVE TODOS**: Work on TODOs that are "pending" or "in_progress". Complete them by doing real work, not just updating status. + +## Important + +- You must return a valid JSON object matching the schema +- Be thorough but efficient - don't request files you don't need +- Build understanding incrementally +- Connect insights across multiple files when relevant +- Each iteration should advance the analysis, not repeat previous steps +- You can include \`todo_updates\` alongside any action (not just when action is 'update_todos') +- When creating TODOs, make them specific and actionable (e.g., "Analyze authentication system" not "Do stuff") +`; + + try { + const response = await this.aiRepository.askThinkJson(param.ai, prompt); + return response as ThinkResponse; + } catch (error) { + logError(`Error in reasoning step: ${error}`); + return undefined; + } + } + + private async generateFinalAnalysis( + param: Execution, + question: string, + analyzedFiles: Map, + proposedChanges: ProposedChange[], + steps: ThinkStep[], + todoManager: ThinkTodoManager + ): Promise { + + const prompt = ` +# Final Analysis Summary + +Based on your analysis of the codebase, provide a comprehensive summary and recommendations. + +## User's Question: +${question} + +## Analysis Summary: +- Total steps taken: ${steps.length} +- Files analyzed: ${analyzedFiles.size} +- Proposed changes: ${proposedChanges.length} +- TODO list: ${todoManager.getSummary()} + +## Analyzed Files: +${Array.from(analyzedFiles.values()).map(f => `- ${f.path} (${f.relevance}): ${f.key_findings}`).join('\n')} + +## Proposed Changes: +${proposedChanges.map(c => ` +### ${c.change_type.toUpperCase()}: ${c.file_path} +**Description:** ${c.description} +**Reasoning:** ${c.reasoning} +${c.suggested_code ? `**Suggested Code:**\n\`\`\`\n${c.suggested_code}\n\`\`\`` : ''} +`).join('\n')} + +## Steps Taken: +${steps.map(s => `${s.step_number}. ${s.action}: ${s.reasoning.substring(0, 150)}...`).join('\n')} + +Provide a comprehensive final analysis that: +1. Summarizes what you discovered +2. Explains the key insights +3. Provides clear recommendations +4. Describes the proposed changes and their rationale +5. Notes any considerations or potential issues + +Be thorough, clear, and actionable. +`; + + const response = await this.aiRepository.ask(param.ai, prompt); + return response || 'Analysis completed. Review the proposed changes and steps above.'; + } +} diff --git a/src/usecase/steps/issue/close_issue_after_merging_use_case.ts b/src/usecase/steps/issue/close_issue_after_merging_use_case.ts index 6731a89e..ab223f6e 100644 --- a/src/usecase/steps/issue/close_issue_after_merging_use_case.ts +++ b/src/usecase/steps/issue/close_issue_after_merging_use_case.ts @@ -84,7 +84,7 @@ export class CloseIssueAfterMergingUseCase implements ParamUseCase logDebugInfo(`Hotfix branch successfully linked to issue: ${JSON.stringify(linkResult)}`); result.push( - ...await this.duplicateChunksByBranch( + ...await this.duplicateAICacheByBranch( supabaseRepository, param, param.branches.main, @@ -212,7 +212,7 @@ export class PrepareBranchesUseCase implements ParamUseCase logDebugInfo(`Release branch successfully linked to issue: ${JSON.stringify(linkResult)}`); result.push( - ...await this.duplicateChunksByBranch( + ...await this.duplicateAICacheByBranch( supabaseRepository, param, param.branches.development, @@ -339,7 +339,7 @@ export class PrepareBranchesUseCase implements ParamUseCase } result.push( - ...await this.duplicateChunksByBranch( + ...await this.duplicateAICacheByBranch( supabaseRepository, param, param.branches.development, @@ -369,13 +369,13 @@ export class PrepareBranchesUseCase implements ParamUseCase return result; } - private duplicateChunksByBranch = async (supabaseRepository: SupabaseRepository | undefined, param: Execution, sourceBranch: string, targetBranch: string) => { + private duplicateAICacheByBranch = async (supabaseRepository: SupabaseRepository | undefined, param: Execution, sourceBranch: string, targetBranch: string) => { const result: Result[] = [] if (!supabaseRepository) { return result; } try { - await supabaseRepository.duplicateChunksByBranch(param.owner, param.repo, sourceBranch, targetBranch); + await supabaseRepository.duplicateAIFileCacheByBranch(param.owner, param.repo, sourceBranch, targetBranch); result.push( new Result({ id: this.taskId, @@ -387,7 +387,7 @@ export class PrepareBranchesUseCase implements ParamUseCase }) ) } catch (error) { - logError(`Error duplicating chunks: ${JSON.stringify(error, null, 2)}`); + logError(`Error duplicating AI cache: ${JSON.stringify(error, null, 2)}`); result.push( new Result({ id: this.taskId, diff --git a/src/usecase/steps/issue_comment/check_issue_comment_language_use_case.ts b/src/usecase/steps/issue_comment/check_issue_comment_language_use_case.ts index 5f4c1078..36804b3f 100644 --- a/src/usecase/steps/issue_comment/check_issue_comment_language_use_case.ts +++ b/src/usecase/steps/issue_comment/check_issue_comment_language_use_case.ts @@ -81,6 +81,7 @@ The text is: ${commentBody} ${this.translatedKey} `; + logInfo(`šŸ”Ž Issue number: ${param.issue.number}`); await this.issueRepository.updateComment( param.owner, param.repo, diff --git a/src/utils/constants.ts b/src/utils/constants.ts index 4665a0d4..d95e1d17 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -1,5 +1,5 @@ -export const COMMAND = 'git-board-flow' -export const TITLE = 'Git Board Flow' +export const COMMAND = 'giik' +export const TITLE = 'Giik' export const REPO_URL = 'https://github.com/landamessenger/git-board-flow' export const DEFAULT_IMAGE_CONFIG = { @@ -197,13 +197,6 @@ export const INPUT_KEYS = { WELCOME_TITLE: 'welcome-title', WELCOME_MESSAGES: 'welcome-messages', - // Docker - DOCKER_CONTAINER_NAME: 'docker-container-name', - DOCKER_DOMAIN: 'docker-domain', - DOCKER_PORT: 'docker-port', - DOCKER_CACHE_OS: 'docker-cache-os', - DOCKER_CACHE_ARCH: 'docker-cache-arch', - // Single action SINGLE_ACTION: 'single-action', SINGLE_ACTION_ISSUE: 'single-action-issue', @@ -213,7 +206,6 @@ export const INPUT_KEYS = { // Tokens TOKEN: 'token', - CLASSIC_TOKEN: 'classic-token', // AI OPENROUTER_API_KEY: 'openrouter-api-key', @@ -393,11 +385,32 @@ export const ERRORS = { export const ACTIONS = { DEPLOYED: 'deployed_action', - COMPILE_VECTOR_SERVER: 'compile_vector_server', - VECTOR: 'vector_action', - VECTOR_LOCAL: 'vector_local', - VECTOR_REMOVAL: 'vector_removal', + AI_CACHE: 'ai_cache_action', + AI_CACHE_LOCAL: 'ai_cache_local_action', PUBLISH_GITHUB_ACTION: 'publish_github_action', CREATE_RELEASE: 'create_release', CREATE_TAG: 'create_tag', + THINK: 'think_action', +} as const; + +export const PROMPTS = { + CODE_BASE_ANALYSIS: ` +You are a technical code analysis assistant. + +Your task is to analyze the content of the following source code file in depth. + +Provide a precise and highly technical explanation of what the code does, including: +- Its main purpose and functionality. +- A breakdown of the logic and flow (step by step or module by module). +- How each class, function, or major block interacts with the rest. +- The technologies, frameworks, or libraries it uses and how. +- Any relevant algorithms, patterns, or data structures implemented. +- Potential edge cases, performance considerations, or hidden behaviors. +- Dependencies and external integrations (APIs, services, databases, etc.). +- Any implicit assumptions or limitations found in the implementation. + +Focus exclusively on *accurate technical analysis and understanding*, not on summarizing in simple language. + +Do not propose improvements, changes, or fixes in this stage — your only goal is to explain exactly what the code does and how it works. + `, } as const; diff --git a/supabase/migrations/20240322000000_create_ai_file_cache_table.sql b/supabase/migrations/20240322000000_create_ai_file_cache_table.sql new file mode 100644 index 00000000..53ba4604 --- /dev/null +++ b/supabase/migrations/20240322000000_create_ai_file_cache_table.sql @@ -0,0 +1,213 @@ +-- Create the ai_file_cache table to store AI-generated file descriptions and relationships +CREATE TABLE IF NOT EXISTS ai_file_cache ( + owner TEXT NOT NULL, + repository TEXT NOT NULL, + branch TEXT NOT NULL, + file_name TEXT NOT NULL, + path TEXT NOT NULL, + sha TEXT NOT NULL, + description TEXT NOT NULL, + consumes TEXT[] DEFAULT '{}', + consumed_by TEXT[] DEFAULT '{}', + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + last_updated TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (owner, repository, branch, path) +); + +-- Create indexes for faster lookups +CREATE INDEX IF NOT EXISTS ai_file_cache_owner_repo_branch_idx ON ai_file_cache(owner, repository, branch); +CREATE INDEX IF NOT EXISTS ai_file_cache_path_idx ON ai_file_cache(path); +CREATE INDEX IF NOT EXISTS ai_file_cache_sha_idx ON ai_file_cache(sha); + +-- Create a trigger to update the last_updated timestamp +CREATE OR REPLACE FUNCTION update_ai_file_cache_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.last_updated = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ language 'plpgsql'; + +CREATE TRIGGER update_ai_file_cache_updated_at + BEFORE UPDATE ON ai_file_cache + FOR EACH ROW + EXECUTE FUNCTION update_ai_file_cache_updated_at(); + +-- Create a function to get file cache by path +CREATE OR REPLACE FUNCTION get_ai_file_cache( + owner_param TEXT, + repository_param TEXT, + branch_param TEXT, + path_param TEXT +) +RETURNS TABLE ( + owner TEXT, + repository TEXT, + branch TEXT, + file_name TEXT, + path TEXT, + sha TEXT, + description TEXT, + consumes TEXT[], + consumed_by TEXT[], + created_at TIMESTAMP WITH TIME ZONE, + last_updated TIMESTAMP WITH TIME ZONE +) +LANGUAGE plpgsql +SECURITY DEFINER +AS $$ +BEGIN + RETURN QUERY + SELECT + ai_file_cache.owner, + ai_file_cache.repository, + ai_file_cache.branch, + ai_file_cache.file_name, + ai_file_cache.path, + ai_file_cache.sha, + ai_file_cache.description, + ai_file_cache.consumes, + ai_file_cache.consumed_by, + ai_file_cache.created_at, + ai_file_cache.last_updated + FROM ai_file_cache + WHERE ai_file_cache.owner = owner_param + AND ai_file_cache.repository = repository_param + AND ai_file_cache.branch = branch_param + AND ai_file_cache.path = path_param + LIMIT 1; +END; +$$; + +-- Create a function to get all file caches for a branch +CREATE OR REPLACE FUNCTION get_ai_file_caches_by_branch( + owner_param TEXT, + repository_param TEXT, + branch_param TEXT +) +RETURNS TABLE ( + owner TEXT, + repository TEXT, + branch TEXT, + file_name TEXT, + path TEXT, + sha TEXT, + description TEXT, + consumes TEXT[], + consumed_by TEXT[], + created_at TIMESTAMP WITH TIME ZONE, + last_updated TIMESTAMP WITH TIME ZONE +) +LANGUAGE plpgsql +SECURITY DEFINER +AS $$ +BEGIN + RETURN QUERY + SELECT + ai_file_cache.owner, + ai_file_cache.repository, + ai_file_cache.branch, + ai_file_cache.file_name, + ai_file_cache.path, + ai_file_cache.sha, + ai_file_cache.description, + ai_file_cache.consumes, + ai_file_cache.consumed_by, + ai_file_cache.created_at, + ai_file_cache.last_updated + FROM ai_file_cache + WHERE ai_file_cache.owner = owner_param + AND ai_file_cache.repository = repository_param + AND ai_file_cache.branch = branch_param + ORDER BY ai_file_cache.path; +END; +$$; + +-- Create a function to delete file cache entries by branch +CREATE OR REPLACE FUNCTION delete_ai_file_cache_by_branch( + owner_param TEXT, + repository_param TEXT, + branch_param TEXT +) +RETURNS void +LANGUAGE plpgsql +SECURITY DEFINER +AS $$ +BEGIN + DELETE FROM ai_file_cache + WHERE owner = owner_param + AND repository = repository_param + AND branch = branch_param; +END; +$$; + +-- Create a function to delete file cache entries by path +CREATE OR REPLACE FUNCTION delete_ai_file_cache_by_path( + owner_param TEXT, + repository_param TEXT, + branch_param TEXT, + path_param TEXT +) +RETURNS void +LANGUAGE plpgsql +SECURITY DEFINER +AS $$ +BEGIN + DELETE FROM ai_file_cache + WHERE owner = owner_param + AND repository = repository_param + AND branch = branch_param + AND path = path_param; +END; +$$; + +-- Create a function to duplicate file cache entries from one branch to another +CREATE OR REPLACE FUNCTION duplicate_ai_file_cache_by_branch( + owner_param TEXT, + repository_param TEXT, + source_branch_param TEXT, + target_branch_param TEXT +) +RETURNS void +LANGUAGE plpgsql +SECURITY DEFINER +AS $$ +BEGIN + INSERT INTO ai_file_cache ( + owner, + repository, + branch, + file_name, + path, + sha, + description, + consumes, + consumed_by, + created_at, + last_updated + ) + SELECT + owner, + repository, + target_branch_param AS branch, + file_name, + path, + sha, + description, + consumes, + consumed_by, + CURRENT_TIMESTAMP, + CURRENT_TIMESTAMP + FROM ai_file_cache + WHERE owner = owner_param + AND repository = repository_param + AND branch = source_branch_param + ON CONFLICT (owner, repository, branch, path) DO UPDATE SET + sha = EXCLUDED.sha, + description = EXCLUDED.description, + consumes = EXCLUDED.consumes, + consumed_by = EXCLUDED.consumed_by, + last_updated = CURRENT_TIMESTAMP; +END; +$$; +